Changelog¶
All notable changes to this project will be documented here. Format follows Keep a Changelog. This project adheres to Semantic Versioning.
[0.1.3] — 2026-11-30¶
Added¶
Dense-page re-analysis (vision pipeline)
- When the initial vision call detects ≥ dense_page_threshold distinct elements in the response DESCRIPTION, the pipeline automatically crops the image into horizontal strips and re-analyzes each strip independently — giving every figure on a dense page its own full token budget instead of a blended summary
- PipelineConfig.dense_page_threshold: int = 3 — controls the minimum element count that triggers re-analysis; set to 0 to disable entirely; respects MULTIXTRACT_DENSE_PAGE_THRESHOLD env var
- count_inventory_elements(description) -> int — utility that counts ELEMENT N: entries in a vision description; exported from multixtract.vision; also importable by users who want to inspect results
Improved DEFAULT_SYSTEM_PROMPT (all vision providers)
- Three-step structure: INVENTORY (enumerate every distinct visual element before describing anything, one line per element, never collapse separate figures), per-ELEMENT descriptions (typed rules for chart/table/diagram/photograph/text-block/screenshot/map/other), and SELF-AUDIT (cross-check that every numeric value in OCR_TEXT appears in the element descriptions)
- Fully domain-neutral — no document type or domain-specific logic baked in; works uniformly across PDFs, DOCX, PPTX, XLSX, images, HTML, EPUB, and any other format
- Parser unchanged: the three-section CAPTION / OCR_TEXT / DESCRIPTION format is preserved
Directory & batch support
- Pipeline.process_batch(*inputs, max_workers=4) — process one or more files and/or directories in a single call; thin facade over BatchProcessor with failure isolation and resume support
- BatchProcessor — concurrent document processor; accepts FileSource, DirectorySource, custom DocumentSource, or a raw Iterator[Path]; entry points: process_inputs(), process_source(), process_paths()
- BatchConfig(max_workers, skip_if_exists, split_chunks, on_progress) — tuning knobs for BatchProcessor
- BatchResult(succeeded, failed, skipped, failures, total) — aggregate outcome of a batch run
- DocumentFailure(path, error) — per-document failure record
- InputResolver / FileSource / DirectorySource / discover() — lazy recursive discovery of supported documents from mixed file/directory inputs
- SUPPORTED_EXTENSIONS — frozenset of all file extensions the default registry handles
- CLI extended to accept directories and mixed inputs (multixtract report.pdf ./docs ./more)
- CLI --workers N flag — max concurrent documents (default: 4)
Formatters (multixtract.formatters)
- AzureAISearchFormatter.from_result(result, timestamp, skip_empty) — converts an in-process ExtractionResult to a list of flat Azure AI Search documents
- AzureAISearchFormatter.from_chunks_file(chunks_data, timestamp, skip_empty) — same, but from a _chunks.json dict (post-processing / offline path)
- AzureAISearchFormatter.index_schema(index_name, vector_dim) — returns a fully configured azure-search-documents SearchIndex object with hybrid (keyword + vector) fields; deferred import so azure-search-documents is not required unless this method is called
Structured error tracking
- ExtractionResult.degradations: list[dict] — partial failures that did not abort the run; each entry: {"stage": "vision"|"embed_image"|"embed_chunk", "id": str, "error": str|None}; populated by Pipeline.process() from three sources: vision exceptions, None image embeddings, None chunk embeddings
- VisionModel.analyze protocol contract updated: providers now raise on failure (previously "must not raise") — the pipeline coordinator catches and records errors in degradations
Progress callbacks
- BatchConfig.on_progress: Callable[[Path, ExtractionResult | Exception], None] | None — called after every document completes (succeeded, skipped, or failed); receives the Path and the result or exception; callback exceptions are caught and logged as warnings so a crashing callback never aborts a batch
PipelineConfig.from_env(prefix="MULTIXTRACT_")
- Classmethod that reads MULTIXTRACT_<FIELD_NAME_UPPER> environment variables and returns a PipelineConfig with those values applied; integer fields are coerced; malformed or absent vars fall back to dataclass defaults; prefix is configurable
Token counting
- count_tokens(text) -> int — tiktoken-based token count (cl100k_base) when tiktoken is installed; falls back to the fast heuristic; used for all final token_cnt stamps on chunks
- estimate_tokens(text) -> int — fast heuristic (unchanged); retained for the splitting hot path
- New optional extra [tiktoken]: pip install "multixtract[tiktoken]"
- Both exported from top-level multixtract
Reliability
- OpenAIVisionModel(max_retries=2) and OpenAIEmbedder(max_retries=2) — max_retries forwarded directly to the OpenAI SDK client constructor; SDK handles Retry-After/retry-after-ms headers, exponential backoff, and ±25% jitter at the HTTP layer
- AzureOpenAIVisionModel(max_retries=2) and AzureOpenAIEmbedder(max_retries=2) — same, via AzureOpenAI(max_retries=max_retries)
Content deduplication
- Image chunks: _deduplicate_image_content now applied inside build_image_content (creation time) so stored chunks are always clean; build_index_document retains a defensive pass for external/older _chunks.json files
Changed¶
Token defaults raised
| Provider | Parameter | Before | After |
|---|---|---|---|
OpenAIVisionModel / AzureOpenAIVisionModel |
max_tokens |
800 → 1500 | 2500 |
Qwen2VLVisionModel |
max_new_tokens |
512 → 1024 | 2048 |
SmolVLMVisionModel |
max_new_tokens |
512 → 1024 | 2048 |
Llama32VisionModel |
max_new_tokens |
512 → 1024 | 2048 |
Defaults only — users who pass explicit values are unaffected. The 3-step prompt (INVENTORY + per-element typed descriptions + SELF-AUDIT) produces substantially longer responses than the previous prompt, particularly when pages contain tables that are transcribed as full Markdown. The prior 1500/1024 defaults were insufficient for dense pages and caused silent truncation mid-DESCRIPTION.
parse_vision_responsedescription join: description buffer lines now joined with\n(was" "); caption and OCR text continue to join with spaces — preserves Markdown table structure andELEMENT N:block boundaries in the stored description_run_visiondegradation tracking: partial crop failures (some strips succeed, some fail) are now recorded inExtractionResult.degradationswithstage="vision_crop"and an"N/M crops failed"message, consistent with the existing degradation schema- OpenAI SDK version constraint:
openai>=1.57.0,<4.0(was<3.0) — aligns with current OpenAI model releases VisionModel.analyzeprotocol: raises on failure instead of returning an emptyVisionResult; hand-rolledtry/exceptremoved fromOpenAIVisionModel.analyze- Retry handling: removed hand-rolled
_retry/_is_permanentfrom OpenAI providers; SDK retry is strictly more correct (correct 4xx/5xx discrimination, header-aware sleep, no double-retry compounding) ExtractionResult: newdegradationsfield (default[]) — backward compatible; existing code constructingExtractionResultpositionally is unaffected
Fixed¶
count_inventory_elementsdouble-counting — the 3-step prompt producesELEMENT N:labels in both the INVENTORY list and the per-element detail sections; a page with N real elements therefore contains 2N matching lines. The function previously counted raw occurrences, returning 2N and causing the dense-page crop pass to split the image into twice as many strips as needed. Fixed by deriving the element count from the highest sequential index seen (max(N)) rather than the occurrence count — correct regardless of how many times each label appears across INVENTORY and detail sections.- Dense-page merge labels —
_crop_and_reanalyzepreviously labeled each crop's merged description withELEMENT N: {description}, colliding with theELEMENT N:markers already present inside each crop's own INVENTORY and detail content. Changed to neutral--- Strip N / M ---section headers, which are orthogonal to the prompt's internal structure and do not interfere with any futurecount_inventory_elementscall on the merged result. count_inventory_elementsignores template placeholder lines (ELEMENT 1: <type: ...>) that a prompt-parroting model may echo verbatim — prevents false triggers of the dense-page re-analysis pass- Dense-page crop pass:
_MIN_CROP_STRIP_HEIGHT = 50 pxguard — images too short to split into meaningful strips are skipped rather than sending degenerate 1-pixel strips to the vision model - Hyperlink extraction —
displaytext lost —sheet_linksentries always set"display"to the URL rather than readinglink.displayfrom the openpyxlHyperlinkobject. Root cause: the original map-building loop stored onlycoord → urland never captured the display field, forcing thesheet_linkscomprehension to repeat the URL. Fixed by introducing_extract_hyperlinks(ws, hidden_cols)which readslink.displaydirectly and falls back to the URL only when the field is absent. ws._hyperlinks/ws.hyperlinksattribute fallback missing —ws.hyperlinkswas accessed unconditionally; on some openpyxl 3.x builds the sheet-level hyperlink collection is exposed only at the privatews._hyperlinksattribute, causing zero hyperlinks to be found when the public attribute is absent. Fixed in_extract_hyperlinkswithgetattr(ws, "_hyperlinks", None) or getattr(ws, "hyperlinks", None), matching openpyxl's own internal access pattern.- Cell-level hyperlink fallback absent — a subset of Excel files register hyperlinks only on the cell object (
cell.hyperlink) without an entry in the sheet-level collection. These were silently dropped. Fixed:_extract_hyperlinksiteratesws.iter_rowsas a second pass and collects anycell.hyperlinkentry whose coordinate was not already seen, with anExceptionguard so a disrupted row iterator on unusual worksheets does not abort the extraction. - Excel hyperlink extraction: full URLs now stored by combining
Hyperlink.target+.location; hyperlink map built before the row loop; hidden-column URLs excluded; external URLs inlined asdisplay (url);chunk_documentskips the redundantLinks:block for xlsx pages examples/azure_ai_search/ingest.py: field names corrected (id/content_vector— werechunk_id/embedding); spuriousfile_path=/file_name=kwargs removed fromPipeline.process()call
Tests¶
- Added
test_count_inventory_elements_full_prompt_format_not_doubled— pins that a 3-element full-format DESCRIPTION (INVENTORY + detail sections) returns3, not6; directly covers the double-count regression - Added
test_count_inventory_elements_full_format_single_elementandtest_count_inventory_elements_full_format_five_elements— boundary and scale coverage for the same contract - Updated
test_dense_page_reanalysis_triggeredto use the full prompt-format description (INVENTORY + detail sections) rather than an inventory-only stub; asserts that exactly 3 crop calls are made (not 6) and that merged output usesStrip Nsection headers - Updated
test_dense_page_image_bytes_freed_after_visionto use full-format description for the same reason - Fixed three pre-existing test failures: xlsx extractor mock updated for
values_only=False; CLI provider tests replaced monkeypatching with real instantiation; batch backpressure test corrected window size andpath.stemcrash - Added 8 unit tests for
_extract_hyperlinkscovering:link.displaytext read correctly; URL fallback when display is absent;ws.hyperlinkspublic-attribute fallback;cell.hyperlinkcell-level fallback; no duplicate when coordinate appears in both sources; internal links excluded; hidden-column links excluded; empty-sheet case
[0.1.2] — 2026-08-15¶
Added¶
Individual chunk splitting
- Pipeline.process() — new split_chunks: bool = False parameter; when True, automatically splits _chunks.json into individual per-chunk documents after processing and populates result.split_stats
- Pipeline.split_chunks_file(chunks_data, timestamp, skip_if_exists, upload_workers) — standalone method to split any _chunks.json dict into individual flat documents; parallel writes via upload_workers (default 4)
- build_index_document(chunk, header, timestamp) — public function that transforms a raw chunk dict into a flat, AI-Search-optimized document: renames embedding → content_vector, promotes metadata fields to top level, adds id, doc_id, file_name, file_path, file_type, total_pgs, last_updated
- SplitStats dataclass — returned by split_chunks_file; fields: created, skipped, failed, deduped
ExtractionResult
- New optional field split_stats: SplitStats | None — populated when split_chunks=True
PipelineConfig
- New field individual_chunks_subdir: str = "individual_chunks" — storage sub-folder for per-chunk documents
Public API
- safe_index_key(s) — sanitizes any string to a valid Azure AI Search document key ([A-Za-z0-9_\-=]); applied automatically to all chunk_id and id values
- build_index_document, SplitStats, safe_index_key exported from top-level multixtract
Chunking internals
- _chunks.json schema: {"_header": {"file_path", "file_name", "total_pgs"}, "chunks": [...]}; each chunk has chunk_id, chunk_type, pg_num, chunk_idx, content, token_cnt, metadata (nested, type-specific), embedding
- Token count computed once per chunk (no double estimate_tokens call)
- _splits_from_buffer() internal helper returns (content, token_cnt) pairs; both code paths (elements + legacy) share it
Fixed¶
Excel extractor
- _is_metadata_row: replaced double str(c).strip() evaluation with a walrus-operator assignment so the stripped string is computed once and reused in the filter — eliminates a subtle correctness risk when the cell value has side effects and improves readability.
- _extract_hyperlinks: probes ws.hyperlinks for accessibility before iterating; falls back to per-cell .hyperlink attribute scanning when the collection is unavailable or raises, preventing silent data loss on worksheets with unusual hyperlink formats.
- Type narrowing in _build_pages (_pg intermediate variable) — removes a mypy int | None incompatible-assignment error that appeared on Python 3.10.
Memory / OOM guards (all extractors, pipeline, image utilities)
- CSV extractor: switched from eager full-file load to streaming row-by-row read; honours _MAX_ROWS_PER_SHEET with early break so large CSVs never materialise fully in memory.
- PDF extractor: changed converted[key] and raster_cache[key] lookups to .pop() so raw image bytes are released immediately after use instead of persisting for the lifetime of the page loop.
- DOCX / PPTX / XLSX extractors: call .clear() on vector_items and wdp_items lists after the LibreOffice batch conversion returns; use .pop() when consuming the converted dict so each image's bytes are freed as soon as they are encoded.
- Pipeline vision worker: releases image_bytes per-future (inside as_completed) rather than after all futures complete, reducing peak memory proportional to vision_workers.
- _image_utils.py — batch_convert_vectors_to_png: deletes raw bytes after writing to the temp directory (bytes are now on disk; no need to keep them in RAM before spawning LibreOffice); decode_wdp_to_png: deletes the intermediate numpy array returned by imagecodecs.jpegxr_decode before PIL takes ownership of the same pixel data.
Changed¶
- Coverage configuration (
pyproject.toml): added[tool.coverage.report] exclude_linespatterns for GPU-dependent model-loading branches (AutoProcessor.from_pretrained,MllamaForConditionalGeneration.from_pretrained,Qwen2_5_VLForConditionalGeneration.from_pretrained,AutoModelForVision2Seq.from_pretrained, CUDA device/dtype selection). Provider source files remain annotation-free; exclusions are declared centrally in config.
Tests¶
- Replaced hollow mock-heavy tests in
tests/test_coverage_gaps.pywith 53 honest tests that exercise real code paths using actual fixture files and in-memory inputs. - New fixtures:
tests/fixtures/hidden_cols.xlsx(XLSX with a hidden column to verify exclusion),tests/fixtures/large.xlsxandtests/fixtures/large.csv(10 001-row files to verify truncation behaviour). - Adopted correct
monkeypatch.setitem(sys.modules, …)pattern for optional-dependency absence tests; import class before patching to preserve class identity in registry assertions; no module reloads.
[0.1.1] — 2026-08-01¶
Added¶
Core extraction
- extract_document() — text, tables, and filtered images from PDF, Word (.docx), PowerPoint (.pptx), Excel/CSV (.xlsx/.csv)
- Legacy .doc / .ppt support via headless LibreOffice conversion
- chunk_document() — sliding-window text chunks, per-table Markdown chunks, per-image chunks
- split_text_into_chunks() — standalone sentence-boundary-aware text splitter
- table_to_markdown() — serialize extracted tables to Markdown
Image filtering (ImageFilterPipeline)
- Dimension filter (configurable major/minor pixel thresholds)
- Solid-colour and tiny-icon rejection (perceptual quality checks)
- Reference-logo deduplication via perceptual hash (reference_img_dir)
- Cross-page duplicate tracking via xref/media-path deduplication
- Vector image pre-conversion (EMF/WMF/SVG → PNG via LibreOffice)
- JPEG-XR / WDP decoding via imagecodecs ([imaging] extra)
Pipeline (Pipeline, PipelineConfig)
- End-to-end orchestration: extract → filter → vision → chunk → embed → store
- All providers optional: vision=None, embedder=None, store=None
- Parallel vision calls (vision_workers), batched embeddings
- Resume support via skip_if_exists (skips documents already in the store)
- Configurable storage sub-folder layout
Vision providers (cloud)
- OpenAIVisionModel — GPT-4o and compatible models ([openai])
- AzureOpenAIVisionModel — Azure OpenAI deployment ([azure])
- Custom system_prompt, max_tokens, temperature, shared client support
Vision providers (local / offline)
- Qwen2VLVisionModel — Qwen2.5-VL-7B/3B, recommended for document understanding ([qwen2vl])
- SmolVLMVisionModel — SmolVLM 2.2B, CPU-friendly ([smolvlm])
- Llama32VisionModel — Llama 3.2 Vision 11B/90B ([llama])
Embedding providers
- OpenAIEmbedder — OpenAI embeddings API ([openai])
- AzureOpenAIEmbedder — Azure OpenAI embeddings deployment ([azure])
Storage providers
- LocalDiskStore — writes JSON and image files to the local filesystem
- AzureBlobStore — Azure Blob Storage with key, service principal, or DefaultAzureCredential auth ([azure])
Extensibility
- DocumentExtractor protocol — add any file format with register_extractor()
- VisionModel protocol — plug in any vision model (Tesseract, Claude, Gemini, …)
- Embedder protocol — plug in any embedding model (sentence-transformers, Cohere, …)
- BlobStore protocol — plug in any storage backend (S3, GCS, …)
CLI
- multixtract <file> — extract any supported document to JSON; vision/embeddings enabled when OPENAI_API_KEY is set
Packaging
- py.typed marker — fully typed, compatible with mypy and pyright
- Optional extras: [pdf], [docx], [pptx], [xlsx], [imaging], [openai], [azure], [qwen2vl], [smolvlm], [llama], [dev], [all]
- Core dependencies: Pillow, ImageHash only