Repository navigation
Expand file tree
/
Copy pathStep13-ConvertToFullText.py
More file actions
1517 lines (1165 loc) · 41.9 KB
/
Copy pathStep13-ConvertToFullText.py
File metadata and controls
1517 lines (1165 loc) · 41.9 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
#!/usr/bin/env python3
"""
================================================================================
Step 5: Article Text Extractor / Full-Text Converter
PROJECT-AWARE + INDEX-AWARE VERSION
PURPOSE
-------
Run this AFTER the PDF download step.
This script scans the database folder, finds article folders containing PDFs,
validates each PDF, then extracts:
1) PDF main text
2) embedded figures/images
3) OCR text from figures/images
4) combined Article_Text.txt / COMBINED.txt
NEW INDEX MODE
--------------
Convert one article by Temp index:
python Step5-FullTextConversion.py --index 25
Convert one article by Temp index inside a specific project:
python Step5-FullTextConversion.py --project project_folder_name --index 25
Convert one article by global discovered index:
python Step5-FullTextConversion.py --global-index 10
Show available indices:
python Step5-FullTextConversion.py --list-indices
Convert a Temp index range:
python Step5-FullTextConversion.py --start-index 0 --end-index 100
Force reprocess selected articles:
python Step5-FullTextConversion.py --index 25 --reset
Change DB folder:
python Step5-FullTextConversion.py --db DataBase_Strategy3_Top1000 --index 25
OUTPUT PER ARTICLE FOLDER
-------------------------
full_text.txt
figures/
figures_ocr.txt
COMBINED.txt
Article_Text.txt
extraction_metadata.json
GLOBAL OUTPUT
-------------
DataBase/extraction_summary.csv
DataBase/pdf_validation_summary.csv
================================================================================
"""
from __future__ import annotations
import os
import sys
import re
import json
import csv
import time
import logging
import threading
import traceback
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from datetime import datetime
# ============================================================
# CONFIGURATION
# ============================================================
DB_DIR = "DataBase_Strategy3_Top1000"
_RESET = False
MAX_WORKERS = 8
SAVE_EVERY = 25
# PDF validation
VALIDATE_WITH_PYPDF = True
REQUIRE_PYPDF_VALIDATION = True
QUARANTINE_BAD_PDFS = False
MIN_PDF_SIZE = 4
# Tesseract
TESSERACT_CMD = ""
TESSERACT_LANG = "eng"
TESSERACT_PSM = 6
# Image filters
MIN_IMAGE_WIDTH = 100
MIN_IMAGE_HEIGHT = 100
# Text quality
MIN_USEFUL_WORDS = 50
# Thread-safe progress
_progress_lock = threading.Lock()
_progress_done = 0
# Dependency status
_PYPDF_AVAILABLE = False
_PYMUPDF_AVAILABLE = False
_TESSERACT_AVAILABLE = None
# PDF validation rows
_pdf_validation_rows = []
_pdf_validation_lock = threading.Lock()
# ============================================================
# LOGGING
# ============================================================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
log = logging.getLogger("Step5FullTextConverter")
# ============================================================
# BASIC UTILITY
# ============================================================
def clean(value) -> str:
s = str(value).strip()
return "" if s.lower() in ("nan", "none", "", "n/a") else s
def natural_sort_key(path: Path):
return [
int(part) if part.isdigit() else part.lower()
for part in re.split(r"(\d+)", path.name)
]
def _clean_text(text: str) -> str:
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def _remove_references(text: str) -> str:
"""
Remove reference section from extracted main text.
This prevents references from dominating downstream full-text QA/ranking.
"""
if not text:
return ""
patterns = [
r"\n\s*References\s*\n",
r"\n\s*Bibliography\s*\n",
r"\n\s*Works Cited\s*\n",
r"\n\s*Literature Cited\s*\n",
]
for pat in patterns:
matches = list(re.finditer(pat, text, re.IGNORECASE))
if matches:
# Use the last/late occurrence only if it appears after some article body.
for m in matches:
if m.start() > len(text) * 0.35:
return text[:m.start()].strip()
return text.strip()
def _safe_read_json(path: Path) -> dict:
if not path.exists():
return {}
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {}
def _safe_file_size(path: Path) -> int:
try:
return path.stat().st_size
except Exception:
return 0
def _read_header(path: Path, n: int = 20) -> bytes:
try:
with open(path, "rb") as fh:
return fh.read(n)
except Exception:
return b""
def _temp_index_from_folder(folder: Path) -> int | None:
m = re.match(r"^Temp_(\d+)$", folder.name)
if not m:
return None
return int(m.group(1))
# ============================================================
# DEPENDENCY CHECKS
# ============================================================
def check_dependencies() -> dict:
global _PYPDF_AVAILABLE, _PYMUPDF_AVAILABLE
status = {}
try:
import pypdf
from pypdf import PdfReader # noqa
_PYPDF_AVAILABLE = True
status["pypdf"] = {
"ok": True,
"version": getattr(pypdf, "__version__", "unknown"),
"error": "",
}
log.info(f" ✓ pypdf ({status['pypdf']['version']})")
except Exception as e:
_PYPDF_AVAILABLE = False
status["pypdf"] = {
"ok": False,
"version": "",
"error": str(e),
}
log.warning(f" ✗ pypdf not installed/working: {e}")
try:
import fitz # noqa
_PYMUPDF_AVAILABLE = True
status["fitz"] = {
"ok": True,
"version": "installed",
"error": "",
}
log.info(" ✓ PyMuPDF / fitz")
except Exception as e:
_PYMUPDF_AVAILABLE = False
status["fitz"] = {
"ok": False,
"version": "",
"error": str(e),
}
log.warning(f" ✗ PyMuPDF / fitz not installed: {e}")
try:
import pytesseract # noqa
status["pytesseract"] = {
"ok": True,
"version": "installed",
"error": "",
}
log.info(" ✓ pytesseract")
except Exception as e:
status["pytesseract"] = {
"ok": False,
"version": "",
"error": str(e),
}
log.warning(f" ✗ pytesseract not installed: {e}")
try:
import PIL # noqa
status["PIL"] = {
"ok": True,
"version": "installed",
"error": "",
}
log.info(" ✓ Pillow")
except Exception as e:
status["PIL"] = {
"ok": False,
"version": "",
"error": str(e),
}
log.warning(f" ✗ Pillow not installed: {e}")
return status
def _check_tesseract() -> bool:
global _TESSERACT_AVAILABLE
if _TESSERACT_AVAILABLE is not None:
return _TESSERACT_AVAILABLE
try:
import pytesseract
if TESSERACT_CMD:
pytesseract.pytesseract.tesseract_cmd = TESSERACT_CMD
version = pytesseract.get_tesseract_version()
_TESSERACT_AVAILABLE = True
log.info(f" Tesseract ready ({version})")
except ImportError:
log.warning(" pytesseract not installed")
_TESSERACT_AVAILABLE = False
except Exception as e:
log.warning(f" Tesseract not available: {e}")
_TESSERACT_AVAILABLE = False
return _TESSERACT_AVAILABLE
# ============================================================
# PDF VALIDATION
# ============================================================
def validate_pdf_with_pypdf(pdf_path: Path) -> dict:
result = {
"pdf_path": str(pdf_path),
"exists": False,
"size_bytes": 0,
"header": "",
"header_ok": False,
"pypdf_available": _PYPDF_AVAILABLE,
"pypdf_ok": False,
"page_count": 0,
"valid": False,
"error": "",
}
try:
if not pdf_path.exists():
result["error"] = "file does not exist"
return result
result["exists"] = True
result["size_bytes"] = _safe_file_size(pdf_path)
if result["size_bytes"] < MIN_PDF_SIZE:
result["error"] = f"file too small: {result['size_bytes']} bytes"
return result
header = _read_header(pdf_path, 20)
result["header"] = repr(header)
result["header_ok"] = header.startswith(b"%PDF")
if not result["header_ok"]:
result["error"] = f"not a PDF header: {repr(header[:20])}"
return result
if not VALIDATE_WITH_PYPDF:
result["valid"] = True
return result
if not _PYPDF_AVAILABLE:
if REQUIRE_PYPDF_VALIDATION:
result["error"] = "pypdf not available"
return result
result["valid"] = True
return result
from pypdf import PdfReader
reader = PdfReader(str(pdf_path))
page_count = len(reader.pages)
result["page_count"] = page_count
if page_count <= 0:
result["error"] = "pypdf opened file but found 0 pages"
return result
_ = reader.pages[0]
result["pypdf_ok"] = True
result["valid"] = True
return result
except Exception as e:
result["error"] = repr(e)
return result
def quarantine_bad_pdf(pdf_path: Path, reason: str) -> Path | None:
if not pdf_path.exists():
return None
bad_path = pdf_path.with_name(
f"{pdf_path.stem}.bad_pdf_validation_"
f"{datetime.now().strftime('%Y%m%d_%H%M%S')}"
f"{pdf_path.suffix}"
)
try:
pdf_path.rename(bad_path)
log.warning(f" Bad PDF moved aside: {bad_path} ({reason})")
return bad_path
except Exception as e:
log.warning(f" Could not quarantine bad PDF: {pdf_path} ({e})")
return None
def record_pdf_validation(
project_name: str,
folder: Path,
pdf_path: Path,
validation: dict,
):
row = dict(validation)
row.update({
"project_name": project_name,
"article_folder": folder.name,
"temp_index": _temp_index_from_folder(folder),
})
with _pdf_validation_lock:
_pdf_validation_rows.append(row)
def save_pdf_validation_summary(db_dir: str):
out_csv = Path(db_dir) / "pdf_validation_summary.csv"
fields = [
"project_name",
"article_folder",
"temp_index",
"pdf_path",
"exists",
"size_bytes",
"header",
"header_ok",
"pypdf_available",
"pypdf_ok",
"page_count",
"valid",
"error",
]
try:
rows = list(_pdf_validation_rows)
with open(out_csv, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fields)
writer.writeheader()
for r in rows:
writer.writerow({k: r.get(k, "") for k in fields})
log.info(f" Saved PDF validation summary: {out_csv}")
except Exception as e:
log.error(f" Could not save PDF validation summary: {e}")
# ============================================================
# DISCOVERY
# ============================================================
def _find_pdf(folder: Path) -> Path | None:
"""
Find a likely PDF in one article folder.
Priority:
1) document.pdf
2) any .pdf with %PDF header
"""
doc_pdf = folder / "document.pdf"
if doc_pdf.exists():
header = _read_header(doc_pdf, 4)
if header == b"%PDF":
return doc_pdf
try:
files = sorted(folder.iterdir(), key=lambda x: x.name.lower())
except Exception:
return None
for f in files:
if f.is_file() and f.suffix.lower() == ".pdf":
header = _read_header(f, 4)
if header == b"%PDF":
return f
return None
def _discover_article_folders(db_path: Path) -> list[tuple[Path, Path, str]]:
"""
Returns list of:
(article_folder, pdf_path, project_name)
Supports:
DataBase/<project>/Temp_x/
DataBase/Temp_x/
"""
found = []
if not db_path.exists():
return found
for item in sorted(db_path.iterdir(), key=natural_sort_key):
if not item.is_dir():
continue
if item.name.startswith("_"):
continue
# Legacy single-level:
# DataBase/Temp_0/document.pdf
if re.match(r"^Temp_\d+$", item.name):
pdf = _find_pdf(item)
if pdf:
found.append((item, pdf, "legacy"))
continue
# Project-aware:
# DataBase/<project>/Temp_0/document.pdf
try:
subs = sorted(item.iterdir(), key=natural_sort_key)
except Exception:
continue
for sub in subs:
if sub.is_dir() and re.match(r"^Temp_\d+$", sub.name):
pdf = _find_pdf(sub)
if pdf:
found.append((sub, pdf, item.name))
return found
def _filter_papers_by_index(
papers: list[tuple[Path, Path, str]],
project: str = "",
index: int | None = None,
start_index: int | None = None,
end_index: int | None = None,
global_index: int | None = None,
) -> list[tuple[Path, Path, str]]:
"""
--index refers to Temp_X index.
--global-index refers to sorted discovered position, 1-based.
"""
selected = list(papers)
project = clean(project)
if project:
selected = [
x for x in selected
if x[2] == project
or project.lower() in x[2].lower()
]
if global_index is not None:
gi = int(global_index)
if gi < 1 or gi > len(selected):
log.error(f" --global-index {gi} is outside valid range 1..{len(selected)}")
return []
return [selected[gi - 1]]
if index is not None:
ti = int(index)
return [
x for x in selected
if _temp_index_from_folder(x[0]) == ti
]
if start_index is not None or end_index is not None:
si = 0 if start_index is None else int(start_index)
ei = 10**18 if end_index is None else int(end_index)
return [
x for x in selected
if _temp_index_from_folder(x[0]) is not None
and si <= _temp_index_from_folder(x[0]) <= ei
]
return selected
def _print_index_preview(
papers: list[tuple[Path, Path, str]],
max_rows: int = 300,
):
log.info("")
log.info("=" * 120)
log.info("DISCOVERED PDF ARTICLES")
log.info("=" * 120)
log.info(
f"{'GLOBAL':>8} "
f"{'TEMP_IDX':>8} "
f"{'PROJECT':<55} "
f"{'FOLDER':<15} "
f"PDF"
)
log.info("-" * 120)
for global_i, (folder, pdf_path, project_name) in enumerate(papers, 1):
temp_i = _temp_index_from_folder(folder)
temp_s = "" if temp_i is None else str(temp_i)
log.info(
f"{global_i:>8} "
f"{temp_s:>8} "
f"{project_name[:55]:<55} "
f"{folder.name:<15} "
f"{pdf_path.name}"
)
if global_i >= max_rows and len(papers) > max_rows:
log.info(f"... showing first {max_rows}/{len(papers)} only")
break
log.info("=" * 120)
log.info("")
# ============================================================
# PDF TEXT EXTRACTION — PyMuPDF
# ============================================================
def extract_text_pymupdf(pdf_path: Path, out_folder: Path) -> str:
import fitz
txt_out = out_folder / "full_text.txt"
if txt_out.exists() and txt_out.stat().st_size > 100 and not _RESET:
log.info(" full_text.txt already exists, loading...")
return txt_out.read_text(encoding="utf-8", errors="ignore")
log.info(" [TEXT] PyMuPDF text extraction...")
try:
doc = fitz.open(str(pdf_path))
pages_text = []
for page_i, page in enumerate(doc, 1):
try:
page_text = page.get_text("text")
except Exception as e:
log.debug(f" Page {page_i} text error: {e}")
page_text = ""
if page_text and page_text.strip():
pages_text.append(page_text)
doc.close()
full_text = "\n\n".join(pages_text)
full_text = _clean_text(full_text)
word_count = len(full_text.split())
if word_count < MIN_USEFUL_WORDS:
log.warning(f" Only {word_count} words extracted, possibly scanned PDF")
txt_out.write_text(full_text, encoding="utf-8")
log.info(
f" Saved full_text.txt "
f"({len(full_text):,} chars / {word_count:,} words)"
)
return full_text
except Exception as e:
log.error(f" PyMuPDF text error: {e}")
log.debug(traceback.format_exc())
return ""
# ============================================================
# FIGURE EXTRACTION — PyMuPDF
# ============================================================
def extract_figures(pdf_path: Path, out_folder: Path) -> list[dict]:
import fitz
log.info(" [FIGS] Extracting figures...")
figures_dir = out_folder / "figures"
figures_dir.mkdir(exist_ok=True)
extracted = []
try:
doc = fitz.open(str(pdf_path))
total = 0
skipped = 0
for page_num, page in enumerate(doc):
try:
images = page.get_images(full=True)
except Exception as e:
log.debug(f" Could not get images on page {page_num + 1}: {e}")
continue
for img_idx, img_info in enumerate(images):
xref = img_info[0]
try:
base_image = doc.extract_image(xref)
img_bytes = base_image["image"]
img_ext = base_image.get("ext", "png")
width = base_image.get("width", 0)
height = base_image.get("height", 0)
if width < MIN_IMAGE_WIDTH or height < MIN_IMAGE_HEIGHT:
skipped += 1
continue
fname = f"fig_p{page_num + 1:03d}_img{img_idx:02d}.{img_ext}"
fpath = figures_dir / fname
if fpath.exists() and fpath.stat().st_size > 0 and not _RESET:
extracted.append({
"path": fpath,
"page": page_num + 1,
"width": width,
"height": height,
"fname": fname,
})
total += 1
continue
with open(fpath, "wb") as f:
f.write(img_bytes)
extracted.append({
"path": fpath,
"page": page_num + 1,
"width": width,
"height": height,
"fname": fname,
})
total += 1
except Exception as img_err:
log.debug(f" xref {xref} error: {img_err}")
doc.close()
log.info(f" {total} figures extracted/available ({skipped} tiny images skipped)")
except Exception as e:
log.error(f" Figure extraction error: {e}")
log.debug(traceback.format_exc())
return extracted
# ============================================================
# OCR — Tesseract
# ============================================================
def _ocr_tesseract(image_path: Path) -> str:
if not _check_tesseract():
return ""
try:
import pytesseract
from PIL import Image
except ImportError:
return ""
if TESSERACT_CMD:
pytesseract.pytesseract.tesseract_cmd = TESSERACT_CMD
try:
img = Image.open(str(image_path)).convert("L")
config = f"--oem 3 --psm {TESSERACT_PSM} -l {TESSERACT_LANG}"
text = pytesseract.image_to_string(img, config=config).strip()
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
except Exception as e:
log.debug(f" Tesseract error on {image_path.name}: {e}")
return ""
def extract_figures_ocr(figures: list[dict], out_folder: Path) -> str:
ocr_out = out_folder / "figures_ocr.txt"
if ocr_out.exists() and ocr_out.stat().st_size > 50 and not _RESET:
log.info(" [OCR] figures_ocr.txt already exists, loading...")
return ocr_out.read_text(encoding="utf-8", errors="ignore")
if not figures:
log.info(" [OCR] No figures to OCR.")
ocr_out.write_text("", encoding="utf-8")
return ""
log.info(f" [OCR] Tesseract on {len(figures)} figures...")
ocr_lines = []
success = 0
for fig in figures:
text = _ocr_tesseract(fig["path"])
ocr_lines.append(
f"-- {fig['fname']} "
f"(p{fig['page']}, {fig['width']}x{fig['height']}px) --"
)
if text:
ocr_lines.append(text[:5000])
success += 1
else:
ocr_lines.append("[no text detected]")
ocr_lines.append("")
ocr_full = "\n".join(ocr_lines).strip()
ocr_out.write_text(ocr_full, encoding="utf-8")
log.info(f" OCR done — {success}/{len(figures)} figures had text")
return ocr_full
# ============================================================
# COMBINE OUTPUTS
# ============================================================
def combine_outputs(
out_folder: Path,
main_text: str,
ocr_text: str,
folder_name: str,
pdf_path: Path,
) -> str:
combined_out = out_folder / "COMBINED.txt"
article_out = out_folder / "Article_Text.txt"
metadata = _safe_read_json(out_folder / "metadata.json")
title = clean(metadata.get("title", ""))
doi = clean(metadata.get("doi", ""))
sections = []
sections.append("=" * 80)
sections.append(f"ARTICLE FOLDER: {folder_name}")
sections.append(f"PDF FILE : {pdf_path.name}")
if title:
sections.append(f"TITLE : {title}")
if doi:
sections.append(f"DOI : {doi}")
sections.append(f"EXTRACTED AT : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
sections.append("=" * 80)
sections.append("")
sections.append("MAIN PDF TEXT")
sections.append("-" * 80)
if main_text:
sections.append(_remove_references(main_text))
else:
sections.append("[Text extraction failed or empty PDF text]")
if ocr_text:
sections.append("")
sections.append("=" * 80)
sections.append("FIGURE OCR TEXT")
sections.append("-" * 80)
sections.append(ocr_text)
full = "\n".join(sections).strip() + "\n"
combined_out.write_text(full, encoding="utf-8")
article_out.write_text(full, encoding="utf-8")
return full
# ============================================================
# METADATA
# ============================================================
def write_extraction_metadata(
paper_folder: Path,
project_name: str,
pdf_path: Path,
result: dict,
pdf_validation: dict | None = None,
) -> None:
meta_path = paper_folder / "extraction_metadata.json"
existing = _safe_read_json(paper_folder / "metadata.json")
payload = {
"project_name": project_name,
"article_folder": paper_folder.name,
"temp_index": _temp_index_from_folder(paper_folder),
"pdf_file": pdf_path.name,
"extracted_at": datetime.now().isoformat(timespec="seconds"),
"status": result.get("status", ""),
"text_chars": result.get("text_chars", 0),
"figures": result.get("figures", 0),
"ocr_figures": result.get("ocr_figures", 0),
"pdf_valid": result.get("pdf_valid", False),
"pdf_pages": result.get("pdf_pages", 0),
"error": result.get("error", ""),
"pdf_validation": pdf_validation or {},
"base_metadata": existing,
}
meta_path.write_text(
json.dumps(payload, indent=2, ensure_ascii=False),
encoding="utf-8",
)
# ============================================================
# PROCESS ONE PAPER
# ============================================================
def process_paper(
paper_folder: Path,
pdf_path: Path,
project_name: str,
) -> dict:
folder_name = paper_folder.name
result = {
"project_name": project_name,
"folder": folder_name,
"temp_index": _temp_index_from_folder(paper_folder),
"pdf": pdf_path.name,
"status": "FAILED",
"text_chars": 0,
"figures": 0,
"ocr_figures": 0,
"error": "",
"pdf_valid": False,
"pdf_pages": 0,
}
validation = validate_pdf_with_pypdf(pdf_path)
result["pdf_valid"] = bool(validation.get("valid", False))
result["pdf_pages"] = int(validation.get("page_count", 0) or 0)
record_pdf_validation(project_name, paper_folder, pdf_path, validation)
if not validation["valid"]:
result["status"] = "BAD_PDF"
result["error"] = validation.get("error", "invalid PDF")
log.warning(
f" BAD PDF: {project_name}/{folder_name}/{pdf_path.name} | "
f"{result['error']}"
)
if QUARANTINE_BAD_PDFS:
quarantine_bad_pdf(pdf_path, result["error"])
write_extraction_metadata(
paper_folder,
project_name,
pdf_path,
result,
pdf_validation=validation,
)
return result