Metadata-Version: 2.5
Name: thesaurus-ai
Version: 0.2.0
Summary: Offline compiler for multilingual lexical search artifacts.
Project-URL: Homepage, https://github.com/gia-uh/thesaurus
Project-URL: Repository, https://github.com/gia-uh/thesaurus
Project-URL: Issues, https://github.com/gia-uh/thesaurus/issues
Project-URL: Changelog, https://github.com/gia-uh/thesaurus/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/gia-uh/thesaurus/blob/main/docs/spec.md
Author: GIA-UH, SYALIA S.R.L.
License: MIT
License-File: LICENSE
Keywords: artifacts,lexical,multilingual,nlp,search
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: >=3.12
Requires-Dist: lingo-ai>=2.2.1
Requires-Dist: pydantic>=2.12.4
Requires-Dist: pyyaml>=6.0.3
Provides-Extra: api
Requires-Dist: fastapi>=0.115; extra == 'api'
Requires-Dist: python-multipart>=0.0.20; extra == 'api'
Requires-Dist: uvicorn>=0.32; extra == 'api'
Description-Content-Type: text/markdown

# Thesaurus

[![CI](https://github.com/gia-uh/thesaurus/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/gia-uh/thesaurus/actions/workflows/ci.yml)

Thesaurus is a co-development between **GIA-UH** and **SYALIA S.R.L.**

Thesaurus is an offline compiler that turns arbitrary corpora into multilingual
lexical search artifacts.

LLMs and embeddings are used **only at build time**. The artifact is
self-contained: a lexical search runtime can load it without models, embeddings,
or network access.

```text
corpus + config ──► compiler ──► artifact/ ──► Artifact API
                     (LLM,          │             (read-only,
                      embeddings)   │              no models)
                                    └──────────► thesaurus-search
                                                  (lexical, no models)
```

The compiler is the product; the artifact is the contract. The project has two
separate HTTP planes:

| Plane | Purpose | Writes | Default |
|---|---|---|---|
| **Build API** | Run compilation jobs | Yes | `:8001` |
| **Artifact API** | Serve mounted artifacts | No | `:8000` |

They are different FastAPI applications with different routes, auth, and
lifecycle. The Build API never proxies artifact routes. The Artifact API never
runs the compiler.

## Install

From PyPI:

```bash
pip install thesaurus-ai
pip install "thesaurus-ai[api]"   # Build API and Artifact API
```

From source:

```bash
uv sync                 # compiler, CLIs, reader, and search runtime
uv sync --extra api     # Build API and Artifact API
```

Requires Python 3.12+.

## Compile an artifact

```bash
uv run thesaurus build --config config.example.yaml
```

The default config reads `examples/corpus.jsonl` and writes `artifact/`:

```yaml
languages:
  source: es
  targets: [en]

models:
  llm: gpt-4.1-mini
  embedding: text-embedding-3-small
  api_key_env: API_KEY
```

API keys are read from the environment named by `models.api_key_env`. They are
never written to the artifact.

For the loaded LM Studio models, use `config.lmstudio.yaml`:

```bash
export LMSTUDIO_API_KEY=lm-studio
uv run thesaurus build --config config.lmstudio.yaml
```

LM Studio does not require a real key, but the OpenAI client requires a non-empty
value.

CLI flags override the config:

```bash
uv run thesaurus build \
  --config config.yaml \
  --output ./artifacts/feria-2026 \
  --artifact-id feria-2026 \
  --overwrite
```

`--serve` builds and then starts the Artifact API for the new artifact:

```bash
uv run thesaurus build --config config.yaml --serve --port 8000
```

## Compile from Python

```python
import asyncio

from thesaurus import Compiler, load_config

config = load_config("config.yaml")
result = asyncio.run(Compiler(config).build())

print(result.artifact_id, result.path, result.counts)
```

For records already in memory:

```python
from thesaurus import compile_records

# records: list[thesaurus.models.Record]
result = asyncio.run(compile_records(records, config))
```

`Compiler` accepts optional `generator`, `translator`, and `embedder` objects
implementing the protocols in `thesaurus.compiler.services`; this is how the
test suite runs without network access.

## Incremental builds

The cache is enabled by default and lives next to the artifact in
`.thesaurus-cache/`. It is content-addressed, atomic, and outside the artifact
contract.

```bash
uv run thesaurus build --config config.yaml                    # default cache
uv run thesaurus build --config config.yaml --cache-dir ./cache # explicit path
uv run thesaurus build --config config.yaml --no-cache           # disable
```

A second build with unchanged corpus and configuration makes **zero LLM,
translation, and embedding calls**. Translation, generation, and embedding
entries are keyed by text, context, model, prompt version, glossary, and the
semantic configuration. A fully cached rebuild does not need model credentials.

Cache hits, misses, writes, and errors are reported in `BuildResult.cache` and
in the CLI JSON output. Corrupt entries are ignored and rebuilt. If the cache
directory is not writable, the build continues and records a warning. The cache
is safe to delete.

## Search an artifact

The `thesaurus_search` runtime is a separate lexical layer. It never calls
models, embeddings, or the network, and the Artifact API itself remains
read-only and search-free.

```bash
uv run thesaurus-search query "robtóica" --artifact ./artifacts/feria-2026
uv run thesaurus-search query "pabell" --artifact ./artifacts/feria-2026 --mode prefix
uv run thesaurus-search query "robótica" --artifact ./artifacts/feria-2026 --mode exact
```

**Fuzzy is the default.** Exact search must be requested explicitly:

| Mode | Behavior |
|---|---|
| `fuzzy` (default) | Exact + prefix + bounded typo correction + concept expansion |
| `prefix` | Exact + prefix completion, no typos |
| `exact` | Strict token equality only |

```python
from thesaurus_search import SearchClient

client = SearchClient.open("./artifacts/feria-2026")
response = client.search("robtóica")                  # fuzzy
response = client.search("pabell", mode="prefix")     # exact + prefix
response = client.search("robótica", mode="exact")    # strict
```

Fuzzy matching uses trigram candidates and bounded Damerau-Levenshtein
distance, with distance 1 allowed for tokens of 5–7 characters and distance 2
for longer tokens. Short tokens, codes, and numbers are not expanded. Results
are ranked with BM25 and include the exact, prefix, fuzzy, or expansion reason
for every match.

Filters include `language`, `view`, `statuses`, `field_paths`, and `form_types`.
The CLI also exposes `thesaurus-search stats`.

## Browser search (vanilla JavaScript)

The `js/` directory contains a dependency-free browser client. It loads the
`.tar.gz` bundle directly, decompresses it with the native gzip stream, parses
the TAR, and searches locally. No npm, Node, bundler, server, or model is
required.

```html
<script type="module">
  import { SearchClient } from "./js/index.js";

  const response = await fetch("./feria-2026.tar.gz");
  const client = await SearchClient.fromBundle(response);

  console.log(client.search("robtóica"));                 // fuzzy default
  console.log(client.search("pabell", { mode: "prefix" }));
  console.log(client.search("robótica", { mode: "exact" }));
</script>
```

It implements the same modes, BM25 ranking, concept expansion, filters, and
result explanations as the Python runtime. See [`js/README.md`](js/README.md)
for the API and the browser test page.

## Use the reader from Python

```python
from thesaurus import Artifact

artifact = Artifact.open("./artifacts/feria-2026")

artifact.manifest
artifact.documents.get("doc-3")
artifact.fields.filter(document_id="doc-3")
artifact.forms.filter(language="en", type="query")
artifact.concepts.get("concept-robotics")
artifact.relations.filter(source_id="concept-robotics")
artifact.views.get("lang-en")

bundle = artifact.bundle("doc-3", include={"fields", "forms", "concepts"})
```

Collections are lazy and indexed by id on first access. The reader never writes
to the artifact directory.

Validate an artifact before serving or publishing it:

```bash
uv run thesaurus validate --artifact ./artifacts/feria-2026
uv run thesaurus validate --artifact ./artifacts/feria-2026 --json
```

Validation checks manifest hashes, collection counts, unique ids, foreign keys,
form normalization, and view field paths.

## Serve artifacts

```bash
uv run thesaurus artifact-api --scan ./artifacts --port 8000
# or mount explicit directories
uv run thesaurus artifact-api \
  --artifact ./artifacts/feria-2026 \
  --artifact ./artifacts/feria-2025 \
  --port 8000
```

Main endpoints:

| Endpoint | Returns |
|---|---|
| `GET /artifacts` | Mounted artifacts |
| `GET /artifacts/{id}` | Manifest |
| `GET /artifacts/{id}/documents` | Documents |
| `GET /artifacts/{id}/documents/{doc_id}` | One document |
| `GET /artifacts/{id}/documents/{doc_id}/bundle` | Document + fields + forms + concepts + relations |
| `GET /artifacts/{id}/fields` | Fields |
| `GET /artifacts/{id}/forms` | Generated forms |
| `GET /artifacts/{id}/concepts` | Concepts |
| `GET /artifacts/{id}/relations` | Concept relations |
| `GET /artifacts/{id}/links` | Field/form → concept links |
| `GET /artifacts/{id}/views` | Views |
| `GET /artifacts/{id}/export` | tar.gz bundle of the artifact |

Listings support filters, pagination, sorting, and nested grouping:

```bash
curl 'http://127.0.0.1:8000/artifacts/feria-2026/forms?language=en&type=query&limit=20'
curl 'http://127.0.0.1:8000/artifacts/feria-2026/forms?group_by=language,type'
```

```json
{
  "data": {
    "es": {"paraphrase": ["..."], "query": ["..."]},
    "en": {"paraphrase": ["..."], "query": ["..."]}
  },
  "meta": {"group_by": ["language", "type"], "count": 42}
}
```

Set `THESAURUS_ARTIFACT_TOKEN` to require `Authorization: Bearer <token>` or
`X-API-Key: <token>`. Send `SIGHUP` to rescan mounts without a restart.

## Build over HTTP

```bash
export THESAURUS_BUILD_TOKEN="change-me"
uv run thesaurus build-api --output ./artifacts --port 8001
```

The Build API refuses to start without a token.

```bash
curl -X POST http://127.0.0.1:8001/builds \
  -H "Authorization: Bearer $THESAURUS_BUILD_TOKEN" \
  -F config=@config.yaml \
  -F corpus=@examples/corpus.jsonl \
  -F artifact_id=feria-2026 \
  -F serve=true
```

Returns a job immediately:

```json
{
  "data": {
    "build_id": "bld-01J...",
    "status": "queued",
    "links": {"self": "/builds/bld-01J...", "events": "/builds/bld-01J.../events"}
  }
}
```

| Endpoint | Purpose |
|---|---|
| `POST /builds` | Start a build |
| `GET /builds` | List jobs |
| `GET /builds/{id}` | Status, phase, progress, counts |
| `GET /builds/{id}/events` | Server-sent progress events |
| `GET /builds/{id}/result` | Artifact id, path, manifest, counts |
| `POST /builds/{id}/cancel` | Cancel a queued or running build |
| `DELETE /builds/{id}` | Remove the job and its uploads |
| `POST /servers` | Start an Artifact API for a directory |
| `GET /servers` | List managed Artifact APIs |
| `DELETE /servers/{id}` | Stop a managed Artifact API |

`serve=true` asks the Build API to launch an Artifact API for the output root
and return its URL. This is an in-process convenience for local use. In
production, run the Artifact API separately and point both services at the same
shared directory.

The handoff is the filesystem:

```text
Build API writes {output_root}/{artifact_id}/
Artifact API mounts {output_root}/
Clients cross only artifact_id.
```

## Artifact layout

```text
artifact/
  manifest.json     # format version, languages, models, counts, file hashes
  documents.jsonl   # original documents and fields
  fields.jsonl      # canonical fields + translated variants
  forms.jsonl       # paraphrases, queries, terms, answers
  concepts.jsonl    # reusable concepts with labels per language
  relations.jsonl   # typed concept relations
  links.jsonl       # field/form → concept links
  views.json        # named projections
  audit.jsonl       # build events
```

The artifact is the source of truth. The reader and the Artifact API add no
state and no data.

## Portable bundles

An artifact directory is portable as-is. To move it between machines, export it
as a tar.gz bundle, transfer the file, and extract it into the exact directory you
want to use:

```bash
# Build into a chosen directory
uv run thesaurus build --config config.yaml --output ./artifacts/feria-2026

# Bundle it
uv run thesaurus export --artifact ./artifacts/feria-2026 --output ./feria-2026.tar.gz

# Extract into a chosen directory
uv run thesaurus extract --bundle ./feria-2026.tar.gz --output ./deploy/feria-2026

# Serve from the extracted path
uv run thesaurus artifact-api --artifact ./deploy/feria-2026 --port 8000
```

Both the Python reader and the browser client can read a bundle directly,
without an explicit extraction step:

```python
from thesaurus import Artifact

with Artifact.open("./feria-2026.tar.gz") as artifact:
    print(artifact.artifact_id)
    artifact.forms.filter(language="es")

Artifact.extract_bundle("./feria-2026.tar.gz", "./deploy/feria-2026")
artifact = Artifact.open("./deploy/feria-2026")
artifact.export_bundle("./backup.tar.gz")
```

Bundles are validated on export and extract, reject unsafe paths, and contain
the artifact files at the archive root. There is no registry, object storage, or
publication service: the tar.gz file is the transport and the extracted
directory is what the Artifact API mounts.

## How generation works

1. The adapter reads JSON, JSONL, or CSV into canonical `Record` objects.
2. Documents and fields are preserved; every field is a generation unit.
3. The source field is translated per target language (default strategy).
4. One structured LLM call per field and language produces candidates:
   paraphrases, queries, key terms, a short answer, concepts, and relations.
5. Candidates are embedded, filtered by a per-type threshold, reduced to a
   Pareto front, and selected with greedy max-min diversity.
6. Concepts are merged, relations deduplicated, and fields/forms linked.
7. Views, audit events, and the layered artifact are written atomically.

Translation strategies:

- `translate_source` (default): translate the field, then generate per language.
- `translate_candidates`: generate in the source language, translate candidates.
- `select_then_translate`: select in the source language, translate selected forms.

Context modes: `field`, `document`, `auto` (default). `auto` uses the full
document when it fits; otherwise an extractive summary plus relevant sibling
fields and metadata.

## Configuration

See [`config.example.yaml`](config.example.yaml). Semantic layers (concepts,
relations, views) are artifact data, not configuration.

An optional glossary is a YAML mapping from a source term to its translations:

```yaml
# glossary.yaml
robótica:
  en: robotics
  fr: robotique
```

```yaml
translation:
  glossary: glossary.yaml
  preserve: [SKU, "Model X"]
```

## Development

```bash
uv sync --extra api
uv run pytest -q
uv run ruff check .
```

The test suite uses deterministic generator, translator, and embedder doubles;
no network or model credentials are required.

## Status

MVP base implemented:

- [x] Execution configuration and validation
- [x] JSON/JSONL and CSV adapters with a registry
- [x] Field-level translation and candidate generation
- [x] Thresholds, Pareto front, and greedy max-min selection
- [x] Concepts, relations, links, views, and audit
- [x] Atomic layered artifact writer
- [x] Python artifact reader
- [x] Artifact validation with `thesaurus validate`
- [x] Portable tar.gz bundles with `export`, `extract`, and direct library reads
- [x] Incremental content-addressed build cache
- [x] Lexical search runtime with fuzzy default, prefix, and exact modes
- [x] Vanilla JavaScript browser search from a tar.gz bundle
- [x] Build API with jobs, progress, cancellation, and server lifecycle
- [x] Read-only Artifact API with filtering, grouping, bundles, and export
- [x] CLI: `build`, `build-api`, `artifact-api`, `inspect`, `validate`, `export`, `extract`, `thesaurus-search`

Not in the MVP: a search HTTP service, review UI, cross-artifact joins,
persistent job storage, and automatic publication/registries. The portable
artifact bundle is the supported transport. The Artifact API deliberately does
not search; `thesaurus_search` is the runtime consumer.

See [`docs/spec.md`](docs/spec.md) for the consolidated design.

## License

MIT. See [`LICENSE`](LICENSE).

## Changelog

See [`CHANGELOG.md`](CHANGELOG.md).
