-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathparser.py
More file actions
1944 lines (1672 loc) · 69.5 KB
/
parser.py
File metadata and controls
1944 lines (1672 loc) · 69.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# type: ignore
"""
Generic Document Parser Utility
This module provides functionality for parsing PDF and image documents using MinerU 2.0 library,
and converts the parsing results into markdown and JSON formats
Note: MinerU 2.0 no longer includes LibreOffice document conversion module.
For Office documents (.doc, .docx, .ppt, .pptx), please convert them to PDF format first.
"""
from __future__ import annotations
import json
import argparse
import base64
import subprocess
import tempfile
import logging
import urllib.parse
import urllib.request
import shutil
import os
from pathlib import Path
from typing import (
Dict,
List,
Optional,
Union,
Tuple,
Any,
TypeVar,
)
T = TypeVar("T")
class MineruExecutionError(Exception):
"""catch mineru error"""
def __init__(self, return_code, error_msg):
self.return_code = return_code
self.error_msg = error_msg
super().__init__(
f"Mineru command failed with return code {return_code}: {error_msg}"
)
class Parser:
"""
Base class for document parsing utilities.
Defines common functionality and constants for parsing different document types.
"""
# Define common file formats
OFFICE_FORMATS = {".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx"}
IMAGE_FORMATS = {".png", ".jpeg", ".jpg", ".bmp", ".tiff", ".tif", ".gif", ".webp"}
TEXT_FORMATS = {".txt", ".md"}
# Class-level logger
logger = logging.getLogger(__name__)
@staticmethod
def _is_url(path: str) -> bool:
"""Check if the path is a URL."""
try:
result = urllib.parse.urlparse(str(path))
return all([result.scheme, result.netloc])
except ValueError:
return False
def _download_file(self, url: str) -> Path:
"""
Download a file from a URL to a temporary file.
Attempts to preserve the file extension from the URL.
"""
try:
self.logger.info(f"Downloading file from URL: {url}")
# Parse URL to get path and extension
parsed_url = urllib.parse.urlparse(url)
path = Path(parsed_url.path)
suffix = path.suffix if path.suffix else ""
# Create a temporary file with the correct extension
# delete=False is important so we can close it and let other processes open it
# We must manually delete it later
fd, tmp_path = tempfile.mkstemp(suffix=suffix)
os.close(fd)
tmp_path = Path(tmp_path)
# Download the file
# We use a user-agent to avoid 403 Forbidden from some sites
req = urllib.request.Request(
url,
data=None,
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}
)
with urllib.request.urlopen(req) as response, open(tmp_path, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
self.logger.info(f"Downloaded to temporary file: {tmp_path} ({tmp_path.stat().st_size} bytes)")
return tmp_path
except Exception as e:
self.logger.error(f"Failed to download file from {url}: {e}")
raise RuntimeError(f"Failed to download file from {url}: {e}")
def __init__(self) -> None:
"""Initialize the base parser."""
pass
@classmethod
def convert_office_to_pdf(
cls, doc_path: Union[str, Path], output_dir: Optional[str] = None
) -> Path:
"""
Convert Office document (.doc, .docx, .ppt, .pptx, .xls, .xlsx) to PDF.
Requires LibreOffice to be installed.
Args:
doc_path: Path to the Office document file
output_dir: Output directory for the PDF file
Returns:
Path to the generated PDF file
"""
try:
# Convert to Path object for easier handling
doc_path = Path(doc_path)
if not doc_path.exists():
raise FileNotFoundError(f"Office document does not exist: {doc_path}")
name_without_suff = doc_path.stem
# Prepare output directory
if output_dir:
base_output_dir = Path(output_dir)
else:
base_output_dir = doc_path.parent / "libreoffice_output"
base_output_dir.mkdir(parents=True, exist_ok=True)
# Create temporary directory for PDF conversion
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
# Convert to PDF using LibreOffice
cls.logger.info(
f"Converting {doc_path.name} to PDF using LibreOffice..."
)
# Prepare subprocess parameters to hide console window on Windows
import platform
# Try LibreOffice commands in order of preference
commands_to_try = ["libreoffice", "soffice"]
conversion_successful = False
for cmd in commands_to_try:
try:
convert_cmd = [
cmd,
"--headless",
"--convert-to",
"pdf",
"--outdir",
str(temp_path),
str(doc_path),
]
# Prepare conversion subprocess parameters
convert_subprocess_kwargs = {
"capture_output": True,
"text": True,
"timeout": 60, # 60 second timeout
"encoding": "utf-8",
"errors": "ignore",
}
# Hide console window on Windows
if platform.system() == "Windows":
convert_subprocess_kwargs["creationflags"] = (
subprocess.CREATE_NO_WINDOW
)
result = subprocess.run(
convert_cmd, **convert_subprocess_kwargs
)
if result.returncode == 0:
conversion_successful = True
cls.logger.info(
f"Successfully converted {doc_path.name} to PDF using {cmd}"
)
break
else:
cls.logger.warning(
f"LibreOffice command '{cmd}' failed: {result.stderr}"
)
except FileNotFoundError:
cls.logger.warning(f"LibreOffice command '{cmd}' not found")
except subprocess.TimeoutExpired:
cls.logger.warning(f"LibreOffice command '{cmd}' timed out")
except Exception as e:
cls.logger.error(
f"LibreOffice command '{cmd}' failed with exception: {e}"
)
if not conversion_successful:
raise RuntimeError(
f"LibreOffice conversion failed for {doc_path.name}. "
f"Please ensure LibreOffice is installed:\n"
"- Windows: Download from https://www.libreoffice.org/download/download/\n"
"- macOS: brew install --cask libreoffice\n"
"- Ubuntu/Debian: sudo apt-get install libreoffice\n"
"- CentOS/RHEL: sudo yum install libreoffice\n"
"Alternatively, convert the document to PDF manually."
)
# Find the generated PDF
pdf_files = list(temp_path.glob("*.pdf"))
if not pdf_files:
raise RuntimeError(
f"PDF conversion failed for {doc_path.name} - no PDF file generated. "
f"Please check LibreOffice installation or try manual conversion."
)
pdf_path = pdf_files[0]
cls.logger.info(
f"Generated PDF: {pdf_path.name} ({pdf_path.stat().st_size} bytes)"
)
# Validate the generated PDF
if pdf_path.stat().st_size < 100: # Very small file, likely empty
raise RuntimeError(
"Generated PDF appears to be empty or corrupted. "
"Original file may have issues or LibreOffice conversion failed."
)
# Copy PDF to final output directory
final_pdf_path = base_output_dir / f"{name_without_suff}.pdf"
import shutil
shutil.copy2(pdf_path, final_pdf_path)
return final_pdf_path
except Exception as e:
cls.logger.error(f"Error in convert_office_to_pdf: {str(e)}")
raise
@classmethod
def convert_text_to_pdf(
cls, text_path: Union[str, Path], output_dir: Optional[str] = None
) -> Path:
"""
Convert text file (.txt, .md) to PDF using ReportLab with full markdown support.
Args:
text_path: Path to the text file
output_dir: Output directory for the PDF file
Returns:
Path to the generated PDF file
"""
try:
text_path = Path(text_path)
if not text_path.exists():
raise FileNotFoundError(f"Text file does not exist: {text_path}")
# Supported text formats
supported_text_formats = {".txt", ".md"}
if text_path.suffix.lower() not in supported_text_formats:
raise ValueError(f"Unsupported text format: {text_path.suffix}")
# Read the text content
try:
with open(text_path, "r", encoding="utf-8") as f:
text_content = f.read()
except UnicodeDecodeError:
# Try with different encodings
for encoding in ["gbk", "latin-1", "cp1252"]:
try:
with open(text_path, "r", encoding=encoding) as f:
text_content = f.read()
cls.logger.info(
f"Successfully read file with {encoding} encoding"
)
break
except UnicodeDecodeError:
continue
else:
raise RuntimeError(
f"Could not decode text file {text_path.name} with any supported encoding"
)
# Prepare output directory
if output_dir:
base_output_dir = Path(output_dir)
else:
base_output_dir = text_path.parent / "reportlab_output"
base_output_dir.mkdir(parents=True, exist_ok=True)
pdf_path = base_output_dir / f"{text_path.stem}.pdf"
# Convert text to PDF
cls.logger.info(f"Converting {text_path.name} to PDF...")
try:
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
support_chinese = True
try:
if "WenQuanYi" not in pdfmetrics.getRegisteredFontNames():
if not Path(
"/usr/share/fonts/wqy-microhei/wqy-microhei.ttc"
).exists():
support_chinese = False
cls.logger.warning(
"WenQuanYi font not found at /usr/share/fonts/wqy-microhei/wqy-microhei.ttc. Chinese characters may not render correctly."
)
else:
pdfmetrics.registerFont(
TTFont(
"WenQuanYi",
"/usr/share/fonts/wqy-microhei/wqy-microhei.ttc",
)
)
except Exception as e:
support_chinese = False
cls.logger.warning(
f"Failed to register WenQuanYi font: {e}. Chinese characters may not render correctly."
)
# Create PDF document
doc = SimpleDocTemplate(
str(pdf_path),
pagesize=A4,
leftMargin=inch,
rightMargin=inch,
topMargin=inch,
bottomMargin=inch,
)
# Get styles
styles = getSampleStyleSheet()
normal_style = styles["Normal"]
heading_style = styles["Heading1"]
if support_chinese:
normal_style.fontName = "WenQuanYi"
heading_style.fontName = "WenQuanYi"
# Try to register a font that supports Chinese characters
try:
# Try to use system fonts that support Chinese
import platform
system = platform.system()
if system == "Windows":
# Try common Windows fonts
for font_name in ["SimSun", "SimHei", "Microsoft YaHei"]:
try:
from reportlab.pdfbase.cidfonts import (
UnicodeCIDFont,
)
pdfmetrics.registerFont(UnicodeCIDFont(font_name))
normal_style.fontName = font_name
heading_style.fontName = font_name
break
except Exception:
continue
elif system == "Darwin": # macOS
for font_name in ["STSong-Light", "STHeiti"]:
try:
from reportlab.pdfbase.cidfonts import (
UnicodeCIDFont,
)
pdfmetrics.registerFont(UnicodeCIDFont(font_name))
normal_style.fontName = font_name
heading_style.fontName = font_name
break
except Exception:
continue
except Exception:
pass # Use default fonts if Chinese font setup fails
# Build content
story = []
# Handle markdown or plain text
if text_path.suffix.lower() == ".md":
# Handle markdown content - simplified implementation
lines = text_content.split("\n")
for line in lines:
line = line.strip()
if not line:
story.append(Spacer(1, 12))
continue
# Headers
if line.startswith("#"):
level = len(line) - len(line.lstrip("#"))
header_text = line.lstrip("#").strip()
if header_text:
header_style = ParagraphStyle(
name=f"Heading{level}",
parent=heading_style,
fontSize=max(16 - level, 10),
spaceAfter=8,
spaceBefore=16 if level <= 2 else 12,
)
story.append(Paragraph(header_text, header_style))
else:
# Regular text
story.append(Paragraph(line, normal_style))
story.append(Spacer(1, 6))
else:
# Handle plain text files (.txt)
cls.logger.info(
f"Processing plain text file with {len(text_content)} characters..."
)
# Split text into lines and process each line
lines = text_content.split("\n")
line_count = 0
for line in lines:
line = line.rstrip()
line_count += 1
# Empty lines
if not line.strip():
story.append(Spacer(1, 6))
continue
# Regular text lines
# Escape special characters for ReportLab
safe_line = (
line.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
)
# Create paragraph
story.append(Paragraph(safe_line, normal_style))
story.append(Spacer(1, 3))
cls.logger.info(f"Added {line_count} lines to PDF")
# If no content was added, add a placeholder
if not story:
story.append(Paragraph("(Empty text file)", normal_style))
# Build PDF
doc.build(story)
cls.logger.info(
f"Successfully converted {text_path.name} to PDF ({pdf_path.stat().st_size / 1024:.1f} KB)"
)
except ImportError:
raise RuntimeError(
"reportlab is required for text-to-PDF conversion. "
"Please install it using: pip install reportlab"
)
except Exception as e:
raise RuntimeError(
f"Failed to convert text file {text_path.name} to PDF: {str(e)}"
)
# Validate the generated PDF
if not pdf_path.exists() or pdf_path.stat().st_size < 100:
raise RuntimeError(
f"PDF conversion failed for {text_path.name} - generated PDF is empty or corrupted."
)
return pdf_path
except Exception as e:
cls.logger.error(f"Error in convert_text_to_pdf: {str(e)}")
raise
@classmethod
def _process_inline_markdown(cls, text: str) -> str:
"""
Process inline markdown formatting (bold, italic, code, links)
Args:
text: Raw text with markdown formatting
Returns:
Text with ReportLab markup
"""
import re
# Escape special characters for ReportLab
text = text.replace("&", "&").replace("<", "<").replace(">", ">")
# Bold text: **text** or __text__
text = re.sub(r"\*\*(.*?)\*\*", r"<b>\1</b>", text)
text = re.sub(r"__(.*?)__", r"<b>\1</b>", text)
# Italic text: *text* or _text_ (but not in the middle of words)
text = re.sub(r"(?<!\w)\*([^*\n]+?)\*(?!\w)", r"<i>\1</i>", text)
text = re.sub(r"(?<!\w)_([^_\n]+?)_(?!\w)", r"<i>\1</i>", text)
# Inline code: `code`
text = re.sub(
r"`([^`]+?)`",
r'<font name="Courier" size="9" color="darkred">\1</font>',
text,
)
# Links: [text](url) - convert to text with URL annotation
def link_replacer(match):
link_text = match.group(1)
url = match.group(2)
return f'<link href="{url}" color="blue"><u>{link_text}</u></link>'
text = re.sub(r"\[([^\]]+?)\]\(([^)]+?)\)", link_replacer, text)
# Strikethrough: ~~text~~
text = re.sub(r"~~(.*?)~~", r"<strike>\1</strike>", text)
return text
def parse_pdf(
self,
pdf_path: Union[str, Path],
output_dir: Optional[str] = None,
method: str = "auto",
lang: Optional[str] = None,
**kwargs,
) -> List[Dict[str, Any]]:
"""
Abstract method to parse PDF document.
Must be implemented by subclasses.
Args:
pdf_path: Path to the PDF file
output_dir: Output directory path
method: Parsing method (auto, txt, ocr)
lang: Document language for OCR optimization
**kwargs: Additional parameters for parser-specific command
Returns:
List[Dict[str, Any]]: List of content blocks
"""
raise NotImplementedError("parse_pdf must be implemented by subclasses")
def parse_image(
self,
image_path: Union[str, Path],
output_dir: Optional[str] = None,
lang: Optional[str] = None,
**kwargs,
) -> List[Dict[str, Any]]:
"""
Abstract method to parse image document.
Must be implemented by subclasses.
Note: Different parsers may support different image formats.
Check the specific parser's documentation for supported formats.
Args:
image_path: Path to the image file
output_dir: Output directory path
lang: Document language for OCR optimization
**kwargs: Additional parameters for parser-specific command
Returns:
List[Dict[str, Any]]: List of content blocks
"""
raise NotImplementedError("parse_image must be implemented by subclasses")
def parse_document(
self,
file_path: Union[str, Path],
method: str = "auto",
output_dir: Optional[str] = None,
lang: Optional[str] = None,
**kwargs,
) -> List[Dict[str, Any]]:
"""
Abstract method to parse a document.
Must be implemented by subclasses.
Args:
file_path: Path to the file to be parsed
method: Parsing method (auto, txt, ocr)
output_dir: Output directory path
lang: Document language for OCR optimization
**kwargs: Additional parameters for parser-specific command
Returns:
List[Dict[str, Any]]: List of content blocks
"""
raise NotImplementedError("parse_document must be implemented by subclasses")
def check_installation(self) -> bool:
"""
Abstract method to check if the parser is properly installed.
Must be implemented by subclasses.
Returns:
bool: True if installation is valid, False otherwise
"""
raise NotImplementedError(
"check_installation must be implemented by subclasses"
)
class MineruParser(Parser):
"""
MinerU 2.0 document parsing utility class
Supports parsing PDF and image documents, converting the content into structured data
and generating markdown and JSON output.
Note: Office documents are no longer directly supported. Please convert them to PDF first.
"""
__slots__ = ()
# Class-level logger
logger = logging.getLogger(__name__)
def __init__(self) -> None:
"""Initialize MineruParser"""
super().__init__()
@classmethod
def _run_mineru_command(
cls,
input_path: Union[str, Path],
output_dir: Union[str, Path],
method: str = "auto",
lang: Optional[str] = None,
backend: Optional[str] = None,
start_page: Optional[int] = None,
end_page: Optional[int] = None,
formula: bool = True,
table: bool = True,
device: Optional[str] = None,
source: Optional[str] = None,
vlm_url: Optional[str] = None,
) -> None:
"""
Run mineru command line tool
Args:
input_path: Path to input file or directory
output_dir: Output directory path
method: Parsing method (auto, txt, ocr)
lang: Document language for OCR optimization
backend: Parsing backend
start_page: Starting page number (0-based)
end_page: Ending page number (0-based)
formula: Enable formula parsing
table: Enable table parsing
device: Inference device
source: Model source
vlm_url: When the backend is `vlm-http-client`, you need to specify the server_url
"""
cmd = [
"mineru",
"-p",
str(input_path),
"-o",
str(output_dir),
"-m",
method,
]
if backend:
cmd.extend(["-b", backend])
if source:
cmd.extend(["--source", source])
if lang:
cmd.extend(["-l", lang])
if start_page is not None:
cmd.extend(["-s", str(start_page)])
if end_page is not None:
cmd.extend(["-e", str(end_page)])
if not formula:
cmd.extend(["-f", "false"])
if not table:
cmd.extend(["-t", "false"])
if device:
cmd.extend(["-d", device])
if vlm_url:
cmd.extend(["-u", vlm_url])
output_lines = []
error_lines = []
try:
# Prepare subprocess parameters to hide console window on Windows
import platform
import threading
from queue import Queue, Empty
# Log the command being executed
cls.logger.info(f"Executing mineru command: {' '.join(cmd)}")
subprocess_kwargs = {
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"text": True,
"encoding": "utf-8",
"errors": "ignore",
"bufsize": 1, # Line buffered
}
# Hide console window on Windows
if platform.system() == "Windows":
subprocess_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
# Function to read output from subprocess and add to queue
def enqueue_output(pipe, queue, prefix):
try:
for line in iter(pipe.readline, ""):
if line.strip(): # Only add non-empty lines
queue.put((prefix, line.strip()))
pipe.close()
except Exception as e:
queue.put((prefix, f"Error reading {prefix}: {e}"))
# Start subprocess
process = subprocess.Popen(cmd, **subprocess_kwargs)
# Create queues for stdout and stderr
stdout_queue = Queue()
stderr_queue = Queue()
# Start threads to read output
stdout_thread = threading.Thread(
target=enqueue_output, args=(process.stdout, stdout_queue, "STDOUT")
)
stderr_thread = threading.Thread(
target=enqueue_output, args=(process.stderr, stderr_queue, "STDERR")
)
stdout_thread.daemon = True
stderr_thread.daemon = True
stdout_thread.start()
stderr_thread.start()
# Process output in real time
while process.poll() is None:
# Check stdout queue
try:
while True:
prefix, line = stdout_queue.get_nowait()
output_lines.append(line)
# Log mineru output with INFO level, prefixed with [MinerU]
cls.logger.info(f"[MinerU] {line}")
except Empty:
pass
# Check stderr queue
try:
while True:
prefix, line = stderr_queue.get_nowait()
# Log mineru errors with WARNING level
if "warning" in line.lower():
cls.logger.warning(f"[MinerU] {line}")
elif "error" in line.lower():
cls.logger.error(f"[MinerU] {line}")
error_message = line.split("\n")[0]
error_lines.append(error_message)
else:
cls.logger.info(f"[MinerU] {line}")
except Empty:
pass
# Small delay to prevent busy waiting
import time
time.sleep(0.1)
# Process any remaining output after process completion
try:
while True:
prefix, line = stdout_queue.get_nowait()
output_lines.append(line)
cls.logger.info(f"[MinerU] {line}")
except Empty:
pass
try:
while True:
prefix, line = stderr_queue.get_nowait()
if "warning" in line.lower():
cls.logger.warning(f"[MinerU] {line}")
elif "error" in line.lower():
cls.logger.error(f"[MinerU] {line}")
error_message = line.split("\n")[0]
error_lines.append(error_message)
else:
cls.logger.info(f"[MinerU] {line}")
except Empty:
pass
# Wait for process to complete and get return code
return_code = process.wait()
# Wait for threads to finish
stdout_thread.join(timeout=5)
stderr_thread.join(timeout=5)
if return_code != 0 or error_lines:
cls.logger.info("[MinerU] Command executed failed")
raise MineruExecutionError(return_code, error_lines)
else:
cls.logger.info("[MinerU] Command executed successfully")
except MineruExecutionError:
raise
except subprocess.CalledProcessError as e:
cls.logger.error(f"Error running mineru subprocess command: {e}")
cls.logger.error(f"Command: {' '.join(cmd)}")
cls.logger.error(f"Return code: {e.returncode}")
raise
except FileNotFoundError:
raise RuntimeError(
"mineru command not found. Please ensure MinerU 2.0 is properly installed:\n"
"pip install -U 'mineru[core]' or uv pip install -U 'mineru[core]'"
)
except Exception as e:
error_message = f"Unexpected error running mineru command: {e}"
cls.logger.error(error_message)
raise RuntimeError(error_message) from e
@classmethod
def _read_output_files(
cls, output_dir: Path, file_stem: str, method: str = "auto"
) -> Tuple[List[Dict[str, Any]], str]:
"""
Read the output files generated by mineru
Args:
output_dir: Output directory
file_stem: File name without extension
method: Parsing method (used as fallback if subdirectory scan fails)
Returns:
Tuple containing (content list JSON, Markdown text)
"""
# Look for the generated files
md_file = output_dir / f"{file_stem}.md"
json_file = output_dir / f"{file_stem}_content_list.json"
images_base_dir = output_dir # Base directory for images
file_stem_subdir = output_dir / file_stem
if file_stem_subdir.is_dir():
# Scan for actual output subdirectory instead of assuming method name
found = False
for subdir in file_stem_subdir.iterdir():
if not subdir.is_dir():
continue
# Check if this subdirectory contains the expected JSON output file
candidate_json = subdir / f"{file_stem}_content_list.json"
if candidate_json.exists():
# Found the actual output directory
md_file = subdir / f"{file_stem}.md"
json_file = candidate_json
images_base_dir = subdir
found = True
cls.logger.info(
f"Found MinerU output in subdirectory: {subdir.name}"
)
break
# Fallback to method-based path if scanning didn't find output
if not found:
cls.logger.debug(
f"No output found by scanning, falling back to method-based path: {method}"
)
md_file = file_stem_subdir / method / f"{file_stem}.md"
json_file = file_stem_subdir / method / f"{file_stem}_content_list.json"
images_base_dir = file_stem_subdir / method
# Read markdown content
md_content = ""
if md_file.exists():
try:
with open(md_file, "r", encoding="utf-8") as f:
md_content = f.read()
except Exception as e:
cls.logger.warning(f"Could not read markdown file {md_file}: {e}")
# Read JSON content list
content_list = []
if json_file.exists():
try:
with open(json_file, "r", encoding="utf-8") as f:
content_list = json.load(f)
# Always fix relative paths in content_list to absolute paths
cls.logger.info(
f"Fixing image paths in {json_file} with base directory: {images_base_dir}"
)
for item in content_list:
if isinstance(item, dict):
for field_name in [
"img_path",
"table_img_path",
"equation_img_path",
]:
if field_name in item and item[field_name]:
img_path = item[field_name]
absolute_img_path = (
images_base_dir / img_path
).resolve()
item[field_name] = str(absolute_img_path)
cls.logger.debug(
f"Updated {field_name}: {img_path} -> {item[field_name]}"
)
except Exception as e:
cls.logger.warning(f"Could not read JSON file {json_file}: {e}")
return content_list, md_content
def parse_pdf(
self,
pdf_path: Union[str, Path],
output_dir: Optional[str] = None,
method: str = "auto",
lang: Optional[str] = None,
**kwargs,
) -> List[Dict[str, Any]]:
"""
Parse PDF document using MinerU 2.0
Args:
pdf_path: Path to the PDF file
output_dir: Output directory path
method: Parsing method (auto, txt, ocr)
lang: Document language for OCR optimization
**kwargs: Additional parameters for mineru command
Returns:
List[Dict[str, Any]]: List of content blocks
"""
try:
# Convert to Path object for easier handling
pdf_path = Path(pdf_path)
if not pdf_path.exists():
raise FileNotFoundError(f"PDF file does not exist: {pdf_path}")
name_without_suff = pdf_path.stem
# Prepare output directory
if output_dir:
base_output_dir = Path(output_dir)
else:
base_output_dir = pdf_path.parent / "mineru_output"
base_output_dir.mkdir(parents=True, exist_ok=True)
# Run mineru command
self._run_mineru_command(
input_path=pdf_path,
output_dir=base_output_dir,
method=method,
lang=lang,
**kwargs,
)
# Read the generated output files
# Map backend to expected output directory name for better compatibility
# MinerU 2.7.0+ uses different directory names based on backend:
# - pipeline -> auto/
# - vlm-* -> vlm/
# - hybrid-* -> hybrid_auto/
# Note: _read_output_files() will scan subdirectories automatically,
# so this mapping is just for optimization and fallback
# Use `or ""` to handle both missing keys and explicit None values
backend = kwargs.get("backend") or ""
if backend.startswith("vlm-"):
method = "vlm"
elif backend.startswith("hybrid-"):
method = "hybrid_auto"
content_list, _ = self._read_output_files(
base_output_dir, name_without_suff, method=method