/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/extract/lexicon * * Tokenizer, synonym concepts and lexical similarity used to match schema * property names against DOM hints (class, id, itemprop, aria-label, labels, * table headers, JSON-LD paths). */ import { isHashedToken } from "./dom.ts"; import type { LeafField } from "./schema.ts"; /** A weighted token describing a DOM node or a structured-data path. */ export interface Feature { token: string; weight: number; } /** Weighted tokens of a schema leaf. `parent` tokens come from the enclosing object. */ export interface FieldTerms { tokens: Feature[]; parentTokens: Feature[]; concepts: Set; } const CONCEPT_WORDS: Record = { price: ["price", "cost", "amount", "prix", "preis", "precio", "tarif", "pricing", "msrp", "offer", "fee", "total"], title: ["title", "name", "heading", "headline", "titre", "nom", "caption", "subject", "hed", "titleline"], url: ["url", "link", "href", "permalink", "uri", "lien", "hit"], image: ["image", "img", "thumbnail", "thumb", "photo", "picture", "pic", "avatar", "cover", "poster", "logo", "src", "visual"], date: ["date", "time", "published", "updated", "posted", "created", "modified", "datetime", "timestamp", "age", "ago", "pubdate", "when", "publish", "update", "post-date"], author: ["author", "by", "byline", "writer", "user", "creator", "auteur", "submitter", "people", "profile", "contributor", "journalist", "reporter"], rating: ["rating", "stars", "star", "rated", "note", "grade", "score"], description: ["description", "summary", "excerpt", "desc", "dek", "teaser", "snippet", "abstract", "intro", "lede", "standfirst", "blurb", "body", "content"], sku: ["sku", "ref", "reference", "mpn", "gtin", "ean", "isbn", "identifier", "code", "id"], brand: ["brand", "manufacturer", "make", "vendor", "marque", "maker"], category: ["category", "section", "kicker", "topic", "genre", "rubrique", "department", "categorie", "eyebrow"], availability: ["availability", "stock", "instock", "available", "inventory", "disponibilite", "unavailable"], reviews: ["reviews", "review", "reviewcount", "count", "votes", "opinions", "avis", "ratings"], comments: ["comments", "comment", "replies", "reply", "discuss", "discussion"], points: ["points", "point", "score", "votes", "karma", "upvotes", "likes"], location: ["location", "city", "place", "address", "where", "lieu", "ville", "region", "locality", "remote"], company: ["company", "employer", "organization", "organisation", "org", "hiring", "entreprise", "societe", "firm"], salary: ["salary", "pay", "compensation", "wage", "salaire", "remuneration"], contract: ["contract", "employment", "jobtype", "schedule", "contrat"], currency: ["currency", "pricecurrency", "devise"], tags: ["tags", "tag", "keywords", "keyword", "labels", "topics"], site: ["site", "domain", "host", "source", "sitestr", "website", "sitebit"], rank: ["rank", "position", "ranking"], change: ["change", "delta", "variation", "diff"], rate: ["rate", "quote", "fx"], email: ["email", "mail", "courriel"], phone: ["phone", "tel", "telephone", "mobile"], }; export function stem(token: string): string { if (token.length > 4 && token.endsWith("ies")) return `${token.slice(0, -3)}y`; if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss") && !token.endsWith("us")) return token.slice(0, -1); return token; } const TOKEN_CONCEPTS = new Map>(); for (const [concept, words] of Object.entries(CONCEPT_WORDS)) { for (const word of words) { const token = stem(word); const set = TOKEN_CONCEPTS.get(token) ?? new Set(); set.add(concept); TOKEN_CONCEPTS.set(token, set); } } const STOP_WORDS: ReadonlySet = new Set(["the", "a", "an", "of", "and", "or", "to", "for", "with", "on", "at", "le", "la", "les", "de", "du", "des", "et"]); /** Split camelCase / snake_case / kebab-case / BEM strings into stemmed lowercase tokens. */ export function tokenize(text: string): string[] { if (!text) return []; const out: string[] = []; const spaced = text .replace(/([a-z0-9])([A-Z])/g, "$1 $2") .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") .normalize("NFD") .replace(/[̀-ͯ]/g, "") .toLowerCase(); for (const raw of spaced.split(/[^a-z0-9]+/)) { if (!raw || raw.length > 30 || /^\d+$/.test(raw) || STOP_WORDS.has(raw) || isHashedToken(raw)) continue; out.push(stem(raw)); } return out; } export function conceptsOf(token: string): ReadonlySet { return TOKEN_CONCEPTS.get(token) ?? EMPTY; } const EMPTY: ReadonlySet = new Set(); export function features(text: string | undefined, weight: number): Feature[] { return text ? tokenize(text).map((token) => ({ token, weight })) : []; } export function fieldTerms(leaf: LeafField): FieldTerms { const tokens = features(leaf.spec.name, 1); for (const f of features(leaf.spec.description, 0.5)) tokens.push(f); const parentTokens = leaf.parent ? features(leaf.parent.name, 0.8) : []; const concepts = new Set(); for (const f of features(leaf.spec.name, 1)) for (const c of conceptsOf(f.token)) concepts.add(c); if (concepts.size === 0) { for (const f of features(leaf.spec.description, 1)) for (const c of conceptsOf(f.token)) concepts.add(c); } if (leaf.spec.format === "uri" && concepts.size === 0) concepts.add("url"); if ((leaf.spec.format === "date" || leaf.spec.format === "date-time") && concepts.size === 0) concepts.add("date"); return { tokens, parentTokens, concepts }; } function tokenMatch(a: string, b: string): number { if (a === b) return 1; const ca = conceptsOf(a); if (ca.size > 0) { const cb = conceptsOf(b); for (const c of ca) if (cb.has(c)) return 0.8; } const [short, long] = a.length <= b.length ? [a, b] : [b, a]; if (short.length >= 4 && long.startsWith(short)) return 0.7; return 0; } function bestMatch(term: Feature, nodeFeatures: readonly Feature[]): number { let best = 0; for (const f of nodeFeatures) { const score = f.weight * tokenMatch(term.token, f.token); if (score > best) best = score; } return best; } /** * Lexical similarity in [0, 1] between a schema leaf and node features: a mix * of the strongest single match and the weighted share of matched field tokens. * Nested leaves are damped when nothing matches the parent object name. */ export function lexicalScore(terms: FieldTerms, nodeFeatures: readonly Feature[]): number { if (nodeFeatures.length === 0 || terms.tokens.length === 0) return 0; let max = 0; let sum = 0; let weights = 0; for (const term of terms.tokens) { const m = bestMatch(term, nodeFeatures) * term.weight; if (m > max) max = m; sum += m; weights += term.weight; } let score = 0.65 * max + 0.35 * (sum / weights); if (terms.parentTokens.length > 0) { let parent = 0; for (const term of terms.parentTokens) parent = Math.max(parent, bestMatch(term, nodeFeatures)); score = score * (0.5 + 0.5 * Math.min(1, parent / 0.8)) + 0.15 * parent; } return Math.min(1, score); }