multimodalart HF Staff commited on
Commit
6426e97
·
verified ·
1 Parent(s): a521435

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/chinese_essay.png filter=lfs diff=lfs merge=lfs -text
37
+ examples/multi_column.png filter=lfs diff=lfs merge=lfs -text
38
+ examples/rotated_letter.png filter=lfs diff=lfs merge=lfs -text
39
+ examples/table_pmc.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,45 @@
1
  ---
2
- title: Indra Ocr
3
- emoji: 📊
4
- colorFrom: pink
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.30.0
8
- python_version: '3.13'
9
  app_file: app.py
10
- pinned: false
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Indra OCR
3
+ emoji: 📄
4
+ colorFrom: gray
5
+ colorTo: green
6
  sdk: gradio
7
  sdk_version: 6.30.0
 
8
  app_file: app.py
9
+ short_description: 1M-param ONNX OCR that turns PDFs and images into markdown
10
+ python_version: "3.12"
11
  ---
12
 
13
+ # Indra OCR
14
+
15
+ A demo of **[datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr)**, a 1M-parameter ONNX OCR
16
+ model that turns PDFs and images into markdown, plain text, or JSON — with a bounding box for every text
17
+ line and every layout block (headings, lists, tables, captions, footnotes...), in reading order. It runs
18
+ entirely on CPU (about 18 MB of ONNX models, no PyTorch), reading up to 49 pages per second.
19
+
20
+ - Digital PDFs go through their own text layer where it passes Indra's checks (any script); scans and
21
+ images go through the OCR models (Latin, Cyrillic, Greek, Devanagari, Bengali, and Chinese).
22
+ - Pages turned upside down or sideways are turned upright first, and small skew is straightened.
23
+ - The preview shows the detected layout: faint blue boxes are text lines, colored labeled boxes are
24
+ layout blocks.
25
+
26
+ ## Examples
27
+
28
+ The example pages are the OmniParseBench pages the model card itself showcases (`rotated_letter`,
29
+ `table_pmc`, `multi_column`, `chinese_essay`). The pages come from
30
+ [OmniParseBench](https://github.com/datalab-to/omni_parse_bench):
31
+
32
+ - `multi_column.png` and `rotated_letter.png` derive from [olmOCR-bench](https://huggingface.co/datasets/allenai/olmOCR-bench)
33
+ (Allen Institute for AI), used under the Open Data Commons Attribution License v1.0 (ODC-BY 1.0).
34
+ Credit: Poznanski J. et al. (2025). olmOCR: Unlocking Trillions of Tokens in PDFs with Vision Language
35
+ Models. arXiv:2502.18443.
36
+ - `table_pmc.png` is a PubMed Central page (OmniParseBench `tables_derived`, `pmc-LICENSE.txt`).
37
+ - `chinese_essay.png` comes from [FinePDFs](https://huggingface.co/datasets/HuggingFaceFW/finepdfs)
38
+ (OmniParseBench `multiling_finepdfs`), used under ODC-BY 1.0.
39
+
40
+ ## License
41
+
42
+ The `indra-ocr` code is Apache-2.0. The model weights use a modified OpenRAIL-M license — free for
43
+ research, personal use, and startups under $20M funding/revenue; see the
44
+ [model card](https://huggingface.co/datalab-to/indra-ocr) for the terms and Datalab's pricing page for
45
+ broader commercial licensing.
app.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio demo for Indra OCR (datalab-to/indra-ocr).
2
+
3
+ A 1M-parameter ONNX OCR model that turns PDFs and images into markdown, plain
4
+ text, or JSON — with a bounding box for every line and every layout block, and
5
+ reading order — entirely on CPU.
6
+ """
7
+
8
+ import json
9
+ import threading
10
+ import time
11
+ from pathlib import Path
12
+
13
+ import gradio as gr
14
+ import indra_ocr
15
+ from indra_ocr.document import MAX_PAGE_PIXELS
16
+ from PIL import Image, ImageDraw
17
+
18
+ CSS = """
19
+ #col-container { max-width: 1280px; margin: 0 auto; }
20
+ .dark .gradio-container { color: var(--body-text-color); }
21
+ """
22
+
23
+ TAG_COLORS = {
24
+ "Text": (9, 105, 218), # blue
25
+ "Section-Header": (221, 74, 104), # red
26
+ "Page-Header": (160, 160, 160), # gray
27
+ "Page-Footer": (160, 160, 160), # gray
28
+ "List-Group": (63, 185, 80), # green
29
+ "Table": (255, 140, 26), # orange
30
+ "Caption": (188, 141, 224), # purple
31
+ "Footnote": (130, 170, 255), # light blue
32
+ "Table-Of-Contents": (255, 214, 10), # yellow
33
+ "Form": (46, 160, 170), # teal
34
+ }
35
+
36
+ MAX_PAGES = 5 # demo cap: fine for a look; the library reads whole files too
37
+
38
+ _converters = {}
39
+ _lock = threading.Lock()
40
+
41
+
42
+ def _converter(mode: str, furniture: bool):
43
+ """One Converter per (mode, furniture) combination, built once and reused."""
44
+ key = (mode, furniture)
45
+ with _lock:
46
+ if key not in _converters:
47
+ _converters[key] = indra_ocr.load(
48
+ threads=4, mode=mode, furniture=furniture
49
+ )
50
+ return _converters[key]
51
+
52
+
53
+ print("[indra] loading models (first boot downloads ~18 MB from datalab-to/indra-ocr)...")
54
+ _t0 = time.perf_counter()
55
+ _converter("auto", False) # eager: the default pipeline is ready before the UI
56
+ print(f"[indra] models ready in {time.perf_counter() - _t0:.1f}s")
57
+
58
+
59
+ def _is_pdf(path: str) -> bool:
60
+ try:
61
+ with open(path, "rb") as f:
62
+ return b"%PDF-" in f.read(1024)
63
+ except OSError:
64
+ return False
65
+
66
+
67
+ def _pdf_page_scale(dpi: float, page) -> float:
68
+ """The same render scale Indra's Converter uses (dpi, lowered for huge pages)."""
69
+ w, h = page.get_size()
70
+ k = dpi / 72.0
71
+ return min(k, (MAX_PAGE_PIXELS / max(w * h, 1.0)) ** 0.5)
72
+
73
+
74
+ def _rotate(img: Image.Image, degrees_ccw: int) -> Image.Image:
75
+ if degrees_ccw % 360 == 0:
76
+ return img
77
+ turns = {90: Image.Transpose.ROTATE_270, 180: Image.Transpose.ROTATE_180}
78
+ turns[270] = Image.Transpose.ROTATE_90
79
+ key = degrees_ccw % 360
80
+ return img.transpose(turns[key]) if key in turns else img
81
+
82
+
83
+ def _draw_preview(img: Image.Image, page) -> Image.Image:
84
+ """Page rendered upright with layout blocks (colored, labeled) and lines."""
85
+ img = _rotate(img, page.rotation)
86
+ draw = ImageDraw.Draw(img)
87
+ for ln in page.lines: # faint blue boxes: every detected line
88
+ draw.rectangle(ln.box, outline=(185, 210, 255), width=2)
89
+ for b in page.blocks: # colored boxes with labels: layout blocks
90
+ color = TAG_COLORS.get(b["label"], (110, 110, 110))
91
+ box = b["bbox"]
92
+ draw.rectangle(box, outline=color, width=4)
93
+ label = f" {b['label']} "
94
+ lx, ly = box[0], max(0.0, box[1] - 18)
95
+ tw = draw.textlength(label)
96
+ draw.rectangle((lx, ly, lx + tw, ly + 17), fill=color)
97
+ draw.text((lx, ly + 1), label, fill=(255, 255, 255))
98
+ return img
99
+
100
+
101
+ def _page_dict(page) -> dict:
102
+ """A Page in the same shape as the CLI's `--format json` output."""
103
+ return {
104
+ "markdown": page.markdown,
105
+ "text": page.text,
106
+ "source": page.source,
107
+ "rotation": page.rotation,
108
+ "skew": round(page.skew, 2),
109
+ "note": page.note,
110
+ "timings": {k: round(v, 1) for k, v in page.timings.items()},
111
+ "lines": [
112
+ {"box": [round(c, 1) for c in ln.box], "text": ln.text,
113
+ "conf": round(ln.conf, 3)}
114
+ for ln in page.lines
115
+ ],
116
+ "blocks": [
117
+ {"label": b["label"], "bbox": [round(c, 1) for c in b["bbox"]],
118
+ "text": b["text"]}
119
+ for b in page.blocks
120
+ ],
121
+ }
122
+
123
+
124
+ def _status_line(i: int, page) -> str:
125
+ bits = [f"page {i}", f"source: {page.source}",
126
+ f"{round(page.timings.get('total_ms', 0))} ms",
127
+ f"{len(page.lines)} lines · {len(page.blocks)} blocks"]
128
+ if page.rotation:
129
+ bits.append(f"turned {page.rotation}°")
130
+ if page.skew:
131
+ bits.append(f"deskewed {page.skew:.1f}°")
132
+ if page.note:
133
+ bits.append(f"({page.note})")
134
+ return " · ".join(bits)
135
+
136
+
137
+ def convert_file(
138
+ file_path: str,
139
+ mode: str = "auto",
140
+ output_format: str = "markdown",
141
+ dpi: float = 200.0,
142
+ keep_furniture: bool = False,
143
+ draw_boxes: bool = True,
144
+ ):
145
+ """Read a PDF or image document: markdown / plain text / JSON, with layout.
146
+
147
+ Indra OCR detects every text line and every layout block (headings, lists,
148
+ tables, captions, footnotes...), orders them for reading, and writes the
149
+ page as markdown. Digital PDFs are read through their own text layer where
150
+ it passes Indra's checks; scans and images go through the OCR models.
151
+
152
+ Args:
153
+ file_path: the uploaded PDF or image file.
154
+ mode: "auto" reads the PDF text layer where it passes the checks and
155
+ OCRs the rest; "ocr" always OCRs; "text" trusts the text layer.
156
+ output_format: "markdown", "plain text", or "json" (lines, boxes,
157
+ layout blocks, confidences, timings).
158
+ dpi: render resolution for PDFs.
159
+ keep_furniture: keep page headers and footers in the output.
160
+ draw_boxes: overlay layout blocks and line boxes on the page preview.
161
+ """
162
+ if not file_path:
163
+ raise gr.Error("Please upload a PDF or image file first.")
164
+ conv = _converter(mode, bool(keep_furniture))
165
+
166
+ try:
167
+ pages = list(conv.convert(file_path, max_pages=MAX_PAGES))
168
+ except indra_ocr.InputError as e:
169
+ raise gr.Error(str(e))
170
+ if not pages:
171
+ raise gr.Error("No pages could be read from that file.")
172
+
173
+ # ---- preview of page 0, drawn from the page's own boxes -------------
174
+ first_i, first_page = pages[0]
175
+ if _is_pdf(file_path):
176
+ import pypdfium2 as pdfium
177
+
178
+ doc = pdfium.PdfDocument(file_path)
179
+ try:
180
+ pg = doc[first_i]
181
+ preview = pg.render(
182
+ scale=_pdf_page_scale(dpi, pg), grayscale=False
183
+ ).to_pil()
184
+ finally:
185
+ doc.close()
186
+ else:
187
+ preview = Image.open(file_path).convert("RGB")
188
+ if draw_boxes:
189
+ preview = _draw_preview(preview, first_page)
190
+
191
+ # ---- result in the chosen format -----------------------------------
192
+ if output_format == "json":
193
+ result = json.dumps(
194
+ {"pages": [_page_dict(p) for _, p in pages]}, ensure_ascii=False, indent=1
195
+ )
196
+ elif output_format == "plain text":
197
+ result = "\n\n".join(p.text for _, p in pages)
198
+ else:
199
+ result = "\n\n---\n\n".join(p.markdown or "" for _, p in pages)
200
+
201
+ rendered = "\n\n---\n\n".join(p.markdown or "" for _, p in pages)
202
+ status = "\n".join(_status_line(i, p) for i, p in pages)
203
+ if len(pages) >= MAX_PAGES:
204
+ status += f"\n(first {MAX_PAGES} pages only — the library reads whole files)"
205
+
206
+ return preview, result, rendered, status
207
+
208
+
209
+ with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo:
210
+ gr.Markdown(
211
+ """
212
+ # 📄 Indra OCR
213
+ **[datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr)** — a 1M-parameter ONNX OCR model that reads PDFs and images
214
+ and turns them into **markdown**, plain text, or **JSON with layout blocks and line boxes** — all on CPU, at up to 49 pages per second.
215
+
216
+ Drop in a document below, or click one of the example pages.
217
+ [Model card](https://huggingface.co/datalab-to/indra-ocr) · [code](https://github.com/datalab-to/indra) (Apache-2.0; weights under a modified OpenRAIL-M license)
218
+ """
219
+ )
220
+
221
+ with gr.Row():
222
+ with gr.Column(scale=5):
223
+ file_in = gr.File(
224
+ label="PDF or image",
225
+ file_types=[".pdf", ".png", ".jpg", ".jpeg", ".webp", ".bmp",
226
+ ".tif", ".tiff"],
227
+ type="filepath",
228
+ )
229
+ run_btn = gr.Button("Convert", variant="primary")
230
+ with gr.Accordion("Advanced settings", open=False):
231
+ mode = gr.Radio(
232
+ ["auto", "ocr", "text"],
233
+ value="auto",
234
+ label="Page reading mode",
235
+ info="auto: PDF text layer where it passes the checks, OCR the rest · ocr: never read the text layer · text: trust the text layer",
236
+ )
237
+ output_format = gr.Radio(
238
+ ["markdown", "plain text", "json"],
239
+ value="markdown",
240
+ label="Output format",
241
+ )
242
+ dpi = gr.Slider(100, 300, value=200, step=10, label="PDF render DPI")
243
+ keep_furniture = gr.Checkbox(
244
+ value=False, label="Keep page headers and footers (furniture)"
245
+ )
246
+ draw_boxes = gr.Checkbox(
247
+ value=True,
248
+ label="Draw layout blocks and line boxes on the preview",
249
+ )
250
+ with gr.Column(scale=4):
251
+ page_preview = gr.Image(
252
+ label="Detected layout (faint blue: lines · colored: blocks)",
253
+ type="pil",
254
+ interactive=False,
255
+ )
256
+
257
+ with gr.Tabs():
258
+ with gr.Tab("Raw output"):
259
+ result_out = gr.Textbox(
260
+ label="Result",
261
+ lines=20,
262
+ max_lines=45,
263
+ show_copy_button=True,
264
+ text_align="left",
265
+ )
266
+ with gr.Tab("Rendered markdown"):
267
+ rendered_out = gr.Markdown(label="Rendered markdown", value="")
268
+ status_out = gr.Textbox(
269
+ label="Per-page status and timing", lines=4, interactive=False
270
+ )
271
+
272
+ run_btn.click(
273
+ convert_file,
274
+ inputs=[file_in, mode, output_format, dpi, keep_furniture, draw_boxes],
275
+ outputs=[page_preview, result_out, rendered_out, status_out],
276
+ api_name="convert",
277
+ concurrency_limit=1,
278
+ )
279
+ file_in.upload(
280
+ convert_file,
281
+ inputs=[file_in, mode, output_format, dpi, keep_furniture, draw_boxes],
282
+ outputs=[page_preview, result_out, rendered_out, status_out],
283
+ api_name="convert_upload",
284
+ concurrency_limit=1,
285
+ )
286
+
287
+ gr.Examples(
288
+ examples=[
289
+ ["examples/table_pmc.png"],
290
+ ["examples/multi_column.png"],
291
+ ["examples/chinese_essay.png"],
292
+ ["examples/rotated_letter.png"],
293
+ ],
294
+ inputs=[file_in],
295
+ fn=convert_file,
296
+ outputs=[page_preview, result_out, rendered_out, status_out],
297
+ cache_examples=True,
298
+ cache_mode="lazy",
299
+ label="Example documents (the OmniParseBench pages used in the model card)",
300
+ )
301
+
302
+ demo.launch(mcp_server=True)
examples/chinese_essay.png ADDED

Git LFS Details

  • SHA256: 45426e6ac7e56581e1135f780d60a11328f96e411568c80544052bf728fdd07b
  • Pointer size: 131 Bytes
  • Size of remote file: 525 kB
examples/multi_column.png ADDED

Git LFS Details

  • SHA256: c9f80ee321b48685e63024ca0649e8977daf93f07bb0fd38818541edf9ab58b3
  • Pointer size: 131 Bytes
  • Size of remote file: 961 kB
examples/rotated_letter.png ADDED

Git LFS Details

  • SHA256: bfb42c69e9950e123aef7bf879ced11d2f6a70d88bfd79e629f9f37b2e6c918f
  • Pointer size: 131 Bytes
  • Size of remote file: 699 kB
examples/table_pmc.png ADDED

Git LFS Details

  • SHA256: f8b89bdcc25fb9687a05e4bf09992a3f4dd8a852b20c9c694dd9da7a081cd495
  • Pointer size: 131 Bytes
  • Size of remote file: 413 kB
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ indra-ocr==0.3.1
2
+ pillow