index.ts 22 KB

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