-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcar_identifier_gui.py
More file actions
2828 lines (2472 loc) · 126 KB
/
car_identifier_gui.py
File metadata and controls
2828 lines (2472 loc) · 126 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Car Identifier GUI with Ollama
Enhanced version with better model configuration and dark theme
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
import json
import base64
import os
import io
from pathlib import Path
from PIL import Image, ImageTk, ImageFile
# Allow very large images without DecompressionBomb errors and handle truncated files
Image.MAX_IMAGE_PIXELS = None
ImageFile.LOAD_TRUNCATED_IMAGES = True
import ollama
try:
import ttkbootstrap as tb
except Exception:
tb = None
class CarIdentifierGUI:
def __init__(self, root):
self.root = root
self.root.title("Car Identifier - Ollama")
self.root.geometry("1200x800")
# Dark theme colors
self.colors = {
'bg_dark': '#1e1e1e',
'bg_medium': '#2d2d2d',
'bg_light': '#3c3c3c',
'accent': '#007acc',
'accent_hover': '#005a9e',
'text_primary': '#ffffff',
'text_secondary': '#cccccc',
'text_muted': '#999999',
'border': '#404040',
'success': '#28a745',
'warning': '#ffc107',
'error': '#dc3545'
}
# Apply dark theme
self.root.configure(bg=self.colors['bg_dark'])
self.setup_dark_theme()
# Variables
self.current_image_path = None
self.current_image = None
self.photo = None
self.identified_data = {}
self.auto_approve = tk.BooleanVar(value=False)
self.high_fidelity_input = tk.BooleanVar(value=True)
self.enhanced_inference = tk.BooleanVar(value=False)
self.processing = False
self.batch_folder = None
self.batch_processing = False
# Verification toggle
self.verify_second_pass = tk.BooleanVar(value=True)
# Metadata handling preferences
self.overwrite_existing = tk.StringVar(value="skip") # "skip", "overwrite", "ask"
self.recursive_scan = tk.BooleanVar(value=True)
# Last identified image tracking
self.last_identified_image_path = None
self.last_identified_data = {}
self.last_identified_thumbnail = None
# Ollama client
self.ollama_client = ollama.Client(host='http://localhost:11434', timeout=60)
self.model_name = 'qwen2.5vl:32b-q4_K_M' # Enhanced vision model for better logo/text recognition
self.setup_ui()
self.check_ollama_connection()
# Warm up model to reduce first-image latency and keep it in GPU memory
try:
self._warmup_model_async()
except Exception:
pass
# UI helpers for themed widgets
def _button(self, parent, text, command, bootstyle='primary', **kwargs):
if tb is not None:
return tb.Button(parent, text=text, command=command, bootstyle=bootstyle, **kwargs)
return ttk.Button(parent, text=text, command=command, **kwargs)
def _combobox(self, parent, textvariable, values, width, state='readonly', bootstyle='secondary', **kwargs):
if tb is not None:
cb = tb.Combobox(parent, textvariable=textvariable, values=values, width=width, bootstyle=bootstyle, **kwargs)
else:
cb = ttk.Combobox(parent, textvariable=textvariable, values=values, width=width, **kwargs)
try:
cb.state([state])
except Exception:
try:
cb.configure(state=state)
except Exception:
pass
return cb
def _create_popup_dropdown(self, parent, variable, options_or_provider, width=14, bootstyle='secondary', on_select=None, list_height=8):
"""Create a reliable dropdown using a borderless Toplevel + Listbox next to the button."""
def _current_options():
try:
if callable(options_or_provider):
return list(options_or_provider()) or []
return list(options_or_provider) or []
except Exception:
return []
initial_text = variable.get() or (_current_options()[0] if _current_options() else 'Select')
btn = self._button(parent, text=initial_text, command=lambda: show_popup(), bootstyle=bootstyle, width=width)
popup_ref = {'win': None}
def close_popup():
try:
if popup_ref['win'] is not None:
popup_ref['win'].destroy()
finally:
popup_ref['win'] = None
def on_pick(value):
variable.set(value)
try:
btn.config(text=value)
except Exception:
pass
if callable(on_select):
on_select(value)
close_popup()
def show_popup():
# If already open, close first (toggle)
if popup_ref['win'] is not None:
close_popup()
return
opts = _current_options()
if not opts:
return
top = tk.Toplevel(self.root)
popup_ref['win'] = top
top.overrideredirect(True)
top.configure(bg=self.colors['border'])
# Position below the button
x = btn.winfo_rootx()
y = btn.winfo_rooty() + btn.winfo_height()
top.geometry(f"+{x}+{y}")
frame = tk.Frame(top, bg=self.colors['bg_light'], bd=1)
frame.pack(fill=tk.BOTH, expand=True)
lb = tk.Listbox(frame, height=min(list_height, max(1, len(opts))),
bg=self.colors['bg_light'], fg=self.colors['text_primary'],
selectbackground=self.colors['accent'], selectforeground=self.colors['text_primary'],
activestyle='none', highlightthickness=0, borderwidth=0)
sb = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=lb.yview)
lb.configure(yscrollcommand=sb.set)
lb.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb.pack(side=tk.RIGHT, fill=tk.Y)
for opt in opts:
lb.insert(tk.END, opt)
# Preselect current value
try:
current = variable.get()
if current in opts:
idx = opts.index(current)
lb.selection_set(idx)
lb.see(idx)
except Exception:
pass
def on_select_event(event=None):
try:
sel = lb.curselection()
if not sel:
return
val = lb.get(sel[0])
on_pick(val)
except Exception:
close_popup()
lb.bind('<Double-Button-1>', on_select_event)
lb.bind('<Return>', on_select_event)
lb.bind('<Escape>', lambda e: close_popup())
# Close when focus leaves
def on_focus_out(event):
# If click lands on the button, keep it (will toggle)
widget = event.widget
if widget is not top and widget is not lb:
close_popup()
top.bind('<FocusOut>', on_focus_out)
# Grab focus to detect focus-out
try:
top.focus_set()
except Exception:
pass
return btn
def _warmup_model_async(self):
"""Run a tiny dummy vision call to warm the model/GPU in the background."""
def _do_warm():
try:
# Use a small but valid image (>= 28px on the short side) to avoid model panics
from PIL import Image
import io as _io
img = Image.new('RGB', (64, 64), color=(255, 255, 255))
buf = _io.BytesIO()
img.save(buf, format='PNG')
img_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
self._chat([
{
'role': 'user',
'content': 'warmup',
'images': [img_b64]
}
])
except Exception:
pass
def _chat(self, messages):
"""Centralized chat call with keep-alive and conservative generation options."""
return self.ollama_client.chat(
model=self.model_name,
messages=messages,
keep_alive="10m",
options={
"temperature": 0.2,
"top_p": 0.8,
"num_predict": 160,
},
)
t = threading.Thread(target=_do_warm, daemon=True)
t.start()
def setup_dark_theme(self):
"""Configure dark theme styling"""
# Prefer ttkbootstrap themes for better Combobox/menu behavior
if tb is not None:
try:
self.bootstrap_style = tb.Style(theme='darkly')
style = self.bootstrap_style
except Exception:
style = ttk.Style()
else:
style = ttk.Style()
# If not using ttkbootstrap, choose a Windows-friendly theme fallback
if tb is None:
try:
style.theme_use('vista')
except tk.TclError:
try:
style.theme_use('xpnative')
except tk.TclError:
style.theme_use('clam')
# Configure colors for different widgets
style.configure('Dark.TFrame', background=self.colors['bg_dark'])
style.configure('Dark.TLabelframe', background=self.colors['bg_dark'], foreground=self.colors['text_primary'])
style.configure('Dark.TLabelframe.Label', background=self.colors['bg_dark'], foreground=self.colors['text_primary'])
# Button styling (ensure high-contrast)
style.configure('Dark.TButton',
background=self.colors['accent'],
foreground=self.colors['text_primary'],
borderwidth=0,
focuscolor='none',
font=('Segoe UI', 10, 'bold'))
style.map('Dark.TButton',
background=[('active', self.colors['accent_hover']),
('pressed', self.colors['accent_hover'])],
foreground=[('disabled', self.colors['text_muted']), ('!disabled', self.colors['text_primary'])])
# Checkbutton styling
style.configure('Dark.TCheckbutton',
background=self.colors['bg_dark'],
foreground=self.colors['text_primary'],
font=('Segoe UI', 9))
# Label styling (increase size/contrast)
style.configure('Dark.TLabel',
background=self.colors['bg_dark'],
foreground=self.colors['text_primary'],
font=('Segoe UI', 10))
# Progress bar styling
style.configure('Dark.Horizontal.TProgressbar',
background=self.colors['accent'],
troughcolor=self.colors['bg_light'],
borderwidth=0)
# Entry styling
style.configure('Dark.TEntry',
fieldbackground=self.colors['bg_light'],
foreground=self.colors['text_primary'],
borderwidth=1,
relief='flat')
# Combobox styling (maximize contrast and hit-area)
style.configure('Dark.TCombobox',
fieldbackground=self.colors['bg_light'],
foreground=self.colors['text_primary'],
background=self.colors['bg_light'],
selectbackground=self.colors['accent'],
selectforeground=self.colors['text_primary'],
arrowcolor=self.colors['text_primary'],
borderwidth=1,
relief='flat',
padding=6)
style.map('Dark.TCombobox',
fieldbackground=[('readonly', self.colors['bg_light']), ('!disabled', self.colors['bg_light'])],
foreground=[('readonly', self.colors['text_primary']), ('!disabled', self.colors['text_primary'])],
background=[('readonly', self.colors['bg_light']), ('!disabled', self.colors['bg_light'])],
arrowcolor=[('active', self.colors['accent']), ('!active', self.colors['text_primary'])])
# Ensure dropdown list (Listbox) colors are dark-theme friendly
try:
self.root.option_add('*TCombobox*Listbox.background', self.colors['bg_light'])
self.root.option_add('*TCombobox*Listbox.foreground', self.colors['text_primary'])
self.root.option_add('*TCombobox*Listbox.selectBackground', self.colors['accent'])
self.root.option_add('*TCombobox*Listbox.selectForeground', self.colors['text_primary'])
self.root.option_add('*TCombobox*Listbox.font', 'Segoe UI 9')
except Exception:
pass
def setup_ui(self):
# Main frame
main_frame = ttk.Frame(self.root, style='Dark.TFrame')
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Title with gradient effect
title_frame = ttk.Frame(main_frame, style='Dark.TFrame')
title_frame.pack(fill=tk.X, pady=(0, 20))
self.title_label = ttk.Label(title_frame,
text=f"🚗 Car Identifier - Model: {getattr(self, 'model_name', 'loading...')}",
font=('Segoe UI', 18, 'bold'),
foreground=self.colors['accent'],
style='Dark.TLabel')
self.title_label.pack()
subtitle_label = ttk.Label(title_frame,
text="Advanced AI-powered car identification and metadata tagging",
font=('Segoe UI', 10),
foreground=self.colors['text_secondary'],
style='Dark.TLabel')
subtitle_label.pack(pady=(5, 0))
# Control frame with modern styling
control_frame = ttk.Frame(main_frame, style='Dark.TFrame')
control_frame.pack(fill=tk.X, pady=(0, 15))
# Create button container with rounded corners effect
button_container = ttk.Frame(control_frame, style='Dark.TFrame')
button_container.pack(fill=tk.X, pady=5)
# File selection button
select_btn = self._button(button_container, text="📁 Select Image",
command=self.select_image, bootstyle='primary')
select_btn.pack(side=tk.LEFT, padx=(0, 10))
# Batch folder selection button
folder_btn = self._button(button_container, text="📂 Select Folder",
command=self.select_folder, bootstyle='secondary')
folder_btn.pack(side=tk.LEFT, padx=(0, 10))
# Process button
self.process_btn = self._button(button_container, text="🔍 Process Image",
command=self.process_image, bootstyle='success')
self.process_btn.pack(side=tk.LEFT, padx=(0, 10))
# Batch process button
self.batch_process_btn = self._button(button_container, text="⚡ Batch Process",
command=self.batch_process_folder, bootstyle='warning')
self.batch_process_btn.pack(side=tk.LEFT, padx=(0, 10))
# Options frame
options_frame = ttk.Frame(control_frame, style='Dark.TFrame')
options_frame.pack(fill=tk.X, pady=5)
# Auto approve checkbox
auto_approve_cb = ttk.Checkbutton(options_frame, text="✅ Auto Approve",
variable=self.auto_approve, style='Dark.TCheckbutton')
auto_approve_cb.pack(side=tk.LEFT, padx=(0, 20))
# Embed metadata checkbox
self.embed_metadata = tk.BooleanVar(value=True)
embed_metadata_cb = ttk.Checkbutton(options_frame, text="💾 Embed in JPG",
variable=self.embed_metadata, style='Dark.TCheckbutton')
embed_metadata_cb.pack(side=tk.LEFT, padx=(0, 20))
# High fidelity input toggle
hf_cb = ttk.Checkbutton(options_frame, text="🖼️ High Fidelity Input",
variable=self.high_fidelity_input, style='Dark.TCheckbutton')
hf_cb.pack(side=tk.LEFT, padx=(0, 20))
# Toggle for enhanced inference (persona + crops)
enh_cb = ttk.Checkbutton(options_frame, text="🤖 Enhanced Reasoning",
variable=self.enhanced_inference, style='Dark.TCheckbutton')
enh_cb.pack(side=tk.LEFT, padx=(0, 20))
# Second-pass verification toggle
verify_cb = ttk.Checkbutton(options_frame, text="🔎 Verify (2nd Pass)",
variable=self.verify_second_pass, style='Dark.TCheckbutton')
verify_cb.pack(side=tk.LEFT, padx=(0, 20))
# Metadata handling dropdown
metadata_label = ttk.Label(options_frame, text="Existing Metadata:", style='Dark.TLabel')
metadata_label.pack(side=tk.LEFT, padx=(0, 5))
# Menu-based dropdown (more reliable than Combobox on some systems)
self.overwrite_dropdown_btn = self._create_popup_dropdown(
options_frame, self.overwrite_existing, ["skip", "overwrite", "ask"], width=12, bootstyle='secondary')
self.overwrite_dropdown_btn.pack(side=tk.LEFT, padx=(0, 20))
# Recursive scan checkbox
recursive_cb = ttk.Checkbutton(options_frame, text="📁 Recursive Scan",
variable=self.recursive_scan, style='Dark.TCheckbutton')
recursive_cb.pack(side=tk.LEFT, padx=(0, 20))
# Model selection dropdown
model_label = ttk.Label(options_frame, text="Model:", style='Dark.TLabel')
model_label.pack(side=tk.LEFT, padx=(0, 5))
self.selected_model_var = tk.StringVar(value=self.model_name)
# Reliable menu-based dropdown for model selection
def on_model_pick(value):
self.selected_model_var.set(value)
self.on_model_selected()
self._model_parent_container = options_frame
self.model_dropdown_btn = self._create_popup_dropdown(options_frame, self.selected_model_var,
[self.model_name], width=35,
bootstyle='secondary', on_select=on_model_pick)
self.model_dropdown_btn.pack(side=tk.LEFT, padx=(0, 5))
refresh_btn = self._button(options_frame,
text="🔄 Refresh Models",
command=self._initialize_model_selector, bootstyle='info')
refresh_btn.pack(side=tk.LEFT, padx=(5, 0))
# Additional picker dialog if desired
# pick_btn = self._button(options_frame,
# text="🔽 Pick",
# command=self._open_model_picker_dialog, bootstyle='info')
# pick_btn.pack(side=tk.LEFT, padx=(5, 0))
# (duplicate Existing Metadata dropdown removed)
# Status and progress frame
status_frame = ttk.Frame(control_frame, style='Dark.TFrame')
status_frame.pack(fill=tk.X, pady=5)
# Status label with icon
self.status_label = ttk.Label(status_frame, text="🟢 Ready",
font=('Segoe UI', 9),
foreground=self.colors['text_secondary'],
style='Dark.TLabel')
self.status_label.pack(side=tk.RIGHT)
# Progress bar for batch processing
self.progress_var = tk.DoubleVar()
self.progress_bar = ttk.Progressbar(status_frame, variable=self.progress_var,
maximum=100, length=200,
style='Dark.Horizontal.TProgressbar')
self.progress_bar.pack(side=tk.RIGHT, padx=(0, 10))
self.progress_bar.pack_forget() # Hidden by default
# Main content frame
content_frame = ttk.Frame(main_frame, style='Dark.TFrame')
content_frame.pack(fill=tk.BOTH, expand=True)
# Left panel - Image display
left_panel = ttk.Frame(content_frame, style='Dark.TFrame')
left_panel.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 10))
# Image frame with dark styling
image_frame = ttk.LabelFrame(left_panel, text="🖼️ Image Preview",
style='Dark.TLabelframe')
image_frame.pack(fill=tk.BOTH, expand=True)
# Canvas for image display with dark background
self.canvas = tk.Canvas(image_frame, bg=self.colors['bg_light'],
relief=tk.FLAT, bd=0, highlightthickness=0)
self.canvas.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Right panel - Results and controls
right_panel = ttk.Frame(content_frame, style='Dark.TFrame')
right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, padx=(10, 0))
# Results frame
results_frame = ttk.LabelFrame(right_panel, text="📊 Identified Data",
style='Dark.TLabelframe')
results_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
# Results text with dark theme
self.results_text = tk.Text(results_frame, height=15, width=50, wrap=tk.WORD,
bg=self.colors['bg_light'], fg=self.colors['text_primary'],
insertbackground=self.colors['text_primary'],
selectbackground=self.colors['accent'],
font=('Consolas', 9),
relief=tk.FLAT, bd=0)
results_scrollbar = ttk.Scrollbar(results_frame, orient=tk.VERTICAL,
command=self.results_text.yview)
self.results_text.configure(yscrollcommand=results_scrollbar.set)
self.results_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
results_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Hide duplicate Identified Data panel (shown in Last Results)
results_frame.pack_forget()
# Action buttons frame
button_frame = ttk.Frame(right_panel, style='Dark.TFrame')
button_frame.pack(fill=tk.X, pady=(0, 10))
# Approve button with success color
self.approve_btn = self._button(button_frame, text="✅ Approve & Save",
command=self.approve_and_save, bootstyle='success')
self.approve_btn.config(state=tk.DISABLED)
self.approve_btn.pack(side=tk.LEFT, padx=(0, 10))
# Reject button
self.reject_btn = self._button(button_frame, text="❌ Reject",
command=self.reject_results, bootstyle='danger')
self.reject_btn.config(state=tk.DISABLED)
self.reject_btn.pack(side=tk.LEFT)
# Metadata editor frame
metadata_frame = ttk.LabelFrame(right_panel, text="📝 Metadata Editor",
style='Dark.TLabelframe')
metadata_frame.pack(fill=tk.BOTH, expand=True)
# Metadata text with dark theme
self.metadata_text = tk.Text(metadata_frame, height=10, width=50, wrap=tk.WORD,
bg=self.colors['bg_light'], fg=self.colors['text_primary'],
insertbackground=self.colors['text_primary'],
selectbackground=self.colors['accent'],
font=('Consolas', 9),
relief=tk.FLAT, bd=0)
metadata_scrollbar = ttk.Scrollbar(metadata_frame, orient=tk.VERTICAL,
command=self.metadata_text.yview)
self.metadata_text.configure(yscrollcommand=metadata_scrollbar.set)
self.metadata_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
metadata_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Hide duplicate Metadata Editor (information also in Last Results)
metadata_frame.pack_forget()
# Bind mouse events for image navigation
self.canvas.bind("<Button-1>", self.on_canvas_click)
self.canvas.bind("<B1-Motion>", self.on_canvas_drag)
self.canvas.bind("<MouseWheel>", self.on_mousewheel)
# Image navigation variables
self.image_scale = 1.0
self.image_offset_x = 0
self.image_offset_y = 0
self.drag_start_x = 0
self.drag_start_y = 0
# Bottom panel - Last identified image and results
bottom_panel = ttk.Frame(main_frame, style='Dark.TFrame')
bottom_panel.pack(fill=tk.X, pady=(10, 0))
# Last identified frame
last_identified_frame = ttk.LabelFrame(bottom_panel, text="📋 Last Identified Image & Results",
style='Dark.TLabelframe')
last_identified_frame.pack(fill=tk.X, pady=(10, 0))
# Expand last identified area to match preview proportions
last_identified_frame.configure(height=1)
# Split the bottom panel into left (image) and right (results)
# Give more space to the image since it's now larger
last_left_panel = ttk.Frame(last_identified_frame, style='Dark.TFrame')
last_left_panel.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(5, 10), pady=5)
last_right_panel = ttk.Frame(last_identified_frame, style='Dark.TFrame')
last_right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, padx=(10, 5), pady=5)
# Last identified image frame
last_image_frame = ttk.LabelFrame(last_left_panel, text="🖼️ Last Identified Image",
style='Dark.TLabelframe')
last_image_frame.pack(fill=tk.BOTH, expand=True)
# Last identified image canvas (sync size with main preview on resize)
self.last_image_canvas = tk.Canvas(last_image_frame, bg=self.colors['bg_light'],
relief=tk.FLAT, bd=0, highlightthickness=0)
self.last_image_canvas.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Last identified results frame
last_results_frame = ttk.LabelFrame(last_right_panel, text="📊 Last Results",
style='Dark.TLabelframe')
last_results_frame.pack(fill=tk.BOTH, expand=True)
# Last results text with dark theme
self.last_results_text = tk.Text(last_results_frame, height=12, width=60, wrap=tk.WORD,
bg=self.colors['bg_light'], fg=self.colors['text_primary'],
insertbackground=self.colors['text_primary'],
selectbackground=self.colors['accent'],
font=('Consolas', 9),
relief=tk.FLAT, bd=0)
last_results_scrollbar = ttk.Scrollbar(last_results_frame, orient=tk.VERTICAL,
command=self.last_results_text.yview)
self.last_results_text.configure(yscrollcommand=last_results_scrollbar.set)
self.last_results_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
last_results_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Initialize with placeholder text
self.last_results_text.insert(1.0, "No images have been identified yet.\n\nProcess an image to see results here.")
self.last_results_text.config(state=tk.DISABLED)
# Populate model selector after UI is ready (non-blocking, but do not change current model)
try:
self._initialize_model_selector()
except Exception:
pass
def update_last_identified_panel(self, image_path, identified_data, raw_response):
"""Update the last identified panel with new results"""
try:
# Update the last identified data
self.last_identified_image_path = image_path
self.last_identified_data = identified_data.copy()
# Create last identified image display
self.create_last_identified_image(image_path)
# Update results text
self.update_last_results_display(raw_response)
except Exception as e:
print(f"Error updating last identified panel: {str(e)}")
def create_last_identified_image(self, image_path):
"""Create a display image for the last identified image (same size as main preview)"""
try:
if image_path and os.path.exists(image_path):
# Open image
img = Image.open(image_path)
# Get canvas dimensions
canvas_width = self.last_image_canvas.winfo_width()
canvas_height = self.last_image_canvas.winfo_height()
if canvas_width <= 1 or canvas_height <= 1:
# Canvas not yet sized, schedule redisplay
self.root.after(100, lambda: self.create_last_identified_image(image_path))
return
# Calculate scale to fit image in canvas (same logic as main display)
img_width, img_height = img.size
scale_x = canvas_width / img_width
scale_y = canvas_height / img_height
scale = min(scale_x, scale_y, 1.0) # Don't scale up
# Resize image
new_width = int(img_width * scale)
new_height = int(img_height * scale)
resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Convert to PhotoImage
self.last_identified_thumbnail = ImageTk.PhotoImage(resized_img)
# Clear canvas and display image
self.last_image_canvas.delete("all")
# Center the image
x = (canvas_width - new_width) // 2
y = (canvas_height - new_height) // 2
self.last_image_canvas.create_image(x, y, anchor=tk.NW, image=self.last_identified_thumbnail)
except Exception as e:
print(f"Error creating last identified image: {str(e)}")
def update_last_results_display(self, raw_response):
"""Update the last results display with new data"""
try:
# Enable text widget for editing
self.last_results_text.config(state=tk.NORMAL)
# Clear existing content
self.last_results_text.delete(1.0, tk.END)
# Add timestamp and file info
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
filename = os.path.basename(self.last_identified_image_path) if self.last_identified_image_path else "Unknown"
header = f"📅 Processed: {timestamp}\n📁 File: {filename}\n\n"
self.last_results_text.insert(tk.END, header)
# Add the raw response
self.last_results_text.insert(tk.END, raw_response)
# Disable text widget to make it read-only
self.last_results_text.config(state=tk.DISABLED)
except Exception as e:
print(f"Error updating last results display: {str(e)}")
def check_ollama_connection(self):
"""Check if Ollama is running and the selected model is available."""
try:
if self._model_exists(self.model_name):
self.status_label.config(text=f"🟢 Ollama connected - {self.model_name} ready",
foreground=self.colors['success'])
return
# Only warn (no auto-switching)
self.status_label.config(text=f"🟡 {self.model_name} model not found - please pull it",
foreground=self.colors['warning'])
messagebox.showwarning("Model Not Found",
f"{self.model_name} model not found. Please run: ollama pull {self.model_name}")
except Exception as e:
self.status_label.config(text="🔴 Ollama connection failed",
foreground=self.colors['error'])
messagebox.showerror("Connection Error",
f"Failed to connect to Ollama: {str(e)}\n"
"Please ensure Ollama is running on localhost:11434")
def _initialize_model_selector(self):
"""Populate the model dropdown with available Ollama models."""
try:
names = self._list_ollama_model_names()
# Keep current model if not present in the list
if self.model_name and not any(self._names_match(self.model_name, n) for n in names):
names.insert(0, self.model_name)
if names:
# Update menu-based model dropdown
try:
self.model_dropdown_btn.destroy()
except Exception:
pass
def on_model_pick(value):
self.selected_model_var.set(value)
self.on_model_selected()
host_parent = getattr(self, 'model_dropdown_btn', None)
host_parent = host_parent.master if host_parent is not None else self._model_parent_container
self.model_dropdown_btn = self._create_popup_dropdown(
host_parent,
self.selected_model_var, names, width=35, bootstyle='secondary', on_select=on_model_pick)
self.model_dropdown_btn.pack(side=tk.LEFT, padx=(0, 5))
if any(self._names_match(self.model_name, n) for n in names):
self.selected_model_var.set(self.model_name)
else:
self.selected_model_var.set(names[0])
self.model_name = names[0]
self.title_label.config(text=f"🚗 Car Identifier - Model: {self.model_name}")
# Immediately check connection and possibly warm the chosen model
self.check_ollama_connection()
# Show count of models discovered
try:
self.status_label.config(text=f"🟢 Models available: {len(names)} | Current: {self.model_name}",
foreground=self.colors['success'])
except Exception:
pass
else:
self.selected_model_var.set(self.model_name)
except Exception as e:
self.status_label.config(text=f"🟡 Unable to list models: {str(e)}",
foreground=self.colors['warning'])
self.selected_model_var.set(self.model_name)
def _open_overwrite_picker_dialog(self):
"""Fallback dialog to pick Existing Metadata handling mode."""
options = ["skip", "overwrite", "ask"]
dlg = tk.Toplevel(self.root)
dlg.title("Existing Metadata Handling")
dlg.configure(bg=self.colors['bg_dark'])
dlg.geometry("360x200")
dlg.transient(self.root)
dlg.grab_set()
ttk.Label(dlg, text="When metadata already exists, choose action:",
style='Dark.TLabel').pack(pady=(12, 8))
var = tk.StringVar(value=self.overwrite_existing.get())
radios_frame = ttk.Frame(dlg, style='Dark.TFrame')
radios_frame.pack(fill=tk.BOTH, expand=True, padx=12)
for opt in options:
ttk.Radiobutton(radios_frame, text=opt.capitalize(), value=opt,
variable=var, style='Dark.TCheckbutton').pack(anchor='w', pady=4)
btns = ttk.Frame(dlg, style='Dark.TFrame')
btns.pack(fill=tk.X, padx=12, pady=(0, 12))
def on_ok():
choice = var.get()
self.overwrite_existing.set(choice)
try:
self.overwrite_combo.set(choice)
except Exception:
pass
dlg.destroy()
def on_cancel():
dlg.destroy()
ok_btn = ttk.Button(btns, text="OK", command=on_ok, style='Dark.TButton')
cancel_btn = ttk.Button(btns, text="Cancel", command=on_cancel, style='Dark.TButton')
ok_btn.pack(side=tk.RIGHT, padx=6)
cancel_btn.pack(side=tk.RIGHT)
def _open_model_picker_dialog(self):
"""Fallback picker dialog in case the combobox dropdown is not visible on this theme/OS."""
try:
names = self._list_ollama_model_names()
except Exception:
names = [self.model_name]
dlg = tk.Toplevel(self.root)
dlg.title("Select Ollama Model")
dlg.configure(bg=self.colors['bg_dark'])
dlg.geometry("520x420")
dlg.transient(self.root)
dlg.grab_set()
lbl = ttk.Label(dlg, text="Available Models", style='Dark.TLabel')
lbl.pack(pady=(10, 5))
frame = ttk.Frame(dlg, style='Dark.TFrame')
frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
listbox = tk.Listbox(frame,
bg=self.colors['bg_light'], fg=self.colors['text_primary'],
selectbackground=self.colors['accent'],
selectforeground=self.colors['text_primary'],
activestyle='dotbox')
sb = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=listbox.yview)
listbox.configure(yscrollcommand=sb.set)
listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb.pack(side=tk.RIGHT, fill=tk.Y)
for n in names:
listbox.insert(tk.END, n)
# Pre-select current
try:
idx = next((i for i, n in enumerate(names) if self._names_match(n, self.model_name)), 0)
listbox.selection_set(idx)
listbox.see(idx)
except Exception:
pass
btns = ttk.Frame(dlg, style='Dark.TFrame')
btns.pack(fill=tk.X, padx=10, pady=(0, 10))
def on_select():
try:
sel = listbox.curselection()
if not sel:
return
chosen = listbox.get(sel[0])
self.model_name = chosen
self.selected_model_var.set(chosen)
self.title_label.config(text=f"🚗 Car Identifier - Model: {self.model_name}")
self.check_ollama_connection()
try:
self._warmup_model_async()
except Exception:
pass
dlg.destroy()
except Exception:
dlg.destroy()
def on_cancel():
dlg.destroy()
select_btn = ttk.Button(btns, text="Select", command=on_select, style='Dark.TButton')
cancel_btn = ttk.Button(btns, text="Cancel", command=on_cancel, style='Dark.TButton')
select_btn.pack(side=tk.RIGHT, padx=5)
cancel_btn.pack(side=tk.RIGHT)
# Double-click to select
listbox.bind('<Double-Button-1>', lambda e: on_select())
def _list_ollama_model_names(self):
"""Return a list of model names available in Ollama, tolerant to varied response shapes."""
all_names = []
# 0) Try HTTP API first for consistent structure
try:
http_names = self._list_models_via_http()
if http_names:
all_names.extend(http_names)
except Exception:
pass
# 1) Collect from Python client
try:
models = self.ollama_client.list()
except Exception:
models = None
if isinstance(models, tuple) and len(models) >= 1:
models = models[0]
if isinstance(models, dict):
model_list_client = models.get('models') if isinstance(models.get('models'), (list, tuple)) else [models]
elif isinstance(models, (list, tuple)):
model_list_client = models
else:
model_list_client = []
client_names = []
for entry in model_list_client:
name = None
if isinstance(entry, dict):
name = entry.get('name') or entry.get('model') or entry.get('tag') or entry.get('digest')
elif isinstance(entry, (str, bytes)):
name = entry.decode('utf-8', errors='ignore') if isinstance(entry, bytes) else entry
elif isinstance(entry, (list, tuple)):
# Try to extract a string or dict name from the sequence
for part in entry:
if isinstance(part, str):
name = part
break
if isinstance(part, dict):
name = part.get('name') or part.get('model')
if name:
break
else:
# Some SDKs may return objects; try common attributes
try:
name = getattr(entry, 'name', None) or getattr(entry, 'model', None)
except Exception:
name = None
if name:
client_names.append(name)
all_names.extend(client_names)
# 2) Collect from CLI JSON if available
try:
import subprocess, json as _json
result = subprocess.run(['ollama', 'list', '--format', 'json'],
capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
parsed = _json.loads(result.stdout)
if isinstance(parsed, dict) and 'models' in parsed:
cli_models = parsed['models']
elif isinstance(parsed, list):
cli_models = parsed
else:
cli_models = []
cli_names = []
for entry in cli_models:
if isinstance(entry, dict):
nm = entry.get('name') or entry.get('model') or entry.get('tag')
else:
nm = str(entry)
if nm:
cli_names.append(nm)
all_names.extend(cli_names)
else:
raise RuntimeError('json list failed')
except Exception:
# 3) Plain text CLI fallback
try:
import subprocess
result = subprocess.run(['ollama', 'list'], capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout:
lines = [ln.strip() for ln in result.stdout.splitlines() if ln.strip()]
if lines and lines[0].upper().startswith('NAME'):
lines = lines[1:]
text_names = [ln.split()[0] for ln in lines if ln]
all_names.extend(text_names)
except Exception:
pass
# Deduplicate preserving order (case/format-insensitive)
seen = set()
unique_names = []
for n in all_names:
key = self._normalize_name(n)
if key not in seen:
seen.add(key)
unique_names.append(n)
return unique_names
def _get_ollama_base_url(self):
try:
# Client may store base URL differently; best effort to recover
base = getattr(self.ollama_client, 'host', None) or getattr(self.ollama_client, 'base_url', None)
if not base:
base = 'http://localhost:11434'
return str(base).rstrip('/')
except Exception: