Spaces:
Running
Running
Download server/knowledge.js from AhmedMSLTI/Millie: direct link, hf CLI and curl.
- Browser
- Download file 4.23 kB
-
https://huggingface.co/spaces/AhmedMSLTI/Millie/resolve/main/server/knowledge.js
- Command line
-
hf download hf://spaces/AhmedMSLTI/Millie/server/knowledge.js
-
curl -L -o knowledge.js https://huggingface.co/spaces/AhmedMSLTI/Millie/resolve/main/server/knowledge.js
4.23 kB
| import { readFile } from 'node:fs/promises'; | |
| import { createSyntheticKnowledge, SYNTHETIC_ORIGIN } from './synthetic.js'; | |
| import { createInventoryKnowledge } from './inventory-data.js'; | |
| export const DATA_PATH = new URL('../data/site.json', import.meta.url); | |
| const stop = new Set('a an the is are of to for and do you i me what which can my your der die das ein eine und ist sind ich sie du wir mir was wie wo wann welche bitte habt haben gibt es bei mit von zu für in im am an den dem des on at it about please ag motors autohaus dealership'.split(' ')); | |
| const synonyms = { cars: ['fahrzeug', 'fahrzeuge', 'autos'], car: ['fahrzeug', 'auto'], vehicles: ['fahrzeug', 'fahrzeuge'], fahrzeuge: ['fahrzeug'], fahrzeug: ['fahrzeuge'], inventory: ['fahrzeug', 'fahrzeuge'], price: ['preis', 'kaufpreis'], prices: ['preis', 'kaufpreis'], hours: ['öffnungszeiten'], opening: ['öffnungszeiten'], location: ['adresse', 'standort', 'kontakt'], address: ['adresse', 'standort'], contact: ['kontakt'], phone: ['telefon'], financing: ['finanzierung'], warranty: ['garantie'], service: ['werkstatt', 'service'] }; | |
| export function terms(text) { | |
| return [...new Set(text.toLowerCase().normalize('NFKC').match(/[\p{L}\p{N}]+/gu) || [])].filter(t => t.length > 1 && !stop.has(t)); | |
| } | |
| export function validateKnowledge(data, siteUrl) { | |
| if (data?.mode === 'inventory') return createInventoryKnowledge(data); | |
| if (data?.version !== 1 || !Array.isArray(data.pages) || Number.isNaN(Date.parse(data.fetchedAt))) throw new Error('Invalid knowledge file'); | |
| const origin = data.mode === 'synthetic' ? SYNTHETIC_ORIGIN : new URL(siteUrl).origin; | |
| if (data.origin !== origin) throw new Error('Knowledge belongs to a different website'); | |
| for (const page of data.pages) { | |
| if (new URL(page.url).origin !== origin || typeof page.text !== 'string' || typeof page.title !== 'string') throw new Error('Untrusted knowledge source'); | |
| } | |
| return data; | |
| } | |
| export async function loadKnowledge(siteUrl, mode = process.env.KNOWLEDGE_MODE || 'synthetic', inventoryPath = process.env.INVENTORY_FILE || new URL('../data/inventory.json', import.meta.url)) { | |
| if (mode === 'synthetic') return validateKnowledge(createSyntheticKnowledge(), siteUrl); | |
| if (mode === 'inventory') { | |
| // A missing/invalid real import is a startup failure, never a silent switch | |
| // back to fictional vehicles or a different dealer's source. | |
| return createInventoryKnowledge(JSON.parse(await readFile(inventoryPath, 'utf8'))); | |
| } | |
| if (mode !== 'website') throw new Error('KNOWLEDGE_MODE must be synthetic, website or inventory'); | |
| try { return validateKnowledge(JSON.parse(await readFile(DATA_PATH, 'utf8')), siteUrl); } | |
| catch (error) { | |
| if (error.code === 'ENOENT') return { version: 1, origin: new URL(siteUrl).origin, fetchedAt: null, pages: [] }; | |
| throw error; | |
| } | |
| } | |
| export function createRetriever(data) { | |
| const chunks = data.pages.flatMap(page => { | |
| const sentences = page.text.split(/\n+/).map(s => s.trim()).filter(Boolean); | |
| const groups = []; | |
| let text = ''; | |
| for (const line of sentences) { | |
| if ((text + line).length > 1000 && text) { groups.push(text); text = ''; } | |
| // Bound chunks even when a page has an enormous single text node. | |
| for (let i = 0; i < line.length; i += 1000) { | |
| const part = line.slice(i, i + 1000); | |
| if (text && text.length + part.length > 1000) { groups.push(text); text = ''; } | |
| text += `${part}\n`; | |
| } | |
| } | |
| if (text) groups.push(text); | |
| return groups.map((text, index) => ({ id: `${page.id}:${index}`, title: page.title, url: page.url, text, tokens: terms(`${page.title} ${text}`) })); | |
| }); | |
| const frequency = new Map(); | |
| for (const c of chunks) for (const t of c.tokens) frequency.set(t, (frequency.get(t) || 0) + 1); | |
| return query => { | |
| const original = terms(query); | |
| const queryTerms = [...new Set(original.flatMap(t => [t, ...(synonyms[t] || [])]))]; | |
| return chunks.map(c => ({ ...c, score: queryTerms.reduce((sum, t) => sum + (c.tokens.includes(t) ? Math.log(1 + chunks.length / frequency.get(t)) : 0), 0) })) | |
| .filter(c => c.score > 0).sort((a, b) => b.score - a.score).slice(0, 4) | |
| .map(({ tokens, score, ...c }) => c); | |
| }; | |
| } | |