Commit graph

71 commits

Author SHA1 Message Date
Pier-Jean Malandrino
c281b6c551 fix: classify pipeline errors into user-friendly messages (M1)
Raw PyTorch/Docling stack traces are no longer shown to the user.
Common failures (missing compiler, OOM, lock contention, corrupted
document) are mapped to actionable messages. Unknown errors are
truncated to 200 chars.

Ref #57 (M1)
2026-04-07 15:32:38 +02:00
Pier-Jean Malandrino
f89dc51661 fix: reset _default_converter on init failure (H5)
If the lazy-init of the default converter fails (e.g. model download
error), the singleton was left as None but subsequent calls would not
retry. Now the failed state is cleared so the next request retries.

Ref #57 (H5)
2026-04-07 15:32:38 +02:00
Pier-Jean Malandrino
f58b563a13 fix: make default table_mode configurable via DEFAULT_TABLE_MODE (H1)
TableFormerMode.ACCURATE is very expensive on CPU (~3-5x slower).
The default can now be set to "fast" on resource-constrained
environments (HF Spaces) via the DEFAULT_TABLE_MODE env var.

User-specified table_mode in the request still takes precedence.

Ref #57 (H1)
2026-04-07 15:32:38 +02:00
Pier-Jean Malandrino
6327b13614 fix: pass max_num_pages and max_file_size to Docling convert (C3)
Defense-in-depth: even if upload validation passes, Docling itself
now enforces page count and file size limits. Configurable via
MAX_PAGE_COUNT and MAX_FILE_SIZE env vars (0 = unlimited).

Ref #57 (C3)
2026-04-07 15:32:38 +02:00
Pier-Jean Malandrino
c0fb128718 fix: replace _converter_lock with timeout-based acquisition (C2)
A frozen conversion holding the lock indefinitely blocks all subsequent
jobs. Using lock.acquire(timeout=300) fails fast with a clear error
instead of waiting forever.

Ref #57 (C2)
2026-04-07 15:32:38 +02:00
Pier-Jean Malandrino
4c76101142 fix: add document_timeout to PdfPipelineOptions (C1)
Docling's native document_timeout is the only mechanism that can
interrupt processing inside a blocked thread (OCR, table extraction).
Without it, asyncio.wait_for cannot stop a frozen conversion.

Configurable via DOCUMENT_TIMEOUT env var (default: 120s).

Closes #57 (C1)
2026-04-07 15:32:38 +02:00
Pier-Jean Malandrino
05ed49b893 Add issue templates, GitHub stars badge, fix health endpoint type hint 2026-04-07 11:57:29 +02:00
Pier-Jean Malandrino
09145206d2 fix: limit upload to 5 MB / 20 pages max and increase conversion timeout
Prevents PyTorch/Docling pipeline crashes on HF Spaces CPU by:
- Reducing max file size from 50 MB to 5 MB
- Adding configurable MAX_PAGE_COUNT setting (env var, default unlimited)
- Increasing conversion timeout from 600s to 900s
- Adding frontend upload validation with explicit error messages
- Exposing maxPageCount via /api/health for dynamic UI hints
2026-04-07 10:56:16 +02:00
Pier-Jean Malandrino
ee57b04f84 Add disclaimer banner for shared deployments (HuggingFace)
Feature-flagged via DEPLOYMENT_MODE env var and /api/health endpoint.
Disabled by default (self-hosted), enabled when deploymentMode=huggingface.
2026-04-04 21:06:38 +02:00
Pier-Jean Malandrino
1c82a80389 Guard all docling-dependent tests for lightweight CI
local_converter imports docling at module level, so any test that
touches it crashes when docling is not installed. Skip those tests
with importorskip / skipif so the CI (which only has docling-core)
passes cleanly.
2026-04-03 15:46:29 +02:00
Pier-Jean Malandrino
d8f87c34bc Skip pipeline options tests when docling is not installed
The docling library (torch, transformers) is too heavy for lightweight
CI environments that only install docling-core. Use importorskip so
these tests are cleanly skipped instead of crashing collection.
2026-04-03 15:42:14 +02:00
Pier-Jean Malandrino
fefd406dc8 Align tests with schema refactoring (AliasChoices, status codes)
Adapt test expectations to external changes: upload returns 200,
ValueError yields 400, and schemas now accept both snake_case and
camelCase via AliasChoices.
2026-04-03 14:21:30 +02:00
Pier-Jean Malandrino
503b7e8a40 Fix import ordering violations (ruff I001)
Reorder first-party imports in local_converter and local_chunker to
satisfy isort rules: domain imports before infra imports.
2026-04-03 14:05:38 +02:00
Pier-Jean Malandrino
a9299e2735 Add document_service tests for upload, preview, and deletion
Cover PDF validation, file size limits, preview generation, page
counting, file deletion with path traversal protection, and the
not-found case — all previously untested code paths.
2026-04-03 13:57:05 +02:00
Pier-Jean Malandrino
d089bb8670 Add in-memory rate limiting middleware
Lightweight sliding-window per-IP rate limiter (100 req/min default)
with no external dependency. Health endpoint is excluded. Returns 429
with Retry-After header when exceeded. Sufficient for single-process
SQLite deployments; document the Redis upgrade path for scale.
2026-04-03 13:56:05 +02:00
Pier-Jean Malandrino
c82fd66ffc Add docstrings to all public methods
Domain model state transitions, repository CRUD operations, and service
methods now have descriptive docstrings to lower the contribution
barrier for an open-source project.
2026-04-03 13:54:52 +02:00
Pier-Jean Malandrino
8ee470f1aa Add database ping to health check endpoint
Health endpoint now verifies SQLite connectivity and reports a
"degraded" status when the database is unreachable, instead of
blindly returning "ok".
2026-04-03 13:53:01 +02:00
Pier-Jean Malandrino
360ea7ea8f Stream upload reads in 64 KB chunks
Read uploaded files in fixed-size chunks instead of a single file.read()
to reduce peak memory pressure. Also enforces the size limit during
streaming so oversized payloads are rejected before fully buffered.
2026-04-03 13:52:32 +02:00
Pier-Jean Malandrino
c2e91262c6 Limit concurrent analyses with asyncio.Semaphore
Unbounded asyncio.create_task calls could exhaust CPU and memory on
modest hardware. Add a configurable semaphore (MAX_CONCURRENT_ANALYSES,
default 3) so excess jobs queue instead of running all at once.
2026-04-03 13:51:53 +02:00
Pier-Jean Malandrino
7bd7d0f793 Validate page bounds on preview endpoint
Reject requests where page exceeds the document page count with a clear
400 error, instead of letting pdf2image fail with an opaque exception.
2026-04-03 13:50:32 +02:00
Pier-Jean Malandrino
661568f2cb Add return type annotations and use 201 for upload
All endpoint functions, lifespan context manager, and get_connection now
have explicit return types. Upload endpoint returns 201 Created instead
of 200 to follow REST conventions.
2026-04-03 13:50:07 +02:00
Pier-Jean Malandrino
69ce1df5a1 Narrow exception handlers for better diagnostics
Replace broad `except Exception` with specific types (FileNotFoundError,
PermissionError, OSError) so errors are properly categorized in logs.
Users reporting bugs will get actionable messages instead of generic ones.
2026-04-03 13:48:33 +02:00
Pier-Jean Malandrino
c50106c185 Centralize config through Settings singleton
UPLOAD_DIR and DB_PATH were read directly from os.environ, bypassing
the Settings dataclass. This caused an inconsistency where overriding
Settings had no effect on these values. Now all modules import from
infra.settings.settings.
2026-04-03 13:47:53 +02:00
Pier-Jean Malandrino
ab6d42aecd Move bbox.py from domain/ to infra/ and unify coordinate logic
domain/ must be pure with no external dependencies. bbox.py imports
docling_core and belongs in infra/. Also refactor ServeConverter to
use the canonical to_topleft_list via BoundingBox instead of
duplicated manual coordinate conversion. Move docling-core to base
requirements since it is now needed in both modes.
2026-04-03 13:17:26 +02:00
Pier-Jean Malandrino
dbcd9dfa4c Fix naive datetime fallbacks in repository layer
Use UTC-aware datetimes consistently to prevent TypeError when
comparing aware and naive datetime objects.
2026-04-03 13:04:44 +02:00
Pier-Jean Malandrino
8856daf3c9 Force .pdf extension on uploaded files regardless of user input
The file content is already validated as PDF, so the user-supplied
extension should not be trusted or written to disk.
2026-04-03 13:03:21 +02:00
Pier-Jean Malandrino
2cbef859e7 Fix generate_page_images option silently dropped in remote mode
The form data builder was not forwarding generate_page_images to
Docling Serve, so page image generation was silently ignored.
2026-04-03 13:01:50 +02:00
Pier-Jean Malandrino
e1636e710d Fix ServeConverter not returning document_json for chunking
The remote converter never set document_json in ConversionResult,
silently preventing chunking from working in remote mode.
2026-04-03 13:00:43 +02:00
Pier-Jean Malandrino
abe59c3cb7 Fix health endpoint not reachable through nginx proxy
Move /health to /api/health on backend and update the frontend
feature flag store to match. Without this, the combined Docker
image nginx proxy could not reach the endpoint and feature flags
(chunking/prepare mode) failed to load.
2026-04-03 12:14:15 +02:00
Pier-Jean Malandrino
48c5e4ea6b Fix RapidOCR model download permission in local image
Grant appuser write access to rapidocr/models directory so OCR
models can be downloaded at runtime.
2026-04-03 10:44:20 +02:00
Pier-Jean Malandrino
48b7d5d3e8 Use CPU-only torch in local image to reduce size from 5.8GB to 1.9GB
Install torch and torchvision from the CPU-only index before docling
to avoid pulling CUDA/nvidia/triton dependencies. Update documentation
with measured image sizes (270MB remote, 1.9GB local).
2026-04-03 09:52:22 +02:00
Pier-Jean Malandrino
9ac0840607 Add multi-target Dockerfiles for remote and local builds
Both root and backend Dockerfiles now use a shared base stage with
two targets: remote (lightweight, ~300MB) and local (full Docling,
~2-3GB). docker-compose uses CONVERSION_MODE to select the target.
2026-04-03 09:24:41 +02:00
Pier-Jean Malandrino
8dd917b6ed Split requirements into base and local variants
Remote mode only needs FastAPI, httpx and lightweight deps.
Local mode adds docling and docling-core for in-process conversion.
2026-04-03 09:24:41 +02:00
Pier-Jean Malandrino
1ff8c5108f Add release process, dynamic versioning, and changelog catch-up
Replace hardcoded version strings with build-time injection:
- Frontend: Vite __APP_VERSION__ from env or package.json
- Backend: APP_VERSION env var exposed via /health endpoint
- Docker: build arg propagated through both stages
- CI: release workflow extracts version from git tag

Document branching strategy and release process in CONTRIBUTING.md.
Catch up CHANGELOG with v0.2.0 and Unreleased sections.
Sync package.json version to 0.3.0.
2026-04-02 16:08:37 +02:00
Pier-Jean Malandrino
82059ec0b1 Add tests for ChunkBbox domain, schema, and API serialization
Cover ChunkBbox construction and serialization, ChunkBboxResponse
camelCase output, rechunk endpoint bbox propagation, and frontend
store test data alignment with the new bboxes field.
2026-04-02 14:47:40 +02:00
Pier-Jean Malandrino
4af6b5b231 Add chunk-to-bbox hover highlighting in Prepare mode
Extract bounding boxes from chunk doc_items provenance in the chunker,
propagate through domain/service/API layers, and render highlighted
bboxes on canvas when hovering a chunk card. Reset highlights on
mode and page changes to prevent stale visual state.
2026-04-02 14:47:31 +02:00
Pier-Jean Malandrino
05de0cc774 Add chunking tests and update existing test assertions
16 new chunking tests (domain, schemas, API endpoints).
Update existing tests for chunkingOptions parameter and document_json mock.
2026-04-02 12:33:07 +02:00
Pier-Jean Malandrino
a9517d38eb Add chunking service orchestration, API endpoints, and wiring
AnalysisService gains rechunk() and inline chunking during conversion.
ChunkingOptionsRequest/ChunkResponse schemas, POST rechunk endpoint,
and conditional chunker injection in main.py (local engine only).
2026-04-02 12:33:07 +02:00
Pier-Jean Malandrino
4b1ec364f4 Add LocalChunker adapter and DoclingDocument serialization
LocalChunker implements DocumentChunker port using docling-core chunkers.
LocalConverter now serializes DoclingDocument to JSON for re-chunking support.
2026-04-02 12:33:07 +02:00
Pier-Jean Malandrino
f5b31f809f Add document_json and chunks_json persistence layer
Schema migration for new columns, repository read/write support,
and dedicated update_chunks method for re-chunking operations.
2026-04-02 12:33:07 +02:00
Pier-Jean Malandrino
78c27b087d Add chunking domain objects and DocumentChunker port
ChunkingOptions and ChunkResult value objects, document_json/chunks_json
fields on AnalysisJob, and DocumentChunker protocol for adapter injection.
2026-04-02 12:33:07 +02:00
Pier-Jean Malandrino
d42c97160d Format backend codebase with ruff 2026-04-02 12:33:07 +02:00
Pier-Jean Malandrino
2b991108f7 Rebase sync 2026-03-31 16:55:17 +02:00
Pier-Jean Malandrino
1b8cfe0a6b Fix Serve API contract: send to_formats as repeated form fields
Docling Serve expects array fields (to_formats) as repeated multipart
keys (to_formats=md&to_formats=html&to_formats=json), not a JSON
string. Changed _build_form_data to return list[tuple] so httpx sends
repeated keys correctly. Fixes 422 Unprocessable Entity on convert.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 16:52:36 +02:00
Pier-Jean Malandrino
001cf6807c Fix audit findings: security, robustness, and dead code
- Remove dead get_analysis_service() function in main.py
- Scope file deletion to UPLOAD_DIR to prevent path traversal
- Parse datetime strings back to datetime objects in repos
- Add 10-minute polling timeout in frontend analysis store
- Accept .pdf extension (not just MIME type) on drag-and-drop
- Guard localStorage access for private browsing compatibility

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 16:52:36 +02:00
Pier-Jean Malandrino
0af3b81b8f Fix zombie jobs and unprotected JSON parse
Bug #1: _on_task_done now receives job_id via functools.partial and
calls _mark_failed when the background task raises or is cancelled,
preventing jobs from being stuck in RUNNING state forever.

Bug #5: _parse_response wraps json.loads in try/except JSONDecodeError
so malformed json_content strings fall back gracefully instead of crashing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 16:52:36 +02:00
Pier-Jean Malandrino
a63af61b73 Fix lint ans test errors 2026-03-31 16:35:48 +02:00
Pier-Jean Malandrino
fe4e792885 Fix audit findings: remove domain→infra violation, align Serve API, fix DI
- Delete domain/parsing.py (broke hexagonal layering by importing infra)
- Migrate all tests to import directly from domain.value_objects and
  infra.local_converter
- Rewrite ServeConverter to match real Docling Serve v1 API contract:
  options sent as individual form fields (not JSON blob), response
  parsed from document.json_content (DoclingDocument), proper bbox
  coord_origin handling (TOPLEFT/BOTTOMLEFT)
- Transmit all conversion options including generate_picture_images
- Replace fragile lazy import circular dep with FastAPI Depends() +
  app.state for AnalysisService injection
- Add frontend file size validation (50MB) before upload

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 10:58:58 +02:00
Pier-Jean Malandrino
a3486a8501 Add ServeConverter adapter for remote Docling Serve integration
Implement the HTTP client adapter that delegates document conversion
to a remote Docling Serve instance via its /v1/convert/file endpoint.
Switchable via CONVERSION_ENGINE=remote env var. Includes health check,
API key auth, response parsing, and 30 new tests covering parsing,
type mapping, HTTP calls, and DI wiring.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 10:36:35 +02:00
Pier-Jean Malandrino
3743ed4ca8 Refactor backend to hexagonal architecture for converter extensibility
Extract domain value objects and ports from parsing.py, move Docling-specific
code to infra/local_converter.py, and convert analysis_service to a class
with injected DocumentConverter. This prepares the codebase for plugging in
alternative conversion backends (e.g. Docling Serve) via the Protocol pattern.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 10:34:07 +02:00