File size: 6,714 Bytes
7527970 |
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 |
#!/usr/bin/env env python3
import argparse
import json
import os
import shutil
import sys
import tempfile
from pathlib import Path
try:
from grobid_client.grobid_client import GrobidClient
except ImportError:
print("Error: grobid-client-python is not installed.")
print("Please install it with: pip install grobid-client-python")
sys.exit(1)
def process_pdfs_with_grobid(
input_folder: str,
output_folder: str,
config_path: str | None = None,
):
"""
Process all PDF files in the input folder with GROBID and save TEI XML to output folder.
Args:
input_folder: Path to folder containing PDF files
output_folder: Path to folder where XML files will be saved
config_path: Path to GROBID client configuration file
"""
# Validate input folder
if not os.path.exists(input_folder):
print(f"Error: Input folder '{input_folder}' does not exist.")
sys.exit(1)
if not os.path.isdir(input_folder):
print(f"Error: '{input_folder}' is not a directory.")
sys.exit(1)
# Create output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
# Find all PDF files in input folder
pdf_files = list(Path(input_folder).glob("*.pdf"))
pdf_files.extend(list(Path(input_folder).glob("*.PDF")))
valid_pdf_files = []
for pdf_file in pdf_files:
if not pdf_file.exists():
print(f"Warning: skipping missing/broken PDF path: {pdf_file}")
continue
valid_pdf_files.append(pdf_file)
pdf_files = valid_pdf_files
if not pdf_files:
print(f"No PDF files found in '{input_folder}'")
return
print(f"Found {len(pdf_files)} PDF file(s) to process")
# Initialize GROBID client
temp_config_path = None
try:
if config_path and os.path.exists(config_path):
client = GrobidClient(config_path=config_path)
else:
default_config = {
"grobid_server": "http://localhost:8070",
"batch_size": 1000,
"sleep_time": 5,
"timeout": 60,
}
temp_handle = tempfile.NamedTemporaryFile(
mode="w",
suffix=".json",
delete=False,
)
json.dump(default_config, temp_handle)
temp_handle.close()
temp_config_path = temp_handle.name
client = GrobidClient(config_path=temp_config_path)
except Exception as e:
print(f"Error initializing GROBID client: {e}")
if config_path:
print(f"Make sure the config file exists at '{config_path}'")
else:
print("Provide --config config.json if required.")
sys.exit(1)
# Create temporary directories for processing
temp_input_dir = tempfile.mkdtemp()
temp_output_dir = tempfile.mkdtemp()
try:
# Copy PDFs to temporary input directory
print("\nPreparing files for processing...")
for pdf_file in pdf_files:
pdf_filename = os.path.basename(pdf_file)
temp_pdf_path = os.path.join(temp_input_dir, pdf_filename)
shutil.copy2(pdf_file, temp_pdf_path)
print(f" - {pdf_filename}")
# Process with GROBID
print(f"\nProcessing {len(pdf_files)} PDF(s) with GROBID...")
print(
"This may take a while depending on the number and size of files...",
)
client.process(
"processFulltextDocument",
temp_input_dir,
output=temp_output_dir,
)
# Copy results to output folder
print("\nSaving results...")
processed_count = 0
failed_count = 0
for pdf_file in pdf_files:
pdf_filename = os.path.basename(pdf_file)
# Expected output filename from GROBID
output_filename = (
f"{os.path.splitext(pdf_filename)[0]}.grobid.tei.xml"
)
temp_output_path = os.path.join(temp_output_dir, output_filename)
if os.path.exists(temp_output_path):
# Copy to final output directory
final_output_path = os.path.join(
output_folder,
output_filename,
)
shutil.copy2(temp_output_path, final_output_path)
print(f" ✓ {pdf_filename} -> {output_filename}")
processed_count += 1
else:
print(
f" ✗ {pdf_filename} - Processing failed (no output generated)",
)
failed_count += 1
# Summary
print(f"\n{'=' * 60}")
print("Processing complete!")
print(f"Successfully processed: {processed_count}/{len(pdf_files)}")
if failed_count > 0:
print(f"Failed: {failed_count}/{len(pdf_files)}")
print(f"Output saved to: {os.path.abspath(output_folder)}")
print(f"{'=' * 60}")
except Exception as e:
print(f"\nError during processing: {e}")
sys.exit(1)
finally:
# Clean up temporary directories
shutil.rmtree(temp_input_dir, ignore_errors=True)
shutil.rmtree(temp_output_dir, ignore_errors=True)
if temp_config_path and os.path.exists(temp_config_path):
try:
os.remove(temp_config_path)
except OSError:
pass
def main():
"""Main entry point for the script."""
parser = argparse.ArgumentParser(
description="Process PDF files with GROBID and extract TEI XML",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python grobid_batch_processor.py --input_path ./pdfs --output_path ./output
python grobid_batch_processor.py --input_path ./pdfs --output_path ./output --config ./my_config.json
Note: Make sure GROBID server is running before executing this script.
See: https://grobid.readthedocs.io/en/latest/Grobid-service/
""",
)
parser.add_argument(
"--input_folder",
help="Path to folder containing PDF files to process",
)
parser.add_argument(
"--output_folder",
help="Path to folder where XML output files will be saved",
)
parser.add_argument(
"--config",
default=None,
help="Path to GROBID client configuration file (optional).",
)
args = parser.parse_args()
print("=" * 60)
print("GROBID Batch PDF Processor")
print("=" * 60)
process_pdfs_with_grobid(
args.input_folder,
args.output_folder,
args.config,
)
if __name__ == "__main__":
main()
|