Update image_to_caption.py
Browse files- image_to_caption.py +947 -844
image_to_caption.py
CHANGED
@@ -1,844 +1,947 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
from
|
4 |
-
import
|
5 |
-
import
|
6 |
-
import
|
7 |
-
import
|
8 |
-
|
9 |
-
import
|
10 |
-
import
|
11 |
-
import
|
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 |
-
if
|
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 |
-
try:
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
if
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
def
|
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 |
-
if
|
786 |
-
|
787 |
-
|
788 |
-
|
789 |
-
|
790 |
-
|
791 |
-
|
792 |
-
|
793 |
-
|
794 |
-
|
795 |
-
|
796 |
-
|
797 |
-
|
798 |
-
|
799 |
-
|
800 |
-
|
801 |
-
|
802 |
-
def
|
803 |
-
global
|
804 |
-
|
805 |
-
|
806 |
-
|
807 |
-
|
808 |
-
|
809 |
-
|
810 |
-
|
811 |
-
if
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import tkinter as tk
|
3 |
+
from tkinter import filedialog, messagebox, ttk
|
4 |
+
from PIL import Image as PILImage, ImageTk
|
5 |
+
import os
|
6 |
+
import queue
|
7 |
+
import threading
|
8 |
+
import torch
|
9 |
+
from transformers import AutoModelForCausalLM, LlamaTokenizer
|
10 |
+
import json
|
11 |
+
import traceback
|
12 |
+
import math
|
13 |
+
|
14 |
+
torch.set_grad_enabled(False)
|
15 |
+
|
16 |
+
stop_processing = False
|
17 |
+
error_messages = []
|
18 |
+
selected_files = []
|
19 |
+
save_directory = ""
|
20 |
+
caption_window = None
|
21 |
+
caption_frame = None
|
22 |
+
thumbnails = []
|
23 |
+
caption_text_widgets = []
|
24 |
+
error_window = None
|
25 |
+
status_var = None
|
26 |
+
num_files_var = None
|
27 |
+
errors_var = None
|
28 |
+
progress = None
|
29 |
+
prompt_var = None
|
30 |
+
max_new_tokens_var = None
|
31 |
+
do_sample_var = None
|
32 |
+
temperature_var = None
|
33 |
+
top_k_var = None
|
34 |
+
top_p_var = None
|
35 |
+
thread_count_var = None
|
36 |
+
precision_var = None
|
37 |
+
batch_size_var = None
|
38 |
+
prepend_text_var = None
|
39 |
+
append_text_var = None
|
40 |
+
caption_handling_var = None # Variable to handle radio buttons for caption handling
|
41 |
+
start_button = None
|
42 |
+
stop_button = None
|
43 |
+
model = None
|
44 |
+
prompt_entry = None
|
45 |
+
select_files_button = None
|
46 |
+
show_captions_button = None
|
47 |
+
thread_count_entry = None
|
48 |
+
precision_entry = None
|
49 |
+
batch_size_entry = None
|
50 |
+
prepend_text_entry = None
|
51 |
+
append_text_entry = None
|
52 |
+
root = None
|
53 |
+
q = queue.Queue()
|
54 |
+
|
55 |
+
current_page = 0
|
56 |
+
images_per_page = 20
|
57 |
+
total_pages = 1
|
58 |
+
content_canvas = None
|
59 |
+
search_var = None
|
60 |
+
original_selected_files = []
|
61 |
+
action_var = None
|
62 |
+
action_entry = None
|
63 |
+
|
64 |
+
def load_model():
|
65 |
+
global model, tokenizer
|
66 |
+
if model is None:
|
67 |
+
tokenizer = LlamaTokenizer.from_pretrained('lmsys/vicuna-7b-v1.5')
|
68 |
+
|
69 |
+
bit_precision = bit_precision_var.get()
|
70 |
+
|
71 |
+
load_in_4bit = load_in_8bit = False
|
72 |
+
|
73 |
+
# Thiết lập torch_type dựa trên giá trị bit_precision
|
74 |
+
if bit_precision == 4:
|
75 |
+
load_in_4bit = True
|
76 |
+
torch_type = torch.float16 # Dùng float16 khi sử dụng bitsandbytes
|
77 |
+
elif bit_precision == 8:
|
78 |
+
load_in_8bit = True
|
79 |
+
torch_type = torch.float16 # Dùng float16 khi sử dụng bitsandbytes
|
80 |
+
elif bit_precision == 16:
|
81 |
+
torch_type = torch.float16
|
82 |
+
elif bit_precision == 32:
|
83 |
+
torch_type = torch.float32
|
84 |
+
|
85 |
+
try:
|
86 |
+
import bitsandbytes as bnb
|
87 |
+
model = AutoModelForCausalLM.from_pretrained(
|
88 |
+
'THUDM/cogvlm-chat-hf',
|
89 |
+
torch_dtype=torch_type,
|
90 |
+
low_cpu_mem_usage=True,
|
91 |
+
load_in_4bit=load_in_4bit,
|
92 |
+
load_in_8bit=load_in_8bit,
|
93 |
+
trust_remote_code=True,
|
94 |
+
)
|
95 |
+
except ImportError:
|
96 |
+
# Nếu không có bitsandbytes hoặc dùng 16-bit hoặc 32-bit
|
97 |
+
model = AutoModelForCausalLM.from_pretrained(
|
98 |
+
'THUDM/cogvlm-chat-hf',
|
99 |
+
torch_dtype=torch_type,
|
100 |
+
low_cpu_mem_usage=True,
|
101 |
+
trust_remote_code=True,
|
102 |
+
)
|
103 |
+
|
104 |
+
# Chỉ chuyển mô hình sang GPU nếu không sử dụng chế độ 4-bit hoặc 8-bit
|
105 |
+
if not load_in_4bit and not load_in_8bit:
|
106 |
+
model = model.to(torch.device('cuda'))
|
107 |
+
|
108 |
+
# Đảm bảo chuyển đổi mô hình sang float32 nếu đang ở chế độ 32-bit
|
109 |
+
if bit_precision == 32:
|
110 |
+
model = model.to(torch.float32)
|
111 |
+
elif bit_precision == 16:
|
112 |
+
model = model.to(torch.float16)
|
113 |
+
|
114 |
+
model.eval()
|
115 |
+
|
116 |
+
# Kiểm tra thông tin model nạp vào
|
117 |
+
print(f"Model loaded with dtype: {torch_type}, 4bit: {load_in_4bit}, 8bit: {load_in_8bit}")
|
118 |
+
|
119 |
+
|
120 |
+
def update_and_save_config():
|
121 |
+
top_p_value = top_p_var.get() if do_sample_var.get() else None
|
122 |
+
config_entry = {
|
123 |
+
'prompt': prompt_var.get(),
|
124 |
+
'max_new_tokens': max_new_tokens_var.get(),
|
125 |
+
'temperature': temperature_var.get(),
|
126 |
+
'top_k': top_k_var.get(),
|
127 |
+
'top_p': float(top_p_value) if top_p_value is not None else None,
|
128 |
+
'bit_precision': bit_precision_var.get(), # Hợp nhất cả precision và bit
|
129 |
+
'thread_count': thread_count_var.get(),
|
130 |
+
'batch_size': batch_size_var.get(),
|
131 |
+
'prepend_text': prepend_text_var.get(),
|
132 |
+
'append_text': append_text_var.get(),
|
133 |
+
'caption_handling': caption_handling_var.get()
|
134 |
+
}
|
135 |
+
|
136 |
+
try:
|
137 |
+
with open('captions.json', 'w') as f:
|
138 |
+
json.dump(config_entry, f, indent=2)
|
139 |
+
except Exception as e:
|
140 |
+
print(f"Error saving config to captions.json: {e}")
|
141 |
+
|
142 |
+
def load_config_from_json():
|
143 |
+
try:
|
144 |
+
if os.path.exists('captions.json'):
|
145 |
+
with open('captions.json', 'r') as f:
|
146 |
+
config_entry = json.load(f)
|
147 |
+
prompt_var.set(config_entry.get('prompt', ''))
|
148 |
+
max_new_tokens_var.set(config_entry.get('max_new_tokens', 200))
|
149 |
+
temperature_var.set(config_entry.get('temperature', 1.0))
|
150 |
+
top_k_var.set(config_entry.get('top_k', 50))
|
151 |
+
top_p_var.set(config_entry.get('top_p', 0.95))
|
152 |
+
bit_precision_var.set(config_entry.get('bit_precision', 8)) # Tải bit_precision
|
153 |
+
thread_count_var.set(config_entry.get('thread_count', 4))
|
154 |
+
batch_size_var.set(config_entry.get('batch_size', 1))
|
155 |
+
prepend_text_var.set(config_entry.get('prepend_text', ''))
|
156 |
+
append_text_var.set(config_entry.get('append_text', ''))
|
157 |
+
caption_handling_var.set(config_entry.get('caption_handling', 'skip'))
|
158 |
+
|
159 |
+
prompt_entry.delete("1.0", tk.END)
|
160 |
+
prompt_entry.insert(tk.END, config_entry.get('prompt', ''))
|
161 |
+
except Exception as e:
|
162 |
+
print(f"Error loading config from captions.json: {e}")
|
163 |
+
|
164 |
+
def on_config_change(*args):
|
165 |
+
root.after(100, update_config)
|
166 |
+
|
167 |
+
def update_config():
|
168 |
+
try:
|
169 |
+
precision_value = precision_var.get()
|
170 |
+
if precision_value == "":
|
171 |
+
return # Không làm gì nếu giá trị là chuỗi rỗng
|
172 |
+
|
173 |
+
update_and_save_config()
|
174 |
+
except Exception as e:
|
175 |
+
print(f"Lỗi khi xử lý giá trị: {e}")
|
176 |
+
|
177 |
+
def on_prompt_change(event=None):
|
178 |
+
prompt_var.set(prompt_entry.get("1.0", tk.END).strip())
|
179 |
+
update_and_save_config()
|
180 |
+
|
181 |
+
def show_errors():
|
182 |
+
global error_window
|
183 |
+
if error_window is not None:
|
184 |
+
return
|
185 |
+
|
186 |
+
error_window = tk.Toplevel(root)
|
187 |
+
error_window.title("Error Details")
|
188 |
+
error_window.geometry("500x400")
|
189 |
+
|
190 |
+
error_text = tk.Text(error_window, wrap='word')
|
191 |
+
error_text.pack(expand=True, fill='both')
|
192 |
+
|
193 |
+
if error_messages:
|
194 |
+
for error in error_messages:
|
195 |
+
error_text.insert('end', error + '\n')
|
196 |
+
else:
|
197 |
+
error_text.insert('end', "No errors recorded.")
|
198 |
+
|
199 |
+
error_text.config(state='disabled')
|
200 |
+
|
201 |
+
def on_close_error_window():
|
202 |
+
global error_window
|
203 |
+
error_window.destroy()
|
204 |
+
error_window = None
|
205 |
+
|
206 |
+
error_window.protocol("WM_DELETE_WINDOW", on_close_error_window)
|
207 |
+
|
208 |
+
def validate_numeric_input(value):
|
209 |
+
if value == "" or value == "-":
|
210 |
+
return True
|
211 |
+
try:
|
212 |
+
float(value)
|
213 |
+
return True
|
214 |
+
except ValueError:
|
215 |
+
return False
|
216 |
+
|
217 |
+
def center_window(window):
|
218 |
+
window.update_idletasks()
|
219 |
+
width = window.winfo_width()
|
220 |
+
height = window.winfo_height()
|
221 |
+
x = (window.winfo_screenwidth() // 2) - (width // 2)
|
222 |
+
y = (window.winfo_screenheight() // 2) - (height // 2)
|
223 |
+
window.geometry(f'{width}x{height}+{x}+{y}')
|
224 |
+
|
225 |
+
def toggle_sampling_options():
|
226 |
+
if do_sample_var.get():
|
227 |
+
temperature_label.pack(pady=5, after=do_sample_check)
|
228 |
+
temperature_entry.pack(pady=5, after=temperature_label)
|
229 |
+
top_k_label.pack(pady=5, after=temperature_entry)
|
230 |
+
top_k_entry.pack(pady=5, after=top_k_label)
|
231 |
+
top_p_label.pack(pady=5, after=top_k_entry)
|
232 |
+
top_p_entry.pack(pady=5, after=top_p_label)
|
233 |
+
root.geometry(f"{root.winfo_width()}x{root.winfo_height() + 150}")
|
234 |
+
else:
|
235 |
+
temperature_label.pack_forget()
|
236 |
+
temperature_entry.pack_forget()
|
237 |
+
top_k_label.pack_forget()
|
238 |
+
top_k_entry.pack_forget()
|
239 |
+
top_p_label.pack_forget()
|
240 |
+
top_p_entry.pack_forget()
|
241 |
+
root.geometry(f"{root.winfo_width()}x{root.winfo_height() - 150}")
|
242 |
+
center_window(root)
|
243 |
+
|
244 |
+
def open_image_to_caption():
|
245 |
+
global bit_precision_var, root
|
246 |
+
global initial_bit_precision
|
247 |
+
global app_initialized
|
248 |
+
global stop_processing, error_messages, selected_files, save_directory, status_var, num_files_var, errors_var, progress
|
249 |
+
global prompt_var, max_new_tokens_var, do_sample_var, temperature_var, top_k_var, top_p_var, thread_count_var, precision_var, batch_size_var
|
250 |
+
global prepend_text_var, append_text_var, search_var, action_var, caption_handling_var
|
251 |
+
global start_button, stop_button
|
252 |
+
global temperature_label, temperature_entry, top_k_label, top_k_entry, top_p_label, top_p_entry
|
253 |
+
global do_sample_check, prompt_entry, select_files_button, show_captions_button, thread_count_entry, precision_entry, batch_size_entry
|
254 |
+
global prepend_text_entry, append_text_entry
|
255 |
+
global q
|
256 |
+
|
257 |
+
app_initialized = False
|
258 |
+
|
259 |
+
# Định nghĩa hàm xử lý khi bit_precision thay đổi
|
260 |
+
def on_bit_precision_change(*args):
|
261 |
+
if not app_initialized:
|
262 |
+
return
|
263 |
+
|
264 |
+
update_and_save_config()
|
265 |
+
|
266 |
+
result = messagebox.showinfo(
|
267 |
+
"Bit Precision Changed",
|
268 |
+
"You have changed the bit precision. Please restart the app for the changes to take effect."
|
269 |
+
)
|
270 |
+
|
271 |
+
if result == "ok":
|
272 |
+
root.destroy() # Tắt ứng dụng hiện tại
|
273 |
+
python = sys.executable
|
274 |
+
os.execl(python, python, "main.py")
|
275 |
+
|
276 |
+
|
277 |
+
# Initialize the main Tkinter root window
|
278 |
+
root = tk.Tk()
|
279 |
+
root.title("Image to Caption")
|
280 |
+
root.geometry("1050x950")
|
281 |
+
|
282 |
+
# Khởi tạo các biến Tkinter sau khi root đã được tạo
|
283 |
+
status_var = tk.StringVar()
|
284 |
+
num_files_var = tk.StringVar()
|
285 |
+
errors_var = tk.StringVar(value="Errors: 0")
|
286 |
+
progress = tk.IntVar()
|
287 |
+
prompt_var = tk.StringVar(value="Describe this image")
|
288 |
+
max_new_tokens_var = tk.IntVar(value=200)
|
289 |
+
do_sample_var = tk.BooleanVar(value=False)
|
290 |
+
temperature_var = tk.DoubleVar(value=1.0)
|
291 |
+
top_k_var = tk.IntVar(value=50)
|
292 |
+
top_p_var = tk.DoubleVar(value=0.95)
|
293 |
+
thread_count_var = tk.IntVar(value=4)
|
294 |
+
precision_var = tk.IntVar(value=1)
|
295 |
+
batch_size_var = tk.IntVar(value=1)
|
296 |
+
prepend_text_var = tk.StringVar()
|
297 |
+
append_text_var = tk.StringVar()
|
298 |
+
caption_handling_var = tk.StringVar(value='skip') # Default value is 'skip'
|
299 |
+
search_var = tk.StringVar() # Biến search_var khởi tạo ở đây
|
300 |
+
action_var = tk.StringVar() # Biến action_var khởi tạo ở đây
|
301 |
+
|
302 |
+
bit_precision_var = tk.IntVar(value=8)
|
303 |
+
initial_bit_precision = bit_precision_var.get()
|
304 |
+
|
305 |
+
q = queue.Queue()
|
306 |
+
|
307 |
+
validate_cmd = root.register(validate_numeric_input)
|
308 |
+
|
309 |
+
back_button = tk.Button(root, text="<-", font=('Helvetica', 14), command=return_to_menu)
|
310 |
+
back_button.pack(anchor='nw', padx=10, pady=10)
|
311 |
+
|
312 |
+
title_label = tk.Label(root, text="Image Caption Generator", font=('Helvetica', 16))
|
313 |
+
title_label.pack(pady=10)
|
314 |
+
|
315 |
+
warning_label = tk.Label(root, text="NOTE: 4-bit requires 20GB RAM and 12GB VRAM, 8-bit requires 20GB RAM and 16GB VRAM, 16-bit requires 50GB RAM and 24GB VRAM, 32-bit requires 85GB RAM and 40GB VRAM.",
|
316 |
+
font=('Helvetica', 10), fg="red", wraplength=750, justify="left")
|
317 |
+
warning_label.pack(pady=10)
|
318 |
+
|
319 |
+
select_files_button = tk.Button(root, text="Select Files", command=select_files)
|
320 |
+
select_files_button.pack(pady=10)
|
321 |
+
|
322 |
+
show_captions_button = tk.Button(root, text="Show Captions", command=open_caption_window)
|
323 |
+
show_captions_button.pack(pady=10)
|
324 |
+
|
325 |
+
num_files_label = tk.Label(root, textvariable=num_files_var)
|
326 |
+
num_files_label.pack(pady=5)
|
327 |
+
|
328 |
+
bit_frame = tk.Frame(root)
|
329 |
+
bit_frame.pack(pady=5)
|
330 |
+
|
331 |
+
bit_label = tk.Label(bit_frame, text="Select Bit Precision:")
|
332 |
+
bit_label.pack(side="left", padx=10)
|
333 |
+
|
334 |
+
tk.Radiobutton(bit_frame, text="4-bit", variable=bit_precision_var, value=4).pack(side="left", padx=5)
|
335 |
+
tk.Radiobutton(bit_frame, text="8-bit", variable=bit_precision_var, value=8).pack(side="left", padx=5)
|
336 |
+
tk.Radiobutton(bit_frame, text="16-bit", variable=bit_precision_var, value=16).pack(side="left", padx=5)
|
337 |
+
tk.Radiobutton(bit_frame, text="32-bit", variable=bit_precision_var, value=32).pack(side="left", padx=5)
|
338 |
+
|
339 |
+
prompt_label = tk.Label(root, text="Prompt (text to describe the image):")
|
340 |
+
prompt_label.pack(pady=5)
|
341 |
+
prompt_entry = tk.Text(root, height=3, wrap='word', width=60)
|
342 |
+
prompt_entry.pack(pady=5, padx=10, fill='both', expand=True)
|
343 |
+
prompt_entry.bind('<KeyRelease>', on_prompt_change)
|
344 |
+
|
345 |
+
prepend_text_label = tk.Label(root, text="Prepend Text:")
|
346 |
+
prepend_text_label.pack(pady=5)
|
347 |
+
prepend_text_entry = tk.Entry(root, textvariable=prepend_text_var, justify='center', width=60)
|
348 |
+
prepend_text_entry.pack(pady=5)
|
349 |
+
|
350 |
+
append_text_label = tk.Label(root, text="Append Text:")
|
351 |
+
append_text_label.pack(pady=5)
|
352 |
+
append_text_entry = tk.Entry(root, textvariable=append_text_var, justify='center', width=60)
|
353 |
+
append_text_entry.pack(pady=5)
|
354 |
+
|
355 |
+
# Thêm các radio button để xử lý caption khi ảnh đã có caption
|
356 |
+
caption_handling_label = tk.Label(root, text="If a caption already exists for an image:", font=('Helvetica', 12))
|
357 |
+
caption_handling_label.pack(pady=5)
|
358 |
+
|
359 |
+
# Frame chứa các radio button
|
360 |
+
options_frame = tk.Frame(root)
|
361 |
+
options_frame.pack(pady=5)
|
362 |
+
|
363 |
+
# Radio buttons
|
364 |
+
overwrite_radio = tk.Radiobutton(options_frame, text="Overwrite existing caption", variable=caption_handling_var, value='overwrite')
|
365 |
+
overwrite_radio.pack(side="left", padx=10)
|
366 |
+
|
367 |
+
append_radio = tk.Radiobutton(options_frame, text="Append to existing caption", variable=caption_handling_var, value='append')
|
368 |
+
append_radio.pack(side="left", padx=10)
|
369 |
+
|
370 |
+
skip_radio = tk.Radiobutton(options_frame, text="Skip images with existing caption", variable=caption_handling_var, value='skip')
|
371 |
+
skip_radio.pack(side="left", padx=10)
|
372 |
+
|
373 |
+
bit_precision_var.trace('w', on_bit_precision_change)
|
374 |
+
|
375 |
+
load_config_from_json()
|
376 |
+
|
377 |
+
app_initialized = True
|
378 |
+
|
379 |
+
prompt_var.trace('w', on_config_change)
|
380 |
+
max_new_tokens_var.trace('w', on_config_change)
|
381 |
+
temperature_var.trace('w', on_config_change)
|
382 |
+
top_k_var.trace('w', on_config_change)
|
383 |
+
top_p_var.trace('w', on_config_change)
|
384 |
+
precision_var.trace('w', on_config_change)
|
385 |
+
thread_count_var.trace('w', on_config_change)
|
386 |
+
batch_size_var.trace('w', on_config_change)
|
387 |
+
prepend_text_var.trace('w', on_config_change)
|
388 |
+
append_text_var.trace('w', on_config_change)
|
389 |
+
caption_handling_var.trace('w', on_config_change) # Trace for the caption handling radio buttons
|
390 |
+
|
391 |
+
max_new_tokens_label = tk.Label(root, text="Max New Tokens (max number of tokens to generate):")
|
392 |
+
max_new_tokens_label.pack(pady=5)
|
393 |
+
max_new_tokens_entry = tk.Entry(root, textvariable=max_new_tokens_var, justify='center', width=5, validate='key', validatecommand=(validate_cmd, '%P'))
|
394 |
+
max_new_tokens_entry.pack(pady=5)
|
395 |
+
|
396 |
+
do_sample_check = tk.Checkbutton(root, text="Do Sample (random sampling):", variable=do_sample_var, command=toggle_sampling_options)
|
397 |
+
do_sample_check.pack(pady=5)
|
398 |
+
|
399 |
+
temperature_label = tk.Label(root, text="Temperature (control randomness of sampling):")
|
400 |
+
top_k_label = tk.Label(root, text="Top-k (consider top k tokens):")
|
401 |
+
top_p_label = tk.Label(root, text="Top-p (consider tokens with cumulative probability p):")
|
402 |
+
|
403 |
+
temperature_entry = tk.Entry(root, textvariable=temperature_var, justify='center', width=5, validate='key', validatecommand=(validate_cmd, '%P'))
|
404 |
+
top_k_entry = tk.Entry(root, textvariable=top_k_var, justify='center', width=5, validate='key', validatecommand=(validate_cmd, '%P'))
|
405 |
+
top_p_entry = tk.Entry(root, textvariable=top_p_var, justify='center', width=5, validate='key', validatecommand=(validate_cmd, '%P'))
|
406 |
+
|
407 |
+
# Frame to hold all three horizontally aligned elements
|
408 |
+
horizontal_frame = tk.Frame(root)
|
409 |
+
horizontal_frame.pack(pady=5, padx=5)
|
410 |
+
|
411 |
+
thread_count_label = tk.Label(horizontal_frame, text="Thread Count (number of threads to use):")
|
412 |
+
thread_count_label.pack(side=tk.LEFT, padx=5)
|
413 |
+
thread_count_entry = tk.Entry(horizontal_frame, textvariable=thread_count_var, justify='center', width=5, validate='key', validatecommand=(validate_cmd, '%P'))
|
414 |
+
thread_count_entry.pack(side=tk.LEFT, padx=5)
|
415 |
+
|
416 |
+
batch_size_label = tk.Label(horizontal_frame, text="Batch Size (number of images to process at once):")
|
417 |
+
batch_size_label.pack(side=tk.LEFT, padx=5)
|
418 |
+
batch_size_entry = tk.Entry(horizontal_frame, textvariable=batch_size_var, justify='center', width=5, validate='key', validatecommand=(validate_cmd, '%P'))
|
419 |
+
batch_size_entry.pack(side=tk.LEFT, padx=5)
|
420 |
+
|
421 |
+
errors_button = tk.Button(root, textvariable=errors_var, command=show_errors)
|
422 |
+
errors_button.pack(pady=10)
|
423 |
+
|
424 |
+
start_button = tk.Button(root, text="Generate Captions", command=lambda: [process_files(), update_and_save_config()])
|
425 |
+
start_button.pack(pady=10)
|
426 |
+
|
427 |
+
stop_button = tk.Button(root, text="Stop", command=stop_processing_func)
|
428 |
+
stop_button.pack(pady=10)
|
429 |
+
|
430 |
+
progress_bar = ttk.Progressbar(root, variable=progress, maximum=100)
|
431 |
+
progress_bar.pack(pady=10, fill=tk.X)
|
432 |
+
|
433 |
+
status_label = tk.Label(root, textvariable=status_var, fg="green")
|
434 |
+
status_label.pack(pady=5)
|
435 |
+
|
436 |
+
center_window(root)
|
437 |
+
root.protocol("WM_DELETE_WINDOW", on_closing)
|
438 |
+
root.mainloop()
|
439 |
+
|
440 |
+
def select_files():
|
441 |
+
global selected_files, save_directory, total_pages, original_selected_files
|
442 |
+
filetypes = [("All Image files", "*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.tiff;*.tif;*.svg;*.webp")]
|
443 |
+
filepaths = filedialog.askopenfilenames(title="Select Image Files", filetypes=filetypes)
|
444 |
+
if filepaths:
|
445 |
+
selected_files.clear()
|
446 |
+
selected_files.extend(filepaths)
|
447 |
+
original_selected_files = selected_files.copy()
|
448 |
+
validate_selected_files()
|
449 |
+
|
450 |
+
num_files_var.set(f"{len(selected_files)} files selected.")
|
451 |
+
save_directory = os.path.dirname(selected_files[0])
|
452 |
+
total_pages = (len(selected_files) + images_per_page - 1) // images_per_page
|
453 |
+
if caption_window is not None:
|
454 |
+
update_image_preview(content_canvas)
|
455 |
+
|
456 |
+
def validate_selected_files():
|
457 |
+
global selected_files, num_files_var
|
458 |
+
selected_files = [file for file in selected_files if os.path.exists(file)]
|
459 |
+
num_files_var.set(f"{len(selected_files)} files selected.")
|
460 |
+
|
461 |
+
def toggle_buttons(state):
|
462 |
+
state = tk.NORMAL if state else tk.DISABLED
|
463 |
+
select_files_button.config(state=state)
|
464 |
+
show_captions_button.config(state=state)
|
465 |
+
prompt_entry.config(state=state)
|
466 |
+
prepend_text_entry.config(state=state)
|
467 |
+
append_text_entry.config(state=state)
|
468 |
+
do_sample_check.config(state=state)
|
469 |
+
temperature_entry.config(state=state)
|
470 |
+
top_k_entry.config(state=state)
|
471 |
+
top_p_entry.config(state=state)
|
472 |
+
thread_count_entry.config(state=state)
|
473 |
+
batch_size_entry.config(state=state)
|
474 |
+
start_button.config(state=state)
|
475 |
+
stop_button.config(state=tk.NORMAL)
|
476 |
+
|
477 |
+
def generate_caption(image_path, save_directory, q):
|
478 |
+
if stop_processing:
|
479 |
+
return
|
480 |
+
|
481 |
+
try:
|
482 |
+
load_model()
|
483 |
+
|
484 |
+
filename = os.path.basename(image_path)
|
485 |
+
caption_file_path = os.path.join(save_directory, f"{filename}_caption.txt")
|
486 |
+
|
487 |
+
# Kiểm tra các lựa chọn của người dùng
|
488 |
+
if os.path.exists(caption_file_path):
|
489 |
+
if caption_handling_var.get() == 'skip':
|
490 |
+
q.put(image_path)
|
491 |
+
return
|
492 |
+
elif caption_handling_var.get() == 'append':
|
493 |
+
with open(caption_file_path, 'r', encoding='utf-8') as f:
|
494 |
+
existing_caption = f.read()
|
495 |
+
else:
|
496 |
+
existing_caption = ""
|
497 |
+
else:
|
498 |
+
existing_caption = ""
|
499 |
+
|
500 |
+
image = PILImage.open(image_path).convert('RGB')
|
501 |
+
if not isinstance(image, PILImage.Image):
|
502 |
+
raise ValueError(f"Expected image to be of type PIL.Image.Image, but got {type(image)}")
|
503 |
+
|
504 |
+
inputs = model.build_conversation_input_ids(
|
505 |
+
tokenizer,
|
506 |
+
query=prompt_var.get(),
|
507 |
+
history=[],
|
508 |
+
images=[image]
|
509 |
+
)
|
510 |
+
|
511 |
+
# Điều chỉnh dtype dựa trên bit_precision
|
512 |
+
if bit_precision_var.get() == 32:
|
513 |
+
image_tensor = inputs['images'][0].to('cuda').to(torch.float32)
|
514 |
+
else:
|
515 |
+
image_tensor = inputs['images'][0].to('cuda').to(torch.float16)
|
516 |
+
|
517 |
+
inputs = {
|
518 |
+
'input_ids': inputs['input_ids'].unsqueeze(0).to('cuda'),
|
519 |
+
'token_type_ids': inputs['token_type_ids'].unsqueeze(0).to('cuda'),
|
520 |
+
'attention_mask': inputs['attention_mask'].unsqueeze(0).to('cuda'),
|
521 |
+
'images': [[image_tensor]],
|
522 |
+
}
|
523 |
+
|
524 |
+
gen_kwargs = {
|
525 |
+
"max_new_tokens": max_new_tokens_var.get(),
|
526 |
+
"do_sample": do_sample_var.get(),
|
527 |
+
"temperature": temperature_var.get(),
|
528 |
+
"top_k": top_k_var.get(),
|
529 |
+
"top_p": top_p_var.get() if do_sample_var.get() else None,
|
530 |
+
"num_beams": precision_var.get()
|
531 |
+
}
|
532 |
+
|
533 |
+
with torch.no_grad():
|
534 |
+
outputs = model.generate(**inputs, **gen_kwargs)
|
535 |
+
outputs = outputs[:, inputs['input_ids'].shape[1]:]
|
536 |
+
new_caption = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
537 |
+
|
538 |
+
final_caption = f"{prepend_text_var.get()} {existing_caption} {new_caption} {append_text_var.get()}".strip()
|
539 |
+
|
540 |
+
with open(caption_file_path, 'w', encoding='utf-8') as file:
|
541 |
+
file.write(final_caption)
|
542 |
+
|
543 |
+
q.put(image_path)
|
544 |
+
torch.cuda.empty_cache()
|
545 |
+
except torch.cuda.OutOfMemoryError as e:
|
546 |
+
torch.cuda.empty_cache()
|
547 |
+
error_message = f"CUDA OutOfMemoryError: {traceback.format_exc()}"
|
548 |
+
print(error_message)
|
549 |
+
q.put(error_message)
|
550 |
+
error_messages.append(error_message)
|
551 |
+
except Exception as e:
|
552 |
+
error_message = f"Error processing image {image_path}: {traceback.format_exc()}"
|
553 |
+
print(error_message)
|
554 |
+
q.put(error_message)
|
555 |
+
error_messages.append(error_message)
|
556 |
+
|
557 |
+
|
558 |
+
def worker(save_directory, num_threads, batch_size):
|
559 |
+
try:
|
560 |
+
progress.set(0)
|
561 |
+
threads = []
|
562 |
+
|
563 |
+
num_batches = math.ceil(len(selected_files) / batch_size)
|
564 |
+
batch_size_per_thread = max(1, batch_size // num_threads) # Số ảnh mỗi luồng xử lý trong một batch
|
565 |
+
|
566 |
+
for batch_index in range(num_batches):
|
567 |
+
if stop_processing:
|
568 |
+
break
|
569 |
+
|
570 |
+
start_index = batch_index * batch_size
|
571 |
+
end_index = min(start_index + batch_size, len(selected_files))
|
572 |
+
batch = selected_files[start_index:end_index]
|
573 |
+
|
574 |
+
# Chia ảnh trong batch cho các luồng
|
575 |
+
for i in range(0, len(batch), batch_size_per_thread):
|
576 |
+
thread_batch = batch[i:i + batch_size_per_thread]
|
577 |
+
thread = threading.Thread(target=generate_captions_for_batch, args=(thread_batch, save_directory, q))
|
578 |
+
threads.append(thread)
|
579 |
+
thread.start()
|
580 |
+
|
581 |
+
# Đợi các luồng trong batch hiện tại hoàn thành
|
582 |
+
for thread in threads:
|
583 |
+
thread.join()
|
584 |
+
threads.clear()
|
585 |
+
|
586 |
+
q.put(None)
|
587 |
+
except Exception as e:
|
588 |
+
if not stop_processing:
|
589 |
+
q.put(e)
|
590 |
+
|
591 |
+
def generate_captions_for_batch(batch, save_directory, q):
|
592 |
+
for image_path in batch:
|
593 |
+
generate_caption(image_path, save_directory, q)
|
594 |
+
|
595 |
+
def update_progress():
|
596 |
+
try:
|
597 |
+
completed = 0
|
598 |
+
while True:
|
599 |
+
item = q.get()
|
600 |
+
if item is None:
|
601 |
+
break
|
602 |
+
if isinstance(item, str):
|
603 |
+
if "Error" in item:
|
604 |
+
root.after(0, errors_var.set, f"Errors: {len(error_messages)}")
|
605 |
+
continue
|
606 |
+
completed += 1
|
607 |
+
progress.set(int((completed / len(selected_files)) * 100))
|
608 |
+
if not stop_processing:
|
609 |
+
root.after(0, status_var.set, f"Processed {completed} files")
|
610 |
+
root.after(0, root.update_idletasks)
|
611 |
+
if not stop_processing:
|
612 |
+
root.after(0, progress.set(100))
|
613 |
+
show_completion_message(completed)
|
614 |
+
except Exception as e:
|
615 |
+
if not stop_processing:
|
616 |
+
root.after(0, status_var.set(f"Error: {e}"))
|
617 |
+
finally:
|
618 |
+
toggle_buttons(True)
|
619 |
+
|
620 |
+
def show_completion_message(completed):
|
621 |
+
message = f"Processing complete. {completed} files processed."
|
622 |
+
if error_messages:
|
623 |
+
message += f" {len(error_messages)} errors occurred."
|
624 |
+
messagebox.showinfo("Process Complete", message)
|
625 |
+
|
626 |
+
def process_files():
|
627 |
+
global stop_processing, error_messages
|
628 |
+
stop_processing = False
|
629 |
+
error_messages.clear()
|
630 |
+
errors_var.set("Errors: 0")
|
631 |
+
|
632 |
+
validate_selected_files()
|
633 |
+
|
634 |
+
if not selected_files or not save_directory:
|
635 |
+
status_var.set("Please select images.")
|
636 |
+
return
|
637 |
+
|
638 |
+
toggle_buttons(False)
|
639 |
+
|
640 |
+
threading.Thread(target=worker, args=(save_directory, thread_count_var.get(), batch_size_var.get())).start()
|
641 |
+
threading.Thread(target=update_progress).start()
|
642 |
+
|
643 |
+
def stop_processing_func():
|
644 |
+
global stop_processing
|
645 |
+
stop_processing = True
|
646 |
+
torch.cuda.empty_cache()
|
647 |
+
status_var.set("Processing stopped.")
|
648 |
+
|
649 |
+
def open_caption_window():
|
650 |
+
global caption_window, caption_frame, caption_text_widgets, current_page, total_pages, content_canvas
|
651 |
+
if caption_window is not None:
|
652 |
+
return
|
653 |
+
|
654 |
+
validate_selected_files()
|
655 |
+
|
656 |
+
caption_window = tk.Toplevel(root)
|
657 |
+
caption_window.title("Image Thumbnails and Captions")
|
658 |
+
caption_window.geometry("940x900")
|
659 |
+
|
660 |
+
main_frame = tk.Frame(caption_window)
|
661 |
+
main_frame.pack(fill=tk.BOTH, expand=True)
|
662 |
+
|
663 |
+
search_frame = tk.Frame(main_frame)
|
664 |
+
search_frame.pack(side=tk.TOP, fill=tk.X)
|
665 |
+
|
666 |
+
search_entry = tk.Entry(search_frame, textvariable=search_var)
|
667 |
+
search_entry.pack(side=tk.LEFT, padx=10, pady=5, fill=tk.X, expand=True)
|
668 |
+
|
669 |
+
search_button = tk.Button(search_frame, text="Search", command=search_captions)
|
670 |
+
search_button.pack(side=tk.LEFT, padx=10)
|
671 |
+
|
672 |
+
reset_button = tk.Button(search_frame, text="Reset Order", command=reset_order)
|
673 |
+
reset_button.pack(side=tk.LEFT, padx=10)
|
674 |
+
|
675 |
+
action_frame = tk.Frame(main_frame)
|
676 |
+
action_frame.pack(side=tk.TOP, fill=tk.X)
|
677 |
+
|
678 |
+
action_entry = tk.Entry(action_frame, textvariable=action_var)
|
679 |
+
action_entry.pack(side=tk.LEFT, padx=10, pady=5, fill=tk.X, expand=True)
|
680 |
+
|
681 |
+
prepend_button = tk.Button(action_frame, text="Add to Beginning", command=lambda: add_to_captions("prepend"))
|
682 |
+
prepend_button.pack(side=tk.LEFT, padx=5)
|
683 |
+
|
684 |
+
append_button = tk.Button(action_frame, text="Add to End", command=lambda: add_to_captions("append"))
|
685 |
+
append_button.pack(side=tk.LEFT, padx=5)
|
686 |
+
|
687 |
+
insert_middle_button = tk.Button(action_frame, text="Add to Middle", command=lambda: add_to_captions("insert_middle"))
|
688 |
+
insert_middle_button.pack(side=tk.LEFT, padx=5)
|
689 |
+
|
690 |
+
delete_keyword_button = tk.Button(action_frame, text="Delete Keyword", command=delete_keyword_from_captions)
|
691 |
+
delete_keyword_button.pack(side=tk.LEFT, padx=5)
|
692 |
+
|
693 |
+
delete_images_button = tk.Button(action_frame, text="Delete Images with Keyword", command=delete_images_with_keyword)
|
694 |
+
delete_images_button.pack(side=tk.LEFT, padx=5)
|
695 |
+
|
696 |
+
content_canvas = tk.Canvas(main_frame)
|
697 |
+
content_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
698 |
+
|
699 |
+
caption_frame = tk.Frame(content_canvas)
|
700 |
+
content_canvas.create_window((0, 0), window=caption_frame, anchor='nw')
|
701 |
+
|
702 |
+
caption_scrollbar = tk.Scrollbar(main_frame, orient="vertical", command=content_canvas.yview)
|
703 |
+
caption_scrollbar.pack(side=tk.LEFT, fill=tk.Y)
|
704 |
+
content_canvas.configure(yscrollcommand=caption_scrollbar.set)
|
705 |
+
|
706 |
+
caption_frame.bind("<Configure>", lambda e: content_canvas.configure(scrollregion=content_canvas.bbox("all")))
|
707 |
+
content_canvas.bind_all("<MouseWheel>", lambda event: content_canvas.yview_scroll(int(-1*(event.delta/120)), "units"))
|
708 |
+
|
709 |
+
# Định nghĩa hàm on_mouse_wheel
|
710 |
+
def on_mouse_wheel(event):
|
711 |
+
try:
|
712 |
+
if content_canvas.winfo_exists():
|
713 |
+
content_canvas.yview_scroll(int(-1*(event.delta/120)), "units")
|
714 |
+
except tk.TclError:
|
715 |
+
pass
|
716 |
+
|
717 |
+
content_canvas.bind_all("<MouseWheel>", on_mouse_wheel)
|
718 |
+
|
719 |
+
def on_caption_window_close():
|
720 |
+
global caption_window
|
721 |
+
caption_window.destroy()
|
722 |
+
caption_window = None
|
723 |
+
|
724 |
+
caption_window.protocol("WM_DELETE_WINDOW", on_caption_window_close)
|
725 |
+
|
726 |
+
update_image_preview(content_canvas)
|
727 |
+
|
728 |
+
def update_image_preview(content_canvas):
|
729 |
+
global thumbnails, caption_text_widgets, current_page, images_per_page, total_pages
|
730 |
+
if caption_frame is None:
|
731 |
+
return
|
732 |
+
|
733 |
+
for widget in caption_frame.winfo_children():
|
734 |
+
if isinstance(widget, tk.Label) or isinstance(widget, tk.Text) or isinstance(widget, tk.Frame):
|
735 |
+
widget.destroy()
|
736 |
+
|
737 |
+
thumbnails.clear()
|
738 |
+
caption_text_widgets.clear()
|
739 |
+
|
740 |
+
if not selected_files:
|
741 |
+
return
|
742 |
+
|
743 |
+
start_index = current_page * images_per_page
|
744 |
+
end_index = start_index + images_per_page
|
745 |
+
files_to_display = selected_files[start_index:end_index]
|
746 |
+
|
747 |
+
for i, file_path in enumerate(files_to_display):
|
748 |
+
thumbnail_size = (200, 200)
|
749 |
+
try:
|
750 |
+
image = PILImage.open(file_path)
|
751 |
+
image.thumbnail(thumbnail_size)
|
752 |
+
thumbnail = ImageTk.PhotoImage(image)
|
753 |
+
thumbnails.append(thumbnail)
|
754 |
+
|
755 |
+
img_label = tk.Label(caption_frame, image=thumbnail)
|
756 |
+
img_label.grid(row=i*2, column=0, padx=5, pady=5, sticky="nsew")
|
757 |
+
|
758 |
+
file_label = tk.Label(caption_frame, text=os.path.basename(file_path), font=('Helvetica', 12), wraplength=300, justify="left")
|
759 |
+
file_label.grid(row=i*2, column=1, padx=5, pady=5, sticky="nsew")
|
760 |
+
|
761 |
+
caption_file = os.path.join(save_directory, f"{os.path.basename(file_path)}_caption.txt")
|
762 |
+
if os.path.exists(caption_file):
|
763 |
+
with open(caption_file, 'r', encoding='utf-8') as file:
|
764 |
+
caption_text = file.read()
|
765 |
+
else:
|
766 |
+
caption_text = ""
|
767 |
+
|
768 |
+
caption_var = tk.StringVar(value=caption_text)
|
769 |
+
|
770 |
+
caption_text_widget = tk.Text(caption_frame, width=50, height=3, wrap=tk.WORD, font=('Helvetica', 12))
|
771 |
+
caption_text_widget.insert(tk.END, caption_text)
|
772 |
+
caption_text_widget.grid(row=i*2, column=2, padx=5, pady=5, sticky="nsew")
|
773 |
+
|
774 |
+
caption_var.trace_add("write", lambda *args, fp=file_path, cv=caption_var: save_caption(fp, cv.get()))
|
775 |
+
|
776 |
+
caption_text_widget.bind("<KeyRelease>", lambda e, cv=caption_var, w=caption_text_widget: cv.set(w.get("1.0", "end-1c")))
|
777 |
+
caption_text_widgets.append(caption_text_widget)
|
778 |
+
|
779 |
+
except Exception as e:
|
780 |
+
tk.Label(caption_frame, text="Error loading image").grid(row=i*2, column=0, columnspan=4, padx=5, pady=5)
|
781 |
+
|
782 |
+
nav_frame = tk.Frame(caption_frame)
|
783 |
+
nav_frame.grid(row=images_per_page*2, column=0, columnspan=3, pady=10)
|
784 |
+
|
785 |
+
if current_page > 0:
|
786 |
+
prev_button = tk.Button(nav_frame, text="Previous", command=lambda: navigate(-1, content_canvas))
|
787 |
+
prev_button.pack(side=tk.LEFT)
|
788 |
+
|
789 |
+
page_label = tk.Label(nav_frame, text=f"Page {current_page + 1} of {total_pages}")
|
790 |
+
page_label.pack(side=tk.LEFT, padx=5)
|
791 |
+
|
792 |
+
page_entry = tk.Entry(nav_frame, width=5)
|
793 |
+
page_entry.pack(side=tk.LEFT)
|
794 |
+
|
795 |
+
go_button = tk.Button(nav_frame, text="Go", command=lambda: go_to_page(page_entry.get(), content_canvas))
|
796 |
+
go_button.pack(side=tk.LEFT, padx=5)
|
797 |
+
|
798 |
+
if current_page < total_pages - 1:
|
799 |
+
next_button = tk.Button(nav_frame, text="Next", command=lambda: navigate(1, content_canvas))
|
800 |
+
next_button.pack(side=tk.RIGHT)
|
801 |
+
|
802 |
+
def navigate(direction, content_canvas):
|
803 |
+
global current_page
|
804 |
+
current_page += direction
|
805 |
+
update_image_preview(content_canvas)
|
806 |
+
|
807 |
+
def go_to_page(page_number, content_canvas):
|
808 |
+
global current_page, total_pages
|
809 |
+
try:
|
810 |
+
page_number = int(page_number)
|
811 |
+
if 1 <= page_number <= total_pages:
|
812 |
+
current_page = page_number - 1
|
813 |
+
update_image_preview(content_canvas)
|
814 |
+
else:
|
815 |
+
messagebox.showerror("Invalid Page", f"Please enter a valid page number between 1 and {total_pages}.")
|
816 |
+
except ValueError:
|
817 |
+
messagebox.showerror("Invalid Input", "Please enter a valid integer for the page number.")
|
818 |
+
|
819 |
+
def save_caption(file_path, caption_text):
|
820 |
+
output_path = os.path.join(save_directory, f"{os.path.basename(file_path)}_caption.txt")
|
821 |
+
try:
|
822 |
+
with open(output_path, 'w', encoding='utf-8') as file:
|
823 |
+
file.write(caption_text.strip())
|
824 |
+
except Exception as e:
|
825 |
+
print(f"Error saving captions: {e}")
|
826 |
+
|
827 |
+
def search_captions():
|
828 |
+
global selected_files
|
829 |
+
search_term = search_var.get().lower().strip()
|
830 |
+
if not search_term:
|
831 |
+
return
|
832 |
+
|
833 |
+
try:
|
834 |
+
selected_files.sort(key=lambda x: search_score(x, search_term), reverse=True)
|
835 |
+
except Exception as e:
|
836 |
+
error_message = f"Error during sorting: {e}"
|
837 |
+
print(error_message)
|
838 |
+
error_messages.append(error_message)
|
839 |
+
|
840 |
+
update_image_preview(content_canvas)
|
841 |
+
|
842 |
+
def search_score(file_path, search_term):
|
843 |
+
caption_file = os.path.join(save_directory, f"{os.path.basename(file_path)}_caption.txt")
|
844 |
+
try:
|
845 |
+
if os.path.exists(caption_file):
|
846 |
+
with open(caption_file, 'r', encoding='utf-8') as file:
|
847 |
+
caption_text = file.read().lower()
|
848 |
+
if search_term in caption_text:
|
849 |
+
return caption_text.count(search_term)
|
850 |
+
|
851 |
+
except Exception as e:
|
852 |
+
error_message = f"Error reading file {caption_file}: {e}"
|
853 |
+
print(error_message)
|
854 |
+
error_messages.append(error_message)
|
855 |
+
return 0
|
856 |
+
|
857 |
+
def reset_order():
|
858 |
+
global selected_files
|
859 |
+
selected_files = original_selected_files.copy()
|
860 |
+
update_image_preview(content_canvas)
|
861 |
+
|
862 |
+
def add_to_captions(position):
|
863 |
+
global selected_files
|
864 |
+
keyword = action_var.get()
|
865 |
+
if not keyword:
|
866 |
+
return
|
867 |
+
|
868 |
+
for file_path in selected_files:
|
869 |
+
caption_file = os.path.join(save_directory, f"{os.path.basename(file_path)}_caption.txt")
|
870 |
+
if os.path.exists(caption_file):
|
871 |
+
with open(caption_file, 'r+', encoding='utf-8') as file:
|
872 |
+
caption_text = file.read()
|
873 |
+
if position == "prepend":
|
874 |
+
caption_text = f"{keyword} {caption_text}"
|
875 |
+
elif position == "append":
|
876 |
+
caption_text = f"{caption_text} {keyword}"
|
877 |
+
elif position == "insert_middle":
|
878 |
+
middle_index = len(caption_text) // 2
|
879 |
+
caption_text = f"{caption_text[:middle_index]} {keyword} {caption_text[middle_index:]}"
|
880 |
+
file.seek(0)
|
881 |
+
file.write(caption_text)
|
882 |
+
file.truncate()
|
883 |
+
|
884 |
+
update_image_preview(content_canvas)
|
885 |
+
|
886 |
+
def delete_keyword_from_captions():
|
887 |
+
keyword = action_var.get().lower().strip()
|
888 |
+
if not keyword:
|
889 |
+
return
|
890 |
+
|
891 |
+
for file_path in selected_files:
|
892 |
+
caption_file = os.path.join(save_directory, f"{os.path.basename(file_path)}_caption.txt")
|
893 |
+
if os.path.exists(caption_file):
|
894 |
+
with open(caption_file, 'r+', encoding='utf-8') as file:
|
895 |
+
caption_text = file.read().lower().replace(keyword, "")
|
896 |
+
|
897 |
+
updated_caption = caption_text.replace(keyword, "").strip()
|
898 |
+
|
899 |
+
file.seek(0)
|
900 |
+
file.write(updated_caption)
|
901 |
+
file.truncate()
|
902 |
+
|
903 |
+
update_image_preview(content_canvas)
|
904 |
+
|
905 |
+
def delete_images_with_keyword():
|
906 |
+
global selected_files
|
907 |
+
keyword = action_var.get().lower()
|
908 |
+
if not keyword:
|
909 |
+
return
|
910 |
+
|
911 |
+
files_to_delete = []
|
912 |
+
for file_path in selected_files:
|
913 |
+
caption_file = os.path.join(save_directory, f"{os.path.basename(file_path)}_caption.txt")
|
914 |
+
if os.path.exists(caption_file):
|
915 |
+
with open(caption_file, 'r', encoding='utf-8') as file:
|
916 |
+
caption_text = file.read().lower()
|
917 |
+
if keyword in caption_text:
|
918 |
+
files_to_delete.append(file_path)
|
919 |
+
|
920 |
+
for file_path in files_to_delete:
|
921 |
+
try:
|
922 |
+
os.remove(file_path)
|
923 |
+
caption_file = os.path.join(save_directory, f"{os.path.basename(file_path)}_caption.txt")
|
924 |
+
if os.path.exists(caption_file):
|
925 |
+
os.remove(caption_file)
|
926 |
+
except Exception as e:
|
927 |
+
error_message = f"Error deleting file {file_path} or its caption: {e}"
|
928 |
+
print(error_message)
|
929 |
+
error_messages.append(error_message)
|
930 |
+
|
931 |
+
selected_files = [file_path for file_path in selected_files if file_path not in files_to_delete]
|
932 |
+
|
933 |
+
validate_selected_files()
|
934 |
+
|
935 |
+
update_image_preview(content_canvas)
|
936 |
+
|
937 |
+
def return_to_menu():
|
938 |
+
stop_processing_func()
|
939 |
+
root.destroy()
|
940 |
+
import main
|
941 |
+
main.open_main_menu()
|
942 |
+
|
943 |
+
def on_closing():
|
944 |
+
return_to_menu()
|
945 |
+
|
946 |
+
if __name__ == "__main__":
|
947 |
+
open_image_to_caption()
|