Legal document analysis organized by matter. The ingestion pipeline converts matter files into versioned text, legal structure, source locations, metadata, and search records.
The metadata extraction plan describes what is built: the document types, the fields for each type, and how they are extracted and verified. The longer-term legal document intelligence design covers the research and later phases.
A Turborepo monorepo managed with pnpm workspaces. Turborepo schedules the tasks below and caches their outputs in .turbo/.
| Path | Contents |
|---|---|
apps/web |
Next.js frontend (@lexintel/web), source grouped under src/ |
apps/api |
FastAPI service, ingestion worker, ranking service, database image, and tests (@lexintel/api), Python package grouped under src/ |
apps/api/benchmarks |
Retrieval benchmarks and fixtures |
test_cases/ |
Sample matters for manual testing |
Install the JavaScript dependencies once from the root (pnpm is provided via Corepack):
pnpm install| Command | Effect |
|---|---|
pnpm dev |
Start the web dev server and the API with reload together |
pnpm dev:web |
Start only the Next.js dev server in apps/web |
pnpm dev:api |
Run only the API locally with reload (needs a reachable database, for example Compose) |
pnpm dev:worker |
Run the ingestion worker locally (needs a reachable database) |
pnpm build |
Production build of the frontend |
pnpm lint / pnpm check-types |
Lint and type-check the frontend |
pnpm test |
Backend fast test suite through uv |
pnpm cli -- <file.pdf> |
Run the local PDF inspector |
pnpm scrape --from 01-01-2024 --to 31-01-2024 --out judgments |
Download Supreme Court of India judgments by date, mirrored to R2 when configured |
pnpm scrape --sync judgments |
Upload already-downloaded PDFs to R2 without re-scraping |
The backend keeps its own Python toolchain (uv, pyproject.toml, uv.lock) inside apps/api. Its package.json only wraps the common uv commands so Turborepo can schedule them.
docker compose up --build -d
docker compose psDocker starts FastAPI, the ingestion worker, and PostgreSQL with pgvector and BM25. The API listens at http://localhost:8000 and exposes interactive API documentation at /docs. The frontend can run with pnpm dev from the repository root. It uses the local API by default. The Compose stack is for local development and uses a loopback API binding.
curl -fsS http://localhost:8000/health
curl -fsS http://localhost:8000/matters \
-F 'name=Patent fixture' \
-F 'files=@test_cases/matter1_ip_dispute/complaint_patent_infringement.txt'Create a matter with up to 20 files or upload a single file to an existing matter. PDF, DOCX, and UTF-8 text files up to 50 MiB are accepted. The worker supports native and scanned PDFs, OCR on mixed pages, LibreOffice PDF previews for Word, Docling layout and tables, type-specific metadata, and evidence-backed chunks. The worker may download public Docling model weights on its first PDF job. Docker volumes retain originals, parsed data, and models.
Judgment chunks follow numbered paragraphs. When a long paragraph splits at a sentence boundary, the next chunk can repeat one complete sentence, with up to 250 characters of overlap within the 1,750-character chunk limit. The repeated sentence keeps its original source offsets.
Visit the matter's Documents tab or use these API routes with the IDs returned from upload:
| Route | Output |
|---|---|
GET /matters/{matter}/documents |
Job status, warnings, and embedding request and token counts |
GET /matters/{matter}/documents/{document}/artifact |
Pages and coordinates, profile, sections, tables, references, chunks, and warnings |
GET /matters/{matter}/documents/{document}/preview |
PDF or rendered Word preview and plain-text originals |
GET /matters/{matter}/chunks?document_id={document} |
Parsed chunks, including when indexing is paused |
POST /matters/{matter}/documents/{document}/retry |
Requeue an eligible job using any existing parse and completed embedding batches |
apps/api/src/lexintel_ingest/sci_scraper.py downloads judgments from the Supreme Court's public Judgment Date service. It is a command line tool, not part of the ingestion worker.
# Metadata and PDFs for a period (max 31 day search windows are split automatically)
pnpm scrape --from 01-01-2024 --to 31-03-2024 --out judgments --manifest judgments/index.json
# Metadata only
pnpm scrape --from 01-01-2024 --to 31-01-2024 --no-pdfPDFs are written to --out named after the court's own filename, and re-running skips files already on disk. The script runs from apps/api, so a relative --out or --manifest resolves there: --out judgments writes to apps/api/judgments/, which git ignores. --manifest records the diary number, case number, parties, advocates, bench, judgment date, and source URL for every judgment as JSON.
The service allows at most 31 days per search, so longer periods are split into consecutive windows. The form nonce is read from the page markup, and the CAPTCHA is bypassed with the same sci_auto_submit flag the site's own JavaScript sends. robots.txt allows the /wp-admin/admin-ajax.php endpoint the service uses. Only direct PDF links are followed; the HTML viewer links in the results return a database error instead of a document.
When R2 credentials are in the environment, every downloaded PDF is also uploaded to the bucket and the manifest is uploaded next to it. Objects are keyed as {R2_PREFIX}/{filename} using the court's own filename, so a file downloaded by a scrape and one uploaded later with --sync land on the same key. A PDF that already exists in R2 is not downloaded again. Without credentials the scraper stays local-only, exactly as before.
| Variable | Required | Purpose |
|---|---|---|
R2_ACCOUNT_ID |
Yes | Cloudflare account ID; builds the <account>.r2.cloudflarestorage.com endpoint |
R2_ACCESS_KEY_ID |
Yes | R2 access key ID from an S3-compatible API token |
R2_SECRET_ACCESS_KEY |
Yes | R2 secret access key |
R2_BUCKET |
Yes | Bucket name |
R2_PREFIX |
No | Key prefix, for example judgments/sci. Slashes are normalised |
R2_ENDPOINT_URL |
No | Overrides the endpoint, for a local S3 emulator such as MinIO |
R2_PUBLIC_BASE_URL |
No | When set, each manifest entry gets an r2_url for its PDF |
The four required variables must be set together. A partially configured environment stops the run with a message naming the missing variable instead of silently writing to disk. Put them in an ignored .env (see .env.example) or export them in the shell.
# Scrape and mirror to R2
R2_ACCOUNT_ID=… R2_ACCESS_KEY_ID=… R2_SECRET_ACCESS_KEY=… R2_BUCKET=lexintel-judgments R2_PREFIX=judgments \
pnpm scrape --from 01-01-2024 --to 31-03-2024 --out judgments --manifest judgments/index.json
# Upload PDFs already on disk (for example a directory scraped before R2 was configured) without re-scraping
pnpm scrape --sync judgments
# Report what --sync would upload without writing anything
pnpm scrape --sync judgments --dry-run
# Keep a run local even when R2 is configured
pnpm scrape --from 01-01-2024 --to 31-01-2024 --no-r2--sync uploads every *.pdf directly inside the directory, skips empty files and objects already in the bucket, and never contacts the court. It needs R2 credentials and exits non-zero when any upload fails. Scrape runs count uploads separately (uploaded, already in R2, upload failures) from downloads, and an R2 failure never discards the local copy. The manifest's storage block records whether the run targeted local or r2, with the bucket, prefix, and endpoint.
Scrape runs also exit non-zero if any search window, PDF download, or R2 upload fails, including partial failures. Re-run the same date range to retry missing objects. HTTP 429 and server errors are retried with exponential backoff. --dry-run requires --sync; it cannot be used for a scrape. Use a dated manifest name for each batch to keep separate runs from replacing the same R2 manifest.
Paid indexing is off by default. Parsing, OCR, metadata, and table extraction run locally and still produce a readable artifact. A successfully parsed document stays in awaiting_index until indexing is enabled. To enable it, set LEXINTEL_PAID_INDEXING=1 and provide OPENROUTER_API_KEY to the worker in your local environment or ignored .env. Recreate the worker with docker compose up -d worker, then retry the documents you want indexed.
Indexing uses Voyage 4 Large at 1,024 dimensions. The worker batches distinct search passages, reuses successful batches after retries, and deduplicates identical uploads within a matter. It records successful provider request counts and input tokens. The worker rejects a document if the combined UTF-8 size of its distinct embedding inputs exceeds 2 MB.
Run the fast checks from the repository root:
npm run testRun the integration suite against a separate Docker project. It exercises the real database, job worker, Docling, Tesseract, and LibreOffice with simulated embeddings.
docker compose -p lexintel-test run --rm --build --user root -T \
-e LEXINTEL_INTEGRATION_TESTS=1 -e LEXINTEL_PAID_INDEXING=0 \
-v "$PWD/apps/api/tests:/tests:ro" worker \
sh -c 'uv sync --locked --group parser && python -m unittest discover -s /tests -v'The local native PDF inspector is also available without starting services:
npm run cli -- /absolute/path/to/document.pdfThe Ask AI tab searches passages from the selected matter with PostgreSQL BM25 and local E5 embeddings, then reranks the combined candidates with local MiniLM. The Docker ranking service downloads public model weights on first start and indexes parsed passages in the background. Search falls back to BM25 while the service is unavailable, busy, or indexing that matter. It shows ranked passages, source pages, and links to the originals or rendered previews. Searches use no provider tokens. Saved chats are scoped to the matter.
For an existing Compose database, apply the retrieval migrations before starting the updated API. The first command backfills BM25 passages. The ranking service fills the local vector table automatically.
docker compose exec -T db psql -v ON_ERROR_STOP=1 --single-transaction -U lexintel -f - < apps/api/db/retrieval.sql
docker compose exec -T db psql -v ON_ERROR_STOP=1 --single-transaction -U lexintel -f - < apps/api/db/local-ranking.sqlThe held-out retrieval benchmark includes the scored comparison and reproduction commands. Set LEXINTEL_RANKER_URL= when starting Compose to use BM25 only.
Ask AI writes answers through the Codex CLI on the host, using its signed-in
subscription; no API key or per-token billing is involved. Sign in once with
codex login, then start the answer service with pnpm dev:answer from the root.
It listens on 127.0.0.1:8002 and runs codex exec per question in an empty
temporary directory with a read-only sandbox, the user Codex config ignored, and a
JSON schema for the reply. Set LEXINTEL_CODEX_MODEL or LEXINTEL_CODEX_EFFORT
(default low) to change the model or reasoning effort. Compose connects to the
host on port 8002; set LEXINTEL_ANSWER_URL= to disable generation.
Every retained claim must cite a retrieved passage and supply a quote of at least four words or twenty characters found in that passage. The comparison ignores case, quote style, whitespace and invisible PDF control characters, so a PDF that splits "2 nd" still matches a quote of "2nd"; every visible character must match. Unsupported claims are dropped; if none remain, the system abstains. This checks textual evidence, not logical entailment. If generation is unavailable, Ask AI still returns retrieved passages.
Evaluate against the real API (with the benchmark matters already ingested):
cd apps/api
PYTHONPATH=src uv run --locked python benchmarks/answer_eval.py --only heldout --output results.jsonOmit --only to run both suites, or use --only oracle. The runner removes
the conversations it creates and reports fact support, retrieval, citation
validity, abstention, latency, and local token counts. See the
grounded-answer benchmark for the first scored run.
Each parsed document gets a type and a fixed set of fields for that type (for
example court, case number, judges, decision date and disposition for a judgment;
rent, deposit and lock-in for a lease; number, department and parent act for a
notification). The definitions live in one registry,
apps/api/src/lexintel_ingest/metadata/registry.py, which the classifier, the
model prompt, the API (GET /schemas) and the frontend all read.
Extraction runs in two stages:
- Rules, inside the parser: a scored classifier and per-type patterns. They need no network and always run.
- Model, in the worker after parsing: when the rules are unsure of the type, the
Codex answer service classifies the document. It then proposes the remaining
fields from the opening, closing and most relevant passages. Every proposed
value must quote the document. The quote is located in the page text and stored
as evidence; values without a matching quote are dropped. A model value never
replaces a rule value or a user correction; a disagreement is marked
conflicting.
If the answer service is not running, documents still finish, with rule fields only
and extraction.status = "partial". Set LEXINTEL_METADATA_MODEL=0 to skip the
model stage, or LEXINTEL_METADATA_TIMEOUT (seconds, default 240) to change its
time limit. Expect roughly 30 to 90 seconds of model time per document.
In the Documents tab, a Details view shows the fields with links to their
source passages. You can correct a value or the document type there. A type change
rebuilds the document's sections and re-indexes it. Re-extract runs the model
again and keeps corrected fields. The document list can be filtered by type and
party; the API also accepts date_from and date_to.
For an existing database, re-apply retrieval.sql (see above) so that metadata
edits do not trigger passage re-indexing. Then backfill documents parsed before this
feature. This uses the stored pages, not a new parse:
docker compose exec worker python -m lexintel_ingest.metadata.backfill --dry-run
docker compose exec worker python -m lexintel_ingest.metadata.backfill # rules only
docker compose exec worker python -m lexintel_ingest.metadata.backfill --model # also call CodexMeasure classification and extraction against the labelled sets (see metadata evaluation):
cd apps/api
PYTHONPATH=src uv run --locked python benchmarks/metadata_eval.py --split all
PYTHONPATH=src uv run --locked python benchmarks/metadata_eval.py --split heldout --model http://127.0.0.1:8002