Deploy DocNeedle updates
Browse files- .vscode/settings.json +3 -0
- LICENSE +201 -0
- README.md +326 -803
- app.py +8 -2
- benchmark_results/summary_all.json +9 -9
- benchmark_results/summary_long.json +3 -3
- benchmark_results/summary_medium.json +17 -0
- benchmark_results/summary_short.json +17 -0
- pyproject.toml +1 -0
- scripts/benchmark_extractbench.py +20 -3
- scripts/deploy_space.sh +35 -0
- src/docneedle/extraction/service.py +1 -2
- src/docneedle/llm/local_engine.py +1 -3
- src/docneedle/retrieval/docneedle_embed.cpp +13 -33
- src/docneedle/retrieval/libdocneedle_embed.so +2 -2
.vscode/settings.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"antigravity.enableInlineDiff": true
|
| 3 |
+
}
|
LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or exemplary damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright 2026 DocNeedle Contributors
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
README.md
CHANGED
|
@@ -8,6 +8,7 @@ sdk_version: 6.0.0
|
|
| 8 |
python_version: 3.14
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
<p align="center">
|
|
@@ -17,9 +18,9 @@ pinned: false
|
|
| 17 |
<h1 align="center">DocNeedle</h1>
|
| 18 |
|
| 19 |
<p align="center">
|
| 20 |
-
<strong>
|
| 21 |
-
Extract
|
| 22 |
-
Zero external API
|
| 23 |
</p>
|
| 24 |
|
| 25 |
<p align="center">
|
|
@@ -38,49 +39,17 @@ pinned: false
|
|
| 38 |
- [Overview](#overview)
|
| 39 |
- [Key Features](#key-features)
|
| 40 |
- [Tech Stack](#tech-stack)
|
|
|
|
| 41 |
- [Prerequisites](#prerequisites)
|
| 42 |
- [Getting Started](#getting-started)
|
| 43 |
-
- [1. Clone Repository](#1-clone-repository)
|
| 44 |
-
- [2. Install System Dependencies](#2-install-system-dependencies)
|
| 45 |
-
- [3. Setup Python 3.14t Environment with `uv`](#3-setup-python-314t-environment-with-uv)
|
| 46 |
-
- [4. Install Project Dependencies](#4-install-project-dependencies)
|
| 47 |
-
- [5. Download Quantized Models](#5-download-quantized-models)
|
| 48 |
-
- [6. Configuration Setup](#6-configuration-setup)
|
| 49 |
-
- [7. Launch the Application](#7-launch-the-application)
|
| 50 |
- [System Architecture](#system-architecture)
|
| 51 |
-
|
| 52 |
-
- [End-to-End Extraction Lifecycle](#end-to-end-extraction-lifecycle)
|
| 53 |
-
- [Data Flow](#data-flow)
|
| 54 |
-
- [OCR-Free Visual RAG & Digital Text Ingestion](#ocr-free-visual-rag--digital-text-ingestion)
|
| 55 |
-
- [Interactive PDF AcroForm Direct Extraction](#interactive-pdf-acroform-direct-extraction)
|
| 56 |
-
- [Spatial Collision Resolution](#spatial-collision-resolution)
|
| 57 |
-
- [Native C++ Cross-Modal Embedding Engine](#native-c-cross-modal-embedding-engine)
|
| 58 |
-
- [Zero-Disk Privacy Guarantee](#zero-disk-privacy-guarantee)
|
| 59 |
-
- [Supported Data Types & Validation Rules](#supported-data-types--validation-rules)
|
| 60 |
-
- [Recursive JSON Schema Dereferencing (`$ref`)](#recursive-json-schema-dereferencing-ref)
|
| 61 |
-
- [Web Dashboard (Gradio 6 UI)](#web-dashboard-gradio-6-ui)
|
| 62 |
- [API Reference](#api-reference)
|
| 63 |
-
- [Endpoints Summary](#endpoints-summary)
|
| 64 |
-
- [1. Synchronous Extraction (`POST /v1/extract`)](#1-synchronous-extraction-post-v1extract)
|
| 65 |
-
- [2. Asynchronous Job Creation (`POST /v1/jobs`)](#2-asynchronous-job-creation-post-v1jobs)
|
| 66 |
-
- [3. Job Status Polling (`GET /v1/jobs/{job_id}`)](#3-job-status-polling-get-v1jobsjob_id)
|
| 67 |
-
- [4. Real-Time SSE Streaming (`GET /v1/jobs/{job_id}/events`)](#4-real-time-sse-streaming-get-v1jobsjob_idevents)
|
| 68 |
-
- [5. System Health & Hardware Diagnostics (`GET /healthz`)](#5-system-health--hardware-diagnostics-get-healthz)
|
| 69 |
- [Configuration Reference](#configuration-reference)
|
| 70 |
-
|
| 71 |
-
- [Environment Variables](#environment-variables)
|
| 72 |
-
- [Available Scripts & Benchmarking](#available-scripts--benchmarking)
|
| 73 |
-
- [Command Reference](#command-reference)
|
| 74 |
-
- [ExtractBench Evaluation Benchmark](#extractbench-evaluation-benchmark)
|
| 75 |
- [Testing](#testing)
|
| 76 |
-
- [Running the Test Suite](#running-the-test-suite)
|
| 77 |
-
- [Test Suite Organization](#test-suite-organization)
|
| 78 |
-
- [Important Note on Dev Server VRAM](#important-note-on-dev-server-vram)
|
| 79 |
- [Production Deployment](#production-deployment)
|
| 80 |
-
|
| 81 |
-
- [Hugging Face Spaces (ZeroGPU)](#hugging-face-spaces-zerogpu)
|
| 82 |
-
- [Bare-Metal / Linux Systemd Service](#bare-metal--linux-systemd-service)
|
| 83 |
-
- [Troubleshooting & FAQs](#troubleshooting--faqs)
|
| 84 |
- [Contributing](#contributing)
|
| 85 |
- [License](#license)
|
| 86 |
|
|
@@ -88,33 +57,32 @@ pinned: false
|
|
| 88 |
|
| 89 |
## Overview
|
| 90 |
|
| 91 |
-
**DocNeedle** is
|
| 92 |
|
| 93 |
-
Unlike
|
| 94 |
|
| 95 |
-
- **Zero
|
| 96 |
-
- **
|
| 97 |
-
- **OCR-
|
| 98 |
-
- **
|
| 99 |
|
| 100 |
---
|
| 101 |
|
| 102 |
## Key Features
|
| 103 |
|
| 104 |
-
- **
|
| 105 |
-
- **In-Process Multimodal
|
| 106 |
-
- **LLM:** Qwen3.5-4B GGUF (`Qwen3.5-4B-Q4_K_M.gguf` + `mmproj-Qwen3.5-4B-F16.gguf`)
|
| 107 |
-
- **Cross-Modal Embedder:** EmbeddingGemma-2 GGUF (`embeddinggemma-2-UD-Q4_K_XL.gguf` + `mmproj-F16.gguf`)
|
| 108 |
-
- **Reranker:** Qwen3-Reranker-0.6B GGUF (`Qwen3-Reranker-0.6B.Q4_K_M.gguf`)
|
| 109 |
-
- **Native C++
|
| 110 |
-
- **AcroForm Direct
|
| 111 |
-
- **
|
| 112 |
-
- **
|
| 113 |
-
- **
|
| 114 |
-
- **
|
| 115 |
-
- **
|
| 116 |
-
- **
|
| 117 |
-
- **ZeroGPU & Multi-Arch CUDA Ready:** Precompiled CUDA cubin libraries for `sm_80`, `sm_86`, `sm_89`, and `sm_120a` architectures with seamless ZeroGPU dynamic leasing via `@spaces.GPU`.
|
| 118 |
|
| 119 |
---
|
| 120 |
|
|
@@ -122,172 +90,172 @@ Unlike traditional document extraction pipelines that rely on cloud APIs or brit
|
|
| 122 |
|
| 123 |
| Layer | Technologies |
|
| 124 |
| :--- | :--- |
|
| 125 |
-
| **Runtime
|
| 126 |
-
| **Microservice
|
| 127 |
-
| **Web Dashboard** | Gradio 6+,
|
| 128 |
-
| **
|
| 129 |
-
| **AcroForm
|
| 130 |
-
| **
|
| 131 |
-
| **
|
| 132 |
-
| **
|
| 133 |
-
| **
|
| 134 |
-
| **
|
| 135 |
-
| **
|
| 136 |
-
| **Package Management** | `uv` (Astral) |
|
| 137 |
-
| **Container & Cloud** | Docker, Docker Compose, Hugging Face Spaces (ZeroGPU A10G / A100) |
|
| 138 |
|
| 139 |
---
|
| 140 |
|
| 141 |
-
##
|
| 142 |
|
| 143 |
-
|
| 144 |
|
| 145 |
-
|
| 146 |
-
- **OS:** Linux (Ubuntu 22.04/24.04, Debian 12, Arch, or Fedora recommended). macOS and Windows WSL2 are supported.
|
| 147 |
-
- **RAM:** Minimum 8 GB (16 GB recommended for CPU-only inference).
|
| 148 |
-
- **GPU (Optional, Recommended):** NVIDIA GPU with CUDA 12.0+ (Compute Capability $\ge$ 8.0: RTX 30/40/50 series, A100, H100, Blackwell). DocNeedle runs comfortably on 8 GB VRAM.
|
| 149 |
-
- **Storage:** ~5 GB free space for quantized model weights and tokenizers.
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
|
|
|
| 153 |
|
| 154 |
-
|
| 155 |
-
# Ubuntu / Debian
|
| 156 |
-
sudo apt-get update && sudo apt-get install -y \
|
| 157 |
-
build-essential \
|
| 158 |
-
cmake \
|
| 159 |
-
curl \
|
| 160 |
-
git \
|
| 161 |
-
libgl1 \
|
| 162 |
-
libglib2.0-0
|
| 163 |
|
| 164 |
-
#
|
| 165 |
-
sudo dnf install -y gcc gcc-c++ cmake curl git mesa-libGL glib2
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
-
###
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
```bash
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
| 176 |
```
|
| 177 |
|
| 178 |
-
--
|
| 179 |
|
| 180 |
-
|
| 181 |
|
| 182 |
-
|
| 183 |
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
```bash
|
| 187 |
-
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
```
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
Ensure the required system libraries are installed (see [Prerequisites](#prerequisites)):
|
| 194 |
|
| 195 |
```bash
|
| 196 |
-
|
| 197 |
```
|
| 198 |
|
| 199 |
-
|
|
|
|
|
|
|
| 200 |
|
| 201 |
-
|
| 202 |
|
| 203 |
```bash
|
| 204 |
-
|
| 205 |
-
|
| 206 |
|
| 207 |
-
|
| 208 |
uv venv --python 3.14t
|
| 209 |
-
|
| 210 |
-
# Activate the virtual environment
|
| 211 |
source .venv/bin/activate
|
| 212 |
-
```
|
| 213 |
|
| 214 |
-
Verify that your Python interpreter is running in free-threaded mode:
|
| 215 |
-
|
| 216 |
-
```bash
|
| 217 |
python -c "import sys; print('Free-threaded (No-GIL):', not getattr(sys, '_is_gil_enabled', lambda: True)())"
|
| 218 |
-
#
|
| 219 |
```
|
| 220 |
|
| 221 |
-
###
|
| 222 |
-
|
| 223 |
-
Install all core dependencies and development tools using `uv`:
|
| 224 |
|
| 225 |
```bash
|
| 226 |
uv sync
|
| 227 |
```
|
| 228 |
|
| 229 |
> [!NOTE]
|
| 230 |
-
>
|
| 231 |
> ```bash
|
| 232 |
> export CUDACXX=/usr/local/cuda/bin/nvcc
|
| 233 |
> export CMAKE_ARGS="-DGGML_CUDA=on -DCMAKE_CUDA_ARCHITECTURES=native"
|
| 234 |
> uv pip install --no-build-isolation "llama-cpp-python>=0.3.0,<0.4.0"
|
| 235 |
> ```
|
| 236 |
|
| 237 |
-
###
|
| 238 |
-
|
| 239 |
-
DocNeedle relies on compact, high-precision quantized GGUF models. Run the automated model downloader script:
|
| 240 |
|
| 241 |
```bash
|
| 242 |
uv run python scripts/download_models.py
|
| 243 |
```
|
| 244 |
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
| Model Category | Model Identifier | Destination Subpath |
|
| 248 |
-
| :--- | :--- | :--- |
|
| 249 |
-
| **Embedder GGUF** | `unsloth/embeddinggemma-2-GGUF` | `models/embedding/embeddinggemma-2-UD-Q4_K_XL.gguf` |
|
| 250 |
-
| **Embedder Vision** | `unsloth/embeddinggemma-2-GGUF` | `models/embedding/mmproj-F16.gguf` |
|
| 251 |
-
| **Reranker GGUF** | `mradermacher/Qwen3-Reranker-0.6B-GGUF` | `models/reranker/Qwen3-Reranker-0.6B.Q4_K_M.gguf` |
|
| 252 |
-
| **LLM Engine GGUF** | `unsloth/Qwen3.5-4B-GGUF` | `models/llm/Qwen3.5-4B-Q4_K_M.gguf` |
|
| 253 |
-
| **LLM Vision** | `unsloth/Qwen3.5-4B-GGUF` | `models/llm/mmproj-Qwen3.5-4B-F16.gguf` |
|
| 254 |
-
| **Chunker Tokenizer** | `Qwen/Qwen3-Reranker-0.6B` | Hugging Face local cache |
|
| 255 |
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
### 6. Configuration Setup
|
| 259 |
-
|
| 260 |
-
DocNeedle loads configuration from `config.toml` by default. You can inspect or customize settings:
|
| 261 |
-
|
| 262 |
-
```bash
|
| 263 |
-
# Optional: copy example environment file if you wish to override via env vars
|
| 264 |
-
cp .env.example .env 2>/dev/null || touch .env
|
| 265 |
-
```
|
| 266 |
|
| 267 |
-
|
| 268 |
-
- `gpu_enabled = true`: Enables CUDA offloading if available. Set to `false` for CPU-only.
|
| 269 |
-
- `llm_n_gpu_layers = -1`: Offloads all layers to GPU (`0` runs on CPU).
|
| 270 |
-
- `reranker_enabled = false`: Disabled by default on CPU for ultra-low latency; enable for maximum citation precision.
|
| 271 |
|
| 272 |
-
|
|
|
|
|
|
|
| 273 |
|
| 274 |
-
###
|
| 275 |
|
| 276 |
-
|
| 277 |
|
| 278 |
```bash
|
| 279 |
uv run python app.py
|
| 280 |
```
|
| 281 |
|
| 282 |
-
|
| 283 |
-
-
|
| 284 |
-
-
|
| 285 |
-
- **ReDoc Documentation:** [http://localhost:7860/redoc](http://localhost:7860/redoc)
|
| 286 |
-
- **Health & Hardware Diagnostics:** [http://localhost:7860/healthz](http://localhost:7860/healthz)
|
| 287 |
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
If you only need the headless REST microservice without the Gradio UI:
|
| 291 |
|
| 292 |
```bash
|
| 293 |
uv run uvicorn docneedle.main:app --host 0.0.0.0 --port 8000 --reload
|
|
@@ -301,84 +269,34 @@ uv run uvicorn docneedle.main:app --host 0.0.0.0 --port 8000 --reload
|
|
| 301 |
|
| 302 |
```
|
| 303 |
DocNeedle/
|
| 304 |
-
├── assets/ #
|
| 305 |
├── app.py # Unified Gradio 6 UI + FastAPI root mount & ZeroGPU entry
|
| 306 |
-
├── config.toml #
|
| 307 |
-
├── pyproject.toml
|
| 308 |
-
├──
|
| 309 |
-
├── Dockerfile # Multi-stage Python 3.14-slim container specification
|
| 310 |
-
├── docker-compose.yml # Standalone container orchestration configuration
|
| 311 |
├── scripts/
|
| 312 |
-
│ ├── download_models.py # Model downloader with
|
| 313 |
-
│ ├── benchmark_extractbench.py # ExtractBench
|
| 314 |
-
│ └── deploy_space.sh #
|
| 315 |
-
├── models/ #
|
| 316 |
-
│ ├── embedding/ # EmbeddingGemma-2 GGUF & SigLIP mmproj-F16
|
| 317 |
-
│ ├── reranker/ # Qwen3-Reranker-0.6B Q4_K_M GGUF
|
| 318 |
-
│ └── llm/ # Qwen3.5-4B-Q4_K_M GGUF & mmproj-Qwen3.5-4B-F16
|
| 319 |
├── src/docneedle/
|
| 320 |
-
│ ├── main.py # FastAPI
|
| 321 |
-
│ ├── config.py #
|
| 322 |
-
│ ├── cuda_compat.py # ZeroGPU preloaders &
|
| 323 |
-
│ ├── api/
|
| 324 |
-
│
|
| 325 |
-
│
|
| 326 |
-
│
|
| 327 |
-
│
|
| 328 |
-
│ │
|
| 329 |
-
│
|
| 330 |
-
│
|
| 331 |
-
│
|
| 332 |
-
|
| 333 |
-
│ │ ├── acroform.py # Native PDF AcroForm interactive form field extractor
|
| 334 |
-
│ │ ├── models.py # DocumentChunk, IngestionResult models
|
| 335 |
-
│ │ ├── cache.py # Ingestion cache to avoid duplicate rendering
|
| 336 |
-
│ │ └── service.py # Ingestion coordinator service
|
| 337 |
-
│ ├── retrieval/ # Hybrid search & vector store subsystem
|
| 338 |
-
│ │ ├── embedder.py # EmbeddingGemma2Embedder (multilingual text + visual embedding)
|
| 339 |
-
│ │ ├── docneedle_embed.cpp # Native C++ GGUF embedding and SigLIP projection source
|
| 340 |
-
│ │ ├── libdocneedle_embed.so # Compiled native cross-modal embedder shared library
|
| 341 |
-
│ │ ├── worker.py # IsolatedEmbeddingClient (process-isolated embedder host)
|
| 342 |
-
│ │ ├── bm25.py # BM25Engine (Okapi BM25 sparse keyword index)
|
| 343 |
-
│ │ ├── reranker.py # Qwen3Reranker (cross-encoder logit scoring via llama.cpp)
|
| 344 |
-
│ │ ├── store.py # SessionVectorStore (in-memory RRF fusion & document diversity)
|
| 345 |
-
│ │ └── models.py # SearchResult, SearchQuery models
|
| 346 |
-
│ ├── extraction/ # Information extraction & verification subsystem
|
| 347 |
-
│ │ ├── service.py # ExtractionService (retrieval query builder & orchestrator)
|
| 348 |
-
│ │ ├── verifier.py # ConfidenceCalculator (type checking & evidence alignment)
|
| 349 |
-
│ │ ├── matcher.py # Exact and fuzzy chunk text matcher & page resolver
|
| 350 |
-
│ │ ├── collision.py # SpatialCollisionResolver (resolves duplicate entity hallucinations)
|
| 351 |
-
│ │ └── schemas.py # ExtractionItemQuery, ExtractionResponse, ExtractionItemResult
|
| 352 |
-
│ └── llm/ # In-process LLM inference engine
|
| 353 |
-
│ ├── local_engine.py # LocalLLMEngine (Qwen3.5-4B GGUF + mmproj multimodal chat engine)
|
| 354 |
-
│ ├── client.py # LLMClient abstract base interface
|
| 355 |
-
│ ├── handlers.py # Structured output completion handlers
|
| 356 |
-
│ ├── parsing.py # Thought stripping, JSON parsing, unicode normalization
|
| 357 |
-
│ ├── prompts.py # Schema-constrained prompt builder & data contract synthesis
|
| 358 |
-
│ └── speculative.py # Speculative decoding prompt lookup draft model manager
|
| 359 |
-
└── tests/ # Comprehensive Pytest test suite
|
| 360 |
-
├── test_acroform.py # AcroForm form extraction tests
|
| 361 |
-
├── test_clean_modules.py # Fast unit tests: string sanitization, prompts, response parsing
|
| 362 |
-
├── test_collision.py # Spatial collision resolution unit tests
|
| 363 |
-
├── test_collision_turkish.py # Turkish domain collision resolution tests
|
| 364 |
-
├── test_cuda_compat.py # CUDA shared library preloading and ZeroGPU decorator mocks
|
| 365 |
-
├── test_extraction.py # Extraction query synthesis and verifier unit tests
|
| 366 |
-
├── test_health.py # Diagnostic endpoints & free-threaded status tests
|
| 367 |
-
├── test_ingest.py # Docling parser and chunking tests
|
| 368 |
-
├── test_jobs.py # Asynchronous JobManager, state machines, TTL, and SSE queues
|
| 369 |
-
├── test_multimodal_extraction.py # Multimodal vision extraction tests
|
| 370 |
-
├── test_ocr_grounding.py # Confidence calculation, fuzzy matching, and snippet alignment
|
| 371 |
-
├── test_retrieval.py # SessionVectorStore, BM25, and RRF fusion tests
|
| 372 |
-
├── test_speculative.py # Speculative decoding prompt lookup unit tests
|
| 373 |
-
└── test_ui_schema_sync.py # UI schema mapping verification tests
|
| 374 |
```
|
| 375 |
|
| 376 |
-
---
|
| 377 |
-
|
| 378 |
### End-to-End Extraction Lifecycle
|
| 379 |
|
| 380 |
-
When a request is submitted to DocNeedle (via API or UI), it passes through a 7-stage pipeline:
|
| 381 |
-
|
| 382 |
```mermaid
|
| 383 |
flowchart TD
|
| 384 |
A["Uploaded Files & Schema"] --> B["1. Ingestion: AcroForm Direct + Docling + pypdfium2"]
|
|
@@ -392,316 +310,161 @@ flowchart TD
|
|
| 392 |
I --> J["finally: store.clear() (RAM purged)"]
|
| 393 |
```
|
| 394 |
|
| 395 |
-
1. **Document Ingestion (`IngestionService` & `DoclingParser`):**
|
| 396 |
-
- The file format (PDF, DOCX, XLSX, image) is detected.
|
| 397 |
-
- For PDFs, `ingest/acroform.py` inspects interactive form fields via `pypdfium2`. Form values are extracted directly without OCR.
|
| 398 |
-
- For standard pages, `pypdfium2` checks whether digital text is present (`has_digital_text`). If digital text exists, Docling extracts document hierarchy, tables, headings, and markdown structures while preserving high-resolution page rendering in memory.
|
| 399 |
-
- If purely scanned or an image, pages are rendered as 150 DPI RGB images.
|
| 400 |
-
2. **Chunking (`DoclingChunker`):**
|
| 401 |
-
- Documents are split into semantic chunks (maximum 768 tokens, bounded by sentence and paragraph boundaries).
|
| 402 |
-
- Table headers are repeated on split table rows to maintain context.
|
| 403 |
-
- Visual page images are attached to chunk objects (`image_bytes`).
|
| 404 |
-
3. **In-Memory Session Store (`SessionVectorStore`):**
|
| 405 |
-
- Chunks are indexed into a temporary in-memory store.
|
| 406 |
-
- Text chunks receive dense semantic embeddings via EmbeddingGemma-2 (`title: {doc} | text: {content}`).
|
| 407 |
-
- Scanned visual chunks are embedded cross-modally via the SigLIP vision projector (`libdocneedle_embed.so`).
|
| 408 |
-
- A sparse Okapi BM25 index is generated in RAM simultaneously.
|
| 409 |
-
4. **Hybrid Retrieval:**
|
| 410 |
-
- For each target schema item, a specialized retrieval query is formulated.
|
| 411 |
-
- Top-$K$ dense vector results and top-$K$ BM25 keyword results are fused using Reciprocal Rank Fusion ($RRF=60$).
|
| 412 |
-
- Document diversity constraints prevent a single document from starving others (`max_chunks_per_document = 2`).
|
| 413 |
-
5. **Reranking (Optional):**
|
| 414 |
-
- If `enable_reranker=True`, candidate passages are scored by Qwen3-Reranker using cross-encoder logit differences.
|
| 415 |
-
6. **Multimodal LLM Inference (`LocalLLMEngine`):**
|
| 416 |
-
- The top supporting text snippets and visual page images are formatted into a multimodal chat turn.
|
| 417 |
-
- Qwen3.5-4B multimodal IT evaluates the evidence and extracts the exact key value and supporting quote in JSON format.
|
| 418 |
-
7. **Collision Resolution & Verification:**
|
| 419 |
-
- `SpatialCollisionResolver` resolves duplicate entity hallucinations across candidate pages.
|
| 420 |
-
- `ConfidenceCalculator` validates extracted values against the requested schema type.
|
| 421 |
-
- **Privacy Cleanup:** In the `finally:` block, `store.clear()` unconditionally purges all vectors and document chunks from RAM.
|
| 422 |
-
|
| 423 |
-
---
|
| 424 |
-
|
| 425 |
-
### Data Flow
|
| 426 |
-
|
| 427 |
-
```
|
| 428 |
-
Client Request (Files + Schema)
|
| 429 |
-
│
|
| 430 |
-
▼
|
| 431 |
-
FastAPI Router / Gradio Handler
|
| 432 |
-
│
|
| 433 |
-
├──► IngestionService ────► AcroForm Direct Extractor (pypdfium2)
|
| 434 |
-
│ ────► Docling Parser (digital text & markdown)
|
| 435 |
-
│ ────► High-Res Page Renderer (visual page chunks)
|
| 436 |
-
│
|
| 437 |
-
├──► SessionVectorStore ──► Dense EmbeddingGemma-2 (libdocneedle_embed.so)
|
| 438 |
-
│ ──► Sparse BM25 Engine
|
| 439 |
-
│ │
|
| 440 |
-
│ ▼
|
| 441 |
-
│ Hybrid RRF Fusion
|
| 442 |
-
│ │
|
| 443 |
-
├──► ExtractionService ───► LocalLLMEngine (Qwen3.5-4B Multimodal GGUF)
|
| 444 |
-
│ │
|
| 445 |
-
│ ▼
|
| 446 |
-
├──► SpatialCollisionResolver ──► Resolves duplicate entity hallucinations
|
| 447 |
-
│ │
|
| 448 |
-
│ ▼
|
| 449 |
-
├──► ConfidenceCalculator ─► Type check & evidence snippet alignment
|
| 450 |
-
│
|
| 451 |
-
▼
|
| 452 |
-
JSON Response ──► finally: store.clear() (RAM purged)
|
| 453 |
-
```
|
| 454 |
-
|
| 455 |
-
---
|
| 456 |
-
|
| 457 |
### OCR-Free Visual RAG & Digital Text Ingestion
|
| 458 |
|
| 459 |
-
DocNeedle
|
| 460 |
-
|
| 461 |
-
1. **Digital Documents:** When a PDF has an embedded digital text layer (`pdf_embedded_text_min_chars = 50`), DocNeedle extracts clean markdown text, nested headings, and structured tables via Docling Core. High-resolution rasterized page images are simultaneously preserved.
|
| 462 |
-
2. **Purely Scanned Documents & Images:** When digital text is absent, pages are rasterized as 150 DPI RGB images. Cross-modal embeddings are generated via SigLIP vision projection. During extraction, the raw page image is supplied directly to the multimodal Qwen3.5-4B LLM, which inspects the visual pixels directly—achieving superior fidelity on handwritten notes, stamps, receipts, and low-contrast scans.
|
| 463 |
-
|
| 464 |
-
---
|
| 465 |
-
|
| 466 |
-
### Interactive PDF AcroForm Direct Extraction
|
| 467 |
|
| 468 |
-
|
|
|
|
| 469 |
|
| 470 |
-
|
| 471 |
-
- Reads field names, alternate descriptions, and user-entered values directly from UTF-16LE binary form streams.
|
| 472 |
-
- Form fields are formatted into structured markdown tables and injected into the document chunks prior to retrieval.
|
| 473 |
-
- Guarantees 100% extraction accuracy on interactive PDF forms without hallucination or OCR error.
|
| 474 |
|
| 475 |
-
-
|
| 476 |
|
| 477 |
### Spatial Collision Resolution
|
| 478 |
|
| 479 |
-
|
| 480 |
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
4. Assigns the value strictly to the field with the highest affinity score, resetting all other colliding fields to `found: False, value: None`.
|
| 486 |
-
|
| 487 |
-
---
|
| 488 |
|
| 489 |
### Native C++ Cross-Modal Embedding Engine
|
| 490 |
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
- `src/docneedle/retrieval/docneedle_embed.cpp` implements a zero-overhead C++ GGUF inference and SigLIP projection engine.
|
| 494 |
-
- Compiled into `libdocneedle_embed.so` and loaded via Python `ctypes`.
|
| 495 |
-
- Embeds both text strings (`instruction: "task: search result | query: {text}"`) and raw image bytes into a unified 768-dimensional L2-normalized vector space.
|
| 496 |
-
- Precompiled native CUDA cubin libraries for `sm_80`, `sm_86`, `sm_89`, and `sm_120a` architectures ensure instant startup across modern NVIDIA GPUs.
|
| 497 |
-
|
| 498 |
-
---
|
| 499 |
|
| 500 |
### Zero-Disk Privacy Guarantee
|
| 501 |
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
2. **Volatile In-Memory Indices:** Embeddings and chunk graphs live exclusively in RAM within `SessionVectorStore`.
|
| 506 |
-
3. **Strict Ephemeral Cleanup:** Vector stores are flushed unconditionally inside `finally:` blocks:
|
| 507 |
```python
|
| 508 |
store = SessionVectorStore()
|
| 509 |
try:
|
| 510 |
store.add_chunks(chunks)
|
| 511 |
-
# ...
|
| 512 |
return response
|
| 513 |
finally:
|
| 514 |
-
store.clear() #
|
| 515 |
```
|
| 516 |
-
4. **Temporary
|
| 517 |
-
5. **Async
|
| 518 |
-
|
| 519 |
-
---
|
| 520 |
|
| 521 |
### Supported Data Types & Validation Rules
|
| 522 |
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
| Type Key | Description | Example Target | Validation Rule |
|
| 526 |
| :--- | :--- | :--- | :--- |
|
| 527 |
-
| `string` |
|
| 528 |
-
| `number` |
|
| 529 |
-
| `money` |
|
| 530 |
-
| `date` |
|
| 531 |
-
| `time` | Clock time or duration | `14:30`, `09:00 AM`, `45 mins` |
|
| 532 |
-
| `email` |
|
| 533 |
-
| `phone` |
|
| 534 |
-
| `id` | Identification
|
| 535 |
-
| `iban` |
|
| 536 |
-
| `percentage`|
|
| 537 |
-
| `person` |
|
| 538 |
-
| `organization`|
|
| 539 |
-
| `address` |
|
| 540 |
-
| `boolean` | Binary
|
| 541 |
-
| `list` / `array` |
|
| 542 |
-
|
| 543 |
-
---
|
| 544 |
|
| 545 |
### Recursive JSON Schema Dereferencing (`$ref`)
|
| 546 |
|
| 547 |
-
|
| 548 |
-
- Dereferences internal pointers (`#/definitions/Item` or `#/$defs/Item`) up to 20 levels deep.
|
| 549 |
-
- Accepts both flat item query arrays (`[{"key": "total", "type": "money", ...}]`) and nested JSON Schema objects with properties and definitions.
|
| 550 |
|
| 551 |
---
|
| 552 |
|
| 553 |
## Web Dashboard (Gradio 6 UI)
|
| 554 |
|
| 555 |
-
|
| 556 |
|
| 557 |
-
- **
|
| 558 |
-
- **Raw JSON Schema Tab:**
|
| 559 |
-
- **Multi-Document
|
| 560 |
-
- **
|
| 561 |
-
- **Dual Output
|
| 562 |
-
- **Formatted Cards View:** Visual cards with green/amber confidence badges, extracted values, and highlighted document provenance citations.
|
| 563 |
-
- **Raw JSON View:** Copy-pasteable complete JSON payload matching the `/v1/extract` response contract.
|
| 564 |
|
| 565 |
---
|
| 566 |
|
| 567 |
## API Reference
|
| 568 |
|
| 569 |
-
### Endpoints Summary
|
| 570 |
-
|
| 571 |
| Method | Endpoint | Description |
|
| 572 |
| :--- | :--- | :--- |
|
| 573 |
-
| `GET` | `/` |
|
| 574 |
-
| `GET` | `/healthz` |
|
| 575 |
-
| `
|
| 576 |
-
| `POST`| `/v1/
|
| 577 |
-
| `
|
| 578 |
-
| `GET` | `/v1/jobs/{job_id}` |
|
| 579 |
-
| `GET` | `/
|
| 580 |
-
| `GET` | `/docs` | Interactive Swagger OpenAPI documentation |
|
| 581 |
-
| `GET` | `/redoc` | Interactive ReDoc API documentation |
|
| 582 |
-
|
| 583 |
-
---
|
| 584 |
|
| 585 |
### 1. Synchronous Extraction (`POST /v1/extract`)
|
| 586 |
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
#### Request Parameters (Multipart Form-Data)
|
| 590 |
|
| 591 |
| Parameter | Type | Required | Description |
|
| 592 |
| :--- | :--- | :--- | :--- |
|
| 593 |
-
| `files` | `binary[]` | Yes | One or more
|
| 594 |
-
| `schema` | `string` | Yes | JSON
|
| 595 |
-
| `enable_reranker` | `boolean` | No | Overrides
|
| 596 |
-
|
| 597 |
-
#### cURL Example
|
| 598 |
|
| 599 |
```bash
|
| 600 |
curl -X POST "http://localhost:7860/v1/extract" \
|
| 601 |
-F "files=@contract.pdf" \
|
| 602 |
-F 'schema=[
|
| 603 |
-
{
|
| 604 |
-
|
| 605 |
-
"description": "Agreed monthly rent amount",
|
| 606 |
-
"type": "money"
|
| 607 |
-
},
|
| 608 |
-
{
|
| 609 |
-
"key": "tenant_name",
|
| 610 |
-
"description": "Full legal name of the tenant",
|
| 611 |
-
"type": "person"
|
| 612 |
-
},
|
| 613 |
-
{
|
| 614 |
-
"key": "commencement_date",
|
| 615 |
-
"description": "Contract start date",
|
| 616 |
-
"type": "date"
|
| 617 |
-
}
|
| 618 |
]'
|
| 619 |
```
|
| 620 |
|
| 621 |
-
|
| 622 |
|
| 623 |
```python
|
| 624 |
-
import httpx
|
| 625 |
-
import json
|
| 626 |
-
|
| 627 |
-
url = "http://localhost:7860/v1/extract"
|
| 628 |
|
| 629 |
schema = [
|
| 630 |
{"key": "monthly_rent", "description": "Agreed monthly rent amount", "type": "money"},
|
| 631 |
{"key": "tenant_name", "description": "Full legal name of the tenant", "type": "person"},
|
| 632 |
-
{"key": "commencement_date", "description": "Contract start date", "type": "date"},
|
| 633 |
]
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
("files", ("contract.pdf", open("contract.pdf", "rb"), "application/pdf")),
|
| 637 |
-
]
|
| 638 |
-
data = {
|
| 639 |
-
"schema": json.dumps(schema),
|
| 640 |
-
"enable_reranker": "false",
|
| 641 |
-
}
|
| 642 |
|
| 643 |
with httpx.Client(timeout=120.0) as client:
|
| 644 |
-
response = client.post(
|
| 645 |
-
|
| 646 |
-
print(json.dumps(result, indent=2))
|
| 647 |
```
|
| 648 |
|
| 649 |
-
|
| 650 |
|
| 651 |
```json
|
| 652 |
{
|
| 653 |
"status": "completed",
|
| 654 |
-
"processing_time_ms":
|
| 655 |
-
"total_items":
|
| 656 |
-
"found_items":
|
| 657 |
"results": [
|
| 658 |
{
|
| 659 |
-
"key": "monthly_rent",
|
| 660 |
-
"
|
| 661 |
-
|
| 662 |
-
"confidence": 0.96,
|
| 663 |
-
"evidence": {
|
| 664 |
-
"document": "contract.pdf",
|
| 665 |
-
"page": 1,
|
| 666 |
-
"snippet": "Kira Bedeli: Aylık 25.000 TL olup her ayın 5. gününe kadar ev sahibinin hesabına ödenecektir."
|
| 667 |
-
},
|
| 668 |
-
"thinking": null
|
| 669 |
-
},
|
| 670 |
-
{
|
| 671 |
-
"key": "tenant_name",
|
| 672 |
-
"found": true,
|
| 673 |
-
"value": "Tolga Arslan",
|
| 674 |
-
"confidence": 0.95,
|
| 675 |
-
"evidence": {
|
| 676 |
-
"document": "contract.pdf",
|
| 677 |
-
"page": 1,
|
| 678 |
-
"snippet": "KİRACI: Tolga Arslan (T.C. Kimlik No: 12345678901)"
|
| 679 |
-
},
|
| 680 |
"thinking": null
|
| 681 |
},
|
| 682 |
{
|
| 683 |
-
"key": "
|
| 684 |
-
"
|
| 685 |
-
|
| 686 |
-
"confidence": 0.94,
|
| 687 |
-
"evidence": {
|
| 688 |
-
"document": "contract.pdf",
|
| 689 |
-
"page": 2,
|
| 690 |
-
"snippet": "İşbu sözleşme 01.11.2024 tarihinde taraflarca imza altına alınmıştır."
|
| 691 |
-
},
|
| 692 |
"thinking": null
|
| 693 |
}
|
| 694 |
]
|
| 695 |
}
|
| 696 |
```
|
| 697 |
|
| 698 |
-
---
|
| 699 |
-
|
| 700 |
### 2. Asynchronous Job Creation (`POST /v1/jobs`)
|
| 701 |
|
| 702 |
-
For large documents or
|
| 703 |
-
|
| 704 |
-
#### cURL Example
|
| 705 |
|
| 706 |
```bash
|
| 707 |
curl -X POST "http://localhost:7860/v1/jobs" \
|
|
@@ -712,8 +475,6 @@ curl -X POST "http://localhost:7860/v1/jobs" \
|
|
| 712 |
]'
|
| 713 |
```
|
| 714 |
|
| 715 |
-
#### Response (`202 Accepted`)
|
| 716 |
-
|
| 717 |
```json
|
| 718 |
{
|
| 719 |
"job_id": "job_01jcb7x4e8rfb9q2",
|
|
@@ -724,104 +485,71 @@ curl -X POST "http://localhost:7860/v1/jobs" \
|
|
| 724 |
}
|
| 725 |
```
|
| 726 |
|
| 727 |
-
---
|
| 728 |
-
|
| 729 |
### 3. Job Status Polling (`GET /v1/jobs/{job_id}`)
|
| 730 |
|
| 731 |
-
Poll real-time execution progress, status, and partial or completed results.
|
| 732 |
-
|
| 733 |
```bash
|
| 734 |
curl -X GET "http://localhost:7860/v1/jobs/job_01jcb7x4e8rfb9q2"
|
| 735 |
```
|
| 736 |
|
| 737 |
-
#### Response (`200 OK`)
|
| 738 |
-
|
| 739 |
```json
|
| 740 |
{
|
| 741 |
"job_id": "job_01jcb7x4e8rfb9q2",
|
| 742 |
"status": "extracting",
|
| 743 |
-
"progress": {
|
| 744 |
-
|
| 745 |
-
"total_items": 2,
|
| 746 |
-
"completed_items": 1,
|
| 747 |
-
"current_key": "total_revenue",
|
| 748 |
-
"percent": 50.0
|
| 749 |
-
},
|
| 750 |
"created_at": 1730390400.125,
|
| 751 |
"completed_at": null,
|
| 752 |
"processing_time_ms": null,
|
| 753 |
"results": [
|
| 754 |
-
{
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
"confidence": 0.95,
|
| 759 |
-
"evidence": {
|
| 760 |
-
"document": "annual_report.pdf",
|
| 761 |
-
"page": 4,
|
| 762 |
-
"snippet": "Net profit for the fiscal year reached $12.4M."
|
| 763 |
-
},
|
| 764 |
-
"thinking": null
|
| 765 |
-
}
|
| 766 |
],
|
| 767 |
"response": null,
|
| 768 |
"error": null
|
| 769 |
}
|
| 770 |
```
|
| 771 |
|
| 772 |
-
---
|
| 773 |
-
|
| 774 |
### 4. Real-Time SSE Streaming (`GET /v1/jobs/{job_id}/events`)
|
| 775 |
|
| 776 |
-
Stream live progress updates and field extractions as they happen using Server-Sent Events (SSE):
|
| 777 |
-
|
| 778 |
```bash
|
| 779 |
curl -N "http://localhost:7860/v1/jobs/job_01jcb7x4e8rfb9q2/events"
|
| 780 |
```
|
| 781 |
|
| 782 |
-
#### Sample Stream Output
|
| 783 |
-
|
| 784 |
```
|
|
|
|
|
|
|
|
|
|
| 785 |
event: progress
|
| 786 |
-
data: {"
|
| 787 |
|
| 788 |
event: progress
|
| 789 |
-
data: {"
|
| 790 |
|
| 791 |
event: item_extracted
|
| 792 |
-
data: {"key": "total_revenue", "found": true, "value": "$84.2M", "confidence": 0.96}
|
| 793 |
|
| 794 |
event: completed
|
| 795 |
-
data: {"status": "completed", "total_items": 2, "found_items": 2, "
|
| 796 |
```
|
| 797 |
|
| 798 |
-
|
| 799 |
|
| 800 |
```python
|
| 801 |
-
import httpx
|
| 802 |
-
import json
|
| 803 |
|
| 804 |
events_url = "http://localhost:7860/v1/jobs/job_01jcb7x4e8rfb9q2/events"
|
| 805 |
-
|
| 806 |
with httpx.Client(timeout=None) as client:
|
| 807 |
with client.stream("GET", events_url) as stream:
|
| 808 |
for line in stream.iter_lines():
|
| 809 |
if line.startswith("data: "):
|
| 810 |
-
|
| 811 |
-
print("Received SSE:", data)
|
| 812 |
```
|
| 813 |
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
### 5. System Health & Hardware Diagnostics (`GET /healthz`)
|
| 817 |
-
|
| 818 |
-
Returns diagnostic metadata regarding the active Python interpreter, GIL state, CUDA/GPU hardware, and model readiness:
|
| 819 |
-
|
| 820 |
-
```bash
|
| 821 |
-
curl -X GET "http://localhost:7860/healthz"
|
| 822 |
-
```
|
| 823 |
|
| 824 |
-
|
| 825 |
|
| 826 |
```json
|
| 827 |
{
|
|
@@ -829,43 +557,12 @@ curl -X GET "http://localhost:7860/healthz"
|
|
| 829 |
"service": "DocNeedle",
|
| 830 |
"version": "0.1.0",
|
| 831 |
"uptime_seconds": 1284.5,
|
| 832 |
-
"process_memory_mb": 420.8,
|
| 833 |
-
"python_version": "3.14.4 experimental free-threading build (tags/v3.14.4:...) [GCC 11.4.0]",
|
| 834 |
"free_threaded": true,
|
| 835 |
"gil_enabled": false,
|
| 836 |
-
"hardware": {
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
"cuda_visible_devices": "0",
|
| 841 |
-
"spaces_zero_gpu": null
|
| 842 |
-
},
|
| 843 |
-
"models": {
|
| 844 |
-
"all_ready": true,
|
| 845 |
-
"llm": {"name": "Qwen3.5-4B-Q4_K_M.gguf", "ready": true, "size_mb": 2680.4},
|
| 846 |
-
"llm_mmproj": {"name": "mmproj-Qwen3.5-4B-F16.gguf", "ready": true, "size_mb": 840.2},
|
| 847 |
-
"embedding": {"name": "embeddinggemma-2-UD-Q4_K_XL.gguf", "ready": true, "size_mb": 152.6},
|
| 848 |
-
"embedding_mmproj": {"name": "mmproj-F16.gguf", "ready": true, "size_mb": 420.1},
|
| 849 |
-
"reranker": {"name": "Qwen3-Reranker-0.6B.Q4_K_M.gguf", "ready": true, "size_mb": 450.8}
|
| 850 |
-
},
|
| 851 |
-
"jobs": {
|
| 852 |
-
"active_jobs": 0,
|
| 853 |
-
"total_cached_jobs": 2
|
| 854 |
-
},
|
| 855 |
-
"config": {
|
| 856 |
-
"embedding_model": "unsloth/embeddinggemma-2-GGUF",
|
| 857 |
-
"embedding_quantization": "ud-q4_k_xl",
|
| 858 |
-
"llm_model": "Qwen3.5-4B-Q4_K_M",
|
| 859 |
-
"llm_speculative_enabled": true,
|
| 860 |
-
"multimodal_embedding": true,
|
| 861 |
-
"multimodal_llm": true,
|
| 862 |
-
"reranker_enabled": false,
|
| 863 |
-
"gpu_enabled": true,
|
| 864 |
-
"cpu_threads": 8,
|
| 865 |
-
"max_upload_size_mb": 100,
|
| 866 |
-
"max_total_upload_size_mb": 100,
|
| 867 |
-
"max_schema_items": 50
|
| 868 |
-
}
|
| 869 |
}
|
| 870 |
```
|
| 871 |
|
|
@@ -873,7 +570,7 @@ curl -X GET "http://localhost:7860/healthz"
|
|
| 873 |
|
| 874 |
## Configuration Reference
|
| 875 |
|
| 876 |
-
|
| 877 |
|
| 878 |
### Configuration File (`config.toml`)
|
| 879 |
|
|
@@ -884,37 +581,44 @@ app_version = "0.1.0"
|
|
| 884 |
debug = false
|
| 885 |
host = "0.0.0.0"
|
| 886 |
port = 8000
|
| 887 |
-
cors_origins = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 888 |
|
| 889 |
[hardware]
|
| 890 |
-
gpu_enabled = true #
|
| 891 |
-
llm_n_gpu_layers = -1 # -1
|
| 892 |
model_n_batch = 256 # Logical batch size for prompt evaluation
|
| 893 |
model_n_ubatch = 256 # Physical micro-batch size for GPU kernels
|
| 894 |
-
reranker_n_ctx = 2048 #
|
| 895 |
-
model_kv_cache_type_k = 1 # 1 = GGML_TYPE_F16 (
|
| 896 |
-
model_kv_cache_type_v = 1
|
| 897 |
-
model_flash_attn = true # Flash Attention
|
| 898 |
|
| 899 |
[ingest]
|
| 900 |
max_upload_size_mb = 100
|
| 901 |
-
pdf_render_scale = 1.5 # 150 DPI page rendering
|
| 902 |
-
pdf_embedded_text_min_chars = 50 # Minimum text length
|
| 903 |
pdf_embedded_text_max_check_pages = 5
|
| 904 |
ingestion_cache_enabled = true
|
| 905 |
|
| 906 |
[chunker]
|
| 907 |
tokenizer_model = "Qwen/Qwen3-Reranker-0.6B"
|
| 908 |
max_tokens = 768
|
| 909 |
-
repeat_table_header = true # Repeat
|
| 910 |
merge_peers = true
|
| 911 |
max_chunk_chars = 4000
|
| 912 |
min_split_chars = 200
|
| 913 |
overflow_factor = 1.25
|
| 914 |
|
| 915 |
[bm25]
|
| 916 |
-
k1 = 1.5 #
|
| 917 |
-
b = 0.75 #
|
| 918 |
top_k = 10
|
| 919 |
|
| 920 |
[embedding]
|
|
@@ -926,26 +630,30 @@ instruction = "task: search result | query: {text}"
|
|
| 926 |
doc_instruction = "title: {doc_name} | text: {text}"
|
| 927 |
|
| 928 |
[retrieval]
|
| 929 |
-
top_k = 10 # Candidates
|
| 930 |
-
rrf_constant = 60
|
| 931 |
-
reranker_enabled = false #
|
| 932 |
reranker_model = "Qwen/Qwen3-Reranker-0.6B"
|
| 933 |
reranker_candidate_k = 4
|
| 934 |
rerank_top_k = 3
|
| 935 |
-
max_chunks_per_document = 2 # Prevent single
|
|
|
|
| 936 |
|
| 937 |
[llm]
|
| 938 |
model_name = "Qwen3.5-4B-Q4_K_M"
|
| 939 |
mmproj_name = "mmproj-Qwen3.5-4B-F16"
|
| 940 |
-
n_ctx =
|
| 941 |
-
temperature = 0.0 #
|
| 942 |
top_p = 0.95
|
| 943 |
max_tokens = 4096
|
| 944 |
single_field_max_tokens = 128
|
| 945 |
thinking_max_tokens = 512
|
| 946 |
enable_thinking = false
|
| 947 |
-
|
|
|
|
|
|
|
| 948 |
speculative_cpu_enabled = false
|
|
|
|
| 949 |
speculative_num_pred_tokens = 5
|
| 950 |
speculative_max_ngram_size = 2
|
| 951 |
|
|
@@ -959,299 +667,114 @@ job_retention_minutes = 15 # In-memory TTL for async job results
|
|
| 959 |
model_storage_dir = "models"
|
| 960 |
|
| 961 |
[security]
|
| 962 |
-
max_schema_items = 50 #
|
| 963 |
-
max_upload_files = 20 #
|
| 964 |
-
max_total_upload_size_mb = 100 #
|
| 965 |
-
max_concurrent_jobs = 10 #
|
| 966 |
```
|
| 967 |
|
| 968 |
### Environment Variables
|
| 969 |
|
| 970 |
-
Any parameter in `config.toml` can be overridden by environment variables:
|
| 971 |
-
|
| 972 |
| Variable | Description | Default |
|
| 973 |
| :--- | :--- | :--- |
|
| 974 |
-
| `GPU_ENABLED` | Enable
|
| 975 |
-
| `LLM_N_GPU_LAYERS` |
|
| 976 |
-
| `MODEL_STORAGE_DIR` |
|
| 977 |
-
| `CONFIG_TOML` | Custom
|
| 978 |
-
| `RERANKER_ENABLED` | Enable
|
| 979 |
-
| `HOST` |
|
| 980 |
-
| `PORT` |
|
| 981 |
-
| `DEBUG` |
|
| 982 |
-
| `SPACES_ZERO_GPU` |
|
| 983 |
|
| 984 |
---
|
| 985 |
|
| 986 |
-
## Available Scripts
|
| 987 |
-
|
| 988 |
-
### Command Reference
|
| 989 |
|
| 990 |
| Command | Description |
|
| 991 |
| :--- | :--- |
|
| 992 |
-
| `uv run python app.py` |
|
| 993 |
-
| `uv run uvicorn docneedle.main:app --reload` |
|
| 994 |
-
| `uv run python scripts/download_models.py` | Download all
|
| 995 |
-
| `uv run python scripts/
|
| 996 |
-
| `uv run
|
| 997 |
-
| `uv run
|
| 998 |
-
| `uv run
|
| 999 |
-
| `uv run
|
| 1000 |
-
| `uv run
|
| 1001 |
-
| `
|
| 1002 |
-
| `uv run ruff check .` | Run Ruff linter across the entire repository |
|
| 1003 |
-
| `uv run ruff check . --fix` | Automatically fix auto-fixable lint issues |
|
| 1004 |
-
| `uv run ruff format .` | Format codebase using Ruff formatter (Python 3.14t profile) |
|
| 1005 |
-
| `bash scripts/deploy_space.sh [SPACE_ID]` | One-click deployment script to Hugging Face Spaces with ZeroGPU |
|
| 1006 |
-
| `docker compose up --build -d` | Build and run containerized DocNeedle stack |
|
| 1007 |
-
|
| 1008 |
-
---
|
| 1009 |
-
|
| 1010 |
-
### ExtractBench Evaluation Benchmark
|
| 1011 |
-
|
| 1012 |
-
DocNeedle includes an automated evaluation runner for LlamaIndex's **ExtractBench** benchmark (`scripts/benchmark_extractbench.py`):
|
| 1013 |
-
|
| 1014 |
-
```bash
|
| 1015 |
-
# Evaluate on the short split
|
| 1016 |
-
uv run python scripts/benchmark_extractbench.py --split short
|
| 1017 |
-
|
| 1018 |
-
# Evaluate on full dataset with custom API endpoint
|
| 1019 |
-
uv run python scripts/benchmark_extractbench.py --split all --api-url http://localhost:7860
|
| 1020 |
-
```
|
| 1021 |
-
|
| 1022 |
-
The benchmark computes:
|
| 1023 |
-
- **Unified Value F1:** Evaluates exact and fuzzy string, numeric, date, and currency matching against ground-truth annotations.
|
| 1024 |
-
- **Page Grounding F1:** Validates whether extracted values are cited with the correct source document page number.
|
| 1025 |
-
- **Strict Nullability / Hallucination Rejection:** Confirms the model outputs `found: False, value: None` when a schema field does not exist in the document.
|
| 1026 |
|
| 1027 |
---
|
| 1028 |
|
| 1029 |
## Testing
|
| 1030 |
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
DocNeedle includes an asynchronous test suite powered by `pytest` and `pytest-asyncio`.
|
| 1034 |
|
| 1035 |
```bash
|
| 1036 |
-
#
|
| 1037 |
uv run pytest tests/test_clean_modules.py tests/test_collision.py tests/test_acroform.py tests/test_health.py tests/test_ui_schema_sync.py
|
| 1038 |
|
| 1039 |
-
#
|
| 1040 |
uv run pytest
|
| 1041 |
```
|
| 1042 |
|
| 1043 |
-
### Test Suite Organization
|
| 1044 |
-
|
| 1045 |
-
```
|
| 1046 |
-
tests/
|
| 1047 |
-
├── test_acroform.py # Interactive PDF form field extraction via pypdfium2
|
| 1048 |
-
├── test_clean_modules.py # Fast unit tests: string sanitization, prompts, response parsing
|
| 1049 |
-
├── test_collision.py # SpatialCollisionResolver unit tests
|
| 1050 |
-
├── test_collision_turkish.py # Turkish contract domain collision tests
|
| 1051 |
-
├── test_cuda_compat.py # CUDA shared library preloading and ZeroGPU decorator mocks
|
| 1052 |
-
├── test_extraction.py # Extraction query synthesis and verifier unit tests
|
| 1053 |
-
├── test_health.py # FastAPI endpoints: /, /healthz, /health, free-threaded checks
|
| 1054 |
-
├── test_ingest.py # Docling parsing, pypdfium2 text checks, chunk creation
|
| 1055 |
-
├── test_jobs.py # Asynchronous JobManager, state machines, TTL, and SSE queues
|
| 1056 |
-
├── test_multimodal_extraction.py # Qwen3.5-4B multimodal extraction with visual page chunks
|
| 1057 |
-
├── test_ocr_grounding.py # Confidence calculation, fuzzy matching, and snippet alignment
|
| 1058 |
-
├── test_retrieval.py # In-memory SessionVectorStore, BM25 indexing, and RRF fusion
|
| 1059 |
-
├── test_speculative.py # Speculative decoding ngram inspection and token validation
|
| 1060 |
-
└── test_ui_schema_sync.py # Gradio UI schema input synchronization with API models
|
| 1061 |
-
```
|
| 1062 |
-
|
| 1063 |
-
### Important Note on Dev Server VRAM
|
| 1064 |
-
|
| 1065 |
> [!WARNING]
|
| 1066 |
-
>
|
| 1067 |
-
>
|
| 1068 |
-
> **Recommendation:** Run lightweight unit tests
|
| 1069 |
|
| 1070 |
---
|
| 1071 |
|
| 1072 |
## Production Deployment
|
| 1073 |
|
| 1074 |
-
### Docker & Docker Compose
|
| 1075 |
-
|
| 1076 |
-
DocNeedle provides a containerized setup based on `python:3.14-slim`.
|
| 1077 |
-
|
| 1078 |
-
#### 1. Quick Start with Docker Compose
|
| 1079 |
-
|
| 1080 |
-
Ensure model weights are downloaded into `./models` on the host, then start the container:
|
| 1081 |
-
|
| 1082 |
-
```bash
|
| 1083 |
-
# 1. Download models locally on host
|
| 1084 |
-
uv run python scripts/download_models.py
|
| 1085 |
-
|
| 1086 |
-
# 2. Build and launch container in detached mode
|
| 1087 |
-
docker compose up --build -d
|
| 1088 |
-
```
|
| 1089 |
-
|
| 1090 |
-
Check container health:
|
| 1091 |
-
|
| 1092 |
-
```bash
|
| 1093 |
-
docker compose ps
|
| 1094 |
-
docker compose logs -f docneedle
|
| 1095 |
-
```
|
| 1096 |
-
|
| 1097 |
-
Access the service at [http://localhost:7860](http://localhost:7860).
|
| 1098 |
-
|
| 1099 |
-
#### 2. Standalone Docker Run
|
| 1100 |
-
|
| 1101 |
-
```bash
|
| 1102 |
-
# Build Docker image
|
| 1103 |
-
docker build -t docneedle:latest .
|
| 1104 |
-
|
| 1105 |
-
# Run container mounting local models and config
|
| 1106 |
-
docker run -d \
|
| 1107 |
-
--name docneedle \
|
| 1108 |
-
-p 7860:7860 \
|
| 1109 |
-
-v $(pwd)/models:/app/models \
|
| 1110 |
-
-v $(pwd)/config.toml:/app/config.toml:ro \
|
| 1111 |
-
--restart unless-stopped \
|
| 1112 |
-
docneedle:latest
|
| 1113 |
-
```
|
| 1114 |
-
|
| 1115 |
-
---
|
| 1116 |
-
|
| 1117 |
### Hugging Face Spaces (ZeroGPU)
|
| 1118 |
|
| 1119 |
-
DocNeedle is designed for
|
| 1120 |
-
|
| 1121 |
-
#### Deployment Script
|
| 1122 |
-
|
| 1123 |
-
Use the automated deployment script `scripts/deploy_space.sh`:
|
| 1124 |
|
| 1125 |
```bash
|
| 1126 |
-
# Ensure huggingface-cli / hf is logged in
|
| 1127 |
hf auth login
|
| 1128 |
-
|
| 1129 |
-
# Deploy to your Space (e.g. username/docneedle)
|
| 1130 |
bash scripts/deploy_space.sh your-hf-username/docneedle
|
| 1131 |
```
|
| 1132 |
|
| 1133 |
-
The script automatically:
|
| 1134 |
-
1. Validates or
|
| 1135 |
-
2.
|
| 1136 |
-
3.
|
| 1137 |
-
4. Monitors build
|
| 1138 |
-
|
| 1139 |
-
---
|
| 1140 |
-
|
| 1141 |
-
### Bare-Metal / Linux Systemd Service
|
| 1142 |
-
|
| 1143 |
-
To run DocNeedle as a persistent system service on Linux:
|
| 1144 |
-
|
| 1145 |
-
1. Create a service file at `/etc/systemd/system/docneedle.service`:
|
| 1146 |
-
|
| 1147 |
-
```ini
|
| 1148 |
-
[Unit]
|
| 1149 |
-
Description=DocNeedle Privacy-First Document Extraction Microservice
|
| 1150 |
-
After=network.target
|
| 1151 |
-
|
| 1152 |
-
[Service]
|
| 1153 |
-
Type=simple
|
| 1154 |
-
User=www-data
|
| 1155 |
-
WorkingDirectory=/opt/DocNeedle
|
| 1156 |
-
Environment="PATH=/opt/DocNeedle/.venv/bin:/usr/local/cuda/bin:/usr/bin"
|
| 1157 |
-
Environment="PYTHONUNBUFFERED=1"
|
| 1158 |
-
Environment="PYTHON_GIL=0"
|
| 1159 |
-
Environment="GPU_ENABLED=true"
|
| 1160 |
-
Environment="PORT=7860"
|
| 1161 |
-
ExecStart=/opt/DocNeedle/.venv/bin/python app.py
|
| 1162 |
-
Restart=always
|
| 1163 |
-
RestartSec=5
|
| 1164 |
-
LimitNOFILE=65536
|
| 1165 |
-
|
| 1166 |
-
[Install]
|
| 1167 |
-
WantedBy=multi-user.target
|
| 1168 |
-
```
|
| 1169 |
-
|
| 1170 |
-
2. Enable and start the service:
|
| 1171 |
-
|
| 1172 |
-
```bash
|
| 1173 |
-
sudo systemctl daemon-reload
|
| 1174 |
-
sudo systemctl enable docneedle
|
| 1175 |
-
sudo systemctl start docneedle
|
| 1176 |
-
sudo systemctl status docneedle
|
| 1177 |
-
```
|
| 1178 |
|
| 1179 |
---
|
| 1180 |
|
| 1181 |
## Troubleshooting & FAQs
|
| 1182 |
|
| 1183 |
-
|
| 1184 |
-
|
| 1185 |
-
|
| 1186 |
-
```
|
| 1187 |
-
|
| 1188 |
-
```
|
| 1189 |
-
|
| 1190 |
-
|
| 1191 |
-
**Cause:** Quantized GGUF weights have not been downloaded or `MODEL_STORAGE_DIR` points to an incorrect directory.
|
| 1192 |
-
**Solution:** Run the downloader script:
|
| 1193 |
-
```bash
|
| 1194 |
-
uv run python scripts/download_models.py
|
| 1195 |
-
```
|
| 1196 |
-
Or set the environment variable pointing to your models directory:
|
| 1197 |
-
```bash
|
| 1198 |
-
export MODEL_STORAGE_DIR=/path/to/models
|
| 1199 |
-
```
|
| 1200 |
-
|
| 1201 |
-
### 3. CUDA Out of Memory (CUDA OOM)
|
| 1202 |
-
**Cause:** Context size or concurrent layer offloading exceeds available VRAM.
|
| 1203 |
-
**Solution:**
|
| 1204 |
-
- In `config.toml`, adjust `llm_n_gpu_layers` to offload fewer layers (e.g. `16` or `20` instead of `-1`).
|
| 1205 |
-
- Verify `model_kv_cache_type_k = 1` and `model_kv_cache_type_v = 1` are set (default in DocNeedle).
|
| 1206 |
-
- Disable the reranker on GPU (`reranker_enabled = false`).
|
| 1207 |
-
|
| 1208 |
-
### 4. `Address already in use` (Port 7860 / 8000)
|
| 1209 |
-
**Cause:** Another instance of DocNeedle or Gradio is already running on the port.
|
| 1210 |
-
**Solution:** Find and terminate the process holding the port:
|
| 1211 |
-
```bash
|
| 1212 |
-
lsof -i :7860
|
| 1213 |
-
kill -9 <PID>
|
| 1214 |
-
```
|
| 1215 |
-
Or run DocNeedle on an alternate port:
|
| 1216 |
-
```bash
|
| 1217 |
-
PORT=7861 uv run python app.py
|
| 1218 |
-
```
|
| 1219 |
-
|
| 1220 |
-
### 5. `libdocneedle_embed.so: cannot open shared object file`
|
| 1221 |
-
**Cause:** The native C++ embedding shared library has not been compiled or is missing from `src/docneedle/retrieval/`.
|
| 1222 |
-
**Solution:** Verify that `src/docneedle/retrieval/libdocneedle_embed.so` exists. If recompiling manually:
|
| 1223 |
-
```bash
|
| 1224 |
-
cd src/docneedle/retrieval
|
| 1225 |
-
g++ -O3 -shared -fPIC -std=c++17 docneedle_embed.cpp -o libdocneedle_embed.so -I. -L. -lllama -lggml-base -lggml-cpu
|
| 1226 |
-
```
|
| 1227 |
-
|
| 1228 |
-
### 6. `ModuleNotFoundError: No module named 'docneedle'`
|
| 1229 |
-
**Cause:** The package was not installed in editable/standard mode or `PYTHONPATH` does not include `src`.
|
| 1230 |
-
**Solution:** Install the local package into your virtual environment:
|
| 1231 |
-
```bash
|
| 1232 |
-
uv pip install -e .
|
| 1233 |
-
```
|
| 1234 |
|
| 1235 |
---
|
| 1236 |
|
| 1237 |
## Contributing
|
| 1238 |
|
| 1239 |
-
Contributions
|
| 1240 |
|
| 1241 |
-
1. **Fork and
|
| 1242 |
-
2. **Strict
|
| 1243 |
-
3. **Privacy
|
| 1244 |
-
4. **Code
|
| 1245 |
```bash
|
| 1246 |
uv run ruff check .
|
| 1247 |
uv run ruff format .
|
| 1248 |
uv run pytest tests/test_clean_modules.py tests/test_collision.py tests/test_acroform.py
|
| 1249 |
```
|
| 1250 |
-
5. **Pull
|
| 1251 |
|
| 1252 |
---
|
| 1253 |
|
| 1254 |
## License
|
| 1255 |
|
| 1256 |
DocNeedle is released under the **[Apache License 2.0](LICENSE)**.
|
| 1257 |
-
You
|
|
|
|
| 8 |
python_version: 3.14
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
+
license: apache-2.0
|
| 12 |
---
|
| 13 |
|
| 14 |
<p align="center">
|
|
|
|
| 18 |
<h1 align="center">DocNeedle</h1>
|
| 19 |
|
| 20 |
<p align="center">
|
| 21 |
+
<strong>Enterprise-Grade Local Document Extraction Microservice & Interactive Platform</strong><br/>
|
| 22 |
+
Extract schema-governed structured data with auditable source citations and statistical confidence scoring using local, in-process neural models.<br/>
|
| 23 |
+
Zero external API reliance, strict zero-disk volatile memory guarantees, and OCR-free visual RAG.
|
| 24 |
</p>
|
| 25 |
|
| 26 |
<p align="center">
|
|
|
|
| 39 |
- [Overview](#overview)
|
| 40 |
- [Key Features](#key-features)
|
| 41 |
- [Tech Stack](#tech-stack)
|
| 42 |
+
- [Benchmark](#benchmark--extractbench-leaderboard-comparison)
|
| 43 |
- [Prerequisites](#prerequisites)
|
| 44 |
- [Getting Started](#getting-started)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
- [System Architecture](#system-architecture)
|
| 46 |
+
- [Web Dashboard](#web-dashboard-gradio-6-ui)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
- [API Reference](#api-reference)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
- [Configuration Reference](#configuration-reference)
|
| 49 |
+
- [Available Scripts](#available-scripts)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
- [Testing](#testing)
|
|
|
|
|
|
|
|
|
|
| 51 |
- [Production Deployment](#production-deployment)
|
| 52 |
+
- [Troubleshooting](#troubleshooting--faqs)
|
|
|
|
|
|
|
|
|
|
| 53 |
- [Contributing](#contributing)
|
| 54 |
- [License](#license)
|
| 55 |
|
|
|
|
| 57 |
|
| 58 |
## Overview
|
| 59 |
|
| 60 |
+
**DocNeedle** is a privacy-first local document extraction microservice with an interactive web application. It ingests unstructured documents (**PDF**, **DOCX**, **XLSX**, high-resolution **images**) together with a user-defined JSON schema, and returns target values with exact textual citations, source document provenance, page numbers, and confidence scores.
|
| 61 |
|
| 62 |
+
Unlike pipelines built on cloud APIs or brittle OCR engines, DocNeedle provides:
|
| 63 |
|
| 64 |
+
- **Zero cloud reliance:** All models run in-process via native multi-architecture `llama.cpp` bindings and C++ shared libraries with hardware acceleration.
|
| 65 |
+
- **Zero-disk privacy:** Payloads, embeddings, and indices live only in volatile RAM and are purged unconditionally after each request (`store.clear()`).
|
| 66 |
+
- **OCR-free visual RAG:** Digital PDFs are parsed for text and tables; scanned documents and images are ingested as high-resolution page chunks, embedded cross-modally (SigLIP projector) and read directly by the multimodal Qwen3.5-4B LLM.
|
| 67 |
+
- **Free-threaded concurrency:** Python 3.14t (PEP 703, No-GIL) for true multi-core parsing, chunking, and HTTP handling.
|
| 68 |
|
| 69 |
---
|
| 70 |
|
| 71 |
## Key Features
|
| 72 |
|
| 73 |
+
- **Zero-Disk Persistence:** `SessionVectorStore` is strictly in-memory; vectors, chunks, and temp files are cleared in `finally: store.clear()`.
|
| 74 |
+
- **In-Process Multimodal Models:**
|
| 75 |
+
- **LLM:** Qwen3.5-4B GGUF (`Qwen3.5-4B-Q4_K_M.gguf` + `mmproj-Qwen3.5-4B-F16.gguf`), schema-constrained JSON extraction.
|
| 76 |
+
- **Cross-Modal Embedder:** EmbeddingGemma-2 GGUF (`embeddinggemma-2-UD-Q4_K_XL.gguf` + `mmproj-F16.gguf`), unified text and visual page embeddings.
|
| 77 |
+
- **Reranker:** Qwen3-Reranker-0.6B GGUF (`Qwen3-Reranker-0.6B.Q4_K_M.gguf`), optional cross-encoder scoring.
|
| 78 |
+
- **Native C++ Embedder:** `libdocneedle_embed.so` (loaded via `ctypes`) runs GGUF inference and SigLIP projection without intermediate serialization.
|
| 79 |
+
- **AcroForm Direct Extraction:** Interactive PDF form fields are parsed via `pypdfium2` (`ingest/acroform.py`) before chunking, with no hallucination.
|
| 80 |
+
- **Spatial Collision Resolution:** `SpatialCollisionResolver` (`extraction/collision.py`) assigns a repeated salient value only to the field with the highest context affinity.
|
| 81 |
+
- **FP16 / Quantized KV Cache & Flash Attention:** High-speed Flash Attention with stable FP16 KV cache (`model_kv_cache_type_k/v = 1`, configurable to Q8_0) supporting a 32,768-token window in compact VRAM.
|
| 82 |
+
- **Speculative Prompt Lookup Decoding:** `LlamaPromptLookupDecoding` (`max_ngram_size=2`, `num_pred_tokens=5`), opt-in.
|
| 83 |
+
- **Hybrid RRF Retrieval:** Dense cosine + Okapi BM25 fused via Reciprocal Rank Fusion ($RRF=60$) with document-diversity constraints.
|
| 84 |
+
- **Unified UI + REST API:** Dark-mode Gradio 6 dashboard and FastAPI on the same port (`7860`), with SSE streaming for async jobs.
|
| 85 |
+
- **ZeroGPU & Multi-Arch CUDA:** Precompiled multi-architecture CUDA binaries (embedded `sm_80`, `sm_86`, `sm_89`, `sm_120a` kernels in `libggml-cuda.so`); dynamic leasing via `@spaces.GPU`.
|
|
|
|
| 86 |
|
| 87 |
---
|
| 88 |
|
|
|
|
| 90 |
|
| 91 |
| Layer | Technologies |
|
| 92 |
| :--- | :--- |
|
| 93 |
+
| **Runtime** | Python 3.14t (Free-Threaded, PEP 703 No-GIL) |
|
| 94 |
+
| **Microservice** | FastAPI 0.115+, Uvicorn 0.32+, Pydantic v2, Pydantic-Settings |
|
| 95 |
+
| **Web Dashboard** | Gradio 6+, dark mode, dynamic schema builder, formatted/raw JSON tabs |
|
| 96 |
+
| **Ingestion** | Docling Core 2.15+, pypdfium2, python-docx, openpyxl, Pillow |
|
| 97 |
+
| **AcroForm** | pypdfium2 native bindings (`FPDFPage_GetAnnot`, `FPDFAnnot_GetFormFieldValue`) |
|
| 98 |
+
| **Embeddings** | EmbeddingGemma-2 UD-Q4_K_XL GGUF + SigLIP mmproj-F16 (768 dim), native `libdocneedle_embed.so` |
|
| 99 |
+
| **Lexical Search** | rank-bm25 (Okapi BM25) |
|
| 100 |
+
| **Reranker** | Qwen3-Reranker-0.6B Q4_K_M GGUF (llama.cpp logit scoring) |
|
| 101 |
+
| **LLM Engine** | Qwen3.5-4B-Q4_K_M GGUF + mmproj-Qwen3.5-4B-F16 (16k context, Flash Attention) |
|
| 102 |
+
| **Inference Backend** | llama-cpp-python 0.3.x with CUDA/cuBLAS |
|
| 103 |
+
| **Packaging & Deployment** | `uv`, Hugging Face Spaces (ZeroGPU A10G / A100) |
|
|
|
|
|
|
|
| 104 |
|
| 105 |
---
|
| 106 |
|
| 107 |
+
## Benchmark & ExtractBench Leaderboard Comparison
|
| 108 |
|
| 109 |
+
### Overview & Methodology
|
| 110 |
|
| 111 |
+
DocNeedle was evaluated on **[ExtractBench](https://www.extractbench.ai/)** ([LlamaIndex](https://github.com/run-llama/ExtractBench), [arXiv:2607.29677](https://arxiv.org/abs/2607.29677)), an enterprise benchmark for schema-guided document extraction: **370 documents**, **4,869 pages**, **13,577 annotated fields** across scanned invoices, regulatory forms, bank statements, contracts, multi-page financial tables, and handwritten notations.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
- **Short (252 docs, 10,676 fields):** up to 10 pages.
|
| 114 |
+
- **Medium (98 docs, 2,808 fields):** 11–50 pages.
|
| 115 |
+
- **Long (20 docs, 93 fields):** over 50 pages.
|
| 116 |
|
| 117 |
+
Tracked metrics: **Unified Value F1** (failed documents score 0), **Page Grounding Accuracy**, **Strict Null Accuracy** (no hallucination for absent fields), **Cost per Page**, and **Data Privacy & Disk Security**.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
### Curated Leaderboard Comparison
|
|
|
|
| 120 |
|
| 121 |
+
Source: official `leaderboard.csv` from [run-llama/ExtractBench](https://github.com/run-llama/ExtractBench) ([leaderboard](https://www.extractbench.ai/#leaderboard)).
|
| 122 |
+
|
| 123 |
+
| System / Model | Provider / Category | Architecture & Size | Overall F1 | Short (≤10p) | Medium (11-50p) | Long (>50p) | Page Grounding | Cost / Page | Privacy & Storage |
|
| 124 |
+
| :--- | :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :--- |
|
| 125 |
+
| **LlamaExtract Agentic Plus** | LlamaIndex | Cloud Agentic Pipeline | **96.17%** | 97.02% | 94.30% | 94.65% | 88.26% | $0.0750 | Cloud API (External) |
|
| 126 |
+
| **Codex (GPT-6.1 Sol Evidence)** | OpenAI / Codex | Frontier Coding Agent | **95.31%** | 97.01% | 92.96% | 85.46% | 89.37% | $0.0713 | Cloud API (External) |
|
| 127 |
+
| **Claude Code (Sonnet 5.5 Evidence)** | Anthropic | Frontier Coding Agent | **94.68%** | 96.22% | 92.97% | 83.69% | 75.99% | $0.0569 | Cloud API (External) |
|
| 128 |
+
| **OpenAI GPT-6 Astra** | OpenAI | Commercial Frontier VLM | **91.91%** | 97.22% | 90.56% | 31.70% | 0.00% *(N/A)* | $0.1109 | Cloud API (External) |
|
| 129 |
+
| **Qwen3.5 4B (Raw Base Model)** | Alibaba / OSS | Standalone Base Model | **82.43%** | 89.06% | 76.64% | 27.31% | 0.00% *(N/A)* | Free (self-host) | Self-Hosted / Local |
|
| 130 |
+
| **Google Gemini 3.8 Flash** | Google | Commercial Fast VLM | **80.71%** | 88.14% | 72.23% | 28.70% | 0.00% *(N/A)* | $0.0043 | Cloud API (External) |
|
| 131 |
+
| **DocNeedle (In-Process)** | **DocNeedle** | **Qwen3.5-4B + Gemma2-RAG** | **75.78%** | **77.30%** | **69.53%** | **70.59%** | **78.82%** | **$0.00 (on-premise)** | **Zero-Disk RAM / Air-Gapped** |
|
| 132 |
+
|
| 133 |
+
> [!TIP]
|
| 134 |
+
> **Model-agnostic scaling:** The published results (**75.78% Overall F1**, **90.70% Short Grounding**) use a compact **4B model** (`Qwen3.5-4B-Q4_K_M`, ~2.6 GB VRAM) and a **0.6B embedder** to validate operation on commodity hardware (6 GB VRAM minimum, or multi-core CPUs). Ingestion, AcroForm parsing, hybrid RAG, and collision resolution are model-agnostic, so larger weights (e.g. **Qwen3.5-9B**, **Qwen3.5-35B**) offer a scaling path toward **88%–95%+ F1** while keeping zero-disk privacy and zero per-page fees.
|
| 135 |
+
|
| 136 |
+
### Key Insights & Trade-offs
|
| 137 |
+
|
| 138 |
+
- **Long-Document Resilience (+43.28 pts vs. base model):** Beyond 50 pages, unaugmented models suffer attention degradation (raw Qwen3.5 4B drops from 89.06% to 27.31%, GPT-6 Astra to 31.70%). DocNeedle sustains **70.59% F1** (2.5× improvement) by routing relevant visual/text chunks into a bounded context.
|
| 139 |
+
- **Auditable Page Grounding (90.70% short, 78.82% overall):** Unlike raw VLMs that score 0.00% on source attribution, DocNeedle pairs every extracted value with verified page numbers and verbatim text snippets.
|
| 140 |
+
- **Deterministic Form Extraction:** Native PDF AcroForm parsing via `pypdfium2` extracts interactive checkboxes and field inputs without OCR artifacts.
|
| 141 |
+
- **Local Privacy & Predictable Costs:** Runs 100% in-process with zero network telemetry; vectors and chunk images reside in volatile RAM and are wiped via `finally: store.clear()`.
|
| 142 |
+
- **Engineering Trade-offs:** Dense single-page documents may experience retrieval filtering on isolated clauses (77.30% F1 vs. 89.06% unconstrained base model), and local multimodal inference averages ~34.7s/doc on workstation GPUs.
|
| 143 |
|
| 144 |
+
### Detailed Results by Split
|
| 145 |
+
|
| 146 |
+
Generated by `scripts/benchmark_extractbench.py` and stored in `benchmark_results/`:
|
| 147 |
+
|
| 148 |
+
| Metric | Short (≤10p) | Medium (11-50p) | Long (>50p) | Full (370 docs) |
|
| 149 |
+
| :--- | :---: | :---: | :---: | :---: |
|
| 150 |
+
| **Documents** | 252 | 98 | 20 | **370** |
|
| 151 |
+
| **Target Fields** | 10,676 | 2,808 | 93 | **13,577** |
|
| 152 |
+
| **Strictly Matched Fields** | 8,776 | 2,159 | 59 | **10,994** |
|
| 153 |
+
| **Unified Value F1** | **77.30%** | **69.53%** | **70.59%** | **75.78%** |
|
| 154 |
+
| **Value Precision** | **81.37%** | **79.55%** | **80.60%** | **81.04%** |
|
| 155 |
+
| **Value Recall** | **73.62%** | **61.75%** | **62.79%** | **71.16%** |
|
| 156 |
+
| **Page Grounding** | **90.70%** | **55.03%** | **45.58%** | **78.82%** |
|
| 157 |
+
| **Strict Null Accuracy** | **82.34%** | **84.90%** | **27.78%** | **82.74%** |
|
| 158 |
+
| **Perfect Documents Rate** | 3.57% (9) | 1.02% (1) | 0.00% (0) | **2.70% (10)** |
|
| 159 |
+
| **Avg. Latency / Document** | 34.7 s | 67.8 s | 95.9 s | **46.9 s** |
|
| 160 |
+
| **Total Execution Time** | 2h 30m 38s | 1h 50m 48s | 32m 11s | **4h 49m 28s** |
|
| 161 |
+
|
| 162 |
+
### Reproducing the Benchmark
|
| 163 |
|
| 164 |
```bash
|
| 165 |
+
uv run python app.py # 1. start the server
|
| 166 |
+
uv run python scripts/benchmark_extractbench.py --split short # 2. short split
|
| 167 |
+
uv run python scripts/benchmark_extractbench.py --split all --api-url http://localhost:7860 # 3. all 370 documents
|
| 168 |
+
cat benchmark_results/summary_short.json benchmark_results/summary_all.json # 4. view summaries
|
| 169 |
```
|
| 170 |
|
| 171 |
+
Per-document logs, ground-truth diffs, and summary metrics are saved to `benchmark_results/`.
|
| 172 |
|
| 173 |
+
---
|
| 174 |
|
| 175 |
+
## Prerequisites
|
| 176 |
|
| 177 |
+
- **OS:** Linux (Ubuntu 22.04/24.04, Debian 12, Arch, Fedora recommended). On Windows, use WSL2 (Ubuntu 22.04/24.04 recommended); native Windows and macOS are not supported because the bundled native libraries (`libdocneedle_embed.so`, `libllama.so`, `libggml-*.so`) are Linux ELF binaries.
|
| 178 |
+
- **RAM:** 8 GB minimum (16 GB recommended for CPU-only inference).
|
| 179 |
+
- **GPU (optional):** NVIDIA, CUDA 12.0+, Compute Capability ≥ 8.0 (RTX 30/40/50, A100, H100, Blackwell). Fits within 6 GB VRAM (minimum).
|
| 180 |
+
- **Storage:** ~5 GB for model weights and tokenizers.
|
| 181 |
+
- **System packages** (OpenGL and GLib for Docling/pypdfium2):
|
| 182 |
|
| 183 |
```bash
|
| 184 |
+
# Ubuntu / Debian
|
| 185 |
+
sudo apt-get update && sudo apt-get install -y build-essential cmake curl git libgl1 libglib2.0-0
|
| 186 |
+
# Fedora / RHEL
|
| 187 |
+
sudo dnf install -y gcc gcc-c++ cmake curl git mesa-libGL glib2
|
| 188 |
+
# Arch Linux
|
| 189 |
+
sudo pacman -S base-devel cmake curl git mesa glib2
|
| 190 |
```
|
| 191 |
|
| 192 |
+
- **[`uv`](https://github.com/astral-sh/uv):**
|
|
|
|
|
|
|
| 193 |
|
| 194 |
```bash
|
| 195 |
+
curl -LsSf https://astral.sh/uv/install.sh | sh
|
| 196 |
```
|
| 197 |
|
| 198 |
+
---
|
| 199 |
+
|
| 200 |
+
## Getting Started
|
| 201 |
|
| 202 |
+
### 1. Clone and Create the Environment
|
| 203 |
|
| 204 |
```bash
|
| 205 |
+
git clone https://github.com/N4YuC4/DocNeedle.git
|
| 206 |
+
cd DocNeedle
|
| 207 |
|
| 208 |
+
uv python install 3.14t # free-threaded Python
|
| 209 |
uv venv --python 3.14t
|
|
|
|
|
|
|
| 210 |
source .venv/bin/activate
|
|
|
|
| 211 |
|
|
|
|
|
|
|
|
|
|
| 212 |
python -c "import sys; print('Free-threaded (No-GIL):', not getattr(sys, '_is_gil_enabled', lambda: True)())"
|
| 213 |
+
# Expected: Free-threaded (No-GIL): True
|
| 214 |
```
|
| 215 |
|
| 216 |
+
### 2. Install Dependencies
|
|
|
|
|
|
|
| 217 |
|
| 218 |
```bash
|
| 219 |
uv sync
|
| 220 |
```
|
| 221 |
|
| 222 |
> [!NOTE]
|
| 223 |
+
> To compile `llama-cpp-python` with CUDA locally, export the toolkit paths first:
|
| 224 |
> ```bash
|
| 225 |
> export CUDACXX=/usr/local/cuda/bin/nvcc
|
| 226 |
> export CMAKE_ARGS="-DGGML_CUDA=on -DCMAKE_CUDA_ARCHITECTURES=native"
|
| 227 |
> uv pip install --no-build-isolation "llama-cpp-python>=0.3.0,<0.4.0"
|
| 228 |
> ```
|
| 229 |
|
| 230 |
+
### 3. Download Quantized Models
|
|
|
|
|
|
|
| 231 |
|
| 232 |
```bash
|
| 233 |
uv run python scripts/download_models.py
|
| 234 |
```
|
| 235 |
|
| 236 |
+
Automatically downloads the required quantized weights (~4.5 GB) into `models/` (EmbeddingGemma-2 cross-modal embedder, Qwen3.5-4B GGUF, SigLIP vision projectors, and reranker). Pass `--embedding`, `--reranker`, or `--llm` to download specific groups.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
+
### 4. Configure
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
+
Settings load from `config.toml`; optionally override via `.env` (`cp .env.example .env 2>/dev/null || touch .env`). Key defaults:
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
+
- `gpu_enabled = true`: CUDA offload if available (`false` for CPU-only).
|
| 243 |
+
- `llm_n_gpu_layers = -1`: offload all layers (`0` = CPU).
|
| 244 |
+
- `reranker_enabled = false`: disabled by default for low latency; enable for maximum citation precision.
|
| 245 |
|
| 246 |
+
### 5. Launch
|
| 247 |
|
| 248 |
+
**Unified Gradio UI + FastAPI (default, port `7860`):**
|
| 249 |
|
| 250 |
```bash
|
| 251 |
uv run python app.py
|
| 252 |
```
|
| 253 |
|
| 254 |
+
- Dashboard: [http://localhost:7860](http://localhost:7860)
|
| 255 |
+
- Swagger: [http://localhost:7860/docs](http://localhost:7860/docs) · ReDoc: [http://localhost:7860/redoc](http://localhost:7860/redoc)
|
| 256 |
+
- Health: [http://localhost:7860/healthz](http://localhost:7860/healthz)
|
|
|
|
|
|
|
| 257 |
|
| 258 |
+
**API-only server (port `8000`):**
|
|
|
|
|
|
|
| 259 |
|
| 260 |
```bash
|
| 261 |
uv run uvicorn docneedle.main:app --host 0.0.0.0 --port 8000 --reload
|
|
|
|
| 269 |
|
| 270 |
```
|
| 271 |
DocNeedle/
|
| 272 |
+
├── assets/ # Logo (SVG) and static icons
|
| 273 |
├── app.py # Unified Gradio 6 UI + FastAPI root mount & ZeroGPU entry
|
| 274 |
+
├── config.toml # Application, model & pipeline configuration
|
| 275 |
+
├── pyproject.toml / requirements.txt
|
| 276 |
+
├── Dockerfile / docker-compose.yml
|
|
|
|
|
|
|
| 277 |
├── scripts/
|
| 278 |
+
│ ├── download_models.py # Model downloader with verification
|
| 279 |
+
│ ├── benchmark_extractbench.py # ExtractBench runner (Value F1, Grounding F1)
|
| 280 |
+
│ └── deploy_space.sh # Hugging Face Spaces (ZeroGPU) deployment
|
| 281 |
+
├── models/ # embedding/, reranker/, llm/ (GGUF + projectors)
|
|
|
|
|
|
|
|
|
|
| 282 |
├── src/docneedle/
|
| 283 |
+
│ ├── main.py # FastAPI factory, CORS, /healthz
|
| 284 |
+
│ ├── config.py # Pydantic BaseSettings (TOML + env)
|
| 285 |
+
│ ├── cuda_compat.py # ZeroGPU preloaders & memory leasing wrappers
|
| 286 |
+
│ ├── api/ # routes_extract.py, routes_jobs.py, validation.py ($ref, size checks)
|
| 287 |
+
│ ├── jobs/ # models.py, manager.py (in-memory registry, SSE queues, TTL)
|
| 288 |
+
│ ├── ingest/ # parser.py, chunker.py, acroform.py, cache.py, service.py, models.py
|
| 289 |
+
│ ├── retrieval/ # embedder.py, docneedle_embed.cpp, libdocneedle_embed.so,
|
| 290 |
+
│ │ # worker.py (process-isolated embedder), bm25.py, reranker.py,
|
| 291 |
+
│ │ # store.py (SessionVectorStore, RRF), models.py
|
| 292 |
+
│ ├── extraction/ # service.py, verifier.py, matcher.py, collision.py, schemas.py
|
| 293 |
+
│ └── llm/ # local_engine.py, client.py, handlers.py, parsing.py,
|
| 294 |
+
│ # prompts.py, speculative.py
|
| 295 |
+
└── tests/ # Pytest suite (see Testing)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
```
|
| 297 |
|
|
|
|
|
|
|
| 298 |
### End-to-End Extraction Lifecycle
|
| 299 |
|
|
|
|
|
|
|
| 300 |
```mermaid
|
| 301 |
flowchart TD
|
| 302 |
A["Uploaded Files & Schema"] --> B["1. Ingestion: AcroForm Direct + Docling + pypdfium2"]
|
|
|
|
| 310 |
I --> J["finally: store.clear() (RAM purged)"]
|
| 311 |
```
|
| 312 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
### OCR-Free Visual RAG & Digital Text Ingestion
|
| 314 |
|
| 315 |
+
DocNeedle natively ingests PDFs, Office documents (`.docx`, `.xlsx`, `.xls`), web pages (`.html`, `.htm`), delimited text (`.csv`, `.tsv`, `.txt`, `.md`, `.json`, `.xml`), and image formats (`.png`, `.jpg`, `.jpeg`, `.webp`, `.tiff`, `.bmp`).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
|
| 317 |
+
1. **Digital documents:** With an embedded text layer (`pdf_embedded_text_min_chars = 50`), Docling extracts markdown, headings, and tables; rasterized pages are preserved alongside.
|
| 318 |
+
2. **Scanned documents & images:** Pages are rasterized at 150 DPI and embedded cross-modally via SigLIP. The raw page image goes directly to the multimodal LLM, which improves fidelity on handwriting, stamps, receipts, and low-contrast scans.
|
| 319 |
|
| 320 |
+
### Interactive PDF AcroForm Extraction
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
+
`src/docneedle/ingest/acroform.py` inspects form fields via `pypdfium2.raw` (`FPDFPage_GetAnnot`, `FPDFAnnot_GetFormFieldType`), reads names, alternate descriptions, and values from UTF-16LE form streams, formats them as markdown tables, and injects them into the chunks before retrieval, giving deterministic accuracy on interactive forms.
|
| 323 |
|
| 324 |
### Spatial Collision Resolution
|
| 325 |
|
| 326 |
+
LLMs may repeat one salient number or entity across several unpopulated fields. `SpatialCollisionResolver` (`extraction/collision.py`):
|
| 327 |
|
| 328 |
+
1. Detects duplicate non-trivial values across distinct schema items.
|
| 329 |
+
2. Counts occurrences of the value on candidate pages.
|
| 330 |
+
3. If the value occurs only once, scores context affinity between each field description and the text around the value.
|
| 331 |
+
4. Assigns the value to the highest-affinity field and resets the others to `found: False, value: None`.
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
### Native C++ Cross-Modal Embedding Engine
|
| 334 |
|
| 335 |
+
`src/docneedle/retrieval/docneedle_embed.cpp` is compiled to `libdocneedle_embed.so` and loaded via `ctypes`. It embeds text (`instruction: "task: search result | query: {text}"`) and raw image bytes into one 768-dimensional L2-normalized space. Precompiled multi-architecture CUDA kernels embedded directly in `libggml-cuda.so` (supporting `sm_80`, `sm_86`, `sm_89`, and `sm_120a`) ensure immediate startup on modern NVIDIA GPUs without runtime compilation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
### Zero-Disk Privacy Guarantee
|
| 338 |
|
| 339 |
+
1. **No external telemetry:** Embeddings and inference run in-process; no cloud endpoint is contacted.
|
| 340 |
+
2. **Volatile indices:** Embeddings and chunk graphs exist only in RAM within `SessionVectorStore`.
|
| 341 |
+
3. **Ephemeral cleanup:**
|
|
|
|
|
|
|
| 342 |
```python
|
| 343 |
store = SessionVectorStore()
|
| 344 |
try:
|
| 345 |
store.add_chunks(chunks)
|
| 346 |
+
# ... retrieval & extraction ...
|
| 347 |
return response
|
| 348 |
finally:
|
| 349 |
+
store.clear() # deallocates chunk buffers immediately
|
| 350 |
```
|
| 351 |
+
4. **Temporary uploads:** OS temp files from parser streaming are unlinked (`temp_path.unlink()`) in `finally:` blocks.
|
| 352 |
+
5. **Async job TTL:** Cached job results expire after `job_retention_minutes` (default 15).
|
|
|
|
|
|
|
| 353 |
|
| 354 |
### Supported Data Types & Validation Rules
|
| 355 |
|
| 356 |
+
| Type Key | Description | Example | Validation Rule |
|
|
|
|
|
|
|
| 357 |
| :--- | :--- | :--- | :--- |
|
| 358 |
+
| `string` | Free text | Any phrase or sentence | Trimmed string |
|
| 359 |
+
| `number` | Numeric quantity | `42`, `3.14`, `1,250` | Strips commas/spaces, verifies numeric |
|
| 360 |
+
| `money` | Amount with currency | `25.000 TL`, `$4,500.00`, `€120` | Amount + currency symbol/code |
|
| 361 |
+
| `date` | ISO or localized date | `2024-10-15`, `15/10/2024` | Format & calendar sanity |
|
| 362 |
+
| `time` | Clock time or duration | `14:30`, `09:00 AM`, `45 mins` | 12h/24h patterns |
|
| 363 |
+
| `email` | Email address | `contact@docneedle.org` | RFC 5322 regex |
|
| 364 |
+
| `phone` | Phone number | `+90 555 123 4567` | Digit count & country codes |
|
| 365 |
+
| `id` | Identification number | National ID, passport, plate | Alphanumeric identifier |
|
| 366 |
+
| `iban` | Bank account number | `TR33 0006 1005 1234 5678 9012 34` | Format & checksum |
|
| 367 |
+
| `percentage` | Percentage | `18%`, `2.5 %` | Extracts number before `%` |
|
| 368 |
+
| `person` | Human name | `Tolga Arslan`, `Dr. Jane Doe` | Capitalized name syntax |
|
| 369 |
+
| `organization` | Company or entity | `Acme Corp` | Entity keywords & casing |
|
| 370 |
+
| `address` | Street address | `Ataturk Cad. No: 12 Kadikoy/Istanbul` | Filters header timestamps |
|
| 371 |
+
| `boolean` | Binary condition | `true`, `false`, `yes`, `no` | Normalized to `True`/`False` |
|
| 372 |
+
| `list` / `array` | Delimited items | `Apple; Banana; Orange` | Split into typed items |
|
|
|
|
|
|
|
| 373 |
|
| 374 |
### Recursive JSON Schema Dereferencing (`$ref`)
|
| 375 |
|
| 376 |
+
`src/docneedle/api/validation.py` dereferences internal pointers (`#/definitions/Item`, `#/$defs/Item`) up to 20 levels deep and accepts both flat item arrays (`[{"key": "total", "type": "money", ...}]`) and nested JSON Schema objects.
|
|
|
|
|
|
|
| 377 |
|
| 378 |
---
|
| 379 |
|
| 380 |
## Web Dashboard (Gradio 6 UI)
|
| 381 |
|
| 382 |
+
Served at `http://localhost:7860`, matching the REST API:
|
| 383 |
|
| 384 |
+
- **Schema Builder:** Add, edit, or remove fields visually with type dropdowns.
|
| 385 |
+
- **Raw JSON Schema Tab:** Bidirectional sync with the visual builder.
|
| 386 |
+
- **Multi-Document Upload:** PDFs, Word, Excel, and images via drag & drop.
|
| 387 |
+
- **Live Progress:** SSE-driven progress bar with current step, field key, and percentage.
|
| 388 |
+
- **Dual Output:** Formatted cards (confidence badges, values, highlighted citations) and raw JSON matching the `/v1/extract` contract.
|
|
|
|
|
|
|
| 389 |
|
| 390 |
---
|
| 391 |
|
| 392 |
## API Reference
|
| 393 |
|
|
|
|
|
|
|
| 394 |
| Method | Endpoint | Description |
|
| 395 |
| :--- | :--- | :--- |
|
| 396 |
+
| `GET` | `/` | Service info, docs links, version |
|
| 397 |
+
| `GET` | `/healthz`, `/health` | Diagnostics (GIL status, GPU/CUDA, models, config); `/health` is an alias |
|
| 398 |
+
| `POST` | `/v1/extract` | **Synchronous** extraction, returns complete JSON |
|
| 399 |
+
| `POST` | `/v1/jobs` | **Asynchronous** extraction, returns `202 Accepted` with tracking URLs |
|
| 400 |
+
| `GET` | `/v1/jobs/{job_id}` | Poll job progress and results |
|
| 401 |
+
| `GET` | `/v1/jobs/{job_id}/events` | **SSE** real-time job events |
|
| 402 |
+
| `GET` | `/docs`, `/redoc` | Swagger / ReDoc documentation |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
|
| 404 |
### 1. Synchronous Extraction (`POST /v1/extract`)
|
| 405 |
|
| 406 |
+
Multipart form-data parameters:
|
|
|
|
|
|
|
| 407 |
|
| 408 |
| Parameter | Type | Required | Description |
|
| 409 |
| :--- | :--- | :--- | :--- |
|
| 410 |
+
| `files` | `binary[]` | Yes | One or more files (PDF, DOCX, XLSX, HTML, CSV, TXT, MD, PNG, JPG, WEBP, TIFF) |
|
| 411 |
+
| `schema` | `string` | Yes | JSON array of target keys, descriptions, and types |
|
| 412 |
+
| `enable_reranker` | `boolean` | No | Overrides reranking; defaults to `config.toml` |
|
|
|
|
|
|
|
| 413 |
|
| 414 |
```bash
|
| 415 |
curl -X POST "http://localhost:7860/v1/extract" \
|
| 416 |
-F "files=@contract.pdf" \
|
| 417 |
-F 'schema=[
|
| 418 |
+
{"key": "monthly_rent", "description": "Agreed monthly rent amount", "type": "money"},
|
| 419 |
+
{"key": "tenant_name", "description": "Full legal name of the tenant", "type": "person"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
]'
|
| 421 |
```
|
| 422 |
|
| 423 |
+
Python (`httpx`):
|
| 424 |
|
| 425 |
```python
|
| 426 |
+
import httpx, json
|
|
|
|
|
|
|
|
|
|
| 427 |
|
| 428 |
schema = [
|
| 429 |
{"key": "monthly_rent", "description": "Agreed monthly rent amount", "type": "money"},
|
| 430 |
{"key": "tenant_name", "description": "Full legal name of the tenant", "type": "person"},
|
|
|
|
| 431 |
]
|
| 432 |
+
files = [("files", ("contract.pdf", open("contract.pdf", "rb"), "application/pdf"))]
|
| 433 |
+
data = {"schema": json.dumps(schema), "enable_reranker": "false"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
|
| 435 |
with httpx.Client(timeout=120.0) as client:
|
| 436 |
+
response = client.post("http://localhost:7860/v1/extract", files=files, data=data)
|
| 437 |
+
print(json.dumps(response.json(), indent=2))
|
|
|
|
| 438 |
```
|
| 439 |
|
| 440 |
+
Response (`200 OK`):
|
| 441 |
|
| 442 |
```json
|
| 443 |
{
|
| 444 |
"status": "completed",
|
| 445 |
+
"processing_time_ms": 910.5,
|
| 446 |
+
"total_items": 2,
|
| 447 |
+
"found_items": 2,
|
| 448 |
"results": [
|
| 449 |
{
|
| 450 |
+
"key": "monthly_rent", "found": true, "value": "25.000 TL", "confidence": 0.96,
|
| 451 |
+
"evidence": {"document": "contract.pdf", "page": 1,
|
| 452 |
+
"snippet": "Kira Bedeli: Aylık 25.000 TL olup her ayın 5. gününe kadar ödenecektir."},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
"thinking": null
|
| 454 |
},
|
| 455 |
{
|
| 456 |
+
"key": "tenant_name", "found": true, "value": "Tolga Arslan", "confidence": 0.95,
|
| 457 |
+
"evidence": {"document": "contract.pdf", "page": 1,
|
| 458 |
+
"snippet": "KİRACI: Tolga Arslan (T.C. Kimlik No: 12345678901)"},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 459 |
"thinking": null
|
| 460 |
}
|
| 461 |
]
|
| 462 |
}
|
| 463 |
```
|
| 464 |
|
|
|
|
|
|
|
| 465 |
### 2. Asynchronous Job Creation (`POST /v1/jobs`)
|
| 466 |
|
| 467 |
+
For large documents or batch workflows. Returns `202 Accepted` immediately with polling and SSE URLs.
|
|
|
|
|
|
|
| 468 |
|
| 469 |
```bash
|
| 470 |
curl -X POST "http://localhost:7860/v1/jobs" \
|
|
|
|
| 475 |
]'
|
| 476 |
```
|
| 477 |
|
|
|
|
|
|
|
| 478 |
```json
|
| 479 |
{
|
| 480 |
"job_id": "job_01jcb7x4e8rfb9q2",
|
|
|
|
| 485 |
}
|
| 486 |
```
|
| 487 |
|
|
|
|
|
|
|
| 488 |
### 3. Job Status Polling (`GET /v1/jobs/{job_id}`)
|
| 489 |
|
|
|
|
|
|
|
| 490 |
```bash
|
| 491 |
curl -X GET "http://localhost:7860/v1/jobs/job_01jcb7x4e8rfb9q2"
|
| 492 |
```
|
| 493 |
|
|
|
|
|
|
|
| 494 |
```json
|
| 495 |
{
|
| 496 |
"job_id": "job_01jcb7x4e8rfb9q2",
|
| 497 |
"status": "extracting",
|
| 498 |
+
"progress": {"current_step": "Extracting: total_revenue", "total_items": 2,
|
| 499 |
+
"completed_items": 1, "current_key": "total_revenue", "percent": 50.0},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
"created_at": 1730390400.125,
|
| 501 |
"completed_at": null,
|
| 502 |
"processing_time_ms": null,
|
| 503 |
"results": [
|
| 504 |
+
{"key": "net_profit", "found": true, "value": "$12.4M", "confidence": 0.95,
|
| 505 |
+
"evidence": {"document": "annual_report.pdf", "page": 4,
|
| 506 |
+
"snippet": "Net profit for the fiscal year reached $12.4M."},
|
| 507 |
+
"thinking": null}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
],
|
| 509 |
"response": null,
|
| 510 |
"error": null
|
| 511 |
}
|
| 512 |
```
|
| 513 |
|
|
|
|
|
|
|
| 514 |
### 4. Real-Time SSE Streaming (`GET /v1/jobs/{job_id}/events`)
|
| 515 |
|
|
|
|
|
|
|
| 516 |
```bash
|
| 517 |
curl -N "http://localhost:7860/v1/jobs/job_01jcb7x4e8rfb9q2/events"
|
| 518 |
```
|
| 519 |
|
|
|
|
|
|
|
| 520 |
```
|
| 521 |
+
event: status
|
| 522 |
+
data: {"status": "pending", "progress": {"current_step": "Queued in memory", "total_items": 2, "completed_items": 0, "current_key": null, "percent": 0.0}, "results": []}
|
| 523 |
+
|
| 524 |
event: progress
|
| 525 |
+
data: {"status": "parsing", "progress": {"current_step": "Parsing: annual_report.pdf (1240.2 KB)...", "total_items": 2, "completed_items": 0, "current_key": null, "percent": 15.0}}
|
| 526 |
|
| 527 |
event: progress
|
| 528 |
+
data: {"status": "extracting", "progress": {"current_step": "Extracting: total_revenue", "total_items": 2, "completed_items": 1, "current_key": "total_revenue", "percent": 60.0}}
|
| 529 |
|
| 530 |
event: item_extracted
|
| 531 |
+
data: {"key": "total_revenue", "found": true, "value": "$84.2M", "confidence": 0.96, "evidence": {"document": "annual_report.pdf", "page": 4, "snippet": "Consolidated total revenue reached $84.2M."}, "thinking": null}
|
| 532 |
|
| 533 |
event: completed
|
| 534 |
+
data: {"status": "completed", "processing_time_ms": 2840.0, "total_items": 2, "found_items": 2, "results": [{"key": "total_revenue", "found": true, "value": "$84.2M", "confidence": 0.96, "evidence": {"document": "annual_report.pdf", "page": 4, "snippet": "Consolidated total revenue reached $84.2M."}, "thinking": null}]}
|
| 535 |
```
|
| 536 |
|
| 537 |
+
Python consumer:
|
| 538 |
|
| 539 |
```python
|
| 540 |
+
import httpx, json
|
|
|
|
| 541 |
|
| 542 |
events_url = "http://localhost:7860/v1/jobs/job_01jcb7x4e8rfb9q2/events"
|
|
|
|
| 543 |
with httpx.Client(timeout=None) as client:
|
| 544 |
with client.stream("GET", events_url) as stream:
|
| 545 |
for line in stream.iter_lines():
|
| 546 |
if line.startswith("data: "):
|
| 547 |
+
print("Received SSE:", json.loads(line[6:]))
|
|
|
|
| 548 |
```
|
| 549 |
|
| 550 |
+
### 5. Health & Hardware Diagnostics (`GET /healthz`)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
|
| 552 |
+
Returns interpreter, GIL state, CUDA/GPU hardware, model readiness, job counts, and active configuration:
|
| 553 |
|
| 554 |
```json
|
| 555 |
{
|
|
|
|
| 557 |
"service": "DocNeedle",
|
| 558 |
"version": "0.1.0",
|
| 559 |
"uptime_seconds": 1284.5,
|
|
|
|
|
|
|
| 560 |
"free_threaded": true,
|
| 561 |
"gil_enabled": false,
|
| 562 |
+
"hardware": {"device": "cuda", "gpu_enabled": true, "torch_cuda": true},
|
| 563 |
+
"models": {"all_ready": true, "llm": {"ready": true}, "embedding": {"ready": true}, "reranker": {"ready": true}},
|
| 564 |
+
"jobs": {"active_jobs": 0, "total_cached_jobs": 2},
|
| 565 |
+
"config": {"llm_model": "Qwen3.5-4B-Q4_K_M", "embedding_model": "unsloth/embeddinggemma-2-GGUF", "gpu_enabled": true}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
}
|
| 567 |
```
|
| 568 |
|
|
|
|
| 570 |
|
| 571 |
## Configuration Reference
|
| 572 |
|
| 573 |
+
Settings load from `config.toml` and can be overridden by `.env` files or OS environment variables.
|
| 574 |
|
| 575 |
### Configuration File (`config.toml`)
|
| 576 |
|
|
|
|
| 581 |
debug = false
|
| 582 |
host = "0.0.0.0"
|
| 583 |
port = 8000
|
| 584 |
+
cors_origins = [
|
| 585 |
+
"http://localhost:3000",
|
| 586 |
+
"http://127.0.0.1:3000",
|
| 587 |
+
"http://localhost:5173",
|
| 588 |
+
"http://127.0.0.1:5173",
|
| 589 |
+
"https://docneedle.vercel.app",
|
| 590 |
+
"*"
|
| 591 |
+
]
|
| 592 |
|
| 593 |
[hardware]
|
| 594 |
+
gpu_enabled = true # CUDA GPU offload (auto-detected on ZeroGPU)
|
| 595 |
+
llm_n_gpu_layers = -1 # -1 = all layers on GPU; 0 = CPU
|
| 596 |
model_n_batch = 256 # Logical batch size for prompt evaluation
|
| 597 |
model_n_ubatch = 256 # Physical micro-batch size for GPU kernels
|
| 598 |
+
reranker_n_ctx = 2048 # Reranker context window
|
| 599 |
+
model_kv_cache_type_k = 1 # 1 = GGML_TYPE_F16 (stable FP16 KV cache)
|
| 600 |
+
model_kv_cache_type_v = 1
|
| 601 |
+
model_flash_attn = true # Flash Attention
|
| 602 |
|
| 603 |
[ingest]
|
| 604 |
max_upload_size_mb = 100
|
| 605 |
+
pdf_render_scale = 1.5 # 150 DPI page rendering for visual chunks
|
| 606 |
+
pdf_embedded_text_min_chars = 50 # Minimum text length to treat a PDF as digital
|
| 607 |
pdf_embedded_text_max_check_pages = 5
|
| 608 |
ingestion_cache_enabled = true
|
| 609 |
|
| 610 |
[chunker]
|
| 611 |
tokenizer_model = "Qwen/Qwen3-Reranker-0.6B"
|
| 612 |
max_tokens = 768
|
| 613 |
+
repeat_table_header = true # Repeat headers across table chunks
|
| 614 |
merge_peers = true
|
| 615 |
max_chunk_chars = 4000
|
| 616 |
min_split_chars = 200
|
| 617 |
overflow_factor = 1.25
|
| 618 |
|
| 619 |
[bm25]
|
| 620 |
+
k1 = 1.5 # Term frequency saturation
|
| 621 |
+
b = 0.75 # Length normalization
|
| 622 |
top_k = 10
|
| 623 |
|
| 624 |
[embedding]
|
|
|
|
| 630 |
doc_instruction = "title: {doc_name} | text: {text}"
|
| 631 |
|
| 632 |
[retrieval]
|
| 633 |
+
top_k = 10 # Candidates from RRF hybrid search
|
| 634 |
+
rrf_constant = 60
|
| 635 |
+
reranker_enabled = false # Qwen3 cross-encoder (off by default on CPU)
|
| 636 |
reranker_model = "Qwen/Qwen3-Reranker-0.6B"
|
| 637 |
reranker_candidate_k = 4
|
| 638 |
rerank_top_k = 3
|
| 639 |
+
max_chunks_per_document = 2 # Prevent single-document dominance
|
| 640 |
+
reranker_instruction = "Given a web search query, retrieve relevant passages that answer the query"
|
| 641 |
|
| 642 |
[llm]
|
| 643 |
model_name = "Qwen3.5-4B-Q4_K_M"
|
| 644 |
mmproj_name = "mmproj-Qwen3.5-4B-F16"
|
| 645 |
+
n_ctx = 32768 # 32k context window
|
| 646 |
+
temperature = 0.0 # Greedy decoding for deterministic extraction
|
| 647 |
top_p = 0.95
|
| 648 |
max_tokens = 4096
|
| 649 |
single_field_max_tokens = 128
|
| 650 |
thinking_max_tokens = 512
|
| 651 |
enable_thinking = false
|
| 652 |
+
log_extraction_payloads = false
|
| 653 |
+
stop_tokens = ["<|im_end|>", "<|endoftext|>", "</s>"]
|
| 654 |
+
speculative_enabled = false # Prompt lookup decoding
|
| 655 |
speculative_cpu_enabled = false
|
| 656 |
+
speculative_max_vocab_size = 65536
|
| 657 |
speculative_num_pred_tokens = 5
|
| 658 |
speculative_max_ngram_size = 2
|
| 659 |
|
|
|
|
| 667 |
model_storage_dir = "models"
|
| 668 |
|
| 669 |
[security]
|
| 670 |
+
max_schema_items = 50 # Target items per request
|
| 671 |
+
max_upload_files = 20 # Documents per batch
|
| 672 |
+
max_total_upload_size_mb = 100 # Batch payload limit
|
| 673 |
+
max_concurrent_jobs = 10 # Parallel background jobs
|
| 674 |
```
|
| 675 |
|
| 676 |
### Environment Variables
|
| 677 |
|
|
|
|
|
|
|
| 678 |
| Variable | Description | Default |
|
| 679 |
| :--- | :--- | :--- |
|
| 680 |
+
| `GPU_ENABLED` | Enable CUDA acceleration (`true`/`false`) | `true` |
|
| 681 |
+
| `LLM_N_GPU_LAYERS` | LLM layers offloaded to GPU (`-1` = all, `0` = CPU) | `-1` |
|
| 682 |
+
| `MODEL_STORAGE_DIR` | Path to downloaded GGUF models | `models` |
|
| 683 |
+
| `CONFIG_TOML` | Custom configuration file path | `config.toml` |
|
| 684 |
+
| `RERANKER_ENABLED` | Enable reranker by default | `false` |
|
| 685 |
+
| `HOST` | Bind interface | `0.0.0.0` |
|
| 686 |
+
| `PORT` | Listening port | `7860` (app.py) / `8000` (uvicorn) |
|
| 687 |
+
| `DEBUG` | Verbose debug logging | `false` |
|
| 688 |
+
| `SPACES_ZERO_GPU` | ZeroGPU leasing flag (auto-set by Hugging Face) | `None` |
|
| 689 |
|
| 690 |
---
|
| 691 |
|
| 692 |
+
## Available Scripts
|
|
|
|
|
|
|
| 693 |
|
| 694 |
| Command | Description |
|
| 695 |
| :--- | :--- |
|
| 696 |
+
| `uv run python app.py` | Unified Gradio UI + FastAPI on port `7860` |
|
| 697 |
+
| `uv run uvicorn docneedle.main:app --reload` | API-only dev server with hot reload (port `8000`) |
|
| 698 |
+
| `uv run python scripts/download_models.py [--embedding\|--llm\|--reranker]` | Download all models (~4.5 GB) or a single group |
|
| 699 |
+
| `uv run python scripts/benchmark_extractbench.py --split short` | Run the ExtractBench evaluation |
|
| 700 |
+
| `uv run pytest` | Full automated test suite |
|
| 701 |
+
| `uv run pytest tests/test_clean_modules.py tests/test_collision.py tests/test_acroform.py` | Fast unit tests (no model load) |
|
| 702 |
+
| `uv run pytest tests/test_health.py` | `/healthz` and route tests |
|
| 703 |
+
| `uv run ruff check . [--fix]` | Lint (optionally auto-fix) |
|
| 704 |
+
| `uv run ruff format .` | Format code (Python 3.14t profile) |
|
| 705 |
+
| `bash scripts/deploy_space.sh [SPACE_ID]` | Deploy to Hugging Face Spaces (ZeroGPU) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 706 |
|
| 707 |
---
|
| 708 |
|
| 709 |
## Testing
|
| 710 |
|
| 711 |
+
DocNeedle uses `pytest` and `pytest-asyncio` (`asyncio_mode = "auto"`).
|
|
|
|
|
|
|
| 712 |
|
| 713 |
```bash
|
| 714 |
+
# Fast unit tests (<6 s, no model weights)
|
| 715 |
uv run pytest tests/test_clean_modules.py tests/test_collision.py tests/test_acroform.py tests/test_health.py tests/test_ui_schema_sync.py
|
| 716 |
|
| 717 |
+
# Full end-to-end suite (requires model weights)
|
| 718 |
uv run pytest
|
| 719 |
```
|
| 720 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 721 |
> [!WARNING]
|
| 722 |
+
> While the dev server (`app.py`) runs, it holds ~7.1 GB of GPU VRAM. Running heavy end-to-end model tests concurrently causes CUDA OOM.
|
| 723 |
+
>
|
| 724 |
+
> **Recommendation:** Run lightweight unit tests while the server is active, or stop `app.py` before executing the full test suite.
|
| 725 |
|
| 726 |
---
|
| 727 |
|
| 728 |
## Production Deployment
|
| 729 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 730 |
### Hugging Face Spaces (ZeroGPU)
|
| 731 |
|
| 732 |
+
DocNeedle is designed for single-command deployment to Hugging Face **ZeroGPU** (NVIDIA A100 / A10G dynamic slices):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 733 |
|
| 734 |
```bash
|
|
|
|
| 735 |
hf auth login
|
|
|
|
|
|
|
| 736 |
bash scripts/deploy_space.sh your-hf-username/docneedle
|
| 737 |
```
|
| 738 |
|
| 739 |
+
The script automatically executes the following:
|
| 740 |
+
1. Validates or provisions a public ZeroGPU Gradio Space (`--flavor zero-a10g`).
|
| 741 |
+
2. Synchronizes application source code, configuration, and assets (excluding local environments and caches).
|
| 742 |
+
3. Triggers automated quantized model bootstrap on container cold-start.
|
| 743 |
+
4. Monitors build and deployment status until the Space reaches `RUNNING`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 744 |
|
| 745 |
---
|
| 746 |
|
| 747 |
## Troubleshooting & FAQs
|
| 748 |
|
| 749 |
+
| Symptom | Cause | Solution |
|
| 750 |
+
| :--- | :--- | :--- |
|
| 751 |
+
| `libGL.so.1: cannot open shared object file` | Missing OpenGL runtime in headless Linux | `sudo apt-get install -y libgl1 libglib2.0-0` |
|
| 752 |
+
| `FileNotFoundError: Missing required model: ...` | Weights not downloaded or wrong `MODEL_STORAGE_DIR` | `uv run python scripts/download_models.py`, or `export MODEL_STORAGE_DIR=/path/to/models` |
|
| 753 |
+
| CUDA Out of Memory | Context size or layer offload exceeds VRAM | Lower `llm_n_gpu_layers` (e.g. `16`–`20`); keep `model_kv_cache_type_k/v = 1`; set `reranker_enabled = false` |
|
| 754 |
+
| `Address already in use` (7860 / 8000) | Port held by another instance | `lsof -i :7860` then `kill -9 <PID>`, or `PORT=7861 uv run python app.py` |
|
| 755 |
+
| `libdocneedle_embed.so: cannot open shared object file` | Native library missing from `src/docneedle/retrieval/` | Verify the file exists; to rebuild: `cd src/docneedle/retrieval && g++ -O3 -shared -fPIC -std=c++17 docneedle_embed.cpp -o libdocneedle_embed.so -I../../../.venv/lib/python3.14/site-packages/include -L. -Wl,-rpath,'$ORIGIN' -lllama -lggml_llamacpp -lggml-base -lggml-cpu -lmtmd` |
|
| 756 |
+
| `ModuleNotFoundError: No module named 'docneedle'` | Package not installed or `src` not on `PYTHONPATH` | `uv pip install -e .` |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 757 |
|
| 758 |
---
|
| 759 |
|
| 760 |
## Contributing
|
| 761 |
|
| 762 |
+
Contributions are welcome. Please follow these standards:
|
| 763 |
|
| 764 |
+
1. **Fork and branch:** `git checkout -b feature/my-feature`.
|
| 765 |
+
2. **Strict no-fallback policy:** Maintain fail-fast behavior; do not introduce silent fallbacks, mock degradations, or fallback models.
|
| 766 |
+
3. **Privacy first:** Preserve the zero-disk persistence guarantee.
|
| 767 |
+
4. **Code quality:**
|
| 768 |
```bash
|
| 769 |
uv run ruff check .
|
| 770 |
uv run ruff format .
|
| 771 |
uv run pytest tests/test_clean_modules.py tests/test_collision.py tests/test_acroform.py
|
| 772 |
```
|
| 773 |
+
5. **Pull request:** Describe motivation, implementation details, and verification steps.
|
| 774 |
|
| 775 |
---
|
| 776 |
|
| 777 |
## License
|
| 778 |
|
| 779 |
DocNeedle is released under the **[Apache License 2.0](LICENSE)**.
|
| 780 |
+
You may use, modify, and distribute this software in commercial and non-commercial projects under the terms of the Apache 2.0 license.
|
app.py
CHANGED
|
@@ -2185,13 +2185,19 @@ if __name__ == "__main__":
|
|
| 2185 |
css=CUSTOM_CSS,
|
| 2186 |
ssr_mode=False,
|
| 2187 |
)
|
| 2188 |
-
server_app =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2189 |
if server_app is not None:
|
| 2190 |
server_app.include_router(extract_router)
|
| 2191 |
server_app.include_router(jobs_router)
|
| 2192 |
server_app.add_api_route("/healthz", health_check, methods=["GET"])
|
| 2193 |
server_app.add_api_route("/health", health_check, methods=["GET"])
|
| 2194 |
-
logger.info(
|
|
|
|
|
|
|
| 2195 |
demo.block_thread()
|
| 2196 |
else:
|
| 2197 |
# Mount Gradio dashboard onto root path for external ASGI runners (e.g. uvicorn app:app)
|
|
|
|
| 2185 |
css=CUSTOM_CSS,
|
| 2186 |
ssr_mode=False,
|
| 2187 |
)
|
| 2188 |
+
server_app = (
|
| 2189 |
+
res[0]
|
| 2190 |
+
if isinstance(res, tuple) and len(res) > 0
|
| 2191 |
+
else getattr(demo, "server_app", getattr(demo, "app", None))
|
| 2192 |
+
)
|
| 2193 |
if server_app is not None:
|
| 2194 |
server_app.include_router(extract_router)
|
| 2195 |
server_app.include_router(jobs_router)
|
| 2196 |
server_app.add_api_route("/healthz", health_check, methods=["GET"])
|
| 2197 |
server_app.add_api_route("/health", health_check, methods=["GET"])
|
| 2198 |
+
logger.info(
|
| 2199 |
+
"--> [STARTUP] FastAPI REST routes successfully mounted onto active Gradio server_app."
|
| 2200 |
+
)
|
| 2201 |
demo.block_thread()
|
| 2202 |
else:
|
| 2203 |
# Mount Gradio dashboard onto root path for external ASGI runners (e.g. uvicorn app:app)
|
benchmark_results/summary_all.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
| 1 |
{
|
| 2 |
"benchmark": "ExtractBench",
|
| 3 |
"split": "all",
|
| 4 |
-
"timestamp": "2026-11-
|
| 5 |
"total_documents": 370,
|
| 6 |
"total_fields": 13577,
|
| 7 |
-
"matched_fields":
|
| 8 |
-
"unified_value_f1": 0.
|
| 9 |
-
"value_precision": 0.
|
| 10 |
-
"value_recall": 0.
|
| 11 |
"perfect_documents": 10,
|
| 12 |
"perfect_document_rate": 0.027,
|
| 13 |
-
"strict_null_accuracy": 0.
|
| 14 |
-
"page_grounding_accuracy": 0.
|
| 15 |
-
"avg_latency_ms":
|
| 16 |
-
"total_benchmark_time_seconds":
|
| 17 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"benchmark": "ExtractBench",
|
| 3 |
"split": "all",
|
| 4 |
+
"timestamp": "2026-11-07T20:15:05.609512+00:00",
|
| 5 |
"total_documents": 370,
|
| 6 |
"total_fields": 13577,
|
| 7 |
+
"matched_fields": 10994,
|
| 8 |
+
"unified_value_f1": 0.7578,
|
| 9 |
+
"value_precision": 0.8104,
|
| 10 |
+
"value_recall": 0.7116,
|
| 11 |
"perfect_documents": 10,
|
| 12 |
"perfect_document_rate": 0.027,
|
| 13 |
+
"strict_null_accuracy": 0.8274,
|
| 14 |
+
"page_grounding_accuracy": 0.7882,
|
| 15 |
+
"avg_latency_ms": 46940.67,
|
| 16 |
+
"total_benchmark_time_seconds": 17368.05
|
| 17 |
}
|
benchmark_results/summary_long.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
{
|
| 2 |
"benchmark": "ExtractBench",
|
| 3 |
"split": "long",
|
| 4 |
-
"timestamp": "2026-11-
|
| 5 |
"total_documents": 20,
|
| 6 |
"total_fields": 93,
|
| 7 |
"matched_fields": 59,
|
|
@@ -12,6 +12,6 @@
|
|
| 12 |
"perfect_document_rate": 0.0,
|
| 13 |
"strict_null_accuracy": 0.2778,
|
| 14 |
"page_grounding_accuracy": 0.4558,
|
| 15 |
-
"avg_latency_ms":
|
| 16 |
-
"total_benchmark_time_seconds":
|
| 17 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"benchmark": "ExtractBench",
|
| 3 |
"split": "long",
|
| 4 |
+
"timestamp": "2026-11-07T20:52:32.332921+00:00",
|
| 5 |
"total_documents": 20,
|
| 6 |
"total_fields": 93,
|
| 7 |
"matched_fields": 59,
|
|
|
|
| 12 |
"perfect_document_rate": 0.0,
|
| 13 |
"strict_null_accuracy": 0.2778,
|
| 14 |
"page_grounding_accuracy": 0.4558,
|
| 15 |
+
"avg_latency_ms": 95962.12,
|
| 16 |
+
"total_benchmark_time_seconds": 1931.41
|
| 17 |
}
|
benchmark_results/summary_medium.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"benchmark": "ExtractBench",
|
| 3 |
+
"split": "medium",
|
| 4 |
+
"timestamp": "2026-11-08T18:45:35.622471+00:00",
|
| 5 |
+
"total_documents": 98,
|
| 6 |
+
"total_fields": 2808,
|
| 7 |
+
"matched_fields": 2159,
|
| 8 |
+
"unified_value_f1": 0.6953,
|
| 9 |
+
"value_precision": 0.7955,
|
| 10 |
+
"value_recall": 0.6175,
|
| 11 |
+
"perfect_documents": 1,
|
| 12 |
+
"perfect_document_rate": 0.0102,
|
| 13 |
+
"strict_null_accuracy": 0.849,
|
| 14 |
+
"page_grounding_accuracy": 0.5503,
|
| 15 |
+
"avg_latency_ms": 67845.57,
|
| 16 |
+
"total_benchmark_time_seconds": 6648.87
|
| 17 |
+
}
|
benchmark_results/summary_short.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"benchmark": "ExtractBench",
|
| 3 |
+
"split": "short",
|
| 4 |
+
"timestamp": "2026-11-08T21:31:44.304927+00:00",
|
| 5 |
+
"total_documents": 252,
|
| 6 |
+
"total_fields": 10676,
|
| 7 |
+
"matched_fields": 8776,
|
| 8 |
+
"unified_value_f1": 0.773,
|
| 9 |
+
"value_precision": 0.8137,
|
| 10 |
+
"value_recall": 0.7362,
|
| 11 |
+
"perfect_documents": 9,
|
| 12 |
+
"perfect_document_rate": 0.0357,
|
| 13 |
+
"strict_null_accuracy": 0.8234,
|
| 14 |
+
"page_grounding_accuracy": 0.907,
|
| 15 |
+
"avg_latency_ms": 34714.96,
|
| 16 |
+
"total_benchmark_time_seconds": 9038.26
|
| 17 |
+
}
|
pyproject.toml
CHANGED
|
@@ -3,6 +3,7 @@ name = "docneedle"
|
|
| 3 |
version = "0.1.0"
|
| 4 |
description = "Privacy-first local RAG document extraction microservice"
|
| 5 |
readme = "README.md"
|
|
|
|
| 6 |
requires-python = ">=3.14"
|
| 7 |
dependencies = [
|
| 8 |
"fastapi>=0.115.0",
|
|
|
|
| 3 |
version = "0.1.0"
|
| 4 |
description = "Privacy-first local RAG document extraction microservice"
|
| 5 |
readme = "README.md"
|
| 6 |
+
license = { text = "Apache-2.0" }
|
| 7 |
requires-python = ">=3.14"
|
| 8 |
dependencies = [
|
| 9 |
"fastapi>=0.115.0",
|
scripts/benchmark_extractbench.py
CHANGED
|
@@ -1015,6 +1015,8 @@ async def run_benchmark(
|
|
| 1015 |
)
|
| 1016 |
records = [r for r in records if r.get("id") not in already_evaluated_ids]
|
| 1017 |
|
|
|
|
|
|
|
| 1018 |
start_time = time.perf_counter()
|
| 1019 |
|
| 1020 |
# Setup progress bar
|
|
@@ -1030,7 +1032,11 @@ async def run_benchmark(
|
|
| 1030 |
)
|
| 1031 |
|
| 1032 |
with progress:
|
| 1033 |
-
task_id = progress.add_task(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1034 |
|
| 1035 |
for idx, row in enumerate(records, 1):
|
| 1036 |
doc_id = row["id"]
|
|
@@ -1039,7 +1045,15 @@ async def run_benchmark(
|
|
| 1039 |
expected_output = json.loads(row["expected_output"])
|
| 1040 |
field_rules = json.loads(row["field_rules"])
|
| 1041 |
|
| 1042 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1043 |
|
| 1044 |
try:
|
| 1045 |
# 1. Ensure PDF is available locally
|
|
@@ -1105,7 +1119,10 @@ async def run_benchmark(
|
|
| 1105 |
|
| 1106 |
progress.advance(task_id)
|
| 1107 |
|
| 1108 |
-
|
|
|
|
|
|
|
|
|
|
| 1109 |
|
| 1110 |
# ---------------------------------------------------------------------------
|
| 1111 |
# Aggregate Metrics Calculation & Final Reporting
|
|
|
|
| 1015 |
)
|
| 1016 |
records = [r for r in records if r.get("id") not in already_evaluated_ids]
|
| 1017 |
|
| 1018 |
+
resumed_count = len(already_evaluated_ids)
|
| 1019 |
+
remaining_count = len(records)
|
| 1020 |
start_time = time.perf_counter()
|
| 1021 |
|
| 1022 |
# Setup progress bar
|
|
|
|
| 1032 |
)
|
| 1033 |
|
| 1034 |
with progress:
|
| 1035 |
+
task_id = progress.add_task(
|
| 1036 |
+
"[cyan]Evaluating documents...",
|
| 1037 |
+
total=total_docs,
|
| 1038 |
+
completed=resumed_count,
|
| 1039 |
+
)
|
| 1040 |
|
| 1041 |
for idx, row in enumerate(records, 1):
|
| 1042 |
doc_id = row["id"]
|
|
|
|
| 1045 |
expected_output = json.loads(row["expected_output"])
|
| 1046 |
field_rules = json.loads(row["field_rules"])
|
| 1047 |
|
| 1048 |
+
curr_global = resumed_count + idx
|
| 1049 |
+
num_fields = len(schema_dict.get("properties", {}))
|
| 1050 |
+
progress.update(
|
| 1051 |
+
task_id,
|
| 1052 |
+
description=(
|
| 1053 |
+
f"[cyan]Doc {curr_global}/{total_docs}: {doc_id} "
|
| 1054 |
+
f"[dim]({idx}/{remaining_count} kalan, {num_fields} alan)[/dim]"
|
| 1055 |
+
),
|
| 1056 |
+
)
|
| 1057 |
|
| 1058 |
try:
|
| 1059 |
# 1. Ensure PDF is available locally
|
|
|
|
| 1119 |
|
| 1120 |
progress.advance(task_id)
|
| 1121 |
|
| 1122 |
+
if resumed_count > 0 and evaluations:
|
| 1123 |
+
total_duration = sum(e.latency_ms for e in evaluations) / 1000.0
|
| 1124 |
+
else:
|
| 1125 |
+
total_duration = time.perf_counter() - start_time
|
| 1126 |
|
| 1127 |
# ---------------------------------------------------------------------------
|
| 1128 |
# Aggregate Metrics Calculation & Final Reporting
|
scripts/deploy_space.sh
CHANGED
|
@@ -17,6 +17,37 @@ fi
|
|
| 17 |
|
| 18 |
echo "==> Deploying project files to $SPACE_ID..."
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
hf upload "$SPACE_ID" . . --repo-type space \
|
| 21 |
--exclude ".git/**" \
|
| 22 |
--exclude ".venv/**" \
|
|
@@ -29,10 +60,14 @@ hf upload "$SPACE_ID" . . --repo-type space \
|
|
| 29 |
--exclude "*.pyc" \
|
| 30 |
--exclude ".python-version" \
|
| 31 |
--exclude "**/.fuse_hidden*" \
|
|
|
|
| 32 |
--delete "src/docneedle/ingest/ocr_engine.py" \
|
| 33 |
--delete "src/docneedle/bin/*" \
|
| 34 |
--commit-message "$COMMIT_MSG"
|
| 35 |
|
|
|
|
|
|
|
|
|
|
| 36 |
echo "==> Upload finished. Waiting for Space to build and reach RUNNING status..."
|
| 37 |
hf spaces wait "$SPACE_ID" --timeout 5m
|
| 38 |
echo "==> Successfully deployed! Space is live at: https://huggingface.co/spaces/$SPACE_ID"
|
|
|
|
| 17 |
|
| 18 |
echo "==> Deploying project files to $SPACE_ID..."
|
| 19 |
|
| 20 |
+
README_FILE="README.md"
|
| 21 |
+
README_BAK="${README_FILE}.hf_bak"
|
| 22 |
+
|
| 23 |
+
restore_readme() {
|
| 24 |
+
if [ -f "$README_BAK" ]; then
|
| 25 |
+
echo "==> Restoring clean GitHub README.md..."
|
| 26 |
+
mv -f "$README_BAK" "$README_FILE"
|
| 27 |
+
fi
|
| 28 |
+
}
|
| 29 |
+
trap restore_readme EXIT INT TERM
|
| 30 |
+
|
| 31 |
+
echo "==> Preparing Hugging Face Spaces YAML frontmatter..."
|
| 32 |
+
cp -p "$README_FILE" "$README_BAK"
|
| 33 |
+
|
| 34 |
+
cat << 'EOF' > "$README_FILE"
|
| 35 |
+
---
|
| 36 |
+
title: DocNeedle
|
| 37 |
+
emoji: 📑
|
| 38 |
+
colorFrom: blue
|
| 39 |
+
colorTo: indigo
|
| 40 |
+
sdk: gradio
|
| 41 |
+
sdk_version: 6.0.0
|
| 42 |
+
python_version: 3.14
|
| 43 |
+
app_file: app.py
|
| 44 |
+
pinned: false
|
| 45 |
+
license: apache-2.0
|
| 46 |
+
---
|
| 47 |
+
|
| 48 |
+
EOF
|
| 49 |
+
cat "$README_BAK" >> "$README_FILE"
|
| 50 |
+
|
| 51 |
hf upload "$SPACE_ID" . . --repo-type space \
|
| 52 |
--exclude ".git/**" \
|
| 53 |
--exclude ".venv/**" \
|
|
|
|
| 60 |
--exclude "*.pyc" \
|
| 61 |
--exclude ".python-version" \
|
| 62 |
--exclude "**/.fuse_hidden*" \
|
| 63 |
+
--exclude "README.md.hf_bak" \
|
| 64 |
--delete "src/docneedle/ingest/ocr_engine.py" \
|
| 65 |
--delete "src/docneedle/bin/*" \
|
| 66 |
--commit-message "$COMMIT_MSG"
|
| 67 |
|
| 68 |
+
restore_readme
|
| 69 |
+
trap - EXIT INT TERM
|
| 70 |
+
|
| 71 |
echo "==> Upload finished. Waiting for Space to build and reach RUNNING status..."
|
| 72 |
hf spaces wait "$SPACE_ID" --timeout 5m
|
| 73 |
echo "==> Successfully deployed! Space is live at: https://huggingface.co/spaces/$SPACE_ID"
|
src/docneedle/extraction/service.py
CHANGED
|
@@ -395,8 +395,7 @@ class ExtractionService:
|
|
| 395 |
matches = item_matches.get(item.key, [])
|
| 396 |
if not matches and sorted_batch_chunks:
|
| 397 |
matches = [
|
| 398 |
-
SearchResult(chunk=c, score=1.0)
|
| 399 |
-
for c in sorted_batch_chunks[:k]
|
| 400 |
]
|
| 401 |
is_cover = bool(
|
| 402 |
_COVER_PAGE_PATTERN.search(item.description or "")
|
|
|
|
| 395 |
matches = item_matches.get(item.key, [])
|
| 396 |
if not matches and sorted_batch_chunks:
|
| 397 |
matches = [
|
| 398 |
+
SearchResult(chunk=c, score=1.0) for c in sorted_batch_chunks[:k]
|
|
|
|
| 399 |
]
|
| 400 |
is_cover = bool(
|
| 401 |
_COVER_PAGE_PATTERN.search(item.description or "")
|
src/docneedle/llm/local_engine.py
CHANGED
|
@@ -428,9 +428,7 @@ class LocalLLMEngine:
|
|
| 428 |
wrapper_tokens = len(self.llm.tokenize(wrapper_no_ctx.encode("utf-8")))
|
| 429 |
max_ctx_budget = max(
|
| 430 |
256,
|
| 431 |
-
max_prompt_ceiling
|
| 432 |
-
- wrapper_tokens
|
| 433 |
-
- total_image_tokens,
|
| 434 |
)
|
| 435 |
|
| 436 |
ctx_tokens = self.llm.tokenize(clean_context.encode("utf-8"))
|
|
|
|
| 428 |
wrapper_tokens = len(self.llm.tokenize(wrapper_no_ctx.encode("utf-8")))
|
| 429 |
max_ctx_budget = max(
|
| 430 |
256,
|
| 431 |
+
max_prompt_ceiling - wrapper_tokens - total_image_tokens,
|
|
|
|
|
|
|
| 432 |
)
|
| 433 |
|
| 434 |
ctx_tokens = self.llm.tokenize(clean_context.encode("utf-8"))
|
src/docneedle/retrieval/docneedle_embed.cpp
CHANGED
|
@@ -43,30 +43,6 @@ static void normalize_l2(float * vec, int dim) {
|
|
| 43 |
}
|
| 44 |
}
|
| 45 |
|
| 46 |
-
// Binary ABI struct matching libllama.so layout without the 8-byte lazy_mode shift
|
| 47 |
-
// present in newer llama.h headers. This prevents tensor_split / progress_callback
|
| 48 |
-
// pointer corruption during llama_model_load_from_file.
|
| 49 |
-
struct libllama_model_params {
|
| 50 |
-
void * devices;
|
| 51 |
-
void * tensor_buft_overrides;
|
| 52 |
-
int32_t n_gpu_layers;
|
| 53 |
-
int32_t split_mode;
|
| 54 |
-
int32_t main_gpu;
|
| 55 |
-
int32_t load_mode;
|
| 56 |
-
const float * tensor_split;
|
| 57 |
-
void * progress_callback;
|
| 58 |
-
void * progress_callback_user_data;
|
| 59 |
-
void * kv_overrides;
|
| 60 |
-
bool vocab_only;
|
| 61 |
-
bool use_mmap;
|
| 62 |
-
bool use_mlock;
|
| 63 |
-
bool check_tensors;
|
| 64 |
-
char pad[12];
|
| 65 |
-
};
|
| 66 |
-
|
| 67 |
-
typedef struct libllama_model_params (*model_default_params_fn_t)();
|
| 68 |
-
typedef llama_model * (*model_load_from_file_fn_t)(const char *, struct libllama_model_params);
|
| 69 |
-
|
| 70 |
extern "C" {
|
| 71 |
|
| 72 |
void * docneedle_embed_init(
|
|
@@ -78,19 +54,23 @@ void * docneedle_embed_init(
|
|
| 78 |
) {
|
| 79 |
llama_backend_init();
|
| 80 |
|
| 81 |
-
|
| 82 |
-
auto load_from_file_fn = (model_load_from_file_fn_t)dlsym(RTLD_DEFAULT, "llama_model_load_from_file");
|
| 83 |
-
|
| 84 |
-
if (!default_params_fn || !load_from_file_fn) {
|
| 85 |
-
return nullptr;
|
| 86 |
-
}
|
| 87 |
-
|
| 88 |
-
struct libllama_model_params mparams = default_params_fn();
|
| 89 |
mparams.n_gpu_layers = n_gpu_layers;
|
| 90 |
mparams.progress_callback = nullptr;
|
| 91 |
mparams.progress_callback_user_data = nullptr;
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
if (!model) {
|
| 95 |
return nullptr;
|
| 96 |
}
|
|
|
|
| 43 |
}
|
| 44 |
}
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
extern "C" {
|
| 47 |
|
| 48 |
void * docneedle_embed_init(
|
|
|
|
| 54 |
) {
|
| 55 |
llama_backend_init();
|
| 56 |
|
| 57 |
+
llama_model_params mparams = llama_model_default_params();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
mparams.n_gpu_layers = n_gpu_layers;
|
| 59 |
mparams.progress_callback = nullptr;
|
| 60 |
mparams.progress_callback_user_data = nullptr;
|
| 61 |
|
| 62 |
+
ggml_backend_dev_t cpu_dev = nullptr;
|
| 63 |
+
ggml_backend_dev_t devs[2] = { nullptr, nullptr };
|
| 64 |
+
if (n_gpu_layers == 0) {
|
| 65 |
+
cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
|
| 66 |
+
if (cpu_dev) {
|
| 67 |
+
devs[0] = cpu_dev;
|
| 68 |
+
mparams.devices = devs;
|
| 69 |
+
}
|
| 70 |
+
mparams.use_extra_bufts = false;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
llama_model * model = llama_model_load_from_file(model_path, mparams);
|
| 74 |
if (!model) {
|
| 75 |
return nullptr;
|
| 76 |
}
|
src/docneedle/retrieval/libdocneedle_embed.so
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7c6dd692fbd39368126fd820269cde101f1d6fecfdace497e5de447c148cb3c9
|
| 3 |
+
size 26656
|