index.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. import { v4 as uuidv4 } from 'uuid';
  2. import sha256 from 'js-sha256';
  3. import { WEBUI_BASE_URL } from '$lib/constants';
  4. import { TTS_RESPONSE_SPLIT } from '$lib/types';
  5. //////////////////////////
  6. // Helper functions
  7. //////////////////////////
  8. export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
  9. function escapeRegExp(string: string): string {
  10. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  11. }
  12. export const replaceTokens = (content, sourceIds, char, user) => {
  13. const charToken = /{{char}}/gi;
  14. const userToken = /{{user}}/gi;
  15. const videoIdToken = /{{VIDEO_FILE_ID_([a-f0-9-]+)}}/gi; // Regex to capture the video ID
  16. const htmlIdToken = /{{HTML_FILE_ID_([a-f0-9-]+)}}/gi; // Regex to capture the HTML ID
  17. // Replace {{char}} if char is provided
  18. if (char !== undefined && char !== null) {
  19. content = content.replace(charToken, char);
  20. }
  21. // Replace {{user}} if user is provided
  22. if (user !== undefined && user !== null) {
  23. content = content.replace(userToken, user);
  24. }
  25. // Replace video ID tags with corresponding <video> elements
  26. content = content.replace(videoIdToken, (match, fileId) => {
  27. const videoUrl = `${WEBUI_BASE_URL}/api/v1/files/${fileId}/content`;
  28. return `<video src="${videoUrl}" controls></video>`;
  29. });
  30. // Replace HTML ID tags with corresponding HTML content
  31. content = content.replace(htmlIdToken, (match, fileId) => {
  32. const htmlUrl = `${WEBUI_BASE_URL}/api/v1/files/${fileId}/content/html`;
  33. return `<iframe src="${htmlUrl}" width="100%" frameborder="0" onload="this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';"></iframe>`;
  34. });
  35. // Remove sourceIds from the content and replace them with <source_id>...</source_id>
  36. if (Array.isArray(sourceIds)) {
  37. sourceIds.forEach((sourceId) => {
  38. // Escape special characters in the sourceId
  39. const escapedSourceId = escapeRegExp(sourceId);
  40. // Create a token based on the exact `[sourceId]` string
  41. const sourceToken = `\\[${escapedSourceId}\\]`; // Escape special characters for RegExp
  42. const sourceRegex = new RegExp(sourceToken, 'g'); // Match all occurrences of [sourceId]
  43. content = content.replace(sourceRegex, `<source_id data="${sourceId}" />`);
  44. });
  45. }
  46. return content;
  47. };
  48. export const sanitizeResponseContent = (content: string) => {
  49. return content
  50. .replace(/<\|[a-z]*$/, '')
  51. .replace(/<\|[a-z]+\|$/, '')
  52. .replace(/<$/, '')
  53. .replaceAll(/<\|[a-z]+\|>/g, ' ')
  54. .replaceAll('<', '&lt;')
  55. .replaceAll('>', '&gt;')
  56. .trim();
  57. };
  58. export const processResponseContent = (content: string) => {
  59. return content.trim();
  60. };
  61. export const revertSanitizedResponseContent = (content: string) => {
  62. return content.replaceAll('&lt;', '<').replaceAll('&gt;', '>');
  63. };
  64. export function unescapeHtml(html: string) {
  65. const doc = new DOMParser().parseFromString(html, 'text/html');
  66. return doc.documentElement.textContent;
  67. }
  68. export const capitalizeFirstLetter = (string) => {
  69. return string.charAt(0).toUpperCase() + string.slice(1);
  70. };
  71. export const splitStream = (splitOn) => {
  72. let buffer = '';
  73. return new TransformStream({
  74. transform(chunk, controller) {
  75. buffer += chunk;
  76. const parts = buffer.split(splitOn);
  77. parts.slice(0, -1).forEach((part) => controller.enqueue(part));
  78. buffer = parts[parts.length - 1];
  79. },
  80. flush(controller) {
  81. if (buffer) controller.enqueue(buffer);
  82. }
  83. });
  84. };
  85. export const convertMessagesToHistory = (messages) => {
  86. const history = {
  87. messages: {},
  88. currentId: null
  89. };
  90. let parentMessageId = null;
  91. let messageId = null;
  92. for (const message of messages) {
  93. messageId = uuidv4();
  94. if (parentMessageId !== null) {
  95. history.messages[parentMessageId].childrenIds = [
  96. ...history.messages[parentMessageId].childrenIds,
  97. messageId
  98. ];
  99. }
  100. history.messages[messageId] = {
  101. ...message,
  102. id: messageId,
  103. parentId: parentMessageId,
  104. childrenIds: []
  105. };
  106. parentMessageId = messageId;
  107. }
  108. history.currentId = messageId;
  109. return history;
  110. };
  111. export const getGravatarURL = (email) => {
  112. // Trim leading and trailing whitespace from
  113. // an email address and force all characters
  114. // to lower case
  115. const address = String(email).trim().toLowerCase();
  116. // Create a SHA256 hash of the final string
  117. const hash = sha256(address);
  118. // Grab the actual image URL
  119. return `https://www.gravatar.com/avatar/${hash}`;
  120. };
  121. export const canvasPixelTest = () => {
  122. // Test a 1x1 pixel to potentially identify browser/plugin fingerprint blocking or spoofing
  123. // Inspiration: https://github.com/kkapsner/CanvasBlocker/blob/master/test/detectionTest.js
  124. const canvas = document.createElement('canvas');
  125. const ctx = canvas.getContext('2d');
  126. canvas.height = 1;
  127. canvas.width = 1;
  128. const imageData = new ImageData(canvas.width, canvas.height);
  129. const pixelValues = imageData.data;
  130. // Generate RGB test data
  131. for (let i = 0; i < imageData.data.length; i += 1) {
  132. if (i % 4 !== 3) {
  133. pixelValues[i] = Math.floor(256 * Math.random());
  134. } else {
  135. pixelValues[i] = 255;
  136. }
  137. }
  138. ctx.putImageData(imageData, 0, 0);
  139. const p = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  140. // Read RGB data and fail if unmatched
  141. for (let i = 0; i < p.length; i += 1) {
  142. if (p[i] !== pixelValues[i]) {
  143. console.log(
  144. 'canvasPixelTest: Wrong canvas pixel RGB value detected:',
  145. p[i],
  146. 'at:',
  147. i,
  148. 'expected:',
  149. pixelValues[i]
  150. );
  151. console.log('canvasPixelTest: Canvas blocking or spoofing is likely');
  152. return false;
  153. }
  154. }
  155. return true;
  156. };
  157. export const generateInitialsImage = (name) => {
  158. const canvas = document.createElement('canvas');
  159. const ctx = canvas.getContext('2d');
  160. canvas.width = 100;
  161. canvas.height = 100;
  162. if (!canvasPixelTest()) {
  163. console.log(
  164. 'generateInitialsImage: failed pixel test, fingerprint evasion is likely. Using default image.'
  165. );
  166. return '/user.png';
  167. }
  168. ctx.fillStyle = '#F39C12';
  169. ctx.fillRect(0, 0, canvas.width, canvas.height);
  170. ctx.fillStyle = '#FFFFFF';
  171. ctx.font = '40px Helvetica';
  172. ctx.textAlign = 'center';
  173. ctx.textBaseline = 'middle';
  174. const sanitizedName = name.trim();
  175. const initials =
  176. sanitizedName.length > 0
  177. ? sanitizedName[0] +
  178. (sanitizedName.split(' ').length > 1
  179. ? sanitizedName[sanitizedName.lastIndexOf(' ') + 1]
  180. : '')
  181. : '';
  182. ctx.fillText(initials.toUpperCase(), canvas.width / 2, canvas.height / 2);
  183. return canvas.toDataURL();
  184. };
  185. export const copyToClipboard = async (text) => {
  186. let result = false;
  187. if (!navigator.clipboard) {
  188. const textArea = document.createElement('textarea');
  189. textArea.value = text;
  190. // Avoid scrolling to bottom
  191. textArea.style.top = '0';
  192. textArea.style.left = '0';
  193. textArea.style.position = 'fixed';
  194. document.body.appendChild(textArea);
  195. textArea.focus();
  196. textArea.select();
  197. try {
  198. const successful = document.execCommand('copy');
  199. const msg = successful ? 'successful' : 'unsuccessful';
  200. console.log('Fallback: Copying text command was ' + msg);
  201. result = true;
  202. } catch (err) {
  203. console.error('Fallback: Oops, unable to copy', err);
  204. }
  205. document.body.removeChild(textArea);
  206. return result;
  207. }
  208. result = await navigator.clipboard
  209. .writeText(text)
  210. .then(() => {
  211. console.log('Async: Copying to clipboard was successful!');
  212. return true;
  213. })
  214. .catch((error) => {
  215. console.error('Async: Could not copy text: ', error);
  216. return false;
  217. });
  218. return result;
  219. };
  220. export const compareVersion = (latest, current) => {
  221. return current === '0.0.0'
  222. ? false
  223. : current.localeCompare(latest, undefined, {
  224. numeric: true,
  225. sensitivity: 'case',
  226. caseFirst: 'upper'
  227. }) < 0;
  228. };
  229. export const findWordIndices = (text) => {
  230. const regex = /\[([^\]]+)\]/g;
  231. const matches = [];
  232. let match;
  233. while ((match = regex.exec(text)) !== null) {
  234. matches.push({
  235. word: match[1],
  236. startIndex: match.index,
  237. endIndex: regex.lastIndex - 1
  238. });
  239. }
  240. return matches;
  241. };
  242. export const removeLastWordFromString = (inputString, wordString) => {
  243. console.log('inputString', inputString);
  244. // Split the string by newline characters to handle lines separately
  245. const lines = inputString.split('\n');
  246. // Take the last line to operate only on it
  247. const lastLine = lines.pop();
  248. // Split the last line into an array of words
  249. const words = lastLine.split(' ');
  250. // Conditional to check for the last word removal
  251. if (words.at(-1) === wordString || (wordString === '' && words.at(-1) === '\\#')) {
  252. words.pop(); // Remove last word if condition is satisfied
  253. }
  254. // Join the remaining words back into a string and handle space correctly
  255. let updatedLastLine = words.join(' ');
  256. // Add a trailing space to the updated last line if there are still words
  257. if (updatedLastLine !== '') {
  258. updatedLastLine += ' ';
  259. }
  260. // Combine the lines together again, placing the updated last line back in
  261. const resultString = [...lines, updatedLastLine].join('\n');
  262. // Return the final string
  263. console.log('resultString', resultString);
  264. return resultString;
  265. };
  266. export const removeFirstHashWord = (inputString) => {
  267. // Split the string into an array of words
  268. const words = inputString.split(' ');
  269. // Find the index of the first word that starts with #
  270. const index = words.findIndex((word) => word.startsWith('#'));
  271. // Remove the first word with #
  272. if (index !== -1) {
  273. words.splice(index, 1);
  274. }
  275. // Join the remaining words back into a string
  276. const resultString = words.join(' ');
  277. return resultString;
  278. };
  279. export const transformFileName = (fileName) => {
  280. // Convert to lowercase
  281. const lowerCaseFileName = fileName.toLowerCase();
  282. // Remove special characters using regular expression
  283. const sanitizedFileName = lowerCaseFileName.replace(/[^\w\s]/g, '');
  284. // Replace spaces with dashes
  285. const finalFileName = sanitizedFileName.replace(/\s+/g, '-');
  286. return finalFileName;
  287. };
  288. export const calculateSHA256 = async (file) => {
  289. // Create a FileReader to read the file asynchronously
  290. const reader = new FileReader();
  291. // Define a promise to handle the file reading
  292. const readFile = new Promise((resolve, reject) => {
  293. reader.onload = () => resolve(reader.result);
  294. reader.onerror = reject;
  295. });
  296. // Read the file as an ArrayBuffer
  297. reader.readAsArrayBuffer(file);
  298. try {
  299. // Wait for the FileReader to finish reading the file
  300. const buffer = await readFile;
  301. // Convert the ArrayBuffer to a Uint8Array
  302. const uint8Array = new Uint8Array(buffer);
  303. // Calculate the SHA-256 hash using Web Crypto API
  304. const hashBuffer = await crypto.subtle.digest('SHA-256', uint8Array);
  305. // Convert the hash to a hexadecimal string
  306. const hashArray = Array.from(new Uint8Array(hashBuffer));
  307. const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('');
  308. return `${hashHex}`;
  309. } catch (error) {
  310. console.error('Error calculating SHA-256 hash:', error);
  311. throw error;
  312. }
  313. };
  314. export const getImportOrigin = (_chats) => {
  315. // Check what external service chat imports are from
  316. if ('mapping' in _chats[0]) {
  317. return 'openai';
  318. }
  319. return 'webui';
  320. };
  321. export const getUserPosition = async (raw = false) => {
  322. // Get the user's location using the Geolocation API
  323. const position = await new Promise((resolve, reject) => {
  324. navigator.geolocation.getCurrentPosition(resolve, reject);
  325. }).catch((error) => {
  326. console.error('Error getting user location:', error);
  327. throw error;
  328. });
  329. if (!position) {
  330. return 'Location not available';
  331. }
  332. // Extract the latitude and longitude from the position
  333. const { latitude, longitude } = position.coords;
  334. if (raw) {
  335. return { latitude, longitude };
  336. } else {
  337. return `${latitude.toFixed(3)}, ${longitude.toFixed(3)} (lat, long)`;
  338. }
  339. };
  340. const convertOpenAIMessages = (convo) => {
  341. // Parse OpenAI chat messages and create chat dictionary for creating new chats
  342. const mapping = convo['mapping'];
  343. const messages = [];
  344. let currentId = '';
  345. let lastId = null;
  346. for (const message_id in mapping) {
  347. const message = mapping[message_id];
  348. currentId = message_id;
  349. try {
  350. if (
  351. messages.length == 0 &&
  352. (message['message'] == null ||
  353. (message['message']['content']['parts']?.[0] == '' &&
  354. message['message']['content']['text'] == null))
  355. ) {
  356. // Skip chat messages with no content
  357. continue;
  358. } else {
  359. const new_chat = {
  360. id: message_id,
  361. parentId: lastId,
  362. childrenIds: message['children'] || [],
  363. role: message['message']?.['author']?.['role'] !== 'user' ? 'assistant' : 'user',
  364. content:
  365. message['message']?.['content']?.['parts']?.[0] ||
  366. message['message']?.['content']?.['text'] ||
  367. '',
  368. model: 'gpt-3.5-turbo',
  369. done: true,
  370. context: null
  371. };
  372. messages.push(new_chat);
  373. lastId = currentId;
  374. }
  375. } catch (error) {
  376. console.log('Error with', message, '\nError:', error);
  377. }
  378. }
  379. const history: Record<PropertyKey, (typeof messages)[number]> = {};
  380. messages.forEach((obj) => (history[obj.id] = obj));
  381. const chat = {
  382. history: {
  383. currentId: currentId,
  384. messages: history // Need to convert this to not a list and instead a json object
  385. },
  386. models: ['gpt-3.5-turbo'],
  387. messages: messages,
  388. options: {},
  389. timestamp: convo['create_time'],
  390. title: convo['title'] ?? 'New Chat'
  391. };
  392. return chat;
  393. };
  394. const validateChat = (chat) => {
  395. // Because ChatGPT sometimes has features we can't use like DALL-E or might have corrupted messages, need to validate
  396. const messages = chat.messages;
  397. // Check if messages array is empty
  398. if (messages.length === 0) {
  399. return false;
  400. }
  401. // Last message's children should be an empty array
  402. const lastMessage = messages[messages.length - 1];
  403. if (lastMessage.childrenIds.length !== 0) {
  404. return false;
  405. }
  406. // First message's parent should be null
  407. const firstMessage = messages[0];
  408. if (firstMessage.parentId !== null) {
  409. return false;
  410. }
  411. // Every message's content should be a string
  412. for (const message of messages) {
  413. if (typeof message.content !== 'string') {
  414. return false;
  415. }
  416. }
  417. return true;
  418. };
  419. export const convertOpenAIChats = (_chats) => {
  420. // Create a list of dictionaries with each conversation from import
  421. const chats = [];
  422. let failed = 0;
  423. for (const convo of _chats) {
  424. const chat = convertOpenAIMessages(convo);
  425. if (validateChat(chat)) {
  426. chats.push({
  427. id: convo['id'],
  428. user_id: '',
  429. title: convo['title'],
  430. chat: chat,
  431. timestamp: convo['timestamp']
  432. });
  433. } else {
  434. failed++;
  435. }
  436. }
  437. console.log(failed, 'Conversations could not be imported');
  438. return chats;
  439. };
  440. export const isValidHttpUrl = (string: string) => {
  441. let url;
  442. try {
  443. url = new URL(string);
  444. } catch (_) {
  445. return false;
  446. }
  447. return url.protocol === 'http:' || url.protocol === 'https:';
  448. };
  449. export const removeEmojis = (str: string) => {
  450. // Regular expression to match emojis
  451. const emojiRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g;
  452. // Replace emojis with an empty string
  453. return str.replace(emojiRegex, '');
  454. };
  455. export const removeFormattings = (str: string) => {
  456. return (
  457. str
  458. // Block elements (remove completely)
  459. .replace(/(```[\s\S]*?```)/g, '') // Code blocks
  460. .replace(/^\|.*\|$/gm, '') // Tables
  461. // Inline elements (preserve content)
  462. .replace(/(?:\*\*|__)(.*?)(?:\*\*|__)/g, '$1') // Bold
  463. .replace(/(?:[*_])(.*?)(?:[*_])/g, '$1') // Italic
  464. .replace(/~~(.*?)~~/g, '$1') // Strikethrough
  465. .replace(/`([^`]+)`/g, '$1') // Inline code
  466. // Links and images
  467. .replace(/!?\[([^\]]*)\](?:\([^)]+\)|\[[^\]]*\])/g, '$1') // Links & images
  468. .replace(/^\[[^\]]+\]:\s*.*$/gm, '') // Reference definitions
  469. // Block formatting
  470. .replace(/^#{1,6}\s+/gm, '') // Headers
  471. .replace(/^\s*[-*+]\s+/gm, '') // Lists
  472. .replace(/^\s*(?:\d+\.)\s+/gm, '') // Numbered lists
  473. .replace(/^\s*>[> ]*/gm, '') // Blockquotes
  474. .replace(/^\s*:\s+/gm, '') // Definition lists
  475. // Cleanup
  476. .replace(/\[\^[^\]]*\]/g, '') // Footnotes
  477. .replace(/[-*_~]/g, '') // Remaining markers
  478. .replace(/\n{2,}/g, '\n')
  479. ); // Multiple newlines
  480. };
  481. export const cleanText = (content: string) => {
  482. return removeFormattings(removeEmojis(content.trim()));
  483. };
  484. // This regular expression matches code blocks marked by triple backticks
  485. const codeBlockRegex = /```[\s\S]*?```/g;
  486. export const extractSentences = (text: string) => {
  487. const codeBlocks: string[] = [];
  488. let index = 0;
  489. // Temporarily replace code blocks with placeholders and store the blocks separately
  490. text = text.replace(codeBlockRegex, (match) => {
  491. const placeholder = `\u0000${index}\u0000`; // Use a unique placeholder
  492. codeBlocks[index++] = match;
  493. return placeholder;
  494. });
  495. // Split the modified text into sentences based on common punctuation marks, avoiding these blocks
  496. let sentences = text.split(/(?<=[.!?])\s+/);
  497. // Restore code blocks and process sentences
  498. sentences = sentences.map((sentence) => {
  499. // Check if the sentence includes a placeholder for a code block
  500. return sentence.replace(/\u0000(\d+)\u0000/g, (_, idx) => codeBlocks[idx]);
  501. });
  502. return sentences.map(cleanText).filter(Boolean);
  503. };
  504. export const extractParagraphsForAudio = (text: string) => {
  505. const codeBlocks: string[] = [];
  506. let index = 0;
  507. // Temporarily replace code blocks with placeholders and store the blocks separately
  508. text = text.replace(codeBlockRegex, (match) => {
  509. const placeholder = `\u0000${index}\u0000`; // Use a unique placeholder
  510. codeBlocks[index++] = match;
  511. return placeholder;
  512. });
  513. // Split the modified text into paragraphs based on newlines, avoiding these blocks
  514. let paragraphs = text.split(/\n+/);
  515. // Restore code blocks and process paragraphs
  516. paragraphs = paragraphs.map((paragraph) => {
  517. // Check if the paragraph includes a placeholder for a code block
  518. return paragraph.replace(/\u0000(\d+)\u0000/g, (_, idx) => codeBlocks[idx]);
  519. });
  520. return paragraphs.map(cleanText).filter(Boolean);
  521. };
  522. export const extractSentencesForAudio = (text: string) => {
  523. return extractSentences(text).reduce((mergedTexts, currentText) => {
  524. const lastIndex = mergedTexts.length - 1;
  525. if (lastIndex >= 0) {
  526. const previousText = mergedTexts[lastIndex];
  527. const wordCount = previousText.split(/\s+/).length;
  528. const charCount = previousText.length;
  529. if (wordCount < 4 || charCount < 50) {
  530. mergedTexts[lastIndex] = previousText + ' ' + currentText;
  531. } else {
  532. mergedTexts.push(currentText);
  533. }
  534. } else {
  535. mergedTexts.push(currentText);
  536. }
  537. return mergedTexts;
  538. }, [] as string[]);
  539. };
  540. export const getMessageContentParts = (content: string, split_on: string = 'punctuation') => {
  541. const messageContentParts: string[] = [];
  542. switch (split_on) {
  543. default:
  544. case TTS_RESPONSE_SPLIT.PUNCTUATION:
  545. messageContentParts.push(...extractSentencesForAudio(content));
  546. break;
  547. case TTS_RESPONSE_SPLIT.PARAGRAPHS:
  548. messageContentParts.push(...extractParagraphsForAudio(content));
  549. break;
  550. case TTS_RESPONSE_SPLIT.NONE:
  551. messageContentParts.push(cleanText(content));
  552. break;
  553. }
  554. return messageContentParts;
  555. };
  556. export const blobToFile = (blob, fileName) => {
  557. // Create a new File object from the Blob
  558. const file = new File([blob], fileName, { type: blob.type });
  559. return file;
  560. };
  561. /**
  562. * @param {string} template - The template string containing placeholders.
  563. * @returns {string} The template string with the placeholders replaced by the prompt.
  564. */
  565. export const promptTemplate = (
  566. template: string,
  567. user_name?: string,
  568. user_location?: string
  569. ): string => {
  570. // Get the current date
  571. const currentDate = new Date();
  572. // Format the date to YYYY-MM-DD
  573. const formattedDate =
  574. currentDate.getFullYear() +
  575. '-' +
  576. String(currentDate.getMonth() + 1).padStart(2, '0') +
  577. '-' +
  578. String(currentDate.getDate()).padStart(2, '0');
  579. // Format the time to HH:MM:SS AM/PM
  580. const currentTime = currentDate.toLocaleTimeString('en-US', {
  581. hour: 'numeric',
  582. minute: 'numeric',
  583. second: 'numeric',
  584. hour12: true
  585. });
  586. // Get the current weekday
  587. const currentWeekday = getWeekday();
  588. // Get the user's timezone
  589. const currentTimezone = getUserTimezone();
  590. // Get the user's language
  591. const userLanguage = localStorage.getItem('locale') || 'en-US';
  592. // Replace {{CURRENT_DATETIME}} in the template with the formatted datetime
  593. template = template.replace('{{CURRENT_DATETIME}}', `${formattedDate} ${currentTime}`);
  594. // Replace {{CURRENT_DATE}} in the template with the formatted date
  595. template = template.replace('{{CURRENT_DATE}}', formattedDate);
  596. // Replace {{CURRENT_TIME}} in the template with the formatted time
  597. template = template.replace('{{CURRENT_TIME}}', currentTime);
  598. // Replace {{CURRENT_WEEKDAY}} in the template with the current weekday
  599. template = template.replace('{{CURRENT_WEEKDAY}}', currentWeekday);
  600. // Replace {{CURRENT_TIMEZONE}} in the template with the user's timezone
  601. template = template.replace('{{CURRENT_TIMEZONE}}', currentTimezone);
  602. // Replace {{USER_LANGUAGE}} in the template with the user's language
  603. template = template.replace('{{USER_LANGUAGE}}', userLanguage);
  604. if (user_name) {
  605. // Replace {{USER_NAME}} in the template with the user's name
  606. template = template.replace('{{USER_NAME}}', user_name);
  607. }
  608. if (user_location) {
  609. // Replace {{USER_LOCATION}} in the template with the current location
  610. template = template.replace('{{USER_LOCATION}}', user_location);
  611. }
  612. return template;
  613. };
  614. /**
  615. * This function is used to replace placeholders in a template string with the provided prompt.
  616. * The placeholders can be in the following formats:
  617. * - `{{prompt}}`: This will be replaced with the entire prompt.
  618. * - `{{prompt:start:<length>}}`: This will be replaced with the first <length> characters of the prompt.
  619. * - `{{prompt:end:<length>}}`: This will be replaced with the last <length> characters of the prompt.
  620. * - `{{prompt:middletruncate:<length>}}`: This will be replaced with the prompt truncated to <length> characters, with '...' in the middle.
  621. *
  622. * @param {string} template - The template string containing placeholders.
  623. * @param {string} prompt - The string to replace the placeholders with.
  624. * @returns {string} The template string with the placeholders replaced by the prompt.
  625. */
  626. export const titleGenerationTemplate = (template: string, prompt: string): string => {
  627. template = template.replace(
  628. /{{prompt}}|{{prompt:start:(\d+)}}|{{prompt:end:(\d+)}}|{{prompt:middletruncate:(\d+)}}/g,
  629. (match, startLength, endLength, middleLength) => {
  630. if (match === '{{prompt}}') {
  631. return prompt;
  632. } else if (match.startsWith('{{prompt:start:')) {
  633. return prompt.substring(0, startLength);
  634. } else if (match.startsWith('{{prompt:end:')) {
  635. return prompt.slice(-endLength);
  636. } else if (match.startsWith('{{prompt:middletruncate:')) {
  637. if (prompt.length <= middleLength) {
  638. return prompt;
  639. }
  640. const start = prompt.slice(0, Math.ceil(middleLength / 2));
  641. const end = prompt.slice(-Math.floor(middleLength / 2));
  642. return `${start}...${end}`;
  643. }
  644. return '';
  645. }
  646. );
  647. template = promptTemplate(template);
  648. return template;
  649. };
  650. export const approximateToHumanReadable = (nanoseconds: number) => {
  651. const seconds = Math.floor((nanoseconds / 1e9) % 60);
  652. const minutes = Math.floor((nanoseconds / 6e10) % 60);
  653. const hours = Math.floor((nanoseconds / 3.6e12) % 24);
  654. const results: string[] = [];
  655. if (seconds >= 0) {
  656. results.push(`${seconds}s`);
  657. }
  658. if (minutes > 0) {
  659. results.push(`${minutes}m`);
  660. }
  661. if (hours > 0) {
  662. results.push(`${hours}h`);
  663. }
  664. return results.reverse().join(' ');
  665. };
  666. export const getTimeRange = (timestamp) => {
  667. const now = new Date();
  668. const date = new Date(timestamp * 1000); // Convert Unix timestamp to milliseconds
  669. // Calculate the difference in milliseconds
  670. const diffTime = now.getTime() - date.getTime();
  671. const diffDays = diffTime / (1000 * 3600 * 24);
  672. const nowDate = now.getDate();
  673. const nowMonth = now.getMonth();
  674. const nowYear = now.getFullYear();
  675. const dateDate = date.getDate();
  676. const dateMonth = date.getMonth();
  677. const dateYear = date.getFullYear();
  678. if (nowYear === dateYear && nowMonth === dateMonth && nowDate === dateDate) {
  679. return 'Today';
  680. } else if (nowYear === dateYear && nowMonth === dateMonth && nowDate - dateDate === 1) {
  681. return 'Yesterday';
  682. } else if (diffDays <= 7) {
  683. return 'Previous 7 days';
  684. } else if (diffDays <= 30) {
  685. return 'Previous 30 days';
  686. } else if (nowYear === dateYear) {
  687. return date.toLocaleString('default', { month: 'long' });
  688. } else {
  689. return date.getFullYear().toString();
  690. }
  691. };
  692. /**
  693. * Extract frontmatter as a dictionary from the specified content string.
  694. * @param content {string} - The content string with potential frontmatter.
  695. * @returns {Object} - The extracted frontmatter as a dictionary.
  696. */
  697. export const extractFrontmatter = (content) => {
  698. const frontmatter = {};
  699. let frontmatterStarted = false;
  700. let frontmatterEnded = false;
  701. const frontmatterPattern = /^\s*([a-z_]+):\s*(.*)\s*$/i;
  702. // Split content into lines
  703. const lines = content.split('\n');
  704. // Check if the content starts with triple quotes
  705. if (lines[0].trim() !== '"""') {
  706. return {};
  707. }
  708. frontmatterStarted = true;
  709. for (let i = 1; i < lines.length; i++) {
  710. const line = lines[i];
  711. if (line.includes('"""')) {
  712. if (frontmatterStarted) {
  713. frontmatterEnded = true;
  714. break;
  715. }
  716. }
  717. if (frontmatterStarted && !frontmatterEnded) {
  718. const match = frontmatterPattern.exec(line);
  719. if (match) {
  720. const [, key, value] = match;
  721. frontmatter[key.trim()] = value.trim();
  722. }
  723. }
  724. }
  725. return frontmatter;
  726. };
  727. // Function to determine the best matching language
  728. export const bestMatchingLanguage = (supportedLanguages, preferredLanguages, defaultLocale) => {
  729. const languages = supportedLanguages.map((lang) => lang.code);
  730. const match = preferredLanguages
  731. .map((prefLang) => languages.find((lang) => lang.startsWith(prefLang)))
  732. .find(Boolean);
  733. return match || defaultLocale;
  734. };
  735. // Get the date in the format YYYY-MM-DD
  736. export const getFormattedDate = () => {
  737. const date = new Date();
  738. return date.toISOString().split('T')[0];
  739. };
  740. // Get the time in the format HH:MM:SS
  741. export const getFormattedTime = () => {
  742. const date = new Date();
  743. return date.toTimeString().split(' ')[0];
  744. };
  745. // Get the current date and time in the format YYYY-MM-DD HH:MM:SS
  746. export const getCurrentDateTime = () => {
  747. return `${getFormattedDate()} ${getFormattedTime()}`;
  748. };
  749. // Get the user's timezone
  750. export const getUserTimezone = () => {
  751. return Intl.DateTimeFormat().resolvedOptions().timeZone;
  752. };
  753. // Get the weekday
  754. export const getWeekday = () => {
  755. const date = new Date();
  756. const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  757. return weekdays[date.getDay()];
  758. };
  759. export const createMessagesList = (history, messageId) => {
  760. if (messageId === null) {
  761. return [];
  762. }
  763. const message = history.messages[messageId];
  764. if (message?.parentId) {
  765. return [...createMessagesList(history, message.parentId), message];
  766. } else {
  767. return [message];
  768. }
  769. };
  770. export const formatFileSize = (size) => {
  771. if (size == null) return 'Unknown size';
  772. if (typeof size !== 'number' || size < 0) return 'Invalid size';
  773. if (size === 0) return '0 B';
  774. const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  775. let unitIndex = 0;
  776. while (size >= 1024 && unitIndex < units.length - 1) {
  777. size /= 1024;
  778. unitIndex++;
  779. }
  780. return `${size.toFixed(1)} ${units[unitIndex]}`;
  781. };
  782. export const getLineCount = (text) => {
  783. console.log(typeof text);
  784. return text ? text.split('\n').length : 0;
  785. };