This commit is contained in:
2025-11-03 09:14:03 +01:00
parent fff548ca8d
commit 8bd87fc9eb

View File

@@ -1,19 +1,21 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import os,zlib
import json
import requests
import pymysql
from pathlib import Path
from datetime import datetime
import time
import shutil
# ==============================
# 🔧 CONFIGURATION
# ==============================
TOKEN_PATH = Path("token.txt")
CLINIC_SLUG = "mudr-buzalkova"
BASE_DIR = Path(r"d:\Dropbox\ordinace\Dokumentace_ke_zpracování\Medevio_přílohy")
BASE_DIR = Path(r"u:\Dropbox\ordinace\Dokumentace_ke_zpracování\Medevio_přílohy")
BASE_DIR.mkdir(parents=True, exist_ok=True)
DB_CONFIG = {
@@ -49,6 +51,32 @@ query ClinicRequestDetail_GetPatientRequest2(
}
"""
def short_crc8(uuid_str: str) -> str:
"""Return deterministic 8-char hex string from any input string (CRC32)."""
return f"{zlib.crc32(uuid_str.encode('utf-8')) & 0xffffffff:08x}"
def extract_filename_from_url(url: str) -> str:
"""Extracts filename from S3-style URL (between last '/' and first '?')."""
try:
filename = url.split("/")[-1].split("?")[0]
return filename
except Exception:
return "unknown_filename"
def safe_rename(src: Path, dst: Path, retries: int = 5, delay: float = 3.0):
"""Rename a folder with retries to avoid Dropbox/OneDrive sync lock issues."""
for attempt in range(1, retries + 1):
try:
src.rename(dst)
return # success
except PermissionError as e:
print(f" ⚠️ Rename attempt {attempt}/{retries} failed ({e}) — waiting {delay}s...")
time.sleep(delay)
except Exception as e:
print(f" ❌ Unexpected rename error: {e}")
break
print(f" 🚫 Failed to rename '{src}''{dst}' after {retries} attempts.")
# ==============================
# 🔑 TOKEN
# ==============================
@@ -115,6 +143,7 @@ def main():
for i, row in enumerate(rows, 1):
req_id = row["id"]
print(req_id)
prijmeni = row.get("pacient_prijmeni") or "Neznamy"
jmeno = row.get("pacient_jmeno") or ""
created = row.get("createdAt")
@@ -129,25 +158,45 @@ def main():
print(f"\n[{i}/{len(rows)}] 📂 {patient_dir.relative_to(BASE_DIR)}")
attachments = fetch_attachments(headers, req_id)
# print(attachments)
if not attachments:
print(" ⚠️ No attachments")
attachmentspocet = " (0)"
continue
else:
attachmentspocet = " ("+str(len(attachments))+")"
patient_dir=patient_dir+attachmentspocet
# vytvoř krátký CRC32 hash z UUID
uuid_short = short_crc8(str(req_id))
# Dočasná složka bez počtu
temp_dir = BASE_DIR / f"{prijmeni}, {jmeno}" / f"{created_date} {uuid_short}"
temp_dir.mkdir(parents=True, exist_ok=True)
for a in attachments:
m = a.get("medicalRecord") or {}
fname = m.get("description") or f"{m.get('id')}.bin"
# fname = m.get("description") or f"{m.get('id')}.bin"
url = m.get("downloadUrl")
fname = extract_filename_from_url(url)
if url:
out_path = patient_dir / fname
out_path = temp_dir / fname
download_file(url, out_path)
# Po stažení všech příloh spočítej skutečné soubory
real_count = len([f for f in temp_dir.iterdir() if f.is_file()])
# Přejmenuj složku na finální název s počtem
final_dir = temp_dir.parent / f"{temp_dir.name} ({real_count})"
if real_count != 0:
safe_rename(temp_dir, final_dir)
print(f" 📎 Saved {real_count} attachments → {final_dir.relative_to(BASE_DIR)}")
else:
print(f" ⚠️ No attachments for {temp_dir.name}")
temp_dir.rmdir() # smaž prázdnou složku
conn.close()
print("\n✅ Done!")