commit 8712668ad4698d59a5fcac06a7e1d3d93d7d8747 Author: vlado Date: Sun Mar 16 07:53:00 2025 +0100 První nahrdánícd diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/Medicus1.iml b/.idea/Medicus1.iml new file mode 100644 index 0000000..67995e4 --- /dev/null +++ b/.idea/Medicus1.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..3b38978 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..a75fd4d --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/02 Zapis dekurs.py b/02 Zapis dekurs.py new file mode 100644 index 0000000..652a4f4 --- /dev/null +++ b/02 Zapis dekurs.py @@ -0,0 +1,20 @@ +import fdb,os +from datetime import date + +from pathlib import Path +import time +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))) \ No newline at end of file diff --git a/04 kontrola souboru.py b/04 kontrola souboru.py new file mode 100644 index 0000000..2b419c9 --- /dev/null +++ b/04 kontrola souboru.py @@ -0,0 +1,23 @@ + +import os,shutil,fdb +import re,datetime,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) \ No newline at end of file diff --git a/PDF optimization.py b/PDF optimization.py new file mode 100644 index 0000000..569273a --- /dev/null +++ b/PDF optimization.py @@ -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") \ No newline at end of file diff --git a/PDF3.py b/PDF3.py new file mode 100644 index 0000000..7124873 --- /dev/null +++ b/PDF3.py @@ -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") \ No newline at end of file diff --git a/PDFOpenView.py b/PDFOpenView.py new file mode 100644 index 0000000..2efe104 --- /dev/null +++ b/PDFOpenView.py @@ -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') \ No newline at end of file diff --git a/PDFmanipulation.py b/PDFmanipulation.py new file mode 100644 index 0000000..ee17244 --- /dev/null +++ b/PDFmanipulation.py @@ -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)) \ No newline at end of file diff --git a/funkce.py b/funkce.py new file mode 100644 index 0000000..8520764 --- /dev/null +++ b/funkce.py @@ -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) + diff --git a/funkce1.py b/funkce1.py new file mode 100644 index 0000000..edd6aac --- /dev/null +++ b/funkce1.py @@ -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 \ No newline at end of file diff --git a/output.pdf b/output.pdf new file mode 100644 index 0000000..33b132f Binary files /dev/null and b/output.pdf differ diff --git a/p01.py b/p01.py new file mode 100644 index 0000000..83f2c90 --- /dev/null +++ b/p01.py @@ -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() + + diff --git a/page_1.jpg b/page_1.jpg new file mode 100644 index 0000000..1e65874 Binary files /dev/null and b/page_1.jpg differ diff --git a/page_2.jpg b/page_2.jpg new file mode 100644 index 0000000..0408f7a Binary files /dev/null and b/page_2.jpg differ diff --git a/page_3.jpg b/page_3.jpg new file mode 100644 index 0000000..6fb10e9 Binary files /dev/null and b/page_3.jpg differ diff --git a/page_4.jpg b/page_4.jpg new file mode 100644 index 0000000..3f27d8d Binary files /dev/null and b/page_4.jpg differ diff --git a/pdf2.py b/pdf2.py new file mode 100644 index 0000000..5fd5478 --- /dev/null +++ b/pdf2.py @@ -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) \ No newline at end of file diff --git a/s03soubory.py b/s03soubory.py new file mode 100644 index 0000000..92a9a5a --- /dev/null +++ b/s03soubory.py @@ -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)) + diff --git a/temp.jpg b/temp.jpg new file mode 100644 index 0000000..201c67a Binary files /dev/null and b/temp.jpg differ