import re import subprocess import sys from pathlib import Path DATUM_IZPISKA = re.compile(r"Datum izpiska\s+(\d{2})\.(\d{2})\.(\d{4})") # raneme nlb-izpisek based on datum izpiska def pdf_to_text(pdf_path): result = subprocess.run( ["pdftotext", "-layout", str(pdf_path), "-"], capture_output=True, text=True, check=True, ) return result.stdout def find_date(text): match = DATUM_IZPISKA.search(text) if not match: return None day, month, year = match.groups() return f"{year}-{month}-{day}" def unique_target(dir_path, stem, suffix, current_path): target = dir_path / f"{stem}{suffix}" n = 2 while target.exists() and target != current_path: target = dir_path / f"{stem}_{n}{suffix}" n += 1 return target def main(): pdf_dir = Path(sys.argv[1]) for pdf_path in sorted(pdf_dir.glob("*.pdf")): text = pdf_to_text(pdf_path) date = find_date(text) if not date: print(f"skip {pdf_path.name}: no 'Datum izpiska' found") continue target = unique_target(pdf_dir, f"izpisek_{date}", pdf_path.suffix, pdf_path) if target == pdf_path: continue pdf_path.rename(target) print(f"{pdf_path.name} -> {target.name}") if __name__ == "__main__": main()