Apug98 commited on
Commit
f656538
·
verified ·
1 Parent(s): a7e0279

Create parsing/parse_rulebook.py

Browse files
Files changed (1) hide show
  1. parsing/parse_rulebook.py +46 -0
parsing/parse_rulebook.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ from docling.document_converter import DocumentConverter, PdfFormatOption
4
+ from docling.datamodel.base_models import InputFormat
5
+ from docling.datamodel.pipeline_options import PdfPipelineOptions, RapidOcrOptions
6
+
7
+ # Assumes this file lives at <repo_root>/parsing/parse_rulebook.py
8
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
9
+ RULEBOOK_DIR = PROJECT_ROOT / "rulebooks"
10
+
11
+ OUTPUT_DIR = PROJECT_ROOT / "parsed"
12
+ OUTPUT_DIR.mkdir(exist_ok=True)
13
+
14
+ def parse(file_name: str, out_name: str, ocr = False):
15
+
16
+ pdf_path = RULEBOOK_DIR / file_name
17
+ output_file = OUTPUT_DIR / f"{out_name}.md"
18
+
19
+ if not pdf_path.exists():
20
+ raise FileNotFoundError(f"Could not find {pdf_path}")
21
+
22
+ pipeline_options = PdfPipelineOptions()
23
+ pipeline_options.do_ocr = ocr
24
+
25
+ if ocr:
26
+ pipeline_options.ocr_options = RapidOcrOptions(
27
+ lang=["english"],
28
+ force_full_page_ocr=True,
29
+ backend="onnxruntime",
30
+ )
31
+ converter = DocumentConverter(
32
+ format_options={
33
+ InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)
34
+ }
35
+ )
36
+
37
+ doc = converter.convert(str(pdf_path)).document
38
+
39
+ markdown = doc.export_to_markdown()
40
+
41
+ with open(output_file, "w", encoding = "utf-8" ) as f:
42
+ f.write(markdown)
43
+
44
+ print(f"Saved parsed rulebook to {output_file}")
45
+
46
+ return output_file