@kablamo/react-transcript-editor
Version:
A React component to make transcribing audio and video easier and faster.
1,622 lines (1,352 loc) • 157 kB
JavaScript
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 36);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("react");
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = require("prop-types");
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = require("draft-js");
/***/ }),
/* 3 */
/***/ (function(module, exports) {
module.exports = require("@fortawesome/react-fontawesome");
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = require("@fortawesome/free-solid-svg-icons");
/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "secondsToTimecode", function() { return /* reexport */ src_secondsToTimecode; });
__webpack_require__.d(__webpack_exports__, "timecodeToSeconds", function() { return /* binding */ timecode_converter_timecodeToSeconds; });
__webpack_require__.d(__webpack_exports__, "shortTimecode", function() { return /* binding */ timecode_converter_shortTimecode; });
// CONCATENATED MODULE: ./packages/util/timecode-converter/src/secondsToTimecode.js
/**
* Raised in this comment https://github.com/bbc/react-transcript-editor/pull/9
* abstracted from https://github.com/bbc/newslabs-cdn/blob/master/js/20-bbcnpf.utils.js
* In broadcast VIDEO, timecode is NOT hh:mm:ss:ms, it's hh:mm:ss:ff where ff is frames,
* dependent on the framerate of the media concerned.
* `hh:mm:ss:ff`
*/
/**
* Helper function
* Rounds to the 14milliseconds boundaries
* Time in video can only "exist in" 14milliseconds boundaries.
* This makes it possible for the HTML5 player to be frame accurate.
* @param {*} seconds
* @param {*} fps
*/
var normalisePlayerTime = function normalisePlayerTime(seconds, fps) {
return Number((1.0 / fps * Math.floor(Number((fps * seconds).toPrecision(12)))).toFixed(2));
};
/*
* @param {*} seconds
* @param {*} fps
*/
var secondsToTimecode = function secondsToTimecode(seconds, framePerSeconds) {
// written for PAL non-drop timecode
var fps = 25;
if (framePerSeconds !== undefined) {
fps = framePerSeconds;
}
var normalisedSeconds = normalisePlayerTime(seconds, fps);
var wholeSeconds = Math.floor(normalisedSeconds);
var frames = ((normalisedSeconds - wholeSeconds) * fps).toFixed(2); // prepends zero - example pads 3 to 03
function _padZero(n) {
if (n < 10) return "0".concat(parseInt(n));
return parseInt(n);
}
return "".concat(_padZero(wholeSeconds / 60 / 60 % 60), ":").concat(_padZero(wholeSeconds / 60 % 60), ":").concat(_padZero(wholeSeconds % 60), ":").concat(_padZero(frames));
};
/* harmony default export */ var src_secondsToTimecode = (secondsToTimecode);
// CONCATENATED MODULE: ./packages/util/timecode-converter/src/timecodeToSeconds.js
/**
* Helperf unction
* @param {*} tc
* @param {*} fps
*/
var timecodeToFrames = function timecodeToFrames(tc, fps) {
// TODO make 29.97 fps drop-frame aware - works for 25 only.
var s = tc.split(':');
var frames = parseInt(s[3]);
frames += parseInt(s[2]) * fps;
frames += parseInt(s[1]) * (fps * 60);
frames += parseInt(s[0]) * (fps * 60 * 60);
return frames;
};
/**
* Convert broadcast timecodes to seconds
* @param {*} tc - `hh:mm:ss:ff`
* @param {*} framePerSeconds - defaults to 25 if not provided
*/
var timecodeToSecondsHelper = function timecodeToSecondsHelper(tc, framePerSeconds) {
var fps = 25;
if (framePerSeconds !== undefined) {
fps = framePerSeconds;
}
var frames = timecodeToFrames(tc, fps);
return Number(Number(frames / fps).toFixed(2));
};
/* harmony default export */ var src_timecodeToSeconds = (timecodeToSecondsHelper);
// CONCATENATED MODULE: ./packages/util/timecode-converter/src/padTimeToTimecode.js
var countColon = function countColon(timecode) {
return timecode.split(':').length;
};
var includesFullStop = function includesFullStop(timecode) {
return timecode.includes('.');
};
var isOneDigit = function isOneDigit(str) {
return str.length === 1;
};
var padTimeToTimecode = function padTimeToTimecode(time) {
if (typeof time === 'string') {
switch (countColon(time)) {
case 4:
// is already in timecode format
// hh:mm:ss:ff
return time;
case 2:
// m:ss
if (isOneDigit(time.split(':')[0])) {
return "00:0".concat(time, ":00");
}
return "00:".concat(time, ":00");
case 3:
// hh:mm:ss
return "".concat(time, ":00");
default:
// mm.ss
if (includesFullStop(time)) {
// m.ss
if (isOneDigit(time.split('.')[0])) {
return "00:0".concat(time.split('.')[0], ":").concat(time.split('.')[1], ":00");
}
return "00:".concat(time.replace('.', ':'), ":00");
} // if just int, then it's seconds
// s
if (isOneDigit(time)) {
return "00:00:0".concat(time, ":00");
}
return "00:00:".concat(time, ":00");
} // edge case if it's number return a number coz cannot refactor
// TODO: might need to refactor and move this elsewhere
} else {
return time;
}
};
/* harmony default export */ var src_padTimeToTimecode = (padTimeToTimecode);
// CONCATENATED MODULE: ./packages/util/timecode-converter/index.js
/**
* Wrapping around "time stamps" and timecode conversion modules
* To provide more support for variety of formats.
*/
/**
* @param {*} time
* Can take as input timecodes in the following formats
* - hh:mm:ss:ff
* - mm:ss
* - m:ss
* - ss - seconds --> if it's already in seconds then it just returns seconds
* - hh:mm:ff
* @todo could be refactored with some helper functions for clarity
*/
var timecode_converter_timecodeToSeconds = function timecodeToSeconds(time) {
if (typeof time === 'string') {
var resultPadded = src_padTimeToTimecode(time);
var resultConverted = src_timecodeToSeconds(resultPadded);
return resultConverted;
} // assuming it receive timecode as seconds as string '600'
return parseFloat(time);
};
var timecode_converter_shortTimecode = function shortTimecode(time) {
var timecode = src_secondsToTimecode(time);
return timecode.slice(0, -3);
};
/***/ }),
/* 6 */,
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/**
* Helper function to generate draft.js entities,
* see unit test for example data structure
* it adds offset and length to recognise word in draftjs
*/
/**
* @param {json} words - List of words
* @param {string} wordAttributeName - eg 'punct' or 'text' or etc.
* attribute for the word object containing the text. eg word ={ punct:'helo', ... }
* or eg word ={ text:'helo', ... }
*/
var generateEntitiesRanges = function generateEntitiesRanges(words, wordAttributeName) {
var position = 0;
return words.map(function (word) {
var result = {
start: word.start,
end: word.end,
confidence: word.confidence,
text: word[wordAttributeName],
offset: position,
length: word[wordAttributeName].length,
key: Math.random().toString(36).substring(6)
}; // increase position counter - to determine word offset in paragraph
position = position + word[wordAttributeName].length + 1;
return result;
});
};
/* harmony default export */ __webpack_exports__["a"] = (generateEntitiesRanges);
/***/ }),
/* 8 */,
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function (useSourceMap) {
var list = []; // return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return '@media ' + item[2] + '{' + content + '}';
} else {
return content;
}
}).join('');
}; // import a list of modules into the list
list.i = function (modules, mediaQuery) {
if (typeof modules === 'string') {
modules = [[null, modules, '']];
}
var alreadyImportedModules = {};
for (var i = 0; i < this.length; i++) {
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
for (i = 0; i < modules.length; i++) {
var item = modules[i]; // skip already imported module
// this implementation is not 100% perfect for weird media query combinations
// when a module is imported multiple times with different media queries.
// I hope this will never occur (Hey this way we have smaller bundles)
if (item[0] == null || !alreadyImportedModules[item[0]]) {
if (mediaQuery && !item[2]) {
item[2] = mediaQuery;
} else if (mediaQuery) {
item[2] = '(' + item[2] + ') and (' + mediaQuery + ')';
}
list.push(item);
}
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || '';
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === 'function') {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */';
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
return '/*# ' + data + ' */';
}
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var stylesInDom = {};
var memoize = function (fn) {
var memo;
return function () {
if (typeof memo === "undefined") memo = fn.apply(this, arguments);
return memo;
};
};
var isOldIE = memoize(function () {
// Test for IE <= 9 as proposed by Browserhacks
// @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
// Tests for existence of standard globals is to allow style-loader
// to operate correctly into non-standard environments
// @see https://github.com/webpack-contrib/style-loader/issues/177
return window && document && document.all && !window.atob;
});
var getTarget = function (target, parent) {
if (parent){
return parent.querySelector(target);
}
return document.querySelector(target);
};
var getElement = (function (fn) {
var memo = {};
return function(target, parent) {
// If passing function in options, then use it for resolve "head" element.
// Useful for Shadow Root style i.e
// {
// insertInto: function () { return document.querySelector("#foo").shadowRoot }
// }
if (typeof target === 'function') {
return target();
}
if (typeof memo[target] === "undefined") {
var styleTarget = getTarget.call(this, target, parent);
// Special case to return head of iframe instead of iframe itself
if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
try {
// This will throw an exception if access to iframe is blocked
// due to cross-origin restrictions
styleTarget = styleTarget.contentDocument.head;
} catch(e) {
styleTarget = null;
}
}
memo[target] = styleTarget;
}
return memo[target]
};
})();
var singleton = null;
var singletonCounter = 0;
var stylesInsertedAtTop = [];
var fixUrls = __webpack_require__(16);
module.exports = function(list, options) {
if (typeof DEBUG !== "undefined" && DEBUG) {
if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
}
options = options || {};
options.attrs = typeof options.attrs === "object" ? options.attrs : {};
// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
// tags it will allow on a page
if (!options.singleton && typeof options.singleton !== "boolean") options.singleton = isOldIE();
// By default, add <style> tags to the <head> element
if (!options.insertInto) options.insertInto = "head";
// By default, add <style> tags to the bottom of the target
if (!options.insertAt) options.insertAt = "bottom";
var styles = listToStyles(list, options);
addStylesToDom(styles, options);
return function update (newList) {
var mayRemove = [];
for (var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
domStyle.refs--;
mayRemove.push(domStyle);
}
if(newList) {
var newStyles = listToStyles(newList, options);
addStylesToDom(newStyles, options);
}
for (var i = 0; i < mayRemove.length; i++) {
var domStyle = mayRemove[i];
if(domStyle.refs === 0) {
for (var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j]();
delete stylesInDom[domStyle.id];
}
}
};
};
function addStylesToDom (styles, options) {
for (var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
if(domStyle) {
domStyle.refs++;
for(var j = 0; j < domStyle.parts.length; j++) {
domStyle.parts[j](item.parts[j]);
}
for(; j < item.parts.length; j++) {
domStyle.parts.push(addStyle(item.parts[j], options));
}
} else {
var parts = [];
for(var j = 0; j < item.parts.length; j++) {
parts.push(addStyle(item.parts[j], options));
}
stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
}
}
}
function listToStyles (list, options) {
var styles = [];
var newStyles = {};
for (var i = 0; i < list.length; i++) {
var item = list[i];
var id = options.base ? item[0] + options.base : item[0];
var css = item[1];
var media = item[2];
var sourceMap = item[3];
var part = {css: css, media: media, sourceMap: sourceMap};
if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]});
else newStyles[id].parts.push(part);
}
return styles;
}
function insertStyleElement (options, style) {
var target = getElement(options.insertInto)
if (!target) {
throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");
}
var lastStyleElementInsertedAtTop = stylesInsertedAtTop[stylesInsertedAtTop.length - 1];
if (options.insertAt === "top") {
if (!lastStyleElementInsertedAtTop) {
target.insertBefore(style, target.firstChild);
} else if (lastStyleElementInsertedAtTop.nextSibling) {
target.insertBefore(style, lastStyleElementInsertedAtTop.nextSibling);
} else {
target.appendChild(style);
}
stylesInsertedAtTop.push(style);
} else if (options.insertAt === "bottom") {
target.appendChild(style);
} else if (typeof options.insertAt === "object" && options.insertAt.before) {
var nextSibling = getElement(options.insertAt.before, target);
target.insertBefore(style, nextSibling);
} else {
throw new Error("[Style Loader]\n\n Invalid value for parameter 'insertAt' ('options.insertAt') found.\n Must be 'top', 'bottom', or Object.\n (https://github.com/webpack-contrib/style-loader#insertat)\n");
}
}
function removeStyleElement (style) {
if (style.parentNode === null) return false;
style.parentNode.removeChild(style);
var idx = stylesInsertedAtTop.indexOf(style);
if(idx >= 0) {
stylesInsertedAtTop.splice(idx, 1);
}
}
function createStyleElement (options) {
var style = document.createElement("style");
if(options.attrs.type === undefined) {
options.attrs.type = "text/css";
}
if(options.attrs.nonce === undefined) {
var nonce = getNonce();
if (nonce) {
options.attrs.nonce = nonce;
}
}
addAttrs(style, options.attrs);
insertStyleElement(options, style);
return style;
}
function createLinkElement (options) {
var link = document.createElement("link");
if(options.attrs.type === undefined) {
options.attrs.type = "text/css";
}
options.attrs.rel = "stylesheet";
addAttrs(link, options.attrs);
insertStyleElement(options, link);
return link;
}
function addAttrs (el, attrs) {
Object.keys(attrs).forEach(function (key) {
el.setAttribute(key, attrs[key]);
});
}
function getNonce() {
if (false) {}
return __webpack_require__.nc;
}
function addStyle (obj, options) {
var style, update, remove, result;
// If a transform function was defined, run it on the css
if (options.transform && obj.css) {
result = typeof options.transform === 'function'
? options.transform(obj.css)
: options.transform.default(obj.css);
if (result) {
// If transform returns a value, use that instead of the original css.
// This allows running runtime transformations on the css.
obj.css = result;
} else {
// If the transform function returns a falsy value, don't add this css.
// This allows conditional loading of css
return function() {
// noop
};
}
}
if (options.singleton) {
var styleIndex = singletonCounter++;
style = singleton || (singleton = createStyleElement(options));
update = applyToSingletonTag.bind(null, style, styleIndex, false);
remove = applyToSingletonTag.bind(null, style, styleIndex, true);
} else if (
obj.sourceMap &&
typeof URL === "function" &&
typeof URL.createObjectURL === "function" &&
typeof URL.revokeObjectURL === "function" &&
typeof Blob === "function" &&
typeof btoa === "function"
) {
style = createLinkElement(options);
update = updateLink.bind(null, style, options);
remove = function () {
removeStyleElement(style);
if(style.href) URL.revokeObjectURL(style.href);
};
} else {
style = createStyleElement(options);
update = applyToTag.bind(null, style);
remove = function () {
removeStyleElement(style);
};
}
update(obj);
return function updateStyle (newObj) {
if (newObj) {
if (
newObj.css === obj.css &&
newObj.media === obj.media &&
newObj.sourceMap === obj.sourceMap
) {
return;
}
update(obj = newObj);
} else {
remove();
}
};
}
var replaceText = (function () {
var textStore = [];
return function (index, replacement) {
textStore[index] = replacement;
return textStore.filter(Boolean).join('\n');
};
})();
function applyToSingletonTag (style, index, remove, obj) {
var css = remove ? "" : obj.css;
if (style.styleSheet) {
style.styleSheet.cssText = replaceText(index, css);
} else {
var cssNode = document.createTextNode(css);
var childNodes = style.childNodes;
if (childNodes[index]) style.removeChild(childNodes[index]);
if (childNodes.length) {
style.insertBefore(cssNode, childNodes[index]);
} else {
style.appendChild(cssNode);
}
}
}
function applyToTag (style, obj) {
var css = obj.css;
var media = obj.media;
if(media) {
style.setAttribute("media", media)
}
if(style.styleSheet) {
style.styleSheet.cssText = css;
} else {
while(style.firstChild) {
style.removeChild(style.firstChild);
}
style.appendChild(document.createTextNode(css));
}
}
function updateLink (link, options, obj) {
var css = obj.css;
var sourceMap = obj.sourceMap;
/*
If convertToAbsoluteUrls isn't defined, but sourcemaps are enabled
and there is no publicPath defined then lets turn convertToAbsoluteUrls
on by default. Otherwise default to the convertToAbsoluteUrls option
directly
*/
var autoFixUrls = options.convertToAbsoluteUrls === undefined && sourceMap;
if (options.convertToAbsoluteUrls || autoFixUrls) {
css = fixUrls(css);
}
if (sourceMap) {
// http://stackoverflow.com/a/26603875
css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
}
var blob = new Blob([css], { type: "text/css" });
var oldSrc = link.href;
link.href = URL.createObjectURL(blob);
if(oldSrc) URL.revokeObjectURL(oldSrc);
}
/***/ }),
/* 11 */,
/* 12 */
/***/ (function(module, exports) {
module.exports = require("docx");
/***/ }),
/* 13 */,
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
var content = __webpack_require__(46);
if(typeof content === 'string') content = [[module.i, content, '']];
var transform;
var insertInto;
var options = {"hmr":true}
options.transform = transform
options.insertInto = undefined;
var update = __webpack_require__(10)(content, options);
if(content.locals) module.exports = content.locals;
if(false) {}
/***/ }),
/* 15 */,
/* 16 */
/***/ (function(module, exports) {
/**
* When source maps are enabled, `style-loader` uses a link element with a data-uri to
* embed the css on the page. This breaks all relative urls because now they are relative to a
* bundle instead of the current page.
*
* One solution is to only use full urls, but that may be impossible.
*
* Instead, this function "fixes" the relative urls to be absolute according to the current page location.
*
* A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command.
*
*/
module.exports = function (css) {
// get current location
var location = typeof window !== "undefined" && window.location;
if (!location) {
throw new Error("fixUrls requires window.location");
}
// blank or null?
if (!css || typeof css !== "string") {
return css;
}
var baseUrl = location.protocol + "//" + location.host;
var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/");
// convert each url(...)
/*
This regular expression is just a way to recursively match brackets within
a string.
/url\s*\( = Match on the word "url" with any whitespace after it and then a parens
( = Start a capturing group
(?: = Start a non-capturing group
[^)(] = Match anything that isn't a parentheses
| = OR
\( = Match a start parentheses
(?: = Start another non-capturing groups
[^)(]+ = Match anything that isn't a parentheses
| = OR
\( = Match a start parentheses
[^)(]* = Match anything that isn't a parentheses
\) = Match a end parentheses
) = End Group
*\) = Match anything and then a close parens
) = Close non-capturing group
* = Match anything
) = Close capturing group
\) = Match a close parens
/gi = Get all matches, not the first. Be case insensitive.
*/
var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function(fullMatch, origUrl) {
// strip quotes (if they exist)
var unquotedOrigUrl = origUrl
.trim()
.replace(/^"(.*)"$/, function(o, $1){ return $1; })
.replace(/^'(.*)'$/, function(o, $1){ return $1; });
// already a full url? no change
if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(unquotedOrigUrl)) {
return fullMatch;
}
// convert the url to a full url
var newUrl;
if (unquotedOrigUrl.indexOf("//") === 0) {
//TODO: should we add protocol?
newUrl = unquotedOrigUrl;
} else if (unquotedOrigUrl.indexOf("/") === 0) {
// path should be relative to the base url
newUrl = baseUrl + unquotedOrigUrl; // already starts with '/'
} else {
// path should be relative to current directory
newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './'
}
// send back the fixed url(...)
return "url(" + JSON.stringify(newUrl) + ")";
});
// send back the fixed css
return fixedCss;
};
/***/ }),
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "createEntityMap", function() { return /* reexport */ create_entity_map; });
// EXTERNAL MODULE: ./packages/stt-adapters/generate-entities-ranges/index.js
var generate_entities_ranges = __webpack_require__(7);
// CONCATENATED MODULE: ./packages/stt-adapters/bbc-kaldi/group-words-by-speakers.js
/**
edge cases
- more segments then words - not an issue if you start by matching words with segment
and handle edge case where it doesn't find a match
- more words then segments - orphan words
*/
function groupWordsInParagraphsBySpeakers(words, segments) {
// add speakers to each word
var wordsWithSpeakers = addSpeakerToEachWord(words, segments.segments); // group words by speakers sequentially
var result = groupWordsBySpeaker(wordsWithSpeakers);
return result;
}
;
/**
* Add speakers to each words
* if it doesn't have add unknown attribute `U_UKN`
* @param {*} words
* @param {*} segments
*/
function addSpeakerToEachWord(words, segments) {
var tmpWordsWithSpeakers = [];
words.forEach(function (word) {
var tmpSpeakerSegment = findSegmentForWord(word, segments);
word.speaker = formatSpeakerName(tmpSpeakerSegment.speaker);
tmpWordsWithSpeakers.push(word);
});
return tmpWordsWithSpeakers;
}
/**
* Groups Words by speaker attribute
* @param {array} wordsWithSpeakers - same as kaldi words list but with a `speaker` label attribute on each word
* @return {array} - list of paragraph objcts, with words, text and sepaker attributes.
* where words is an array and the other two are strings.
*/
function groupWordsBySpeaker(wordsWithSpeakers) {
var currentSpeaker = wordsWithSpeakers[0].speaker;
var results = [];
var paragraph = {
words: [],
text: '',
speaker: ''
};
wordsWithSpeakers.forEach(function (word) {
// if current speaker same as word speaker add words to paragraph
if (currentSpeaker === word.speaker) {
paragraph.words.push(word);
paragraph.text += word.punct + ' ';
paragraph.speaker = currentSpeaker;
} // if it's not same speaker
else {
// update current speaker
currentSpeaker = word.speaker; // remove spacing in text
paragraph.text = paragraph.text.trim(); //save previous paragraph
results.push(paragraph); // reset paragraph
paragraph = {
words: [],
text: '',
speaker: 'U_UKN'
}; // add words attributes to new
paragraph.words.push(word);
paragraph.text += word.punct + ' ';
}
}); // add last paragraph
results.push(paragraph);
return results;
}
/**
* Helper functions
*/
/**
* given word start and end time attributes
* looks for segment range that contains that word
* if it doesn't find any it returns a segment with `UKN`
* speaker attributes.
* @param {object} word - word object
* @param {array} segments - list of segments objects
* @return {object} - a single segment whose range contains the word
*/
function findSegmentForWord(word, segments) {
var tmpSegment = segments.find(function (seg) {
var segEnd = seg.start + seg.duration;
return word.start >= seg.start && word.end <= segEnd;
}); // if find doesn't find any matches it returns an undefined
if (tmpSegment === undefined) {
// covering edge case orphan word not belonging to any segments
// adding UKN speaker label
return {
'@type': 'Segment',
// keeping both speaker id and gender as this is used later
// to format speaker label combining the two
speaker: {
'@id': 'UKN',
gender: 'U'
}
};
} else {
// find returns the first element that matches the criteria
return tmpSegment;
}
}
/**
* formats kaldi speaker object into a string
* Combining Gender and speaker Id
* @param {object} speaker - BBC kaldi speaker object
* @return {string} -
*/
function formatSpeakerName(speaker) {
return speaker.gender + '_' + speaker['@id'];
}
/* harmony default export */ var group_words_by_speakers = (groupWordsInParagraphsBySpeakers);
// CONCATENATED MODULE: ./packages/stt-adapters/bbc-kaldi/index.js
/**
* Convert BBC Kaldi json to draftJs
* see `sample` folder for example of input and output as well as `example-usage.js`
*
*/
/**
* groups words list from kaldi transcript based on punctuation.
* @todo To be more accurate, should introduce an honorifics library to do the splitting of the words.
* @param {array} words - array of words opbjects from kaldi transcript
*/
var groupWordsInParagraphs = function groupWordsInParagraphs(words) {
var results = [];
var paragraph = {
words: [],
text: []
};
words.forEach(function (word) {
// if word contains punctuation
if (/[.?!]/.test(word.punct)) {
paragraph.words.push(word);
paragraph.text.push(word.punct);
paragraph.text = paragraph.text.join(' ');
results.push(paragraph); // reset paragraph
paragraph = {
words: [],
text: []
};
} else {
paragraph.words.push(word);
paragraph.text.push(word.punct);
}
});
return results;
};
var bbc_kaldi_bbcKaldiToDraft = function bbcKaldiToDraft(bbcKaldiJson) {
var results = [];
var tmpWords;
var speakerSegmentation = null;
var wordsByParagraphs = []; // BBC Octo Labs API Response wraps Kaldi response around retval,
// while kaldi contains word attribute at root
if (bbcKaldiJson.retval !== undefined) {
tmpWords = bbcKaldiJson.retval.words;
if (bbcKaldiJson.retval.segmentation !== undefined) {
speakerSegmentation = bbcKaldiJson.retval.segmentation;
}
} else {
tmpWords = bbcKaldiJson.words;
if (bbcKaldiJson.segmentation !== undefined) {
speakerSegmentation = bbcKaldiJson.segmentation;
}
}
if (speakerSegmentation === null) {
wordsByParagraphs = groupWordsInParagraphs(tmpWords);
} else {
wordsByParagraphs = group_words_by_speakers(tmpWords, speakerSegmentation);
}
wordsByParagraphs.forEach(function (paragraph, i) {
// if paragraph contain words
// eg sometimes the speaker segmentation might not contain words :man-shrugging:
if (paragraph.words[0] !== undefined) {
var speakerLabel = "TBC ".concat(i);
if (speakerSegmentation !== null) {
speakerLabel = paragraph.speaker;
}
var draftJsContentBlockParagraph = {
text: paragraph.text,
type: 'paragraph',
data: {
speaker: speakerLabel,
words: paragraph.words,
start: paragraph.words[0].start
},
// the entities as ranges are each word in the space-joined text,
// so it needs to be compute for each the offset from the beginning of the paragraph and the length
entityRanges: Object(generate_entities_ranges["a" /* default */])(paragraph.words, 'punct') // wordAttributeName
};
results.push(draftJsContentBlockParagraph);
}
});
return results;
};
/* harmony default export */ var bbc_kaldi = (bbc_kaldi_bbcKaldiToDraft);
// CONCATENATED MODULE: ./packages/stt-adapters/autoEdit2/index.js
/**
* Convert autoEdit2 Json to draftJS
* see `sample` folder for example of input and output as well as `example-usage.js`
*/
/**
* groups words list from autoEdit transcript based on punctuation.
* @todo To be more accurate, should introduce an honorifics library to do the splitting of the words.
* @param {array} words - array of words objects from autoEdit transcript
*/
var autoEdit2_groupWordsInParagraphs = function groupWordsInParagraphs(autoEditText) {
var results = [];
var paragraph = {
words: [],
text: []
};
autoEditText.forEach(function (autoEditparagraph) {
autoEditparagraph.paragraph.forEach(function (autoEditLine) {
autoEditLine.line.forEach(function (word) {
// adjusting time reference attributes from
// `startTime` `endTime` to `start` `end`
// for word object
var tmpWord = {
text: word.text,
start: word.startTime,
end: word.endTime
}; // if word contains punctuation
if (/[.?!]/.test(word.text)) {
paragraph.words.push(tmpWord);
paragraph.text.push(word.text);
results.push(paragraph); // reset paragraph
paragraph = {
words: [],
text: []
};
} else {
paragraph.words.push(tmpWord);
paragraph.text.push(word.text);
}
});
});
});
return results;
};
var autoEdit2_autoEdit2ToDraft = function autoEdit2ToDraft(autoEdit2Json) {
var results = [];
var tmpWords = autoEdit2Json.text;
var wordsByParagraphs = autoEdit2_groupWordsInParagraphs(tmpWords);
wordsByParagraphs.forEach(function (paragraph, i) {
var draftJsContentBlockParagraph = {
text: paragraph.text.join(' '),
type: 'paragraph',
data: {
speaker: "TBC ".concat(i),
words: paragraph.words,
start: paragraph.words[0].start
},
// the entities as ranges are each word in the space-joined text,
// so it needs to be compute for each the offset from the beginning of the paragraph and the length
entityRanges: Object(generate_entities_ranges["a" /* default */])(paragraph.words, 'text')
}; // console.log(JSON.stringify(draftJsContentBlockParagraph,null,2))
results.push(draftJsContentBlockParagraph);
}); // console.log(JSON.stringify(results,null,2))
return results;
};
/* harmony default export */ var autoEdit2 = (autoEdit2_autoEdit2ToDraft);
// CONCATENATED MODULE: ./packages/stt-adapters/speechmatics/index.js
/**
* Convert Speechmatics Json to DraftJs
* see `sample` folder for example of input and output as well as `example-usage.js`
*/
/**
* Determines the speaker of a paragraph by comparing the start time of the paragraph with
* the speaker times.
* @param {float} start - Starting point of paragraph
* @param {array} speakers - list of all speakers with start and end time
*/
var getSpeaker = function getSpeaker(start, speakers) {
for (var speakerIdx in speakers) {
var speaker = speakers[speakerIdx];
var segmentStart = parseFloat(start);
if (segmentStart >= speaker.start & segmentStart < speaker.end) {
return speaker.name;
}
}
return 'UNK';
};
/**
* groups words list from speechmatics based on speaker change and paragraph length.
* @param {array} words - array of words objects from speechmatics transcript
* @param {array} speakers - array of speaker objects from speechmatics transcript
* @param {int} words - number of words which trigger a paragraph break
*/
var speechmatics_groupWordsInParagraphs = function groupWordsInParagraphs(words, speakers, maxParagraphWords) {
var results = [];
var paragraph = {
words: [],
text: [],
speaker: ''
};
var oldSpeaker = getSpeaker(words[0].start, speakers);
var newSpeaker;
var sentenceEnd = false;
words.forEach(function (word) {
newSpeaker = getSpeaker(word.start, speakers); // if speaker changes
if (newSpeaker !== oldSpeaker || paragraph.words.length > maxParagraphWords && sentenceEnd) {
paragraph.speaker = oldSpeaker;
results.push(paragraph);
oldSpeaker = newSpeaker; // reset paragraph
paragraph = {
words: [],
text: []
};
}
paragraph.words.push(word);
paragraph.text.push(word.punct);
sentenceEnd = /[.?!]/.test(word.punct) ? true : false;
});
paragraph.speaker = oldSpeaker;
results.push(paragraph);
return results;
};
/**
* Speechmatics treats punctuation as own words. This function merges punctuations with
* the pevious word and adjusts the total duration of the word.
* @param {array} words - array of words objects from speechmatics transcript
*/
var curatePunctuation = function curatePunctuation(words) {
var curatedWords = [];
words.forEach(function (word) {
if (/[.?!]/.test(word.name)) {
curatedWords[curatedWords.length - 1].name = curatedWords[curatedWords.length - 1].name + word.name;
curatedWords[curatedWords.length - 1].duration = (parseFloat(curatedWords[curatedWords.length - 1].duration) + parseFloat(word.duration)).toString();
} else {
curatedWords.push(word);
}
});
return curatedWords;
};
var speechmatics_speechmaticsToDraft = function speechmaticsToDraft(speechmaticsJson) {
var results = [];
var tmpWords;
tmpWords = curatePunctuation(speechmaticsJson.words);
tmpWords = tmpWords.map(function (element, index) {
return {
start: element.time,
end: (parseFloat(element.time) + parseFloat(element.duration)).toString(),
confidence: element.confidence,
word: element.name.toLowerCase().replace(/[.?!]/g, ''),
punct: element.name,
index: index
};
});
var tmpSpeakers;
tmpSpeakers = speechmaticsJson.speakers;
tmpSpeakers = tmpSpeakers.map(function (element) {
return {
start: parseFloat(element.time),
end: parseFloat(element.time) + parseFloat(element.duration),
name: element.name
};
});
var wordsByParagraphs = speechmatics_groupWordsInParagraphs(tmpWords, tmpSpeakers, 150);
wordsByParagraphs.forEach(function (paragraph) {
var paragraphStart = paragraph.words[0].start;
var draftJsContentBlockParagraph = {
text: paragraph.text.join(' '),
type: 'paragraph',
data: {
speaker: paragraph.speaker,
words: paragraph.words,
start: paragraphStart
},
// the entities as ranges are each word in the space-joined text,
// so it needs to be compute for each the offset from the beginning of the paragraph and the length
entityRanges: Object(generate_entities_ranges["a" /* default */])(paragraph.words, 'punct') // wordAttributeName
};
results.push(draftJsContentBlockParagraph);
});
return results;
};
/* harmony default export */ var speechmatics = (speechmatics_speechmaticsToDraft);
// CONCATENATED MODULE: ./packages/stt-adapters/amazon-transcribe/group-words-by-speakers.js
var groupWordsBySpeakerLabel = function groupWordsBySpeakerLabel(words) {
var groupedWords = [];
var currentSpeaker = '';
words.forEach(function (word) {
if (word.speaker_label === currentSpeaker) {
groupedWords[groupedWords.length - 1].words.push(word);
} else {
currentSpeaker = word.speaker_label; // start new speaker block
groupedWords.push({
speaker: word.speaker_label,
words: [word]
});
}
});
return groupedWords;
};
var findSpeakerForWord = function findSpeakerForWord(word, segments) {
var startTime = parseFloat(word.start_time);
var endTime = parseFloat(word.end_time);
var firstMatchingSegment = segments.find(function (seg) {
return startTime >= parseFloat(seg.start_time) && endTime <= parseFloat(seg.end_time);
});
if (firstMatchingSegment === undefined) {
return 'UKN';
} else {
return firstMatchingSegment.speaker_label.replace('spk_', '');
}
};
var addSpeakerLabelToWords = function addSpeakerLabelToWords(words, segments) {
return words.map(function (w) {
return Object.assign(w, {
'speaker_label': findSpeakerForWord(w, segments)
});
});
};
var group_words_by_speakers_groupWordsBySpeaker = function groupWordsBySpeaker(words, speakerLabels) {
var wordsWithSpeakers = addSpeakerLabelToWords(words, speakerLabels.segments);
return groupWordsBySpeakerLabel(wordsWithSpeakers);
};
// CONCATENATED MODULE: ./packages/stt-adapters/amazon-transcribe/index.js
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Converts AWS Transcribe Json to DraftJs
* see `sample` folder for example of input and output as well as `example-usage.js`
*/
var stripLeadingSpace = function stripLeadingSpace(word) {
return word.replace(/^\s/, '');
};
/**
* @param {json} words - List of words
* @param {string} wordAttributeName - eg 'punct' or 'text' or etc.
* attribute for the word object containing the text. eg word ={ punct:'helo', ... }
* or eg word ={ text:'helo', ... }
*/
var getBestAlternativeForWord = function getBestAlternativeForWord(word) {
if (/punctuation/.test(word.type)) {
return Object.assign(word.alternatives[0], {
confidence: 1
}); //Transcribe doesn't provide a confidence for punctuation
}
var wordWithHighestConfidence = word.alternatives.reduce(function (prev, current) {
return parseFloat(prev.confidence) > parseFloat(current.confidence) ? prev : current;
});
return wordWithHighestConfidence;
};
/**
* Normalizes words so they can be used in
* the generic generateEntitiesRanges() method
**/
var normalizeWord = function normalizeWord(currentWord) {
var bestAlternative = getBestAlternativeForWord(currentWord);
return {
start: parseFloat(currentWord.start_time),
end: parseFloat(currentWord.end_time),
text: bestAlternative.content,
confidence: parseFloat(bestAlternative.confidence)
};
};
var appendPunctuationToPreviousWord = function appendPunctuationToPreviousWord(punctuation, previousWord) {
var punctuationContent = punctuation.alternatives[0].content;
return _objectSpread({}, previousWord, {
alternatives: previousWord.alternatives.map(function (w) {
return _objectSpread({}, w, {
content: w.content + stripLeadingSpace(punctuationContent)
});
})
});
};
var mapPunctuationItemsToWords = function mapPunctuationItemsToWords(words) {
var itemsToRemove = [];
var dirtyArray = words.map(function (word, index) {
var previousWord = {};
if (word.type === 'punctuation') {
itemsToRemove.push(index - 1);
previousWord = words[index - 1];
return appendPunctuationToPreviousWord(word, previousWord);
} else {
return word;
}
});
return dirtyArray.filter(function (item, index) {
return !itemsToRemove.includes(index);
});
};
/**
* groups words list from amazon transcribe transcript based on punctuation.
* @todo To be more accurate, should introduce an honorifics library to do the splitting of the words.
* @param {array} words - array of words objects from kaldi transcript
*/
var amazon_transcribe_groupWordsInParagraphs = function groupWordsInParagraphs(words) {
var results = [];
var paragraph = {
words: [],
text: []
};
words.forEach(function (word) {
var content = getBestAlternativeForWord(word).content;
var normalizedWord = normalizeWord(word);
if (/[.?!]/.test(content)) {
paragraph.words.push(normalizedWord);
paragraph.text.push(content);
results.push(paragraph); // reset paragraph
paragraph = {
words: [],
text: []
};
} else {
paragraph.words.push(normalizedWord);
paragraph.text.push(content);
}
});
return results;
};
var amazon_transcribe_groupSpeakerWordsInParagraphs = function groupSpeakerWordsInParagraphs(words, speakerLabels) {
var wordsBySpeaker = group_words_by_speakers_groupWordsBySpeaker(words, speakerLabels);
return wordsBySpeaker.map(function (speakerGroup) {
return {
words: speakerGroup.words.map(normalizeWord),
text: speakerGroup.words.map(function (w) {
return getBestAlternativeForWord(w).content;
}),
speaker: speakerGroup.speaker
};
});
};
var amazon_transcribe_amazonTranscribeToDraft = function amazonTranscribeToDraft(amazonTranscribeJson) {
var results = [];
var tmpWords = amazonTranscribeJson.results.items;
var speakerLabels = amazonTranscribeJson.results.speaker_labels;
var wordsWithRemappedPunctuation = mapPunctuationItemsToWords(tmpWords);
var speakerSegmentation = typeof speakerLabels != 'undefined';
var wordsByParagraphs = speakerSegmentation ? amazon_transcribe_groupSpeakerWordsInParagraphs(wordsWithRemappedPunctuation, speakerLabels) : amazon_transcribe_groupWordsInParagraphs(wordsWithRemappedPunctuation);
wordsByParagraphs.forEach(function (paragraph, i) {
var draftJsContentBlockParagraph = {
text: paragraph.text.join(' '),
type: 'paragraph',
data: {
speaker: paragraph.speaker ? "Speaker ".concat(paragraph.speaker) : "TBC ".concat(i),
words: paragraph.words,
start: parseFloat(paragraph.words[0].start)
},
// the entities as ranges are each word in the space-joined text,
// so it needs to be compute for each the offset from the beginning of the paragraph and the length
entityRanges: Object(generate_entities_ranges["a" /* default */])(paragraph.words, 'text') // wordAttributeName
};
results.push(draftJsContentBlockParagraph);
});
return results;
};
/* harmony default export */ var amazon_transcribe = (amazon_transcribe_amazonTranscribeToDraft);
// CONCATENATED MODULE: ./packages/stt-adapters/ibm/index.js
/**
* Convert IBM json to draftJS
* see `sample` folder for example of input and output as well as `example-usage.js`
*
*/
var ibm_ibmToDraft = function ibmToDraft(ibmJson) {
// helper function to normalise IBM words at line level
var normalizeTimeStampsToWords = function normalizeTimeStampsToWords(timestamps) {
return timestamps.map(function (ibmWord) {
return {
text: ibmWord[