Compare commits

...

11 Commits

Author SHA1 Message Date
michaela.buzalkova
d982868db9 lenovo 2025-12-22 07:00:30 +01:00
3c34a78700 z230 2025-12-14 19:07:10 +01:00
michaela.buzalkova
7996ea641f lenovo 2025-12-14 11:07:42 +01:00
michaela.buzalkova
dcc127dc7a sestra 2025-12-04 15:26:49 +01:00
af2565b751 z230 2025-12-02 15:28:00 +01:00
5fe221ea94 Z230 2025-11-23 22:05:21 +01:00
d4894fde95 Z230 2025-11-21 16:56:11 +01:00
d43e502710 Z230 2025-11-20 10:01:53 +01:00
michaela.buzalkova
ef1f47ca5c sestra 2025-11-19 06:42:27 +01:00
michaela.buzalkova
756ea2dcd1 Merge remote-tracking branch 'origin/master' 2025-11-17 17:13:38 +01:00
0f953c2d86 Z230 2025-11-14 16:15:20 +01:00
11 changed files with 1083 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
#Virtual environments
.venv/*

View File

@@ -0,0 +1,45 @@
import fitz
from pathlib import Path
BASE_DIR = Path(r"z:\Dropbox\Ordinace\Dokumentace_ke_zpracování\AdobeFlattenStamp")
def flatten_pdf_rasterize(input_pdf: Path):
print(f"Processing: {input_pdf.name}")
doc = fitz.open(input_pdf)
# Create a new empty PDF
new_doc = fitz.open()
for page in doc:
# Render each page to a high-resolution image
pix = page.get_pixmap(dpi=400)
# Create a new PDF page with same size
new_page = new_doc.new_page(width=page.rect.width, height=page.rect.height)
# Insert the rasterized image
new_page.insert_image(new_page.rect, pixmap=pix)
# Save output
output_pdf = input_pdf.with_name(input_pdf.stem + "_flatten.pdf")
new_doc.save(output_pdf, deflate=True)
new_doc.close()
doc.close()
print(f" ✔ Saved: {output_pdf.name}")
def main():
pdfs = list(BASE_DIR.glob("*.pdf"))
if not pdfs:
print("No PDF files found.")
return
for pdf in pdfs:
flatten_pdf_rasterize(pdf)
print("\nAll files processed.")
if __name__ == "__main__":
main()

53
ECG/10 ECG test1.py Normal file
View File

@@ -0,0 +1,53 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import fitz
from pathlib import Path
import os
BASE_DIR = Path(r"u:\Dropbox\Ordinace\Dokumentace_ke_zpracování\EKGforProcessing")
FLAG = "rotated-by-script"
for pdf_path in BASE_DIR.glob("*.pdf"):
print(f"Processing: {pdf_path.name}")
doc = fitz.open(pdf_path)
meta = doc.metadata
keywords = meta.get("keywords", "") or meta.get("Keywords", "") or ""
# ---- Check if already processed ----
if FLAG in keywords:
print(" → Already rotated, skipping.")
doc.close()
continue
try:
# ---- Rotate first page ----
first = doc[0]
first.set_rotation((first.rotation + 90) % 360)
# ---- Delete page 2 (if exists) ----
if doc.page_count > 1:
doc.delete_page(1)
# ---- Update metadata Keywords ----
new_keywords = (keywords + " " + FLAG).strip()
meta["keywords"] = new_keywords
doc.set_metadata(meta)
# ---- Save via temporary file ----
tmp_path = pdf_path.with_suffix(".tmp.pdf")
doc.save(tmp_path, deflate=True, garbage=3)
doc.close()
os.replace(tmp_path, pdf_path)
print(" → Rotated & marked.")
except Exception as e:
print(f"❌ Error: {e}")
doc.close()
print("Done.")

168
ECG/20 ECG test2.py Normal file
View File

@@ -0,0 +1,168 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import fitz
from pathlib import Path
import os
import easyocr
from PIL import Image
import io
import re,time
BASE_DIR = Path(r"u:\Dropbox\Ordinace\Dokumentace_ke_zpracování\EKGforProcessing")
FLAG = "rotated-by-script"
# OCR Reader
reader = easyocr.Reader(['cs'], gpu=False)
def ocr_page(page):
pix = page.get_pixmap(alpha=False)
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
buf = io.BytesIO()
img.save(buf, format="PNG")
lines = reader.readtext(buf.getvalue(), detail=0)
return "\n".join(lines)
def extract_rodne_cislo(text):
"""
Extract rodné číslo in formats:
- 6 digits + slash + 4 digits → 655527/1910
- 6 digits + slash + 3 digits → 655527/910
- 10 digits without slash → 6555271910
Always returns 10 digits without slash.
"""
m = re.search(r"\b(\d{6})/?(\d{3,4})\b", text)
if not m:
return None
left = m.group(1)
right = m.group(2).zfill(4) # ensure 4 digits
return left + right
def extract_date(text):
"""Extract DD.MM.YYYY from 'DD.MM.YYYY HH.MM.SS'."""
m = re.search(r"\b(\d{1,2}\.\d{1,2}\.\d{4})\b", text)
return m.group(1) if m else None
def convert_date_to_iso(dmy):
"""Convert DD.MM.YYYY → YYYY-MM-DD."""
d, m, y = dmy.split(".")
return f"{y}-{m.zfill(2)}-{d.zfill(2)}"
def rename_ecg_file(pdf_path, rc, date_dmy):
"""Rename PDF reliably, even if Dropbox temporarily locks it."""
date_iso = convert_date_to_iso(date_dmy)
new_name = f"{rc} {date_iso} [EKG] [bez hodnocení].pdf"
new_path = pdf_path.with_name(new_name)
if new_path.exists():
print(f" ⚠ File with name already exists: {new_name}")
return
# Try renaming with retries in case Dropbox locks the file
for attempt in range(15): # ~4.5 seconds total
try:
pdf_path.rename(new_path)
print(f" → File renamed to: {new_name}")
return
except PermissionError:
print(f" ⚠ File locked (Dropbox?), retrying... {attempt+1}/15")
time.sleep(1)
print(" ❌ Could not rename file after several attempts.")
for pdf_path in BASE_DIR.glob("*.pdf"):
print(f"\nProcessing: {pdf_path.name}")
doc = fitz.open(pdf_path)
meta = doc.metadata
keywords = meta.get("keywords", "") or meta.get("Keywords", "")
# =============================
# 1) ALREADY ROTATED → do OCR
# =============================
if FLAG in keywords:
print(" → Already rotated, skipping rotation.")
page = doc[0]
print(" Performing OCR...")
text = ocr_page(page)
print("----- OCR RESULT -----")
print(text)
print("----------------------")
rc = extract_rodne_cislo(text)
date = extract_date(text)
print("\n----- EXTRACTED DATA -----")
print("Rodné číslo :", rc)
print("Datum :", date)
print("---------------------------")
# IMPORTANT: close file BEFORE renaming
doc.close()
if rc and date:
rename_ecg_file(pdf_path, rc, date)
else:
print(" ⚠ Missing RC or date file NOT renamed.")
continue
# =============================
# 2) NOT ROTATED → rotate + OCR
# =============================
try:
first = doc[0]
first.set_rotation((first.rotation + 90) % 360)
if doc.page_count > 1:
doc.delete_page(1)
meta["keywords"] = (keywords + " " + FLAG).strip()
doc.set_metadata(meta)
tmp = pdf_path.with_suffix(".tmp.pdf")
doc.save(tmp, deflate=True, garbage=3)
doc.close()
os.replace(tmp, pdf_path)
print(" → Rotated + saved + marked")
doc2 = fitz.open(pdf_path)
page = doc2[0]
text = ocr_page(page)
print("----- OCR RESULT -----")
print(text)
print("----------------------")
rc = extract_rodne_cislo(text)
date = extract_date(text)
print("\n----- EXTRACTED DATA -----")
print("Rodné číslo :", rc)
print("Datum :", date)
print("---------------------------")
# CLOSE PDF FIRST — VERY IMPORTANT
doc2.close()
if rc and date:
rename_ecg_file(pdf_path, rc, date)
except Exception as e:
print("❌ Error:", e)
doc.close()
print("\nDone.")

View File

@@ -0,0 +1,47 @@
import fitz
from pathlib import Path
# =========================================
# CONFIG
# =========================================
input_path = Path(r"u:\Dropbox\Ordinace\Dokumentace_ke_zpracování\A4 expand\mericka_rotated_inplace.pdf")
output_path = input_path.with_name(input_path.stem + "_A4.pdf")
A4_WIDTH = 595.28
A4_HEIGHT = 841.89
def place_on_a4(input_pdf: Path, output_pdf: Path):
src = fitz.open(input_pdf)
dst = fitz.open()
for page in src:
# Extract actual width & height of rotated page
w = page.rect.width
h = page.rect.height
# --- SCALE to A4 width ---
scale_factor = A4_WIDTH / w
new_w = A4_WIDTH
new_h = h * scale_factor
# Create A4 page
new_page = dst.new_page(width=A4_WIDTH, height=A4_HEIGHT)
# Center vertically
x = 0
y = (A4_HEIGHT - new_h) / 2
target_rect = fitz.Rect(x, y, x + new_w, y + new_h)
# Draw original PDF onto A4 page
new_page.show_pdf_page(target_rect, src, page.number)
dst.save(output_pdf)
dst.close()
src.close()
print("Saved A4 adapted:", output_pdf)
place_on_a4(input_path, output_path)

View File

@@ -0,0 +1,105 @@
from pdf2image import convert_from_path
from PIL import Image
import img2pdf
import os
import pathlib
import glob
# *** KONFIGURACE ***
# Cesta ke složce, kde se nacházejí PDF soubory
INPUT_DIR = r"u:\Dropbox\Ordinace\Dokumentace_ke_zpracování\AdobeMakeSmaller"
# Cesta k binární složce Poppleru (musí být správná, aby to fungovalo)
POPPLER_BIN_PATH = r'c:\poppler\library\bin'
# Rozlišení pro čitelnost (300 DPI by mělo být perfektní pro text)
TARGET_DPI = 200
# *******************
def create_min_bw_pdf(input_pdf_path, output_pdf_path, dpi):
"""
Konvertuje jeden PDF soubor na nový, maximálně zmenšený, černobílý PDF.
"""
temp_image_path = "temp_bw_image_for_batch.png"
success = False
print(f"\n--- Zpracovávám: {pathlib.Path(input_pdf_path).name} (DPI: {dpi}) ---")
try:
# 1. Převod PDF na obrázek (bitmapu)
# Používáme grayscale=True, ale hlavní komprese přijde v kroku 2
images = convert_from_path(
input_pdf_path,
dpi=dpi,
grayscale=True,
thread_count=1,
poppler_path=POPPLER_BIN_PATH
)
if not images:
print(f"⚠️ Chyba: Nepodařilo se konvertovat stránku z {input_pdf_path}.")
return success
# 2. Zpracování a převod na 1-bitový ČERNOBÍLÝ režim (maximální komprese barev)
image = images[0]
bw_image = image.convert('1')
# Uložení do dočasného PNG souboru (nejlepší pro 1-bitový obraz)
bw_image.save(temp_image_path, format='PNG', optimize=True)
# 3. Konverze dočasného obrázku zpět na PDF (přepisování originálu)
# Důležité: 'output_pdf_path' je stejné jako 'input_pdf_path'
with open(output_pdf_path, "wb") as f:
f.write(img2pdf.convert(temp_image_path))
# Zpráva o úspěchu a úspoře
original_size = os.path.getsize(input_pdf_path)
new_size = os.path.getsize(output_pdf_path)
reduction = (1 - new_size / original_size) * 100
print(
f"✅ Úspěch! Původní: {original_size / 1024:.2f} KB, Nový: {new_size / 1024:.2f} KB (Úspora: {reduction:.2f} %)")
success = True
except Exception as e:
print(f"❌ Nastala chyba při zpracování {input_pdf_path}: {e}")
print("Zkontrolujte, zda je Poppler cesta správná a máte práva k zápisu.")
finally:
# Vyčištění dočasného souboru
if os.path.exists(temp_image_path):
os.remove(temp_image_path)
return success
def process_directory(input_directory, dpi):
"""
Prochází zadaný adresář, hledá PDF a volá konverzní funkci.
"""
if not os.path.isdir(input_directory):
print(f"Chyba: Adresář nebyl nalezen na cestě: {input_directory}")
return
# Najdeme všechny soubory s příponou .pdf (ignorujeme velikost písmen)
pdf_files = glob.glob(os.path.join(input_directory, '*.pdf'), recursive=False)
if not pdf_files:
print(f"Ve složce {input_directory} nebyly nalezeny žádné PDF soubory.")
return
print(f"\nNalezeno {len(pdf_files)} souborů ke zpracování v {input_directory}.")
print("----------------------------------------------------------------------")
total_processed = 0
for file_path in pdf_files:
# Vstupní cesta je zároveň výstupní cestou (přepisování)
if create_min_bw_pdf(file_path, file_path, dpi):
total_processed += 1
print("----------------------------------------------------------------------")
print(f"Konec zpracování. Celkem úspěšně zpracováno: {total_processed}/{len(pdf_files)} souborů.")
# --- SPUSŤTE POUZE, AŽ BUDETE PŘIPRAVENI PŘEPSAT SOUBORY ---
print(f"!!! POUŽÍVÁ SE DPI: {TARGET_DPI}. ORIGINÁLNÍ SOUBORY BUDOU PŘEPSÁNY !!!")
process_directory(INPUT_DIR, TARGET_DPI)

View File

@@ -0,0 +1,111 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import hashlib
import json
from pathlib import Path
import time
# === ZDE JEN PŘIDÁVEJ ADRESÁŘE ===
DIRECTORIES = [
Path(r"U:\Dropbox\Ordinace\Dokumentace_zpracovaná"),
Path(r"U:\Dropbox\Ordinace\LAB-PDF"),
]
CHUNK = 65536
def md5_file(path: Path) -> str:
h = hashlib.md5()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(CHUNK), b""):
h.update(chunk)
return h.hexdigest()
def load_db(db_path: Path) -> dict:
if db_path.exists():
with db_path.open("r", encoding="utf-8") as f:
return json.load(f)
return {}
def save_db(db: dict, db_path: Path):
with db_path.open("w", encoding="utf-8") as f:
json.dump(db, f, ensure_ascii=False, indent=2)
def process_directory(root: Path):
print("\n===========================================")
print(f"📁 ZPRACOVÁVÁM ADRESÁŘ: {root}")
print("===========================================\n")
db_path = root / "processed_files.json"
# Načíst databázi
db = load_db(db_path)
print(f"Načteno z DB: {len(db)} záznamů")
# Projít souborový systém
files_in_fs = {}
start_scan = time.time()
for f in root.rglob("*"):
if f.is_file() and f.suffix.lower() != ".json":
stat = f.stat()
files_in_fs[f.name] = {
"size": stat.st_size,
"mtime": int(stat.st_mtime),
"path": str(f)
}
print(f"Nalezeno v FS: {len(files_in_fs)} souborů")
print(f"Čas skenu: {time.time() - start_scan:.2f} s\n")
new_files = 0
changed_files = 0
for fname, info in files_in_fs.items():
size = info["size"]
mtime = info["mtime"]
# nový soubor?
if fname not in db:
print(f"Nový soubor → MD5: {fname}")
new_files += 1
db[fname] = {
"size": size,
"mtime": mtime,
"md5": md5_file(Path(info["path"]))
}
continue
# změněný soubor?
if db[fname]["size"] != size or db[fname]["mtime"] != mtime:
print(f"Změněný soubor → MD5: {fname}")
changed_files += 1
db[fname] = {
"size": size,
"mtime": mtime,
"md5": md5_file(Path(info["path"]))
}
# uložit databázi
save_db(db, db_path)
print("\n=== Výsledky ===")
print(f" Nové soubory: {new_files}")
print(f" Změněné soubory: {changed_files}")
print(f" Celkem v DB: {len(db)}")
print(f" Databáze: {db_path}")
print("=============================\n")
def main():
for directory in DIRECTORIES:
process_directory(directory)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,158 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import hashlib
import json
from pathlib import Path
import time
import traceback
# ======= CONFIG =======
MP_DIR = Path(r"U:\Dropbox\Ordinace\Dokumentace_ke_zpracování\MP")
JSON_PATHS = [
Path(r"U:\Dropbox\Ordinace\LAB-PDF\processed_files.json"),
Path(r"U:\Dropbox\Ordinace\Dokumentace_zpracovaná\processed_files.json"),
]
CHUNK = 65536
PRINT_EVERY = 50
# ======================
def try_rename(old_path: Path, new_path: Path, retries: int = 5, delay: int = 5):
"""Try rename with retry mechanism."""
for attempt in range(1, retries + 1):
try:
old_path.rename(new_path)
return True
except Exception as e:
print(f"⚠ Rename failed ({attempt}/{retries}): {e}")
if attempt < retries:
print(f" Waiting {delay}s before retry...")
time.sleep(delay)
else:
print(" ❌ Maximum retries reached. Skipping.")
traceback.print_exc()
return False
def md5_file(path: Path) -> str:
h = hashlib.md5()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(CHUNK), b""):
h.update(chunk)
return h.hexdigest()
def load_all_md5(json_paths):
"""Načte MD5 ze všech JSONů a vrátí množinu."""
md5_set = set()
for jp in json_paths:
if not jp.exists():
print(f"⚠ JSON nenalezen: {jp}")
continue
try:
with jp.open("r", encoding="utf-8") as f:
db = json.load(f)
for _, info in db.items():
md5_set.add(info["md5"])
print(f"Načteno {len(db)} záznamů z {jp}")
except Exception as e:
print(f"❌ Chyba při čtení {jp}: {e}")
print(f"➡ Celkem MD5 hashů: {len(md5_set)}\n")
return md5_set
def mark_folders_if_all_marked(root: Path, dryrun: bool):
print("\n=== KONTROLA ADRESÁŘŮ — OZNAČENÍ PLNĚ HOTOVÝCH ===")
for folder in sorted(root.rglob("*")):
if not folder.is_dir():
continue
files = [f for f in folder.iterdir() if f.is_file()]
if not files:
continue
# všechny soubory označené?
if not all(f.name.startswith("") for f in files):
continue
# adresář už označen?
if len(folder.name) > 10 and folder.name[10] == "":
continue
# vložení ▲ na 11. pozici
insert_pos = 10
name = folder.name
if len(name) <= insert_pos:
new_name = name + ""
else:
new_name = name[:insert_pos] + "" + name[insert_pos:]
new_path = folder.parent / new_name
print(f"✔ Adresář označen: {folder.name}{new_name}")
if not dryrun:
try_rename(folder, new_path)
def run_matcher(dryrun: bool = True):
print("\n=== MATCHER V3 — SOUBORY + ADRESÁŘE ===")
print(f"Režim: {'DRYRUN (simulace)' if dryrun else 'OSTRÝ'}\n")
all_md5 = load_all_md5(JSON_PATHS)
counter = 0
renamed = 0
start = time.time()
for file in MP_DIR.rglob("*"):
if not file.is_file():
continue
counter += 1
if counter % PRINT_EVERY == 0:
speed = counter / (time.time() - start)
print(f" {counter} soub. ({speed:.1f}/s)")
md5 = md5_file(file)
if md5 in all_md5:
if file.name.startswith(""):
continue
new_name = "" + file.name
new_path = file.parent / new_name
if dryrun:
print(f"[DRYRUN] Označil bych: {file.name}{new_name}")
else:
# === RETRY RENAME (soubory) ===
success = try_rename(file, new_path)
if success:
renamed += 1
print(f"{file.name}{new_name}")
# označit adresáře
mark_folders_if_all_marked(MP_DIR, dryrun)
total_time = time.time() - start
speed = 0 if counter == 0 or total_time == 0 else counter / total_time
print("\n=== MATCHER HOTOVO ===")
print(f" Zkontrolováno: {counter} souborů")
print(f" Označeno: {renamed}")
print(f" Rychlost: {speed:.1f} soub./s")
print(f" Režim: {'DRYRUN' if dryrun else 'OSTRÝ'}\n")
if __name__ == "__main__":
run_matcher(dryrun=False)

View File

@@ -0,0 +1,57 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from pathlib import Path
# ==============================
# CONFIGURATION
# ==============================
BASE_DIR = Path(r"u:\Dropbox\Ordinace\Dokumentace_ke_zpracování\MP")
# ==============================
# MAIN LOGIC
# ==============================
def all_files_start_with_triangle(dir_path: Path) -> bool:
"""Return True if all files in directory start with ▲"""
for item in dir_path.iterdir():
if item.is_file():
if not item.name.startswith(""):
return False
return True
def process():
for dir_path in BASE_DIR.iterdir():
if not dir_path.is_dir():
continue
# Skip directories that already have ▲ at position 12
old_name = dir_path.name
if len(old_name) > 11 and old_name[10:11] == "":
continue
# Check if ALL files start with ▲
if not all_files_start_with_triangle(dir_path):
continue
# Insert ▲ after the date (position 10)
# OLD: "2025-11-20 ŠTEPÁN, ..."
# NEW: "2025-11-20▲ ŠTEPÁN, ..."
if len(old_name) < 11:
# Name too short, skip to avoid errors
continue
new_name = old_name[:10] + "" + old_name[10:]
new_path = dir_path.parent / new_name
# Rename directory
print(f"Renaming:\n {dir_path.name}\n{new_name}")
os.rename(dir_path, new_path)
if __name__ == "__main__":
process()
print("\n✓ Done.")

View File

@@ -0,0 +1,56 @@
import os
from pathlib import Path
# ==========================
# CONFIG
# ==========================
FOLDER_1 = Path(r"U:\Dropbox\Ordinace\Dokumentace_ke_zpracování")
FOLDER_2 = Path(r"U:\Dropbox\Ordinace\Dokumentace_ke_zpracování\MP")
TRIANGLE = ""
# Set to True for testing (no changes), False to really rename
DRY_RUN = False
def main():
# ---- Collect files in FOLDER_1 (top level only)
files_folder1 = [f for f in FOLDER_1.iterdir() if f.is_file()]
names_folder1 = {f.name.lower() for f in files_folder1}
# ---- Collect ALL files in FOLDER_2 (recursive)
files_folder2 = [f for f in FOLDER_2.rglob("*") if f.is_file()]
actions = [] # store what would be renamed
for file2 in files_folder2:
original_name = file2.name
lower_name = original_name.lower()
# Skip if already starts with ▲
if original_name.startswith(TRIANGLE):
continue
# Check if the filename exists in Folder 1
if lower_name in names_folder1:
new_name = TRIANGLE + original_name
new_path = file2.with_name(new_name)
actions.append((file2, new_path))
if DRY_RUN:
print(f"[DRY RUN] Would rename: {file2}{new_path}")
else:
print(f"Renaming: {file2}{new_path}")
file2.rename(new_path)
print("\n===============================")
if DRY_RUN:
print(f"DRY RUN COMPLETE — {len(actions)} file(s) would be renamed.")
else:
print(f"DONE — {len(actions)} file(s) renamed.")
print("===============================")
if __name__ == "__main__":
main()

281
pomoc/s03soubory.py Normal file
View File

@@ -0,0 +1,281 @@
import os,shutil,fdb,time, socket
import re,datetime,funkce
def get_medicus_connection():
"""
Connect to Firebird 'medicus.fdb' depending on computer name.
Returns fdb.Connection or raises RuntimeError if unknown or connection fails.
"""
computer_name = socket.gethostname().upper()
try:
if computer_name == "Z230":
print("Computer name is Z230")
cesta = r"u:\dropboxtest\Ordinace\Dokumentace_ke_zpracování"
cestazpracovana = r"u:\Dropboxtest\Ordinace\Dokumentace_zpracovaná"
return fdb.connect(dsn=r"localhost:c:\medicus 3\data\medicus.fdb", user="SYSDBA", password="masterkey", charset="win1250"),cesta,cestazpracovana
elif computer_name == "LEKAR":
print("Computer name is LEKAR")
cesta = r"z:\dropbox\Ordinace\Dokumentace_ke_zpracování"
cestazpracovana = r"z:\Dropbox\Ordinace\Dokumentace_zpracovaná"
return fdb.connect(dsn=r"localhost:m:\medicus\data\medicus.fdb", user="SYSDBA", password="masterkey", charset="win1250"),cesta,cestazpracovana
elif computer_name in ("SESTRA", "POHODA"):
print("Computer name is SESTRA or POHODA")
cesta = r"z:\dropbox\Ordinace\Dokumentace_ke_zpracování"
cestazpracovana = r"z:\Dropbox\Ordinace\Dokumentace_zpracovaná"
return fdb.connect(dsn=r"192.168.1.10:m:\medicus\data\medicus.fdb", user="SYSDBA", password="masterkey", charset="win1250"),cesta,cestazpracovana
else:
raise RuntimeError(f"❌ Unknown computer name: {computer_name}")
except Exception as e:
print(f"⚠️ Error connecting to Medicus on {computer_name}: {e}")
raise
#toto volání současně nadefinuje cesty do dropboxu
conn,cesta,cestazpracovana=get_medicus_connection()
def is_encodable_win1250(text: str) -> bool:
try:
text.encode("cp1250")
return True
except UnicodeEncodeError:
return False
def make_win1250_safe(text: str) -> str:
return text.encode("cp1250", errors="replace").decode("cp1250").replace("?", "_")
def restore_files_for_import(retezec):
drop=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace"
next=r"u:\NextcloudOrdinace\Dokumentace_ke_zpracování"
# Check if the directory exists
if not os.path.exists(drop):
print(f"The directory '{drop}' does not exist.")
return
# Iterate over all files and subdirectories in the directory
for item in os.listdir(drop):
item_path = os.path.join(drop, item)
# If it's a file or a symbolic link, delete it
if os.path.isfile(item_path) or os.path.islink(item_path):
os.unlink(item_path)
print(f"Deleted file: {item_path}")
# If it's a directory, delete it recursively
elif os.path.isdir(item_path):
shutil.rmtree(item_path)
print(f"Deleted directory: {item_path}")
for item in os.listdir(next):
item_path = os.path.join(next, item)
# If it's a file finished with PDF, copy it
if os.path.isfile(item_path) and item_path.endswith(".pdf") and retezec in item_path:
shutil.copy(item_path,os.path.join(drop,item))
print(f"Copied file: {item_path}")
def kontrola_rc(rc,connection):
cur = connection.cursor()
cur.execute("select count(*),idpac from kar where rodcis=? group by idpac",(rc,))
row = cur.fetchone()
if row:
return row[1]
else:
return False
def kontrola_struktury(souborname,connection):
if souborname.endswith('.pdf'):
#kontrola struktury
pattern=re.compile(r'(^\d{9,10}) (\d{4}-\d{2}-\d{2}) (\w+, \w.+?) \[(.+?)\] \[(.*?)\]')
match=pattern.search(souborname)
# print(souborname)
vpohode=True
if match and len(match.groups())==5:
datum=match.group(2)
try:
datum_object = datetime.datetime.strptime(datum,"%Y-%m-%d").date()
# print(datum_object)
except:
vpohode=False
return vpohode
cur = connection.cursor()
cur.execute("select count(*) from kar where rodcis=?", (match.group(1),))
row = cur.fetchone()[0]
if row!=1:
vpohode = False
return vpohode
else:
vpohode=False
return vpohode
else:
vpohode=False
return vpohode
return vpohode
def vrat_info_o_souboru(souborname, connection):
pattern = re.compile(r'(^\d{9,10}) (\d{4}-\d{2}-\d{2}) (\w+, \w.+?) \[(.+?)\] \[(.*?)\]')
match = pattern.search(souborname)
rc = match.group(1)
datum = datetime.datetime.strptime(match.group(2), "%Y-%m-%d").date()
jmeno = match.group(3)
prvnizavorka = match.group(4)
druhazavorka = match.group(5)
cur=connection.cursor()
cur.execute("select idpac from kar where rodcis=?",(rc,))
idpac = cur.fetchone()[0]
datumsouboru = datetime.datetime.fromtimestamp(os.path.getctime(os.path.join(cesta,souborname)))
return (rc,idpac,datum,jmeno,prvnizavorka,druhazavorka,souborname,datumsouboru)
def prejmenuj_chybny_soubor(souborname,cesta):
if souborname[0]!="":
soubornovy = "" + souborname
os.rename(os.path.join(cesta,souborname),os.path.join(cesta,soubornovy))
# print(kontrola_struktury(ss))
# info=vrat_info_o_souboru(ss)
# print(kontrola_rc(info[0],conn))
# restore_files_for_import("")
# restore_files_for_import("346204097")
info=[]
for soubor in os.listdir(cesta):
plna_cesta = os.path.join(cesta, soubor)
if not os.path.isfile(plna_cesta):
continue # skip folders or anything thats not a regular fil
if not is_encodable_win1250(soubor):
safe_name = make_win1250_safe(soubor)
novy_plna_cesta = os.path.join(cesta, safe_name)
print(f"⚠️ Renaming invalid filename:\n {soubor}{safe_name}")
os.rename(plna_cesta, novy_plna_cesta)
# Update variable for later processing
soubor = safe_name
plna_cesta = novy_plna_cesta
print(soubor)
if kontrola_struktury(soubor,conn):
info.append(vrat_info_o_souboru(soubor,conn))
# os.remove(os.path.join(cesta,soubor))
else:
prejmenuj_chybny_soubor(soubor,cesta)
info = sorted(info, key=lambda x: (x[0], x[1]))
print(info)
skupiny={}
for row in info:
skupiny[row[0]]=[]
for row in info:
skupiny[row[0]].append(row)
# print(skupiny)
# rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks BOOKMARKNAMES }}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}}
# {\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;}
# {\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}}
# \uc1\pard\s10\plain\cs20\f0\i\fs20 P\'f8\'edlohy:\par
# \pard\s10{\*\bkmkstart 0}\plain\cs22\f0\ul\fs20\cf1 BOOKMARKNAMESTEXT{\*\bkmkend 0}\par
# \pard\s10\plain\cs15\f0\fs20 \par
# }"""
rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks BOOKMARKNAMES }}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}}
{\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;}
{\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}}
\uc1\pard\s10\plain\cs20\f0\i\fs20 P\'f8\'edlohy:\par
BOOKMARKSTEXT
\pard\s10\plain\cs15\f0\fs20 \par
}"""
for key in skupiny.keys():
rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks BOOKMARKNAMES }}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}}
{\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;}
{\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}}
\uc1\pard\s10\plain\cs20\f0\i\fs20 Vlo\'9eena skenovan\'e1 dokumentace:\par
BOOKMARKSTEXT
\pard\s10\plain\cs15\f0\fs20\par
}"""
# if key=="8257300425": #346204097
if True:
prvnibookmark=True
print(key,len(skupiny[key]))
cislo=9
poradi=0
bookmark=""
bookmarks=""
for row in skupiny[key]:
# print(row)
pacid=row[1]
filename=row[6]
fileid=funkce.zapis_file(vstupconnection=conn, idpac=row[1],
cesta=cesta, souborname=row[6], prvnizavorka=row[4],
soubordate=row[2], souborfiledate=row[7], poznamka=row[5])
for attempt in range(3):
try:
# Replace this with the command that might raise an error
if not os.path.exists(os.path.join(cestazpracovana,row[6])):
shutil.move(os.path.join(cesta,row[6]), os.path.join(cestazpracovana,row[6]))
print("Command succeeded!")
break # Exit the loop if the command succeeds
else:
now = datetime.datetime.now()
datetime_string = now.strftime("%Y-%m-%d %H-%M-%S")
print(os.path.join(cestazpracovana,row[6][:-4]+" "+datetime_string+".pdf"))
shutil.move(os.path.join(cesta,row[6]),os.path.join(cestazpracovana,row[6][:-4]+" "+datetime_string+".pdf"))
print("Command succeeded!")
break # Exit the loop if the command succeeds
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt < 3 - 1:
print(f"Retrying in {5} seconds...")
time.sleep(5)
else:
print("Max retries reached. Command failed.")
filename=funkce.convert_to1250(filename)
print("Encodedfilename", filename)
filenameforbookmark=row[2].strftime('%Y-%m-%d')+" "+row[4]+": "+row[5]
bookmark=bookmark+'"'+filenameforbookmark+'","Files:'+str(fileid)+'",'+str(cislo)+";"
cislo+=7
# print(bookmark)
if prvnibookmark:
bookmarks=bookmarks+r'\pard\s10{\*\bkmkstart '+str(poradi)+r"}\plain\cs22\f0\ul\fs20\cf1 "+filenameforbookmark+r"{\*\bkmkend "+str(poradi)+r"}\par"
prvnibookmark=False
else:
bookmarks=bookmarks+r'\pard\s10{\*\bkmkstart '+str(poradi)+r"}" + filenameforbookmark + r"{\*\bkmkend " + str(poradi) + r"}\par"
bookmark=bookmark[:-1]
# bookmarks=bookmarks[:-2]
print(bookmark)
print(bookmarks)
rtf = rtf.replace("BOOKMARKNAMES", bookmark)
rtf=rtf.replace("BOOKMARKSTEXT",bookmarks)
print(rtf)
dekursid = funkce.get_dekurs_id(conn)
datumzapisu = datetime.datetime.now().date()
caszapisu = datetime.datetime.now().time()
cur=conn.cursor()
cur.execute("insert into dekurs (id,iduzi,idprac,idodd,idpac,datum,cas,dekurs)"
" values(?,?,?,?,?,?,?,?)",
(dekursid,6,2,2, row[1],datumzapisu,caszapisu, rtf))
conn.commit()
# rtf = rtf.replace("FILEID", str(idfile))
#Zde zapisujeme soubor
# fileid=funkce.zapis_file(conn,row[1],cesta,row[6],row[4],row[2],row[7],row[5])
# zapis_dekurs(vstupconnection, idpac, idodd, iduzi, idprac, idfile, filename, text, datumzpravy,datumsouboru)
# return (rc, idpac, datum, jmeno, prvnizavorka, druhazavorka, souborname, datumsouboru)
# Zde zapisujeme dekurs
# text=row[2].strftime("%Y-%m-%d")+" "+row[4].strip()+": "+row[5].strip()
# funkce.zapis_dekurs(conn, row[1], 2, 6, 2, fileid, text, text, row[7], row[2])
# os.remove(os.path.join(cesta, soubor))