docling-extractor 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ """
2
+ docling_extractor - Production-grade document extraction with intelligent fallback chains.
3
+
4
+ Main components:
5
+ - extract_single_document: Primary entry point for document processing
6
+ - DoclingExtractor: Handles digital PDF extraction with Docling
7
+ - is_scanned_pdf: Detects whether a PDF is scanned or digital
8
+
9
+ For full documentation, see: https://github.com/panwarnalini-hub/clinical-doc-pipelines
10
+ """
11
+
12
+ __version__ = "1.0.0"
13
+ __author__ = "Nalini Panwar"
14
+
15
+ from .extractor import (
16
+ extract_single_document,
17
+ DoclingExtractor,
18
+ is_scanned_pdf,
19
+ )
20
+
21
+ __all__ = [
22
+ "extract_single_document",
23
+ "DoclingExtractor",
24
+ "is_scanned_pdf",
25
+ ]
@@ -0,0 +1,690 @@
1
+ # docling_extractor.py v0.0.10
2
+ """
3
+ Document extraction pipeline:
4
+ - DIGITAL PDFs: Docling → PyMuPDF → pdfplumber → raw_text
5
+ - SCANNED PDFs: Tesseract → PyMuPDF (with image extraction)
6
+
7
+ Designed for Databricks workers with read-only site-packages.
8
+ """
9
+
10
+ import os
11
+ import re
12
+ import traceback
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+ from typing import Dict, List, Any, Optional
16
+
17
+ import fitz # PyMuPDF
18
+
19
+
20
+ def is_scanned_pdf(path: str, sample_pages: int = 3) -> bool:
21
+ """
22
+ Detect if PDF is scanned (images only, minimal text).
23
+ Samples first few pages to decide.
24
+ """
25
+ try:
26
+ doc = fitz.open(path)
27
+ if len(doc) == 0:
28
+ doc.close()
29
+ return False
30
+
31
+ pages_to_check = min(sample_pages, len(doc))
32
+ total_text_chars = 0
33
+ total_images = 0
34
+
35
+ for i in range(pages_to_check):
36
+ page = doc[i]
37
+ text = page.get_text().strip()
38
+ images = page.get_images()
39
+ total_text_chars += len(text)
40
+ total_images += len(images)
41
+
42
+ doc.close()
43
+
44
+ # If very little text but has images, likely scanned
45
+ avg_chars_per_page = total_text_chars / pages_to_check
46
+ return avg_chars_per_page < 100 and total_images > 0
47
+
48
+ except Exception:
49
+ return False
50
+
51
+
52
+ class DoclingExtractor:
53
+ """
54
+ Extract DIGITAL PDFs using Docling.
55
+ OCR is disabled to avoid RapidOCR read-only filesystem issues.
56
+ """
57
+
58
+ def __init__(self, output_dir: str):
59
+ self.output_dir = output_dir
60
+ os.makedirs(output_dir, exist_ok=True)
61
+ self.converter = None
62
+ self._init_error = None
63
+
64
+ try:
65
+ from docling.document_converter import DocumentConverter, PdfFormatOption
66
+ from docling.datamodel.pipeline_options import PdfPipelineOptions
67
+ from docling.datamodel.base_models import InputFormat
68
+
69
+ # Configure for DIGITAL PDFs only - no OCR
70
+ pipeline_options = PdfPipelineOptions()
71
+ pipeline_options.images_scale = 2.0
72
+ pipeline_options.generate_page_images = True
73
+ pipeline_options.generate_picture_images = True
74
+ pipeline_options.do_ocr = False # Disabled for digital PDFs
75
+ pipeline_options.do_table_structure = True
76
+
77
+ self.converter = DocumentConverter(
78
+ format_options={
79
+ InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)
80
+ }
81
+ )
82
+ except Exception as e:
83
+ self._init_error = f"Docling init failed: {str(e)}"
84
+
85
+ def extract(self, path: str, doc_id: str) -> dict:
86
+ """Extract document and return structured data."""
87
+
88
+ if self._init_error:
89
+ return {
90
+ "success": False,
91
+ "error": self._init_error,
92
+ "pages": [], "sections": [], "images": [],
93
+ "tables": [], "formulas": [], "errors": [],
94
+ "tools_used": ["docling_init_failed"],
95
+ }
96
+
97
+ try:
98
+ from docling_core.types.doc.document import (
99
+ DoclingDocument, TableItem, PictureItem,
100
+ SectionHeaderItem
101
+ )
102
+
103
+ doc_output_dir = os.path.join(self.output_dir, doc_id)
104
+ os.makedirs(doc_output_dir, exist_ok=True)
105
+
106
+ conv_result = self.converter.convert(path)
107
+ doc: DoclingDocument = conv_result.document
108
+
109
+ now = datetime.utcnow().isoformat()
110
+ pages, sections, images, tables, formulas, errors = [], [], [], [], [], []
111
+ section_seq = image_seq = table_seq = 0
112
+
113
+ # === PAGES ===
114
+ for page_no, page in doc.pages.items():
115
+ page_text = ""
116
+ for item, level in doc.iterate_items():
117
+ if hasattr(item, 'prov') and item.prov:
118
+ for prov in item.prov:
119
+ if prov.page_no == page_no:
120
+ text = getattr(item, 'text', '') or ''
121
+ if text:
122
+ page_text += text + "\n"
123
+ break
124
+
125
+ pages.append({
126
+ "document_id": doc_id,
127
+ "protocol_id": doc_id,
128
+ "page_number": int(page_no),
129
+ "text": page_text,
130
+ "source_path": path,
131
+ })
132
+
133
+ # === SECTIONS ===
134
+ for item, level in doc.iterate_items():
135
+ if isinstance(item, (TableItem, PictureItem)):
136
+ continue
137
+
138
+ text = getattr(item, 'text', '') or ''
139
+ if not text.strip():
140
+ continue
141
+
142
+ section_seq += 1
143
+
144
+ if isinstance(item, SectionHeaderItem):
145
+ section_type = "heading"
146
+ heading_level = getattr(item, 'level', 1)
147
+ elif hasattr(item, 'label'):
148
+ section_type = self._map_label(item.label)
149
+ heading_level = None
150
+ else:
151
+ section_type = "paragraph"
152
+ heading_level = None
153
+
154
+ page_no = 0
155
+ bbox = [None, None, None, None]
156
+ if hasattr(item, 'prov') and item.prov:
157
+ prov = item.prov[0]
158
+ page_no = prov.page_no
159
+ if prov.bbox:
160
+ bbox = [prov.bbox.l, prov.bbox.t, prov.bbox.r, prov.bbox.b]
161
+
162
+ sections.append({
163
+ "section_id": f"{doc_id}_s{section_seq:05d}",
164
+ "document_id": doc_id,
165
+ "protocol_id": doc_id,
166
+ "page_number": int(page_no),
167
+ "sequence_number": section_seq,
168
+ "section_type": section_type,
169
+ "content_text": text,
170
+ "heading_level": heading_level,
171
+ "bbox_x0": bbox[0],
172
+ "bbox_y0": bbox[1],
173
+ "bbox_x1": bbox[2],
174
+ "bbox_y1": bbox[3],
175
+ "extracted_at": now,
176
+ "source_path": path,
177
+ })
178
+
179
+ # === IMAGES ===
180
+ for pic_item in doc.pictures:
181
+ image_seq += 1
182
+ page_no = pic_item.prov[0].page_no if pic_item.prov else 0
183
+
184
+ file_path = None
185
+ width = height = None
186
+
187
+ if pic_item.image and pic_item.image.pil_image:
188
+ pil_img = pic_item.image.pil_image
189
+ width, height = pil_img.size
190
+ img_filename = f"p{page_no:03d}_img{image_seq:03d}.png"
191
+ img_path = os.path.join(doc_output_dir, img_filename)
192
+ pil_img.save(img_path, "PNG")
193
+ file_path = img_path
194
+
195
+ images.append({
196
+ "image_id": f"{doc_id}_p{page_no:03d}_img{image_seq:03d}",
197
+ "document_id": doc_id,
198
+ "protocol_id": doc_id,
199
+ "page_number": int(page_no),
200
+ "image_format": "PNG",
201
+ "image_path": file_path,
202
+ "width": width,
203
+ "height": height,
204
+ "source_path": path,
205
+ })
206
+
207
+ # === TABLES ===
208
+ for table_item in doc.tables:
209
+ table_seq += 1
210
+ page_no = table_item.prov[0].page_no if table_item.prov else 0
211
+
212
+ html_content = md_content = ""
213
+ row_count = col_count = 0
214
+
215
+ if table_item.data:
216
+ row_count = table_item.data.num_rows
217
+ col_count = table_item.data.num_cols
218
+
219
+ try:
220
+ html_content = table_item.export_to_html() if hasattr(table_item, 'export_to_html') else ""
221
+ except:
222
+ pass
223
+ try:
224
+ md_content = table_item.export_to_markdown() if hasattr(table_item, 'export_to_markdown') else ""
225
+ except:
226
+ pass
227
+
228
+ tables.append({
229
+ "table_id": f"{doc_id}_p{page_no:03d}_tbl{table_seq:03d}",
230
+ "document_id": doc_id,
231
+ "protocol_id": doc_id,
232
+ "page_number": int(page_no),
233
+ "html": html_content,
234
+ "markdown": md_content,
235
+ "row_count": row_count,
236
+ "column_count": col_count,
237
+ "source_path": path,
238
+ })
239
+
240
+ # Save exports
241
+ md_path = os.path.join(doc_output_dir, f"{doc_id}.md")
242
+ with open(md_path, "w", encoding="utf-8") as f:
243
+ f.write(doc.export_to_markdown())
244
+
245
+ return {
246
+ "success": True,
247
+ "pages": pages,
248
+ "sections": sections,
249
+ "images": images,
250
+ "tables": tables,
251
+ "formulas": formulas,
252
+ "errors": errors,
253
+ "tools_used": ["docling"],
254
+ "output_path": doc_output_dir,
255
+ }
256
+
257
+ except Exception as e:
258
+ return {
259
+ "success": False,
260
+ "error": str(e),
261
+ "traceback": traceback.format_exc()[:1500],
262
+ "pages": [], "sections": [], "images": [],
263
+ "tables": [], "formulas": [], "errors": [],
264
+ "tools_used": ["docling_failed"],
265
+ }
266
+
267
+ def _map_label(self, label) -> str:
268
+ if label is None:
269
+ return "paragraph"
270
+ label_str = label.value if hasattr(label, 'value') else str(label)
271
+ mapping = {
272
+ "title": "title", "document_index": "toc", "section_header": "heading",
273
+ "paragraph": "paragraph", "text": "paragraph", "list_item": "list_item",
274
+ "caption": "caption", "formula": "equation", "footnote": "footnote",
275
+ }
276
+ return mapping.get(label_str.lower(), "paragraph")
277
+
278
+
279
+ def _extract_with_tesseract(source_path: str, doc_id: str, output_dir: str) -> dict:
280
+ """
281
+ Extract SCANNED PDF using Tesseract OCR.
282
+ Fallback for scanned documents.
283
+ """
284
+ try:
285
+ import pytesseract
286
+ from PIL import Image
287
+
288
+ doc_output_dir = os.path.join(output_dir, doc_id)
289
+ os.makedirs(doc_output_dir, exist_ok=True)
290
+
291
+ pdf = fitz.open(source_path)
292
+ pages, sections, images = [], [], []
293
+ section_seq = image_seq = 0
294
+ now = datetime.utcnow().isoformat()
295
+
296
+ for page_idx in range(len(pdf)):
297
+ page = pdf[page_idx]
298
+ page_num = page_idx + 1
299
+
300
+ # Render page to image
301
+ pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
302
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
303
+
304
+ # OCR the image
305
+ text = pytesseract.image_to_string(img)
306
+
307
+ pages.append({
308
+ "document_id": doc_id,
309
+ "protocol_id": doc_id,
310
+ "page_number": page_num,
311
+ "text": text,
312
+ "source_path": source_path,
313
+ })
314
+
315
+ # Save page image
316
+ image_seq += 1
317
+ img_filename = f"p{page_num:03d}_page.png"
318
+ img_path = os.path.join(doc_output_dir, img_filename)
319
+ img.save(img_path, "PNG")
320
+
321
+ images.append({
322
+ "image_id": f"{doc_id}_p{page_num:03d}_img{image_seq:03d}",
323
+ "document_id": doc_id,
324
+ "protocol_id": doc_id,
325
+ "page_number": page_num,
326
+ "image_format": "PNG",
327
+ "image_path": img_path,
328
+ "width": pix.width,
329
+ "height": pix.height,
330
+ "source_path": source_path,
331
+ })
332
+
333
+ # Create section from OCR text
334
+ if text.strip():
335
+ section_seq += 1
336
+ sections.append({
337
+ "section_id": f"{doc_id}_s{section_seq:05d}",
338
+ "document_id": doc_id,
339
+ "protocol_id": doc_id,
340
+ "page_number": page_num,
341
+ "sequence_number": section_seq,
342
+ "section_type": "ocr_text",
343
+ "content_text": text,
344
+ "extracted_at": now,
345
+ "source_path": source_path,
346
+ })
347
+
348
+ pdf.close()
349
+
350
+ return {
351
+ "success": True,
352
+ "pages": pages,
353
+ "sections": sections,
354
+ "images": images,
355
+ "tables": [],
356
+ "formulas": [],
357
+ "errors": [],
358
+ "tools_used": ["tesseract"],
359
+ }
360
+
361
+ except ImportError:
362
+ return {"success": False, "error": "pytesseract not installed", "tools_used": ["tesseract_missing"]}
363
+ except Exception as e:
364
+ return {"success": False, "error": str(e), "tools_used": ["tesseract_failed"]}
365
+
366
+
367
+ def _extract_with_pymupdf(source_path: str, doc_id: str, output_dir: str) -> dict:
368
+ """
369
+ Extract using PyMuPDF - fast fallback for digital PDFs.
370
+ Also extracts images.
371
+ """
372
+ try:
373
+ doc_output_dir = os.path.join(output_dir, doc_id)
374
+ os.makedirs(doc_output_dir, exist_ok=True)
375
+
376
+ pdf = fitz.open(source_path)
377
+ pages, sections, images = [], [], []
378
+ section_seq = image_seq = 0
379
+ now = datetime.utcnow().isoformat()
380
+
381
+ for page_idx in range(len(pdf)):
382
+ page = pdf[page_idx]
383
+ page_num = page_idx + 1
384
+ page_text = page.get_text("text") or ""
385
+
386
+ pages.append({
387
+ "document_id": doc_id,
388
+ "protocol_id": doc_id,
389
+ "page_number": page_num,
390
+ "text": page_text,
391
+ "source_path": source_path,
392
+ })
393
+
394
+ # Extract images
395
+ for img_idx, img in enumerate(page.get_images()):
396
+ try:
397
+ image_seq += 1
398
+ xref = img[0]
399
+ base_image = pdf.extract_image(xref)
400
+ image_bytes = base_image["image"]
401
+ img_ext = base_image.get("ext", "png")
402
+
403
+ img_filename = f"p{page_num:03d}_img{image_seq:03d}.{img_ext}"
404
+ img_path = os.path.join(doc_output_dir, img_filename)
405
+ with open(img_path, "wb") as f:
406
+ f.write(image_bytes)
407
+
408
+ images.append({
409
+ "image_id": f"{doc_id}_p{page_num:03d}_img{image_seq:03d}",
410
+ "document_id": doc_id,
411
+ "protocol_id": doc_id,
412
+ "page_number": page_num,
413
+ "image_format": img_ext.upper(),
414
+ "image_path": img_path,
415
+ "width": base_image.get("width"),
416
+ "height": base_image.get("height"),
417
+ "source_path": source_path,
418
+ })
419
+ except:
420
+ pass
421
+
422
+ # Extract sections from text blocks
423
+ blocks = page.get_text("dict").get("blocks", [])
424
+ for block in blocks:
425
+ if block.get("type") == 0: # Text block
426
+ for line in block.get("lines", []):
427
+ text = " ".join([span["text"] for span in line.get("spans", [])])
428
+ if text.strip():
429
+ section_seq += 1
430
+ sections.append({
431
+ "section_id": f"{doc_id}_s{section_seq:05d}",
432
+ "document_id": doc_id,
433
+ "protocol_id": doc_id,
434
+ "page_number": page_num,
435
+ "sequence_number": section_seq,
436
+ "section_type": "paragraph",
437
+ "content_text": text,
438
+ "extracted_at": now,
439
+ "source_path": source_path,
440
+ })
441
+
442
+ pdf.close()
443
+
444
+ return {
445
+ "success": True,
446
+ "pages": pages,
447
+ "sections": sections,
448
+ "images": images,
449
+ "tables": [],
450
+ "formulas": [],
451
+ "errors": [],
452
+ "tools_used": ["pymupdf"],
453
+ }
454
+
455
+ except Exception as e:
456
+ return {"success": False, "error": str(e), "tools_used": ["pymupdf_failed"]}
457
+
458
+
459
+ def _extract_with_pdfplumber(source_path: str, doc_id: str) -> dict:
460
+ """Extract using pdfplumber - good for tables."""
461
+ try:
462
+ import pdfplumber
463
+
464
+ pages, tables = [], []
465
+ table_seq = 0
466
+
467
+ with pdfplumber.open(source_path) as pdf:
468
+ for page_idx, page in enumerate(pdf.pages):
469
+ page_num = page_idx + 1
470
+
471
+ pages.append({
472
+ "document_id": doc_id,
473
+ "protocol_id": doc_id,
474
+ "page_number": page_num,
475
+ "text": page.extract_text() or "",
476
+ "source_path": source_path,
477
+ })
478
+
479
+ # Extract tables
480
+ for tbl in page.extract_tables() or []:
481
+ if tbl:
482
+ table_seq += 1
483
+ tables.append({
484
+ "table_id": f"{doc_id}_p{page_num:03d}_tbl{table_seq:03d}",
485
+ "document_id": doc_id,
486
+ "protocol_id": doc_id,
487
+ "page_number": page_num,
488
+ "row_count": len(tbl),
489
+ "column_count": len(tbl[0]) if tbl else 0,
490
+ "source_path": source_path,
491
+ })
492
+
493
+ return {
494
+ "success": True,
495
+ "pages": pages,
496
+ "sections": [],
497
+ "images": [],
498
+ "tables": tables,
499
+ "formulas": [],
500
+ "errors": [],
501
+ "tools_used": ["pdfplumber"],
502
+ }
503
+
504
+ except Exception as e:
505
+ return {"success": False, "error": str(e), "tools_used": ["pdfplumber_failed"]}
506
+
507
+
508
+ def extract_single_document(
509
+ input_path: str = None,
510
+ output_dir: str = None,
511
+ path: str = None,
512
+ output_volume: str = None,
513
+ document_id: str = None,
514
+ ) -> dict:
515
+ """
516
+ Extract a single document with appropriate method based on type.
517
+
518
+ DIGITAL PDFs: Docling → PyMuPDF → pdfplumber → raw_text
519
+ SCANNED PDFs: Tesseract → PyMuPDF
520
+
521
+ Args:
522
+ input_path: Path to source PDF
523
+ output_dir: Output directory
524
+ document_id: Explicit document ID (recommended)
525
+ """
526
+ source_path = input_path or path
527
+ output_path = output_dir or output_volume
528
+
529
+ if not source_path:
530
+ raise ValueError("Must provide input_path or path")
531
+ if not output_path:
532
+ raise ValueError("Must provide output_dir or output_volume")
533
+
534
+ # Determine doc_id
535
+ if document_id:
536
+ doc_id = document_id
537
+ else:
538
+ doc_id = os.path.basename(os.path.dirname(source_path))
539
+ if not doc_id or doc_id in ("tmp", "uploads", "documents", ""):
540
+ doc_id = os.path.splitext(os.path.basename(source_path))[0]
541
+
542
+ def _safe(o):
543
+ if o is None:
544
+ return None
545
+ if isinstance(o, (str, int, float, bool)):
546
+ return o
547
+ if isinstance(o, dict):
548
+ return {str(k): _safe(v) for k, v in o.items()}
549
+ if isinstance(o, list):
550
+ return [_safe(x) for x in o]
551
+ return str(o)
552
+
553
+ record = {
554
+ "protocol_id": doc_id,
555
+ "document_id": doc_id,
556
+ "source_path": source_path,
557
+ "processing_status": "failed",
558
+ "page_count": 0,
559
+ "error_count": 0,
560
+ "processed_at": datetime.utcnow().isoformat(),
561
+ "tools_used": [],
562
+ "error_message": "",
563
+ }
564
+
565
+ # === DETECT SCANNED vs DIGITAL ===
566
+ scanned = is_scanned_pdf(source_path)
567
+
568
+ if scanned:
569
+ # === SCANNED PDF CHAIN: Tesseract → PyMuPDF ===
570
+
571
+ # Try Tesseract first
572
+ result = _extract_with_tesseract(source_path, doc_id, output_path)
573
+ if result.get("success"):
574
+ record.update({
575
+ "processing_status": "success",
576
+ "page_count": len(result.get("pages", [])),
577
+ "tools_used": result.get("tools_used", ["tesseract"]),
578
+ })
579
+ return {"registry": _safe(record), **{k: _safe(v) for k, v in result.items() if k != "success"}}
580
+
581
+ # Fallback to PyMuPDF (will just get images, minimal text)
582
+ result = _extract_with_pymupdf(source_path, doc_id, output_path)
583
+ if result.get("success"):
584
+ record.update({
585
+ "processing_status": "success",
586
+ "page_count": len(result.get("pages", [])),
587
+ "tools_used": result.get("tools_used", ["pymupdf"]),
588
+ "error_message": "Scanned PDF - Tesseract failed, using PyMuPDF",
589
+ })
590
+ return {"registry": _safe(record), **{k: _safe(v) for k, v in result.items() if k != "success"}}
591
+
592
+ else:
593
+ # === DIGITAL PDF CHAIN: Docling → PyMuPDF → pdfplumber → raw_text ===
594
+
595
+ # Try Docling first (with HARD KILL timeout using multiprocessing)
596
+ try:
597
+ import multiprocessing
598
+
599
+ DOCLING_TIMEOUT_SECONDS = 90 # Enterprise standard: 90s per document
600
+
601
+ def _run_docling_worker(result_queue, src_path, out_path, d_id):
602
+ """Worker function that runs in separate process."""
603
+ try:
604
+ extractor = DoclingExtractor(out_path)
605
+ result = extractor.extract(src_path, d_id)
606
+ result_queue.put(result)
607
+ except Exception as e:
608
+ result_queue.put({"success": False, "error": str(e)})
609
+
610
+ # Use multiprocessing for hard kill capability
611
+ result_queue = multiprocessing.Queue()
612
+ process = multiprocessing.Process(
613
+ target=_run_docling_worker,
614
+ args=(result_queue, source_path, output_path, doc_id)
615
+ )
616
+ process.start()
617
+ process.join(timeout=DOCLING_TIMEOUT_SECONDS)
618
+
619
+ if process.is_alive():
620
+ # HARD KILL - terminate the hung process
621
+ process.terminate()
622
+ process.join(timeout=5) # Give it 5s to terminate gracefully
623
+ if process.is_alive():
624
+ process.kill() # Force kill if still alive
625
+ process.join()
626
+ result = {"success": False, "error": f"Docling timeout after {DOCLING_TIMEOUT_SECONDS}s (terminated)"}
627
+ else:
628
+ # Process completed - get result
629
+ try:
630
+ result = result_queue.get_nowait()
631
+ except:
632
+ result = {"success": False, "error": "Docling process completed but no result returned"}
633
+
634
+ if result.get("success"):
635
+ record.update({
636
+ "processing_status": "success",
637
+ "page_count": len(result.get("pages", [])),
638
+ "tools_used": result.get("tools_used", ["docling"]),
639
+ })
640
+ return {"registry": _safe(record), **{k: _safe(v) for k, v in result.items() if k != "success"}}
641
+ else:
642
+ record["error_message"] = f"Docling: {result.get('error', 'unknown')}"
643
+ except Exception as e:
644
+ record["error_message"] = f"Docling exception: {str(e)}"
645
+
646
+ # Fallback to PyMuPDF
647
+ result = _extract_with_pymupdf(source_path, doc_id, output_path)
648
+ if result.get("success"):
649
+ record.update({
650
+ "processing_status": "success",
651
+ "page_count": len(result.get("pages", [])),
652
+ "tools_used": result.get("tools_used", ["pymupdf"]),
653
+ })
654
+ return {"registry": _safe(record), **{k: _safe(v) for k, v in result.items() if k != "success"}}
655
+
656
+ # Fallback to pdfplumber
657
+ result = _extract_with_pdfplumber(source_path, doc_id)
658
+ if result.get("success"):
659
+ record.update({
660
+ "processing_status": "success",
661
+ "page_count": len(result.get("pages", [])),
662
+ "tools_used": result.get("tools_used", ["pdfplumber"]),
663
+ })
664
+ return {"registry": _safe(record), **{k: _safe(v) for k, v in result.items() if k != "success"}}
665
+
666
+ # Last resort: raw text
667
+ try:
668
+ with open(source_path, "rb") as f:
669
+ raw = f.read().decode("latin-1", "ignore")
670
+
671
+ record.update({
672
+ "processing_status": "success",
673
+ "page_count": 1,
674
+ "tools_used": ["raw_text"],
675
+ })
676
+ return {
677
+ "registry": _safe(record),
678
+ "pages": [{"document_id": doc_id, "protocol_id": doc_id, "page_number": 1, "text": raw}],
679
+ "sections": [], "images": [], "tables": [], "formulas": [], "errors": [],
680
+ }
681
+ except:
682
+ pass
683
+
684
+ # Total failure
685
+ record["error_message"] = "All extraction methods failed"
686
+ return {
687
+ "registry": _safe(record),
688
+ "pages": [], "sections": [], "images": [], "tables": [], "formulas": [],
689
+ "errors": [{"error_type": "total_failure", "message": record["error_message"]}],
690
+ }
@@ -0,0 +1,302 @@
1
+ Metadata-Version: 2.4
2
+ Name: docling-extractor
3
+ Version: 1.0.0
4
+ Summary: Production-grade document extraction with intelligent fallback chain: Docling -> PyMuPDF -> pdfplumber -> Tesseract
5
+ Author-email: Nalini Panwar <panwarnalini@gmail.com>
6
+ Maintainer-email: Nalini Panwar <panwarnalini@gmail.com>
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/panwarnalini-hub/clinical-doc-pipelines
9
+ Project-URL: Documentation, https://github.com/panwarnalini-hub/clinical-doc-pipelines/blob/main/README.md
10
+ Project-URL: Repository, https://github.com/panwarnalini-hub/clinical-doc-pipelines
11
+ Project-URL: Bug Tracker, https://github.com/panwarnalini-hub/clinical-doc-pipelines/issues
12
+ Keywords: document-extraction,pdf-processing,docling,ocr,data-engineering,clinical-trials,nlp,databricks
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Scientific/Engineering
25
+ Classifier: Topic :: Text Processing
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Requires-Python: >=3.8
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Requires-Dist: PyMuPDF>=1.23.0
31
+ Requires-Dist: pdfplumber>=0.10.0
32
+ Provides-Extra: full
33
+ Requires-Dist: docling>=2.0.0; extra == "full"
34
+ Requires-Dist: docling-core>=2.0.0; extra == "full"
35
+ Requires-Dist: pytesseract>=0.3.10; extra == "full"
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
38
+ Requires-Dist: black>=23.0.0; extra == "dev"
39
+ Requires-Dist: isort>=5.12.0; extra == "dev"
40
+ Dynamic: license-file
41
+
42
+ # Docling Extractor
43
+
44
+ Production-grade document extraction library with intelligent fallback chain for robust PDF processing.
45
+
46
+ ## Overview
47
+
48
+ Docling Extractor provides a reliable pipeline for extracting text, tables, images, and structured content from PDF documents. The library automatically detects document type (scanned vs. digital) and applies the appropriate extraction method with fallback support.
49
+
50
+ ## Key Features
51
+
52
+ **Intelligent PDF Detection**
53
+ - Automatically identifies scanned vs. digital PDFs
54
+ - Routes documents to optimal extraction method
55
+
56
+ **Robust Fallback Chain**
57
+
58
+ For Digital PDFs:
59
+ 1. Docling - Advanced layout analysis with table/image extraction
60
+ 2. PyMuPDF - Fast text extraction with basic structure
61
+ 3. pdfplumber - Table-focused extraction
62
+ 4. Raw text - Binary extraction as last resort
63
+
64
+ For Scanned PDFs:
65
+ 1. Tesseract OCR - Text recognition
66
+ 2. PyMuPDF - Image extraction with minimal text
67
+
68
+ **Production Ready**
69
+ - 90-second timeout protection with process termination
70
+ - Databricks optimized for distributed processing
71
+ - Structured output (pages, sections, tables, images, formulas)
72
+ - Comprehensive error handling and logging
73
+
74
+ ## Installation
75
+
76
+ Basic installation (PyMuPDF + pdfplumber):
77
+ ```bash
78
+ pip install docling-extractor
79
+ ```
80
+
81
+ Full installation (includes Docling and Tesseract):
82
+ ```bash
83
+ pip install docling-extractor[full]
84
+ ```
85
+
86
+ **Note:** Tesseract requires system installation:
87
+ ```bash
88
+ # Ubuntu/Debian
89
+ sudo apt-get install tesseract-ocr
90
+
91
+ # macOS
92
+ brew install tesseract
93
+
94
+ # Windows
95
+ # Download from: https://github.com/UB-Mannheim/tesseract/wiki
96
+ ```
97
+
98
+ ## Quick Start
99
+
100
+ ### Basic Usage
101
+
102
+ ```python
103
+ from docling_extractor import extract_single_document
104
+
105
+ # Extract a document
106
+ result = extract_single_document(
107
+ input_path="/path/to/document.pdf",
108
+ output_dir="/path/to/output",
109
+ document_id="doc_001"
110
+ )
111
+
112
+ # Access extracted content
113
+ print(f"Status: {result['registry']['processing_status']}")
114
+ print(f"Pages extracted: {len(result['pages'])}")
115
+ print(f"Tables found: {len(result['tables'])}")
116
+ print(f"Tools used: {result['registry']['tools_used']}")
117
+
118
+ # Get page text
119
+ for page in result['pages']:
120
+ print(f"Page {page['page_number']}: {page['text'][:100]}...")
121
+ ```
122
+
123
+ ### Working with Different Document Types
124
+
125
+ ```python
126
+ # Digital PDF (uses Docling -> PyMuPDF -> pdfplumber chain)
127
+ result = extract_single_document(
128
+ input_path="digital_document.pdf",
129
+ output_dir="./output"
130
+ )
131
+
132
+ # Scanned PDF (uses Tesseract -> PyMuPDF chain)
133
+ result = extract_single_document(
134
+ input_path="scanned_document.pdf",
135
+ output_dir="./output"
136
+ )
137
+ ```
138
+
139
+ ### Accessing Structured Data
140
+
141
+ ```python
142
+ result = extract_single_document(
143
+ input_path="document.pdf",
144
+ output_dir="./output",
145
+ document_id="my_doc"
146
+ )
147
+
148
+ # Pages
149
+ for page in result['pages']:
150
+ print(f"Page {page['page_number']}")
151
+ print(page['text'])
152
+
153
+ # Tables
154
+ for table in result['tables']:
155
+ print(f"Table on page {table['page_number']}")
156
+ print(f"Dimensions: {table['row_count']}x{table['column_count']}")
157
+
158
+ # Images
159
+ for img in result['images']:
160
+ print(f"Image saved to: {img['image_path']}")
161
+ print(f"Size: {img['width']}x{img['height']}")
162
+
163
+ # Sections (from Docling)
164
+ for section in result['sections']:
165
+ print(f"Section type: {section['section_type']}")
166
+ print(f"Content: {section['content_text'][:100]}...")
167
+ ```
168
+
169
+ ## Output Structure
170
+
171
+ The extraction result contains:
172
+
173
+ ```python
174
+ {
175
+ 'registry': {
176
+ 'protocol_id': 'document_id',
177
+ 'document_id': 'document_id',
178
+ 'processing_status': 'success', # or 'failed'
179
+ 'page_count': 10,
180
+ 'tools_used': ['docling'], # or ['pymupdf'], ['pdfplumber'], etc.
181
+ 'error_message': '',
182
+ 'processed_at': '2024-12-31T12:00:00'
183
+ },
184
+ 'pages': [
185
+ {
186
+ 'document_id': 'doc_id',
187
+ 'protocol_id': 'doc_id',
188
+ 'page_number': 1,
189
+ 'text': 'extracted text...',
190
+ 'source_path': '/path/to/file.pdf'
191
+ }
192
+ ],
193
+ 'tables': [...],
194
+ 'images': [...],
195
+ 'sections': [...],
196
+ 'formulas': [...],
197
+ 'errors': [...]
198
+ }
199
+ ```
200
+
201
+ ## Use Cases
202
+
203
+ **Clinical Trials & Regulatory Documents**
204
+ - Extract data from clinical trial protocols
205
+ - Process regulatory submission documents
206
+ - Handle ICH-GCP compliant document structures
207
+
208
+ **Research & Academic Papers**
209
+ - Extract structured content from research papers
210
+ - Preserve table and figure information
211
+ - Handle multi-column layouts
212
+
213
+ **Financial Documents**
214
+ - Process annual reports and filings
215
+ - Extract tables from financial statements
216
+ - Handle scanned historical documents
217
+
218
+ **Enterprise Document Processing**
219
+ - Batch processing with Databricks integration
220
+ - Reliable extraction with fallback support
221
+ - Structured output for downstream NLP/ML
222
+
223
+ ## Advanced Configuration
224
+
225
+ ### Using Docling Directly
226
+
227
+ ```python
228
+ from docling_extractor import DoclingExtractor
229
+
230
+ extractor = DoclingExtractor(output_dir="./output")
231
+ result = extractor.extract(
232
+ path="document.pdf",
233
+ doc_id="my_document"
234
+ )
235
+ ```
236
+
237
+ ### Checking PDF Type
238
+
239
+ ```python
240
+ from docling_extractor import is_scanned_pdf
241
+
242
+ if is_scanned_pdf("document.pdf"):
243
+ print("Scanned PDF - will use OCR")
244
+ else:
245
+ print("Digital PDF - will use text extraction")
246
+ ```
247
+
248
+ ## Performance
249
+
250
+ Typical processing times (single-threaded):
251
+ - Digital PDF (10 pages): 5-15 seconds
252
+ - Scanned PDF (10 pages): 30-60 seconds
253
+ - Timeout: 90 seconds (configurable in code)
254
+
255
+ For Databricks distributed processing, use `extract_single_document` with Spark UDFs.
256
+
257
+ ## Requirements
258
+
259
+ **Core Dependencies:**
260
+ - Python >= 3.8
261
+ - PyMuPDF >= 1.23.0
262
+ - pdfplumber >= 0.10.0
263
+
264
+ **Optional Dependencies:**
265
+ - docling >= 2.0.0 (for advanced extraction)
266
+ - docling-core >= 2.0.0
267
+ - pytesseract >= 0.3.10 (for OCR)
268
+
269
+ ## Troubleshooting
270
+
271
+ **Docling timeout issues:**
272
+ The library includes a 90-second hard timeout with process termination. If Docling hangs, it will automatically fall back to PyMuPDF.
273
+
274
+ **OCR not working:**
275
+ Ensure Tesseract is installed system-wide. Check with:
276
+ ```bash
277
+ tesseract --version
278
+ ```
279
+
280
+ **Read-only filesystem (Databricks):**
281
+ The library is designed for Databricks' read-only site-packages. Docling OCR is disabled by default to avoid RapidOCR filesystem issues.
282
+
283
+ ## License
284
+
285
+ MIT License - see LICENSE file for details
286
+
287
+ ## Author
288
+
289
+ Nalini Panwar - [LinkedIn](https://www.linkedin.com/in/nalinipanwar/) | [GitHub](https://github.com/panwarnalini-hub)
290
+
291
+ ## Contributing
292
+
293
+ Contributions welcome. Please open an issue or submit a pull request at:
294
+ https://github.com/panwarnalini-hub/clinical-doc-pipelines
295
+
296
+ ## Acknowledgments
297
+
298
+ Built with:
299
+ - [Docling](https://github.com/DS4SD/docling) - IBM Research document understanding
300
+ - [PyMuPDF](https://pymupdf.readthedocs.io/) - Fast PDF processing
301
+ - [pdfplumber](https://github.com/jsvine/pdfplumber) - Table extraction
302
+ - [Tesseract](https://github.com/tesseract-ocr/tesseract) - OCR engine
@@ -0,0 +1,7 @@
1
+ docling_extractor/__init__.py,sha256=lcCTgUnddWfkHhZ8dQ-mai0apWYyY1oVt_1nO1ernsM,647
2
+ docling_extractor/extractor.py,sha256=_0NXoC_Hdk2f8sdKpfjbLq1Z9lzsUVpVF6ljUW4wMx0,26963
3
+ docling_extractor-1.0.0.dist-info/licenses/LICENSE,sha256=c8jtwDDshXedrII9QcnUK20419tFt2pYJ-k1GxuXLNg,1070
4
+ docling_extractor-1.0.0.dist-info/METADATA,sha256=CYs2-bWLh5TXql793D1KwKEQlobmpV3AV5VRQyarN2w,8779
5
+ docling_extractor-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
6
+ docling_extractor-1.0.0.dist-info/top_level.txt,sha256=4eW1ya1XwKb2EhBBBfNY_mW95ZlKXrtzWxZRGfmNYZA,18
7
+ docling_extractor-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Nalini Panwar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ docling_extractor