-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainApp.py
More file actions
2221 lines (1867 loc) · 84.5 KB
/
MainApp.py
File metadata and controls
2221 lines (1867 loc) · 84.5 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
import argparse
import base64
import hashlib
import json
import os
import re
import shutil
import sys
import uuid
from pathlib import Path
from typing import Callable
from PySide6.QtCore import QByteArray, QObject, Qt, QThread, Signal
from PySide6.QtGui import QColor, QFont, QFontDatabase, QFontMetrics, QIcon, QPalette
from PySide6.QtWidgets import (
QApplication,
QCheckBox,
QComboBox,
QDialog,
QFileDialog,
QFrame,
QHBoxLayout,
QInputDialog,
QLabel,
QLineEdit,
QMainWindow,
QMessageBox,
QPushButton,
QScrollArea,
QSizePolicy,
QSplitter,
QStackedWidget,
QTextEdit,
QVBoxLayout,
QWidget,
)
from embedded_fonts import EMBEDDED_FONTS
from embedded_locales import EMBEDDED_LOCALES as FILE_EMBEDDED_LOCALES
APP_FALLBACK_TITLE = "ImageMerge"
APP_DIR = Path(__file__).resolve().parent
APP_METADATA_PATH = APP_DIR / "app_metadata.json"
def load_app_metadata() -> dict[str, str]:
defaults = {
"app_name": APP_FALLBACK_TITLE,
"company_name": "TamKungZ_",
"file_description": "Open-source image and video merge tool",
"file_version": "",
"product_version": "",
"copyright": "",
}
if APP_METADATA_PATH.exists():
try:
parsed = json.loads(APP_METADATA_PATH.read_text(encoding="utf-8"))
if isinstance(parsed, dict):
for key, value in parsed.items():
defaults[str(key)] = str(value)
except Exception:
pass
return defaults
APP_METADATA = load_app_metadata()
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif", ".tiff"}
VIDEO_EXTS = {".mp4", ".mov", ".mkv", ".avi", ".webm", ".m4v", ".wmv", ".flv", ".ts", ".mts"}
MEDIA_EXTS = IMAGE_EXTS | VIDEO_EXTS
MODE_MOVE = "move"
MODE_COPY_DELETE = "copy_delete"
MODE_COPY_KEEP = "copy_keep"
MODE_MAIN_FOLDER = "main_folder"
MODE_INSIDE_FOLDER = "inside_folder"
WORKFLOW_MERGE = "merge"
WORKFLOW_MAIN_FOLDER = "main_folder"
WORKFLOW_INSIDE_FOLDER = "inside_folder"
DEFAULT_LANG = "en"
LOCALES_DIR = APP_DIR / "locales"
def discover_supported_langs() -> set[str]:
langs = set(FILE_EMBEDDED_LOCALES.keys())
if LOCALES_DIR.exists():
for locale_file in LOCALES_DIR.glob("*.json"):
if locale_file.stem:
langs.add(locale_file.stem.lower())
if DEFAULT_LANG not in langs:
langs.add(DEFAULT_LANG)
return langs
SUPPORTED_LANGS = discover_supported_langs()
UUID_LIKE_RE = re.compile(
r"^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})(?: \(\d+\))?$"
)
HEX_HASH_RE = re.compile(r"^[0-9a-fA-F]{24,}(?: \(\d+\))?$")
IMG_NUMBER_RE = re.compile(r"^(IMG)[ _-]?(\d+)(?:\s*\(\d+\))?$", re.IGNORECASE)
PREFIX_ALLOWED_RE = re.compile(r"[^a-zA-Z0-9_-]+")
C_BG = "#efefef"
C_SURFACE = "#ffffff"
C_SURFACE2 = "#f4f4f4"
C_SURFACE3 = "#e4e4e4"
C_BORDER = "rgba(20,20,20,0.12)"
C_BORDER2 = "rgba(20,20,20,0.22)"
C_ACCENT = "#111111"
C_ACCENT_DIM= "rgba(17,17,17,0.12)"
C_TEXT = "#111111"
C_TEXT2 = "#222222"
C_TEXT3 = "#444444"
C_SUCCESS = "#1b1b1b"
C_WARNING = "#4f4f4f"
C_DANGER = "#2b2b2b"
LANGUAGE_NATIVE_NAMES = {
"ar": "العربية",
"de": "Deutsch",
"en": "English",
"es": "Español",
"fr": "Français",
"id": "Bahasa Indonesia",
"ja": "日本語",
"ko": "한국어",
"ru": "Русский",
"th": "ไทย",
"vi": "Tiếng Việt",
"zh": "中文",
}
def setup_app_fonts(lang: str = DEFAULT_LANG) -> str:
lang = (lang or DEFAULT_LANG).lower()
db = QFontDatabase()
loaded_family = None
for encoded_data in EMBEDDED_FONTS.values():
try:
font_bytes = base64.b64decode(encoded_data)
font_id = QFontDatabase.addApplicationFontFromData(QByteArray(font_bytes))
if font_id == -1:
continue
families = QFontDatabase.applicationFontFamilies(font_id)
if families and loaded_family is None:
loaded_family = families[0]
except Exception:
continue
script_font_candidates: dict[str, tuple[str, ...]] = {
"th": ("Leelawadee UI", "Tahoma", "Noto Sans Thai", "Noto Sans"),
"ja": ("Yu Gothic UI", "Meiryo", "Noto Sans CJK JP", "MS UI Gothic", "Noto Sans"),
"ko": ("Malgun Gothic", "Noto Sans CJK KR", "Apple SD Gothic Neo", "Noto Sans"),
"zh": ("Microsoft YaHei UI", "PingFang SC", "Noto Sans CJK SC", "SimHei", "Noto Sans"),
"ar": ("Segoe UI", "Tahoma", "Noto Naskh Arabic", "Noto Sans Arabic", "Noto Sans", "Arial"),
"ru": ("Segoe UI", "Arial", "Noto Sans", "DejaVu Sans"),
"vi": ("Segoe UI", "Arial", "Noto Sans", "DejaVu Sans"),
}
if loaded_family and lang == "th":
return loaded_family
for font in script_font_candidates.get(lang, ()):
if db.hasFamily(font):
return font
if loaded_family:
return loaded_family
if os.name == "nt":
for font in ("Segoe UI", "Arial"):
if db.hasFamily(font):
return font
elif sys.platform == "darwin":
for font in ("SF Pro Text", "Helvetica Neue", "Helvetica", "Arial"):
if db.hasFamily(font):
return font
else:
for font in ("Noto Sans", "DejaVu Sans", "Liberation Sans", "FreeSans"):
if db.hasFamily(font):
return font
return "Sans Serif"
def normalize_prefix(prefix: str) -> str:
prefix = prefix.strip()
if not prefix:
return ""
prefix = prefix.replace(" ", "-")
prefix = PREFIX_ALLOWED_RE.sub("-", prefix)
prefix = re.sub(r"-+", "-", prefix).strip("-_")
return prefix.lower()
def build_output_name(index: int, ext: str, prefix: str = "") -> str:
prefix = normalize_prefix(prefix)
if prefix:
return f"{prefix}-{index:04d}{ext.lower()}"
return f"{index:04d}{ext.lower()}"
def split_existing_prefix_and_number(path: Path) -> tuple[str, int]:
stem = path.stem
match = re.match(r"^(?:(.+?)-)?(\d+)$", stem)
if match:
prefix = normalize_prefix(match.group(1) or "")
return prefix, int(match.group(2))
match_number = re.match(r"^(\d+)", stem)
if match_number:
return "", int(match_number.group(1))
return "", 99999999
def dedupe_key(file_hash: str, ext: str) -> tuple[str, str]:
return file_hash, ext.lower()
def detect_language() -> str:
env_lang = os.environ.get("IMAGEMERGE_LANG", "").strip().lower()
if env_lang in SUPPORTED_LANGS:
return env_lang
if "-" in env_lang or "_" in env_lang:
base = re.split(r"[-_]", env_lang)[0]
if base in SUPPORTED_LANGS:
return base
return DEFAULT_LANG
class I18n:
def __init__(self, lang: str):
self.catalogs: dict[str, dict[str, str]] = {}
for code in sorted(SUPPORTED_LANGS):
self._load_catalog(code)
if not self.catalogs.get(DEFAULT_LANG):
self.catalogs[DEFAULT_LANG] = {}
self.lang = lang if lang in self.catalogs else DEFAULT_LANG
def _load_catalog(self, lang: str):
catalog: dict[str, str] = {}
locale_file = LOCALES_DIR / f"{lang}.json"
if locale_file.exists():
try:
parsed = json.loads(locale_file.read_text(encoding="utf-8"))
if isinstance(parsed, dict):
catalog = {str(key): str(value) for key, value in parsed.items()}
except Exception:
catalog = {}
if not catalog:
embedded = FILE_EMBEDDED_LOCALES.get(lang, {})
catalog = {str(key): str(value) for key, value in embedded.items()}
self.catalogs[lang] = catalog
def t(self, key: str, **kwargs) -> str:
text = self.catalogs.get(self.lang, {}).get(key)
if text is None:
text = self.catalogs.get(DEFAULT_LANG, {}).get(key, key)
try:
return text.format(**kwargs)
except Exception:
return text
def t_identity(key: str, **kwargs) -> str:
if not kwargs:
return key
try:
return key.format(**kwargs)
except Exception:
return key
class Logger:
def __init__(self, writer: Callable[[str], None]):
self.writer = writer
def write(self, text: str):
self.writer(text)
def sha256_file(path: Path) -> str:
hash_obj = hashlib.sha256()
with open(path, "rb") as file:
for chunk in iter(lambda: file.read(8192), b""):
hash_obj.update(chunk)
return hash_obj.hexdigest()
def classify_source_name(path: Path) -> tuple[str, int | None]:
stem = path.stem.strip()
img_match = IMG_NUMBER_RE.match(stem)
if img_match:
return "img_number", int(img_match.group(2))
if UUID_LIKE_RE.match(stem) or HEX_HASH_RE.match(stem):
return "time_only", None
return "default", None
def source_sort_key(item):
file_path, ctime, _prefix = item
stem_lower = file_path.stem.lower()
ext_lower = file_path.suffix.lower()
group_type, value = classify_source_name(file_path)
if group_type == "img_number":
return (0, int(value), ctime, stem_lower, ext_lower)
if group_type == "time_only":
return (1, ctime, stem_lower, ext_lower)
return (2, ctime, stem_lower, ext_lower)
def is_media_file(path: Path) -> bool:
return path.is_file() and path.suffix.lower() in MEDIA_EXTS
def is_image(path: Path) -> bool:
return path.suffix.lower() in IMAGE_EXTS
def is_video(path: Path) -> bool:
return path.suffix.lower() in VIDEO_EXTS
def iter_media_files(root_dir: Path):
for root, _, filenames in os.walk(root_dir):
for name in filenames:
file_path = Path(root) / name
if file_path.suffix.lower() in MEDIA_EXTS:
yield file_path
def organize_output(
output_dir: Path,
logger: Logger | None = None,
tr=t_identity,
minimal_rename: bool = False,
):
media_files = [path for path in output_dir.iterdir() if is_media_file(path)]
image_files = sorted(
[path for path in media_files if is_image(path)],
key=lambda path: split_existing_prefix_and_number(path)[1],
)
video_files = sorted(
[path for path in media_files if is_video(path)],
key=lambda path: split_existing_prefix_and_number(path)[1],
)
ordered_files = image_files + video_files
if minimal_rename:
planned: list[tuple[Path, Path]] = []
final_files: list[Path] = []
for index, file_path in enumerate(ordered_files, start=1):
prefix, _ = split_existing_prefix_and_number(file_path)
desired = output_dir / build_output_name(index, file_path.suffix, prefix)
final_files.append(desired)
if file_path.name != desired.name:
planned.append((file_path, desired))
if planned:
temp_pairs: list[tuple[Path, Path]] = []
for src_path, dst_path in planned:
temp_name = f"__temp__{uuid.uuid4().hex}{src_path.suffix.lower()}"
temp_path = output_dir / temp_name
src_path.rename(temp_path)
temp_pairs.append((temp_path, dst_path))
for temp_path, dst_path in temp_pairs:
temp_path.rename(dst_path)
renamed_files = final_files
else:
temp_files: list[tuple[Path, str]] = []
for file_path in ordered_files:
prefix, _ = split_existing_prefix_and_number(file_path)
temp_name = f"__temp__{uuid.uuid4().hex}{file_path.suffix.lower()}"
temp_path = output_dir / temp_name
file_path.rename(temp_path)
temp_files.append((temp_path, prefix))
renamed_files: list[Path] = []
for index, (temp_path, prefix) in enumerate(temp_files, start=1):
new_path = output_dir / build_output_name(index, temp_path.suffix, prefix)
temp_path.rename(new_path)
renamed_files.append(new_path)
if logger:
logger.write(tr("log_output_organized", count=len(renamed_files)))
return renamed_files
def collect_source_media(input_dir_configs: list[dict]):
image_files = []
video_files = []
for config in input_dir_configs:
source_path: Path = config["path"]
prefix: str = config.get("prefix", "")
for file_path in iter_media_files(source_path):
try:
ctime = os.path.getctime(file_path)
except OSError:
ctime = 0
item = (file_path, ctime, prefix)
if is_image(file_path):
image_files.append(item)
elif is_video(file_path):
video_files.append(item)
image_files.sort(key=source_sort_key)
video_files.sort(key=source_sort_key)
return image_files + video_files
def safe_delete_file(path: Path, logger: Logger | None = None, tr=t_identity):
try:
if path.exists():
path.unlink()
if logger:
logger.write(tr("log_source_deleted", path=path))
except Exception as exc:
if logger:
logger.write(tr("log_source_delete_failed", path=path, error=exc))
def create_safe_workspace(output_dir: Path) -> tuple[Path, Path]:
root = output_dir / ".imagemerge_temp"
session_dir = root / f"session-{uuid.uuid4().hex}"
workspace_output_dir = session_dir / "output"
workspace_output_dir.mkdir(parents=True, exist_ok=True)
return session_dir, workspace_output_dir
def copy_media_to_workspace(output_dir: Path, workspace_output_dir: Path):
for path in output_dir.iterdir():
if is_media_file(path):
shutil.copy2(path, workspace_output_dir / path.name)
def apply_workspace_to_output(output_dir: Path, workspace_output_dir: Path):
for path in list(output_dir.iterdir()):
if is_media_file(path):
path.unlink()
for path in workspace_output_dir.iterdir():
if is_media_file(path):
shutil.move(str(path), str(output_dir / path.name))
def process_media(
input_dir_configs: list[dict],
output_dir: Path,
mode: str,
clear_output_first: bool,
remove_duplicates_in_place: bool,
use_safe_temp_workspace: bool,
logger: Logger,
tr=t_identity,
):
if not input_dir_configs and mode not in {MODE_MAIN_FOLDER, MODE_INSIDE_FOLDER}:
raise ValueError(tr("error_no_input"))
input_paths = [config["path"] for config in input_dir_configs]
if mode not in {MODE_MAIN_FOLDER, MODE_INSIDE_FOLDER} and output_dir in input_paths:
raise ValueError(tr("error_output_same_as_input"))
output_dir.mkdir(parents=True, exist_ok=True)
active_output_dir = output_dir
session_dir: Path | None = None
pending_source_deletes: list[Path] = []
if use_safe_temp_workspace:
session_dir, workspace_output_dir = create_safe_workspace(output_dir)
copy_media_to_workspace(output_dir, workspace_output_dir)
active_output_dir = workspace_output_dir
logger.write(f"Safe workspace: {session_dir}")
logger.write(tr("log_start"))
logger.write(tr("log_mode", mode=mode))
logger.write(tr("log_output_dir", output=output_dir))
source_scan_configs: list[dict] = []
if mode == MODE_MAIN_FOLDER:
seen_paths: set[Path] = set()
source_scan_configs.append({"path": active_output_dir, "prefix": ""})
seen_paths.add(active_output_dir)
for config in input_dir_configs:
scan_path = config["path"]
if scan_path in seen_paths:
continue
source_scan_configs.append({"path": scan_path, "prefix": config.get("prefix", "")})
seen_paths.add(scan_path)
elif mode == MODE_INSIDE_FOLDER:
source_scan_configs.append({"path": active_output_dir, "prefix": ""})
else:
source_scan_configs = list(input_dir_configs)
for config in source_scan_configs:
logger.write(
tr(
"log_input_entry",
input_path=config["path"],
prefix=normalize_prefix(config.get("prefix", "")) or "-",
)
)
if clear_output_first:
logger.write(tr("log_clearing_output"))
removed = 0
for path in list(active_output_dir.iterdir()):
if is_media_file(path):
path.unlink()
removed += 1
logger.write(tr("log_cleared_output", count=removed))
if mode == MODE_INSIDE_FOLDER:
ordered_files = organize_output(active_output_dir, logger=logger, tr=tr, minimal_rename=True)
skipped = 0
deleted_sources = 0
failed = 0
if remove_duplicates_in_place:
seen_hashes: set[tuple[str, str]] = set()
for file_path in ordered_files:
try:
file_hash = sha256_file(file_path)
file_key = dedupe_key(file_hash, file_path.suffix)
if file_key in seen_hashes:
safe_delete_file(file_path, logger, tr)
deleted_sources += 1
skipped += 1
continue
seen_hashes.add(file_key)
except Exception as exc:
failed += 1
logger.write(tr("log_hash_failed", path=file_path, error=exc))
final_files = organize_output(active_output_dir, logger=logger, tr=tr, minimal_rename=True)
if use_safe_temp_workspace and session_dir:
apply_workspace_to_output(output_dir, active_output_dir)
shutil.rmtree(session_dir, ignore_errors=True)
logger.write("=" * 50)
logger.write(tr("log_added", count=0))
logger.write(tr("log_skipped", count=skipped))
logger.write(tr("log_moved_count", count=0))
logger.write(tr("log_copied_count", count=0))
logger.write(tr("log_deleted_sources", count=deleted_sources))
logger.write(tr("log_failed", count=failed))
logger.write(tr("log_total_output", count=len(final_files)))
logger.write(tr("log_done"))
return
existing_output_files = organize_output(active_output_dir, logger=logger, tr=tr)
existing_hashes: dict[tuple[str, str], Path] = {}
for file_path in existing_output_files:
try:
file_hash = sha256_file(file_path)
existing_hashes[dedupe_key(file_hash, file_path.suffix)] = file_path
except Exception as exc:
logger.write(tr("log_skip_unreadable_output", path=file_path, error=exc))
source_items = collect_source_media(source_scan_configs)
logger.write(tr("log_found_media", count=len(source_items)))
added = 0
skipped = 0
moved = 0
copied = 0
deleted_sources = 0
failed = 0
current_index = len(existing_output_files)
for file_path, _ctime, prefix in source_items:
try:
file_hash = sha256_file(file_path)
except Exception as exc:
failed += 1
logger.write(tr("log_hash_failed", path=file_path, error=exc))
continue
ext = file_path.suffix.lower()
file_key = dedupe_key(file_hash, ext)
if file_key in existing_hashes:
skipped += 1
logger.write(tr("log_duplicate_skip", path=file_path))
if mode in {MODE_MOVE, MODE_COPY_DELETE}:
if use_safe_temp_workspace:
pending_source_deletes.append(file_path)
else:
safe_delete_file(file_path, logger, tr)
deleted_sources += 1
continue
current_index += 1
dest_path = active_output_dir / build_output_name(current_index, ext, prefix)
try:
if mode == MODE_MOVE:
if use_safe_temp_workspace:
shutil.copy2(file_path, dest_path)
pending_source_deletes.append(file_path)
else:
shutil.move(str(file_path), str(dest_path))
moved += 1
logger.write(tr("log_moved", source=file_path, dest=dest_path.name))
elif mode == MODE_COPY_DELETE:
shutil.copy2(file_path, dest_path)
copied += 1
logger.write(tr("log_copied", source=file_path, dest=dest_path.name))
if use_safe_temp_workspace:
pending_source_deletes.append(file_path)
else:
safe_delete_file(file_path, logger, tr)
deleted_sources += 1
elif mode == MODE_COPY_KEEP:
shutil.copy2(file_path, dest_path)
copied += 1
logger.write(tr("log_copied", source=file_path, dest=dest_path.name))
elif mode in {MODE_MAIN_FOLDER, MODE_INSIDE_FOLDER}:
shutil.copy2(file_path, dest_path)
copied += 1
logger.write(tr("log_copied", source=file_path, dest=dest_path.name))
else:
raise ValueError(tr("error_unknown_mode", mode=mode))
existing_hashes[file_key] = dest_path
added += 1
except Exception as exc:
failed += 1
logger.write(tr("log_process_failed", path=file_path, error=exc))
final_files = organize_output(active_output_dir, logger=logger, tr=tr)
if use_safe_temp_workspace and session_dir:
apply_workspace_to_output(output_dir, active_output_dir)
unique_deletes: list[Path] = []
seen_del: set[Path] = set()
for path in pending_source_deletes:
if path not in seen_del:
seen_del.add(path)
unique_deletes.append(path)
for path in unique_deletes:
if path.exists():
safe_delete_file(path, logger, tr)
deleted_sources += 1
shutil.rmtree(session_dir, ignore_errors=True)
logger.write("=" * 50)
logger.write(tr("log_added", count=added))
logger.write(tr("log_skipped", count=skipped))
logger.write(tr("log_moved_count", count=moved))
logger.write(tr("log_copied_count", count=copied))
logger.write(tr("log_deleted_sources", count=deleted_sources))
logger.write(tr("log_failed", count=failed))
logger.write(tr("log_total_output", count=len(final_files)))
logger.write(tr("log_done"))
class ProcessWorker(QObject):
log_line = Signal(str)
process_done = Signal()
process_error = Signal(str)
finished = Signal()
def __init__(self, input_configs, output_dir, mode, clear_output_first, remove_duplicates_in_place, use_safe_temp_workspace, tr):
super().__init__()
self.input_configs = input_configs
self.output_dir = output_dir
self.mode = mode
self.clear_output_first = clear_output_first
self.remove_duplicates_in_place = remove_duplicates_in_place
self.use_safe_temp_workspace = use_safe_temp_workspace
self.tr = tr
def run(self):
logger = Logger(self.log_line.emit)
try:
process_media(
self.input_configs,
self.output_dir,
self.mode,
self.clear_output_first,
self.remove_duplicates_in_place,
self.use_safe_temp_workspace,
logger,
self.tr,
)
self.process_done.emit()
except Exception as exc:
logger.write(f"ERROR: {exc}")
self.process_error.emit(str(exc))
finally:
self.finished.emit()
def parse_cli_input(entry: str) -> dict:
raw = (entry or "").strip()
if not raw:
raise ValueError("Input entry cannot be empty")
if "::" in raw:
path_text, prefix_text = raw.rsplit("::", 1)
else:
path_text, prefix_text = raw, ""
path = Path(path_text).expanduser().resolve()
prefix = normalize_prefix(prefix_text)
return {"path": path, "prefix": prefix}
def create_cli_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog=APP_FALLBACK_TITLE,
description="ImageMerge CLI mode",
)
parser.add_argument("--cli", action="store_true", help="Run in CLI mode without opening GUI")
parser.add_argument("--input", action="append", default=[], metavar="PATH[::PREFIX]",
help="Input folder entry, repeatable.")
parser.add_argument("--output", default="", metavar="PATH", help="Output folder path")
parser.add_argument("--mode", default=MODE_COPY_KEEP,
choices=[MODE_COPY_KEEP, MODE_COPY_DELETE, MODE_MOVE, MODE_MAIN_FOLDER, MODE_INSIDE_FOLDER], help="Process mode")
parser.add_argument("--clear-output", action="store_true",
help="Clear media files in output before processing")
parser.add_argument("--remove-duplicates", action="store_true",
help="Inside organizer: remove duplicate files by content hash + extension")
parser.add_argument("--no-safe-temp", action="store_true",
help="Disable safe temp workspace staging and write directly to output")
parser.add_argument("--lang", default="", choices=sorted(SUPPORTED_LANGS), help="CLI log language")
return parser
def run_cli(argv: list[str]) -> int:
parser = create_cli_parser()
args = parser.parse_args(argv)
run_cli_mode = args.cli or bool(args.input) or bool(args.output)
if not run_cli_mode:
parser.print_help()
return 0
if not args.input and args.mode not in {MODE_MAIN_FOLDER, MODE_INSIDE_FOLDER}:
parser.error("--input is required in CLI mode")
if not args.output:
parser.error("--output is required in CLI mode")
input_configs = [parse_cli_input(entry) for entry in args.input]
lang = args.lang or detect_language()
tr = I18n(lang).t
output_dir = Path(args.output).expanduser().resolve()
logger = Logger(lambda text: print(text, flush=True))
process_media(
input_configs=input_configs,
output_dir=output_dir,
mode=args.mode,
clear_output_first=args.clear_output,
remove_duplicates_in_place=args.remove_duplicates,
use_safe_temp_workspace=(not args.no_safe_temp),
logger=logger,
tr=tr,
)
return 0
def _h_sep() -> QFrame:
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFixedHeight(1)
line.setStyleSheet(f"background:{C_BORDER2}; border:none;")
return line
def _section_label(text: str) -> QLabel:
lbl = QLabel(text.upper())
lbl.setStyleSheet(
f"color:{C_TEXT3}; font-size:11px; font-weight:700; letter-spacing:1.1px;"
)
return lbl
class ModeCard(QWidget):
clicked = Signal(str)
def __init__(self, mode_key: str, title: str, desc: str, parent=None):
super().__init__(parent)
self.mode_key = mode_key
self._selected = False
self.setCursor(Qt.PointingHandCursor)
self.setFixedHeight(120)
lay = QVBoxLayout(self)
lay.setContentsMargins(14, 12, 14, 12)
lay.setSpacing(6)
self.title_lbl = QLabel(title)
self.title_lbl.setStyleSheet(f"font-size:17px; font-weight:700; color:{C_TEXT};")
lay.addWidget(self.title_lbl)
self.desc_lbl = QLabel(desc)
self.desc_lbl.setWordWrap(True)
self.desc_lbl.setStyleSheet(f"font-size:13px; color:{C_TEXT2};")
lay.addWidget(self.desc_lbl)
lay.addStretch()
self._refresh_style()
def set_selected(self, selected: bool):
self._selected = selected
self._refresh_style()
if selected:
self.title_lbl.setStyleSheet(f"font-size:17px; font-weight:700; color:{C_ACCENT};")
else:
self.title_lbl.setStyleSheet(f"font-size:17px; font-weight:700; color:{C_TEXT};")
def _refresh_style(self):
if self._selected:
self.setStyleSheet(
f"background:{C_ACCENT_DIM}; border:2px solid {C_ACCENT}; border-radius:10px;"
)
else:
self.setStyleSheet(f"background:{C_SURFACE}; border:1px solid {C_BORDER2}; border-radius:10px;")
def mousePressEvent(self, _event):
self.clicked.emit(self.mode_key)
class SourceRow(QWidget):
remove_requested = Signal(str)
edit_requested = Signal(str)
def __init__(self, path: str, prefix: str, parent=None):
super().__init__(parent)
self.path_str = path
self._selected = False
self.setFixedHeight(46)
self.setCursor(Qt.PointingHandCursor)
lay = QHBoxLayout(self)
lay.setContentsMargins(14, 0, 10, 0)
lay.setSpacing(10)
self.path_lbl = QLabel(path)
self.path_lbl.setStyleSheet(f"font-size:14px; color:{C_TEXT};")
self.path_lbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
lay.addWidget(self.path_lbl)
self.prefix_lbl = QLabel(prefix if prefix else "—")
if prefix:
self.prefix_lbl.setStyleSheet(
f"font-size:12px; font-weight:700; color:{C_ACCENT};"
f" background:{C_ACCENT_DIM}; border:1px solid rgba(17,17,17,0.35);"
f" border-radius:10px; padding:1px 8px;"
)
else:
self.prefix_lbl.setStyleSheet(f"font-size:12px; color:{C_TEXT3}; padding:1px 8px;")
self.prefix_lbl.setFixedWidth(110)
self.prefix_lbl.setAlignment(Qt.AlignCenter)
lay.addWidget(self.prefix_lbl)
rm_btn = QPushButton("✕")
rm_btn.setFixedSize(24, 24)
rm_btn.setCursor(Qt.PointingHandCursor)
rm_btn.setStyleSheet(
f"QPushButton {{ background:transparent; border:none; color:{C_TEXT3};"
f" border-radius:5px; font-size:12px; }}"
f"QPushButton:hover {{ background:rgba(30,30,30,0.12); color:{C_DANGER}; }}"
)
rm_btn.clicked.connect(lambda: self.remove_requested.emit(self.path_str))
lay.addWidget(rm_btn)
self._refresh_style()
def update_prefix(self, prefix: str):
self.prefix_lbl.setText(prefix if prefix else "—")
if prefix:
self.prefix_lbl.setStyleSheet(
f"font-size:12px; font-weight:700; color:{C_ACCENT};"
f" background:{C_ACCENT_DIM}; border:1px solid rgba(17,17,17,0.35);"
f" border-radius:10px; padding:1px 8px;"
)
else:
self.prefix_lbl.setStyleSheet(f"font-size:12px; color:{C_TEXT3}; padding:1px 8px;")
def set_selected(self, selected: bool):
self._selected = selected
self._refresh_style()
def _refresh_style(self):
if self._selected:
self.setStyleSheet(f"background:{C_ACCENT_DIM};")
else:
self.setStyleSheet("background:transparent;")
def mouseDoubleClickEvent(self, _event):
self.edit_requested.emit(self.path_str)
def mousePressEvent(self, _event):
self.edit_requested.emit(self.path_str)
class FolderOnlyRow(QWidget):
remove_requested = Signal(str)
edit_requested = Signal(str)
def __init__(self, path: str, parent=None):
super().__init__(parent)
self.path_str = path
self._selected = False
self.setFixedHeight(42)
self.setCursor(Qt.PointingHandCursor)
lay = QHBoxLayout(self)
lay.setContentsMargins(14, 0, 10, 0)
lay.setSpacing(10)
self.path_lbl = QLabel(path)
self.path_lbl.setStyleSheet(f"font-size:14px; color:{C_TEXT};")
self.path_lbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
lay.addWidget(self.path_lbl)
rm_btn = QPushButton("✕")
rm_btn.setFixedSize(24, 24)
rm_btn.setCursor(Qt.PointingHandCursor)
rm_btn.setStyleSheet(
f"QPushButton {{ background:transparent; border:none; color:{C_TEXT3};"
f" border-radius:5px; font-size:12px; }}"
f"QPushButton:hover {{ background:rgba(30,30,30,0.12); color:{C_DANGER}; }}"
)
rm_btn.clicked.connect(lambda: self.remove_requested.emit(self.path_str))
lay.addWidget(rm_btn)
self._refresh_style()
def set_selected(self, selected: bool):
self._selected = selected
self._refresh_style()
def _refresh_style(self):
if self._selected:
self.setStyleSheet(f"background:{C_ACCENT_DIM};")
else:
self.setStyleSheet("background:transparent;")
def mouseDoubleClickEvent(self, _event):
self.edit_requested.emit(self.path_str)
def mousePressEvent(self, _event):
self.edit_requested.emit(self.path_str)
class StatCard(QWidget):
def __init__(self, label: str, color: str = C_TEXT, parent=None):
super().__init__(parent)
self._color = color
lay = QVBoxLayout(self)
lay.setContentsMargins(12, 10, 12, 10)
lay.setSpacing(2)
self.value_lbl = QLabel("—")
self.value_lbl.setStyleSheet(f"font-size:26px; font-weight:700; color:{color};")
lay.addWidget(self.value_lbl)
self.label_lbl = QLabel(label.upper())
self.label_lbl.setStyleSheet(
f"font-size:11px; font-weight:700; letter-spacing:0.6px; color:{C_TEXT3};"
)
lay.addWidget(self.label_lbl)
self.setStyleSheet(f"background:{C_SURFACE2}; border-radius:8px;")
def set_value(self, val):
self.value_lbl.setText(str(val))
def set_label(self, text: str):
self.label_lbl.setText(text.upper())
class App(QMainWindow):
def __init__(self):
super().__init__()
self.i18n = I18n(detect_language())
self.t = self.i18n.t
icon_path = Path(__file__).resolve().parent / "assets" / "icon.ico"
if icon_path.exists():
self.setWindowIcon(QIcon(str(icon_path)))
self.setWindowTitle(self.t("app_title") or APP_FALLBACK_TITLE)
self.resize(1360, 900)
self.setMinimumSize(1100, 720)
self.input_entries: list[dict] = []
self._source_rows: dict[str, SourceRow] = {}
self._selected_path: str | None = None
self.main_input_entries: list[dict] = []
self._main_source_rows: dict[str, FolderOnlyRow] = {}
self._main_selected_path: str | None = None
self._current_mode: str = MODE_COPY_KEEP