index.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. import { v4 as uuidv4 } from 'uuid';
  2. import sha256 from 'js-sha256';
  3. //////////////////////////
  4. // Helper functions
  5. //////////////////////////
  6. export const sanitizeResponseContent = (content: string) => {
  7. return content
  8. .replace(/<\|[a-z]*$/, '')
  9. .replace(/<\|[a-z]+\|$/, '')
  10. .replace(/<$/, '')
  11. .replaceAll(/<\|[a-z]+\|>/g, ' ')
  12. .replaceAll('<', '&lt;')
  13. .replaceAll('>', '&gt;')
  14. .trim();
  15. };
  16. export const revertSanitizedResponseContent = (content: string) => {
  17. return content.replaceAll('&lt;', '<').replaceAll('&gt;', '>');
  18. };
  19. export const capitalizeFirstLetter = (string) => {
  20. return string.charAt(0).toUpperCase() + string.slice(1);
  21. };
  22. export const splitStream = (splitOn) => {
  23. let buffer = '';
  24. return new TransformStream({
  25. transform(chunk, controller) {
  26. buffer += chunk;
  27. const parts = buffer.split(splitOn);
  28. parts.slice(0, -1).forEach((part) => controller.enqueue(part));
  29. buffer = parts[parts.length - 1];
  30. },
  31. flush(controller) {
  32. if (buffer) controller.enqueue(buffer);
  33. }
  34. });
  35. };
  36. export const convertMessagesToHistory = (messages) => {
  37. const history = {
  38. messages: {},
  39. currentId: null
  40. };
  41. let parentMessageId = null;
  42. let messageId = null;
  43. for (const message of messages) {
  44. messageId = uuidv4();
  45. if (parentMessageId !== null) {
  46. history.messages[parentMessageId].childrenIds = [
  47. ...history.messages[parentMessageId].childrenIds,
  48. messageId
  49. ];
  50. }
  51. history.messages[messageId] = {
  52. ...message,
  53. id: messageId,
  54. parentId: parentMessageId,
  55. childrenIds: []
  56. };
  57. parentMessageId = messageId;
  58. }
  59. history.currentId = messageId;
  60. return history;
  61. };
  62. export const getGravatarURL = (email) => {
  63. // Trim leading and trailing whitespace from
  64. // an email address and force all characters
  65. // to lower case
  66. const address = String(email).trim().toLowerCase();
  67. // Create a SHA256 hash of the final string
  68. const hash = sha256(address);
  69. // Grab the actual image URL
  70. return `https://www.gravatar.com/avatar/${hash}`;
  71. };
  72. export const canvasPixelTest = () => {
  73. // Test a 1x1 pixel to potentially identify browser/plugin fingerprint blocking or spoofing
  74. // Inspiration: https://github.com/kkapsner/CanvasBlocker/blob/master/test/detectionTest.js
  75. const canvas = document.createElement('canvas');
  76. const ctx = canvas.getContext('2d');
  77. canvas.height = 1;
  78. canvas.width = 1;
  79. const imageData = new ImageData(canvas.width, canvas.height);
  80. const pixelValues = imageData.data;
  81. // Generate RGB test data
  82. for (let i = 0; i < imageData.data.length; i += 1) {
  83. if (i % 4 !== 3) {
  84. pixelValues[i] = Math.floor(256 * Math.random());
  85. } else {
  86. pixelValues[i] = 255;
  87. }
  88. }
  89. ctx.putImageData(imageData, 0, 0);
  90. const p = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  91. // Read RGB data and fail if unmatched
  92. for (let i = 0; i < p.length; i += 1) {
  93. if (p[i] !== pixelValues[i]) {
  94. console.log(
  95. 'canvasPixelTest: Wrong canvas pixel RGB value detected:',
  96. p[i],
  97. 'at:',
  98. i,
  99. 'expected:',
  100. pixelValues[i]
  101. );
  102. console.log('canvasPixelTest: Canvas blocking or spoofing is likely');
  103. return false;
  104. }
  105. }
  106. return true;
  107. };
  108. export const generateInitialsImage = (name) => {
  109. const canvas = document.createElement('canvas');
  110. const ctx = canvas.getContext('2d');
  111. canvas.width = 100;
  112. canvas.height = 100;
  113. if (!canvasPixelTest()) {
  114. console.log(
  115. 'generateInitialsImage: failed pixel test, fingerprint evasion is likely. Using default image.'
  116. );
  117. return '/user.png';
  118. }
  119. ctx.fillStyle = '#F39C12';
  120. ctx.fillRect(0, 0, canvas.width, canvas.height);
  121. ctx.fillStyle = '#FFFFFF';
  122. ctx.font = '40px Helvetica';
  123. ctx.textAlign = 'center';
  124. ctx.textBaseline = 'middle';
  125. const sanitizedName = name.trim();
  126. const initials =
  127. sanitizedName.length > 0
  128. ? sanitizedName[0] +
  129. (sanitizedName.split(' ').length > 1
  130. ? sanitizedName[sanitizedName.lastIndexOf(' ') + 1]
  131. : '')
  132. : '';
  133. ctx.fillText(initials.toUpperCase(), canvas.width / 2, canvas.height / 2);
  134. return canvas.toDataURL();
  135. };
  136. export const copyToClipboard = async (text) => {
  137. let result = false;
  138. if (!navigator.clipboard) {
  139. const textArea = document.createElement('textarea');
  140. textArea.value = text;
  141. // Avoid scrolling to bottom
  142. textArea.style.top = '0';
  143. textArea.style.left = '0';
  144. textArea.style.position = 'fixed';
  145. document.body.appendChild(textArea);
  146. textArea.focus();
  147. textArea.select();
  148. try {
  149. const successful = document.execCommand('copy');
  150. const msg = successful ? 'successful' : 'unsuccessful';
  151. console.log('Fallback: Copying text command was ' + msg);
  152. result = true;
  153. } catch (err) {
  154. console.error('Fallback: Oops, unable to copy', err);
  155. }
  156. document.body.removeChild(textArea);
  157. return result;
  158. }
  159. result = await navigator.clipboard
  160. .writeText(text)
  161. .then(() => {
  162. console.log('Async: Copying to clipboard was successful!');
  163. return true;
  164. })
  165. .catch((error) => {
  166. console.error('Async: Could not copy text: ', error);
  167. return false;
  168. });
  169. return result;
  170. };
  171. export const compareVersion = (latest, current) => {
  172. return current === '0.0.0'
  173. ? false
  174. : current.localeCompare(latest, undefined, {
  175. numeric: true,
  176. sensitivity: 'case',
  177. caseFirst: 'upper'
  178. }) < 0;
  179. };
  180. export const findWordIndices = (text) => {
  181. const regex = /\[([^\]]+)\]/g;
  182. const matches = [];
  183. let match;
  184. while ((match = regex.exec(text)) !== null) {
  185. matches.push({
  186. word: match[1],
  187. startIndex: match.index,
  188. endIndex: regex.lastIndex - 1
  189. });
  190. }
  191. return matches;
  192. };
  193. export const removeFirstHashWord = (inputString) => {
  194. // Split the string into an array of words
  195. const words = inputString.split(' ');
  196. // Find the index of the first word that starts with #
  197. const index = words.findIndex((word) => word.startsWith('#'));
  198. // Remove the first word with #
  199. if (index !== -1) {
  200. words.splice(index, 1);
  201. }
  202. // Join the remaining words back into a string
  203. const resultString = words.join(' ');
  204. return resultString;
  205. };
  206. export const transformFileName = (fileName) => {
  207. // Convert to lowercase
  208. const lowerCaseFileName = fileName.toLowerCase();
  209. // Remove special characters using regular expression
  210. const sanitizedFileName = lowerCaseFileName.replace(/[^\w\s]/g, '');
  211. // Replace spaces with dashes
  212. const finalFileName = sanitizedFileName.replace(/\s+/g, '-');
  213. return finalFileName;
  214. };
  215. export const calculateSHA256 = async (file) => {
  216. // Create a FileReader to read the file asynchronously
  217. const reader = new FileReader();
  218. // Define a promise to handle the file reading
  219. const readFile = new Promise((resolve, reject) => {
  220. reader.onload = () => resolve(reader.result);
  221. reader.onerror = reject;
  222. });
  223. // Read the file as an ArrayBuffer
  224. reader.readAsArrayBuffer(file);
  225. try {
  226. // Wait for the FileReader to finish reading the file
  227. const buffer = await readFile;
  228. // Convert the ArrayBuffer to a Uint8Array
  229. const uint8Array = new Uint8Array(buffer);
  230. // Calculate the SHA-256 hash using Web Crypto API
  231. const hashBuffer = await crypto.subtle.digest('SHA-256', uint8Array);
  232. // Convert the hash to a hexadecimal string
  233. const hashArray = Array.from(new Uint8Array(hashBuffer));
  234. const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('');
  235. return `${hashHex}`;
  236. } catch (error) {
  237. console.error('Error calculating SHA-256 hash:', error);
  238. throw error;
  239. }
  240. };
  241. export const getImportOrigin = (_chats) => {
  242. // Check what external service chat imports are from
  243. if ('mapping' in _chats[0]) {
  244. return 'openai';
  245. }
  246. return 'webui';
  247. };
  248. const convertOpenAIMessages = (convo) => {
  249. // Parse OpenAI chat messages and create chat dictionary for creating new chats
  250. const mapping = convo['mapping'];
  251. const messages = [];
  252. let currentId = '';
  253. let lastId = null;
  254. for (let message_id in mapping) {
  255. const message = mapping[message_id];
  256. currentId = message_id;
  257. try {
  258. if (
  259. messages.length == 0 &&
  260. (message['message'] == null ||
  261. (message['message']['content']['parts']?.[0] == '' &&
  262. message['message']['content']['text'] == null))
  263. ) {
  264. // Skip chat messages with no content
  265. continue;
  266. } else {
  267. const new_chat = {
  268. id: message_id,
  269. parentId: lastId,
  270. childrenIds: message['children'] || [],
  271. role: message['message']?.['author']?.['role'] !== 'user' ? 'assistant' : 'user',
  272. content:
  273. message['message']?.['content']?.['parts']?.[0] ||
  274. message['message']?.['content']?.['text'] ||
  275. '',
  276. model: 'gpt-3.5-turbo',
  277. done: true,
  278. context: null
  279. };
  280. messages.push(new_chat);
  281. lastId = currentId;
  282. }
  283. } catch (error) {
  284. console.log('Error with', message, '\nError:', error);
  285. }
  286. }
  287. let history = {};
  288. messages.forEach((obj) => (history[obj.id] = obj));
  289. const chat = {
  290. history: {
  291. currentId: currentId,
  292. messages: history // Need to convert this to not a list and instead a json object
  293. },
  294. models: ['gpt-3.5-turbo'],
  295. messages: messages,
  296. options: {},
  297. timestamp: convo['create_time'],
  298. title: convo['title'] ?? 'New Chat'
  299. };
  300. return chat;
  301. };
  302. const validateChat = (chat) => {
  303. // Because ChatGPT sometimes has features we can't use like DALL-E or migh have corrupted messages, need to validate
  304. const messages = chat.messages;
  305. // Check if messages array is empty
  306. if (messages.length === 0) {
  307. return false;
  308. }
  309. // Last message's children should be an empty array
  310. const lastMessage = messages[messages.length - 1];
  311. if (lastMessage.childrenIds.length !== 0) {
  312. return false;
  313. }
  314. // First message's parent should be null
  315. const firstMessage = messages[0];
  316. if (firstMessage.parentId !== null) {
  317. return false;
  318. }
  319. // Every message's content should be a string
  320. for (let message of messages) {
  321. if (typeof message.content !== 'string') {
  322. return false;
  323. }
  324. }
  325. return true;
  326. };
  327. export const convertOpenAIChats = (_chats) => {
  328. // Create a list of dictionaries with each conversation from import
  329. const chats = [];
  330. let failed = 0;
  331. for (let convo of _chats) {
  332. const chat = convertOpenAIMessages(convo);
  333. if (validateChat(chat)) {
  334. chats.push({
  335. id: convo['id'],
  336. user_id: '',
  337. title: convo['title'],
  338. chat: chat,
  339. timestamp: convo['timestamp']
  340. });
  341. } else {
  342. failed++;
  343. }
  344. }
  345. console.log(failed, 'Conversations could not be imported');
  346. return chats;
  347. };
  348. export const isValidHttpUrl = (string) => {
  349. let url;
  350. try {
  351. url = new URL(string);
  352. } catch (_) {
  353. return false;
  354. }
  355. return url.protocol === 'http:' || url.protocol === 'https:';
  356. };
  357. export const removeEmojis = (str) => {
  358. // Regular expression to match emojis
  359. const emojiRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g;
  360. // Replace emojis with an empty string
  361. return str.replace(emojiRegex, '');
  362. };
  363. export const extractSentences = (text) => {
  364. // Split the paragraph into sentences based on common punctuation marks
  365. const sentences = text.split(/(?<=[.!?])\s+/);
  366. return sentences
  367. .map((sentence) => removeEmojis(sentence.trim()))
  368. .filter((sentence) => sentence !== '');
  369. };
  370. export const extractSentencesForAudio = (text) => {
  371. return extractSentences(text).reduce((mergedTexts, currentText) => {
  372. const lastIndex = mergedTexts.length - 1;
  373. if (lastIndex >= 0) {
  374. const previousText = mergedTexts[lastIndex];
  375. const wordCount = previousText.split(/\s+/).length;
  376. if (wordCount < 2) {
  377. mergedTexts[lastIndex] = previousText + ' ' + currentText;
  378. } else {
  379. mergedTexts.push(currentText);
  380. }
  381. } else {
  382. mergedTexts.push(currentText);
  383. }
  384. return mergedTexts;
  385. }, []);
  386. };
  387. export const blobToFile = (blob, fileName) => {
  388. // Create a new File object from the Blob
  389. const file = new File([blob], fileName, { type: blob.type });
  390. return file;
  391. };
  392. /**
  393. * @param {string} template - The template string containing placeholders.
  394. * @returns {string} The template string with the placeholders replaced by the prompt.
  395. */
  396. export const promptTemplate = (
  397. template: string,
  398. user_name?: string,
  399. current_location?: string
  400. ): string => {
  401. // Get the current date
  402. const currentDate = new Date();
  403. // Format the date to YYYY-MM-DD
  404. const formattedDate =
  405. currentDate.getFullYear() +
  406. '-' +
  407. String(currentDate.getMonth() + 1).padStart(2, '0') +
  408. '-' +
  409. String(currentDate.getDate()).padStart(2, '0');
  410. // Format the time to HH:MM:SS AM/PM
  411. const currentTime = currentDate.toLocaleTimeString('en-US', {
  412. hour: 'numeric',
  413. minute: 'numeric',
  414. second: 'numeric',
  415. hour12: true
  416. });
  417. // Replace {{CURRENT_DATETIME}} in the template with the formatted datetime
  418. template = template.replace('{{CURRENT_DATETIME}}', `${formattedDate} ${currentTime}`);
  419. // Replace {{CURRENT_DATE}} in the template with the formatted date
  420. template = template.replace('{{CURRENT_DATE}}', formattedDate);
  421. // Replace {{CURRENT_TIME}} in the template with the formatted time
  422. template = template.replace('{{CURRENT_TIME}}', currentTime);
  423. if (user_name) {
  424. // Replace {{USER_NAME}} in the template with the user's name
  425. template = template.replace('{{USER_NAME}}', user_name);
  426. }
  427. if (current_location) {
  428. // Replace {{CURRENT_LOCATION}} in the template with the current location
  429. template = template.replace('{{CURRENT_LOCATION}}', current_location);
  430. }
  431. return template;
  432. };
  433. /**
  434. * This function is used to replace placeholders in a template string with the provided prompt.
  435. * The placeholders can be in the following formats:
  436. * - `{{prompt}}`: This will be replaced with the entire prompt.
  437. * - `{{prompt:start:<length>}}`: This will be replaced with the first <length> characters of the prompt.
  438. * - `{{prompt:end:<length>}}`: This will be replaced with the last <length> characters of the prompt.
  439. * - `{{prompt:middletruncate:<length>}}`: This will be replaced with the prompt truncated to <length> characters, with '...' in the middle.
  440. *
  441. * @param {string} template - The template string containing placeholders.
  442. * @param {string} prompt - The string to replace the placeholders with.
  443. * @returns {string} The template string with the placeholders replaced by the prompt.
  444. */
  445. export const titleGenerationTemplate = (template: string, prompt: string): string => {
  446. template = template.replace(
  447. /{{prompt}}|{{prompt:start:(\d+)}}|{{prompt:end:(\d+)}}|{{prompt:middletruncate:(\d+)}}/g,
  448. (match, startLength, endLength, middleLength) => {
  449. if (match === '{{prompt}}') {
  450. return prompt;
  451. } else if (match.startsWith('{{prompt:start:')) {
  452. return prompt.substring(0, startLength);
  453. } else if (match.startsWith('{{prompt:end:')) {
  454. return prompt.slice(-endLength);
  455. } else if (match.startsWith('{{prompt:middletruncate:')) {
  456. if (prompt.length <= middleLength) {
  457. return prompt;
  458. }
  459. const start = prompt.slice(0, Math.ceil(middleLength / 2));
  460. const end = prompt.slice(-Math.floor(middleLength / 2));
  461. return `${start}...${end}`;
  462. }
  463. return '';
  464. }
  465. );
  466. template = promptTemplate(template);
  467. return template;
  468. };
  469. export const approximateToHumanReadable = (nanoseconds: number) => {
  470. const seconds = Math.floor((nanoseconds / 1e9) % 60);
  471. const minutes = Math.floor((nanoseconds / 6e10) % 60);
  472. const hours = Math.floor((nanoseconds / 3.6e12) % 24);
  473. const results: string[] = [];
  474. if (seconds >= 0) {
  475. results.push(`${seconds}s`);
  476. }
  477. if (minutes > 0) {
  478. results.push(`${minutes}m`);
  479. }
  480. if (hours > 0) {
  481. results.push(`${hours}h`);
  482. }
  483. return results.reverse().join(' ');
  484. };
  485. export const getTimeRange = (timestamp) => {
  486. const now = new Date();
  487. const date = new Date(timestamp * 1000); // Convert Unix timestamp to milliseconds
  488. // Calculate the difference in milliseconds
  489. const diffTime = now.getTime() - date.getTime();
  490. const diffDays = diffTime / (1000 * 3600 * 24);
  491. const nowDate = now.getDate();
  492. const nowMonth = now.getMonth();
  493. const nowYear = now.getFullYear();
  494. const dateDate = date.getDate();
  495. const dateMonth = date.getMonth();
  496. const dateYear = date.getFullYear();
  497. if (nowYear === dateYear && nowMonth === dateMonth && nowDate === dateDate) {
  498. return 'Today';
  499. } else if (nowYear === dateYear && nowMonth === dateMonth && nowDate - dateDate === 1) {
  500. return 'Yesterday';
  501. } else if (diffDays <= 7) {
  502. return 'Previous 7 days';
  503. } else if (diffDays <= 30) {
  504. return 'Previous 30 days';
  505. } else if (nowYear === dateYear) {
  506. return date.toLocaleString('default', { month: 'long' });
  507. } else {
  508. return date.getFullYear().toString();
  509. }
  510. };