import os,time,tkinter as tk,logging
from tkinter import ttk,filedialog,messagebox
from PIL import Image,ImageTk
from collections import defaultdict
import datetime,threading,asyncio
from DTKLPR5 import DTKLPRLibrary,LPREngine,LPRParams,BURN_POS,LicensePlate
from DTKVID import DTKVIDLibrary,VideoCapture,VideoFrame

lib_path='C:\\Users\\omar\\OneDrive\\Рабочий стол\\DTKLPRSDK_Trial\\lib\\windows\\x64'
os.environ['PATH']=lib_path+os.pathsep+os.environ['PATH']
stopFlag,plates_data=False,defaultdict(list)
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s')

def FrameCapturedCallback(videoCapture,frame,engine):engine.PutFrame(frame,0)
def CaptureErrorCallback(videoCapture,errorCode,engine):
    global stopFlag
    if errorCode!=3:logging.error(f"Capture error: {errorCode}")
    stopFlag=True
def LicensePlateDetectedCallback(engine,plate):
    plates_data[plate.Text()].append(plate)
    logging.info(f"Detected plate: {plate.Text()}")
    return 0

class ReportPanel:
    def __init__(self,master,plates_data):
        self.master,self.plates_data,self.selected_plate=master,plates_data,None
        self.create_widgets()
    def create_widgets(self):
        self.plate_listbox=tk.Listbox(self.master,width=30)
        self.plate_listbox.pack(side=tk.LEFT,fill=tk.Y)
        self.plate_listbox.bind("<<ListboxSelect>>",self.on_plate_select)
        for plate_text in self.plates_data:self.plate_listbox.insert(tk.END,plate_text)
        self.info_frame=tk.Frame(self.master)
        self.info_frame.pack(side=tk.LEFT,fill=tk.BOTH,expand=True)
        self.plate_image_label=tk.Label(self.info_frame)
        self.plate_image_label.pack()
        self.frame_image_label=tk.Label(self.info_frame)
        self.frame_image_label.pack()
        self.info_text=tk.Text(self.info_frame,wrap=tk.WORD)
        self.info_text.pack(fill=tk.BOTH,expand=True)
        self.export_button=ttk.Button(self.info_frame,text="Export Report",command=self.export_report)
        self.export_button.pack(pady=10)
    def on_plate_select(self,event):
        selection=self.plate_listbox.curselection()
        if selection:
            self.selected_plate=self.plates_data[self.plate_listbox.get(selection[0])][0]
            self.update_info()
    def update_info(self):
        if self.selected_plate:
            try:
                plate_image=self.selected_plate.GetPlateImage().resize((300,100))
                plate_photo=ImageTk.PhotoImage(plate_image)
                self.plate_image_label.config(image=plate_photo)
                self.plate_image_label.image=plate_photo
            except Exception as e:logging.error(f"Error loading plate image: {e}")
            try:
                frame_image=self.selected_plate.GetImage().resize((300,200))
                frame_photo=ImageTk.PhotoImage(frame_image)
                self.frame_image_label.config(image=frame_photo)
                self.frame_image_label.image=frame_photo
            except Exception as e:logging.error(f"Error loading frame image: {e}")
            self.info_text.delete("1.0",tk.END)
            self.info_text.insert(tk.END,f"Plate: {self.selected_plate.Text()}\nConfidence: {self.selected_plate.Confidence()}\nCountry: {self.selected_plate.CountryCode()}\nTimestamp: {self.selected_plate.Timestamp()}\nAppearances: {len(self.plates_data[self.selected_plate.Text()])}\nFirst Appearance: {self.plates_data[self.selected_plate.Text()][0].DateTimeString()}\nLast Appearance: {self.plates_data[self.selected_plate.Text()][-1].DateTimeString()}\n")
    def export_report(self):
        file_path=filedialog.asksaveasfilename(defaultextension=".txt")
        if file_path:
            with open(file_path,"w") as f:
                f.write(f"License Plate Recognition Report - {datetime.datetime.now()}\n\n")
                for plate_text,plate_list in self.plates_data.items():
                    f.write(f"Plate: {plate_text}\nAppearances: {len(plate_list)}\nFirst Appearance: {plate_list[0].DateTimeString()}\nLast Appearance: {plate_list[-1].DateTimeString()}\n\n")
            messagebox.showinfo("Export Success","Report exported successfully!")

async def process_video(video_path,progress_var):
    global stopFlag,plates_data
    params=LPRParams(DTKLPRLibrary(lib_path))
    params.MinPlateWidth,params.MaxPlateWidth,params.Countries,params.FormatPlateText,params.RotateAngle,params.BurnFormatString,params.BurnPosition,params.NumThreads=80,300,"AZ",True,0,"%DATETIME% | Plate: %PLATE_NUM%",BURN_POS.RIGHT_TOP,8
    engine=LPREngine(params,True,LicensePlateDetectedCallback)
    if engine.IsLicensed()!=0:
        messagebox.showerror("Error",["","No License","No channels available","Cannot validate trial license"][engine.IsLicensed()])
        return
    videoCapture=VideoCapture(FrameCapturedCallback,CaptureErrorCallback,engine,DTKVIDLibrary(lib_path))
    videoCapture.StartCaptureFromFile(video_path,1)
    logging.info("Video started")
    start_time=time.time()
    while not stopFlag:
        await asyncio.sleep(0.001)
        progress_var.set(videoCapture.GetVideoFPS())
    logging.info("Video stopped")
    videoCapture.StopCapture()
    logging.info(f"Processing time: {time.time()-start_time} seconds")
    report_window=tk.Toplevel(root)
    report_window.title("License Plate Recognition Report")
    ReportPanel(report_window,plates_data)

def browse_video():
    video_path=filedialog.askopenfilename(filetypes=[("Video Files","*.avi *.mp4 *.mov")])
    if video_path:
        progress_var=tk.DoubleVar()
        progress_bar=ttk.Progressbar(root,variable=progress_var,maximum=100)
        progress_bar.pack(fill=tk.X,padx=10,pady=10)
        threading.Thread(target=asyncio.run,args=(process_video(video_path,progress_var),)).start()

root=tk.Tk()
root.title("License Plate Recognition")
ttk.Button(root,text="Browse Video",command=browse_video).pack(pady=20)
root.mainloop()













привет помоги пожалуйста, вот например я вставляю в программу видео которе идет 20 сек, он обрабатывает видео за 20 сек.... просто проблемма бывает когда у меня видео большое ! и я не могу столько ждать а еще скрипт логает и закрываеться ! 



в самой DTKLPRLibrary DTKVID  нету функциональности чтобы это исправить 



также когда я пытаюсь сделать многопочтосноть возникают ошибки с лиценцией почему то скрипт пишет что отсутствует лицензия 





пожалуйста найди решение и пришли весь весь обновленный код !