diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..b57f642b441f43c1712dfd708e79965f117c4f2e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,35 +1 @@ -*.7z filter=lfs diff=lfs merge=lfs -text -*.arrow filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.bz2 filter=lfs diff=lfs merge=lfs -text -*.ckpt filter=lfs diff=lfs merge=lfs -text -*.ftz filter=lfs diff=lfs merge=lfs -text -*.gz filter=lfs diff=lfs merge=lfs -text -*.h5 filter=lfs diff=lfs merge=lfs -text -*.joblib filter=lfs diff=lfs merge=lfs -text -*.lfs.* filter=lfs diff=lfs merge=lfs -text -*.mlmodel filter=lfs diff=lfs merge=lfs -text -*.model filter=lfs diff=lfs merge=lfs -text -*.msgpack filter=lfs diff=lfs merge=lfs -text -*.npy filter=lfs diff=lfs merge=lfs -text -*.npz filter=lfs diff=lfs merge=lfs -text -*.onnx filter=lfs diff=lfs merge=lfs -text -*.ot filter=lfs diff=lfs merge=lfs -text *.parquet filter=lfs diff=lfs merge=lfs -text -*.pb filter=lfs diff=lfs merge=lfs -text -*.pickle filter=lfs diff=lfs merge=lfs -text -*.pkl filter=lfs diff=lfs merge=lfs -text -*.pt filter=lfs diff=lfs merge=lfs -text -*.pth filter=lfs diff=lfs merge=lfs -text -*.rar filter=lfs diff=lfs merge=lfs -text -*.safetensors filter=lfs diff=lfs merge=lfs -text -saved_model/**/* filter=lfs diff=lfs merge=lfs -text -*.tar.* filter=lfs diff=lfs merge=lfs -text -*.tar filter=lfs diff=lfs merge=lfs -text -*.tflite filter=lfs diff=lfs merge=lfs -text -*.tgz filter=lfs diff=lfs merge=lfs -text -*.wasm filter=lfs diff=lfs merge=lfs -text -*.xz filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.zst filter=lfs diff=lfs merge=lfs -text -*tfevents* filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2ebf311eee4972e67b7cfc62859e2d4cc760b95b --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +--- +license: mit +language: + - fr +pipeline_tag: text-classification +tags: + - patents + - ipc + - classification + - embeddings + - reranking + - text2ipc +base_model: + - intfloat/multilingual-e5-base + - BAAI/bge-reranker-v2-m3 +base_model_relation: merge +--- + +# text2ipc 0.2.2: IPC 20260101 (FR) via intfloat/multilingual-e5-base + +Both models above are listed as base models so that they show in the model tree +(the Hub only has "merge" as a relation for two models): the index in this +repository derives from the first, and the second is downloaded and called at run +time when reranking is on. No weights are merged. + +Maps free text (a patent abstract, a title, or a whole description) to ranked +International Patent Classification symbols. Every IPC entry is embedded once from its +full ancestor path (section > class > subclass > group > subgroups); a query is +embedded by paragraph (title and abstract separately, averaged), a paragraph over the +embedder's limit is cut into sentence chunks, and the entries are ranked by cosine +similarity, walking the hierarchy to answer at the level asked. An optional second +stage, the **reranker**, re-judges the best candidates with a cross-encoder. + +This repository is a **custom Inference Endpoints handler** (`handler.py`). Deploy it as +an Inference Endpoint and call: + +```json +{"inputs": "enxada manual com duas lâminas para capina", + "parameters": {"level": "group", "top_k": 5, "rerank": true}} +``` + +`inputs` is a string or a list of strings (one result list each). Parameters: + +| parameter | values | default | meaning | +|---|---|---|---| +| `level` | section, class, subclass, group, subgroup, auto | subgroup | where in the hierarchy to answer; `auto` descends while the evidence supports it | +| `top_k` | integer | 10 | results per input (distinct branches, so possibly fewer) | +| `rerank` | true, false, or a spec such as `ce:BAAI/bge-reranker-v2-m3` | false | second stage: judge the candidates with a cross-encoder | +| `candidates` | integer | max(5 × top_k, 25) | how many first-stage entries the reranker judges | +| `fusion` | blend, judge, product | blend | `blend` is `cosine × (0.5 + 0.5 × sigmoid(logit))` | +| `chunking` | mean, max, truncate | mean | how the paragraphs and chunks of a long text combine | +| `gap` | float | none | drop results more than this below the best first-stage score | +| `auto_margin` | float | 0.02 | `auto` level: keep descending while a child is within this of its parent | +| `normalize` | true, false | true | collapse whitespace and lower-case shouting paragraphs | + +The response is a list of `{symbol, canonical, level, depth, score, similarity, judge, +title, path}`: `similarity` is the cosine, `score` the value the list is ordered by, +`judge` the reranker's verdict in 0..1 (null without `rerank`), `path` the full +section-to-entry text. + +**Reranker.** `rerank: true` loads `BAAI/bge-reranker-v2-m3` (568M parameters, Apache-2.0, +about 2.2 GB) on first use and judges each (text, path text) pair; on 991 INPI +applications it lifts subclass@1 from 23.6% to 31.6% and group@1 from 11.2% to +16.6%, for well under a second per input on a GPU. Size the endpoint for the extra +model when you enable it. + +## Use it locally + +```bash +pip install "text2ipc[st] @ git+https://github.com/Jaimenms/text2ipc" +t2ipc download jaimenms/text2ipc-fr # or --revision v0.2.2 to pin this edition +t2ipc classify "Aparelho para combate a incêndios com mangueira flexível" --lang FR --level group +t2ipc classify "..." --lang FR --level group --rerank +``` + +```python +from text2ipc import IpcClassifier +clf = IpcClassifier("20260101", lang="FR") +for m in clf.classify("...", level="group", top_k=5, rerank=True): + print(m.pretty, round(m.score, 3), m.judge, m.text) +``` + +## Versions + +Every publication of this repository is tagged `v` (`v0.2.0`, +`v0.2.0-2`, ...), so `t2ipc download jaimenms/text2ipc-fr --revision ` and the Hub's +`revision` parameter pin an edition. The IPC version of the index is in the file +names and in `text2ipc.json`; the package code vendored under `text2ipc/` is the one +the handler runs. Changes per version: `CHANGELOG.md` in the GitHub repository. + +Contents: `scheme/` (titles and hierarchy), `index/` (vectors, parquet), `text2ipc/` +(the package, vendored), `text2ipc.json` (which index to serve), `handler.py`. + +Data: IPC scheme master files by WIPO. Embedder: `intfloat/multilingual-e5-base` from the +Hub. Method, evaluation protocol and every measurement: +https://github.com/Jaimenms/text2ipc (`docs/methodology.md`, `docs/evals.md`). +A browser demo that needs no server runs at https://huggingface.co/spaces/jaimenms/text2ipc. diff --git a/handler.py b/handler.py new file mode 100644 index 0000000000000000000000000000000000000000..68ef1956da789a0dbc4617c44fee74ebb635bae5 --- /dev/null +++ b/handler.py @@ -0,0 +1,68 @@ +"""Hugging Face Inference Endpoints handler: text in, ranked IPC symbols out. + +Copied to the root of the model repository by ``t2ipc hf-export``. The repository +also carries ``scheme/`` and ``index/`` (parquet), ``text2ipc.json`` (which index to +serve) and a copy of the ``text2ipc`` package, so no PyPI release is required. + +Request:: + + {"inputs": "enxada manual com duas lâminas", + "parameters": {"level": "group", "top_k": 5}} + +Response (one list per input; a single string yields a single list):: + + [{"symbol": "A01B 1/10", "canonical": "A01B0001100000", "level": "subgroup", + "score": 0.83, "similarity": 0.81, "title": "...", "path": "..."}, ...] +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any + +ALLOWED_PARAMS = { + "level", "top_k", "gap", "auto_margin", "normalize", "chunking", "rerank", "candidates", "fusion" +} + + +class EndpointHandler: + def __init__(self, path: str = ""): + root = Path(path or ".").resolve() + if str(root) not in sys.path: + sys.path.insert(0, str(root)) # vendored text2ipc package + from text2ipc.classifier import IpcClassifier + + cfg = json.loads((root / "text2ipc.json").read_text()) + self.clf = IpcClassifier( + cfg["version"], + lang=cfg["lang"], + model=cfg.get("embedder") or cfg["model"], + root=root, + ) + _ = self.clf.index # load eagerly so the first request is fast + _ = self.clf.embedder + + def __call__(self, data: dict[str, Any]) -> list[dict] | list[list[dict]]: + inputs = data.get("inputs", "") + params = {k: v for k, v in (data.get("parameters") or {}).items() if k in ALLOWED_PARAMS} + if isinstance(inputs, str): + return self._one(inputs, params) + return [self._one(text, params) for text in inputs] + + def _one(self, text: str, params: dict[str, Any]) -> list[dict]: + return [ + { + "symbol": m.pretty, + "canonical": m.symbol, + "level": m.level, + "depth": m.depth, + "score": round(m.score, 4), + "similarity": round(m.similarity, 4), + "judge": None if m.judge is None else round(m.judge, 4), + "title": m.title, + "path": m.text, + } + for m in self.clf.classify(text, **params) + ] diff --git a/index/ipc_20260101_fr_st-intfloat-multilingual-e5-base.parquet b/index/ipc_20260101_fr_st-intfloat-multilingual-e5-base.parquet new file mode 100644 index 0000000000000000000000000000000000000000..cfa49405a292d8482de94cc60bd6f0bfc9c06c2f --- /dev/null +++ b/index/ipc_20260101_fr_st-intfloat-multilingual-e5-base.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a893be5c0183e3a9cf2c54ccbc561ad9dc8e6ee5fff716fb7f5f4b5581751b99 +size 341388135 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..0378eed50d71a3ad78c06a7679b53911ef482558 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +numpy>=1.26 +httpx>=0.27 +typer>=0.12 +rich>=13.7 +sentence-transformers>=3.0 diff --git a/scheme/ipc_20260101_fr.parquet b/scheme/ipc_20260101_fr.parquet new file mode 100644 index 0000000000000000000000000000000000000000..6a0d95bec64c38714a67e374c395b8c80c8375c6 --- /dev/null +++ b/scheme/ipc_20260101_fr.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:948ce492c471ba17281c093e92145673988bf143a56aa4829a9793203775189f +size 2497665 diff --git a/text2ipc.json b/text2ipc.json new file mode 100644 index 0000000000000000000000000000000000000000..ae722ba6119afacb861a285ec2e8e80425741a4f --- /dev/null +++ b/text2ipc.json @@ -0,0 +1,5 @@ +{ + "version": "20260101", + "lang": "FR", + "model": "st:intfloat/multilingual-e5-base" +} \ No newline at end of file diff --git a/text2ipc/__init__.py b/text2ipc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d558b7e08bddbe8cc42d3429d4c9a3e32e6d884a --- /dev/null +++ b/text2ipc/__init__.py @@ -0,0 +1,13 @@ +"""text2ipc - map free text to IPC symbols with embeddings and hierarchical heuristics. + +>>> from text2ipc import classify +>>> for m in classify("A hand-held hoe with two blades", version="20260101", level="group"): +... print(m.pretty, round(m.score, 3), m.title) +""" + +from .classifier import IpcClassifier, classify +from .config import LEVELS +from .search import Beam, Match, SearchParams, Weights + +__all__ = ["LEVELS", "Beam", "IpcClassifier", "Match", "SearchParams", "Weights", "classify"] +__version__ = "0.2.2" diff --git a/text2ipc/chunking.py b/text2ipc/chunking.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c399fb02eb9afca6ac9febc90dc7f5e679b20b --- /dev/null +++ b/text2ipc/chunking.py @@ -0,0 +1,78 @@ +"""Split a long text into pieces an embedder can take whole. + +Embedders have a token limit (512 for the e5 family) beyond which they truncate +silently, so a full patent description would be judged by its first page. Instead +the text is cut at paragraph and sentence ends into chunks that fit, each chunk is +embedded as a query, and the chunk vectors are combined (``IpcClassifier.embed_text``). +""" + +from __future__ import annotations + +import re +from collections.abc import Callable + +_PARAGRAPH = re.compile(r"\n\s*\n") +_SENTENCE = re.compile(r"(?<=[.!?;:])\s+(?=\S)") + + +def split_text( + text: str, + max_tokens: int | None, + count_tokens: Callable[[str], int], + *, + overlap: int = 1, +) -> list[str]: + """One chunk per paragraph, cut further into sentence chunks of at most + ``max_tokens`` tokens when a paragraph is too long. + + Paragraphs are separated by a blank line and never merged: a title above an + abstract gives two chunks. Within a paragraph, cuts happen at sentence ends, + except for a single sentence over the limit, which is cut by words. ``overlap`` + repeats that many trailing sentences of a chunk at the start of the next. + ``count_tokens`` must count a text the way the embedder will see it (prefix and + special tokens included); ``max_tokens=None`` means no limit. + """ + out: list[str] = [] + for paragraph in _PARAGRAPH.split(text): + if paragraph.strip(): + out.extend(_pack(paragraph.strip(), max_tokens, count_tokens, overlap)) + return out + + +def _pack( + paragraph: str, max_tokens: int | None, count_tokens: Callable[[str], int], overlap: int +) -> list[str]: + if max_tokens is None: + return [" ".join(paragraph.split())] + units = [s.strip() for s in _SENTENCE.split(paragraph) if s.strip()] + units = [u for unit in units for u in _cut_by_words(unit, max_tokens, count_tokens)] + chunks: list[list[str]] = [] + current: list[str] = [] + for unit in units: + if current and count_tokens(" ".join([*current, unit])) > max_tokens: + chunks.append(current) + carry = current[-overlap:] if overlap > 0 else [] + current = [*carry, unit] + while len(current) > 1 and count_tokens(" ".join(current)) > max_tokens: + current = current[1:] + else: + current.append(unit) + if current: + chunks.append(current) + return [" ".join(c) for c in chunks] + + +def _cut_by_words(unit: str, max_tokens: int, count_tokens: Callable[[str], int]) -> list[str]: + if count_tokens(unit) <= max_tokens: + return [unit] + out: list[str] = [] + words = unit.split() + piece: list[str] = [] + for w in words: + if piece and count_tokens(" ".join([*piece, w])) > max_tokens: + out.append(" ".join(piece)) + piece = [] + piece.append(w) + if piece: + out.append(" ".join(piece)) + return out diff --git a/text2ipc/classifier.py b/text2ipc/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..5c497c4628c67e88f8be01419f744551671b8953 --- /dev/null +++ b/text2ipc/classifier.py @@ -0,0 +1,219 @@ +"""The simple interface: version + level + text -> ranked IPC symbols.""" + +from __future__ import annotations + +import dataclasses +import datetime as dt +from functools import lru_cache +from pathlib import Path + +import numpy as np + +from .chunking import split_text +from .config import DEFAULT_RERANKER, LEVELS, default_model, home +from .embeddings import Embedder, get_embedder, model_slug +from .embeddings.base import normalize +from .index import IpcIndex, available_indexes, scheme_table_path +from .rerank import Reranker, fuse, get_reranker, sigmoid +from .search import Beam, Match, SearchParams, Weights, search +from .textnorm import collapse_whitespace, lowercase_if_shouting + + +class IpcClassifier: + """Loads one built index and answers queries against it. + + Construction is cheap; the index, its scheme table and the embedding model load on + first use. + """ + + def __init__( + self, + version: str = "latest", + *, + lang: str = "EN", + model: str | Embedder | None = None, + root: Path | None = None, + ): + self.root = root or home() + self.lang = lang.upper() + self._model_spec = model or default_model() + self.version = resolve_built_version(version, self.lang, self._model_name, self.root) + self._index: IpcIndex | None = None + self._embedder: Embedder | None = None + self._rerankers: dict[str, Reranker] = {} + #: How many chunks the last ``embed_text`` call used (1 when the text fit). + self.last_chunks = 1 + + @property + def _model_name(self) -> str: + return self._model_spec if isinstance(self._model_spec, str) else self._model_spec.name + + @property + def index(self) -> IpcIndex: + if self._index is None: + path = _index_for(self.version, self.lang, self._model_name, self.root) + self._index = IpcIndex.read(path, scheme_table_path(self.version, self.lang, self.root)) + return self._index + + @property + def embedder(self) -> Embedder: + if self._embedder is None: + self._embedder = get_embedder(self._model_spec) + if self._embedder.name != self.index.meta.model: + raise ValueError( + f"Index built with {self.index.meta.model}, embedder is {self._embedder.name}" + ) + return self._embedder + + def classify( + self, + text: str, + level: str = "subgroup", + top_k: int = 10, + *, + gap: float | None = None, + weights: Weights | None = None, + beam: Beam | None = None, + auto_margin: float = 0.02, + normalize: bool = True, + chunking: str = "mean", + rerank: bool | str | Reranker = False, + candidates: int | None = None, + fusion: str = "blend", + ) -> list[Match]: + """Rank IPC entries for a text of any length. + + ``rerank`` adds a second stage: the first stage keeps ``candidates`` entries + (default ``max(5 * top_k, 25)``), a cross-encoder (``True`` for the default + model, or a spec such as ``ce:BAAI/bge-reranker-v2-m3``) judges each one + against the text, and ``fusion`` combines the two scores (``blend``, + ``judge`` or ``product``, see ``rerank.fuse``). ``gap`` applies to the first + stage. Each match then carries its ``judge`` verdict in 0..1. + + Paragraphs (blank-line separated, e.g. a title above an abstract) are embedded + separately, and a paragraph over the embedder's limit is cut into sentence + chunks. ``chunking`` says how the pieces combine: ``"mean"`` searches with + their unit-length mean, ``"max"`` searches with every vector and scores an + entry by its best piece, ``"truncate"`` embeds the text whole and lets the + embedder cut it (the old behaviour). + """ + if normalize: + text = normalize_query(text) + n_first = top_k if not rerank else (candidates or max(5 * top_k, 25)) + params = SearchParams( + level=level, + top_k=n_first, + gap=gap, + weights=weights or Weights(), + beam=beam or Beam(), + auto_margin=auto_margin, + ) + matches = search(self.index, self.embed_text(text, chunking=chunking), params) + if not rerank or not matches: + return matches[:top_k] + reranker = self.reranker(rerank) + logits = reranker.score(text, [m.text for m in matches]) + fused = fuse(np.array([m.score for m in matches]), logits, fusion) + verdict = sigmoid(logits) + order = np.argsort(-fused, kind="stable")[:top_k] + return [ + dataclasses.replace(matches[i], score=float(fused[i]), judge=float(verdict[i])) + for i in order + ] + + def reranker(self, spec: bool | str | Reranker = True) -> Reranker: + """The reranker for a spec (``True`` means the default), loaded once.""" + if spec is True: + spec = DEFAULT_RERANKER + if not isinstance(spec, str): + return spec + if spec not in self._rerankers: + self._rerankers[spec] = get_reranker(spec) + return self._rerankers[spec] + + def embed_text(self, text: str, *, chunking: str = "mean") -> np.ndarray: + """Query vector for a text of any length; a ``(chunks, dim)`` stack for ``"max"``. + + Sets ``last_chunks``. A single paragraph within the token limit is embedded + whole. + """ + if chunking not in ("mean", "max", "truncate"): + raise ValueError("chunking must be 'mean', 'max' or 'truncate'") + embedder = self.embedder + chunks = ( + [text] + if chunking == "truncate" + else split_text(text, embedder.max_tokens, embedder.count_tokens) + ) + self.last_chunks = len(chunks) + if len(chunks) == 1: + return embedder.embed_query(text) + vectors = embedder.embed_queries(chunks) + if chunking == "max": + return vectors + return normalize(vectors.mean(axis=0))[0] + + +def normalize_query(text: str) -> str: + """Collapse whitespace and lower-case text that is mostly upper case, paragraph by + paragraph, keeping blank lines as paragraph breaks. + + Patent titles are printed in capitals; the tokenizers of multilingual models + handle them badly (subclass hit@10 on RPI titles went from 25% to 35% by + lower-casing). Mixed-case abstracts are left alone. Per paragraph, so that a + shouting title above a mixed-case abstract is still lower-cased. + """ + return "\n\n".join(lowercase_if_shouting(p) for p in collapse_whitespace(text).split("\n\n")) + + +def classify( + text: str, + version: str = "latest", + level: str = "subgroup", + top_k: int = 10, + *, + lang: str = "EN", + model: str | None = None, + root: Path | None = None, + **kwargs, +) -> list[Match]: + """One-call form. Classifiers are cached per (version, lang, model).""" + if level not in (*LEVELS, "auto"): + raise ValueError(f"level must be one of {LEVELS} or 'auto'") + clf = _cached(version, lang.upper(), model or default_model(), str(root) if root else None) + return clf.classify(text, level=level, top_k=top_k, **kwargs) + + +@lru_cache(maxsize=8) +def _cached(version: str, lang: str, model: str, root: str | None) -> IpcClassifier: + return IpcClassifier(version, lang=lang, model=model, root=Path(root) if root else None) + + +def resolve_built_version(spec: str, lang: str, model: str, root: Path) -> str: + """Resolve ``latest`` / ``current`` against indexes already built for lang+model.""" + if spec.isdigit() and len(spec) == 8: + return spec + slug = model_slug(model) + versions = sorted( + r.version for r in available_indexes(root) if r.lang == lang and r.model_slug == slug + ) + if spec == "current": + today = dt.date.today().strftime("%Y%m%d") + versions = [v for v in versions if v <= today] + if not versions: + raise FileNotFoundError( + f"No index built for lang={lang} model={model} under {root}. " + "Run: t2ipc build --version (or t2ipc download)" + ) + return versions[-1] + + +def _index_for(version: str, lang: str, model: str, root: Path) -> Path: + slug = model_slug(model) + for r in available_indexes(root): + if r.version == version and r.lang == lang and r.model_slug == slug: + return r.path + raise FileNotFoundError( + f"No index for version={version} lang={lang} model={model} under {root}. " + f"Run: t2ipc build --version {version} --lang {lang} --model {model}" + ) diff --git a/text2ipc/cli.py b/text2ipc/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1e104fe2a2b80822b580c08920396f99fdfe4140 --- /dev/null +++ b/text2ipc/cli.py @@ -0,0 +1,400 @@ +"""``t2ipc`` command line.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import typer +from rich.console import Console +from rich.table import Table + +from .config import ( + DEFAULT_HF_REPO, + DEFAULT_RERANKER, + LEVELS, + OVERLAY_LANGS, + WIPO_LANGS, + default_model, + home, +) +from .embeddings import get_embedder +from .index import ( + IpcIndex, + available_indexes, + build_index, + find_previous_index, + index_path, + scheme_table_path, +) +from .scheme import ( + SchemeTable, + apply_titles, + fetch_scheme, + format_symbol, + load_titles_csv, + parse_scheme, +) +from .versions import list_local_versions, list_remote_versions, resolve_version +from .web.export import WEB_DEFAULT_MODEL, WEB_DEFAULT_RERANKER + +app = typer.Typer(help="Map free text to IPC symbols.", no_args_is_help=True) +console = Console() + + +@app.command() +def versions(remote: bool = typer.Option(True, help="Query wipo.int; --no-remote lists local")): + """List IPC versions, newest last.""" + for v in list_remote_versions() if remote else list_local_versions(): + console.print(v) + + +@app.command() +def indexes(): + """List indexes built under the text2ipc home.""" + table = Table("version", "lang", "model", "rows", "MB", "path") + for ref in available_indexes(): + meta = IpcIndex.read_meta(ref.path) + table.add_row( + ref.version, + ref.lang, + meta.model, + str(meta.rows), + f"{ref.path.stat().st_size / 1e6:.0f}", + str(ref.path), + ) + console.print(table) + console.print(f"home: {home()}") + + +@app.command() +def build( + version: str = typer.Option( + "latest", help="YYYYMMDD, 'latest' (newest published) or 'current' (in force)" + ), + lang: str = typer.Option( + "EN", help="Scheme language: EN or FR (WIPO master files), PT (INPI translation)" + ), + model: str = typer.Option(None, help="Embedder spec, e.g. st:intfloat/multilingual-e5-base"), + previous: str = typer.Option( + "auto", help="'auto': newest older index for the same lang+model; 'none'; or a path" + ), + titles_csv: Path = typer.Option(None, help="symbol,title CSV overriding entry titles"), + out: Path = typer.Option(None, help="Output parquet; default is under the text2ipc home"), + batch_size: int = typer.Option(256), + force_download: bool = typer.Option(False, help="Re-download the WIPO zip / INPI titles"), +): + """Download the WIPO scheme for a version, write the scheme table and the index.""" + model = model or default_model() + version = resolve_version(version) + lang = lang.upper() + scheme, overlay = _prepare_scheme(version, lang, titles_csv, force_download) + + prev: tuple[Path, Path] | None = None + found = None + if previous == "auto": + found = find_previous_index(version, lang, model) + elif previous != "none": + found = Path(previous) + if found is not None: + prev = (found, scheme_table_path(IpcIndex.read_meta(found).version, lang)) + console.print(f"reusing vectors from {found.name}") + + embedder = get_embedder(model) + with console.status("embedding...") as status: + index, report = build_index( + scheme, + embedder, + version=version, + lang=lang, + previous=prev, + titles_overlay=overlay, + batch_size=batch_size, + progress=lambda done, total: status.update(f"embedding {done}/{total}"), + ) + target = out or index_path(version, lang, model) + index.write(target) + console.print(report.summary()) + console.print(f"wrote {target}") + + +def _prepare_scheme( + version: str, lang: str, titles_csv: Path | None, force: bool +) -> tuple[SchemeTable, str | None]: + """Parse the WIPO XML (plus a title overlay for PT), write and return the scheme table.""" + if lang in WIPO_LANGS: + xml_path = fetch_scheme(version, lang, force=force) + elif lang in OVERLAY_LANGS: + xml_path = fetch_scheme(version, "EN", force=force) + else: + raise typer.BadParameter(f"lang must be one of {WIPO_LANGS + tuple(OVERLAY_LANGS)}") + nodes = parse_scheme(xml_path) + overlay = None + if titles_csv is not None: + nodes = apply_titles(nodes, load_titles_csv(titles_csv)) + overlay = str(titles_csv) + elif lang in OVERLAY_LANGS: + from .scheme import fetch_inpi_titles + + with console.status("fetching Portuguese titles from INPI...") as status: + titles = fetch_inpi_titles( + version, + force=force, + progress=lambda i, n: status.update(f"INPI titles: subclass {i}/{n}"), + ) + nodes = apply_titles(nodes, titles) + overlay = f"{OVERLAY_LANGS[lang]}:{lang.lower()}" + console.print(f"{len(titles)} Portuguese titles applied") + scheme = SchemeTable.from_nodes(nodes) + target = scheme_table_path(version, lang) + scheme.write(target) + console.print( + f"[bold]{version} {lang}[/]: {len(scheme)} entries from {xml_path.name} -> {target.name}" + ) + return scheme, overlay + + +@app.command("scheme") +def scheme_cmd( + version: str = typer.Option("latest", help="YYYYMMDD, 'latest' or 'current'"), + lang: str = typer.Option("EN", help="EN, FR (WIPO) or PT (INPI titles)"), + titles_csv: Path = typer.Option(None, help="symbol,title CSV overriding entry titles"), + force_download: bool = typer.Option(False), +): + """Write only the scheme table (titles + hierarchy) for a version and language.""" + version = resolve_version(version) + _prepare_scheme(version, lang.upper(), titles_csv, force_download) + + +@app.command() +def classify( + text: str = typer.Argument(..., help="Abstract or any free text; use '-' to read stdin"), + version: str = typer.Option( + "latest", help="YYYYMMDD, 'latest' or 'current' among built indexes" + ), + level: str = typer.Option("subgroup", help=f"{', '.join(LEVELS)} or auto"), + top_k: int = typer.Option(10), + lang: str = typer.Option("EN"), + model: str = typer.Option(None), + gap: float = typer.Option(None, help="Drop results more than this below the best score"), + chunking: str = typer.Option( + "mean", help="Long texts: 'mean' of chunk vectors, 'max' over chunks, or 'truncate'" + ), + rerank: bool = typer.Option(False, help="Second stage: cross-encoder over the candidates"), + reranker: str = typer.Option(None, help=f"Reranker spec (default {DEFAULT_RERANKER})"), + candidates: int = typer.Option(None, help="First-stage list the reranker judges"), + as_json: bool = typer.Option(False, "--json"), +): + """Rank IPC symbols for a text of any length (a whole description is chunked).""" + from .classifier import IpcClassifier + + if text == "-": + text = sys.stdin.read() + clf = IpcClassifier(version, lang=lang, model=model) + matches = clf.classify( + text, + level=level, + top_k=top_k, + gap=gap, + chunking=chunking, + rerank=reranker or rerank, + candidates=candidates, + ) + if as_json: + print(json.dumps([m.__dict__ | {"pretty": m.pretty} for m in matches], indent=2)) + return + reranked = rerank or reranker + columns = ( + "#", + "symbol", + "score", + "sim", + *(("judge",) if reranked else ()), + "section > ... > entry", + ) + chunks = f", {clf.last_chunks} chunks" if clf.last_chunks > 1 else "" + table = Table(*columns, title=f"IPC {clf.version} {clf.lang}{chunks}") + for i, m in enumerate(matches, 1): + judge = (f"{m.judge:.2f}",) if reranked else () + table.add_row(str(i), m.pretty, f"{m.score:.3f}", f"{m.similarity:.3f}", *judge, m.text) + console.print(table) + + +@app.command() +def show( + symbol: str = typer.Argument(..., help="e.g. 'A01B 1/02' or A01B0001020000"), + version: str = typer.Option("latest"), + lang: str = typer.Option("EN"), + model: str = typer.Option(None), +): + """Print the symbol path and the full text an entry was embedded with.""" + from .classifier import IpcClassifier + from .scheme import normalize_symbol + + clf = IpcClassifier(version, lang=lang, model=model) + node = clf.index.node(normalize_symbol(symbol)) + console.print(f"[bold]{format_symbol(node.symbol)}[/] ({node.level}, depth {node.depth})") + console.print(" | ".join(format_symbol(s) for s in clf.index.scheme.path_of(node.symbol))) + console.print(clf.index.text_of(node.symbol)) + + +@app.command("rpi") +def rpi_cases( + issue: int = typer.Argument(..., help="RPI issue number, e.g. 2905"), + out: Path = typer.Option(None, help="JSONL path; default evals/rpi_.jsonl"), + require_abstract: bool = typer.Option(False, help="Skip records without INID 57"), +): + """Download an RPI issue and extract eval cases from dispatches 1.3 and 3.1.""" + from .eval import cases_from_rpi, fetch_rpi, parse_rpi, save_cases + + records = parse_rpi(fetch_rpi(issue)) + cases = cases_from_rpi(records, require_abstract=require_abstract) + target = out or Path("evals") / f"rpi_{issue}.jsonl" + save_cases(cases, target) + with_abs = sum(1 for c in cases if c.abstract) + console.print( + f"{len(records)} records, {len(cases)} cases ({with_abs} with abstract) -> {target}" + ) + + +@app.command("eval") +def eval_cmd( + cases: Path = typer.Argument(..., help="JSONL produced by `t2ipc rpi`"), + version: str = typer.Option("latest"), + level: str = typer.Option("subgroup"), + top_k: int = typer.Option(10), + lang: str = typer.Option("EN"), + model: str = typer.Option(None), + limit: int = typer.Option(None, help="Only the first N cases"), + show_misses: int = typer.Option(0, help="Print this many misses at the target level"), + rerank: bool = typer.Option(False, help="Second stage: cross-encoder over the candidates"), + reranker: str = typer.Option(None, help=f"Reranker spec (default {DEFAULT_RERANKER})"), +): + """Hit-rate at each hierarchy level against office-assigned symbols.""" + from .classifier import IpcClassifier + from .eval import evaluate, load_cases + + items = load_cases(cases)[:limit] + clf = IpcClassifier(version, lang=lang, model=model) + with console.status("evaluating...") as status: + result = evaluate( + items, + lambda t: clf.classify(t, level=level, top_k=top_k, rerank=reranker or rerank), + level=level, + top_k=top_k, + progress=lambda i, n: status.update(f"evaluating {i}/{n}"), + ) + console.print( + f"[bold]{cases.name}[/] n={result.n} version={clf.version} lang={clf.lang} " + f"model={clf.index.meta.model}" + + (f" reranker={clf.reranker(reranker or True).name}" if (rerank or reranker) else "") + ) + console.print(result.table()) + for case_id, gold, preds in result.misses[:show_misses]: + got = " ".join(format_symbol(p) for p in preds) + console.print(f" miss {case_id}: gold {gold} | got {got}") + + +@app.command() +def download( + repo: str = typer.Argument(DEFAULT_HF_REPO, help="Hugging Face model repo made by hf-export"), + revision: str = typer.Option(None, help="Branch, tag or commit"), +): + """Fetch a prebuilt index and its scheme table from the Hugging Face Hub.""" + from .index.publish import download_from_hf + + with console.status(f"downloading from huggingface.co/{repo}..."): + path, cfg = download_from_hf(repo, revision=revision) + console.print(f"ready: {path}") + console.print( + f'try: t2ipc classify "..." --version {cfg["version"]} --lang {cfg["lang"]} ' + f"--model {cfg['model']}" + ) + + +@app.command("hf-export") +def hf_export( + out: Path = typer.Argument(..., help="Directory to create (becomes the HF model repo)"), + version: str = typer.Option("latest"), + lang: str = typer.Option("EN"), + model: str = typer.Option(None), + repo_id: str = typer.Option(None, help="Hub repo id written into the model card"), +): + """Assemble a Hugging Face Inference Endpoints repository (handler.py + index).""" + from .classifier import resolve_built_version + from .hf import export_hf_repo + + model = model or default_model() + version = resolve_built_version(version, lang.upper(), model, home()) + path = export_hf_repo( + out, + version=version, + lang=lang, + model=model, + repo_id=repo_id or f"/text2ipc-{lang.lower()}", + ) + console.print(f"HF repo assembled at {path}") + console.print(f"publish with: huggingface-cli upload / {path} . --repo-type model") + + +@app.command("web-export") +def web_export( + out: Path = typer.Argument(..., help="Directory to create (becomes a static HF Space)"), + version: str = typer.Option("latest", help="Resolved per language among built indexes"), + lang: list[str] = typer.Option(["PT"], help="Scheme language; repeat for several"), + model: str = typer.Option( + None, help=f"Embedder the indexes were built with (default {WEB_DEFAULT_MODEL})" + ), + web_model: str = typer.Option(None, help="transformers.js model id (default: Xenova twin)"), + web_dtype: str = typer.Option("q8", help="ONNX weights the browser loads: q8, fp16, fp32"), + repo_id: str = typer.Option(None, help="Space id written into the README"), + examples: Path = typer.Option( + None, help="JSONL of eval cases; their title + abstract become the example texts" + ), + web_reranker: str = typer.Option( + WEB_DEFAULT_RERANKER, + help="transformers.js cross-encoder for the Rerank option; '' for none", + ), +): + """Assemble a static Hugging Face Space that classifies in the browser (ADR 0007).""" + from .web import export_web_demo + + path = export_web_demo( + out, + model=model or WEB_DEFAULT_MODEL, + langs=[lg.upper() for lg in lang], + version=version, + repo_id=repo_id or "/text2ipc", + web_model=web_model, + web_dtype=web_dtype, + examples=examples, + web_reranker=web_reranker or None, + ) + total = sum(f.stat().st_size for f in path.rglob("*") if f.is_file()) + console.print(f"static Space assembled at {path} ({total / 1e6:.0f} MB)") + console.print( + f"publish with: scripts/publish_space.sh " + f"(or hf upload / {path} . --repo-type space)" + ) + + +@app.command("migrate-csv") +def migrate_csv( + csv_path: Path = typer.Argument(..., help="Legacy ipc___.csv index"), + delete: bool = typer.Option(False, help="Delete the CSV and its meta.json afterwards"), +): + """Convert a legacy CSV index into scheme table + parquet index, without embedding.""" + from .index.migrate import migrate_csv_index + + scheme_target, index_target, report = migrate_csv_index(csv_path) + console.print(report) + console.print(f"wrote {scheme_target.name} and {index_target.name}") + if delete: + csv_path.unlink() + csv_path.with_suffix(".meta.json").unlink(missing_ok=True) + console.print("deleted the CSV") + + +if __name__ == "__main__": + app() diff --git a/text2ipc/config.py b/text2ipc/config.py new file mode 100644 index 0000000000000000000000000000000000000000..688ea7f424f051a898857a555727c6fef861b3e9 --- /dev/null +++ b/text2ipc/config.py @@ -0,0 +1,70 @@ +"""Package-wide constants and locations.""" + +from __future__ import annotations + +import os +from pathlib import Path + +#: Hierarchy levels, top to bottom. ``depth`` further refines subgroups by dot count. +LEVELS: tuple[str, ...] = ("section", "class", "subclass", "group", "subgroup") + +#: Special level meaning "descend while the evidence supports it". +AUTO_LEVEL = "auto" + +#: Scheme languages WIPO ships in its master files. +WIPO_LANGS: tuple[str, ...] = ("EN", "FR") +#: Languages available as a title overlay on the English hierarchy, and their source. +OVERLAY_LANGS: dict[str, str] = {"PT": "inpi"} +DEFAULT_LANG = "EN" + +#: Multilingual by default so that a Portuguese abstract can be matched against the +#: English scheme. ``e5-base`` roughly doubles precision over ``e5-small`` on the RPI +#: evals (docs/evals.md). Override with ``TEXT2IPC_MODEL`` or the ``model=`` argument. +DEFAULT_MODEL = "st:intfloat/multilingual-e5-base" + +#: Cross-encoder that re-scores the first stage's candidates when ``rerank`` is on. +#: Multilingual, 568M parameters; lifts subclass@1 by 9 points on the PT evals. +DEFAULT_RERANKER = "ce:BAAI/bge-reranker-v2-m3" + +WIPO_BASE_URL = "https://www.wipo.int/ipc/itos4ipc/ITSupport_and_download_area" + + +#: Hugging Face model repository holding the published Portuguese index. +DEFAULT_HF_REPO = "jaimenms/text2ipc-pt" + + +def home() -> Path: + """Directory holding downloaded schemes and built indexes. + + Resolution order: + + 1. ``TEXT2IPC_HOME``. + 2. ``/data`` when the current directory (or one of its parents) is the + text2ipc study repository and that directory exists, so artefacts stay next to + the code while developing, also from ``notebooks/`` or ``tests/``. + 3. ``$XDG_CACHE_HOME/text2ipc`` or ``~/.cache/text2ipc`` for installed users. + """ + if env := os.environ.get("TEXT2IPC_HOME"): + return Path(env).expanduser() + if (repo_data := _repo_data_dir()) is not None: + return repo_data + base = os.environ.get("XDG_CACHE_HOME") + root = Path(base).expanduser() if base else Path.home() / ".cache" + return root / "text2ipc" + + +def _repo_data_dir(cwd: Path | None = None) -> Path | None: + for candidate in [cwd or Path.cwd(), *(cwd or Path.cwd()).parents]: + pyproject = candidate / "pyproject.toml" + try: + is_repo = pyproject.is_file() and 'name = "text2ipc"' in pyproject.read_text() + except OSError: + return None + if is_repo: + data = candidate / "data" + return data if data.is_dir() else None + return None + + +def default_model() -> str: + return os.environ.get("TEXT2IPC_MODEL", DEFAULT_MODEL) diff --git a/text2ipc/embeddings/__init__.py b/text2ipc/embeddings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..879ac994fe9c8c05e66d26ccf246083053d1e01d --- /dev/null +++ b/text2ipc/embeddings/__init__.py @@ -0,0 +1,3 @@ +from .base import Embedder, get_embedder, model_slug + +__all__ = ["Embedder", "get_embedder", "model_slug"] diff --git a/text2ipc/embeddings/base.py b/text2ipc/embeddings/base.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce0f141ec8f1477e73ddc6cb0524967aa75ab36 --- /dev/null +++ b/text2ipc/embeddings/base.py @@ -0,0 +1,79 @@ +"""Embedding backends behind one small interface. + +A backend is selected by a spec string ``:``: + +- ``st:intfloat/multilingual-e5-small`` sentence-transformers, runs locally (default) +- ``ollama:nomic-embed-text`` any embedding model served by Ollama +- ``hash:64`` deterministic bag-of-words, for tests only + +Vectors are always L2-normalised so that a dot product is a cosine similarity. +""" + +from __future__ import annotations + +import re +from collections.abc import Sequence +from typing import Protocol, runtime_checkable + +import numpy as np + + +@runtime_checkable +class Embedder(Protocol): + @property + def name(self) -> str: + """Full spec string, stored in the index metadata.""" + + @property + def dim(self) -> int: ... + + def embed_passages(self, texts: Sequence[str]) -> np.ndarray: + """(len(texts), dim) float32 array of unit vectors.""" + + def embed_query(self, text: str) -> np.ndarray: + """(dim,) float32 unit vector. Some models want a different prefix for queries.""" + + def embed_queries(self, texts: Sequence[str]) -> np.ndarray: + """(len(texts), dim) unit vectors, one query per text.""" + + @property + def max_tokens(self) -> int | None: + """Longest input the model embeds whole; None when unbounded or unknown.""" + + def count_tokens(self, text: str) -> int: + """Tokens ``embed_query(text)`` feeds the model, prefix and special tokens included.""" + + +def get_embedder(spec: str | Embedder, **kwargs) -> Embedder: + if not isinstance(spec, str): + return spec + backend, _, model = spec.partition(":") + if not model: + raise ValueError(f"Embedder spec must look like 'backend:model', got {spec!r}") + if backend == "st": + from .st import SentenceTransformerEmbedder + + return SentenceTransformerEmbedder(model, **kwargs) + if backend == "ollama": + from .ollama import OllamaEmbedder + + return OllamaEmbedder(model, **kwargs) + if backend == "hash": + from .hashing import HashEmbedder + + return HashEmbedder(int(model), **kwargs) + raise ValueError(f"Unknown embedding backend {backend!r}") + + +def model_slug(name: str) -> str: + """Filesystem-safe form of a spec, used in index file names.""" + return re.sub(r"[^A-Za-z0-9.]+", "-", name).strip("-").lower() + + +def normalize(vectors: np.ndarray) -> np.ndarray: + vectors = np.asarray(vectors, dtype=np.float32) + if vectors.ndim == 1: + vectors = vectors[None, :] + norms = np.linalg.norm(vectors, axis=1, keepdims=True) + norms[norms == 0] = 1.0 + return vectors / norms diff --git a/text2ipc/embeddings/hashing.py b/text2ipc/embeddings/hashing.py new file mode 100644 index 0000000000000000000000000000000000000000..85657710139fd7849ae6adf603f129ec1169e309 --- /dev/null +++ b/text2ipc/embeddings/hashing.py @@ -0,0 +1,55 @@ +"""Deterministic bag-of-words embedder for tests and offline smoke runs. + +Each lower-cased token is hashed to one dimension, so texts sharing words are similar. +No semantics, but fully reproducible and dependency free. +""" + +from __future__ import annotations + +import hashlib +import re +from collections.abc import Sequence + +import numpy as np + +from .base import normalize + +_TOKEN_RE = re.compile(r"[a-z0-9]+") + + +class HashEmbedder: + def __init__(self, dim: int = 64): + self._dim = dim + + @property + def name(self) -> str: + return f"hash:{self._dim}" + + @property + def dim(self) -> int: + return self._dim + + def _vector(self, text: str) -> np.ndarray: + v = np.zeros(self._dim, dtype=np.float32) + for tok in _TOKEN_RE.findall(text.lower()): + h = int(hashlib.md5(tok.encode()).hexdigest(), 16) # noqa: S324 - not security + v[h % self._dim] += 1.0 + return v + + def embed_passages(self, texts: Sequence[str]) -> np.ndarray: + if not texts: + return np.zeros((0, self._dim), dtype=np.float32) + return normalize(np.stack([self._vector(t) for t in texts])) + + def embed_query(self, text: str) -> np.ndarray: + return self.embed_passages([text])[0] + + def embed_queries(self, texts: Sequence[str]) -> np.ndarray: + return self.embed_passages(texts) + + @property + def max_tokens(self) -> int | None: + return None + + def count_tokens(self, text: str) -> int: + return len(_TOKEN_RE.findall(text.lower())) diff --git a/text2ipc/embeddings/ollama.py b/text2ipc/embeddings/ollama.py new file mode 100644 index 0000000000000000000000000000000000000000..6a88e9b0cb6eab4a409911d5eaec03c74331ff33 --- /dev/null +++ b/text2ipc/embeddings/ollama.py @@ -0,0 +1,65 @@ +"""Ollama backend: any model that answers ``POST /api/embed``.""" + +from __future__ import annotations + +from collections.abc import Sequence + +import httpx +import numpy as np + +from .base import normalize + + +class OllamaEmbedder: + def __init__( + self, + model: str, + *, + host: str = "http://localhost:11434", + batch_size: int = 32, + timeout: float = 120.0, + ): + self._model = model + self._host = host.rstrip("/") + self._batch_size = batch_size + self._client = httpx.Client(timeout=timeout) + self._dim: int | None = None + + @property + def name(self) -> str: + return f"ollama:{self._model}" + + @property + def dim(self) -> int: + if self._dim is None: + self._dim = int(self.embed_passages(["probe"]).shape[1]) + return self._dim + + def _embed(self, texts: Sequence[str]) -> np.ndarray: + resp = self._client.post( + f"{self._host}/api/embed", json={"model": self._model, "input": list(texts)} + ) + resp.raise_for_status() + return normalize(np.asarray(resp.json()["embeddings"], dtype=np.float32)) + + def embed_passages(self, texts: Sequence[str]) -> np.ndarray: + chunks = [ + self._embed(texts[i : i + self._batch_size]) + for i in range(0, len(texts), self._batch_size) + ] + if not chunks: + return np.zeros((0, self.dim), dtype=np.float32) + return np.vstack(chunks) + + def embed_query(self, text: str) -> np.ndarray: + return self._embed([text])[0] + + def embed_queries(self, texts: Sequence[str]) -> np.ndarray: + return self._embed(list(texts)) + + @property + def max_tokens(self) -> int | None: + return None # Ollama truncates server side; the limit is not exposed + + def count_tokens(self, text: str) -> int: + return len(text.split()) diff --git a/text2ipc/embeddings/st.py b/text2ipc/embeddings/st.py new file mode 100644 index 0000000000000000000000000000000000000000..1bd4765b5e194e8b5e9ac5f164420819fc2a264c --- /dev/null +++ b/text2ipc/embeddings/st.py @@ -0,0 +1,83 @@ +"""sentence-transformers backend (``pip install text2ipc[st]``).""" + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np + +from .base import normalize + +#: Query / passage prefixes some model families were trained with. +_PREFIXES: dict[str, tuple[str, str]] = { + "e5": ("query: ", "passage: "), + "bge-.*-en": ("Represent this sentence for searching relevant passages: ", ""), +} + + +def prefixes_for(model: str) -> tuple[str, str]: + import re + + lowered = model.lower() + for pattern, pair in _PREFIXES.items(): + if re.search(pattern, lowered): + return pair + return ("", "") + + +class SentenceTransformerEmbedder: + def __init__(self, model: str, *, batch_size: int = 64, device: str | None = None): + try: + from sentence_transformers import SentenceTransformer + except ImportError as e: # pragma: no cover + raise ImportError("Install the 'st' extra: uv add 'text2ipc[st]'") from e + self._model_name = model + self._model = SentenceTransformer(model, device=device) + self._batch_size = batch_size + self._query_prefix, self._passage_prefix = prefixes_for(model) + + @property + def name(self) -> str: + return f"st:{self._model_name}" + + @property + def dim(self) -> int: + getter = getattr(self._model, "get_embedding_dimension", None) + if getter is None: # older sentence-transformers + getter = self._model.get_sentence_embedding_dimension + return int(getter()) + + def embed_passages(self, texts: Sequence[str]) -> np.ndarray: + if not texts: + return np.zeros((0, self.dim), dtype=np.float32) + out = self._model.encode( + [self._passage_prefix + t for t in texts], + batch_size=self._batch_size, + normalize_embeddings=True, + convert_to_numpy=True, + show_progress_bar=len(texts) > 500, + ) + return normalize(out) + + def embed_query(self, text: str) -> np.ndarray: + return self.embed_passages_raw([self._query_prefix + text])[0] + + def embed_queries(self, texts: Sequence[str]) -> np.ndarray: + if not texts: + return np.zeros((0, self.dim), dtype=np.float32) + return self.embed_passages_raw([self._query_prefix + t for t in texts]) + + @property + def max_tokens(self) -> int | None: + limit = getattr(self._model, "max_seq_length", None) + return int(limit) if limit else None + + def count_tokens(self, text: str) -> int: + ids = self._model.tokenizer( + self._query_prefix + text, add_special_tokens=True, truncation=False, verbose=False + )["input_ids"] # verbose=False: counting past the limit is the point, no warning + return len(ids) + + def embed_passages_raw(self, texts: Sequence[str]) -> np.ndarray: + out = self._model.encode(list(texts), normalize_embeddings=True, convert_to_numpy=True) + return normalize(out) diff --git a/text2ipc/eval/__init__.py b/text2ipc/eval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10ca700b129edd30d580afc94a7c9640d62d940f --- /dev/null +++ b/text2ipc/eval/__init__.py @@ -0,0 +1,20 @@ +from .cases import EvalCase, load_cases, load_many, save_cases +from .harness import EvalResult, evaluate +from .rerank import JudgedCase, fused_order, fusion_results, judge_candidates +from .rpi import cases_from_rpi, fetch_rpi, parse_rpi + +__all__ = [ + "EvalCase", + "EvalResult", + "JudgedCase", + "cases_from_rpi", + "evaluate", + "fetch_rpi", + "fused_order", + "fusion_results", + "judge_candidates", + "load_cases", + "load_many", + "parse_rpi", + "save_cases", +] diff --git a/text2ipc/eval/cases.py b/text2ipc/eval/cases.py new file mode 100644 index 0000000000000000000000000000000000000000..56150695a15f9b23d87b9c699378d2ac18115612 --- /dev/null +++ b/text2ipc/eval/cases.py @@ -0,0 +1,70 @@ +"""Eval cases: a text and the IPC symbols a patent office assigned to it.""" + +from __future__ import annotations + +import json +from dataclasses import asdict, dataclass, field +from pathlib import Path + + +@dataclass(frozen=True) +class EvalCase: + id: str + text: str # what gets classified: abstract when available, else the title + ipc: tuple[str, ...] # canonical 14-char gold symbols + lang: str = "pt" + title: str | None = None + abstract: str | None = None + source: str | None = None + tags: tuple[str, ...] = field(default_factory=tuple) + + +def save_cases(cases: list[EvalCase], path: Path | str) -> None: + Path(path).parent.mkdir(parents=True, exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + for c in cases: + fh.write(json.dumps(asdict(c), ensure_ascii=False) + "\n") + + +def load_many( + paths: list[Path | str] | str, + *, + sample: int | None = None, + seed: int = 0, + stratify_by_abstract: bool = True, +) -> list[EvalCase]: + """Load several JSONL files (or a glob) and optionally draw a random sample. + + With ``stratify_by_abstract`` the sample takes half its cases from those that have + an abstract and half from title-only ones, as far as each pool allows. + """ + import glob + import random + + files = sorted(glob.glob(paths)) if isinstance(paths, str) else list(paths) + cases = [c for f in files for c in load_cases(f)] + if sample is None or sample >= len(cases): + return cases + rng = random.Random(seed) + if not stratify_by_abstract: + return rng.sample(cases, sample) + with_abs = [c for c in cases if c.abstract] + without = [c for c in cases if not c.abstract] + n_abs = min(len(with_abs), sample // 2) + n_wo = min(len(without), sample - n_abs) + n_abs = min(len(with_abs), sample - n_wo) + picked = rng.sample(with_abs, n_abs) + rng.sample(without, n_wo) + rng.shuffle(picked) + return picked + + +def load_cases(path: Path | str) -> list[EvalCase]: + cases = [] + with open(path, encoding="utf-8") as fh: + for line in fh: + if line.strip(): + d = json.loads(line) + d["ipc"] = tuple(d["ipc"]) + d["tags"] = tuple(d.get("tags", ())) + cases.append(EvalCase(**d)) + return cases diff --git a/text2ipc/eval/harness.py b/text2ipc/eval/harness.py new file mode 100644 index 0000000000000000000000000000000000000000..9c9ef1bb8bfa69c2520f3d5236b8c30381e30c39 --- /dev/null +++ b/text2ipc/eval/harness.py @@ -0,0 +1,113 @@ +"""Hit-rate at every hierarchy level. + +A case counts as a hit at level L and cut-off k if any of the top-k predictions, +truncated to level L, equals any gold symbol truncated to level L. Gold sets are +multi-label and the first listed symbol is the office's main one, so ``main_*`` +metrics score only against that symbol. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass, field + +from ..config import LEVELS +from ..search import Match +from .cases import EvalCase + + +def truncate(symbol: str, level: str) -> str: + if level == "section": + return symbol[:1] + if level == "class": + return symbol[:3] + if level == "subclass": + return symbol[:4] + if level == "group": + return symbol[:8] + "000000" if len(symbol) == 14 else symbol + return symbol + + +@dataclass +class EvalResult: + level: str + top_k: int + n: int = 0 + hits: dict[str, dict[int, int]] = field(default_factory=dict) # level -> k -> hits + main_hits: dict[str, dict[int, int]] = field(default_factory=dict) + reciprocal_rank: dict[str, float] = field(default_factory=dict) + misses: list[tuple[str, str, list[str]]] = field(default_factory=list) # id, gold, predicted + + def rate(self, level: str, k: int, *, main: bool = False) -> float: + table = self.main_hits if main else self.hits + return table.get(level, {}).get(k, 0) / self.n if self.n else 0.0 + + def mrr(self, level: str) -> float: + return self.reciprocal_rank.get(level, 0.0) / self.n if self.n else 0.0 + + def rows(self, ks: tuple[int, ...] = (1, 3, 5, 10)) -> list[dict]: + """One dict per level, ready for ``pandas.DataFrame``.""" + ks = tuple(k for k in ks if k <= self.top_k) + out = [] + for level in LEVELS[: LEVELS.index(self.level) + 1]: + row = {"level": level, "n": self.n} + row.update({f"hit@{k}": self.rate(level, k) for k in ks}) + row["main@1"] = self.rate(level, 1, main=True) + row["mrr"] = self.mrr(level) + out.append(row) + return out + + def table(self, ks: tuple[int, ...] = (1, 3, 5, 10)) -> str: + ks = tuple(k for k in ks if k <= self.top_k) + head = "level " + "".join(f" hit@{k:<3}" for k in ks) + " main@1 mrr" + rows = [head] + for level in LEVELS[: LEVELS.index(self.level) + 1]: + cells = "".join(f" {self.rate(level, k):6.1%}" for k in ks) + rows.append( + f"{level:<11}{cells} {self.rate(level, 1, main=True):6.1%} {self.mrr(level):.3f}" + ) + return "\n".join(rows) + + +def evaluate( + cases: list[EvalCase], + classify: Callable[[str], list[Match]], + *, + level: str = "subgroup", + top_k: int = 10, + progress: Callable[[int, int], None] | None = None, +) -> EvalResult: + result = EvalResult(level=level, top_k=top_k) + levels = LEVELS[: LEVELS.index(level) + 1] + for lv in levels: + result.hits[lv] = dict.fromkeys(range(1, top_k + 1), 0) + result.main_hits[lv] = dict.fromkeys(range(1, top_k + 1), 0) + result.reciprocal_rank[lv] = 0.0 + + for i, case in enumerate(cases, 1): + preds = [m.symbol for m in classify(case.text)[:top_k]] + result.n += 1 + for lv in levels: + gold = {truncate(s, lv) for s in case.ipc} + main = truncate(case.ipc[0], lv) + seen: list[str] = [] + first_hit = None + for p in preds: + t = truncate(p, lv) + if t in seen: + continue + seen.append(t) + if first_hit is None and t in gold: + first_hit = len(seen) + result.reciprocal_rank[lv] += 1.0 / first_hit + if t == main: + for k in range(len(seen), top_k + 1): + result.main_hits[lv][k] += 1 + if first_hit is not None: + for k in range(first_hit, top_k + 1): + result.hits[lv][k] += 1 + elif lv == level: + result.misses.append((case.id, ",".join(sorted(gold)), seen[:5])) + if progress: + progress(i, len(cases)) + return result diff --git a/text2ipc/eval/rerank.py b/text2ipc/eval/rerank.py new file mode 100644 index 0000000000000000000000000000000000000000..451c231ea35726b7490403c915e331dde874685f --- /dev/null +++ b/text2ipc/eval/rerank.py @@ -0,0 +1,84 @@ +"""Measure the second stage without paying for it more than once. + +``judge_candidates`` runs the first stage and the reranker over a list of cases and +keeps the candidates with their first-stage scores and judge logits; +``fusion_results`` then evaluates several ways of combining the two scores from that +single run (notebook 02 and the tables in docs/evals.md). +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import dataclass, replace + +import numpy as np + +from ..rerank import Reranker, fuse, sigmoid +from ..search import Match, SearchParams, search +from .cases import EvalCase +from .harness import EvalResult, evaluate + +FUSIONS: tuple[str, ...] = ("first", "judge", "blend", "product") + + +@dataclass(frozen=True) +class JudgedCase: + case: EvalCase + matches: list[Match] # first-stage candidates, in first-stage order + logits: np.ndarray # one reranker logit per candidate + + +def judge_candidates( + clf, + cases: Sequence[EvalCase], + *, + candidates: int = 25, + level: str = "subgroup", + reranker: bool | str | Reranker = True, + progress: Callable[[int, int], None] | None = None, +) -> list[JudgedCase]: + """First stage (``candidates`` entries) plus reranker logits for every case.""" + from ..classifier import normalize_query + + judge = clf.reranker(reranker) + params = SearchParams(level=level, top_k=candidates) + out = [] + for i, case in enumerate(cases, 1): + text = normalize_query(case.text) + matches = search(clf.index, clf.embed_text(text), params) + logits = judge.score(text, [m.text for m in matches]) if matches else np.zeros(0) + out.append(JudgedCase(case, matches, np.asarray(logits, dtype=np.float32))) + if progress: + progress(i, len(cases)) + return out + + +def fused_order(judged: JudgedCase, fusion: str, top_k: int) -> list[Match]: + """The candidate list reordered by one fusion rule (``first`` keeps stage one).""" + if fusion == "first": + return judged.matches[:top_k] + scores = np.array([m.score for m in judged.matches]) + fused = fuse(scores, judged.logits, fusion) + verdict = sigmoid(judged.logits) + order = np.argsort(-fused, kind="stable")[:top_k] + return [ + replace(judged.matches[i], score=float(fused[i]), judge=float(verdict[i])) for i in order + ] + + +def fusion_results( + judged: Sequence[JudgedCase], + *, + fusions: Sequence[str] = FUSIONS, + top_k: int = 10, + level: str = "subgroup", +) -> dict[str, EvalResult]: + """Hit rates per fusion rule, from one judged run.""" + by_text = {j.case.text: j for j in judged} + cases = [j.case for j in judged] + return { + f: evaluate( + cases, lambda t, f=f: fused_order(by_text[t], f, top_k), level=level, top_k=top_k + ) + for f in fusions + } diff --git a/text2ipc/eval/rpi.py b/text2ipc/eval/rpi.py new file mode 100644 index 0000000000000000000000000000000000000000..b25ea174609c524b30ab4319df87eb45fdf21a97 --- /dev/null +++ b/text2ipc/eval/rpi.py @@ -0,0 +1,229 @@ +"""Eval cases from the *Revista da Propriedade Industrial* (RPI), INPI Brazil. + +Every week INPI publishes a zip at ``https://revistas.inpi.gov.br/txt/P.zip``. +Recent issues hold ``Patente__.xml``; older ones (e.g. 2100, from 2011) +hold only ``P.txt``, a Latin-1 text file with one ``(INID) value`` field per +line and a ``(Cd) `` line opening every dispatch. Both formats are parsed. + +Dispatch codes 1.3 (PCT application admitted to the national phase) and 3.1 +(application published) expose a title (INID 54), the IPC symbols (INID 51) and, in +issues that include it, the abstract (INID 57). Recent XML issues carry no abstract; +the text issues around 2100 do, which makes them the better eval source. Text is +Portuguese. +""" + +from __future__ import annotations + +import io +import re +import xml.etree.ElementTree as ET +import zipfile +from pathlib import Path + +import httpx + +from ..config import home +from ..scheme.symbols import normalize_symbol +from .cases import EvalCase + +RPI_URL = "https://revistas.inpi.gov.br/txt/P{issue}.zip" +PUBLISHED_DISPATCHES = ("1.3", "3.1") + + +def fetch_rpi(issue: int | str, *, root: Path | None = None, timeout: float = 120.0) -> Path: + """Download the issue zip (cached under ``/rpi``) and return the XML path.""" + target_dir = (root or home()) / "rpi" + existing = sorted(target_dir.glob(f"Patente_{issue}_*.xml")) or sorted( + target_dir.glob(f"P{issue}.txt") + ) + if existing: + return existing[0] + target_dir.mkdir(parents=True, exist_ok=True) + content = _download(RPI_URL.format(issue=issue), timeout=timeout) + with zipfile.ZipFile(io.BytesIO(content)) as zf: + names = [n for n in zf.namelist() if n.lower().endswith(".xml")] or [ + n for n in zf.namelist() if n.lower().endswith(".txt") + ] + if not names: + raise FileNotFoundError(f"No XML or TXT inside {RPI_URL.format(issue=issue)}") + out = target_dir / Path(names[0]).name + out.write_bytes(zf.read(names[0])) + return out + + +def _download(url: str, *, timeout: float, attempts: int = 3) -> bytes: + """INPI's server sometimes closes the connection early; retry a few times.""" + headers = {"User-Agent": "Mozilla/5.0 (text2ipc)", "Accept-Encoding": "identity"} + last: Exception | None = None + for _ in range(attempts): + try: + resp = httpx.get(url, timeout=timeout, follow_redirects=True, headers=headers) + resp.raise_for_status() + return resp.content + except (httpx.TransportError, httpx.HTTPStatusError) as e: # pragma: no cover + last = e + raise RuntimeError(f"Could not download {url} after {attempts} attempts") from last + + +def parse_rpi(path: Path | str, dispatches: tuple[str, ...] = PUBLISHED_DISPATCHES) -> list[dict]: + """Raw records: issue, number, dispatch, title, abstract, ipc list (as printed).""" + path = Path(path) + if path.suffix.lower() == ".txt": + return parse_rpi_text(path, dispatches) + return parse_rpi_xml(path, dispatches) + + +_FIELD_RE = re.compile(r"^\((?P[A-Za-z0-9]{2})\)\s?(?P.*)$") +_IPC_RE = re.compile(r"[A-H]\d{2}[A-Z]\s?\d{1,4}/\d{2,6}") + + +def parse_rpi_text( + path: Path | str, dispatches: tuple[str, ...] = PUBLISHED_DISPATCHES +) -> list[dict]: + """Parse the legacy ``P.txt`` layout.""" + path = Path(path) + raw = path.read_bytes() + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + text = raw.decode("latin-1") + header = re.search(r"^\s*N[o°º]\s*(\d+)\s+de\s", text, flags=re.MULTILINE) + fname = re.search(r"P(\d+)", path.stem) + issue_no = header.group(1) if header else (fname.group(1) if fname else "") + records: list[dict] = [] + current: dict | None = None + last_field: str | None = None + for line in text.splitlines(): + m = _FIELD_RE.match(line) + if m is None: + if current is not None and last_field and line.strip(): + current[last_field] += " " + line.strip() + continue + inid, value = m.group("inid"), m.group("value").strip() + if inid == "Cd": + if current is not None: + records.append(current) + current = {"dispatch": value, "21": "", "51": "", "54": "", "57": ""} + last_field = None + continue + if current is None: + continue + if inid in current and inid != "dispatch": + current[inid] = (current[inid] + " " + value).strip() if current[inid] else value + last_field = inid + else: + last_field = None + if current is not None: + records.append(current) + + out = [] + for r in records: + if r["dispatch"] not in dispatches: + continue + title = _clean(r["54"]) + abstract = _strip_repeated_title(_clean(r["57"]), title) + out.append( + { + "issue": issue_no, + "number": _clean(r["21"]), + "dispatch": r["dispatch"], + "title": title, + "abstract": abstract, + "ipc": [m.group(0) for m in _IPC_RE.finditer(r["51"])], + } + ) + return out + + +def _strip_repeated_title(abstract: str, title: str) -> str: + """Text issues print the title again at the start of the abstract, with slightly + different spacing and punctuation, so compare on letters and digits only.""" + key = _alnum(title) + if not key or not _alnum(abstract).startswith(key): + return abstract + consumed = 0 + for i, ch in enumerate(abstract): + if ch.isalnum(): + consumed += 1 + if consumed == len(key): + return abstract[i + 1 :].lstrip(" .:;,-") + return abstract + + +def _alnum(text: str) -> str: + return "".join(ch for ch in text.lower() if ch.isalnum()) + + +def parse_rpi_xml( + xml_path: Path | str, dispatches: tuple[str, ...] = PUBLISHED_DISPATCHES +) -> list[dict]: + root = ET.parse(xml_path).getroot() + issue = root.get("numero", "") + records = [] + for d in root.iter("despacho"): + code = (d.findtext("codigo") or "").strip() + if code not in dispatches: + continue + pp = d.find("processo-patente") + if pp is None: + continue + number = (pp.findtext("numero") or "").strip() + title = _clean(pp.findtext("titulo")) + abstract = _clean(_first_text(pp, ("resumo", ".//*[@inid='57']"))) + ipc = [ + (e.text or "").strip() + for e in pp.iter("classificacao-internacional") + if (e.text or "").strip() + ] + records.append( + { + "issue": issue, + "number": number, + "dispatch": code, + "title": title, + "abstract": abstract, + "ipc": ipc, + } + ) + return records + + +def cases_from_rpi(records: list[dict], *, require_abstract: bool = False) -> list[EvalCase]: + cases = [] + for r in records: + text = r["abstract"] or r["title"] + if not text or not r["ipc"] or (require_abstract and not r["abstract"]): + continue + symbols = [] + for raw in r["ipc"]: + try: + symbols.append(normalize_symbol(raw)) + except ValueError: + continue + if not symbols: + continue + cases.append( + EvalCase( + id=f"rpi{r['issue']}:{r['number'].replace(' ', '')}", + text=text, + ipc=tuple(dict.fromkeys(symbols)), + lang="pt", + title=r["title"] or None, + abstract=r["abstract"] or None, + source=f"RPI {r['issue']} despacho {r['dispatch']}", + tags=("abstract" if r["abstract"] else "title-only", f"despacho-{r['dispatch']}"), + ) + ) + return cases + + +def _first_text(el: ET.Element, paths: tuple[str, ...]) -> str | None: + for p in paths: + found = el.find(p) + if found is not None and (found.text or "").strip(): + return found.text + return None + + +def _clean(text: str | None) -> str: + return re.sub(r"\s+", " ", text or "").strip() diff --git a/text2ipc/hf/__init__.py b/text2ipc/hf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/text2ipc/index/__init__.py b/text2ipc/index/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea700d3ba3d4e15034e20daa943f8a7e803bbd8 --- /dev/null +++ b/text2ipc/index/__init__.py @@ -0,0 +1,14 @@ +from .build import BuildReport, build_index +from .paths import available_indexes, find_previous_index, index_path, scheme_table_path +from .store import IndexMeta, IpcIndex + +__all__ = [ + "BuildReport", + "IndexMeta", + "IpcIndex", + "available_indexes", + "build_index", + "find_previous_index", + "index_path", + "scheme_table_path", +] diff --git a/text2ipc/index/build.py b/text2ipc/index/build.py new file mode 100644 index 0000000000000000000000000000000000000000..eb36fdb580cdf68bda2098078e9f0fa99db343b2 --- /dev/null +++ b/text2ipc/index/build.py @@ -0,0 +1,113 @@ +"""Build an index for one scheme version, reusing vectors from an older one. + +A node's vector depends only on its rendered text (the full path of titles) and the +model. For every symbol present in the previous index with an identical text hash the +old vector is copied instead of recomputed. Between two yearly IPC versions that is +typically well over 95 percent of the entries. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np + +from ..embeddings.base import Embedder +from ..scheme.table import SchemeTable +from .store import IndexMeta, IpcIndex + + +@dataclass +class BuildReport: + version: str + lang: str + model: str + total: int = 0 + reused: int = 0 + computed: int = 0 + added: list[str] = field(default_factory=list) + changed: list[str] = field(default_factory=list) + removed: list[str] = field(default_factory=list) + previous: str | None = None + + def summary(self) -> str: + head = f"{self.version} {self.lang} {self.model}: {self.total} entries" + if self.previous is None: + return f"{head}, all {self.computed} embedded from scratch" + return ( + f"{head}; reused {self.reused}, embedded {self.computed} " + f"(added {len(self.added)}, changed {len(self.changed)}, " + f"removed {len(self.removed)}) vs {self.previous}" + ) + + +def build_index( + scheme: SchemeTable, + embedder: Embedder, + *, + version: str, + lang: str, + previous: IpcIndex | tuple[Path, Path] | None = None, + titles_overlay: str | None = None, + batch_size: int = 256, + progress=None, +) -> tuple[IpcIndex, BuildReport]: + """``previous`` is an index or a ``(index parquet, scheme parquet)`` pair.""" + lang = lang.upper() + report = BuildReport(version=version, lang=lang, model=embedder.name, total=len(scheme)) + + prev = _load_previous(previous, embedder, lang, report) + prev_hash = prev.hashes() if prev else {} + prev_symbols = set(prev_hash) + texts = scheme.texts() + hashes = scheme.hashes() + + vectors = np.zeros((len(scheme), embedder.dim), dtype=np.float32) + todo: list[int] = [] + for i, node in enumerate(scheme.nodes): + old = prev_hash.get(node.symbol) + if old is not None and old == hashes[i]: + vectors[i] = prev.vectors[prev.position[node.symbol]] # type: ignore[union-attr] + report.reused += 1 + else: + todo.append(i) + (report.changed if old is not None else report.added).append(node.symbol) + report.removed = sorted(prev_symbols - set(scheme.position)) + report.computed = len(todo) + + for start in range(0, len(todo), batch_size): + batch = todo[start : start + batch_size] + vectors[batch] = embedder.embed_passages([texts[i] for i in batch]) + if progress is not None: + progress(min(start + batch_size, len(todo)), len(todo)) + + meta = IndexMeta.now( + version=version, + lang=lang, + model=embedder.name, + dim=embedder.dim, + rows=len(scheme), + titles_overlay=titles_overlay, + ) + return IpcIndex(meta, scheme, vectors, hashes), report + + +def _load_previous( + previous: IpcIndex | tuple[Path, Path] | None, + embedder: Embedder, + lang: str, + report: BuildReport, +) -> IpcIndex | None: + if previous is None: + return None + prev = IpcIndex.read(*previous) if isinstance(previous, tuple) else previous + if prev.meta.model != embedder.name or prev.meta.dim != embedder.dim: + raise ValueError( + f"Previous index was built with {prev.meta.model} ({prev.meta.dim}d), " + f"cannot reuse for {embedder.name} ({embedder.dim}d)" + ) + if prev.meta.lang != lang: + raise ValueError(f"Previous index is {prev.meta.lang}, cannot reuse for {lang}") + report.previous = prev.meta.version + return prev diff --git a/text2ipc/index/migrate.py b/text2ipc/index/migrate.py new file mode 100644 index 0000000000000000000000000000000000000000..db9775906e8a8a6483c6462492df77bfd143b5e2 --- /dev/null +++ b/text2ipc/index/migrate.py @@ -0,0 +1,66 @@ +"""One-off conversion of the legacy CSV indexes (ADR 0002) to parquet (ADR 0006). + +The CSV rows carry the rendered text and its hash, so the conversion can verify that +the new scheme table renders exactly the text the vectors were computed from, and no +embedding is needed. +""" + +from __future__ import annotations + +import csv +import json +from pathlib import Path + +import numpy as np + +from ..config import OVERLAY_LANGS +from ..scheme import SchemeTable, apply_titles, parse_scheme +from ..scheme.download import scheme_path +from ..scheme.inpi import fetch_inpi_titles +from .paths import index_path, scheme_table_path +from .store import IndexMeta, IpcIndex + + +def migrate_csv_index(csv_file: Path) -> tuple[Path, Path, str]: + root = csv_file.resolve().parents[1] + meta_raw = json.loads(csv_file.with_suffix(".meta.json").read_text()) + meta_raw.pop("style", None) + meta = IndexMeta(**meta_raw) + + xml = scheme_path(meta.version, "EN" if meta.lang in OVERLAY_LANGS else meta.lang, root) + nodes = parse_scheme(xml) + if meta.lang in OVERLAY_LANGS: + nodes = apply_titles(nodes, fetch_inpi_titles(meta.version, root=root)) + scheme = SchemeTable.from_nodes(nodes) + hashes = scheme.hashes() + + vectors = np.zeros((len(scheme), meta.dim), dtype=np.float32) + seen = 0 + mismatched: list[str] = [] + with open(csv_file, newline="", encoding="utf-8") as fh: + for row in csv.DictReader(fh): + i = scheme.position[row["symbol"]] + if row["text_hash"] != hashes[i]: + mismatched.append(row["symbol"]) + vectors[i] = np.fromstring(row["embedding"], sep=" ", dtype=np.float32) + seen += 1 + if seen != len(scheme): + raise ValueError(f"{csv_file.name}: {seen} rows for {len(scheme)} scheme entries") + if mismatched: + raise ValueError( + f"{csv_file.name}: rendered text differs for {len(mismatched)} entries " + f"(e.g. {mismatched[:3]}); rebuild instead of migrating" + ) + + scheme_target = scheme_table_path(meta.version, meta.lang, root) + scheme.write(scheme_target) + index = IpcIndex(meta, scheme, vectors, hashes) + index_target = index_path(meta.version, meta.lang, meta.model, root) + index.write(index_target) + csv_mb = csv_file.stat().st_size / 1e6 + pq_mb = index_target.stat().st_size / 1e6 + report = ( + f"{meta.version} {meta.lang} {meta.model}: {seen} rows, all texts identical; " + f"{csv_mb:.0f} MB CSV -> {pq_mb:.0f} MB parquet" + ) + return scheme_target, index_target, report diff --git a/text2ipc/index/paths.py b/text2ipc/index/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ee8d27b1319d32f8afafae9dc3fb7ffd1afeba3e --- /dev/null +++ b/text2ipc/index/paths.py @@ -0,0 +1,60 @@ +"""Where scheme tables and indexes live, and how to find the previous version.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + +from ..config import home +from ..embeddings.base import model_slug + +_NAME_RE = re.compile(r"^ipc_(?P\d{8})_(?P[a-z]{2})_(?P.+)\.parquet$") + + +@dataclass(frozen=True) +class IndexRef: + version: str + lang: str + model_slug: str + path: Path + + +def index_dir(root: Path | None = None) -> Path: + return (root or home()) / "index" + + +def scheme_dir(root: Path | None = None) -> Path: + return (root or home()) / "scheme" + + +def scheme_table_path(version: str, lang: str, root: Path | None = None) -> Path: + return scheme_dir(root) / f"ipc_{version}_{lang.lower()}.parquet" + + +def index_path(version: str, lang: str, model: str, root: Path | None = None) -> Path: + return index_dir(root) / f"ipc_{version}_{lang.lower()}_{model_slug(model)}.parquet" + + +def available_indexes(root: Path | None = None) -> list[IndexRef]: + d = index_dir(root) + if not d.exists(): + return [] + return [ + IndexRef(m["version"], m["lang"].upper(), m["model"], p) + for p in sorted(d.glob("ipc_*.parquet")) + if (m := _NAME_RE.match(p.name)) + ] + + +def find_previous_index( + version: str, lang: str, model: str, root: Path | None = None +) -> Path | None: + """Newest built index for the same language and model with an older version.""" + slug = model_slug(model) + older = [ + r + for r in available_indexes(root) + if r.lang == lang.upper() and r.model_slug == slug and r.version < version + ] + return older[-1].path if older else None diff --git a/text2ipc/index/publish.py b/text2ipc/index/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..d146f1909641f692390ef68878a4a8032586dbcb --- /dev/null +++ b/text2ipc/index/publish.py @@ -0,0 +1,43 @@ +"""Fetch a prebuilt index from a Hugging Face model repository made by ``t2ipc hf-export``. + +Building an index takes minutes and a model download, so end users fetch the two +Parquet tables (``index/`` and ``scheme/``) from the Hub instead. The repository's +``text2ipc.json`` says which version, language and model they belong to. +""" + +from __future__ import annotations + +import json +import shutil +from pathlib import Path + +from ..config import home + + +def download_from_hf( + repo_id: str, *, root: Path | None = None, revision: str | None = None, token=None +) -> tuple[Path, dict]: + """Copy ``index/*.parquet`` and ``scheme/*.parquet`` from a Hub model repo into home. + + Returns the index path and the repo's ``text2ipc.json`` (version, lang, model). + """ + from huggingface_hub import HfApi, hf_hub_download + + root = root or home() + api = HfApi(token=token) + files = api.list_repo_files(repo_id, repo_type="model", revision=revision) + wanted = [f for f in files if f.endswith(".parquet") and f.split("/")[0] in {"index", "scheme"}] + if "text2ipc.json" not in files or not wanted: + raise FileNotFoundError(f"{repo_id}: no text2ipc.json or parquet tables found") + cfg_path = hf_hub_download(repo_id, "text2ipc.json", revision=revision, token=token) + cfg = json.loads(Path(cfg_path).read_text()) + index_target: Path | None = None + for f in wanted: + cached = Path(hf_hub_download(repo_id, f, revision=revision, token=token)) + target = root / f + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(cached, target) + if f.startswith("index/"): + index_target = target + assert index_target is not None + return index_target, cfg diff --git a/text2ipc/index/store.py b/text2ipc/index/store.py new file mode 100644 index 0000000000000000000000000000000000000000..ebd56032fcc796f06a8393493334a4293b5b75b7 --- /dev/null +++ b/text2ipc/index/store.py @@ -0,0 +1,130 @@ +"""One Parquet index per (IPC version, scheme language, embedding model). + +The index carries only what depends on the model: ``symbol``, ``path`` (the ``|``-joined +symbol chain the text was built from), ``text_hash`` and the vector as float32 columns +``e000 .. eNNN``. Titles live in the scheme table (``SchemeTable``), so the same text +is rendered for display and for hashing. Metadata (version, language, model, +dimension, build time) is stored in the Parquet schema metadata under ``text2ipc``. + +Rows keep the scheme's depth-first order, so every parent precedes its children; the +search code relies on that. +""" + +from __future__ import annotations + +import datetime as dt +import json +from dataclasses import asdict, dataclass +from pathlib import Path + +import numpy as np +import pyarrow as pa +import pyarrow.parquet as pq + +from ..config import LEVELS +from ..scheme.model import SYMBOL_SEPARATOR, IpcNode, text_hash +from ..scheme.table import SchemeTable + +META_KEY = b"text2ipc" + + +@dataclass(frozen=True) +class IndexMeta: + version: str + lang: str + model: str + dim: int + rows: int + built_at: str + titles_overlay: str | None = None + + @classmethod + def now(cls, **kwargs) -> IndexMeta: + return cls(built_at=dt.datetime.now(dt.UTC).isoformat(timespec="seconds"), **kwargs) + + +def vector_columns(dim: int) -> list[str]: + width = max(3, len(str(dim - 1))) + return [f"e{i:0{width}d}" for i in range(dim)] + + +class IpcIndex: + """Scheme table + aligned vectors, plus the derived hierarchy arrays.""" + + def __init__( + self, + meta: IndexMeta, + scheme: SchemeTable, + vectors: np.ndarray, + hashes: list[str] | None = None, + ): + if vectors.shape != (len(scheme), meta.dim): + raise ValueError(f"vectors {vectors.shape} do not match {len(scheme)} x {meta.dim}") + self.meta = meta + self.scheme = scheme + self.nodes: list[IpcNode] = scheme.nodes + self.vectors = np.ascontiguousarray(vectors, dtype=np.float32) + self.texts = scheme.texts() + self.hashes_list = hashes or [text_hash(t) for t in self.texts] + self.symbols = [n.symbol for n in self.nodes] + self.position = scheme.position + self.levels = np.array([LEVELS.index(n.level) for n in self.nodes], dtype=np.int8) + self.parent_idx = np.array( + [self.position[n.parent] if n.parent else -1 for n in self.nodes], dtype=np.int64 + ) + if np.any(self.parent_idx >= np.arange(len(self.nodes))): + raise ValueError("Index rows must be in depth-first order (parents before children)") + self.children: list[list[int]] = [[] for _ in self.nodes] + for i, p in enumerate(self.parent_idx): + if p >= 0: + self.children[p].append(i) + + def __len__(self) -> int: + return len(self.nodes) + + def hashes(self) -> dict[str, str]: + return dict(zip(self.symbols, self.hashes_list, strict=True)) + + def node(self, symbol: str) -> IpcNode: + return self.scheme.node(symbol) + + def text_of(self, symbol: str) -> str: + return self.texts[self.position[symbol]] + + # -- persistence --------------------------------------------------------------- + + def write(self, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + columns: dict[str, object] = { + "symbol": pa.array(self.symbols), + "path": pa.array([SYMBOL_SEPARATOR.join(p) for p in self.scheme.paths]), + "text_hash": pa.array(self.hashes_list), + } + for j, name in enumerate(vector_columns(self.meta.dim)): + columns[name] = pa.array(self.vectors[:, j], type=pa.float32()) + table = pa.table(columns).replace_schema_metadata( + {META_KEY: json.dumps(asdict(self.meta)).encode()} + ) + pq.write_table(table, path, compression="zstd") + + @staticmethod + def read_meta(path: Path) -> IndexMeta: + raw = pq.read_schema(path).metadata or {} + if META_KEY not in raw: + raise ValueError(f"{path} carries no text2ipc metadata") + return IndexMeta(**json.loads(raw[META_KEY])) + + @classmethod + def read(cls, path: Path, scheme: SchemeTable | Path) -> IpcIndex: + meta = cls.read_meta(path) + if isinstance(scheme, Path): + scheme = SchemeTable.read(scheme) + table = pq.read_table(path) + symbols = table.column("symbol").to_pylist() + if symbols != [n.symbol for n in scheme.nodes]: + raise ValueError(f"{path.name} rows do not match the scheme table") + cols = vector_columns(meta.dim) + vectors = np.column_stack( + [table.column(c).to_numpy(zero_copy_only=False) for c in cols] + ).astype(np.float32, copy=False) + return cls(meta, scheme, vectors, table.column("text_hash").to_pylist()) diff --git a/text2ipc/rerank/__init__.py b/text2ipc/rerank/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fc0fc24f784b37a07c25c008d4ddca45b607f468 --- /dev/null +++ b/text2ipc/rerank/__init__.py @@ -0,0 +1,3 @@ +from .base import Reranker, fuse, get_reranker, sigmoid + +__all__ = ["Reranker", "fuse", "get_reranker", "sigmoid"] diff --git a/text2ipc/rerank/base.py b/text2ipc/rerank/base.py new file mode 100644 index 0000000000000000000000000000000000000000..989b25e4752391761f37412914b69c81cacab444 --- /dev/null +++ b/text2ipc/rerank/base.py @@ -0,0 +1,72 @@ +"""Second stage: a cross-encoder judges every (text, entry path) pair of the first +stage's candidates and the two scores are fused. + +A reranker is selected by a spec string ``:``: + +- ``ce:BAAI/bge-reranker-v2-m3`` sentence-transformers CrossEncoder (default) +- ``hash:64`` bag-of-words overlap, for tests only + +Measured on the evals (docs/evals.md): over the top-50 of e5-base on the Portuguese +scheme, bge-reranker-v2-m3 lifts subclass@1 from 23.6% to 32.3%. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Protocol, runtime_checkable + +import numpy as np + +FUSIONS = ("blend", "judge", "product") + + +@runtime_checkable +class Reranker(Protocol): + @property + def name(self) -> str: + """Full spec string.""" + + def score(self, query: str, texts: Sequence[str]) -> np.ndarray: + """One relevance logit per text, higher is better (``sigmoid`` maps to 0..1).""" + + +def get_reranker(spec: str | Reranker, **kwargs) -> Reranker: + if not isinstance(spec, str): + return spec + backend, _, model = spec.partition(":") + if not model: + raise ValueError(f"Reranker spec must look like 'backend:model', got {spec!r}") + if backend == "ce": + from .st import CrossEncoderReranker + + return CrossEncoderReranker(model, **kwargs) + if backend == "hash": + from .hashing import HashReranker + + return HashReranker(int(model)) + raise ValueError(f"Unknown reranker backend {backend!r}") + + +def sigmoid(x: np.ndarray) -> np.ndarray: + x = np.asarray(x, dtype=np.float64) + return 1.0 / (1.0 + np.exp(-x)) + + +def fuse(scores: np.ndarray, logits: np.ndarray, how: str = "blend") -> np.ndarray: + """Combine first-stage scores with the judge's logits. + + - ``blend``: ``score * (0.5 + 0.5 * sigmoid(logit))``, the default: the judge + can halve a score but the cosine still orders ties, and the result stays + comparable with unreranked scores. + - ``judge``: ``sigmoid(logit)`` alone. + - ``product``: ``score * sigmoid(logit)``. + """ + s = np.asarray(scores, dtype=np.float64) + j = sigmoid(logits) + if how == "blend": + return s * (0.5 + 0.5 * j) + if how == "judge": + return j + if how == "product": + return s * j + raise ValueError(f"fusion must be one of {FUSIONS}, got {how!r}") diff --git a/text2ipc/rerank/hashing.py b/text2ipc/rerank/hashing.py new file mode 100644 index 0000000000000000000000000000000000000000..efa21fb301111e928904d3cc617729b344d58790 --- /dev/null +++ b/text2ipc/rerank/hashing.py @@ -0,0 +1,26 @@ +"""Deterministic reranker for tests: bag-of-words cosine between query and text, +stretched to a logit-like range so that ``sigmoid`` spans 0..1.""" + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np + +from ..embeddings.hashing import HashEmbedder + + +class HashReranker: + def __init__(self, dim: int = 64): + self._embedder = HashEmbedder(dim) + + @property + def name(self) -> str: + return f"hash:{self._embedder.dim}" + + def score(self, query: str, texts: Sequence[str]) -> np.ndarray: + if not texts: + return np.zeros(0, dtype=np.float32) + q = self._embedder.embed_query(query) + cos = self._embedder.embed_passages(texts) @ q + return (8.0 * (cos - 0.5)).astype(np.float32) diff --git a/text2ipc/rerank/st.py b/text2ipc/rerank/st.py new file mode 100644 index 0000000000000000000000000000000000000000..b32a45b19fcc222d169bed7237173c3d65fb1387 --- /dev/null +++ b/text2ipc/rerank/st.py @@ -0,0 +1,77 @@ +"""sentence-transformers CrossEncoder backend (``pip install text2ipc[st]``). + +The CrossEncoder API was renamed in sentence-transformers 4.0 (``automodel_args`` to +``model_kwargs``, ``activation_fct`` to ``activation_fn``); both generations are +supported by reading the installed signatures once. +""" + +from __future__ import annotations + +import inspect +from collections.abc import Sequence + +import numpy as np + + +def _pick(signature: inspect.Signature, *names: str) -> str | None: + """The first of ``names`` the callable accepts, or None.""" + params = signature.parameters + if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()): + return names[0] + return next((n for n in names if n in params), None) + + +class CrossEncoderReranker: + def __init__( + self, + model: str, + *, + max_length: int = 768, + batch_size: int = 32, + device: str | None = None, + ): + try: + import torch + from sentence_transformers import CrossEncoder + except ImportError as e: # pragma: no cover + raise ImportError("Install the 'st' extra: uv add 'text2ipc[st]'") from e + if device is None: + device = ( + "cuda" + if torch.cuda.is_available() + else "mps" + if torch.backends.mps.is_available() + else "cpu" + ) + dtype = torch.float16 if device in ("cuda", "mps") else torch.float32 + self._model_name = model + self._batch_size = batch_size + self._identity = torch.nn.Identity() + + init_kw = _pick(inspect.signature(CrossEncoder.__init__), "model_kwargs", "automodel_args") + self._activation_kw = _pick( + inspect.signature(CrossEncoder.predict), "activation_fn", "activation_fct" + ) + if init_kw is None or self._activation_kw is None: + raise ImportError( + "This sentence-transformers version has an unknown CrossEncoder API; " + "install sentence-transformers>=3.0" + ) + kwargs = {"device": device, "max_length": max_length, init_kw: {"torch_dtype": dtype}} + self._model = CrossEncoder(model, **kwargs) + + @property + def name(self) -> str: + return f"ce:{self._model_name}" + + def score(self, query: str, texts: Sequence[str]) -> np.ndarray: + if not texts: + return np.zeros(0, dtype=np.float32) + out = self._model.predict( + [(query, t) for t in texts], + batch_size=self._batch_size, + show_progress_bar=False, + convert_to_numpy=True, + **{self._activation_kw: self._identity}, # raw logits, not the default sigmoid + ) + return np.asarray(out, dtype=np.float32).reshape(-1) diff --git a/text2ipc/scheme/__init__.py b/text2ipc/scheme/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7d18f98c74d9d578f995d48c5a50a2c2b06c0bb7 --- /dev/null +++ b/text2ipc/scheme/__init__.py @@ -0,0 +1,22 @@ +from .download import fetch_scheme, scheme_url +from .inpi import fetch_inpi_titles +from .model import IpcNode, text_hash +from .overlay import apply_titles, load_titles_csv +from .parse import parse_scheme +from .symbols import format_symbol, level_of_symbol, normalize_symbol +from .table import SchemeTable + +__all__ = [ + "IpcNode", + "SchemeTable", + "text_hash", + "apply_titles", + "fetch_inpi_titles", + "fetch_scheme", + "format_symbol", + "level_of_symbol", + "load_titles_csv", + "normalize_symbol", + "parse_scheme", + "scheme_url", +] diff --git a/text2ipc/scheme/download.py b/text2ipc/scheme/download.py new file mode 100644 index 0000000000000000000000000000000000000000..f6709c723b91fcc3ba0e2793629266210763be8e --- /dev/null +++ b/text2ipc/scheme/download.py @@ -0,0 +1,50 @@ +"""Fetch and cache WIPO IPC scheme master files.""" + +from __future__ import annotations + +import io +import zipfile +from pathlib import Path + +import httpx + +from ..config import WIPO_BASE_URL, WIPO_LANGS, home + + +def scheme_url(version: str) -> str: + return f"{WIPO_BASE_URL}/{version}/MasterFiles/ipc_scheme_{version}.zip" + + +def scheme_path(version: str, lang: str = "EN", root: Path | None = None) -> Path: + """Raw WIPO master file, kept under ``wipo/``; derived tables go to ``scheme/``.""" + return (root or home()) / "wipo" / f"{lang.upper()}_ipc_scheme_{version}.xml" + + +def fetch_scheme( + version: str, + lang: str = "EN", + *, + root: Path | None = None, + force: bool = False, + timeout: float = 300.0, +) -> Path: + """Return the local path of ``_ipc_scheme_.xml``, downloading if needed. + + The zip holds every language WIPO ships, so one download serves all of them. + """ + lang = lang.upper() + if lang not in WIPO_LANGS: + raise ValueError(f"WIPO master files are only published in {WIPO_LANGS}, not {lang}") + target = scheme_path(version, lang, root) + if target.exists() and not force: + return target + target.parent.mkdir(parents=True, exist_ok=True) + resp = httpx.get(scheme_url(version), timeout=timeout, follow_redirects=True) + resp.raise_for_status() + with zipfile.ZipFile(io.BytesIO(resp.content)) as zf: + for name in zf.namelist(): + if name.endswith(".xml"): + (target.parent / Path(name).name).write_bytes(zf.read(name)) + if not target.exists(): + raise FileNotFoundError(f"{target.name} not found in {scheme_url(version)}") + return target diff --git a/text2ipc/scheme/inpi.py b/text2ipc/scheme/inpi.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb92e13d07859dcb0b390b8e8bd981e722d2253 --- /dev/null +++ b/text2ipc/scheme/inpi.py @@ -0,0 +1,140 @@ +"""Portuguese IPC titles from INPI Brazil's IPC Publication (IPCPUB) instance. + +WIPO publishes authentic master files in English and French only. For other languages +its IPC Publication "bridges" to national offices that run the same IPCPUB software +with a translation loaded; for Portuguese that is INPI Brazil at +``https://ipc.inpi.gov.br/classifications/ipc/ipcpub/``. + +That instance serves the translated scheme as static JSON, one file per subclass plus +an index with sections, classes and subclasses:: + + /media///IPC/scheme/pt/json/index.json + /media///IPC/scheme/pt/json/.json + +The ``timestamp`` per version is embedded in the IPCPUB HTML page. Titles are HTML: +cross references sit in ```` and the edition tag in ````; both +are stripped so the result matches what :mod:`parse` extracts from the WIPO XML. + +Every JSON file is cached under ``/inpi///``; that cache is the +source of truth and titles are re-derived from it on each build (a few seconds). +""" + +from __future__ import annotations + +import json +import re +import time +from collections.abc import Callable +from pathlib import Path + +import httpx + +from ..config import home +from .symbols import normalize_symbol + +INPI_BASE = "https://ipc.inpi.gov.br/classifications/ipc/ipcpub" +_HEADERS = {"User-Agent": "Mozilla/5.0 (text2ipc)"} +_TIMESTAMPS_RE = re.compile(r"timestamps\s*:\s*\{([^}]*)\}") +_PAIR_RE = re.compile(r'"(\d{8})"\s*:\s*"(\d{14})"') +_SECTION_PREFIX_RE = re.compile(r"^\s*SE[ÇC][ÃA]O\s+[A-H]\s*[—–-]\s*", re.IGNORECASE) + + +def fetch_inpi_titles( + version: str, + *, + lang: str = "pt", + root: Path | None = None, + force: bool = False, + pause: float = 0.2, + timeout: float = 60.0, + progress: Callable[[int, int], None] | None = None, +) -> dict[str, str]: + """Return ``{canonical symbol: title}`` for every entry, from the JSON cache or INPI.""" + cache = (root or home()) / "inpi" / version / lang.lower() + if force and cache.exists(): + for f in cache.glob("*.json"): + f.unlink() + with httpx.Client(headers=_HEADERS, timeout=timeout, follow_redirects=True) as client: + stamp = _timestamp_for(client, version) + base = f"{INPI_BASE}/media/{version}/{stamp}/IPC/scheme/{lang}/json" + index = _get_json(client, f"{base}/index.json", cache / "index.json") + titles: dict[str, str] = {} + subclasses: list[str] = [] + for entry in _walk(index): + if entry.get("kind") in {"s", "c", "u"} and entry.get("symbol"): + symbol = _symbol(entry["symbol"]) + titles[symbol] = clean_title(entry.get("title1") or "", entry["kind"]) + if entry["kind"] == "u": + subclasses.append(symbol) + for i, subclass in enumerate(subclasses, 1): + cached = (cache / f"{subclass}.json").exists() + data = _get_json(client, f"{base}/{subclass}.json", cache / f"{subclass}.json") + for entry in _walk(data): + kind = entry.get("kind", "") + if (kind == "m" or kind.isdigit()) and entry.get("symbol"): + titles[_symbol(entry["symbol"])] = clean_title(entry.get("title1") or "", kind) + if progress: + progress(i, len(subclasses)) + if not cached: + time.sleep(pause) + return titles + + +def clean_title(html: str, kind: str = "") -> str: + """Strip cross references, edition tags and markup from an IPCPUB title.""" + html = re.sub(r"", " ", html, flags=re.DOTALL) + html = re.sub(r"\s*\[\d{4}\.\d{2}\]\s*", " ", html) + html = re.sub(r".*?", " ", html, flags=re.DOTALL) + if (m := re.search(r'
(.*)$', html, flags=re.DOTALL)) is not None: + html = m.group(1) + text = re.sub(r"<[^>]+>", " ", html) + text = re.sub(r"\(\s*\)", " ", text) # empty parentheses left by removed refs + text = re.sub(r"\[\d{4}\.\d{2}\]", " ", text) # edition tags printed without a link + text = " ".join(text.replace("\xa0", " ").split()) + if kind == "s": + text = _SECTION_PREFIX_RE.sub("", text) + return text.strip(" ;") + + +def _timestamp_for(client: httpx.Client, version: str) -> str: + page = client.get(f"{INPI_BASE}/", params={"notion": "scheme", "version": version}) + page.raise_for_status() + m = _TIMESTAMPS_RE.search(page.text) + stamps = dict(_PAIR_RE.findall(m.group(1))) if m else {} + if version not in stamps: + raise RuntimeError( + f"INPI IPCPUB has no Portuguese data for IPC {version}; available: {sorted(stamps)}" + ) + return stamps[version] + + +def _get_json(client: httpx.Client, url: str, cache_file: Path, attempts: int = 10): + """Fetch with retries and exponential backoff; INPI answers 503 now and then. + + Every file is cached raw on disk, so an interrupted run resumes where it stopped. + """ + if cache_file.exists(): + return json.loads(cache_file.read_text(encoding="utf-8")) + last: Exception | None = None + for attempt in range(attempts): + try: + resp = client.get(url) + resp.raise_for_status() + data = resp.json() + cache_file.parent.mkdir(parents=True, exist_ok=True) + cache_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") + return data + except (httpx.TransportError, httpx.HTTPStatusError, json.JSONDecodeError) as e: + last = e + time.sleep(min(2.0**attempt, 60.0)) + raise RuntimeError(f"Could not fetch {url}") from last + + +def _walk(items): + for item in items or []: + yield item + yield from _walk(item.get("children")) + + +def _symbol(raw: str) -> str: + return normalize_symbol(raw.replace("\xa0", " ")) diff --git a/text2ipc/scheme/model.py b/text2ipc/scheme/model.py new file mode 100644 index 0000000000000000000000000000000000000000..150d5d3438a8fa5d8e09a661ca3738007d1797fe --- /dev/null +++ b/text2ipc/scheme/model.py @@ -0,0 +1,25 @@ +"""The unit of the IPC hierarchy as this package sees it.""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass + +PATH_SEPARATOR = " > " +SYMBOL_SEPARATOR = "|" + + +@dataclass(frozen=True) +class IpcNode: + """One classifiable IPC entry (section, class, subclass, main group or subgroup).""" + + symbol: str # canonical WIPO form, e.g. A01B0001020000 or A01B + level: str # one of config.LEVELS + depth: int # dot level for subgroups (1 = one dot), 0 otherwise + parent: str | None # canonical symbol of the parent entry, None for sections + title: str # this entry's own title, reference notes stripped + heading: str = "" # guidance heading the entry sits under (main groups only) + + +def text_hash(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16] diff --git a/text2ipc/scheme/overlay.py b/text2ipc/scheme/overlay.py new file mode 100644 index 0000000000000000000000000000000000000000..1365fba250ecce273b766a3fd989d958611ff923 --- /dev/null +++ b/text2ipc/scheme/overlay.py @@ -0,0 +1,34 @@ +"""Replace entry titles with a translation supplied as ``symbol,title`` rows. + +WIPO master files exist in English and French. Other languages (Portuguese via INPI +Brazil, for example) come as title tables. Entries missing from the table keep their +original title, so partial translations degrade gracefully. Guidance headings have no +symbol and stay in the source language. +""" + +from __future__ import annotations + +import csv +from dataclasses import replace +from pathlib import Path + +from .model import IpcNode +from .symbols import normalize_symbol + + +def load_titles_csv(path: Path | str) -> dict[str, str]: + mapping: dict[str, str] = {} + with open(path, newline="", encoding="utf-8") as fh: + reader = csv.DictReader(fh) + if not reader.fieldnames or {"symbol", "title"} - set(reader.fieldnames): + raise ValueError(f"{path}: expected columns 'symbol' and 'title'") + for row in reader: + title = (row["title"] or "").strip() + if title: + mapping[normalize_symbol(row["symbol"])] = " ".join(title.split()) + return mapping + + +def apply_titles(nodes: list[IpcNode], titles: dict[str, str]) -> list[IpcNode]: + titles = {normalize_symbol(k): v for k, v in titles.items()} + return [replace(n, title=titles.get(n.symbol, n.title)) for n in nodes] diff --git a/text2ipc/scheme/parse.py b/text2ipc/scheme/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b990363ab53ca5876ab45f79efa70291411a445e --- /dev/null +++ b/text2ipc/scheme/parse.py @@ -0,0 +1,76 @@ +"""Turn a WIPO ``ipc_scheme`` XML file into a flat, ordered list of :class:`IpcNode`. + +Entries nest physically in the XML (subgroups inside their main group, groups inside +the subclass...). Alongside the classifiable entries there are: + +- ``t`` subsection titles (plain headings between classes, no symbol of their own) +- ``g`` guidance headings that span a range of main groups +- ``n`` notes +- ``i`` catchword indexes + +None of those are classification targets. Guidance headings are kept as context for +the entries that sit under them; the rest are skipped. +""" + +from __future__ import annotations + +import xml.etree.ElementTree as ET +from collections.abc import Iterator +from pathlib import Path + +from .model import IpcNode +from .symbols import level_of_kind + +NS = "{http://www.wipo.int/classifications/ipc/masterfiles}" +TITLE_PART_SEPARATOR = "; " + + +def parse_scheme(path: Path | str) -> list[IpcNode]: + """Entries in depth-first order, so every parent precedes its children.""" + root = ET.parse(path).getroot() + return list(_walk(root, parent=None)) + + +def _walk(element: ET.Element, *, parent: str | None) -> Iterator[IpcNode]: + heading: tuple[str, str] | None = None # (title, last symbol it covers) + for child in element: + if child.tag != f"{NS}ipcEntry": + continue + kind = child.get("kind", "") + level = level_of_kind(kind) + if level is None: + if kind == "g": + # A guidance heading is an empty leaf in the XML covering the sibling + # main groups from ``symbol`` to ``endSymbol``. + heading = (_title_of(child), child.get("endSymbol") or child.get("symbol", "")) + continue + symbol = child.get("symbol", "") + under_heading = heading is not None and level == "group" and symbol <= heading[1] + yield IpcNode( + symbol=symbol, + level=level, + depth=int(kind) if kind.isdigit() else 0, + parent=parent, + title=_title_of(child), + heading=heading[0] if under_heading and heading else "", + ) + yield from _walk(child, parent=symbol) + + +def _title_of(entry: ET.Element) -> str: + """Join the title parts, dropping cross references such as "(edge trimmers A01G 3/06)". + + Cross references point *away* from the entry; embedding them would attract exactly + the texts that belong elsewhere. + """ + body = entry.find(f"{NS}textBody/{NS}title") + if body is None: + return "" + parts = [] + for part in body.findall(f"{NS}titlePart"): + text = part.find(f"{NS}text") + if text is not None: + value = "".join(text.itertext()).strip() + if value: + parts.append(" ".join(value.split())) + return TITLE_PART_SEPARATOR.join(parts) diff --git a/text2ipc/scheme/symbols.py b/text2ipc/scheme/symbols.py new file mode 100644 index 0000000000000000000000000000000000000000..3b24d73af96829fc26900817d2a9bde374e8d1a2 --- /dev/null +++ b/text2ipc/scheme/symbols.py @@ -0,0 +1,59 @@ +"""IPC symbol formats. + +WIPO master files use a fixed 14-character form: subclass (4) + main group (4, zero +padded) + subgroup (6, zero padded). ``A01B0001020000`` is ``A01B 1/02``. Sections, +classes and subclasses are 1, 3 and 4 characters respectively. +""" + +from __future__ import annotations + +import re + +_CANON_RE = re.compile(r"^[A-H](\d{2}([A-Z](\d{4}\d{6})?)?)?$") +_PRETTY_RE = re.compile(r"^([A-H]\d{2}[A-Z])\s*(\d{1,4})/(\d{2,6})$") + +_KIND_TO_LEVEL = {"s": "section", "c": "class", "u": "subclass", "m": "group"} + + +def level_of_kind(kind: str) -> str | None: + """Map a WIPO ``kind`` attribute to a level, or None for non-classifiable kinds.""" + if kind in _KIND_TO_LEVEL: + return _KIND_TO_LEVEL[kind] + if kind.isdigit(): + return "subgroup" + return None + + +def level_of_symbol(symbol: str) -> str: + n = len(symbol) + if n == 1: + return "section" + if n == 3: + return "class" + if n == 4: + return "subclass" + if n == 14: + return "group" if symbol[8:] == "000000" else "subgroup" + raise ValueError(f"Not a canonical IPC symbol: {symbol!r}") + + +def normalize_symbol(symbol: str) -> str: + """Accept ``A01B 1/02``, ``A01B1/02`` or canonical form; return canonical form.""" + s = symbol.strip().upper() + if _CANON_RE.match(s): + return s + if m := _PRETTY_RE.match(s): + sub, group, subgroup = m.groups() + return f"{sub}{int(group):04d}{subgroup.ljust(6, '0')}" + raise ValueError(f"Unrecognised IPC symbol: {symbol!r}") + + +def format_symbol(symbol: str) -> str: + """Canonical -> human form: ``A01B0001020000`` -> ``A01B 1/02``.""" + if len(symbol) != 14: + return symbol + sub, group, subgroup = symbol[:4], symbol[4:8], symbol[8:] + subgroup = subgroup.rstrip("0") + if len(subgroup) < 2: + subgroup = subgroup.ljust(2, "0") + return f"{sub} {int(group)}/{subgroup}" diff --git a/text2ipc/scheme/table.py b/text2ipc/scheme/table.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f217de1b86a67dd7f677b924575edec01351e3 --- /dev/null +++ b/text2ipc/scheme/table.py @@ -0,0 +1,111 @@ +"""The scheme as a table: one row per entry, with the symbol path to the root. + +This is what gets embedded and what is shown to users. The text of an entry is the +concatenation, top-down, of the titles along its path (section > class > subclass > +main group > subgroup > ... > the entry), with the guidance heading inserted before a +main group that sits under one. A subgroup's vector is the embedding of that whole +text, never of its own title alone. + +Stored as ``scheme/ipc__.parquet`` with columns +``symbol, level, depth, parent, title, heading, path`` where ``path`` is the +``|``-joined chain of canonical symbols from the section to the entry. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path + +import pyarrow as pa +import pyarrow.parquet as pq + +from .model import PATH_SEPARATOR, SYMBOL_SEPARATOR, IpcNode, text_hash + +COLUMNS = ("symbol", "level", "depth", "parent", "title", "heading", "path") + + +@dataclass +class SchemeTable: + nodes: list[IpcNode] + paths: list[tuple[str, ...]] # symbols from section to self, aligned with nodes + + def __post_init__(self): + self.position = {n.symbol: i for i, n in enumerate(self.nodes)} + + @classmethod + def from_nodes(cls, nodes: list[IpcNode]) -> SchemeTable: + paths: dict[str, tuple[str, ...]] = {} + out = [] + for n in nodes: # parents precede children in scheme order + if n.parent is None: + path: tuple[str, ...] = (n.symbol,) + else: + path = (*paths[n.parent], n.symbol) + paths[n.symbol] = path + out.append(path) + return cls(nodes, out) + + def __len__(self) -> int: + return len(self.nodes) + + def __iter__(self) -> Iterator[IpcNode]: + return iter(self.nodes) + + def node(self, symbol: str) -> IpcNode: + return self.nodes[self.position[symbol]] + + def path_of(self, symbol: str) -> tuple[str, ...]: + return self.paths[self.position[symbol]] + + def text_of(self, symbol: str) -> str: + return self.text_at(self.position[symbol]) + + def text_at(self, i: int) -> str: + parts = [] + for s in self.paths[i]: + n = self.nodes[self.position[s]] + if n.heading: + parts.append(n.heading) + parts.append(n.title) + return PATH_SEPARATOR.join(p for p in parts if p) + + def texts(self) -> list[str]: + return [self.text_at(i) for i in range(len(self.nodes))] + + def hashes(self) -> list[str]: + return [text_hash(t) for t in self.texts()] + + # -- persistence --------------------------------------------------------------- + + def write(self, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + table = pa.table( + { + "symbol": [n.symbol for n in self.nodes], + "level": [n.level for n in self.nodes], + "depth": pa.array([n.depth for n in self.nodes], type=pa.int8()), + "parent": [n.parent for n in self.nodes], + "title": [n.title for n in self.nodes], + "heading": [n.heading for n in self.nodes], + "path": [SYMBOL_SEPARATOR.join(p) for p in self.paths], + } + ) + pq.write_table(table, path, compression="zstd") + + @classmethod + def read(cls, path: Path) -> SchemeTable: + t = pq.read_table(path, columns=list(COLUMNS)).to_pydict() + nodes = [ + IpcNode( + symbol=t["symbol"][i], + level=t["level"][i], + depth=int(t["depth"][i]), + parent=t["parent"][i] or None, + title=t["title"][i], + heading=t["heading"][i] or "", + ) + for i in range(len(t["symbol"])) + ] + paths = [tuple(p.split(SYMBOL_SEPARATOR)) for p in t["path"]] + return cls(nodes, paths) diff --git a/text2ipc/search/__init__.py b/text2ipc/search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5279b17466cbb97f43b9b4cb47b7d61d43b9429 --- /dev/null +++ b/text2ipc/search/__init__.py @@ -0,0 +1,3 @@ +from .scorer import Beam, Match, SearchParams, Weights, search + +__all__ = ["Beam", "Match", "SearchParams", "Weights", "search"] diff --git a/text2ipc/search/scorer.py b/text2ipc/search/scorer.py new file mode 100644 index 0000000000000000000000000000000000000000..ecfcd3e086f6916766d2ecb9a5f85b5ababd960d --- /dev/null +++ b/text2ipc/search/scorer.py @@ -0,0 +1,239 @@ +"""Hierarchical scoring on top of flat cosine similarity. + +Flat nearest-neighbour over 80k entries has two failure modes: deep entries with long +specific texts win on word overlap alone, and an isolated hit in an unrelated subtree +can outrank a well-supported one. Three heuristics address that: + +1. **Path support** - the mean similarity of an entry's ancestors. A good subgroup + usually sits under a good group, subclass and class. +2. **Subtree support** - the best similarity anywhere below an entry. A class whose + subtree lights up is more plausible than one where only the class title matches. +3. **Beam descent** - candidates at a level are only considered under the top-``b`` + parents of the level above. A parent is ranked by the best composite score anywhere + in its subtree, never by its own title (section and class titles are too generic to + score), so the flat best candidate always survives pruning and the beam only removes + candidates from weakly supported branches. + +The final score is a weighted sum of own similarity, path support and subtree support. +``level="auto"`` walks down from the best subclasses along the best-scoring branch +and answers with the best node on that walk, which yields "as detailed as the +evidence supports". + +**Branch de-duplication** runs last: the top-``k`` results are walked in rank order +and a result is dropped when it lies on the same branch as one already accepted, +i.e. it is an ancestor or a descendant of it. A subgroup nested inside the best +subgroup adds nothing a user could not read off the best one's path, so the list +keeps only distinct branches. The answer may therefore hold fewer than ``k`` rows. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from dataclasses import dataclass, field + +import numpy as np + +from ..config import AUTO_LEVEL, LEVELS +from ..index.store import IpcIndex +from ..scheme.symbols import format_symbol + + +@dataclass(frozen=True) +class Weights: + """Defaults come from the sweeps in docs/evals.md. On the Portuguese scheme path + support lowers every hit rate for both e5 models (section and class titles are + generic and close to every query), so it is off by default since 2026-10-08; it + helped on the English scheme with e5-small. Subtree support is kept for + experiments; beam selection already uses it.""" + + own: float = 1.0 + path: float = 0.0 + subtree: float = 0.0 + + +@dataclass(frozen=True) +class Beam: + """How many parents survive at each level before descending.""" + + section: int = 5 + class_: int = 10 + subclass: int = 20 + group: int = 40 + + def width(self, level: str) -> int: + return getattr(self, "class_" if level == "class" else level) + + +@dataclass(frozen=True) +class SearchParams: + level: str = "subgroup" + top_k: int = 10 + weights: Weights = field(default_factory=Weights) + beam: Beam = field(default_factory=Beam) + #: Drop results scoring more than this below the best one (None keeps top_k). + gap: float | None = None + #: ``auto`` level: descend while best child >= parent - margin. + auto_margin: float = 0.02 + #: ``auto`` level: how many subclasses to start descending from; each yields at most + #: one result, so ``None`` means ``max(5, top_k)`` and ``top_k`` is honoured. + auto_roots: int | None = None + #: Drop results that are ancestors or descendants of a higher-ranked result. + dedupe_branches: bool = True + + +@dataclass(frozen=True) +class Match: + symbol: str + level: str + depth: int + title: str + text: str + score: float + similarity: float + path_support: float + subtree_support: float + #: Reranker verdict in 0..1 when a second stage ran, else None. + judge: float | None = None + + @property + def pretty(self) -> str: + return format_symbol(self.symbol) + + +def search(index: IpcIndex, query: np.ndarray, params: SearchParams | None = None) -> list[Match]: + """Rank entries for a unit query vector, or for a ``(chunks, dim)`` stack of them.""" + params = params or SearchParams() + if params.level != AUTO_LEVEL and params.level not in LEVELS: + raise ValueError(f"level must be one of {LEVELS} or {AUTO_LEVEL!r}") + + q = np.asarray(query, dtype=np.float32) + # a (chunks, dim) stack comes from a long text: an entry scores by its best chunk + sims = index.vectors @ q if q.ndim == 1 else (index.vectors @ q.T).max(axis=1) + path = _path_support(index, sims) + subtree = _subtree_support(index, sims) + w = params.weights + score = w.own * sims + w.path * path + w.subtree * subtree + + best_below = _subtree_support(index, score) + + if params.level == AUTO_LEVEL: + chosen = _auto_descend(index, sims, score, best_below, params) + else: + chosen = _beam_descend(index, best_below, params.level, params.beam) + chosen = sorted(chosen, key=lambda i: -score[i])[: params.top_k] + + if params.gap is not None and chosen: + best = score[chosen[0]] + chosen = [i for i in chosen if score[i] >= best - params.gap] + if params.dedupe_branches: + chosen = _distinct_branches(index, chosen) + + return [ + Match( + symbol=index.nodes[i].symbol, + level=index.nodes[i].level, + depth=index.nodes[i].depth, + title=index.nodes[i].title, + text=index.texts[i], + score=float(score[i]), + similarity=float(sims[i]), + path_support=float(path[i]), + subtree_support=float(subtree[i]), + ) + for i in chosen + ] + + +def _distinct_branches(index: IpcIndex, ranked: list[int]) -> list[int]: + """Keep a result only if no accepted result sits on its path or below it.""" + accepted: list[int] = [] + accepted_chains: list[set[str]] = [] + for i in ranked: + chain = set(index.scheme.paths[i]) + symbol = index.symbols[i] + same_branch = any( + index.symbols[a] in chain or symbol in a_chain + for a, a_chain in zip(accepted, accepted_chains, strict=True) + ) + if not same_branch: + accepted.append(i) + accepted_chains.append(chain) + return accepted + + +def _path_support(index: IpcIndex, sims: np.ndarray) -> np.ndarray: + """Mean similarity of the ancestors; equals own similarity for roots.""" + total = np.zeros_like(sims) + count = np.zeros(len(sims), dtype=np.int32) + for i, p in enumerate(index.parent_idx): # parents precede children + if p >= 0: + total[i] = total[p] + sims[p] + count[i] = count[p] + 1 + return np.where(count > 0, total / np.maximum(count, 1), sims) + + +def _subtree_support(index: IpcIndex, sims: np.ndarray) -> np.ndarray: + """Max similarity over the node and everything below it.""" + best = sims.copy() + parents = index.parent_idx + for i in range(len(sims) - 1, -1, -1): # children precede parents in reverse + p = parents[i] + if p >= 0 and best[i] > best[p]: + best[p] = best[i] + return best + + +def _beam_descend(index: IpcIndex, best_below: np.ndarray, target: str, beam: Beam) -> list[int]: + """Walk down from the sections, keeping the parents whose subtree scores best.""" + target_rank = LEVELS.index(target) + frontier = [i for i in range(len(index)) if index.levels[i] == 0] # sections + for rank, level in enumerate(LEVELS): + if rank == target_rank: + return frontier + frontier = sorted(frontier, key=lambda i: -best_below[i])[: beam.width(level)] + next_level = LEVELS[rank + 1] + if next_level == "subgroup": + frontier = list(_descendants(index, frontier)) + else: + frontier = [c for i in frontier for c in index.children[i]] + return frontier + + +def _descendants(index: IpcIndex, roots: Iterable[int]) -> Iterable[int]: + stack = list(roots) + while stack: + i = stack.pop() + for c in index.children[i]: + yield c + stack.append(c) + + +def _auto_descend( + index: IpcIndex, + sims: np.ndarray, + score: np.ndarray, + best_below: np.ndarray, + params: SearchParams, +) -> list[int]: + """From the best subclasses, walk down the branch with the best subtree score while + that subtree still promises something within ``auto_margin`` of the current node, + then answer with the node on the walked path whose *own* similarity is highest + (deepest on ties). Own similarity is used because composite scores are not + comparable across levels: deeper nodes inherit path support from their ancestors.""" + n_roots = params.auto_roots if params.auto_roots is not None else max(5, params.top_k) + roots = _beam_descend(index, best_below, "subclass", params.beam) + roots = sorted(roots, key=lambda i: -best_below[i])[:n_roots] + out: list[int] = [] + for i in roots: + path = [i] + node = i + while index.children[node]: + best_child = max(index.children[node], key=lambda c: best_below[c]) + if best_below[best_child] < score[node] - params.auto_margin: + break + node = best_child + path.append(node) + best = max(reversed(path), key=lambda j: sims[j]) + if best not in out: + out.append(best) + return sorted(out, key=lambda i: -score[i])[: params.top_k] diff --git a/text2ipc/textnorm.py b/text2ipc/textnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..276987e2db74b2f533154b0deff62c42c86dbf34 --- /dev/null +++ b/text2ipc/textnorm.py @@ -0,0 +1,30 @@ +"""Small text normalisations shared by scheme texts and queries.""" + +from __future__ import annotations + +import re + +_PARAGRAPH = re.compile(r"\n\s*\n") + + +def paragraphs(text: str) -> list[str]: + """Non-empty parts separated by a blank line; single newlines do not split.""" + return [p for p in _PARAGRAPH.split(text) if p.strip()] + + +def collapse_whitespace(text: str) -> str: + """Collapse runs of whitespace inside each paragraph; keep blank lines as breaks.""" + return "\n\n".join(" ".join(p.split()) for p in paragraphs(text)) + + +def lowercase_if_shouting(text: str, threshold: float = 0.6) -> str: + """Lower-case text whose letters are mostly upper case; leave mixed case alone. + + IPC section, class and subclass titles and RPI titles are printed in capitals, + which multilingual tokenizers split badly. "DNA" inside a sentence-case title + stays as is. + """ + letters = [c for c in text if c.isalpha()] + if letters and sum(c.isupper() for c in letters) / len(letters) > threshold: + return text.lower() + return text diff --git a/text2ipc/versions.py b/text2ipc/versions.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab9ad228edef8695448c6db0def332acb5030a6 --- /dev/null +++ b/text2ipc/versions.py @@ -0,0 +1,82 @@ +"""Discover published IPC versions. + +WIPO publishes one directory per version named ``YYYYMMDD`` under the IT support area. +The next year's version is usually published months before it enters into force, so +``latest`` (newest published) and ``current`` (newest in force today) can differ. +""" + +from __future__ import annotations + +import datetime as dt +import re +from pathlib import Path + +import httpx + +from .config import WIPO_BASE_URL, home + +_VERSION_RE = re.compile(r"/(\d{8})/") + + +def parse_version_index(html: str) -> list[str]: + """Extract ``YYYYMMDD`` directory names from the WIPO index page, ascending.""" + found = {m.group(1) for m in _VERSION_RE.finditer(html)} + return sorted(v for v in found if _is_date(v)) + + +def _is_date(v: str) -> bool: + try: + dt.date(int(v[:4]), int(v[4:6]), int(v[6:])) + except ValueError: + return False + return True + + +def list_remote_versions(timeout: float = 30.0) -> list[str]: + """Versions published on wipo.int, ascending. Requires network.""" + resp = httpx.get(f"{WIPO_BASE_URL}/", timeout=timeout, follow_redirects=True) + resp.raise_for_status() + return parse_version_index(resp.text) + + +def list_local_versions(root: Path | None = None) -> list[str]: + """Versions for which a scheme XML has already been downloaded, ascending.""" + wipo_dir = (root or home()) / "wipo" + if not wipo_dir.exists(): + return [] + found = { + m.group(1) + for p in wipo_dir.glob("*_ipc_scheme_*.xml") + if (m := re.search(r"_ipc_scheme_(\d{8})\.xml$", p.name)) + } + return sorted(found) + + +def resolve_version( + spec: str = "latest", + *, + today: dt.date | None = None, + offline: bool = False, + root: Path | None = None, +) -> str: + """Turn ``latest`` / ``current`` / ``YYYYMMDD`` into a concrete version string. + + ``latest`` is the newest version WIPO has published, even if not yet in force. + ``current`` is the newest version whose date is not after ``today``. + """ + if re.fullmatch(r"\d{8}", spec): + return spec + if spec not in {"latest", "current"}: + raise ValueError(f"Unknown version spec {spec!r}; use 'latest', 'current' or YYYYMMDD") + versions = list_local_versions(root) if offline else list_remote_versions() + if not offline: + versions = sorted(set(versions) | set(list_local_versions(root))) + if not versions: + raise RuntimeError("No IPC versions found (offline and nothing downloaded yet)") + if spec == "latest": + return versions[-1] + today = today or dt.date.today() + in_force = [v for v in versions if dt.date(int(v[:4]), int(v[4:6]), int(v[6:])) <= today] + if not in_force: + raise RuntimeError(f"No IPC version in force on {today}") + return in_force[-1] diff --git a/text2ipc/web/__init__.py b/text2ipc/web/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e59a1441a4eb0f10f5cfa1c09879716b25c8b38e --- /dev/null +++ b/text2ipc/web/__init__.py @@ -0,0 +1,3 @@ +from .export import WEB_DEFAULT_MODEL, dequantize_int8, export_web_demo, quantize_int8 + +__all__ = ["WEB_DEFAULT_MODEL", "dequantize_int8", "export_web_demo", "quantize_int8"] diff --git a/text2ipc/web/export.py b/text2ipc/web/export.py new file mode 100644 index 0000000000000000000000000000000000000000..e9a94e8b9a13c02310f35d7811fd8e32c6817eac --- /dev/null +++ b/text2ipc/web/export.py @@ -0,0 +1,268 @@ +"""Assemble a static Hugging Face Space that classifies in the visitor's browser. + +Static Spaces are free; Spaces that run Python are not. So the demo ships the index +as small static files and does everything client side: ``transformers.js`` embeds +the query with the ONNX twin of the embedder, and ``scorer.js`` (a port of +``search/scorer.py``) ranks the entries. See ADR 0007. + +Layout written by :func:`export_web_demo`:: + + index.html, app.js, scorer.js the page (copied from ``web/static/``) + manifest.json embedder, query prefix, one entry per index + data//scheme.json columns symbol, level, depth, parent, title, heading + data//vectors.bin per-row float32 scales, then int8 vectors (or float32) + README.md Space front matter (sdk: static) and a description +""" + +from __future__ import annotations + +import json +import shutil +from pathlib import Path + +import numpy as np + +from .. import __version__ as package_version +from ..config import LEVELS, home +from ..embeddings.st import prefixes_for +from ..index import IpcIndex, available_indexes, scheme_table_path +from ..index.paths import IndexRef + +#: The package default. 279 MB quantised in the browser; e5-small is 118 MB but ranks +#: generic entries (fire hoses) near the top of unrelated texts (ADR 0007). Any model +#: with an ONNX twin on the Hub works. +WEB_DEFAULT_MODEL = "st:intfloat/multilingual-e5-base" + +#: sentence-transformers model -> transformers.js model (ONNX weights on the Hub). +WEB_MODELS = { + "intfloat/multilingual-e5-small": "Xenova/multilingual-e5-small", + "intfloat/multilingual-e5-base": "Xenova/multilingual-e5-base", + "intfloat/multilingual-e5-large": "Xenova/multilingual-e5-large", +} + +STATIC_FILES = ("index.html", "app.js", "scorer.js", "rerank-worker.js") + +#: Token limit the browser applies before chunking a long text (sentence-transformers +#: ``max_seq_length`` of the model); e5 models take 512. +WEB_MAX_TOKENS = {"intfloat/multilingual-e5-small": 512, "intfloat/multilingual-e5-base": 512} + +#: Cross-encoder the page offers as an opt-in second stage (ONNX on the Hub). jina v2 +#: in 8 bits equals bge-reranker-v2-m3 at @1 on the evals at half the size (docs/evals.md). +WEB_DEFAULT_RERANKER = "jinaai/jina-reranker-v2-base-multilingual" +WEB_RERANKER_DTYPE = "q8" +WEB_RERANK_CANDIDATES = 25 +WEB_RERANK_MAX_LENGTH = 768 + +SPACE_README = """--- +title: text2ipc +emoji: 🏷️ +colorFrom: blue +colorTo: green +sdk: static +app_file: index.html +pinned: false +license: mit +short_description: Patent text to IPC symbols, computed in your browser +models: +{models} +--- + +# text2ipc, in the browser + +Paste a patent abstract (Portuguese, English or any language the embedder knows) and +get a ranked list of International Patent Classification symbols. Nothing is sent to +a server: the page downloads the quantised embedder `{web_model}` ({web_dtype}) and the +IPC index once, then embeds the query and scores it against the hierarchy locally. + +Indexes in this Space: {index_list}. The "Rerank" option loads a second model, +`{reranker}` in 8 bits, that re-judges the best candidates against the text +(that model is released under CC BY-NC 4.0: this demo is non-commercial; the +package's default reranker, `BAAI/bge-reranker-v2-m3`, is Apache-2.0). + +How it works, the evaluation numbers and the Python package are at +https://github.com/Jaimenms/text2ipc. The same index runs locally with +`t2ipc classify` and as a Hugging Face Inference Endpoint. + +Data: IPC scheme master files by WIPO{data_note}. Scoring: `scorer.js` is a port of +`text2ipc/search/scorer.py`; vectors are stored as int8 with a per-row scale. +""" + + +def quantize_int8(vectors: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Symmetric per-row int8: ``v ~= q * scale`` with ``scale = max|v| / 127``.""" + v = np.asarray(vectors, dtype=np.float32) + scales = np.max(np.abs(v), axis=1) / 127.0 + scales[scales == 0] = 1.0 + q = np.clip(np.rint(v / scales[:, None]), -127, 127).astype(np.int8) + return q, scales.astype(np.float32) + + +def dequantize_int8(q: np.ndarray, scales: np.ndarray) -> np.ndarray: + return q.astype(np.float32) * np.asarray(scales, dtype=np.float32)[:, None] + + +def write_vectors(path: Path, vectors: np.ndarray, encoding: str = "int8") -> dict: + """Write ``vectors.bin``: for int8, ``rows`` little-endian float32 scales followed by + the ``rows x dim`` int8 matrix; for float32, the matrix alone.""" + rows, dim = vectors.shape + if encoding == "int8": + q, scales = quantize_int8(vectors) + payload = scales.astype(" dict[str, list]: + """The scheme table as parallel columns, rows in index order, parent as a row number.""" + return { + "symbol": index.symbols, + "level": [int(x) for x in index.levels], + "depth": [n.depth for n in index.nodes], + "parent": [int(p) for p in index.parent_idx], + "title": [n.title for n in index.nodes], + "heading": [n.heading for n in index.nodes], + } + + +def web_model_for(model: str) -> str | None: + backend, _, name = model.partition(":") + if backend != "st": + return None + return WEB_MODELS.get(name, name) + + +def export_web_demo( + out: Path, + *, + model: str = WEB_DEFAULT_MODEL, + langs: tuple[str, ...] | list[str] = ("PT",), + version: str = "latest", + root: Path | None = None, + repo_id: str = "/text2ipc", + web_model: str | None = None, + web_dtype: str = "q8", + encoding: str = "int8", + examples: Path | None = None, + web_reranker: str | None = WEB_DEFAULT_RERANKER, +) -> Path: + """Write the static Space into ``out``; one index per language, all on ``model``. + + ``version`` is resolved per language against the indexes built for ``model``. + ``examples`` is a JSONL of eval cases (``t2ipc rpi`` format); only their title and + abstract are shipped, as sample texts the page offers to fill the box with. + """ + from ..classifier import resolve_built_version + from ..embeddings.base import model_slug + + root = root or home() + web_model = web_model or web_model_for(model) + if web_model is None: + raise ValueError(f"No browser model known for {model!r}; pass web_model explicitly") + query_prefix, _ = prefixes_for(model.partition(":")[2]) + + out.mkdir(parents=True, exist_ok=True) + (out / "data").mkdir(exist_ok=True) + entries = [] + dim: int | None = None + data_notes = [] + for lang in langs: + lang = lang.upper() + built = resolve_built_version(version, lang, model, root) + ref = _find(root, built, lang, model_slug(model)) + index = IpcIndex.read(ref.path, scheme_table_path(built, lang, root)) + if dim is not None and index.meta.dim != dim: + raise ValueError("All indexes in one Space must share the embedder") + dim = index.meta.dim + d = out / "data" / lang.lower() + d.mkdir(exist_ok=True) + (d / "scheme.json").write_text(json.dumps(scheme_columns(index), ensure_ascii=False)) + vec = write_vectors(d / "vectors.bin", index.vectors, encoding) + entries.append( + { + "lang": lang, + "version": built, + "rows": vec["rows"], + "titles_overlay": index.meta.titles_overlay, + "scheme": f"data/{lang.lower()}/scheme.json", + "vectors": f"data/{lang.lower()}/vectors.bin", + "encoding": encoding, + "bytes": vec["bytes"], + } + ) + if index.meta.titles_overlay: + data_notes.append(lang) + + manifest = { + "generator": f"text2ipc {package_version}", + "model": model, + "web_model": web_model, + "web_dtype": web_dtype, + "query_prefix": query_prefix, + "max_tokens": WEB_MAX_TOKENS.get(model.partition(":")[2], 512), + "reranker": ( + { + "web_model": web_reranker, + "dtype": WEB_RERANKER_DTYPE, + "candidates": WEB_RERANK_CANDIDATES, + "max_length": WEB_RERANK_MAX_LENGTH, + "fusion": "blend", + } + if web_reranker + else None + ), + "dim": dim, + "levels": list(LEVELS), + "indexes": entries, + } + (out / "manifest.json").write_text(json.dumps(manifest, indent=2)) + + static = Path(__file__).with_name("static") + for name in STATIC_FILES: + shutil.copy2(static / name, out / name) + if examples is not None: + (out / "examples.json").write_text( + json.dumps(load_examples(examples), ensure_ascii=False, indent=1) + ) + (out / "package.json").write_text(json.dumps({"type": "module", "private": True}) + "\n") + (out / ".gitattributes").write_text("*.bin filter=lfs diff=lfs merge=lfs -text\n") + (out / "README.md").write_text( + SPACE_README.format( + models="\n".join( + f" - {m}" for m in [web_model, *([web_reranker] if web_reranker else [])] + ), + web_model=web_model, + web_dtype=web_dtype, + index_list=", ".join(f"IPC {e['version']} {e['lang']}" for e in entries), + reranker=web_reranker or "none", + data_note=( + "; Portuguese titles from INPI Brazil's IPC Publication" + if "PT" in data_notes + else "" + ), + ) + ) + return out + + +def load_examples(path: Path) -> list[dict]: + """Title and abstract of each case; nothing else reaches the page.""" + out = [] + for line in Path(path).read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + c = json.loads(line) + if not (c.get("title") and c.get("abstract")): + raise ValueError(f"example {c.get('id')} needs both a title and an abstract") + out.append({"title": c["title"], "abstract": c["abstract"]}) + return out + + +def _find(root: Path, version: str, lang: str, slug: str) -> IndexRef: + for r in available_indexes(root): + if r.version == version and r.lang == lang and r.model_slug == slug: + return r + raise FileNotFoundError(f"No index for {version} {lang} {slug} in {root}") diff --git a/text2ipc/web/static/app.js b/text2ipc/web/static/app.js new file mode 100644 index 0000000000000000000000000000000000000000..80214008efad793a05858baca4a3923e5a4fad03 --- /dev/null +++ b/text2ipc/web/static/app.js @@ -0,0 +1,706 @@ +// Browser glue for the static demo: fetch manifest + index files, load the ONNX +// embedder with transformers.js, embed the query, rank with scorer.js, and draw the +// merged paths of the results as a tree. Everything stays in the visitor's browser; +// no request carries the text anywhere. +import { env, pipeline } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.1"; +import { + AUTO_LEVEL, + LEVELS, + buildIndex, + chainOf, + formatSymbol, + meanVector, + normalizeQuery, + parseVectors, + rank, + rerankMatches, + splitText, +} from "./scorer.js"; + +env.allowLocalModels = false; + +const $ = (id) => document.getElementById(id); +const ui = { + text: $("text"), + lang: $("lang"), + level: $("level"), + topK: $("topk"), + rerank: $("rerank"), + rerankLabel: $("rerank-label"), + run: $("run"), + status: $("status"), + graph: $("graph"), + legend: $("legend"), + tip: $("tip"), + results: $("results"), + examples: $("examples"), + meta: $("meta"), +}; + + +const state = { + manifest: null, + examples: [], // sample texts: title and abstract of real applications + indexes: new Map(), // lang -> built index + indexLoads: new Map(), // lang -> promise of the load in flight (clicks during loading reuse it) + embedder: null, + embedderLoad: null, // promise of the model load in flight + rerankWorker: null, // Web Worker running the cross-encoder, created on first use + rerankRequests: new Map(), // request id -> {resolve, reject} + rerankSeq: 0, + progress: new Map(), // label -> {loaded, total} + pending: 0, // loads in flight that have not reported progress yet + error: null, +}; + +function exampleText(ex) { + return `${ex.title}\n\n${ex.abstract}`; +} + +// -- status ------------------------------------------------------------------- + +function fmtMB(bytes) { + return `${(bytes / 1e6).toFixed(bytes < 10e6 ? 1 : 0)} MB`; +} + +function fmtProgress({ loaded, total, unit }) { + if (unit === "pairs") return `${loaded} / ${total} pairs`; + return total ? `${fmtMB(loaded)} / ${fmtMB(total)}` : fmtMB(loaded); +} + +function renderStatus(message) { + ui.status.innerHTML = ""; + if (state.error) { + ui.status.className = "status error"; + ui.status.textContent = state.error; + return; + } + ui.status.className = "status"; + if (!state.progress.size) { + ui.status.textContent = + message || (state.pending ? "Loading…" : "Ready. Everything runs in this browser tab."); + return; + } + for (const [label, entry] of state.progress) { + const { loaded, total } = entry; + const row = document.createElement("div"); + row.className = "progress"; + const pct = total ? Math.min(100, Math.round((100 * loaded) / total)) : 0; + row.innerHTML = `
`; + row.querySelector("span").textContent = label; + row.querySelector("small").textContent = fmtProgress(entry); + ui.status.appendChild(row); + } +} + +function setProgress(label, loaded, total, unit) { + state.progress.set(label, { loaded, total, unit }); + renderStatus(); +} + +function doneProgress(label) { + state.progress.delete(label); + renderStatus(); +} + +// -- loading ------------------------------------------------------------------ + +async function fetchWithProgress(url, label) { + const res = await fetch(url); + if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`); + const total = Number(res.headers.get("content-length")) || 0; + if (!res.body) return res.arrayBuffer(); + const reader = res.body.getReader(); + const chunks = []; + let loaded = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + loaded += value.length; + setProgress(label, loaded, total); + } + const out = new Uint8Array(loaded); + let off = 0; + for (const c of chunks) { + out.set(c, off); + off += c.length; + } + doneProgress(label); + return out.buffer; +} + +function entryFor(lang) { + return state.manifest.indexes.find((e) => e.lang === lang) || state.manifest.indexes[0]; +} + +function loadIndex(entry) { + if (state.indexes.has(entry.lang)) return Promise.resolve(state.indexes.get(entry.lang)); + if (!state.indexLoads.has(entry.lang)) { + state.pending += 1; + const load = fetchIndex(entry) + .catch((err) => { + state.indexLoads.delete(entry.lang); // let a later click retry + throw err; + }) + .finally(() => { + state.pending -= 1; + renderStatus(); + }); + state.indexLoads.set(entry.lang, load); + } + return state.indexLoads.get(entry.lang); +} + +async function fetchIndex(entry) { + const label = `IPC ${entry.version} ${entry.lang}`; + const [schemeBuf, vecBuf] = await Promise.all([ + fetchWithProgress(entry.scheme, `${label} scheme`), + fetchWithProgress(entry.vectors, `${label} vectors`), + ]); + const scheme = JSON.parse(new TextDecoder().decode(schemeBuf)); + const vectors = parseVectors(vecBuf, { + rows: entry.rows, + dim: state.manifest.dim, + encoding: entry.encoding, + }); + const index = buildIndex(scheme, vectors); + state.indexes.set(entry.lang, index); + return index; +} + +function loadEmbedder() { + if (state.embedder) return Promise.resolve(state.embedder); + if (!state.embedderLoad) { + const { web_model: model, web_dtype: dtype } = state.manifest; + const label = `model ${model} (${dtype})`; + state.pending += 1; + state.embedderLoad = pipeline("feature-extraction", model, { + dtype, + progress_callback: (e) => { + if (e.status === "progress" && e.file && e.file.endsWith(".onnx")) { + setProgress(label, e.loaded, e.total); + } + }, + }) + .then((p) => { + state.embedder = p; + return p; + }) + .catch((err) => { + state.embedderLoad = null; // let a later click retry + throw err; + }) + .finally(() => { + state.pending -= 1; + doneProgress(label); + }); + } + return state.embedderLoad; +} + +/** The reranker runs in a Web Worker (rerank-worker.js) so the page keeps painting. */ +function rerankWorker() { + if (!state.rerankWorker) { + const worker = new Worker("rerank-worker.js", { type: "module" }); + const { web_model: model, dtype } = state.manifest.reranker; + const loadLabel = `reranker ${model} (${dtype})`; + const judgeLabel = "judging candidates"; + worker.onmessage = (e) => { + const m = e.data; + if (m.type === "progress") setProgress(loadLabel, m.loaded, m.total); + else if (m.type === "ready") doneProgress(loadLabel); + else if (m.type === "judging") setProgress(judgeLabel, m.done, m.total, "pairs"); + else if (m.id !== undefined && state.rerankRequests.has(m.id)) { + const { resolve, reject } = state.rerankRequests.get(m.id); + state.rerankRequests.delete(m.id); + doneProgress(loadLabel); + doneProgress(judgeLabel); + if (m.type === "error") reject(new Error(m.message)); + else resolve(m); + } + }; + worker.onerror = (e) => { + for (const { reject } of state.rerankRequests.values()) reject(new Error(e.message || "reranker worker failed")); + state.rerankRequests.clear(); + doneProgress(loadLabel); + doneProgress(judgeLabel); + }; + state.rerankWorker = worker; + } + return state.rerankWorker; +} + +function askWorker(message) { + const worker = rerankWorker(); + const id = ++state.rerankSeq; + return new Promise((resolve, reject) => { + state.rerankRequests.set(id, { resolve, reject }); + worker.postMessage({ id, ...message }); + }); +} + +/** Cross-encoder logits for (text, path text) pairs; progress shows in the status. */ +async function judge(text, matches) { + const { web_model: modelId, dtype, max_length: maxLength } = state.manifest.reranker; + setProgress("judging candidates", 0, matches.length, "pairs"); + const reply = await askWorker({ + type: "judge", + modelId, + dtype, + text, + texts: matches.map((m) => m.text), + maxLength, + batch: 4, + }); + return reply.logits; +} + +/** + * Query vector for a text of any length. Paragraphs are embedded separately and a + * paragraph over the model's token limit is cut into sentence chunks (scorer.js + * splitText, a port of text2ipc/chunking.py); the unit-length mean of the pieces is + * the query, as IpcClassifier does with chunking="mean". + */ +async function embedText(text) { + const { query_prefix: prefix, max_tokens: limit } = state.manifest; + const countTokens = (t) => state.embedder.tokenizer(prefix + t).input_ids.dims[1]; + const options = { pooling: "mean", normalize: true }; + const chunks = splitText(text, limit || null, countTokens); + if (chunks.length <= 1) { + const out = await state.embedder(prefix + text, options); + return { query: out.data, chunks: 1 }; + } + const out = await state.embedder(chunks.map((c) => prefix + c), options); + const dim = out.dims[out.dims.length - 1]; + const vectors = chunks.map((_, i) => out.data.subarray(i * dim, (i + 1) * dim)); + return { query: meanVector(vectors), chunks: chunks.length }; +} + +// -- classify ----------------------------------------------------------------- + +// One classification at a time. The ONNX session must not run twice concurrently, +// and the page must end up showing the results of the latest request: a request +// made while one is running waits for it and then runs with the current inputs. +let running = false; +let queued = false; + +async function classify() { + if (running) { + queued = true; + return; + } + running = true; + ui.run.disabled = true; + try { + do { + queued = false; + await classifyOnce(); + } while (queued); + } finally { + running = false; + ui.run.disabled = false; + } +} + +async function classifyOnce() { + const text = normalizeQuery(ui.text.value || ""); + if (!text) return; + try { + const entry = entryFor(ui.lang.value); + const [index] = await Promise.all([loadIndex(entry), loadEmbedder()]); + renderStatus("Embedding..."); + const t0 = performance.now(); + const { query, chunks } = await embedText(text); + const t1 = performance.now(); + const topK = Number(ui.topK.value); + const rerank = Boolean(state.manifest.reranker) && ui.rerank.checked; + const candidates = rerank ? Math.max(state.manifest.reranker.candidates, topK) : topK; + let { matches, sims } = rank(index, query, { level: ui.level.value, topK: candidates }); + const t2 = performance.now(); + let judged = ""; + if (rerank && matches.length) { + renderStatus(); + const logits = await judge(text, matches); + matches = rerankMatches(matches, logits, state.manifest.reranker.fusion, topK); + judged = ` · judged ${logits.length} in ${Math.round(performance.now() - t2)} ms`; + } + renderGraph(index, matches, sims, entry); + renderResults(matches, rerank); + ui.meta.textContent = + `IPC ${entry.version} ${entry.lang} · ${entry.rows.toLocaleString()} entries · ` + + `${state.manifest.web_model} ${state.manifest.web_dtype} · ` + + `${chunks > 1 ? `${chunks} chunks · ` : ""}` + + `embed ${Math.round(t1 - t0)} ms · score ${Math.round(t2 - t1)} ms${judged}`; + renderStatus(); + updateUrl(text, entry.lang); + } catch (err) { + state.error = `Something failed: ${err.message || err}`; + renderStatus(); + console.error(err); + } +} + +function renderResults(matches, reranked = false) { + ui.results.innerHTML = ""; + if (!matches.length) { + ui.results.textContent = "No result."; + return; + } + const table = document.createElement("table"); + table.innerHTML = + "#SymbolLevelScoreSim." + + (reranked ? "Judge" : "") + + "Section > … > entry"; + const body = document.createElement("tbody"); + matches.forEach((m, i) => { + const tr = document.createElement("tr"); + const cells = [ + String(i + 1), + m.pretty, + m.level, + m.score.toFixed(3), + m.similarity.toFixed(3), + ...(reranked ? [m.judge.toFixed(2)] : []), + m.text, + ]; + cells.forEach((v, j) => { + const td = document.createElement("td"); + td.textContent = v; + if (j === 1) td.className = "symbol"; + if (j === cells.length - 1) td.className = "path"; + tr.appendChild(td); + }); + body.appendChild(tr); + }); + table.appendChild(body); + ui.results.appendChild(table); +} + +// -- graph: the results' paths merged into one tree ---------------------------- + +const G = { rowH: 34, gap: 96, padX: 14, padY: 16, nodeH: 24, charW: 7.4, badgeW: 34 }; +const SVG = "http://www.w3.org/2000/svg"; + +function svgEl(tag, attrs = {}, text) { + const el = document.createElementNS(SVG, tag); + for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v); + if (text !== undefined) el.textContent = text; + return el; +} + +/** What a node shows: A, 62, C, 25/00, 25/01 along the path A62C 25/01. */ +function nodeLabel(index, i) { + const sym = index.symbol[i]; + const lvl = index.level[i]; + if (lvl === 0) return sym; + if (lvl === 1) return sym.slice(1); + if (lvl === 2) return sym.slice(3); + return formatSymbol(sym).split(" ")[1]; +} + +const ROOT = -1; // virtual level-0 node above the sections, so section edges carry a value + +/** Merge the result paths into one tree under a virtual root; assign a row to every node. */ +function buildGraph(index, matches) { + const nodes = new Map(); + nodes.set(ROOT, { i: ROOT, col: 0, parent: null, children: [], minRank: 1 }); + matches.forEach((m, r) => { + const chain = chainOf(index, m.index); + chain.forEach((i, d) => { + if (!nodes.has(i)) { + nodes.set(i, { i, col: d + 1, parent: d ? chain[d - 1] : ROOT, children: [], minRank: r + 1 }); + } + }); + const leaf = nodes.get(m.index); + leaf.match = m; + leaf.rank = r + 1; + }); + for (const n of nodes.values()) if (n.parent !== null) nodes.get(n.parent).children.push(n.i); + const byRank = (a, b) => nodes.get(a).minRank - nodes.get(b).minRank || a - b; + for (const n of nodes.values()) n.children.sort(byRank); + let row = 0; + const place = (n) => { + if (!n.children.length) { + n.row = row++; + return; + } + n.children.forEach((c) => place(nodes.get(c))); + const rows = n.children.map((c) => nodes.get(c).row); + n.row = (Math.min(...rows) + Math.max(...rows)) / 2; + }; + place(nodes.get(ROOT)); + return { nodes, rows: row }; +} + +function renderGraph(index, matches, sims, entry) { + ui.graph.innerHTML = ""; + hideTip(); + if (!matches.length) { + ui.legend.hidden = true; + return; + } + const { nodes, rows } = buildGraph(index, matches); + for (const n of nodes.values()) { + n.label = n.i === ROOT ? "IPC" : nodeLabel(index, n.i); + n.w = Math.max(28, 12 + n.label.length * G.charW); + } + const cols = Math.max(...[...nodes.values()].map((n) => n.col)) + 1; + const colW = new Array(cols).fill(0); + for (const n of nodes.values()) colW[n.col] = Math.max(colW[n.col], n.w); + const colX = []; + let x = G.padX; + for (let c = 0; c < cols; c++) { + colX.push(x); + x += colW[c] + G.gap; + } + const width = x - G.gap + G.badgeW + G.padX; + const height = rows * G.rowH + 2 * G.padY; + const yOf = (row) => G.padY + row * G.rowH + G.rowH / 2; + + const svg = svgEl("svg", { + width, + height, + viewBox: `0 0 ${width} ${height}`, + role: "img", + "aria-label": "Paths of the results through the IPC hierarchy", + }); + const edges = svgEl("g", { class: "edges" }); + const labels = svgEl("g", { class: "edge-labels" }); + const nodeLayer = svgEl("g", { class: "nodes" }); + svg.append(edges, labels, nodeLayer); + + for (const n of nodes.values()) { + const nx = colX[n.col]; + const ny = yOf(n.row); + const isResult = n.match !== undefined; + if (n.parent !== null) { + const p = nodes.get(n.parent); + const x1 = colX[p.col] + p.w; + const y1 = yOf(p.row); + const xm = (x1 + nx) / 2; + const d = `M${x1},${y1} C${xm},${y1} ${xm},${ny} ${nx},${ny}`; + const value = isResult ? n.match.score : sims[n.i]; + const edge = svgEl("path", { d, class: `edge${isResult ? " result" : ""}` }); + const hit = svgEl("path", { d, class: "hit", tabindex: "0" }); + edges.append(edge, hit); + const lx = (x1 + nx) / 2; + const ly = (y1 + ny) / 2; + const txt = value.toFixed(3); + const lw = 10 + txt.length * 6.6; + const pill = svgEl("g", { class: `edge-label${isResult ? " result" : ""}` }); + pill.append( + svgEl("rect", { x: lx - lw / 2, y: ly - 9, width: lw, height: 18, rx: 9 }), + svgEl("text", { x: lx, y: ly + 4, "text-anchor": "middle" }, txt), + ); + labels.append(pill); + const info = tipInfo(index, n, sims, entry); + hit.setAttribute("aria-label", info.aria); + bindTip(hit, info, edge); + } + const g = svgEl("g", { + class: `node${isResult ? " result" : ""}${n.i === ROOT ? " root" : ""}`, + transform: `translate(${nx},${ny - G.nodeH / 2})`, + tabindex: "0", + }); + g.append( + svgEl("rect", { width: n.w, height: G.nodeH, rx: 6 }), + svgEl("text", { x: n.w / 2, y: G.nodeH / 2 + 4, "text-anchor": "middle" }, n.label), + ); + if (isResult) { + g.append(svgEl("text", { class: "badge", x: n.w + 8, y: G.nodeH / 2 + 4 }, `#${n.rank}`)); + } + const info = tipInfo(index, n, sims, entry); + g.setAttribute("aria-label", info.aria); + bindTip(g, info, g); + nodeLayer.append(g); + } + ui.graph.appendChild(svg); + ui.legend.hidden = false; +} + +function tipInfo(index, n, sims, entry) { + if (n.i === ROOT) { + const strong = `IPC ${entry.version} ${entry.lang}`; + const title = "Level 0: the whole scheme. Each edge to a section carries that section's similarity."; + return { + lines: [{ strong, rest: ` · ${entry.rows.toLocaleString()} entries` }], + symbol: "root", + title, + aria: `${strong}. ${title}`, + }; + } + const sym = formatSymbol(index.symbol[n.i]); + const level = LEVELS[index.level[n.i]]; + const title = index.title[n.i] || index.heading[n.i] || ""; + const lines = []; + if (n.match) { + lines.push({ strong: `score ${n.match.score.toFixed(3)}`, rest: ` · result #${n.rank}` }); + const judged = n.match.judge === undefined ? "" : ` · judge ${n.match.judge.toFixed(2)}`; + lines.push({ + rest: `similarity ${n.match.similarity.toFixed(3)} · path support ${n.match.pathSupport.toFixed(3)}${judged}`, + }); + } else { + lines.push({ strong: `similarity ${sims[n.i].toFixed(3)}`, rest: "" }); + } + return { + lines, + symbol: `${sym} · ${level}`, + title, + aria: `${sym}, ${level}: ${title}. ${lines.map((l) => (l.strong || "") + l.rest).join(". ")}`, + }; +} + +function bindTip(target, info, lift) { + const show = (e) => { + lift.classList.add("hover"); + showTip(info, e); + }; + const hide = () => { + lift.classList.remove("hover"); + hideTip(); + }; + target.addEventListener("pointerenter", show); + target.addEventListener("pointermove", (e) => positionTip(e.clientX, e.clientY)); + target.addEventListener("pointerleave", hide); + target.addEventListener("focus", (e) => { + const r = e.target.getBoundingClientRect(); + lift.classList.add("hover"); + showTip(info, null); + positionTip(r.left + r.width / 2, r.top + r.height / 2); + }); + target.addEventListener("blur", hide); +} + +function showTip(info, e) { + ui.tip.innerHTML = ""; + for (const l of info.lines) { + const p = document.createElement("div"); + if (l.strong) { + const b = document.createElement("strong"); + b.textContent = l.strong; + p.appendChild(b); + } + p.appendChild(document.createTextNode(l.rest)); + ui.tip.appendChild(p); + } + const sym = document.createElement("div"); + sym.className = "tip-symbol"; + sym.textContent = info.symbol; + const title = document.createElement("div"); + title.className = "tip-title"; + title.textContent = info.title; + ui.tip.append(sym, title); + ui.tip.hidden = false; + if (e) positionTip(e.clientX, e.clientY); +} + +function positionTip(cx, cy) { + const pad = 14; + const w = ui.tip.offsetWidth; + const h = ui.tip.offsetHeight; + let left = cx + pad; + let top = cy + pad; + if (left + w > window.innerWidth - 8) left = cx - w - pad; + if (top + h > window.innerHeight - 8) top = cy - h - pad; + ui.tip.style.left = `${Math.max(8, left)}px`; + ui.tip.style.top = `${Math.max(8, top)}px`; +} + +function hideTip() { + ui.tip.hidden = true; +} + +function updateUrl(text, lang) { + const params = new URLSearchParams({ lang, level: ui.level.value, q: text }); + history.replaceState(null, "", `?${params}`); +} + +// -- setup -------------------------------------------------------------------- + +function fillSelect(select, values, labels) { + select.innerHTML = ""; + values.forEach((v, i) => { + const o = document.createElement("option"); + o.value = v; + o.textContent = labels ? labels[i] : v; + select.appendChild(o); + }); +} + +async function loadExamples() { + try { + const res = await fetch("examples.json"); + if (res.ok) state.examples = await res.json(); + } catch { + state.examples = []; + } +} + +function renderExamples() { + ui.examples.innerHTML = ""; + for (const ex of state.examples) { + const b = document.createElement("button"); + b.type = "button"; + b.className = "chip"; + b.textContent = ex.title.length > 56 ? `${ex.title.slice(0, 56)}…` : ex.title; + b.title = `${ex.abstract.slice(0, 160)}…`; + b.addEventListener("click", () => { + ui.text.value = exampleText(ex); // filled in only; Classify runs it + ui.text.focus(); + }); + ui.examples.appendChild(b); + } +} + +async function main() { + try { + const res = await fetch("manifest.json"); + if (!res.ok) throw new Error(`manifest.json: HTTP ${res.status}`); + state.manifest = await res.json(); + } catch (err) { + state.error = `Could not load the index manifest: ${err.message || err}`; + renderStatus(); + return; + } + const m = state.manifest; + fillSelect( + ui.lang, + m.indexes.map((e) => e.lang), + m.indexes.map((e) => `${e.lang} scheme (IPC ${e.version})`), + ); + fillSelect(ui.level, [AUTO_LEVEL, ...LEVELS]); + ui.level.value = "group"; + if (!m.reranker) ui.rerankLabel.hidden = true; + else ui.rerankLabel.title = `${m.reranker.web_model} (${m.reranker.dtype}) re-judges the top ${m.reranker.candidates} when you click Classify; 280 MB once, then about a second per candidate`; + await loadExamples(); + renderExamples(); + + const params = new URLSearchParams(location.search); + if (params.get("lang") && m.indexes.some((e) => e.lang === params.get("lang"))) { + ui.lang.value = params.get("lang"); + } + if (params.get("level") && [AUTO_LEVEL, ...LEVELS].includes(params.get("level"))) { + ui.level.value = params.get("level"); + } + if (params.get("q")) ui.text.value = params.get("q"); + + ui.run.addEventListener("click", classify); + ui.lang.addEventListener("change", () => loadIndex(entryFor(ui.lang.value)).catch(fail)); + window.addEventListener("scroll", hideTip, { passive: true }); + + try { + await Promise.all([loadIndex(entryFor(ui.lang.value)), loadEmbedder()]); + renderStatus(); // nothing runs until Classify is clicked + } catch (err) { + fail(err); + } +} + +function fail(err) { + state.error = `Could not load the model or the index: ${err.message || err}`; + renderStatus(); + console.error(err); +} + +main(); diff --git a/text2ipc/web/static/index.html b/text2ipc/web/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c7221dc59cd18d79e51ad9414d993818708b0539 --- /dev/null +++ b/text2ipc/web/static/index.html @@ -0,0 +1,129 @@ + + + + + +text2ipc + + + + +
+

text2ipc patent text → IPC symbols, in your browser

+

Paste a patent abstract or title in Portuguese, English or another language. + The page embeds it with a multilingual model and scores it against the IPC hierarchy + locally; the text never leaves this tab.

+ + +
+ + + + + +
+
+
Loading…
+
+ +
+
+ + +
+
+ + + diff --git a/text2ipc/web/static/rerank-worker.js b/text2ipc/web/static/rerank-worker.js new file mode 100644 index 0000000000000000000000000000000000000000..d48db8b6816a9a452eae6e09a353880aa8f8fe00 --- /dev/null +++ b/text2ipc/web/static/rerank-worker.js @@ -0,0 +1,88 @@ +// Web Worker for the second stage: loads the cross-encoder and judges (text, path) +// pairs off the main thread, so the page stays responsive and can show progress. +// Messages in: {id, type: "load", modelId, dtype} and +// {id, type: "judge", text, texts, maxLength, batch}. +// Messages out: {type: "progress", loaded, total} while the model downloads, +// {type: "judging", done, total} after every batch, +// {id, type: "loaded"} | {id, type: "done", logits} | {id, type: "error", message}. +import { + AutoTokenizer, + XLMRobertaModel, + env, +} from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.1"; + +env.allowLocalModels = false; + +let tokenizer = null; +let model = null; +let loading = null; + +self.onmessage = async (e) => { + const { id, type } = e.data; + try { + if (type === "load") { + await load(e.data); + self.postMessage({ id, type: "loaded" }); + } else if (type === "judge") { + await load(e.data); + self.postMessage({ id, type: "done", logits: await judge(e.data) }); + } + } catch (err) { + self.postMessage({ id, type: "error", message: (err && err.message) || String(err) }); + } +}; + +function load({ modelId, dtype }) { + if (model) return Promise.resolve(); + if (!loading) { + loading = (async () => { + const progress = (p) => { + if (p.status === "progress" && p.file && p.file.endsWith(".onnx")) { + self.postMessage({ type: "progress", loaded: p.loaded, total: p.total }); + } + }; + // jina's config carries no model_type, so the class is named, as its model card does + const attempt = async () => { + tokenizer = await AutoTokenizer.from_pretrained(modelId); + model = await XLMRobertaModel.from_pretrained(modelId, { dtype, progress_callback: progress }); + }; + try { + await attempt(); + self.postMessage({ type: "ready" }); + } catch (err) { + // Some browsers cannot store a 280 MB response in the Cache API and the + // loader fails with a network error; retry without the cache. + console.warn("reranker load failed, retrying without the browser cache", err); + env.useBrowserCache = false; + try { + await attempt(); + self.postMessage({ type: "ready" }); + } finally { + env.useBrowserCache = true; + } + } + })().catch((err) => { + loading = null; + throw err; + }); + } + return loading; +} + +async function judge({ text, texts, maxLength, batch }) { + const logits = []; + const size = batch || 4; + for (let i = 0; i < texts.length; i += size) { + const part = texts.slice(i, i + size); + const inputs = tokenizer(part.map(() => text), { + text_pair: part, + padding: true, + truncation: true, + max_length: maxLength, + }); + const out = await model(inputs); + for (let j = 0; j < part.length; j++) logits.push(Number(out.logits.data[j])); + self.postMessage({ type: "judging", done: logits.length, total: texts.length }); + } + return logits; +} diff --git a/text2ipc/web/static/scorer.js b/text2ipc/web/static/scorer.js new file mode 100644 index 0000000000000000000000000000000000000000..6be09efa12cdbab76885d8a4b989f4e5dc8c3150 --- /dev/null +++ b/text2ipc/web/static/scorer.js @@ -0,0 +1,411 @@ +// JavaScript port of text2ipc/search/scorer.py: hierarchical scoring on top of +// flat cosine similarity. Pure functions, no DOM, no fetch: the browser page +// (app.js) and the Node parity test (tests/js_parity.mjs) both import it. +// +// Keep in step with the Python module. Every heuristic here mirrors a function +// there by name: pathSupport, subtreeSupport, beamDescend, autoDescend, +// distinctBranches. tests/test_web.py runs both on the mini scheme and compares. + +export const LEVELS = ["section", "class", "subclass", "group", "subgroup"]; +export const AUTO_LEVEL = "auto"; +export const PATH_SEPARATOR = " > "; + +export const DEFAULT_WEIGHTS = { own: 1.0, path: 0.0, subtree: 0.0 }; // see Weights in scorer.py +export const DEFAULT_BEAM = { section: 5, class: 10, subclass: 20, group: 40 }; +export const DEFAULT_PARAMS = { + level: "subgroup", + topK: 10, + gap: null, // drop results scoring more than this below the best one + autoMargin: 0.02, // auto level: descend while best child >= parent - margin + autoRoots: null, // auto level: subclasses to start from; null = max(5, topK) + dedupeBranches: true, // drop ancestors/descendants of a higher-ranked result +}; + +// -- index ------------------------------------------------------------------ + +/** + * Build the in-memory index from the exported columns and vectors. + * scheme: {symbol: string[], level: int[], depth: int[], parent: int[], title: string[], heading: string[]} + * vectors: {encoding: "int8"|"float32", rows, dim, data: Int8Array|Float32Array, scales?: Float32Array} + */ +export function buildIndex(scheme, vectors) { + const n = scheme.symbol.length; + if (vectors.rows !== n) { + throw new Error(`vectors have ${vectors.rows} rows, scheme has ${n}`); + } + const parent = Int32Array.from(scheme.parent); + const children = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { + const p = parent[i]; + if (p >= i) throw new Error("Index rows must be in depth-first order (parents before children)"); + if (p >= 0) children[p].push(i); + } + return { + rows: n, + dim: vectors.dim, + symbol: scheme.symbol, + level: Int8Array.from(scheme.level), + depth: Int8Array.from(scheme.depth), + parent, + children, + title: scheme.title, + heading: scheme.heading, + vectors, + }; +} + +/** Parse vectors.bin as written by text2ipc.web.export.write_vectors. */ +export function parseVectors(buffer, meta) { + const { rows, dim, encoding } = meta; + if (encoding === "int8") { + const scales = new Float32Array(buffer, 0, rows); + const data = new Int8Array(buffer, rows * 4, rows * dim); + return { encoding, rows, dim, data, scales }; + } + if (encoding === "float32") { + return { encoding, rows, dim, data: new Float32Array(buffer, 0, rows * dim) }; + } + throw new Error(`unknown vector encoding ${encoding}`); +} + +/** Canonical symbol to human form: A01B0001020000 -> "A01B 1/02". */ +export function formatSymbol(symbol) { + if (symbol.length !== 14) return symbol; + const sub = symbol.slice(0, 4); + const group = symbol.slice(4, 8); + let subgroup = symbol.slice(8).replace(/0+$/, ""); + if (subgroup.length < 2) subgroup = subgroup.padEnd(2, "0"); + return `${sub} ${parseInt(group, 10)}/${subgroup}`; +} + +/** Symbol chain from the section down to row i. */ +export function chainOf(index, i) { + const chain = []; + for (let node = i; node >= 0; node = index.parent[node]) chain.push(node); + return chain.reverse(); +} + +/** The text an entry was embedded with: titles top-down, heading before a group. */ +export function textAt(index, i) { + const parts = []; + for (const s of chainOf(index, i)) { + if (index.heading[s]) parts.push(index.heading[s]); + parts.push(index.title[s]); + } + return parts.filter((p) => p).join(PATH_SEPARATOR); +} + +// -- query normalisation (text2ipc/textnorm.py, classifier.normalize_query) --- + +const PARAGRAPH_RE = /\n\s*\n/; + +/** Non-empty parts separated by a blank line; single newlines do not split. */ +export function paragraphs(text) { + return text.split(PARAGRAPH_RE).filter((p) => p.trim()); +} + +/** Collapse runs of whitespace inside each paragraph; keep blank lines as breaks. */ +export function collapseWhitespace(text) { + return paragraphs(text) + .map((p) => p.split(/\s+/).filter(Boolean).join(" ")) + .join("\n\n"); +} + +export function lowercaseIfShouting(text, threshold = 0.6) { + const letters = Array.from(text).filter((c) => /\p{L}/u.test(c)); + if (!letters.length) return text; + const upper = letters.filter((c) => c !== c.toLowerCase() && c === c.toUpperCase()).length; + return upper / letters.length > threshold ? text.toLowerCase() : text; +} + +export function normalizeQuery(text) { + return collapseWhitespace(text).split("\n\n").map(lowercaseIfShouting).join("\n\n"); +} + +// -- scoring ------------------------------------------------------------------ + +function similarities(index, query) { + const { rows, dim, data, scales, encoding } = index.vectors; + // an array of vectors comes from a long text: an entry scores by its best chunk + const queries = Array.isArray(query) ? query : [query]; + const sims = new Float64Array(rows).fill(-Infinity); + for (const q of queries) { + if (q.length !== dim) throw new Error(`query has ${q.length} dimensions, index has ${dim}`); + for (let i = 0; i < rows; i++) { + const off = i * dim; + let s = 0; + for (let j = 0; j < dim; j++) s += data[off + j] * q[j]; + s = encoding === "int8" ? s * scales[i] : s; + if (s > sims[i]) sims[i] = s; + } + } + return sims; +} + +// -- long texts (text2ipc/chunking.py) ----------------------------------------- + +const SENTENCE_RE = /(?<=[.!?;:])\s+(?=\S)/; + +/** + * One chunk per paragraph (blank-line separated, never merged), cut further into + * sentence chunks of at most maxTokens tokens when a paragraph is too long; a single + * over-long sentence is cut by words. `overlap` trailing sentences of a chunk are + * repeated at the start of the next. countTokens(text) must count a text as the + * embedder will see it; maxTokens null means no limit. + */ +export function splitText(text, maxTokens, countTokens, overlap = 1) { + return paragraphs(text).flatMap((p) => pack(p.trim(), maxTokens, countTokens, overlap)); +} + +function pack(paragraph, maxTokens, countTokens, overlap) { + if (maxTokens === null || maxTokens === undefined) { + return [paragraph.split(/\s+/).filter(Boolean).join(" ")]; + } + let units = paragraph.split(SENTENCE_RE).map((s) => s.trim()).filter(Boolean); + units = units.flatMap((u) => cutByWords(u, maxTokens, countTokens)); + const chunks = []; + let current = []; + for (const unit of units) { + if (current.length && countTokens([...current, unit].join(" ")) > maxTokens) { + chunks.push(current); + const carry = overlap > 0 ? current.slice(-overlap) : []; + current = [...carry, unit]; + while (current.length > 1 && countTokens(current.join(" ")) > maxTokens) { + current = current.slice(1); + } + } else { + current.push(unit); + } + } + if (current.length) chunks.push(current); + return chunks.map((c) => c.join(" ")); +} + +function cutByWords(unit, maxTokens, countTokens) { + if (countTokens(unit) <= maxTokens) return [unit]; + const out = []; + let piece = []; + for (const w of unit.split(/\s+/).filter(Boolean)) { + if (piece.length && countTokens([...piece, w].join(" ")) > maxTokens) { + out.push(piece.join(" ")); + piece = []; + } + piece.push(w); + } + if (piece.length) out.push(piece.join(" ")); + return out; +} + +/** Unit-length mean of several unit vectors (the "mean" chunking policy). */ +export function meanVector(vectors) { + const dim = vectors[0].length; + const out = new Float32Array(dim); + for (const v of vectors) for (let j = 0; j < dim; j++) out[j] += v[j]; + let norm = 0; + for (let j = 0; j < dim; j++) norm += out[j] * out[j]; + norm = Math.sqrt(norm) || 1; + for (let j = 0; j < dim; j++) out[j] /= norm; + return out; +} + +/** Mean similarity of the ancestors; equals own similarity for roots. */ +function pathSupport(index, sims) { + const n = index.rows; + const total = new Float64Array(n); + const count = new Int32Array(n); + const out = new Float64Array(n); + for (let i = 0; i < n; i++) { + const p = index.parent[i]; // parents precede children + if (p >= 0) { + total[i] = total[p] + sims[p]; + count[i] = count[p] + 1; + } + out[i] = count[i] > 0 ? total[i] / count[i] : sims[i]; + } + return out; +} + +/** Max value over the node and everything below it. */ +function subtreeSupport(index, values) { + const best = Float64Array.from(values); + for (let i = index.rows - 1; i >= 0; i--) { + const p = index.parent[i]; // children precede parents in reverse + if (p >= 0 && best[i] > best[p]) best[p] = best[i]; + } + return best; +} + +/** Stable descending sort of row indices by a value array (Python's sorted(key=-v)). */ +function sortDesc(items, values) { + return items.slice().sort((a, b) => values[b] - values[a]); +} + +function* descendants(index, roots) { + const stack = roots.slice(); + while (stack.length) { + const i = stack.pop(); + for (const c of index.children[i]) { + yield c; + stack.push(c); + } + } +} + +/** Walk down from the sections, keeping the parents whose subtree scores best. */ +function beamDescend(index, bestBelow, target, beam) { + const targetRank = LEVELS.indexOf(target); + let frontier = []; + for (let i = 0; i < index.rows; i++) if (index.level[i] === 0) frontier.push(i); + for (let rank = 0; rank < LEVELS.length; rank++) { + if (rank === targetRank) return frontier; + const level = LEVELS[rank]; + frontier = sortDesc(frontier, bestBelow).slice(0, beam[level]); + const next = LEVELS[rank + 1]; + if (next === "subgroup") { + frontier = Array.from(descendants(index, frontier)); + } else { + frontier = frontier.flatMap((i) => index.children[i]); + } + } + return frontier; +} + +function argmaxFirst(items, values) { + let best = items[0]; + for (const i of items) if (values[i] > values[best]) best = i; + return best; +} + +/** + * From the best subclasses, walk down the branch with the best subtree score while + * that subtree still promises something within autoMargin of the current node, then + * answer with the node on the walked path whose own similarity is highest (deepest + * on ties). + */ +function autoDescend(index, sims, score, bestBelow, p) { + const nRoots = p.autoRoots ?? Math.max(5, p.topK); + let roots = beamDescend(index, bestBelow, "subclass", p.beam); + roots = sortDesc(roots, bestBelow).slice(0, nRoots); + const out = []; + for (const i of roots) { + const path = [i]; + let node = i; + while (index.children[node].length) { + const bestChild = argmaxFirst(index.children[node], bestBelow); + if (bestBelow[bestChild] < score[node] - p.autoMargin) break; + node = bestChild; + path.push(node); + } + const best = argmaxFirst(path.slice().reverse(), sims); + if (!out.includes(best)) out.push(best); + } + return sortDesc(out, score).slice(0, p.topK); +} + +function isAncestorOrSelf(index, a, i) { + for (let node = i; node >= 0; node = index.parent[node]) if (node === a) return true; + return false; +} + +/** Keep a result only if no accepted result sits on its path or below it. */ +function distinctBranches(index, ranked) { + const accepted = []; + for (const i of ranked) { + const sameBranch = accepted.some( + (a) => isAncestorOrSelf(index, a, i) || isAncestorOrSelf(index, i, a), + ); + if (!sameBranch) accepted.push(i); + } + return accepted; +} + +/** + * Rank IPC entries for a unit query vector. Returns matches ordered by score with the + * same fields as text2ipc.search.Match plus `pretty` and `index` (the row). + */ +export function search(index, query, params = {}) { + return rank(index, query, params).matches; +} + +/** + * Like search, but also returns the per-row arrays the matches were computed from + * (`sims`, `scores`, `pathSupport`, `subtreeSupport`), so a caller can show how the + * ancestors of a result scored. The Python package has no counterpart; `search` + * is the function the parity test covers. + */ +export function rank(index, query, params = {}) { + const p = { + ...DEFAULT_PARAMS, + ...params, + weights: { ...DEFAULT_WEIGHTS, ...(params.weights || {}) }, + beam: { ...DEFAULT_BEAM, ...(params.beam || {}) }, + }; + if (p.level !== AUTO_LEVEL && !LEVELS.includes(p.level)) { + throw new Error(`level must be one of ${LEVELS.join(", ")} or ${AUTO_LEVEL}`); + } + const sims = similarities(index, query); + const path = pathSupport(index, sims); + const subtree = subtreeSupport(index, sims); + const w = p.weights; + const score = new Float64Array(index.rows); + for (let i = 0; i < index.rows; i++) { + score[i] = w.own * sims[i] + w.path * path[i] + w.subtree * subtree[i]; + } + const bestBelow = subtreeSupport(index, score); + + let chosen; + if (p.level === AUTO_LEVEL) { + chosen = autoDescend(index, sims, score, bestBelow, p); + } else { + chosen = beamDescend(index, bestBelow, p.level, p.beam); + chosen = sortDesc(chosen, score).slice(0, p.topK); + } + if (p.gap !== null && p.gap !== undefined && chosen.length) { + const best = score[chosen[0]]; + chosen = chosen.filter((i) => score[i] >= best - p.gap); + } + if (p.dedupeBranches) chosen = distinctBranches(index, chosen); + + const matches = chosen.map((i) => ({ + index: i, + symbol: index.symbol[i], + pretty: formatSymbol(index.symbol[i]), + level: LEVELS[index.level[i]], + depth: index.depth[i], + title: index.title[i], + text: textAt(index, i), + score: score[i], + similarity: sims[i], + pathSupport: path[i], + subtreeSupport: subtree[i], + })); + return { matches, sims, scores: score, pathSupport: path, subtreeSupport: subtree }; +} + +// -- second stage (text2ipc/rerank/base.py) ------------------------------------ + +export function sigmoid(x) { + return 1 / (1 + Math.exp(-x)); +} + +/** + * Combine first-stage scores with a judge's logits: "blend" (default) is + * score * (0.5 + 0.5 * sigmoid(logit)); "judge" is sigmoid(logit) alone; + * "product" is score * sigmoid(logit). + */ +export function fuse(scores, logits, how = "blend") { + return scores.map((s, i) => { + const j = sigmoid(logits[i]); + if (how === "blend") return s * (0.5 + 0.5 * j); + if (how === "judge") return j; + if (how === "product") return s * j; + throw new Error(`fusion must be blend, judge or product, got ${how}`); + }); +} + +/** Reorder matches by the fused score and attach each judge verdict (0..1). */ +export function rerankMatches(matches, logits, how = "blend", topK = matches.length) { + const fused = fuse(matches.map((m) => m.score), logits, how); + const order = matches.map((_, i) => i).sort((a, b) => fused[b] - fused[a]); + return order.slice(0, topK).map((i) => ({ ...matches[i], score: fused[i], judge: sigmoid(logits[i]) })); +}