4 from watchdog.observers import Observer
5 from watchdog.events import FileSystemEventHandler, FileSystemEvent
6 from pathlib import Path
7 from typing import Union
8 from filelock import Timeout, FileLock
10 from logging import error, info, debug, warning
14 class ScannerWorkflowEvent(FileSystemEventHandler):
15 """Subclass of FileSystemEventHandler to handle OCRing PDFs"""
17 scanner_workflow = None
19 def __init__(self, scanner_workflow=None):
21 self.scanner_workflow = scanner_workflow
22 if not self.scanner_workflow:
23 raise Error("No scanner_workflow passed to ScannerWorkflowEvent")
25 def on_closed(self, event: FileSystemEvent):
26 if event.is_directory:
28 if not event.src_path.endswith(".pdf"):
30 self.scanner_workflow.process_pdf(event.src_path)
33 class ScannerWorkflow:
40 ocrmypdf_opts = ["-r", "-q", "--deskew", "--clean"]
44 base_dir: Union[Path, str] = ".",
45 input_dir: Union[Path, str] = "input",
46 output_dir: Union[Path, str] = "output",
47 failure_dir: Union[Path, str] = "failure",
48 process_dir: Union[Path, str] = "process",
49 lock_file: Union[Path, str] = ".lock",
51 def concat_if_not_abs(dir1: Path, dir2: Path):
52 if dir2.is_absolute():
58 self.base_dir = Path(base_dir)
59 self.input_dir = concat_if_not_abs(self.base_dir, Path(input_dir))
60 self.output_dir = concat_if_not_abs(self.base_dir, Path(output_dir))
61 self.failure_dir = concat_if_not_abs(self.base_dir, Path(failure_dir))
62 self.process_dir = concat_if_not_abs(self.base_dir, Path(process_dir))
63 self.lock_file = concat_if_not_abs(self.base_dir, Path(lock_file))
64 self.lock = FileLock(self.lock_file)
65 self.base_dir.mkdir(parents=True, exist_ok=True)
66 self.input_dir.mkdir(parents=True, exist_ok=True)
67 self.failure_dir.mkdir(parents=True, exist_ok=True)
68 self.process_dir.mkdir(parents=True, exist_ok=True)
69 self.output_dir.mkdir(parents=True, exist_ok=True)
71 def calculate_name(self, name: str):
73 r"(?P<scanner>[^_]+)_(?P<month>\d{2})(?P<day>\d{2})(?P<year>\d{4})_"
74 r"(?P<time>\d+)_(?P<counter>\d+)\.pdf",
79 f"{res.group('scanner')}_"
80 f"{res.group('year')}{res.group('month')}{res.group('day')}_"
81 f"{res.group('time')}_{res.group('counter')}.pdf"
85 def process_pdf(self, pdf_file: Union[Path, str]):
86 """Process a single PDF."""
87 pdf_file = Path(pdf_file)
89 # move to the processing directory
90 pdf_file = pdf_file.rename(
91 self.process_dir / self.calculate_name(pdf_file.name)
93 output_file = self.output_dir / pdf_file.name
94 res = subprocess.run(["ocrmypdf", *self.ocrmypdf_opts, pdf_file, output_file])
95 if res.returncode != 0:
96 error(f"Unable to properly OCR pdf: {res.stdout} {res.stderr}")
99 info("Processed {orig_pdf} into {output_file}")
101 def event_loop(self):
102 """Main event loop; called from the command line."""
103 ev = ScannerWorkflowEvent(scanner_workflow=self)
104 observer = Observer()
105 observer.schedule(ev, self.input_dir, recursive=True)
107 # process any PDFs in input_dir
108 for file in self.input_dir.iterdir():
109 self.process_pdf(file)
111 while observer.is_alive():
123 help="Directory to look for incoming PDFs",
129 help="Directory to store PDFs being processed",
135 help="Directory to output OCRed PDFs",
141 help="Directory to store failed PDFs",
147 help="Base directory",
153 help="Lock file to ensure only one instance is running",
155 def cli(input_dir, process_dir, output_dir, failure_dir, base_dir, lock_file):
156 """OCR scanner output and save in directory"""
157 sw = ScannerWorkflow(
159 process_dir=process_dir,
160 output_dir=output_dir,
161 failure_dir=failure_dir,
166 with sw.lock.acquire(timeout=10):
169 print("Another instance holds the lock")