index.ts 27 KB

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