notebook vb

This commit is contained in:
2026-03-14 07:45:53 +01:00
parent d6cb2b4490
commit a599b6741b
38 changed files with 15 additions and 17 deletions

18
Trash/02 Zapis dekurs.py Normal file
View File

@@ -0,0 +1,18 @@
import fdb
from datetime import date
import funkce
# Connect to the Firebird database
conn = fdb.connect(
dsn=r'localhost:c:\medicus 3\data\medicus.fdb', # Database path
user='SYSDBA', # Username
password="masterkey", # Password,
charset="win1250")
cur = conn.cursor()
cur.execute("delete from dekurs where idpac=9742")
conn.commit()
print(funkce.zapis_dekurs(conn, cur, 9742, 2, 6, 2, 3, "Příloha.pdf", "test text", date(2023, 10, 15), date(2023, 10, 15)))
print(funkce.zapis_dekurs(conn, cur, 9742, 2, 6, 2, 3, "Příloha.pdf", "test text", date(2023, 10, 15), date(2023, 10, 15)))

View File

@@ -0,0 +1,23 @@
import os, fdb
import funkce1
# Connect to the Firebird database
conn = fdb.connect(
dsn=r'localhost:c:\medicus 3\data\medicus.fdb', # Database path
user='SYSDBA', # Username
password="masterkey", # Password,
charset="win1250")
cesta=r"u:\NextcloudOrdinace\Dokumentace_ke_zpracování"
for soubor in os.listdir(cesta):
print(soubor)
if os.path.isfile(os.path.join(cesta, soubor)):
if funkce1.kontrola_struktury(soubor, conn):
# info.append(vrat_info_o_souboru(soubor,conn))
# os.remove(os.path.join(cesta,soubor))
continue
else:
funkce1.prejmenuj_chybny_soubor(soubor, cesta)

View File

@@ -0,0 +1,168 @@
import os
import mysql.connector
from mysql.connector import Error
from datetime import datetime
class FileSystemToMySQL:
def __init__(self, host, port,user, password, database):
self.host = host
self.port=port
self.user = user
self.password = password
self.database = database
self.connection = None
def connect(self):
try:
self.connection = mysql.connector.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database
)
if self.connection.is_connected():
print("Connected to MySQL database")
self._initialize_database()
except Error as e:
print(f"Error connecting to MySQL: {e}")
def _initialize_database(self):
cursor = self.connection.cursor()
# Create tables if they don't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS folders (
id INT AUTO_INCREMENT PRIMARY KEY,
path VARCHAR(767) NOT NULL,
name VARCHAR(255) NOT NULL,
parent_id INT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
FOREIGN KEY (parent_id) REFERENCES folders(id) ON DELETE CASCADE,
UNIQUE (path)
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS files (
id INT AUTO_INCREMENT PRIMARY KEY,
folder_id INT NOT NULL,
name VARCHAR(255) NOT NULL,
size INT NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
FOREIGN KEY (folder_id) REFERENCES folders(id) ON DELETE CASCADE,
UNIQUE (folder_id, name)
)
""")
self.connection.commit()
cursor.close()
def _get_folder_id(self, folder_path):
cursor = self.connection.cursor()
cursor.execute("SELECT id FROM folders WHERE path = %s", (folder_path,))
result = cursor.fetchone()
cursor.close()
return result[0] if result else None
def _insert_folder(self, folder_path, parent_id=None):
folder_name = os.path.basename(folder_path)
now = datetime.now()
cursor = self.connection.cursor()
cursor.execute("""
INSERT INTO folders (path, name, parent_id, created_at, updated_at)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE updated_at = %s
""", (folder_path, folder_name, parent_id, now, now, now))
folder_id = cursor.lastrowid
if folder_id == 0: # If it was an update
folder_id = self._get_folder_id(folder_path)
self.connection.commit()
cursor.close()
return folder_id
def store_file(self, file_path, folder_path):
try:
# First ensure the folder exists
folder_id = self._insert_folder(folder_path)
# Read file content
with open(file_path, 'rb') as file:
file_content = file.read()
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
now = datetime.now()
cursor = self.connection.cursor()
cursor.execute("""
INSERT INTO files (folder_id, name, size, created_at, updated_at)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
size = VALUES(size),
updated_at = VALUES(updated_at)
""", (folder_id, file_name, file_size, now, now))
self.connection.commit()
cursor.close()
print(f"Stored/updated file: {file_name} in folder: {folder_path}")
except Error as e:
print(f"Error storing file {file_path}: {e}")
def store_directory(self, directory_path, parent_folder_path=None):
try:
# Ensure the parent folder exists
parent_id = None
if parent_folder_path:
parent_id = self._insert_folder(parent_folder_path)
# Store the current directory
dir_id = self._insert_folder(directory_path, parent_id)
# Store all files in the directory
for item in os.listdir(directory_path):
full_path = os.path.join(directory_path, item)
if os.path.isfile(full_path):
self.store_file(full_path, directory_path)
elif os.path.isdir(full_path):
self.store_directory(full_path, directory_path)
print(f"Stored directory: {directory_path}")
except Error as e:
print(f"Error storing directory {directory_path}: {e}")
def close(self):
if self.connection and self.connection.is_connected():
self.connection.close()
print("MySQL connection closed")
# Example usage
if __name__ == "__main__":
# Database configuration
db_config = {
'host': '192.168.1.76',
'port': '3307',
'user': 'root',
'password': 'Vlado9674+',
'database': 'file_storage_db'
}
# Initialize the file system storage
fs_storage = FileSystemToMySQL(**db_config)
fs_storage.connect()
# Store a single file
# fs_storage.store_file('/path/to/your/file.txt', '/path/to/your')
# Store an entire directory
fs_storage.store_directory(r'u:\Dropbox\!!!Days\Downloads Z230')
# Close the connection
fs_storage.close()

48
Trash/Access.py Normal file
View File

@@ -0,0 +1,48 @@
import os
import pyodbc
import random
import string
# Path to your Access database
db_path = r"u:\Dropbox\!!!Days\Downloads Z230\Access\Banka.accdb"
# Connection string
conn_str = (
r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
rf"DBQ={db_path};"
)
# Connect to database
conn = pyodbc.connect(conn_str)
# Create cursor
cursor = conn.cursor()
cursor.execute("delete from transactions")
conn.commit()
exit(0)
length = 10 # desired length
chars = string.ascii_letters + string.digits # A-Z, a-z, 0-9
# Example query
# cursor.execute("SELECT * FROM contacts")
print("Start")
for n in range(10000):
random_str = ''.join(random.choices(chars, k=length))
cursor.execute("insert into contacts (company) values (?)",(random_str))
print("stop")
conn.commit()
print("committed")
exit(0)
# Example query
cursor.execute("SELECT * FROM contacts")
rows = cursor.fetchall()
for row in rows:
print(row)
# Close connection
cursor.close()
conn.close()

105
Trash/DatovaSchranka.py Normal file
View File

@@ -0,0 +1,105 @@
# Přihlašovací údaje
username = 'eupo5s'
password = 'Michalka25+'
schrankaid='bk7e6j2'
from zeep import Client
from zeep.wsse.username import UsernameToken
import time
import os
import base64
# Přihlašovací údaje
USERNAME = 'eupo5s'
PASSWORD = 'Michalka25+'
WSDL_URL = 'https://..../ds.wsdl' # upravit dle prostředí
# Inicializace klienta
client = Client(wsdl=WSDL_URL, wsse=UsernameToken(USERNAME, PASSWORD))
# Kontrola přihlášení
try:
owner_info = client.service.GetOwnerInfoFromLogin()
except Exception as e:
print(f"Chyba přihlášení: {e}")
exit(1)
# Zobrazení základních údajů o přihlášeném účtu
print("Přihlášen jako:", owner_info.dbID, owner_info.firmName)
# Vytvoření adresáře pro testovací soubory
out_dir = os.path.abspath('test_isds_py')
os.makedirs(out_dir, exist_ok=True)
# Vytvoření a odeslání testovacích zpráv
filenames = []
for i, text in enumerate(["První testovací soubor", "Druhý testovací soubor"], 1):
fn = os.path.join(out_dir, f"TESTISDS_{i}.txt")
with open(fn, 'w', encoding='utf-8') as f:
f.write(text)
filenames.append(fn)
# Nahraj přílohy
files_struct = []
for fn in filenames:
with open(fn, "rb") as f:
data = base64.b64encode(f.read()).decode('ascii')
files_struct.append({
'dmFileDescr': os.path.basename(fn),
'dmMimeType': 'text/plain',
'dmEncodedContent': data,
})
# Vytvoření a odeslání zprávy (parametry uprav podle vlastního scénáře!)
msg_id = client.service.CreateMessage(
senderDBID=None,
subject="Testovaci zasilka z Pythonu",
isUrgent=False,
senderOrgUnitCode=None,
# níže: příjemce
dbIDRecipient="231",
recipientFirmName="Nase org jednotka",
recipientOrgUnitNum=-1,
recipientOrgUnitName="ncj. 589",
receiverPersonCode=None,
toHands="K rukam p.Novaka",
deepAttachments=files_struct
)
print("MessageID:", msg_id)
# Chvíle čekání
time.sleep(5)
# Stažení přijatých zpráv v intervalu
records = client.service.GetListOfReceivedMessages(
startTime="2009-11-01T00:00:00",
endTime="2010-10-01T00:00:00",
recNo=0,
maxRec=100,
recordType=1023,
customFilter=None
)
for rec in records.dmRecord:
print(f"ID zasilky: {rec.dmID}, odesilatel: {rec.dmSender}")
received_id = rec.dmID
break
# Stažení jedné zprávy
msg = client.service.MessageDownload(received_id)
print("Stažená zpráva:", msg.dmDm.dmID)
# Uložení souborů
for file in msg.dmDm.dmFiles.dmFile:
content = base64.b64decode(file.dmEncodedContent)
path = os.path.join(out_dir, file.dmFileDescr)
with open(path, 'wb') as f:
f.write(content)
print("Uloženo:", path)
# Označení jako stáhnuto
client.service.MarkMessageAsDownloaded(received_id)
print("Označeno jako přečtené")
# Můžeme pokračovat implementací dalších funkcí: GetDeliveryInfo, SignedMessageDownloadToFile, GetListOfSentMessages, FindDataBox, CheckDataBox…

276
Trash/Davka001.py Normal file
View File

@@ -0,0 +1,276 @@
import os
from collections import namedtuple
hlav = namedtuple("Hlavicka", ["typ", "char", "dtyp", "dico",
"dpob", "drok", "dmes", "dcid", "dpoc", "dbody",
"dfin", "ddpp", "dvdr1", "dvdr2", "ddtyp"])
av=namedtuple("Aveta",["typ","hcid","hstr","hpoc","hpor","hcpo","htpp","hico","hvar","hodb","hrod","hzdg","hkon","hicz",
"hcdz","hrez","hccel","hcbod","dtyp"])
vv=namedtuple("Vveta",["typ","vdat","vkod","vpoc","vodb","vdia","vbod","vtyp"])
zv=namedtuple("Zveta",["typ","hcid","hstr","hpoc","hpor","hico","hvar","hodb","hrod","hzdg","hrez","hccel","htyp"])
lv=namedtuple("Lveta",["typ","ldat","ltpr","lzvl","lkod","lmno","lfin","lvdg","ltyp"])
def lveta(retezec):
TYP= retezec[0:1]
LDAT= retezec[1:9]
LTPR= retezec[9:10]
LZVL= retezec[10:11]
LKOD= retezec[11:18]
LMNO=retezec[18:29]
LFIN= retezec[29:39]
LVDG= retezec[39:44]
VTYP= retezec[44:45]
print(TYP, LDAT, LTPR, LZVL,LKOD,LMNO,LFIN,LVDG,VTYP)
Lveta = lv(TYP, LDAT, LTPR, LZVL,LKOD,LMNO,LFIN,LVDG,VTYP)
print(Lveta)
def vveta(retezec):
TYP= retezec[0:1]
VDAT= retezec[1:9]
VKOD= retezec[9:14]
VPOC= retezec[14:15]
VODB=retezec[15:18]
VDIA= retezec[18:23]
VBOD= retezec[23:30]
VTYP= retezec[30:31]
print(TYP, VDAT, VKOD, VPOC,VODB,VDIA,VBOD,VTYP)
Vveta = vv(TYP, VDAT, VKOD, VPOC,VODB,VDIA,VBOD,VTYP)
print(Vveta)
def zveta(retezec):
TYP= retezec[0:1]
HCID= retezec[1:8]
HSTR= retezec[8:9]
HPOC= retezec[9:10]
HPOR= retezec[10:13]
HICO= retezec[13:21]
HVAR= retezec[21:27]
HODB= retezec[27:30]
HROD= retezec[30:40]
HZDG= retezec[40:45]
HREZ= retezec[45:55]
HCCEL= retezec[55:66]
DTYP= retezec[66:67]
print(TYP, HCID, HSTR, HPOC,HPOR,HICO,HVAR,HODB,HROD,HZDG,HREZ,HCCEL,DTYP )
Zveta = zv(TYP, HCID, HSTR, HPOC,HPOR,HICO,HVAR,HODB,HROD,HZDG,HREZ,HCCEL,DTYP )
print(Zveta)
def prvniradek(retezec):
TYP = retezec[0:1] # Typ věty „D“ úvodní věta dávky
CHAR = retezec[1:2] # Charakter dávky (viz dále ) určuje stav předkládaných dokladů v dávce
DTYP = retezec[2:4] # typ dávky, číselný kód
DICO = retezec[4:12] # IPZ
DPOB = retezec[12:16] # kod oblastního pracoviště pojišťovny
DROK = retezec[16:20] # rok
DMES = retezec[20:22] # měsíc
DCID = retezec[22:28] # Číslo dávky jednoznačné číslo dávky v rámci PZS a roku
DPOC = retezec[28:31] # počet dokladů v dávce, slouží k ověření kompletnosti
DBODY = retezec[31:42] # nepovinné, počet bodů
DFIN = float(retezec[42:60]) # nepovinné, celková částka za doklady
DDPP = retezec[60:61] # druh pojistného plnění
DVDR1 = retezec[61:74]
DVDR2 = retezec[74:87]
DDTYP = retezec[87:88]
print(TYP, CHAR, DTYP, DICO, DPOB, DROK, DMES, DCID, DPOC, DBODY, DFIN, DDPP, DVDR1,DVDR2,DDTYP)
hlavicka=hlav(TYP, CHAR, DTYP, DICO, DPOB, DROK, DMES, DCID, DPOC, DBODY, DFIN, DDPP, DVDR1,DVDR2,DDTYP)
print(hlavicka.dvdr1)
def aveta(retezec):
TYP= retezec[0:1]
HCID= retezec[1:8]
HSTR= retezec[8:9]
HPOC= retezec[9:10]
HPOR= retezec[10:13]
HCPO= retezec[13:16]
HTPP= retezec[16:17]
HICO= retezec[17:25]
HVAR= retezec[25:31]
HODB= retezec[31:34]
HROD= retezec[34:44]
HZDG= retezec[44:49]
HKON= retezec[49:50]
HICZ= retezec[50:58]
HCDZ= retezec[58:65]
HREZ= retezec[65:75]
HCCEL= retezec[75:85]
HCBOD= retezec[85:92]
DTYP= retezec[92:93]
print(TYP, HCID, HSTR, HPOC,HPOR,HCPO,HTPP,HICO,HVAR,HODB,HROD,HZDG,HKON,HICZ,HCDZ,HREZ,HCCEL,HCBOD,DTYP )
Aveta = av(TYP, HCID, HSTR, HPOC,HPOR,HCPO,HTPP,HICO,HVAR,HODB,HROD,HZDG,HKON,HICZ,HCDZ,HREZ,HCCEL,HCBOD,DTYP)
print(Aveta)
konec=0
# with open(r"u:\Dropbox\!!!Days\Downloads Z230\Dávky\DataKDavka (6).111","r",encoding='cp852') as f:
# for importradku in f.readlines():
# if importradku[0]=="D":
# print(importradku)
# prvniradek(importradku)
# if importradku[0]=="A":
# konec=0
# print(importradku)
# aveta(importradku)
# if importradku[0] == "V":
# print(importradku)
# vveta(importradku)
# if importradku[0]=="Z":
# print(importradku)
# zveta(importradku)
# if importradku[0] == "L":
# konec = 1
# print(importradku)
# lveta(importradku)
# if konec==2:
# exit(0)
#010 Projdi vsechny davky
root_davky_dir=r"u:\Dropbox\!!!Days\Downloads Z230\Dávky\Data"
#010.0 os.walk
# for root, folders, files in os.walk(root_davky_dir):
# for file in files:
# print(file)
#010.1 pathlib
from pathlib import Path
# # all txt files in current dir
# for p in Path(".").glob("*.txt"):
# print(p)
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
import re
# ---- header spec (0-based) ----
# name, type, length, start, description (optional)
HEADER_SPEC = [
("TYP", "C", 1, 0, "Typ věty (má být 'D')"),
("CHAR", "C", 1, 1, "Charakter dávky (např. 'P')"),
("DTYP", "C", 2, 2, "Typ dávky (např. '98')"),
("DICO", "C", 8, 4, "IČZ PZS"),
("DPOB", "C", 4, 12, "Územní pracoviště"),
("DROK", "N", 4, 16, "Rok uzavření dokladů"),
("DMES", "N", 2, 20, "Měsíc uzavření dokladů"),
("DCID", "N", 6, 22, "Číslo dávky"),
("DPOC", "N", 3, 28, "Počet dokladů"),
("DBODY", "N", 11, 31, "Počet bodů v dávce (volitelné)"),
("DFIN", "$", 18, 42, "Celkem Kč (18.2, volitelné)"),
("DDPP", "C", 1, 60, "Druh pojistného vztahu"),
("DVDR1", "C", 13, 61, "Verze DR 1"),
("DVDR2", "C", 13, 74, "Verze DR 2"),
("DDTYP", "C", 1, 87, "Doplněk typu věty"),
]
def _slice0(s: str, start: int, length: int) -> str:
"""0-based safe slice."""
if s is None: return ""
return s[start:start+length] if start < len(s) else ""
def _parse_char(s: str):
s = (s or "").strip()
return s or None
def _parse_int(s: str):
if s is None: return None
digits = re.sub(r"\D", "", s)
return int(digits) if digits else None
def _parse_money(s: str):
"""Parse money field '18.2': spaces allowed, comma or dot; returns Decimal or None."""
if s is None: return None
s = s.replace("\u00A0", " ").strip().replace(" ", "").replace(",", ".")
if not s: return None
try:
# keep precision with Decimal
val = Decimal(s)
# optional: round to 2 decimal places
return val.quantize(Decimal("0.01"))
except (InvalidOperation, ValueError):
return None
def parse_davka_header_line(line: str, strict=True) -> dict:
"""
Parse header (first line) of a dávka according to HEADER_SPEC (0-based).
Returns dict with typed values. Raises if not a 'DP98' header (strict=True).
"""
if not line:
raise ValueError("Empty header line.")
if strict and not line.startswith("DP98"):
raise ValueError(f"Invalid header prefix {line[:4]!r}; expected 'DP98'.")
out = {"raw": line}
# field parsing per spec
for name, typ, length, start, *_ in HEADER_SPEC:
raw_val = _slice0(line, start, length)
if typ == "C":
out[name] = _parse_char(raw_val)
elif typ == "N":
out[name] = _parse_int(raw_val)
elif typ == "$":
out[name] = _parse_money(raw_val)
else:
out[name] = raw_val # fallback
# basic validations (soft)
if strict:
if out.get("TYP") != "D":
raise ValueError(f"TYP must be 'D', got {out.get('TYP')!r}")
if out.get("DTYP") != "98":
raise ValueError(f"DTYP must be '98', got {out.get('DTYP')!r}")
# Optional month sanity check (accepts '01'..'12' and '00')
m = out.get("DMES")
if m is not None and m not in range(0, 13): # 0..12
# keep value but you could raise or log here
pass
return out
# recursive
exts=("111","201","205","207","209","211")
keep={}
for soubor in Path(root_davky_dir).rglob("KDAVKA.*"):
if not soubor.is_file():
print(f"{soubor} neni platny soubor")
continue
if soubor.suffix.lstrip(".") not in exts:
print(f"{soubor} nema platnou koncovku")
continue
try:
with soubor.open("r",encoding="cp1250",errors="strict",newline="") as f:
if f.read(4)=="DP98": #takovy soubor chceme brat v potaz
keep[str(soubor)]={"File":soubor}
except:
continue
print(keep)
#020 Read headers of davky in keep
for soubor in keep: #
# def get_kdavka(root_dir, exts=("111","201","205","207","209","211")):
# root = Path(root_dir)
# wanted = {e.upper() for e in exts}
# keep = []
# for p in root.rglob("KDAVKA.*"):
# if not p.is_file():
# continue
# if p.suffix.lstrip(".").upper() not in wanted:
# continue
# try:
# with p.open("r", encoding="cp1250", errors="strict", newline="") as f:
# if f.read(4) == "DP98": # read just 4 chars, cp1250 is single-byte
# keep.append(p)
# except UnicodeDecodeError:
# # bad file — skip
# continue
# keep.sort()
# print(f"{len(keep)} davky (DP98) found under {root}")
# return keep

85
Trash/FIO1.py Normal file
View File

@@ -0,0 +1,85 @@
import json
from datetime import datetime
import os
import pyodbc
import random
import string
# Path to your Access database
db_path = r"u:\Dropbox\!!!Days\Downloads Z230\Access\Banka.accdb"
# Connection string
conn_str = (
r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
rf"DBQ={db_path};"
)
# Connect to database
conn = pyodbc.connect(conn_str)
# Create cursor
cursor = conn.cursor()
cursor.execute("delete from transactions")
conn.commit()
# Load from file, načtení bankovních pohybů
with open(r"u:\Dropbox\!!!Days\Downloads Z230\Fio\pohyby.json", "r", encoding="utf-8") as f:
transactions = json.load(f)
# print(transactions["accountStatement"]["transactionList"])
# Process
for tx in transactions["accountStatement"]["transactionList"]["transaction"]:
#ID pohybu
idpohybu=str(tx["column22"]["value"])
datum=tx["column0"]["value"]
#Datum transakce
datum = datetime.strptime(datum, "%Y-%m-%d%z")
datum = datum.date()
#Částka
objem = int(tx["column1"]["value"])
#Měna
mena = tx["column14"]["value"]
#Název protiúčtu
nazevprotiuctu=tx["column10"]["value"]
#Typ transakce
typ = tx["column8"]["value"]
#Konstantní symbol
if tx["column4"] is not None:
kss=tx["column4"]["value"]
else:
kss=""
# Provedl
if tx["column9"] is not None:
provedl = tx["column9"]["value"]
else:
provedl = ""
# ID pokynu
if tx["column17"] is not None:
idpokynu = str(tx["column17"]["value"])
else:
idpokynu = ""
# print (idpohybu,datum,objem,mena,nazevprotiuctu,typ,kss,provedl,idpokynu)
# if idpohybu=="3016989040":
# # Uložení do Accessu, jestli ještě neexistuje")
# cursor.execute("insert into transactions (idpohybu, datum) values (?,?)", (idpohybu, datum))
# conn.commit()
# print("committed")
print (idpohybu,datum,objem,mena,nazevprotiuctu,typ,kss,provedl,idpokynu)
print(type(idpohybu))
# Uložení do Accessu, jestli ještě neexistuje")
cursor.execute("insert into transactions (idpohybu, datum,objem,mena,nazevprotiuctu,ks,typ,provedl,idpokynu) values (?,?,?,?,?,?,?,?,?)",
(idpohybu, datum,objem, mena, nazevprotiuctu,kss,typ,provedl,idpokynu))
# cursor.execute("insert into transactions (idpohybu) values (?)", (idpohybu))
conn.commit()
print("committed")

7
Trash/Form.py Normal file
View File

@@ -0,0 +1,7 @@
def console_form():
print("=== Registration Form ===")
name = input("Enter your name: ")
email = input("Enter your email: ")
print(f"\nThank you, {name}! We'll contact you at {email}.")
console_form()

78
Trash/Kontakty01.py Normal file
View File

@@ -0,0 +1,78 @@
import firebirdsql,re
def get_connection():
return firebirdsql.connect(
host="192.168.1.4",
port=3050,
database=r"z:\medicus 3\data\medicus.fdb", # path must be valid on the server
user="SYSDBA",
password="masterkey",
charset="WIN1250",
)
def get_registrovani(cur): #vrati list rodnych cisel registrovanych pacientu "registrovani"
cur.execute("""
select rodcis from registr join kar
on registr.idpac=kar.idpac where
kar.vyrazen!='A' and
kar.rodcis is not null and
idicp!=0 and
datum_zruseni is null
""")
registrovani=[]
for radek in cur.fetchall():
registrovani.append(radek[0])
return registrovani
def je_registrovany(con,rodcis):
cur=conn.cursor()
cur.execute("""
select 1 from registr join kar
on registr.idpac=kar.idpac where
kar.vyrazen!='A' and
kar.rodcis is not null and
idicp!=0 and
datum_zruseni is null
and rodcis=%s
limit 1
""")
cur.execute(sql, (rodcis,))
return cur.fetchone() is not None
def strip_cz_prefix(num: str) -> str:
# remove spaces and non-digits first
n = re.sub(r"\D", "", num)
# strip +420, 00420 or 420 at start
if n.startswith("00420"):
return n[5:]
elif n.startswith("420"):
return n[3:]
else:
return n
def is_cz_mobile(num: str) -> bool:
nmbr=strip_cz_prefix(num)
MOBILE_PREFIXES = ("60", "72", "73", "77", "79")
# now check length and prefix
return len(nmbr) == 9 and nmbr[:2] in MOBILE_PREFIXES
def get_mobile(rodcis,conn):
sql = f"""
SELECT kar.prijmeni, kar.rodcis,
karkontakt.poradi, karkontakt.kontakt
FROM karkontakt join kar on kar.idpac=karkontakt.idpac
where kar.rodcis={rodcis}
"""
cur=conn.cursor()
mobil={}
conn = get_connection()
cur = conn.cursor()
# print(get_mobile("340415112",conn))
print(is_cz_mobile("283893084"))

28
Trash/MobilniCisla.py Normal file
View File

@@ -0,0 +1,28 @@
import os, fdb
from lxml import etree
import hashlib
# Connect to the Firebird database
conn = fdb.connect(
dsn=r'localhost:u:\medicus 3\data\medicus.fdb', # Database path
user='SYSDBA', # Username
password="masterkey", # Password,
charset="win1250")
cur = conn.cursor()
# cur.execute("select distinct recept.idpac, rodcis, upper(kar.PRIJMENI || ', ' || kar.jmeno) as jmeno,notifikace_kontakt "
# "from recept join kar on recept.idpac=kar.idpac "
# "join registr on recept.idpac=registr.idpac where datum_zruseni is null "
# "and notifikace_kontakt is not null "
# "order by recept.datum desc")
cur.execute("select kar.idpac, kar.prijmeni, kar.rodcis,poradi, kontakt, popis, karkontakt.typ, vztah from karkontakt join kar on kar.idpac=karkontakt.idpac")
for radek in cur.fetchall():
print(radek)

View File

@@ -0,0 +1,58 @@
import os,re,fdb,time
import logging
logging.basicConfig(level=logging.DEBUG)
def set_single_page_view (filepdfin):
from pikepdf import Pdf, Dictionary, Name
import os
from pathlib import Path
pdf=Pdf.open(filepdfin,allow_overwriting_input=True)
# file_only_path=os.path.dirname(filepdfin)
# file_without_ext = Path(filepdfin).stem
pdf.Root.PageLayout=Name('/SinglePage')
pdf.Root.PageMode=Name('/UseNone')
pdf.save()
# Connect to the Firebird database
conn = fdb.connect(
dsn=r'localhost:u:\medicus 3\data\medicus.fdb', # Database path
user='SYSDBA', # Username
password="masterkey", # Password,
charset="win1250")
# cur = conn.cursor()
cesta=r"u:\dropbox\ordinace\Dokumentace_ke_zpracování"
for file in os.listdir(cesta):
if file.upper().endswith((".PDF")) and os.path.isfile(os.path.join(cesta,file)):
pattern=r"(\d{9,10}) ((?:(?:19|20)\d\d)-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])) (\[.*)"
nalezeno=re.search(pattern,file)
if nalezeno:
print(nalezeno.groups())
x=nalezeno.groups()
rodcis=nalezeno.group(1)
datum=nalezeno.group(2)
konec=nalezeno.group(5)
print(datum)
print(konec)
print(rodcis,type(rodcis))
cur = conn.cursor()
cur.execute("select prijmeni, jmeno from kar where rodcis=?",(rodcis,))
x = cur.fetchone()
if x:
if len(x[0].split(" "))==1:
prijmeni=x[0]
else:
prijmeni=x[0].split(" ")[0]
if len(x[1].split(" "))==1:
jmeno=x[1]
else:
prijmeni=x[1].split(" ")[0]
konecsouboru=file.split(rodcis)[1]
novejmeno=rodcis+" "+datum+" "+prijmeni.strip()+", "+jmeno.strip()+" "+konec
print(novejmeno)
os.rename(os.path.join(cesta,file),os.path.join(cesta,novejmeno))
cur.close()

73
Trash/PDF optimization.py Normal file
View File

@@ -0,0 +1,73 @@
import io
import PyPDF2
import os
from PyPDF2 import PdfReader, PdfWriter
def optimize_pdf_with_images(input_file, destination_folder):
# """ Optimize a PDF by reducing the size of embedded images while preserving all other content. """/
optimized_pdf_path = os.path.join(destination_folder, os.path.basename(input_file))
pdf_reader = PdfReader(input_file)
pdf_writer = PdfWriter()
for pdf_page in pdf_reader.pages:
page_resources = pdf_page.get("/Resources")
if page_resources:
page_resources = page_resources.get_object() # Resolve IndirectObject
if "/XObject" in page_resources:
image_objects = page_resources["/XObject"].get_object()
for img_name in image_objects:
img_obj = image_objects[img_name]
if img_obj.get("/Subtype") == "/Image":
# Extract the image data
image_data = img_obj._data
image_stream = io.BytesIO(image_data)
# Compress the image
compressed_image_stream = compress_image_for_pdf(image_stream)
if compressed_image_stream is None:
print(f"Skipping invalid image: {img_name}")
continue # Skip this image if compression failed
# Get new image dimensions
resized_image = Image.open(compressed_image_stream)
new_width, new_height = resized_image.size
# Create a new image object with compressed data
new_image_object = StreamObject()
new_image_object._data = compressed_image_stream.getvalue()
new_image_object.update({
NameObject("/Filter"): NameObject("/DCTDecode"),
NameObject("/Subtype"): NameObject("/Image"),
NameObject("/Width"): NumberObject(new_width),
NameObject("/Height"): NumberObject(new_height),
NameObject("/ColorSpace"): NameObject("/DeviceRGB"),
NameObject("/BitsPerComponent"): NumberObject(8),
})
# Replace the old image with the new one
image_objects[img_name] = new_image_object
pdf_writer.add_page(pdf_page)
pdf_reader.stream.close()
print(f"PDF reader closed, now writing the optimized file.")
print(f"optimized_pdf_path : {optimized_pdf_path}") # Log the file path
with open(optimized_pdf_path, "wb") as output_pdf:
pdf_writer.write(output_pdf)
print(f"Optimized PDF saved at: {optimized_pdf_path}")
return optimized_pdf_path
optimize_pdf_with_images(r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\6504140489 2025-03-04 Harsa, Radovan [PZ psychiatrie] [28FEB2025-04MAR2025 vágní suicidální proklamace, zbytečná hospitalizace].pdf",
r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\Converted")

8
Trash/PDF3.py Normal file
View File

@@ -0,0 +1,8 @@
from pdf2image import convert_from_path
# Convert a PDF to images
images = convert_from_path(r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\a.pdf")
# Save the images
for i, image in enumerate(images):
image.save(f"page_{i + 1}.jpg", "JPEG")

22
Trash/PDFOpenView.py Normal file
View File

@@ -0,0 +1,22 @@
from pikepdf import Pdf, Name
inputpdf=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\a.pdf"
# # Open the PDF file
# with Pdf.open(inputpdf) as pdf:
# # Ensure the PDF has a Catalog dictionary
# if '/Catalog' not in pdf.Root:
# pdf.Root['/Catalog'] = {}
#
# # Set the OpenAction to fit the page
# pdf.Root['/Catalog']['/OpenAction'] = [pdf.pages[0], Name.Fit]
#
# # Save the modified PDF
# pdf.save('output.pdf')
from pikepdf import Pdf, Dictionary, Name
pdf = Pdf.open(inputpdf)
pdf.Root.PageLayout = Name('/SinglePage')
pdf.Root.PageMode = Name('/UseNone')
pdf.save('output.pdf')

View File

@@ -0,0 +1,22 @@
import os,re
def set_single_page_view (filepdfin):
from pikepdf import Pdf, Dictionary, Name
import os
from pathlib import Path
pdf=Pdf.open(filepdfin,allow_overwriting_input=True)
# file_only_path=os.path.dirname(filepdfin)
# file_without_ext = Path(filepdfin).stem
pdf.Root.PageLayout=Name('/SinglePage')
pdf.Root.PageMode=Name('/UseNone')
pdf.save()
# set_single_page_view(r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\a.pdf")
cesta=r"u:\dropbox\ordinace\Dokumentace_ke_zpracování"
for file in os.listdir(cesta):
if file.upper().endswith((".PDF")) and os.path.isfile(os.path.join(cesta,file)):
set_single_page_view(os.path.join(cesta,file))

22
Trash/PDFmanipulation.py Normal file
View File

@@ -0,0 +1,22 @@
import os
def set_single_page_view (filepdfin):
from pikepdf import Pdf, Dictionary, Name
import os
from pathlib import Path
pdf=Pdf.open(filepdfin,allow_overwriting_input=True)
# file_only_path=os.path.dirname(filepdfin)
# file_without_ext = Path(filepdfin).stem
pdf.Root.PageLayout=Name('/SinglePage')
pdf.Root.PageMode=Name('/UseNone')
pdf.save()
# set_single_page_view(r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\a.pdf")
cesta=r"u:\NextCloudOrdinace\Dokumentace_ke_zpracování"
for file in os.listdir(cesta):
if file.upper().endswith((".PDF")) and os.path.isfile(os.path.join(cesta,file)):
set_single_page_view(os.path.join(cesta,file))

10
Trash/Pojistovna.py Normal file
View File

@@ -0,0 +1,10 @@
# client certificate (no private key)
certorig=r"u:\Dropbox\!!!Days\Downloads Z230\cert\MB komerční full do 2026-01-22.pfx"
certpem=r"u:\Dropbox\!!!Days\Downloads Z230\cert\client.pem"
openssl pkcs12 -in certorig -clcerts -nokeys -out certpem

361
Trash/Reporty01.py Normal file
View File

@@ -0,0 +1,361 @@
import os
import fdb
import csv,time,pandas as pd
import openpyxl
PathToSaveCSV=r"U:\Dropbox\Ordinace\Test"
timestr = time.strftime("%Y-%m-%d %H-%M-%S ")
CSVname="Pacienti.xlsx"
# PathToSaveCSV=r"//tower/tempspeed"
con = fdb.connect(
host='localhost', database=r'm:\MEDICUS\data\medicus.FDB',
user='sysdba', password='masterkey',charset='WIN1250')
# Create a Cursor object that operates in the context of Connection con:
cur = con.cursor()
# import openpyxl module
import openpyxl
import xlwings as xw
wb = openpyxl.Workbook()
sheet = wb.active
# wb.save("sample.xlsx")
#Načtení očkování registrovaných pacientů
cur.execute("select rodcis,prijmeni,jmeno,ockzaz.datum,kodmz,ockzaz.poznamka,latka,nazev,expire from registr join kar on registr.idpac=kar.idpac join ockzaz on registr.idpac=ockzaz.idpac where datum_zruseni is null and kar.vyrazen!='A' and kar.rodcis is not null and idicp!=0 order by ockzaz.datum desc")
nacteno=cur.fetchall()
print(len(nacteno))
sheet.title="Očkování"
sheet.append(["Rodne cislo","Prijmeni","Jmeno","Datum ockovani","Kod MZ","Sarze","Latka","Nazev","Expirace"])
#nacteno jsou ockovani
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Načtení registrovaných pacientů
cur.execute("select rodcis,prijmeni,jmeno,datum_registrace,registr.idpac,poj from registr join kar on registr.idpac=kar.idpac where kar.vyrazen!='A' and kar.rodcis is not null and idicp!=0 and datum_zruseni is null")
nacteno=cur.fetchall()
print(len(nacteno))
wb.create_sheet('Registrovani',0)
sheet=wb['Registrovani']
sheet.append(["Rodne cislo","Prijmeni","Jmeno","Datum registrace","ID pacienta","Pojistovna"])
#nacteno jsou registrovani
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Načtení receptů
cur.execute("""select
kar.rodcis,
TRIM(kar.prijmeni) ||' '|| substring(kar.jmeno from 1 for 1) ||'.' as jmeno,
recept.datum,
TRIM(recept.lek) ||' '|| trim(recept.dop) as lek,
recept.expori AS Poc,
CASE
WHEN recept.opakovani is null THEN 1
ELSE recept.opakovani
END AS OP,
recept.uhrada,
recept.dsig,
recept.NOTIFIKACE_KONTAKT as notifikace,
recept_epodani.erp,
recept_epodani.vystavitel_jmeno,
recept.atc,
recept.CENAPOJ,
recept.cenapac
from recept LEFT Join RECEPT_EPODANI on recept.id_epodani=recept_epodani.id
LEFT join kar on recept.idpac=kar.idpac
order by datum desc,erp desc"""
)
nacteno=cur.fetchall()
print(len(nacteno))
wb.create_sheet('Recepty',0)
sheet=wb['Recepty']
sheet.title="Recepty"
sheet.append(["Rodné číslo","Jméno","Datum vystavení","Název leku","Poč.","Op.","Úhr.","Da signa","Notifikace","eRECEPT","Vystavil","ATC","Cena pojišťovna","Cena pacient"])
#nacteno jsou ockovani
for row in nacteno:
try:
sheet.append(row)
except:
continue
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Načtení vykony vsech
cur.execute("select dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,dokladd.pocvyk,dokladd.ddgn,dokladd.body,vykony.naz "
"from kar join dokladd on kar.rodcis=dokladd.rodcis join vykony on dokladd.kod=vykony.kod where (datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null) order by dokladd.datose desc,dokladd.rodcis")
wb.create_sheet('Vykony',0)
sheet=wb['Vykony']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum vykonu","Kod","Pocet","Dg.","Body","Nazev"])
#nacteno jsou ockovani
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Načtení neschopenek
import datetime
def pocet_dni(zacnes,konnes,pracne):
dnes=datetime.date.today()
if pracne=='A':
return (dnes-zacnes).days
if pracne=='N' and zacnes is not None and konnes is not None and zacnes<=konnes:
return (konnes-zacnes).days
else:
return "NA"
cur.execute("select nes.idpac, "
"kar.rodcis, "
"TRIM(prijmeni) ||', '|| TRIM(jmeno), "
"nes.datnes, "
"nes.ecn, "
"nes.zacnes, "
"nes.pracne, "
"nes.konnes, "
"nes.diagno, "
"nes.kondia, "
"nes.updated "
"from nes "
"left join kar on nes.idpac=kar.idpac where nes.datnes<=current_date "
"order by datnes desc")
tmpnacteno_vse=[]
nacteno_vse=cur.fetchall()
cur.execute("select nes.idpac, "
"kar.rodcis, "
"TRIM(prijmeni) ||', '|| TRIM(jmeno), "
"nes.datnes, "
"nes.ecn, "
"nes.zacnes, "
"nes.pracne, "
"nes.konnes, "
"nes.diagno, "
"nes.kondia, "
"nes.updated "
"from nes "
"left join kar on nes.idpac=kar.idpac where nes.datnes<=current_date and pracne='A'"
"order by datnes desc")
tmpnacteno_aktivni=[]
nacteno_aktivni=cur.fetchall()
for row in nacteno_vse:
tmpnacteno_vse.append((row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],pocet_dni(row[5],row[7],row[6]),row[8],row[9],row[10]))
for row in nacteno_aktivni:
(tmpnacteno_aktivni.append((row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],pocet_dni(row[5],row[7],row[6]),row[8],row[9],row[10])))
wb.create_sheet('Neschopenky všechny',0)
sheet=wb["Neschopenky všechny"]
sheet.append(["ID pac","Rodne cislo","Jmeno","Datum neschopenky","Číslo neschopenky","Zacatek","Aktivní?","Konec","Pocet dni","Diagnoza zacatel","Diagnoza konec","Aktualizovano"])
for row in tmpnacteno_vse:
sheet.append(row)
wb.create_sheet('Neschopenky aktivní',0)
sheet=wb["Neschopenky aktivní"]
sheet.append(["ID pac","Rodne cislo","Jmeno","Datum neschopenky","Číslo neschopenky","Zacatek","Aktivní?","Konec","Pocet dni","Diagnoza zacatel","Diagnoza konec","Aktualizovano"])
for row in tmpnacteno_aktivni:
sheet.append(row)
#Načtení preventivni prohlidky
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=1022 or dokladd.kod=1021) "
"order by datose desc")
wb.create_sheet('Preventivni prohlidky',0)
sheet=wb['Preventivni prohlidky']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni INR
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=01443) "
"order by datose desc")
wb.create_sheet('INR',0)
sheet=wb['INR']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni CRP
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=02230 or dokladd.kod=09111) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('CRP',0)
sheet=wb['CRP']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni Holter
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=17129) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('Holter',0)
sheet=wb['Holter']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni prostata
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=01130 or dokladd.kod=01131 or dokladd.kod=01132 or dokladd.kod=01133 or dokladd.kod=01134) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('Prostata',0)
sheet=wb['Prostata']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni TOKS
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and "
"(dokladd.kod=15118 or dokladd.kod=15119 or dokladd.kod=15120 or dokladd.kod=15121) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('TOKS',0)
sheet=wb['TOKS']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni COVID
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and "
"(dokladd.kod=01306) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('COVID',0)
sheet=wb['COVID']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni Streptest
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and "
"(dokladd.kod=02220) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('Streptest',0)
sheet=wb['Streptest']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
# autofilter
for ws in wb.worksheets:
# Get the maximum number of rows and columns
max_row = ws.max_row
max_column = ws.max_column
ws.auto_filter.ref = f"A1:{openpyxl.utils.get_column_letter(max_column)}{max_row}"
# ws.auto_filter.ref = ws.dimensions
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
# Tento modul je pouze na autofit jednotlivych sloupcu na vsech listech workbooku
file = os.path.join(PathToSaveCSV ,timestr+CSVname)
with xw.App(visible=False) as app:
wb = xw.Book(file)
for sheet in range(len(wb.sheets)):
ws = wb.sheets[sheet]
ws.autofit()
# centrování receptů
sheet = wb.sheets['Recepty']
for sloupec in ["C:C", "E:E", "F:F", "G:G", "I:I", "M:M", "N:N"]:
sheet.range(sloupec).api.HorizontalAlignment = 3 # 3 = Center
wb.save()
wb.close()

346
Trash/Reporty02.py Normal file
View File

@@ -0,0 +1,346 @@
import os
import fdb
import csv,time,pandas as pd
import openpyxl
PathToSaveCSV=r"U:\Dropbox\Ordinace\Test"
timestr = time.strftime("%Y-%m-%d %H-%M-%S ")
CSVname="Pacienti.xlsx"
# PathToSaveCSV=r"//tower/tempspeed"
con = fdb.connect(
host='localhost', database=r'm:\MEDICUS\data\medicus.FDB',
user='sysdba', password='masterkey',charset='WIN1250')
# Create a Cursor object that operates in the context of Connection con:
cur = con.cursor()
# import openpyxl module
import openpyxl
import xlwings as xw
wb = openpyxl.Workbook()
sheet = wb.active
# wb.save("sample.xlsx")
#Načtení registrovaných pacientů
cur.execute("select rodcis,prijmeni,jmeno,datum_registrace,registr.idpac,poj from registr join kar on registr.idpac=kar.idpac where kar.vyrazen!='A' and kar.rodcis is not null and idicp!=0 and datum_zruseni is null")
nacteno=cur.fetchall()
print(len(nacteno))
wb.create_sheet('Registrovani',0)
sheet=wb['Registrovani']
sheet.append(["Rodne cislo","Prijmeni","Jmeno","Datum registrace","ID pacienta","Pojistovna"])
#nacteno jsou registrovani
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Načtení receptů
cur.execute("""select
kar.rodcis,
TRIM(kar.prijmeni) ||' '|| substring(kar.jmeno from 1 for 1) ||'.' as jmeno,
recept.datum,
TRIM(recept.lek) ||' '|| trim(recept.dop) as lek,
recept.expori AS Poc,
CASE
WHEN recept.opakovani is null THEN 1
ELSE recept.opakovani
END AS OP,
recept.uhrada,
recept.dsig,
recept.NOTIFIKACE_KONTAKT as notifikace,
recept_epodani.erp,
recept_epodani.vystavitel_jmeno,
recept.atc,
recept.CENAPOJ,
recept.cenapac
from recept LEFT Join RECEPT_EPODANI on recept.id_epodani=recept_epodani.id
LEFT join kar on recept.idpac=kar.idpac
order by datum desc,erp desc"""
)
nacteno=cur.fetchall()
print(len(nacteno))
wb.create_sheet('Recepty',0)
sheet=wb['Recepty']
sheet.title="Recepty"
sheet.append(["Rodné číslo","Jméno","Datum vystavení","Název leku","Poč.","Op.","Úhr.","Da signa","Notifikace","eRECEPT","Vystavil","ATC","Cena pojišťovna","Cena pacient"])
#nacteno jsou ockovani
for row in nacteno:
try:
sheet.append(row)
except:
continue
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Načtení vykony vsech
cur.execute("select dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,dokladd.pocvyk,dokladd.ddgn,dokladd.body,vykony.naz "
"from kar join dokladd on kar.rodcis=dokladd.rodcis join vykony on dokladd.kod=vykony.kod where (datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null) order by dokladd.datose desc,dokladd.rodcis")
wb.create_sheet('Vykony',0)
sheet=wb['Vykony']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum vykonu","Kod","Pocet","Dg.","Body","Nazev"])
#nacteno jsou ockovani
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Načtení neschopenek
import datetime
def pocet_dni(zacnes,konnes,pracne):
dnes=datetime.date.today()
if pracne=='A':
return (dnes-zacnes).days
if pracne=='N' and zacnes is not None and konnes is not None and zacnes<=konnes:
return (konnes-zacnes).days
else:
return "NA"
cur.execute("select nes.idpac, "
"kar.rodcis, "
"TRIM(prijmeni) ||', '|| TRIM(jmeno), "
"nes.datnes, "
"nes.ecn, "
"nes.zacnes, "
"nes.pracne, "
"nes.konnes, "
"nes.diagno, "
"nes.kondia, "
"nes.updated "
"from nes "
"left join kar on nes.idpac=kar.idpac where nes.datnes<=current_date "
"order by datnes desc")
tmpnacteno_vse=[]
nacteno_vse=cur.fetchall()
cur.execute("select nes.idpac, "
"kar.rodcis, "
"TRIM(prijmeni) ||', '|| TRIM(jmeno), "
"nes.datnes, "
"nes.ecn, "
"nes.zacnes, "
"nes.pracne, "
"nes.konnes, "
"nes.diagno, "
"nes.kondia, "
"nes.updated "
"from nes "
"left join kar on nes.idpac=kar.idpac where nes.datnes<=current_date and pracne='A'"
"order by datnes desc")
tmpnacteno_aktivni=[]
nacteno_aktivni=cur.fetchall()
for row in nacteno_vse:
tmpnacteno_vse.append((row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],pocet_dni(row[5],row[7],row[6]),row[8],row[9],row[10]))
for row in nacteno_aktivni:
(tmpnacteno_aktivni.append((row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],pocet_dni(row[5],row[7],row[6]),row[8],row[9],row[10])))
wb.create_sheet('Neschopenky všechny',0)
sheet=wb["Neschopenky všechny"]
sheet.append(["ID pac","Rodne cislo","Jmeno","Datum neschopenky","Číslo neschopenky","Zacatek","Aktivní?","Konec","Pocet dni","Diagnoza zacatel","Diagnoza konec","Aktualizovano"])
for row in tmpnacteno_vse:
sheet.append(row)
wb.create_sheet('Neschopenky aktivní',0)
sheet=wb["Neschopenky aktivní"]
sheet.append(["ID pac","Rodne cislo","Jmeno","Datum neschopenky","Číslo neschopenky","Zacatek","Aktivní?","Konec","Pocet dni","Diagnoza zacatel","Diagnoza konec","Aktualizovano"])
for row in tmpnacteno_aktivni:
sheet.append(row)
#Načtení preventivni prohlidky
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=1022 or dokladd.kod=1021) "
"order by datose desc")
wb.create_sheet('Preventivni prohlidky',0)
sheet=wb['Preventivni prohlidky']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni INR
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=01443) "
"order by datose desc")
wb.create_sheet('INR',0)
sheet=wb['INR']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni CRP
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=02230 or dokladd.kod=09111) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('CRP',0)
sheet=wb['CRP']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni Holter
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=17129) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('Holter',0)
sheet=wb['Holter']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni prostata
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and (dokladd.kod=01130 or dokladd.kod=01131 or dokladd.kod=01132 or dokladd.kod=01133 or dokladd.kod=01134) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('Prostata',0)
sheet=wb['Prostata']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni TOKS
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and "
"(dokladd.kod=15118 or dokladd.kod=15119 or dokladd.kod=15120 or dokladd.kod=15121) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('TOKS',0)
sheet=wb['TOKS']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni COVID
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and "
"(dokladd.kod=01306) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('COVID',0)
sheet=wb['COVID']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
#Nacteni Streptest
cur.execute("select all dokladd.rodcis,TRIM(prijmeni) ||', '|| TRIM(jmeno),dokladd.datose,dokladd.kod,vykony.naz,dokladd.ddgn,dokladd.body "
"from dokladd left join kar on dokladd.rodcis=kar.rodcis join vykony on dokladd.kod=vykony.kod where "
"((datose>=vykony.platiod and datose<=vykony.platido) OR (datose>=vykony.platiod and vykony.platido is null)) and "
"(dokladd.kod=02220) "
"order by datose desc,dokladd.rodcis,dokladd.kod")
wb.create_sheet('Streptest',0)
sheet=wb['Streptest']
nacteno=cur.fetchall()
print(len(nacteno))
sheet.append(["Rodne cislo","Jmeno","Datum","Kod","Název","Dg.","Body"])
for row in nacteno:
sheet.append(row)
# autofilter
for ws in wb.worksheets:
# Get the maximum number of rows and columns
max_row = ws.max_row
max_column = ws.max_column
ws.auto_filter.ref = f"A1:{openpyxl.utils.get_column_letter(max_column)}{max_row}"
# ws.auto_filter.ref = ws.dimensions
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))
# Tento modul je pouze na autofit jednotlivych sloupcu na vsech listech workbooku
file = os.path.join(PathToSaveCSV ,timestr+CSVname)
with xw.App(visible=False) as app:
wb = xw.Book(file)
for sheet in range(len(wb.sheets)):
ws = wb.sheets[sheet]
ws.autofit()
# centrování receptů
sheet = wb.sheets['Recepty']
for sloupec in ["C:C", "E:E", "F:F", "G:G", "I:I", "M:M", "N:N"]:
sheet.range(sloupec).api.HorizontalAlignment = 3 # 3 = Center
wb.save()
wb.close()

40
Trash/SMS.py Normal file
View File

@@ -0,0 +1,40 @@
import requests
def send_sms_via_diafaan():
# Diafaan SMS Server configuration
server_url = "http://localhost:9710/http/send-message" # Replace with your server address
username = "admin" # Replace with your Diafaan username
password = "" # Replace with your Diafaan password
# SMS details
to_number = "420775735276" # Recipient number with country code
message = "Hello from Python via Diafaan SMS Server!"
sender_id = "" # Optional sender ID
# Prepare the request parameters
params = {
'username': username,
'password': password,
'to': to_number,
'message': message,
'from': sender_id
}
try:
# Send the HTTP GET request
response = requests.get(server_url, params=params)
# Check the response
if response.status_code == 200:
print("SMS sent successfully!")
print("Response:", response.text)
else:
print(f"Failed to send SMS. Status code: {response.status_code}")
print("Response:", response.text)
except Exception as e:
print(f"An error occurred: {str(e)}")
# Call the function
send_sms_via_diafaan()

17
Trash/SMSCallBackDebug.py Normal file
View File

@@ -0,0 +1,17 @@
from flask import Flask, request
app = Flask(__name__)
@app.route("/diafaan-callback", methods=["GET", "POST"])
def diafaan_callback():
print("==== Callback received ====")
print("Method :", request.method)
print("Headers:", dict(request.headers))
print("Args :", request.args) # query string for GET
print("Form :", request.form) # form fields for POST
print("JSON :", request.get_json(silent=True))
print("==========================\n", flush=True)
return "OK" # must return 200 so Diafaan knows it succeeded
if __name__ == "__main__":
# Install flask if needed: pip install flask
app.run(host="0.0.0.0", port=8088)

34
Trash/eRecept.py Normal file
View File

@@ -0,0 +1,34 @@
#test přístupu do eReceptu
# erecept_poc.py
import os
from requests import Session
from requests_pkcs12 import Pkcs12Adapter
from zeep import Client
from zeep.transports import Transport
PFX_FILE = "../AMBSUKL214235369G_31DEC2024.pfx"
PFX_PASSWORD = os.getenv("Vlado7309208104++", "") # nebo zadejte přímo jako řetězec
# WSDL_URL = "https://<ERECEPT_ENDPOINT>/path?wsdl" # doplňte
WSDL_URL = "https://lekar-soap.erecept.sukl.cz/cuer/Lekar?wsdl" # doplňte
# Session s PFX (obstará klientskou autentizaci mTLS) https://lekar-soap.erecept.sukl.cz/cuer/Lekar?wsdl
sess = Session()
sess.mount("https://", Pkcs12Adapter(pkcs12_filename=PFX_FILE, pkcs12_password=PFX_PASSWORD))
# zeep klient s naší session
transport = Transport(session=sess, timeout=30)
client = Client(wsdl=WSDL_URL, transport=transport)
# Pro kontrolu: vylistuj dostupné služby a operace
for service in client.wsdl.services.values():
print(f"Service: {service.name}")
for port in service.ports.values():
ops = sorted(port.binding._operations.values(), key=lambda o: o.name)
print(f" Port: {port.name}")
for op in ops:
print(f" Operation: {op.name}")
# Příklad volání (názvy/parametry dle WSDL):
# headers = {"UserID": "...", "WorkplaceID": "..."} # ilustrativní
# resp = client.service.NazevOperace(requestPayload, _soapheaders=headers)
# print(resp)

24
Trash/fio.py Normal file
View File

@@ -0,0 +1,24 @@
import requests
import json
# Replace with your actual token
API_TOKEN = "v0GJaAVeefzV1lnx1jPCf2nFF7SuOPzzrL5tobPNsC7oCChXG4hahDYVb8Rdcex0"
# Example: download last 30 days of transactions in JSON
url = f"https://fioapi.fio.cz/v1/rest/periods/v0GJaAVeefzV1lnx1jPCf2nFF7SuOPzzrL5tobPNsC7oCChXG4hahDYVb8Rdcex0/2000-01-01/2025-07-23/transactions.json"
response = requests.get(url)
print(response)
data = response.json()
with open(r"u:\Dropbox\!!!Days\Downloads Z230\Fio\pohyby.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
#
# # Print some info
# for trans in data['accountStatement']['transactionList']['transaction']:
# print(f"Date: {trans['column0']['value']}")
# print(f"Amount: {trans['column1']['value']}")
# print(f"Currency: {trans['column14']['value']}")
# print(f"Sender/Receiver: {trans['column10']['value']}")
# print(f"Message: {trans['column16']['value']}")
# print("-" * 40)

114
Trash/funkce.py Normal file
View File

@@ -0,0 +1,114 @@
import os,fdb,datetime
# conn = fdb.connect(
# dsn=r'localhost:u:\medicus 3\data\medicus.fdb', # Database path
# user='SYSDBA', # Username
# password="masterkey", # Password,
# charset="win1250")
# cur = conn.cursor()
def zapis_file(vstupconnection,idpac,cesta,souborname,prvnizavorka,soubordate,souborfiledate,poznamka):
import funkce
cur=vstupconnection.cursor()
fileid = funkce.get_files_id(vstupconnection)
with open(os.path.join(cesta,souborname), 'rb') as f:
daticka = f.read()
query = "insert into files (id,iduzi,iddoctyp,typ,idpac,filename,body,datum,datsouboru,poznamka) values(?,?,?,?,?,?,?,?,?,?)"
cur.execute(query,(fileid,6,1,1,idpac,prvnizavorka+".pdf",daticka,soubordate,souborfiledate,poznamka[:99]))
vstupconnection.commit()
return fileid
def zapis_dekurs(vstupconnection, idpac, idodd, iduzi, idprac, idfile, filename, text, datumzpravy,
datumsouboru):
import funkce
dekursid = funkce.get_dekurs_id(vstupconnection)
cur = vstupconnection.cursor()
print("Funkce zapis_dekurs hlasí OK")
print("idpac", idpac)
print("idodd", idodd)
print("iduzi", iduzi)
print("idfile", idfile)
print("filename", filename)
print("text", text)
print("datumzpravy", datumzpravy)
print("datumsouboru", datumsouboru)
print("dekursid", dekursid)
# rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks "BOOKMARKNAME","Files:FILEID",9}}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}}
# {\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;}
# {\stylesheet{\s0\fi0\li0\ql\ri0\sb0\sa0 Norm\'e1ln\'ed;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs32\f0\ul\fs20\cf1 Odkaz;}}
# \uc1\pard\s0\plain\cs20\f0\i\fs20 P\'f8\'edlohy: {\*\bkmkstart 0}\plain\cs32\f0\ul\fs20\cf1 BOOKMARKNAME{\*\bkmkend 0}\par
# \pard\s0\plain\cs15\f0\fs20 \par
# }
# """
rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks "BOOKMARKNAME","Files:FILEID",9}}{\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 BOOKMARKNAME{\*\bkmkend 0}\par
\pard\s10\plain\cs15\f0\fs20 \par
}
"""
# id idpac filename body docid typ datum iddoctyp poznamka idpac=2 iduzi=2 datsouboru id_edokument ext_id
encodedbookmark = funkce.convert_to1250(filename)
print("Encodedbookmark", encodedbookmark)
rtf = rtf.replace("BOOKMARKNAME", encodedbookmark)
rtf = rtf.replace("FILEID", str(idfile))
rtf = rtf.replace("TEXTENTER", text)
datumzapisu = datetime.datetime.now().date()
caszapisu = datetime.datetime.now().time()
print("Datumzapisu", datumzapisu)
print("Caszapisu", caszapisu)
print("RTF", rtf)
cur.execute("insert into dekurs (id,idpac,idodd,iduzi,idprac,datum,cas,dekurs) values(?,?,?,?,?,?,?,?)",
(dekursid, idpac, idodd, iduzi, idprac, datumzapisu, caszapisu, rtf))
vstupconnection.commit()
def convert_to1250(retezec):
retezec=retezec.encode("cp1250")
retezec=str(retezec)[2:]
retezec = retezec[:-1]
retezec=retezec.replace(r"\x",r"\'")
return retezec
# x=convert_to1250("Příloha")
# print(x,len(x))
def get_dekurs_id(connection):
try:
query = "SELECT GEN_ID(Gen_Dekurs, 1) FROM RDB$DATABASE"
cur = connection.cursor()
cur.execute(query)
newid=cur.fetchone()[0]
print("Funkce GET_DEKURS_ID přiřadila nové ID:",newid)
return(newid)
except:
print("Funkce GET_DEKURS_ID nepřiřadila nové ID")
return(None)
def get_files_id(connection):
try:
query = "SELECT GEN_ID(Gen_Files, 1) FROM RDB$DATABASE"
cur=connection.cursor()
cur.execute(query)
newid=cur.fetchone()[0]
print(newid)
return(newid)
except:
return(None)
def get_idpac(rodnecislo,connection):
try:
query = "SELECT idpac,prijmeni FROM kar where rodcis=?"
cur = connection.cursor()
cur.execute(query,(rodnecislo,))
tmp_nacteno=cur.fetchone()
tmp_id = tmp_nacteno[0]
tmp_jmeno=tmp_nacteno[1]
print(f"Pacient s rodným číslem {rodnecislo} má ID {tmp_id} a jméno {tmp_jmeno}")
return (tmp_id)
except:
return(None)

38
Trash/funkce1.py Normal file
View File

@@ -0,0 +1,38 @@
import os, fdb,re
import datetime
def prejmenuj_chybny_soubor(souborname,cesta):
if souborname[0]!="":
soubornovy = "" + souborname
os.rename(os.path.join(cesta,souborname),os.path.join(cesta,soubornovy))
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

32
Trash/outlook.py Normal file
View File

@@ -0,0 +1,32 @@
import win32com.client
def process_outlook_emails_from_root():
# Connect to Outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
# Get the root folder of the mailbox
root_folder = outlook.Folders.Item(1) # Typically the first item is the root
# Recursive function to process all folders
def process_folder(folder):
print(f"\nProcessing folder: {folder.Name}")
# # Iterate through all items in the current folder
# for item in folder.Items:
# if item.Class == 43: # 43 is the class for MailItem
# print(f"Found email - Subject: {item.Subject}")
# print(f" From: {item.SenderName}")
# print(f" Received: {item.ReceivedTime}")
# # Add your email processing logic here
# Recursively process subfolders
for subfolder in folder.Folders:
process_folder(subfolder)
# Start processing from the root folder
process_folder(root_folder)
if __name__ == "__main__":
process_outlook_emails_from_root()

BIN
Trash/output.pdf Normal file

Binary file not shown.

94
Trash/p01.py Normal file
View File

@@ -0,0 +1,94 @@
import os,re,fdb,time
import datetime
import funkce
con = fdb.connect(
host='localhost', database=r'u:\MEDICUS 3\data\medicus.FDB',
user='sysdba', password='masterkey',charset='WIN1250')
# Create a Cursor object that operates in the context of Connection con:
cur = con.cursor()
cesta=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace"
for soubor in os.listdir(cesta):
if soubor.endswith('.pdf'):
#kontrola struktury
pattern=re.compile(r'(\d{9,10}) (\d{4}-\d{2}-\d{2}) (\w+, \w.+?) \[(.+?)\] \[(.+?)\]')
match=pattern.search(soubor)
print(soubor)
chyba=False
if match and len(match.groups())==5:
rc=match.group(1)
datum=match.group(2)
try:
datum_object = datetime.datetime.strptime(datum,"%Y-%m-%d").date()
print(datum_object)
except:
chyba=True
jmeno=match.group(3)
prvnizavorka=match.group(4)
druhazavorka = match.group(5)
else: chyba=True
if chyba:
soubornovy=""+soubor
if soubor[0]!="":
os.rename(os.path.join(cesta,soubor),os.path.join(cesta,soubornovy))
continue
#zde máme všechno OK rc, datum_object,jmeno,prvnizavorka,druhazavorka
#Nyní kontrola délky jména soubor, akceptáno max 100 znamk
print(soubor)
filetoinsert=os.path.join(cesta,soubor)
print(time.ctime(os.path.getctime(filetoinsert)))
datumsouboru=datetime.datetime.fromtimestamp(os.path.getctime(filetoinsert))
with open(filetoinsert, 'rb') as f:
daticka = f.read()
#newid generation
newfileid = funkce.get_files_id(con)
if newfileid is None:
print("Chyba")
continue
newdekursid= funkce.get_dekurs_id(con)
if newdekursid is None:
print("Chyba")
continue
idpac= funkce.get_idpac(rc, con)
if idpac is None:
print("Chyba")
continue
print("Bude vlozeno:")
print(f"""id: {newfileid}
iddoctyp: 2
idpac: {idpac}
filename: {soubor}
datum: {datum_object}
datsouboru: {datumsouboru}
poznamka: {prvnizavorka} {druhazavorka}""")
print(datum_object.strftime('%Y-%m-%d'))
#id idpac filename body docid typ datum iddoctyp poznamka idpac=2 iduzi=2 datsouboru id_edokument ext_id
query = "insert into files (id,iduzi,iddoctyp,typ,idpac,filename,body,datum,datsouboru,poznamka) values(?,?,?,?,?,?,?,?,?,?)"
# cur.execute(query,(newfileid,6,1,1,idpac,prvnizavorka+".pdf",daticka,datum_object,datumsouboru,druhazavorka[:99]))
cur.execute(query, (newfileid, 6, 1, 1, 9742, prvnizavorka + ".pdf", daticka, datum_object, datumsouboru, druhazavorka[:99]))
con.commit()
#zapis do dekurzu
# funkce.zapis_dekurs(con, idpac, 2, 6, 2, newfileid, prvnizavorka, "test text", datetime.date(2023, 10, 15),datetime.date(2023, 10, 15))
funkce.zapis_dekurs(con, 9742, 2, 6, 2, newfileid, datum_object.strftime('%Y-%m-%d') + " " + prvnizavorka + ": " + druhazavorka, "test text", datetime.date(2023, 10, 15),
datetime.date(2023, 10, 15))
#vymazat zpracovaný soubor
# os.remove(filetoinsert)
con.close()

BIN
Trash/page_1.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

BIN
Trash/page_2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

BIN
Trash/page_3.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

BIN
Trash/page_4.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

45
Trash/pdf2.py Normal file
View File

@@ -0,0 +1,45 @@
from pdf2image import convert_from_path
from PIL import Image
import os,time
def compress_pdf_images(input_pdf, output_pdf, quality=50):
# Convert PDF pages to images
images = convert_from_path(input_pdf)
# Compress images
compressed_images = []
for image in images:
image = image.convert("RGB")
image.save("temp.jpg", "JPEG", quality=quality)
compressed_images.append(Image.open("temp.jpg"))
image.close()
Image.close()
for attempt in range(5):
retry_delay=3
try:
# Your code that might fail
os.remove("temp.jpg")
print("Success:", result)
break # Exit the loop if successful
except Exception as e:
print(f"Attempt {attempt + 1} failed:", e)
if attempt < 5 - 1:
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
else:
print("Max retries reached. Exiting.")
# Save compressed images as a new PDF
compressed_images[0].save(output_pdf, save_all=True, append_images=compressed_images[1:])
# Usage
inputpdf=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\a.pdf"
outputpdf=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\aconverted.pdf"
# Usage
compress_pdf_images(inputpdf, outputpdf, quality=50)

236
Trash/s03soubory.py Normal file
View File

@@ -0,0 +1,236 @@
import os,shutil,fdb,time
import re,datetime,funkce
# Connect to the Firebird database
conn = fdb.connect(
dsn=r'localhost:c:\medicus 3\data\medicus.fdb', # Database path
user='SYSDBA', # Username
password="masterkey", # Password,
charset="win1250")
# cesta=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace"
cesta=r"u:\NextcloudOrdinace\Dokumentace_ke_zpracování"
# cestazpracovana=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentacezpracovaná"
cestazpracovana=r"u:\NextcloudOrdinace\Dokumentace_zpracovaná"
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):
if os.path.isfile(os.path.join(cesta,soubor)):
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))

View File

@@ -0,0 +1,82 @@
import requests
from datetime import datetime, timedelta
def get_received_sms():
# Diafaan server configuration
server_url = "http://192.168.1.113:9710/http/request-received-messages"
username = "admin"
password = ""
# Optional filters (adjust as needed)
params = {
'username': username,
'password': password,
'limit': 10, # Number of messages to retrieve
# 'startdate': (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'), # Last 24 hours
# 'enddate': datetime.now().strftime('%Y-%m-%d'),
# 'unread': 'true' # Only get unread messages (optional)
}
try:
response = requests.get(server_url, params=params)
if response.status_code == 200:
# Parse the response (typically CSV or XML format)
if 'text/csv' in response.headers.get('Content-Type', ''):
messages = parse_csv_response(response.text)
else:
messages = parse_xml_response(response.text)
print(f"Retrieved {len(messages)} messages:")
for msg in messages:
print(f"From: {msg['sender']}, Received: {msg['date']}, Message: {msg['text']}")
return messages
else:
print(f"Failed to retrieve messages. Status code: {response.status_code}")
print("Response:", response.text)
return None
except Exception as e:
print(f"An error occurred: {str(e)}")
return None
def parse_csv_response(csv_data):
"""Parse CSV formatted response from Diafaan"""
messages = []
for line in csv_data.splitlines()[1:]: # Skip header
if line.strip():
parts = line.split(',')
if len(parts) >= 4:
messages.append({
'id': parts[0],
'date': parts[1],
'sender': parts[2],
'text': ','.join(parts[3:]) # Handle commas in message text
})
return messages
def parse_xml_response(xml_data):
"""Parse XML formatted response from Diafaan"""
try:
from xml.etree import ElementTree
messages = []
root = ElementTree.fromstring(xml_data)
for msg in root.findall('message'):
messages.append({
'id': msg.find('id').text if msg.find('id') is not None else '',
'date': msg.find('date').text if msg.find('date') is not None else '',
'sender': msg.find('sender').text if msg.find('sender') is not None else '',
'text': msg.find('text').text if msg.find('text') is not None else ''
})
return messages
except Exception as e:
print(f"Error parsing XML: {str(e)}")
return []
# Call the function
received_messages = get_received_sms()

24
Trash/tagpdf.py Normal file
View File

@@ -0,0 +1,24 @@
from pypdf import PdfReader, PdfWriter
# Load the existing PDF
reader = PdfReader(r"u:\Dropbox\!!!Days\Downloads Z230\output11.pdf")
writer = PdfWriter()
# Copy all pages to the writer
for page in reader.pages:
writer.add_page(page)
#Get metadata
metadata = reader.metadata
author = metadata.get("/Author","")
author=author+', YourName'
print(author)
# Set metadata
writer.add_metadata({"/Author": ""})
writer.add_metadata({"/Author": author})
# Save the updated PDF
with open(r"u:\Dropbox\!!!Days\Downloads Z230\output11.pdf", "wb") as f:
writer.write(f)

BIN
Trash/temp.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

35
Trash/tinker.py Normal file
View File

@@ -0,0 +1,35 @@
import tkinter as tk
from tkinter import messagebox
def on_select(event):
# Get selected item's index
selection = listbox.curselection()
if selection:
index = selection[0]
# Get the selected item
item = listbox.get(index)
# Update label or show a message
label.config(text=f"Selected: {item}")
# Or display a message box
# messagebox.showinfo("Selection", f"You selected: {item}")
root = tk.Tk()
root.title("Listbox Example")
# Sample list of items
items = ["Apple", "Ban Banana", "Cherry", "Date", "Elderberry"]
# Create a Listbox widget
listbox = tk.Listbox(root)
for item in items:
listbox.insert(tk.END, item)
listbox.pack(padx=10, pady=10)
# Bind the select event
listbox.bind('<<ListboxSelect>>', on_select)
# Label to display selected item
label = tk.Label(root, text="Select an item")
label.pack(pady=5)
root.mainloop()