První nahrdánícd
This commit is contained in:
3
.idea/.gitignore
generated
vendored
Normal file
3
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
10
.idea/Medicus1.iml
generated
Normal file
10
.idea/Medicus1.iml
generated
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/.venv" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Python 3.12 (Medicus1)" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
6
.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
6
.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
7
.idea/misc.xml
generated
Normal file
7
.idea/misc.xml
generated
Normal file
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="Python 3.12 (Medicus1)" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.12 (Medicus1)" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/Medicus1.iml" filepath="$PROJECT_DIR$/.idea/Medicus1.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/vcs.xml
generated
Normal file
6
.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
20
02 Zapis dekurs.py
Normal file
20
02 Zapis dekurs.py
Normal file
@@ -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)))
|
||||
23
04 kontrola souboru.py
Normal file
23
04 kontrola souboru.py
Normal file
@@ -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)
|
||||
73
PDF optimization.py
Normal file
73
PDF optimization.py
Normal 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
PDF3.py
Normal file
8
PDF3.py
Normal 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
PDFOpenView.py
Normal file
22
PDFOpenView.py
Normal 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')
|
||||
22
PDFmanipulation.py
Normal file
22
PDFmanipulation.py
Normal 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))
|
||||
114
funkce.py
Normal file
114
funkce.py
Normal 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
funkce1.py
Normal file
38
funkce1.py
Normal 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
|
||||
BIN
output.pdf
Normal file
BIN
output.pdf
Normal file
Binary file not shown.
94
p01.py
Normal file
94
p01.py
Normal 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
page_1.jpg
Normal file
BIN
page_1.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.7 MiB |
BIN
page_2.jpg
Normal file
BIN
page_2.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.0 MiB |
BIN
page_3.jpg
Normal file
BIN
page_3.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
BIN
page_4.jpg
Normal file
BIN
page_4.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.7 MiB |
45
pdf2.py
Normal file
45
pdf2.py
Normal 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
s03soubory.py
Normal file
236
s03soubory.py
Normal 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))
|
||||
|
||||
Reference in New Issue
Block a user