Files
pdf-ocr-hotfolder/pdf_ocr_hotfolder/__main__.py
T
techadmin aa9918adba fix: ocrmypdf-Pin auf 17.4.1, Preflight erkennt den GS-Fall, Rauchtest (v0.6.1)
v0.6.0 hat ocrmypdf auf 16.13.0 gepinnt, um einen ungewollten Major-Sprung
zu verhindern. Auf Bestandsinstallationen war das ein DOWNGRADE (dort lief
via ">=16.0" bereits 17.x) — und 16.13.0 bricht auf Debian 12 mit dem
Bord-Ghostscript 10.0.0 bei JEDER PDF ab, sobald skip_text gesetzt ist.
Im Test auf CT 200 lief das Update mit Exit 0 durch, der Dienst blieb
"active", --check-config meldete "Preflight ok" — und jede Datei landete
in error/. Stiller Totalausfall.

- requirements.txt: ocrmypdf==17.4.1 (real auf Debian 12 + gs 10.0.0
  verifiziert). Ab 17.0.0 steht die GS-Pruefung in ocrmypdf unter einem
  `if options.output_type.startswith('pdfa')`; bis 16.x lief sie ohne
  diesen Guard und schlug auch bei output_type="pdf" zu.
- check_preflight() prueft Ghostscript nicht mehr nur bei gesetztem
  pdfa_level, sondern bildet die reale Bedingung ab:
  betroffene GS-Version UND skip_text UND (PDF/A ODER ocrmypdf < 17).
  Der Dienst bricht damit beim Start ab statt bei der ersten Datei.
- update.sh zeigt Versionsspruenge der gepinnten Pakete; Downgrades als
  WARN, auch in der Abschluss-Zusammenfassung.
- update.sh faehrt nach dem Start einen Rauchtest (eingebettete Mini-PDF
  durch die echte Pipeline) und raeumt restlos auf. Uebersprungen, wenn
  Upload-Ziele oder E-Mail-Notify aktiv sind, damit kein Testmuell zum
  Kunden geht. Abschaltbar mit --no-smoke-test.
- Doku korrigiert: pdfa_level = "" allein ist keine Entwarnung, die haengt
  an der ocrmypdf-Version.

152 Tests gruen.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-22 22:55:47 +02:00

170 lines
5.5 KiB
Python

"""CLI-Entrypoint."""
from __future__ import annotations
import argparse
import logging
import sys
import tomllib
from pathlib import Path
from . import __version__
from .config import Config, ConfigError, config_warnings, load_config
from .service import (
HotfolderService,
PreflightError,
check_output_config,
check_preflight,
detect_ghostscript_version,
detect_ocrmypdf_version,
)
log = logging.getLogger(__name__)
# Exit-Codes von --check-config (werden vom Updater ausgewertet)
CHECK_OK = 0
CHECK_WARN = 1
CHECK_ERROR = 2
def _setup_logging(level: str) -> None:
logging.basicConfig(
level=getattr(logging, level.upper(), logging.INFO),
format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
def _log_config_warnings(cfg: Config) -> None:
"""Schreibt Legacy- und Unbekannt-Warnungen beim Dienststart ins Log."""
for warning in config_warnings(cfg):
log.warning("Config-Warnung: %s", warning)
def check_config(cfg_path: Path) -> int:
"""Lädt und prüft die Config, ohne irgendetwas zu verarbeiten.
Returns:
0 = alles sauber, 1 = nur Warnungen, 2 = Fehler (Config unbrauchbar
oder Preflight scheitert).
"""
print(f"Prüfe Konfiguration: {cfg_path}")
try:
cfg = load_config(cfg_path)
except ConfigError as e:
print(f"FEHLER: {e}", file=sys.stderr)
return CHECK_ERROR
except tomllib.TOMLDecodeError as e:
print(f"FEHLER: {cfg_path} ist kein gültiges TOML: {e}", file=sys.stderr)
return CHECK_ERROR
except OSError as e:
print(f"FEHLER: {cfg_path} nicht lesbar: {e}", file=sys.stderr)
return CHECK_ERROR
print(" Config gelesen.")
for label, path in (("incoming", cfg.paths.incoming),
("outgoing", cfg.paths.outgoing),
("working ", cfg.paths.working),
("error ", cfg.paths.error)):
hint = "" if path.is_dir() else " (existiert noch nicht, "\
"wird beim Start angelegt)"
print(f" {label} = {path}{hint}")
print(f" OCR-Sprachen = {cfg.ocr.languages}")
print(f" Seiten-Timeout= {cfg.ocr.timeout} s")
print(f" PDF/A-Level = {cfg.ocr.pdfa_level or '(aus)'}")
print(f" skip_text = {'an' if cfg.ocr.skip_text else 'aus'}")
print(f" ocrmypdf = {detect_ocrmypdf_version() or '(nicht installiert)'}")
print(f" Ghostscript = {detect_ghostscript_version() or '(nicht gefunden)'}")
errors: list[str] = []
try:
check_preflight(cfg.ocr.pdfa_level, cfg.ocr.skip_text)
print(" Preflight ok (tesseract, gs vorhanden, Ghostscript-Version "
"passt zu ocrmypdf + [ocr]-Einstellungen).")
except PreflightError as e:
errors.append(str(e))
try:
check_output_config(cfg.output.original_on_success,
cfg.output.archive_dir,
cfg.output.name_mode)
print(" [output]-Sektion ok.")
except PreflightError as e:
errors.append(str(e))
warnings = config_warnings(cfg)
if warnings:
print(f"\n{len(warnings)} Warnung(en):")
for w in warnings:
print(f" WARNUNG: {w}")
if errors:
print(f"\n{len(errors)} Fehler:", file=sys.stderr)
for e in errors:
print(f" FEHLER: {e}", file=sys.stderr)
print("\nErgebnis: Config unbrauchbar — der Dienst würde nicht starten.",
file=sys.stderr)
return CHECK_ERROR
if warnings:
print("\nErgebnis: Config nutzbar, aber mit Warnungen.")
return CHECK_WARN
print("\nErgebnis: Config sauber.")
return CHECK_OK
def main() -> int:
parser = argparse.ArgumentParser(
prog="pdf-ocr-hotfolder",
description="Wandelt eingehende PDFs per OCR in durchsuchbare PDFs um.",
)
parser.add_argument("--config", "-c", default="/etc/pdf-ocr-hotfolder/config.toml",
help="Pfad zur Konfigurationsdatei (TOML)")
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
parser.add_argument("--once", action="store_true",
help="Nur bestehende Dateien verarbeiten und beenden")
parser.add_argument("--check-config", action="store_true", dest="check_config",
help="Config nur prüfen, nichts verarbeiten "
"(Exit 0 = sauber, 1 = Warnungen, 2 = Fehler)")
args = parser.parse_args()
cfg_path = Path(args.config)
if not cfg_path.exists():
print(f"Config nicht gefunden: {cfg_path}", file=sys.stderr)
return 2
if args.check_config:
# Hat Vorrang vor --once: es wird nichts verarbeitet.
return check_config(cfg_path)
try:
cfg = load_config(cfg_path)
except ConfigError as e:
print(f"FEHLER: {e}", file=sys.stderr)
return 2
_setup_logging(cfg.log_level)
_log_config_warnings(cfg)
service = HotfolderService(cfg)
if args.once:
try:
errors = service.run_once()
except PreflightError as e:
print(f"FEHLER: {e}", file=sys.stderr)
return 2
return 1 if errors > 0 else 0
try:
service.run()
except PreflightError as e:
print(f"FEHLER: {e}", file=sys.stderr)
return 2
except KeyboardInterrupt:
pass
return 0
if __name__ == "__main__":
sys.exit(main())