text2ipc IPC 20260101 FR (940374f)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes-34
- README.mdAdded+97
- handler.pyAdded+68
- index/ipc_20260101_fr_st-intfloat-multilingual-e5-base.parquetAdded+3
- requirements.txtAdded+5
- scheme/ipc_20260101_fr.parquetAdded+3
- text2ipc.jsonAdded+5
- text2ipc/__init__.pyAdded+13
- text2ipc/chunking.pyAdded+78
- text2ipc/classifier.pyAdded+219
- text2ipc/cli.pyAdded+400
- text2ipc/config.pyAdded+70
- text2ipc/embeddings/__init__.pyAdded+3
- text2ipc/embeddings/base.pyAdded+79
- text2ipc/embeddings/hashing.pyAdded+55
- text2ipc/embeddings/ollama.pyAdded+65
- text2ipc/embeddings/st.pyAdded+83
- text2ipc/eval/__init__.pyAdded+20
- text2ipc/eval/cases.pyAdded+70
- text2ipc/eval/harness.pyAdded+113
- text2ipc/eval/rerank.pyAdded+84
- text2ipc/eval/rpi.pyAdded+229
- text2ipc/hf/__init__.pyAdded
- text2ipc/index/__init__.pyAdded+14
- text2ipc/index/build.pyAdded+113
- text2ipc/index/migrate.pyAdded+66
- text2ipc/index/paths.pyAdded+60
- text2ipc/index/publish.pyAdded+43
- text2ipc/index/store.pyAdded+130
- text2ipc/rerank/__init__.pyAdded+3
- text2ipc/rerank/base.pyAdded+72
- text2ipc/rerank/hashing.pyAdded+26
- text2ipc/rerank/st.pyAdded+77
- text2ipc/scheme/__init__.pyAdded+22
- text2ipc/scheme/download.pyAdded+50
- text2ipc/scheme/inpi.pyAdded+140
- text2ipc/scheme/model.pyAdded+25
- text2ipc/scheme/overlay.pyAdded+34
- text2ipc/scheme/parse.pyAdded+76
- text2ipc/scheme/symbols.pyAdded+59
- text2ipc/scheme/table.pyAdded+111
- text2ipc/search/__init__.pyAdded+3
- text2ipc/search/scorer.pyAdded+239
- text2ipc/textnorm.pyAdded+30
- text2ipc/versions.pyAdded+82
- text2ipc/web/__init__.pyAdded+3
- text2ipc/web/export.pyAdded+268
- text2ipc/web/static/app.jsAdded+706
- text2ipc/web/static/index.htmlAdded+129
- text2ipc/web/static/rerank-worker.jsAdded+88
1234567891011121314151617181920212223242526272829303132333435*.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 -textsaved_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 -text1*.parquet filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697---license: mitlanguage: - frpipeline_tag: text-classificationtags: - patents - ipc - classification - embeddings - reranking - text2ipcbase_model: - intfloat/multilingual-e5-base - BAAI/bge-reranker-v2-m3base_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 thisrepository derives from the first, and the second is downloaded and called at runtime when reranking is on. No weights are merged.
Maps free text (a patent abstract, a title, or a whole description) to rankedInternational Patent Classification symbols. Every IPC entry is embedded once from itsfull ancestor path (section > class > subclass > group > subgroups); a query isembedded by paragraph (title and abstract separately, averaged), a paragraph over theembedder's limit is cut into sentence chunks, and the entries are ranked by cosinesimilarity, walking the hierarchy to answer at the level asked. An optional secondstage, the **reranker**, re-judges the best candidates with a cross-encoder.
This repository is a **custom Inference Endpoints handler** (`handler.py`). Deploy it asan 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 fullsection-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 INPIapplications it lifts subclass@1 from 23.6% to 31.6% and group@1 from 11.2% to16.6%, for well under a second per input on a GPU. Size the endpoint for the extramodel when you enable it.
## Use it locally
```bashpip install "text2ipc[st] @ git+https://github.com/Jaimenms/text2ipc"t2ipc download jaimenms/text2ipc-fr # or --revision v0.2.2 to pin this editiont2ipc classify "Aparelho para combate a incêndios com mangueira flexível" --lang FR --level groupt2ipc classify "..." --lang FR --level group --rerank```
```pythonfrom text2ipc import IpcClassifierclf = 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<package version>` (`v0.2.0`,`v0.2.0-2`, ...), so `t2ipc download jaimenms/text2ipc-fr --revision <tag>` and the Hub's`revision` parameter pin an edition. The IPC version of the index is in the filenames and in `text2ipc.json`; the package code vendored under `text2ipc/` is the onethe 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 theHub. 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.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Hugging Face Inference Endpoints handler: text in, ranked IPC symbols out.
Copied to the root of the model repository by ``t2ipc hf-export``. The repositoryalso carries ``scheme/`` and ``index/`` (parquet), ``text2ipc.json`` (which index toserve) 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 jsonimport sysfrom pathlib import Pathfrom 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) ]123version https://git-lfs.github.com/spec/v1oid sha256:a893be5c0183e3a9cf2c54ccbc561ad9dc8e6ee5fff716fb7f5f4b5581751b99size 34138813512345numpy>=1.26httpx>=0.27typer>=0.12rich>=13.7sentence-transformers>=3.0123version https://git-lfs.github.com/spec/v1oid sha256:948ce492c471ba17281c093e92145673988bf143a56aa4829a9793203775189fsize 249766512345{ "version": "20260101", "lang": "FR", "model": "st:intfloat/multilingual-e5-base"}12345678910111213"""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, classifyfrom .config import LEVELSfrom .search import Beam, Match, SearchParams, Weights
__all__ = ["LEVELS", "Beam", "IpcClassifier", "Match", "SearchParams", "Weights", "classify"]__version__ = "0.2.2"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Split a long text into pieces an embedder can take whole.
Embedders have a token limit (512 for the e5 family) beyond which they truncatesilently, so a full patent description would be judged by its first page. Insteadthe text is cut at paragraph and sentence ends into chunks that fit, each chunk isembedded as a query, and the chunk vectors are combined (``IpcClassifier.embed_text``)."""
from __future__ import annotations
import refrom 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 out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""The simple interface: version + level + text -> ranked IPC symbols."""
from __future__ import annotations
import dataclassesimport datetime as dtfrom functools import lru_cachefrom pathlib import Path
import numpy as np
from .chunking import split_textfrom .config import DEFAULT_RERANKER, LEVELS, default_model, homefrom .embeddings import Embedder, get_embedder, model_slugfrom .embeddings.base import normalizefrom .index import IpcIndex, available_indexes, scheme_table_pathfrom .rerank import Reranker, fuse, get_reranker, sigmoidfrom .search import Beam, Match, SearchParams, Weights, searchfrom .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 <YYYYMMDD> (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}" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400"""``t2ipc`` command line."""
from __future__ import annotations
import jsonimport sysfrom pathlib import Path
import typerfrom rich.console import Consolefrom rich.table import Table
from .config import ( DEFAULT_HF_REPO, DEFAULT_RERANKER, LEVELS, OVERLAY_LANGS, WIPO_LANGS, default_model, home,)from .embeddings import get_embedderfrom .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_versionfrom .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_<issue>.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"<user>/text2ipc-{lang.lower()}", ) console.print(f"HF repo assembled at {path}") console.print(f"publish with: huggingface-cli upload <user>/<repo> {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 "<user>/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 <user>/<space> {path} . --repo-type space)" )
@app.command("migrate-csv")def migrate_csv( csv_path: Path = typer.Argument(..., help="Legacy ipc_<version>_<lang>_<model>.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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Package-wide constants and locations."""
from __future__ import annotations
import osfrom 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. ``<repo>/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)123from .base import Embedder, get_embedder, model_slug
__all__ = ["Embedder", "get_embedder", "model_slug"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Embedding backends behind one small interface.
A backend is selected by a spec string ``<backend>:<model>``:
- ``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 refrom collections.abc import Sequencefrom typing import Protocol, runtime_checkable
import numpy as np
@runtime_checkableclass 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 / norms12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""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 hashlibimport refrom 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()))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Ollama backend: any model that answers ``POST /api/embed``."""
from __future__ import annotations
from collections.abc import Sequence
import httpximport 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())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""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)1234567891011121314151617181920from .cases import EvalCase, load_cases, load_many, save_casesfrom .harness import EvalResult, evaluatefrom .rerank import JudgedCase, fused_order, fusion_results, judge_candidatesfrom .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",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Eval cases: a text and the IPC symbols a patent office assigned to it."""
from __future__ import annotations
import jsonfrom dataclasses import asdict, dataclass, fieldfrom 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 cases123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""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 aremulti-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 Callablefrom dataclasses import dataclass, field
from ..config import LEVELSfrom ..search import Matchfrom .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
@dataclassclass 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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""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 andkeeps the candidates with their first-stage scores and judge logits;``fusion_results`` then evaluates several ways of combining the two scores from thatsingle run (notebook 02 and the tables in docs/evals.md)."""
from __future__ import annotations
from collections.abc import Callable, Sequencefrom dataclasses import dataclass, replace
import numpy as np
from ..rerank import Reranker, fuse, sigmoidfrom ..search import Match, SearchParams, searchfrom .cases import EvalCasefrom .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 }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229"""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<issue>.zip``.Recent issues hold ``Patente_<issue>_<date>.xml``; older ones (e.g. 2100, from 2011)hold only ``P<issue>.txt``, a Latin-1 text file with one ``(INID) value`` field perline and a ``(Cd) <code>`` 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, inissues 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 isPortuguese."""
from __future__ import annotations
import ioimport reimport xml.etree.ElementTree as ETimport zipfilefrom pathlib import Path
import httpx
from ..config import homefrom ..scheme.symbols import normalize_symbolfrom .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 ``<home>/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<inid>[A-Za-z0-9]{2})\)\s?(?P<value>.*)$")_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<issue>.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()1234567891011121314from .build import BuildReport, build_indexfrom .paths import available_indexes, find_previous_index, index_path, scheme_table_pathfrom .store import IndexMeta, IpcIndex
__all__ = [ "BuildReport", "IndexMeta", "IpcIndex", "available_indexes", "build_index", "find_previous_index", "index_path", "scheme_table_path",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""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 themodel. For every symbol present in the previous index with an identical text hash theold vector is copied instead of recomputed. Between two yearly IPC versions that istypically well over 95 percent of the entries."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom pathlib import Path
import numpy as np
from ..embeddings.base import Embedderfrom ..scheme.table import SchemeTablefrom .store import IndexMeta, IpcIndex
@dataclassclass 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 prev123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""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 thatthe new scheme table renders exactly the text the vectors were computed from, and noembedding is needed."""
from __future__ import annotations
import csvimport jsonfrom pathlib import Path
import numpy as np
from ..config import OVERLAY_LANGSfrom ..scheme import SchemeTable, apply_titles, parse_schemefrom ..scheme.download import scheme_pathfrom ..scheme.inpi import fetch_inpi_titlesfrom .paths import index_path, scheme_table_pathfrom .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, report123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Where scheme tables and indexes live, and how to find the previous version."""
from __future__ import annotations
import refrom dataclasses import dataclassfrom pathlib import Path
from ..config import homefrom ..embeddings.base import model_slug
_NAME_RE = re.compile(r"^ipc_(?P<version>\d{8})_(?P<lang>[a-z]{2})_(?P<model>.+)\.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 None12345678910111213141516171819202122232425262728293031323334353637383940414243"""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 twoParquet 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 jsonimport shutilfrom 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, cfg123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""One Parquet index per (IPC version, scheme language, embedding model).
The index carries only what depends on the model: ``symbol``, ``path`` (the ``|``-joinedsymbol 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 textis 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; thesearch code relies on that."""
from __future__ import annotations
import datetime as dtimport jsonfrom dataclasses import asdict, dataclassfrom pathlib import Path
import numpy as npimport pyarrow as paimport pyarrow.parquet as pq
from ..config import LEVELSfrom ..scheme.model import SYMBOL_SEPARATOR, IpcNode, text_hashfrom ..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())123from .base import Reranker, fuse, get_reranker, sigmoid
__all__ = ["Reranker", "fuse", "get_reranker", "sigmoid"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Second stage: a cross-encoder judges every (text, entry path) pair of the firststage's candidates and the two scores are fused.
A reranker is selected by a spec string ``<backend>:<model>``:
- ``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 Portuguesescheme, bge-reranker-v2-m3 lifts subclass@1 from 23.6% to 32.3%."""
from __future__ import annotations
from collections.abc import Sequencefrom typing import Protocol, runtime_checkable
import numpy as np
FUSIONS = ("blend", "judge", "product")
@runtime_checkableclass 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}")1234567891011121314151617181920212223242526"""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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""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 aresupported by reading the installed signatures once."""
from __future__ import annotations
import inspectfrom 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)12345678910111213141516171819202122from .download import fetch_scheme, scheme_urlfrom .inpi import fetch_inpi_titlesfrom .model import IpcNode, text_hashfrom .overlay import apply_titles, load_titles_csvfrom .parse import parse_schemefrom .symbols import format_symbol, level_of_symbol, normalize_symbolfrom .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",]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""Fetch and cache WIPO IPC scheme master files."""
from __future__ import annotations
import ioimport zipfilefrom 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 ``<LANG>_ipc_scheme_<version>.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 target123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Portuguese IPC titles from INPI Brazil's IPC Publication (IPCPUB) instance.
WIPO publishes authentic master files in English and French only. For other languagesits IPC Publication "bridges" to national offices that run the same IPCPUB softwarewith 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 plusan index with sections, classes and subclasses::
<base>/media/<version>/<timestamp>/IPC/scheme/pt/json/index.json <base>/media/<version>/<timestamp>/IPC/scheme/pt/json/<SUBCLASS>.json
The ``timestamp`` per version is embedded in the IPCPUB HTML page. Titles are HTML:cross references sit in ``<span>`` and the edition tag in ``<a rel="versions">``; bothare stripped so the result matches what :mod:`parse` extracts from the WIPO XML.
Every JSON file is cached under ``<home>/inpi/<version>/<lang>/``; that cache is thesource of truth and titles are re-derived from it on each build (a few seconds)."""
from __future__ import annotations
import jsonimport reimport timefrom collections.abc import Callablefrom pathlib import Path
import httpx
from ..config import homefrom .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"<a rel=\"versions\".*?</a>", " ", html, flags=re.DOTALL) html = re.sub(r"<strong>\s*\[\d{4}\.\d{2}\]\s*</strong>", " ", html) html = re.sub(r"<span>.*?</span>", " ", html, flags=re.DOTALL) if (m := re.search(r'<div class="txt[^"]*">(.*)$', 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", " "))12345678910111213141516171819202122232425"""The unit of the IPC hierarchy as this package sees it."""
from __future__ import annotations
import hashlibfrom 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]12345678910111213141516171819202122232425262728293031323334"""Replace entry titles with a translation supplied as ``symbol,title`` rows.
WIPO master files exist in English and French. Other languages (Portuguese via INPIBrazil, for example) come as title tables. Entries missing from the table keep theiroriginal title, so partial translations degrade gracefully. Guidance headings have nosymbol and stay in the source language."""
from __future__ import annotations
import csvfrom dataclasses import replacefrom pathlib import Path
from .model import IpcNodefrom .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]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""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 insidethe 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 forthe entries that sit under them; the rest are skipped."""
from __future__ import annotations
import xml.etree.ElementTree as ETfrom collections.abc import Iteratorfrom pathlib import Path
from .model import IpcNodefrom .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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""IPC symbol formats.
WIPO master files use a fixed 14-character form: subclass (4) + main group (4, zeropadded) + 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}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""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 theconcatenation, top-down, of the titles along its path (section > class > subclass >main group > subgroup > ... > the entry), with the guidance heading inserted before amain group that sits under one. A subgroup's vector is the embedding of that wholetext, never of its own title alone.
Stored as ``scheme/ipc_<version>_<lang>.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 Iteratorfrom dataclasses import dataclassfrom pathlib import Path
import pyarrow as paimport pyarrow.parquet as pq
from .model import PATH_SEPARATOR, SYMBOL_SEPARATOR, IpcNode, text_hash
COLUMNS = ("symbol", "level", "depth", "parent", "title", "heading", "path")
@dataclassclass 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)123from .scorer import Beam, Match, SearchParams, Weights, search
__all__ = ["Beam", "Match", "SearchParams", "Weights", "search"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239"""Hierarchical scoring on top of flat cosine similarity.
Flat nearest-neighbour over 80k entries has two failure modes: deep entries with longspecific texts win on word overlap alone, and an isolated hit in an unrelated subtreecan 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 branchand answers with the best node on that walk, which yields "as detailed as theevidence supports".
**Branch de-duplication** runs last: the top-``k`` results are walked in rank orderand 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 bestsubgroup adds nothing a user could not read off the best one's path, so the listkeeps only distinct branches. The answer may therefore hold fewer than ``k`` rows."""
from __future__ import annotations
from collections.abc import Iterablefrom dataclasses import dataclass, field
import numpy as np
from ..config import AUTO_LEVEL, LEVELSfrom ..index.store import IpcIndexfrom ..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]123456789101112131415161718192021222324252627282930"""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 text12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""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 dtimport refrom 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]123from .export import WEB_DEFAULT_MODEL, dequantize_int8, export_web_demo, quantize_int8
__all__ = ["WEB_DEFAULT_MODEL", "dequantize_int8", "export_web_demo", "quantize_int8"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268"""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 indexas small static files and does everything client side: ``transformers.js`` embedsthe 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/<lang>/scheme.json columns symbol, level, depth, parent, title, heading data/<lang>/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 jsonimport shutilfrom pathlib import Path
import numpy as np
from .. import __version__ as package_versionfrom ..config import LEVELS, homefrom ..embeddings.st import prefixes_forfrom ..index import IpcIndex, available_indexes, scheme_table_pathfrom ..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 = 25WEB_RERANK_MAX_LENGTH = 768
SPACE_README = """---title: text2ipcemoji: 🏷️colorFrom: bluecolorTo: greensdk: staticapp_file: index.htmlpinned: falselicense: mitshort_description: Patent text to IPC symbols, computed in your browsermodels:{models}---
# text2ipc, in the browser
Paste a patent abstract (Portuguese, English or any language the embedder knows) andget a ranked list of International Patent Classification symbols. Nothing is sent toa server: the page downloads the quantised embedder `{web_model}` ({web_dtype}) and theIPC 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; thepackage's default reranker, `BAAI/bge-reranker-v2-m3`, is Apache-2.0).
How it works, the evaluation numbers and the Python package are athttps://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("<f4").tobytes() + np.ascontiguousarray(q).tobytes() elif encoding == "float32": payload = np.ascontiguousarray(vectors, dtype="<f4").tobytes() else: raise ValueError(f"encoding must be int8 or float32, got {encoding!r}") path.write_bytes(payload) return {"rows": rows, "dim": dim, "encoding": encoding, "bytes": len(payload)}
def scheme_columns(index: IpcIndex) -> 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 = "<user>/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}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706// 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 = `<span></span><div class="bar"><i style="width:${pct}%"></i></div><small></small>`; 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 = "<thead><tr><th>#</th><th>Symbol</th><th>Level</th><th>Score</th><th>Sim.</th>" + (reranked ? "<th>Judge</th>" : "") + "<th>Section > … > entry</th></tr></thead>"; 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();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>text2ipc</title><meta name="description" content="Patent text to International Patent Classification symbols, computed in your browser."><style> :root { color-scheme: light dark; --bg: #fbfbfa; --fg: #1d1d1b; --muted: #6b6b66; --line: #e2e2dd; --accent: #1f5fbf; --accent-fg: #fff; --chip: #f0f0ec; --bar: #d8e4f7; --edge: #a9a9a2; --tip-bg: #ffffff; --shadow: 0 4px 16px rgba(0,0,0,.14); --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; } @media (prefers-color-scheme: dark) { :root { --bg: #151514; --fg: #ecece8; --muted: #9b9b94; --line: #2c2c2a; --accent: #6aa0ff; --accent-fg: #0b1526; --chip: #222220; --bar: #243b63; --edge: #55554f; --tip-bg: #1f1f1d; --shadow: 0 4px 16px rgba(0,0,0,.5); } } * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } main { max-width: 960px; margin: 0 auto; padding: 24px 16px 48px; } h1 { font-size: 1.6rem; margin: 0 0 4px; } h1 small { font-weight: normal; color: var(--muted); font-size: 1rem; margin-left: 8px; } p.lead { margin: 0 0 20px; color: var(--muted); } textarea { width: 100%; min-height: 120px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; background: transparent; color: inherit; font: inherit; resize: vertical; } .controls { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin: 12px 0; } .controls label { display: flex; align-items: center; gap: 6px; color: var(--muted); } .controls label small { color: var(--muted); font-size: .8rem; } select, input[type=number] { padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: inherit; font: inherit; } input[type=number] { width: 64px; } button { padding: 8px 16px; border: 0; border-radius: 6px; background: var(--accent); color: var(--accent-fg); font: inherit; font-weight: 600; cursor: pointer; } button:disabled { opacity: .55; cursor: wait; } .chip { background: var(--chip); color: var(--fg); font-weight: normal; padding: 6px 10px; border-radius: 999px; font-size: .9rem; } #examples { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 16px; } .status { color: var(--muted); font-size: .9rem; min-height: 1.5em; margin: 8px 0; } .status.error { color: #c0392b; } .progress { display: grid; grid-template-columns: minmax(120px, 1fr) 2fr auto; gap: 10px; align-items: center; margin: 2px 0; } .bar { height: 8px; background: var(--bar); border-radius: 4px; overflow: hidden; } .bar i { display: block; height: 100%; background: var(--accent); transition: width .2s; } table { width: 100%; border-collapse: collapse; margin-top: 8px; font-size: .92rem; } th, td { text-align: left; vertical-align: top; padding: 8px 8px; border-bottom: 1px solid var(--line); } th { color: var(--muted); font-weight: 600; white-space: nowrap; } td.symbol { font-family: var(--mono); white-space: nowrap; } td.path { color: var(--fg); } #meta { color: var(--muted); font-size: .85rem; margin-top: 8px; } /* graph */ #graph { overflow: auto; margin-top: 12px; border: 1px solid var(--line); border-radius: 8px; } #graph:empty { display: none; } #graph svg { display: block; font: 12px var(--mono); } .edge { fill: none; stroke: var(--edge); stroke-width: 1.5; } .edge.result { stroke: var(--accent); stroke-width: 2.5; } .edge.hover { stroke-width: 4; } .hit { fill: none; stroke: transparent; stroke-width: 24; cursor: pointer; outline: none; } .hit:focus-visible + .edge, .node:focus-visible rect { outline: 2px solid var(--accent); } .edge-labels { pointer-events: none; } /* hovering the number reaches the edge beneath */ .edge-label rect { fill: var(--bg); stroke: var(--line); } .edge-label text { fill: var(--muted); font-size: 11px; } .edge-label.result text { fill: var(--fg); font-weight: 600; } .node { cursor: pointer; outline: none; } .node rect { fill: var(--chip); stroke: var(--line); } .node text { fill: var(--fg); } .node.root rect { fill: var(--bg); stroke: var(--muted); stroke-dasharray: 3 2; } .node.root text { fill: var(--muted); font-weight: 600; } .node.result rect { fill: var(--accent); stroke: var(--accent); } .node.result text { fill: var(--accent-fg); } .node.result text.badge { fill: var(--muted); font: 600 11px system-ui, sans-serif; } .node.hover rect { stroke: var(--fg); stroke-width: 2; } .legend { color: var(--muted); font-size: .85rem; margin: 6px 0 0; } .legend i { display: inline-block; width: 22px; height: 0; vertical-align: middle; margin: 0 4px 0 0; } .legend i.thin { border-top: 1.5px solid var(--edge); } .legend i.thick { border-top: 2.5px solid var(--accent); } #tip { position: fixed; z-index: 10; max-width: 360px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--tip-bg); box-shadow: var(--shadow); font-size: .85rem; pointer-events: none; color: var(--muted); } #tip strong { color: var(--fg); } #tip .tip-symbol { font-family: var(--mono); color: var(--fg); margin-top: 4px; } #tip .tip-title { color: var(--fg); } footer { margin-top: 32px; color: var(--muted); font-size: .85rem; } a { color: var(--accent); } @media (max-width: 640px) { th:nth-child(3), td:nth-child(3), th:nth-child(5), td:nth-child(5) { display: none; } }</style></head><body><main> <h1>text2ipc <small>patent text → IPC symbols, in your browser</small></h1> <p class="lead">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.</p>
<textarea id="text" placeholder="Title and abstract of a patent application, or the whole description: long texts are cut into sentence chunks…" spellcheck="false"></textarea> <div class="controls"> <label>Scheme <select id="lang"></select></label> <label>Level <select id="level"></select></label> <label>Top <input id="topk" type="number" min="1" max="50" value="5"></label> <label id="rerank-label"><input id="rerank" type="checkbox"> Rerank <small>(cross-encoder, about 1 s per candidate)</small></label> <button id="run" type="button">Classify</button> </div> <div id="examples"></div> <div id="status" class="status">Loading…</div> <div id="graph"></div> <p id="legend" class="legend" hidden>Each result's path, merged into one tree: IPC › section › class › subclass › group › subgroups. <i class="thin"></i>similarity of that entry to the text <i class="thick"></i>edge into a result, labelled with its score. Hover or focus an edge or a node for the entry's title. With Rerank, a cross-encoder re-judges the top candidates and the score becomes cosine × (0.5 + 0.5 × judge).</p> <div id="results"></div> <div id="meta"></div> <div id="tip" hidden></div>
<footer> Vectors: one per IPC entry, embedded from its full path (section › class › subclass › group › subgroup). Scoring: cosine similarity, path support and beam descent; <code>auto</code> level stops where the evidence stops. Scheme titles by <a href="https://www.wipo.int/classifications/ipc/en/">WIPO</a> and, for Portuguese, <a href="https://ipc.inpi.gov.br/classifications/ipc/ipcpub/">INPI Brazil</a>. Code, method and evaluation: <a href="https://github.com/Jaimenms/text2ipc">github.com/Jaimenms/text2ipc</a>. </footer></main><script type="module" src="app.js"></script></body></html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788// 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;}.gitattributes-34
README.mdAdded+97
handler.pyAdded+68
index/ipc_20260101_fr_st-intfloat-multilingual-e5-base.parquetAdded+3
requirements.txtAdded+5
scheme/ipc_20260101_fr.parquetAdded+3
text2ipc.jsonAdded+5
text2ipc/__init__.pyAdded+13
text2ipc/chunking.pyAdded+78
text2ipc/classifier.pyAdded+219
text2ipc/cli.pyAdded+400
text2ipc/config.pyAdded+70
text2ipc/embeddings/__init__.pyAdded+3
text2ipc/embeddings/base.pyAdded+79
text2ipc/embeddings/hashing.pyAdded+55
text2ipc/embeddings/ollama.pyAdded+65
text2ipc/embeddings/st.pyAdded+83
text2ipc/eval/__init__.pyAdded+20
text2ipc/eval/cases.pyAdded+70
text2ipc/eval/harness.pyAdded+113
text2ipc/eval/rerank.pyAdded+84
text2ipc/eval/rpi.pyAdded+229
text2ipc/hf/__init__.pyAdded
text2ipc/index/__init__.pyAdded+14
text2ipc/index/build.pyAdded+113
text2ipc/index/migrate.pyAdded+66
text2ipc/index/paths.pyAdded+60
text2ipc/index/publish.pyAdded+43
text2ipc/index/store.pyAdded+130
text2ipc/rerank/__init__.pyAdded+3
text2ipc/rerank/base.pyAdded+72
text2ipc/rerank/hashing.pyAdded+26
text2ipc/rerank/st.pyAdded+77
text2ipc/scheme/__init__.pyAdded+22
text2ipc/scheme/download.pyAdded+50
text2ipc/scheme/inpi.pyAdded+140
text2ipc/scheme/model.pyAdded+25
text2ipc/scheme/overlay.pyAdded+34
text2ipc/scheme/parse.pyAdded+76
text2ipc/scheme/symbols.pyAdded+59
text2ipc/scheme/table.pyAdded+111
text2ipc/search/__init__.pyAdded+3
text2ipc/search/scorer.pyAdded+239
text2ipc/textnorm.pyAdded+30
text2ipc/versions.pyAdded+82
text2ipc/web/__init__.pyAdded+3
text2ipc/web/export.pyAdded+268
text2ipc/web/static/app.jsAdded+706
text2ipc/web/static/index.htmlAdded+129
text2ipc/web/static/rerank-worker.jsAdded+88