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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ import xml.etree.ElementTree as ET
4
+ import os
5
+ import torch
6
+ from transformers import AutoProcessor, AutoModelForImageTextToText, pipeline
7
+ import spaces
8
+
9
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" # turn on HF_TRANSFER
10
+ # --- Global Model and Processor ---
11
+ MODELS = {}
12
+ PROCESSORS = {}
13
+ PIPELINES = {}
14
+ MODEL_LOAD_ERROR_MSG = {}
15
+
16
+ # Available models
17
+ AVAILABLE_MODELS = ["RolmOCR", "Nanonets-OCR-s"]
18
+
19
+ # Load RolmOCR
20
+ try:
21
+ PROCESSORS["RolmOCR"] = AutoProcessor.from_pretrained("reducto/RolmOCR")
22
+ MODELS["RolmOCR"] = AutoModelForImageTextToText.from_pretrained(
23
+ "reducto/RolmOCR", torch_dtype=torch.bfloat16, device_map="auto"
24
+ )
25
+ PIPELINES["RolmOCR"] = pipeline(
26
+ "image-text-to-text", model=MODELS["RolmOCR"], processor=PROCESSORS["RolmOCR"]
27
+ )
28
+ except Exception as e:
29
+ MODEL_LOAD_ERROR_MSG["RolmOCR"] = f"Failed to load RolmOCR: {str(e)}"
30
+ print(f"Error loading RolmOCR: {e}")
31
+
32
+ # Load Nanonets-OCR-s
33
+ try:
34
+ PROCESSORS["Nanonets-OCR-s"] = AutoProcessor.from_pretrained(
35
+ "nanonets/Nanonets-OCR-s"
36
+ )
37
+ MODELS["Nanonets-OCR-s"] = AutoModelForImageTextToText.from_pretrained(
38
+ "nanonets/Nanonets-OCR-s", torch_dtype=torch.bfloat16, device_map="auto"
39
+ )
40
+ PIPELINES["Nanonets-OCR-s"] = pipeline(
41
+ "image-text-to-text",
42
+ model=MODELS["Nanonets-OCR-s"],
43
+ processor=PROCESSORS["Nanonets-OCR-s"],
44
+ )
45
+ except Exception as e:
46
+ MODEL_LOAD_ERROR_MSG["Nanonets-OCR-s"] = f"Failed to load Nanonets-OCR-s: {str(e)}"
47
+ print(f"Error loading Nanonets-OCR-s: {e}")
48
+
49
+
50
+ # --- Helper Functions ---
51
+
52
+
53
+ def get_xml_namespace(xml_file_path):
54
+ """
55
+ Dynamically gets the namespace from the XML file.
56
+ Returns both the namespace and the format type (ALTO or PAGE).
57
+ """
58
+ try:
59
+ tree = ET.parse(xml_file_path)
60
+ root = tree.getroot()
61
+ if "}" in root.tag:
62
+ ns = root.tag.split("}")[0] + "}"
63
+ # Determine format based on root element
64
+ if "PcGts" in root.tag:
65
+ return ns, "PAGE"
66
+ elif "alto" in root.tag.lower():
67
+ return ns, "ALTO"
68
+ except ET.ParseError:
69
+ print(f"Error parsing XML to find namespace: {xml_file_path}")
70
+ return "", "UNKNOWN"
71
+
72
+
73
+ def parse_page_xml_for_text(xml_file_path):
74
+ """
75
+ Parses a PAGE XML file to extract text content.
76
+ Returns:
77
+ - full_text (str): All extracted text concatenated.
78
+ """
79
+ full_text_lines = []
80
+
81
+ if not xml_file_path or not os.path.exists(xml_file_path):
82
+ return "Error: XML file not provided or does not exist."
83
+
84
+ try:
85
+ ns_prefix, _ = get_xml_namespace(xml_file_path)
86
+ tree = ET.parse(xml_file_path)
87
+ root = tree.getroot()
88
+
89
+ # Find all TextLine elements
90
+ for text_line in root.findall(f".//{ns_prefix}TextLine"):
91
+ # First try to get text from TextEquiv/Unicode
92
+ text_equiv = text_line.find(f"{ns_prefix}TextEquiv/{ns_prefix}Unicode")
93
+ if text_equiv is not None and text_equiv.text:
94
+ full_text_lines.append(text_equiv.text)
95
+ continue
96
+
97
+ # If no TextEquiv, try to get text from Word elements
98
+ line_text_parts = []
99
+ for word in text_line.findall(f"{ns_prefix}Word"):
100
+ word_text = word.find(f"{ns_prefix}TextEquiv/{ns_prefix}Unicode")
101
+ if word_text is not None and word_text.text:
102
+ line_text_parts.append(word_text.text)
103
+
104
+ if line_text_parts:
105
+ full_text_lines.append(" ".join(line_text_parts))
106
+
107
+ return "\n".join(full_text_lines)
108
+
109
+ except ET.ParseError as e:
110
+ return f"Error parsing XML: {e}"
111
+ except Exception as e:
112
+ return f"An unexpected error occurred during XML parsing: {e}"
113
+
114
+
115
+ def parse_alto_xml_for_text(xml_file_path):
116
+ """
117
+ Parses an ALTO XML file to extract text content.
118
+ Returns:
119
+ - full_text (str): All extracted text concatenated.
120
+ """
121
+ full_text_lines = []
122
+
123
+ if not xml_file_path or not os.path.exists(xml_file_path):
124
+ return "Error: XML file not provided or does not exist."
125
+
126
+ try:
127
+ ns_prefix, _ = get_xml_namespace(xml_file_path)
128
+ tree = ET.parse(xml_file_path)
129
+ root = tree.getroot()
130
+
131
+ for text_line in root.findall(f".//{ns_prefix}TextLine"):
132
+ line_text_parts = []
133
+ for string_element in text_line.findall(f"{ns_prefix}String"):
134
+ if text := string_element.get("CONTENT"):
135
+ line_text_parts.append(text)
136
+ if line_text_parts:
137
+ full_text_lines.append(" ".join(line_text_parts))
138
+
139
+ return "\n".join(full_text_lines)
140
+
141
+ except ET.ParseError as e:
142
+ return f"Error parsing XML: {e}"
143
+ except Exception as e:
144
+ return f"An unexpected error occurred during XML parsing: {e}"
145
+
146
+
147
+ def parse_xml_for_text(xml_file_path):
148
+ """
149
+ Main function to parse XML files, automatically detecting the format.
150
+ """
151
+ if not xml_file_path or not os.path.exists(xml_file_path):
152
+ return "Error: XML file not provided or does not exist."
153
+
154
+ try:
155
+ _, xml_format = get_xml_namespace(xml_file_path)
156
+
157
+ if xml_format == "PAGE":
158
+ return parse_page_xml_for_text(xml_file_path)
159
+ elif xml_format == "ALTO":
160
+ return parse_alto_xml_for_text(xml_file_path)
161
+ else:
162
+ return "Error: Unsupported XML format. Expected ALTO or PAGE XML."
163
+
164
+ except Exception as e:
165
+ return f"Error determining XML format: {str(e)}"
166
+
167
+
168
+ @spaces.GPU
169
+ def predict(pil_image, model_name="RolmOCR"):
170
+ """Performs OCR prediction using the selected Hugging Face model."""
171
+ global PIPELINES, MODEL_LOAD_ERROR_MSG
172
+
173
+ if model_name not in PIPELINES:
174
+ error_to_report = MODEL_LOAD_ERROR_MSG.get(
175
+ model_name,
176
+ f"Model {model_name} could not be initialized or is not available.",
177
+ )
178
+ raise RuntimeError(error_to_report)
179
+
180
+ selected_pipe = PIPELINES[model_name]
181
+
182
+ # Format the message based on the model
183
+ if model_name == "RolmOCR":
184
+ messages = [
185
+ {
186
+ "role": "user",
187
+ "content": [
188
+ {"type": "image", "image": pil_image},
189
+ {
190
+ "type": "text",
191
+ "text": "Return the plain text representation of this document as if you were reading it naturally.\n",
192
+ },
193
+ ],
194
+ }
195
+ ]
196
+ else: # Nanonets-OCR-s
197
+ messages = [
198
+ {
199
+ "role": "user",
200
+ "content": [
201
+ {"type": "image", "image": pil_image},
202
+ {
203
+ "type": "text",
204
+ "text": "Extract and return all the text from this image. Include all text elements and maintain the reading order. If there are tables, convert them to markdown format. If there are mathematical equations, convert them to LaTeX format.",
205
+ },
206
+ ],
207
+ }
208
+ ]
209
+ max_tokens = 8096
210
+ # Use the pipeline with the properly formatted messages
211
+ return selected_pipe(messages, max_new_tokens=max_tokens)
212
+
213
+
214
+ def run_hf_ocr(image_path, model_name="RolmOCR"):
215
+ """
216
+ Runs OCR on the provided image using the selected Hugging Face model (via predict function).
217
+ """
218
+ if image_path is None:
219
+ return "No image provided for OCR."
220
+
221
+ try:
222
+ pil_image = Image.open(image_path).convert("RGB")
223
+ ocr_results = predict(
224
+ pil_image, model_name
225
+ ) # predict handles model loading and inference
226
+
227
+ # Parse the output based on the user's example structure
228
+ if (
229
+ isinstance(ocr_results, list)
230
+ and ocr_results
231
+ and "generated_text" in ocr_results[0]
232
+ ):
233
+ generated_content = ocr_results[0]["generated_text"]
234
+
235
+ if isinstance(generated_content, str):
236
+ return generated_content
237
+
238
+ if isinstance(generated_content, list) and generated_content:
239
+ if assistant_message := next(
240
+ (
241
+ msg["content"]
242
+ for msg in reversed(generated_content)
243
+ if isinstance(msg, dict)
244
+ and msg.get("role") == "assistant"
245
+ and "content" in msg
246
+ ),
247
+ None,
248
+ ):
249
+ return assistant_message
250
+
251
+ # Fallback if the specific assistant message structure isn't found but there's content
252
+ if (
253
+ isinstance(generated_content[0], dict)
254
+ and "content" in generated_content[0]
255
+ ):
256
+ if (
257
+ len(generated_content) > 1
258
+ and isinstance(generated_content[1], dict)
259
+ and "content" in generated_content[1]
260
+ ):
261
+ return generated_content[1][
262
+ "content"
263
+ ] # Assuming second part is assistant
264
+ else:
265
+ return generated_content[0]["content"]
266
+
267
+ print(f"Unexpected OCR output structure from HF model: {ocr_results}")
268
+ return "Error: Could not parse OCR model output. Check console."
269
+
270
+ else:
271
+ print(f"Unexpected OCR output structure from HF model: {ocr_results}")
272
+ return "Error: OCR model did not return expected output. Check console."
273
+
274
+ except RuntimeError as e: # Catch model loading/initialization errors from predict
275
+ return str(e)
276
+ except Exception as e:
277
+ print(f"Error during Hugging Face OCR processing: {e}")
278
+ return f"Error during Hugging Face OCR: {str(e)}"
279
+
280
+
281
+ # --- Gradio Interface Function ---
282
+
283
+
284
+ def process_files(image_path, xml_path, model_name):
285
+ """
286
+ Main function for the Gradio interface.
287
+ Processes the image for display, runs OCR with selected model,
288
+ and parses XML if provided.
289
+ """
290
+ img_to_display = None
291
+ xml_text_output = "XML not provided or not processed."
292
+ hf_ocr_text_output = "Image not provided or OCR not run."
293
+ ocr_download = gr.DownloadButton(visible=False)
294
+ xml_download = gr.DownloadButton(visible=False)
295
+
296
+ if image_path:
297
+ try:
298
+ img_to_display = Image.open(image_path).convert("RGB")
299
+ hf_ocr_text_output = run_hf_ocr(image_path, model_name)
300
+
301
+ # Create download file for OCR output
302
+ if hf_ocr_text_output and not hf_ocr_text_output.startswith("Error"):
303
+ ocr_filename = f"vlm_ocr_output_{model_name}.txt"
304
+ with open(ocr_filename, "w", encoding="utf-8") as f:
305
+ f.write(hf_ocr_text_output)
306
+ ocr_download = gr.DownloadButton(
307
+ label="Download VLM OCR", value=ocr_filename, visible=True
308
+ )
309
+ except Exception as e:
310
+ img_to_display = None # Clear image if it failed to load
311
+ hf_ocr_text_output = f"Error loading image or running {model_name} OCR: {e}"
312
+ else:
313
+ hf_ocr_text_output = "Please upload an image to perform OCR."
314
+
315
+ if xml_path:
316
+ xml_text_output = parse_xml_for_text(xml_path)
317
+
318
+ # Create download file for XML text
319
+ if xml_text_output and not xml_text_output.startswith("Error"):
320
+ xml_filename = "traditional_ocr_output.txt"
321
+ with open(xml_filename, "w", encoding="utf-8") as f:
322
+ f.write(xml_text_output)
323
+ xml_download = gr.DownloadButton(
324
+ label="Download XML Text", value=xml_filename, visible=True
325
+ )
326
+ else:
327
+ xml_text_output = "No XML file uploaded."
328
+
329
+ # If only XML is provided without an image
330
+ if not image_path and xml_path:
331
+ img_to_display = None # No image to display
332
+ hf_ocr_text_output = "Upload an image to perform OCR."
333
+
334
+ return (
335
+ img_to_display,
336
+ xml_text_output,
337
+ hf_ocr_text_output,
338
+ ocr_download,
339
+ xml_download,
340
+ )
341
+
342
+
343
+ # --- Create Gradio App ---
344
+
345
+ with gr.Blocks() as demo:
346
+ gr.Markdown("# πŸ•°οΈ OCR Time Machine")
347
+ gr.Markdown(
348
+ "Travel through time to see how OCR technology has evolved! \n\n "
349
+ "For decades, galleries, libraries, archives, and museums (GLAMs) have used Optical Character Recognition "
350
+ "to transform digitized books, newspapers, and manuscripts into machine-readable text. Traditional OCR "
351
+ "produces complex XML formats like ALTO, packed with layout details but difficult to use. "
352
+ "Now, cutting-edge Vision-Language Models (VLMs) are revolutionizing OCR with simpler, cleaner Markdown output. "
353
+ "This Space makes it easy to compare these two approaches and see which works best for your historical documents. "
354
+ "Upload a historical document image and its XML file to compare these approaches side-by-side. "
355
+ "We'll extract the reading order from your XML for an apples-to-apples comparison of the actual text content.\n\n"
356
+ "**Available models:** [RolmOCR](https://huggingface.co/reducto/RolmOCR) | "
357
+ "[Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s)"
358
+ )
359
+
360
+ gr.Markdown("---")
361
+
362
+ # How it works section
363
+ gr.Markdown("## πŸš€ How it works")
364
+ gr.Markdown(
365
+ "1. πŸ“€ **Upload Image**: Select a historical document image (JPG, PNG, JP2)\n"
366
+ "2. πŸ“„ **Upload XML** (Optional): Add the corresponding ALTO or PAGE XML file for comparison\n"
367
+ "3. πŸ€– **Choose Model**: Select between RolmOCR (new) or Nanonets-OCR-s (even newer!)\n"
368
+ "4. πŸ” **Compare**: Click 'Compare OCR Methods' to process\n"
369
+ "5. πŸ’Ύ **Download**: Save the results for further analysis"
370
+ )
371
+
372
+ gr.Markdown("---")
373
+
374
+ # Input section
375
+ gr.Markdown("## πŸ“₯ Upload Files")
376
+ with gr.Row():
377
+ with gr.Column(scale=1):
378
+ with gr.Group():
379
+ gr.Markdown("### πŸ“€ Step 1: Upload your document")
380
+ image_input = gr.File(
381
+ label="Historical Document Image",
382
+ type="filepath",
383
+ file_types=["image"],
384
+ )
385
+ xml_input = gr.File(
386
+ label="XML File (Optional - ALTO or PAGE format)",
387
+ type="filepath",
388
+ file_types=[".xml"],
389
+ )
390
+
391
+ with gr.Group():
392
+ gr.Markdown("### πŸ€– Step 2: Select OCR Model")
393
+ model_selector = gr.Radio(
394
+ choices=AVAILABLE_MODELS,
395
+ value="RolmOCR",
396
+ label="Choose Model",
397
+ info="RolmOCR: Fast & general-purpose | Nanonets: Advanced with table/math support",
398
+ )
399
+
400
+ submit_button = gr.Button(
401
+ "πŸ” Compare OCR Methods", variant="primary", size="lg"
402
+ )
403
+
404
+ # Results section
405
+ gr.Markdown("## πŸ“Š Results")
406
+ with gr.Row():
407
+ with gr.Column(scale=1):
408
+ with gr.Group():
409
+ gr.Markdown("### πŸ–ΌοΈ Document Image")
410
+ output_image_display = gr.Image(
411
+ label="Uploaded Document", type="pil", interactive=False
412
+ )
413
+ with gr.Column(scale=1):
414
+ with gr.Group():
415
+ gr.Markdown("### πŸ€– Modern VLM OCR Output")
416
+ hf_ocr_output_textbox = gr.Markdown(
417
+ label="Markdown Format",
418
+ show_copy_button=True,
419
+ )
420
+ ocr_download_btn = gr.DownloadButton(
421
+ label="πŸ’Ύ Download VLM OCR", visible=False, size="sm"
422
+ )
423
+ with gr.Group():
424
+ gr.Markdown("### πŸ“œ Traditional OCR Output")
425
+ xml_output_textbox = gr.Textbox(
426
+ label="XML Reading Order",
427
+ lines=10,
428
+ interactive=False,
429
+ show_copy_button=True,
430
+ )
431
+ xml_download_btn = gr.DownloadButton(
432
+ label="πŸ’Ύ Download XML Text", visible=False, size="sm"
433
+ )
434
+
435
+ submit_button.click(
436
+ fn=process_files,
437
+ inputs=[image_input, xml_input, model_selector],
438
+ outputs=[
439
+ output_image_display,
440
+ xml_output_textbox,
441
+ hf_ocr_output_textbox,
442
+ ocr_download_btn,
443
+ xml_download_btn,
444
+ ],
445
+ )
446
+
447
+ gr.Markdown("---")
448
+
449
+ # Examples section
450
+ with gr.Group():
451
+ gr.Markdown("## 🎯 Try an Example")
452
+ gr.Examples(
453
+ examples=[
454
+ [
455
+ "examples/one/74442232.3.jpg",
456
+ "examples/one/74442232.34.xml",
457
+ "RolmOCR",
458
+ ],
459
+ [
460
+ "examples/one/74442232.3.jpg",
461
+ "examples/one/74442232.34.xml",
462
+ "Nanonets-OCR-s",
463
+ ],
464
+ ],
465
+ inputs=[image_input, xml_input, model_selector],
466
+ outputs=[
467
+ output_image_display,
468
+ xml_output_textbox,
469
+ hf_ocr_output_textbox,
470
+ ocr_download_btn,
471
+ xml_download_btn,
472
+ ],
473
+ fn=process_files,
474
+ cache_examples=False,
475
+ )
476
+ gr.Markdown(
477
+ "*Example from ['A Medical History of British India'](https://data.nls.uk/data/digitised-collections/a-medical-history-of-british-india/) "
478
+ "collection, National Library of Scotland*"
479
+ )
480
+
481
+ gr.Markdown("---")
482
+
483
+ # Tips section
484
+ with gr.Accordion("πŸ’‘ Tips & Information", open=False):
485
+ gr.Markdown(
486
+ "### πŸ“š About ALTO/PAGE XML\n"
487
+ "- **ALTO** (Analyzed Layout and Text Object) and **PAGE** are XML formats that store OCR results with detailed layout information\n"
488
+ "- These files are typically generated by traditional OCR software and include position data for each text element\n"
489
+ "- This tool extracts just the reading order text for easier comparison\n\n"
490
+ "### 🎯 Best Practices\n"
491
+ "- Use high-resolution scans (300+ DPI) for best results\n"
492
+ "- Historical documents with clear text work best\n"
493
+ "- The VLM models can handle complex layouts, tables, and mathematical notation\n\n"
494
+ )
495
+ gr.Code(
496
+ value=(
497
+ """<alto xmlns="http://www.loc.gov/standards/alto/v3/alto.xsd">
498
+ <Layout>
499
+ <Page>
500
+ <PrintSpace>
501
+ <TextLine>
502
+ <String CONTENT="Hello World"/>
503
+ </TextLine>
504
+ </PrintSpace>
505
+ </Page>
506
+ </Layout>
507
+ </alto>"""
508
+ ),
509
+ interactive=False,
510
+ )
511
+
512
+ # Footer
513
+ gr.Markdown("---")
514
+ gr.Markdown(
515
+ "<center>\n\n"
516
+ "Built with ❀️ for the GLAM community | "
517
+ "[Learn more about OCR formats](https://www.loc.gov/standards/alto/) | "
518
+ "Questions? [Open an issue](https://github.com/davanstrien/ocr-playground/issues)\n\n"
519
+ "</center>"
520
+ )
521
+
522
+ if __name__ == "__main__":
523
+ print("Attempting to launch Gradio demo...")
524
+ print(
525
+ "If the Hugging Face model is large, initial startup might take some time due to model download/loading (on first OCR attempt)."
526
+ )
527
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch
3
+ gradio
4
+ Pillow
5
+ lxml
6
+ transformers
7
+ spaces
8
+ torchvision
9
+ accelerate
10
+ hf-transfer
11
+ hf-xet