-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1229 lines (1029 loc) · 54.8 KB
/
Copy pathmain.py
File metadata and controls
1229 lines (1029 loc) · 54.8 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 os
import sys
import json
import requests
from PIL import Image
from io import BytesIO
from pathlib import Path
from typing import List, Optional, Tuple
from tqdm import tqdm
from threading import Lock
from concurrent.futures import ThreadPoolExecutor, as_completed
import glob
from datetime import datetime
from urllib.parse import urlparse
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.table import Table
from rich import box
from rich.prompt import Prompt, Confirm
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeRemainingColumn
# Global console instance
console = Console()
def print_success(message: str):
"""Print success message"""
console.print(f"[bold green]✓[/bold green] {message}")
def print_error(message: str):
"""Print error message"""
console.print(f"[bold red]✗[/bold red] {message}")
def print_info(message: str):
"""Print info message"""
console.print(f"[bold cyan]ℹ[/bold cyan] {message}")
def print_warning(message: str):
"""Print warning message"""
console.print(f"[bold yellow]⚠[/bold yellow] {message}")
def print_result_table(success: int, fail: int, skipped: int = None):
"""Print results in a beautiful table"""
result_table = Table(title="KẾT QUẢ", box=box.DOUBLE_EDGE, border_style="bright_cyan", show_header=False)
result_table.add_column("Status", style="bold", width=15)
result_table.add_column("Count", justify="right", style="bold")
result_table.add_row("[green]Thành công[/green]", f"[green]{success}[/green]")
result_table.add_row("[red]Thất bại[/red]", f"[red]{fail}[/red]")
if skipped is not None:
result_table.add_row("[yellow]Bỏ qua[/yellow]", f"[yellow]{skipped}[/yellow]")
result_table.add_row("[cyan]Tổng cộng[/cyan]", f"[cyan]{success + fail + skipped}[/cyan]")
else:
result_table.add_row("[cyan]Tổng cộng[/cyan]", f"[cyan]{success + fail}[/cyan]")
console.print(result_table)
class ImageConverter:
"""Công cụ chuyển đổi định dạng ảnh từ URL"""
SUPPORTED_FORMATS = ['PNG', 'JPEG', 'JPG', 'WEBP', 'BMP', 'GIF', 'TIFF', 'ICO']
CHECKPOINT_FILE = '.image_converter_checkpoint.json'
MAX_WORKERS = 5 # Số luồng tối đa mặc định
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})
self.checkpoint_lock = Lock() # Lock để đảm bảo thread-safe khi lưu checkpoint
def __del__(self):
"""Cleanup session khi object bị destroy"""
try:
if hasattr(self, 'session'):
self.session.close()
except Exception:
pass
def validate_url(self, url: str) -> bool:
"""Kiểm tra URL có hợp lệ không"""
try:
result = urlparse(url.strip())
return all([result.scheme in ['http', 'https'], result.netloc])
except Exception:
return False
def save_checkpoint(self, file_path: str, processed_indices: list, output_format: str, output_dir: str):
"""Lưu tiến trình hiện tại vào checkpoint file (thread-safe)"""
with self.checkpoint_lock:
checkpoint_data = {
'file_path': file_path,
'processed_indices': processed_indices.copy(), # Copy để tránh race condition
'output_format': output_format,
'output_dir': output_dir,
'timestamp': datetime.now().isoformat()
}
try:
with open(self.CHECKPOINT_FILE, 'w', encoding='utf-8') as f:
json.dump(checkpoint_data, f, indent=2)
except Exception as e:
console.print(f"[bold yellow]⚠[/bold yellow] Không thể lưu checkpoint: {e}")
def load_checkpoint(self) -> Optional[dict]:
"""Đọc checkpoint nếu có"""
if os.path.exists(self.CHECKPOINT_FILE):
try:
with open(self.CHECKPOINT_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception:
# Xóa checkpoint bị corrupt
try:
os.remove(self.CHECKPOINT_FILE)
except Exception:
pass
return None
return None
def clear_checkpoint(self):
"""Xóa checkpoint file"""
try:
if os.path.exists(self.CHECKPOINT_FILE):
os.remove(self.CHECKPOINT_FILE)
except Exception:
pass
def download_image(self, url: str, silent: bool = False) -> Tuple[Optional[Image.Image], int]:
"""Tải ảnh từ URL và trả về ảnh cùng với kích thước file gốc"""
try:
if not silent:
console.print(f"[bold cyan]>[/bold cyan] Đang tải ảnh từ: {url}")
# Validate URL trước khi tải
if not self.validate_url(url):
if not silent:
console.print(f"[bold red]✗[/bold red] URL không hợp lệ: {url}")
return None, 0
response = self.session.get(url, timeout=30)
response.raise_for_status()
original_size = len(response.content)
image = Image.open(BytesIO(response.content))
if not silent:
size_mb = original_size / (1024 * 1024)
console.print(f"[bold green]✓[/bold green] Tải thành công! Kích thước: {image.size}, Định dạng: {image.format}, Dung lượng: {size_mb:.2f} MB ({original_size:,} bytes)")
return image, original_size
except requests.exceptions.RequestException as e:
if not silent:
console.print(f"[bold red]✗[/bold red] Lỗi khi tải ảnh: {e}")
return None, 0
except Exception as e:
if not silent:
console.print(f"[bold red]✗[/bold red] Lỗi khi xử lý ảnh: {e}")
return None, 0
def convert_image(self, image: Image.Image, output_format: str) -> Optional[Image.Image]:
"""Chuyển đổi định dạng ảnh"""
try:
output_format = output_format.upper()
# Xử lý chuyển đổi cho các định dạng đặc biệt
if output_format in ['JPEG', 'JPG']:
# JPEG không hỗ trợ transparency, chuyển sang RGB
if image.mode in ('RGBA', 'LA', 'P'):
background = Image.new('RGB', image.size, (255, 255, 255))
if image.mode == 'P':
image = image.convert('RGBA')
background.paste(image, mask=image.split()[-1] if image.mode in ('RGBA', 'LA') else None)
image = background
elif image.mode != 'RGB':
image = image.convert('RGB')
elif output_format == 'PNG':
# Đảm bảo PNG có alpha channel nếu cần
if image.mode not in ('RGBA', 'RGB'):
image = image.convert('RGBA')
elif output_format in ['BMP', 'ICO']:
# BMP và ICO thường sử dụng RGB
if image.mode not in ('RGB', 'RGBA'):
image = image.convert('RGB')
return image
except Exception as e:
# Không in error để tránh rối progress bar
return None
def save_image(self, image: Image.Image, output_path: str, output_format: str, silent: bool = False, check_duplicate: bool = True) -> bool:
"""Lưu ảnh với định dạng mới"""
try:
output_format = output_format.upper()
if output_format == 'JPG':
output_format = 'JPEG'
# Kiểm tra file đã tồn tại
if check_duplicate and os.path.exists(output_path):
if not silent:
console.print(f"[bold yellow]ℹ[/bold yellow] File đã tồn tại, bỏ qua: {output_path}")
return False
# Tạo thư mục nếu chưa tồn tại
os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True)
# Lưu ảnh với các tham số tối ưu
save_kwargs = {'format': output_format}
if output_format == 'JPEG':
save_kwargs['quality'] = 85
save_kwargs['optimize'] = True
elif output_format == 'PNG':
save_kwargs['optimize'] = True
elif output_format == 'WEBP':
save_kwargs['quality'] = 80 # Giảm quality để giảm dung lượng
save_kwargs['method'] = 6 # Nén mạnh hơn (0-6, 6 là chậm nhưng nén tốt nhất)
save_kwargs['optimize'] = True
image.save(output_path, **save_kwargs)
if not silent:
# Hiển thị thông tin dung lượng file sau khi lưu
saved_size = os.path.getsize(output_path)
size_mb = saved_size / (1024 * 1024)
console.print(f"[bold green]✓[/bold green] Đã lưu: {output_path}")
console.print(f"[bold cyan]ℹ[/bold cyan] Dung lượng file: {size_mb:.2f} MB ({saved_size:,} bytes)")
return True
except Exception as e:
if not silent:
console.print(f"[bold red]✗[/bold red] Lỗi khi lưu ảnh: {e}")
return False
def _worker_process_url(self, idx: int, url: str, output_format: str, output_dir: str, custom_name: Optional[str] = None) -> Tuple[int, int]:
"""Worker function để xử lý URL trong thread pool
Returns: (idx, status) where status: 1=success, 0=fail, -1=skip
"""
# Tính tên file trước để kiểm tra
if custom_name:
filename = f"{custom_name}.{output_format.lower()}"
else:
url_path = url.split('?')[0]
original_name = os.path.splitext(os.path.basename(url_path))[0]
if not original_name:
original_name = f"image_{hash(url) % 10000}"
filename = f"{original_name}.{output_format.lower()}"
output_path = os.path.join(output_dir, filename)
# Kiểm tra file đã tồn tại
if os.path.exists(output_path):
return idx, -1 # Skip
success = self.process_url(url, output_format, output_dir, custom_name, silent=True)
return idx, 1 if success else 0
def _worker_process_movie(self, idx: int, movie: dict, output_format: str, output_dir: str) -> Tuple[int, int]:
"""Worker function để xử lý movie trong thread pool
Returns: (idx, status) where status: 1=success, 0=fail, -1=skip
"""
# Kiểm tra có trường url và slug không
if 'url' not in movie or 'slug' not in movie:
return idx, -1 # Skip
image_url = movie['url']
slug = movie['slug']
# Bỏ qua nếu URL hoặc slug trống
if not image_url or not slug:
return idx, -1 # Skip
# Kiểm tra file đã tồn tại
filename = f"{slug}.{output_format.lower()}"
output_path = os.path.join(output_dir, filename)
if os.path.exists(output_path):
return idx, -1 # Skip
# Xử lý chuyển đổi
image, original_size = self.download_image(image_url, silent=True)
if image is not None: # Check đúng cách
converted_image = self.convert_image(image, output_format)
if converted_image:
filename = f"{slug}.{output_format.lower()}"
output_path = os.path.join(output_dir, filename)
if self.save_image(converted_image, output_path, output_format, silent=True):
return idx, 1 # Success
return idx, 0 # Fail
def process_url(self, url: str, output_format: str, output_dir: str, custom_name: Optional[str] = None, silent: bool = False) -> bool:
"""Xử lý một URL ảnh"""
if not silent:
console.print(f"\n[dim]{'='*60}[/dim]")
# Tải ảnh
image, original_size = self.download_image(url, silent=silent)
if image is None:
return False
# Chuyển đổi định dạng
converted_image = self.convert_image(image, output_format)
if not converted_image:
return False
# Tạo tên file
if custom_name:
filename = f"{custom_name}.{output_format.lower()}"
else:
# Lấy tên file từ URL
url_path = url.split('?')[0] # Bỏ query parameters
original_name = os.path.splitext(os.path.basename(url_path))[0]
if not original_name:
original_name = f"image_{hash(url) % 10000}"
filename = f"{original_name}.{output_format.lower()}"
output_path = os.path.join(output_dir, filename)
# Lưu ảnh
success = self.save_image(converted_image, output_path, output_format, silent=silent)
if success and original_size > 0 and not silent:
saved_size = os.path.getsize(output_path)
diff = saved_size - original_size
percent = (diff / original_size) * 100
if diff > 0:
console.print(f"[bold yellow]⚠[/bold yellow] Dung lượng tăng: +{diff:,} bytes (+{percent:.1f}%)")
else:
console.print(f"[bold green]✓[/bold green] Dung lượng giảm: {abs(diff):,} bytes ({abs(percent):.1f}%)")
return success
def process_urls_from_file(self, file_path: str, output_format: str, output_dir: str, resume: bool = False, num_workers: int = None) -> Tuple[int, int, int]:
"""Xử lý nhiều URL từ file với hỗ trợ checkpoint và đa luồng"""
if num_workers is None:
num_workers = self.MAX_WORKERS
try:
with open(file_path, 'r', encoding='utf-8') as f:
urls = [line.strip() for line in f if line.strip() and not line.startswith('#')]
if not urls:
print_error("File không chứa URL nào!")
return 0, 0, 0
# Kiểm tra resume checkpoint
processed_indices = []
start_index = 0
if resume:
checkpoint = self.load_checkpoint()
if checkpoint and checkpoint.get('file_path') == file_path:
processed_indices = checkpoint.get('processed_indices', [])
start_index = len(processed_indices)
console.print(f"\n[bold cyan]>[/bold cyan] Tiếp tục từ ảnh thứ {start_index + 1}/{len(urls)}")
print_info(f"Tìm thấy {len(urls)} URL trong file")
print_info(f"Sử dụng {num_workers} luồng để xử lý")
if start_index > 0:
print_info(f"Đã xử lý: {start_index} ảnh")
# Constants cho status
STATUS_SUCCESS = 1
STATUS_FAIL = 0
STATUS_SKIP = -1
# Đếm từ processed_results
success_count = 0
fail_count = 0
skipped_count = 0
for item in processed_indices:
if isinstance(item, (list, tuple)):
_, status = item
if status == STATUS_SUCCESS:
success_count += 1
elif status == STATUS_FAIL:
fail_count += 1
else:
skipped_count += 1
else:
# Format cũ để tương thích
if item >= 0:
success_count += 1
else:
fail_count += 1
executor = None
try:
# Sử dụng ThreadPoolExecutor để xử lý đa luồng
executor = ThreadPoolExecutor(max_workers=num_workers)
with tqdm(total=len(urls), initial=start_index, desc="[>] Đang chuyển đổi", unit="ảnh", ncols=100, colour='cyan') as pbar:
# Submit tasks theo batch
batch_size = num_workers * 2
idx = start_index
while idx < len(urls):
# Submit batch tasks
futures = {}
batch_end = min(idx + batch_size, len(urls))
for i in range(idx, batch_end):
future = executor.submit(self._worker_process_url, i, urls[i], output_format, output_dir)
futures[future] = i
# Xử lý kết quả khi hoàn thành
for future in as_completed(futures):
task_idx, status = future.result()
# Thread-safe append
with self.checkpoint_lock:
processed_indices.append([task_idx, status])
if status == STATUS_SUCCESS:
success_count += 1
elif status == STATUS_FAIL:
fail_count += 1
else: # STATUS_SKIP
skipped_count += 1
pbar.update(1)
# Lưu checkpoint sau mỗi batch
self.save_checkpoint(file_path, processed_indices, output_format, output_dir)
idx = batch_end
# Hoàn thành - xóa checkpoint
self.clear_checkpoint()
except KeyboardInterrupt:
console.print("\n\n[bold yellow]⚠[/bold yellow] Đã bị gián đoạn! Đang lưu tiến trình...")
# Shutdown executor trước khi lưu
if executor:
executor.shutdown(wait=True, cancel_futures=True)
self.save_checkpoint(file_path, processed_indices, output_format, output_dir)
print_success(f"Đã lưu tiến trình: {len(processed_indices)}/{len(urls)} ảnh")
print_info("Chạy lại và chọn 'Resume' để tiếp tục")
return success_count, fail_count, skipped_count
finally:
# Đảm bảo executor được đóng
if executor:
executor.shutdown(wait=False)
return success_count, fail_count, skipped_count
except FileNotFoundError:
print_error(f"Không tìm thấy file: {file_path}")
return 0, 0, 0
except Exception as e:
print_error(f"Lỗi khi đọc file: {e}")
return 0, 0, 0
def process_movies_json(self, file_path: str, output_format: str, output_dir: str, resume: bool = False, num_workers: int = None) -> Tuple[int, int, int]:
"""Xử lý file JSON với định dạng movies (slug làm tên, url làm URL) với đa luồng"""
if num_workers is None:
num_workers = self.MAX_WORKERS
# Constants cho status
STATUS_SUCCESS = 1
STATUS_FAIL = 0
STATUS_SKIP = -1
try:
with open(file_path, 'r', encoding='utf-8') as f:
movies = json.load(f)
if not movies:
print_error("File JSON không chứa dữ liệu!")
return 0, 0, 0
if not isinstance(movies, list):
print_error("File JSON phải là một mảng các object!")
return 0, 0, 0
# Kiểm tra resume checkpoint
processed_results = [] # Lưu tuple (idx, status) thay vì magic number
start_index = 0
if resume:
checkpoint = self.load_checkpoint()
if checkpoint and checkpoint.get('file_path') == file_path:
# Chuyển đổi format cũ sang format mới
old_indices = checkpoint.get('processed_indices', [])
for idx_val in old_indices:
if isinstance(idx_val, list): # Format mới
processed_results.append(tuple(idx_val))
else: # Format cũ
if idx_val >= 0:
processed_results.append((idx_val, STATUS_SUCCESS))
elif idx_val == -999999:
processed_results.append((len(processed_results), STATUS_SKIP))
else:
processed_results.append((abs(idx_val), STATUS_FAIL))
start_index = len(processed_results)
console.print(f"\n[bold cyan]>[/bold cyan] Tiếp tục từ phim thứ {start_index + 1}/{len(movies)}")
print_info(f"Tìm thấy {len(movies)} bộ phim trong file")
print_info(f"Sử dụng {num_workers} luồng để xử lý")
if start_index > 0:
print_info(f"Đã xử lý: {start_index} phim")
# Đếm từ processed_results
success_count = sum(1 for _, status in processed_results if status == STATUS_SUCCESS)
fail_count = sum(1 for _, status in processed_results if status == STATUS_FAIL)
skipped_count = sum(1 for _, status in processed_results if status == STATUS_SKIP)
executor = None
try:
# Sử dụng ThreadPoolExecutor để xử lý đa luồng
executor = ThreadPoolExecutor(max_workers=num_workers)
with tqdm(total=len(movies), initial=start_index, desc="[>] Đang chuyển đổi ảnh", unit="phim", ncols=100, colour='green') as pbar:
# Submit tasks theo batch
batch_size = num_workers * 2
idx = start_index
while idx < len(movies):
# Submit batch tasks
futures = {}
batch_end = min(idx + batch_size, len(movies))
for i in range(idx, batch_end):
future = executor.submit(self._worker_process_movie, i, movies[i], output_format, output_dir)
futures[future] = i
# Xử lý kết quả khi hoàn thành
for future in as_completed(futures):
task_idx, status = future.result()
# Thread-safe với lock bao toàn bộ operations
with self.checkpoint_lock:
processed_results.append((task_idx, status))
if status == STATUS_SUCCESS:
success_count += 1
elif status == STATUS_FAIL:
fail_count += 1
else: # STATUS_SKIP
skipped_count += 1
pbar.update(1)
# Lưu checkpoint sau mỗi batch - chuyển đổi sang list để JSON serializable
indices_for_checkpoint = [list(item) for item in processed_results]
self.save_checkpoint(file_path, indices_for_checkpoint, output_format, output_dir)
idx = batch_end
# Hoàn thành - xóa checkpoint
self.clear_checkpoint()
except KeyboardInterrupt:
console.print("\n\n[bold yellow]⚠[/bold yellow] Đã bị gián đoạn! Đang lưu tiến trình...")
# Shutdown executor trước khi lưu
if executor:
executor.shutdown(wait=True, cancel_futures=True)
indices_for_checkpoint = [list(item) for item in processed_results]
self.save_checkpoint(file_path, indices_for_checkpoint, output_format, output_dir)
print_success(f"Đã lưu tiến trình: {len(processed_results)}/{len(movies)} phim")
print_info("Chạy lại và chọn 'Resume' để tiếp tục")
return success_count, fail_count, skipped_count
finally:
# Đảm bảo executor được đóng
if executor:
executor.shutdown(wait=False)
return success_count, fail_count, skipped_count
except FileNotFoundError:
print_error(f"Không tìm thấy file: {file_path}")
return 0, 0, 0
except json.JSONDecodeError as e:
print_error(f"Lỗi khi đọc file JSON: {e}")
return 0, 0, 0
except Exception as e:
print_error(f"Lỗi: {e}")
return 0, 0, 0
def filter_undownloaded_movies(json_file: str, image_dir: str, output_file: str, image_format: str = 'webp') -> Tuple[int, int, int]:
"""Lọc các phim chưa tải từ file JSON, so sánh với thư mục ảnh
Args:
json_file: Đường dẫn đến file JSON chứa danh sách phim
image_dir: Thư mục chứa ảnh đã tải
output_file: File JSON output chứa danh sách phim chưa tải
image_format: Định dạng ảnh để kiểm tra (mặc định: webp)
Returns:
Tuple[int, int, int]: (số phim chưa tải, số phim đã tải, tổng số phim)
"""
try:
# Đọc file JSON
with open(json_file, 'r', encoding='utf-8') as f:
movies = json.load(f)
if not movies or not isinstance(movies, list):
print_error("File JSON không hợp lệ!")
return 0, 0, 0
print_info(f"Đang phân tích {len(movies)} phim từ file JSON...")
# Lấy danh sách file ảnh đã tải (không phân biệt định dạng)
downloaded_files = set()
if os.path.exists(image_dir):
# Lấy tất cả các file ảnh với các định dạng phổ biến
for ext in ['*.jpg', '*.jpeg', '*.png', '*.webp', '*.gif', '*.bmp']:
pattern = os.path.join(image_dir, ext)
for file_path in glob.glob(pattern):
# Lấy tên file không có extension
filename = os.path.splitext(os.path.basename(file_path))[0]
downloaded_files.add(filename.lower())
print_info(f"Tìm thấy {len(downloaded_files)} ảnh đã tải trong thư mục '{image_dir}'")
# Lọc các phim chưa tải
undownloaded_movies = []
downloaded_count = 0
skipped_count = 0
for movie in movies:
# Kiểm tra có slug và url không
if 'slug' not in movie or 'url' not in movie:
skipped_count += 1
continue
slug = movie['slug']
url = movie['url']
if not slug or not url:
skipped_count += 1
continue
# Kiểm tra xem ảnh đã tải chưa
if slug.lower() not in downloaded_files:
undownloaded_movies.append(movie)
else:
downloaded_count += 1
# Lưu danh sách phim chưa tải vào file mới
if undownloaded_movies:
os.makedirs(os.path.dirname(output_file) if os.path.dirname(output_file) else '.', exist_ok=True)
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(undownloaded_movies, f, ensure_ascii=False, indent=2)
console.print()
print_success(f"Đã lưu {len(undownloaded_movies)} phim chưa tải vào: {output_file}")
else:
console.print()
print_info("Tất cả phim đã được tải!")
return len(undownloaded_movies), downloaded_count, len(movies)
except FileNotFoundError:
print_error(f"Không tìm thấy file: {json_file}")
return 0, 0, 0
except json.JSONDecodeError as e:
print_error(f"Lỗi khi đọc file JSON: {e}")
return 0, 0, 0
except Exception as e:
print_error(f"Lỗi: {e}")
return 0, 0, 0
def filter_movies_menu():
"""Menu lọc phim chưa tải"""
console.print()
# Kiểm tra thư mục mock và hiển thị các file JSON có sẵn
mock_dir = "mock"
json_files = []
if os.path.exists(mock_dir) and os.path.isdir(mock_dir):
json_files = [f for f in os.listdir(mock_dir) if f.endswith('.json')]
if json_files:
print_info("Tìm thấy các file JSON trong thư mục mock:")
console.print()
files_table = Table(show_header=False, box=box.SIMPLE, border_style="cyan")
files_table.add_column("#", style="bright_cyan", width=6)
files_table.add_column("Filename", style="bright_white")
files_table.add_column("Size", style="yellow", justify="right")
for i, filename in enumerate(json_files, 1):
file_path_display = os.path.join(mock_dir, filename)
file_size = os.path.getsize(file_path_display)
size_kb = file_size / 1024
files_table.add_row(f"{i}.", filename, f"{size_kb:.2f} KB")
files_table.add_row(f"{len(json_files) + 1}.", "Nhập đường dẫn khác", "")
console.print(files_table)
while True:
try:
choice = Prompt.ask(f"\n[bold]Chọn file (1-{len(json_files) + 1})[/bold]")
choice_idx = int(choice) - 1
if 0 <= choice_idx < len(json_files):
json_file = os.path.join(mock_dir, json_files[choice_idx])
print_success(f"Đã chọn: [cyan]{json_file}[/cyan]")
break
elif choice_idx == len(json_files):
json_file = Prompt.ask("\n[bold cyan]Nhập đường dẫn file JSON[/bold cyan]")
if not json_file or not os.path.exists(json_file):
print_error("Đường dẫn file không hợp lệ!")
return
break
else:
print_error(f"Vui lòng chọn số từ 1 đến {len(json_files) + 1}")
except ValueError:
print_error("Vui lòng nhập số hợp lệ!")
else:
json_file = Prompt.ask("\n[bold cyan]Nhập đường dẫn file JSON[/bold cyan]")
if not json_file or not os.path.exists(json_file):
print_error("Đường dẫn file không hợp lệ!")
return
# Nhập thư mục chứa ảnh đã tải
image_dir = Prompt.ask("\n[bold cyan]Nhập đường dẫn thư mục chứa ảnh[/bold cyan] [dim](Enter = 'images')[/dim]", default="images")
# Nhập định dạng ảnh để kiểm tra
image_format = Prompt.ask("\n[bold cyan]Định dạng ảnh để kiểm tra[/bold cyan] [dim](Enter = 'webp')[/dim]", default="webp").lower()
# Tạo tên file output
base_name = os.path.splitext(os.path.basename(json_file))[0]
output_file = os.path.join(mock_dir, f"{base_name}_undownloaded.json")
custom_output = Prompt.ask(f"\n[bold cyan]Tên file output[/bold cyan] [dim](Enter = '{output_file}')[/dim]", default=output_file)
if custom_output and custom_output != output_file:
output_file = custom_output
console.print("\n[bold yellow]⏳ Đang phân tích...[/bold yellow]")
undownloaded, downloaded, total = filter_undownloaded_movies(json_file, image_dir, output_file, image_format)
# Display filter results
result_table = Table(title="KẾT QUẢ LỌC", box=box.DOUBLE_EDGE, border_style="bright_cyan", show_header=False)
result_table.add_column("Status", style="bold", width=15)
result_table.add_column("Count", justify="right", style="bold")
result_table.add_row("[yellow]Chưa tải[/yellow]", f"[yellow]{undownloaded}[/yellow]")
result_table.add_row("[green]Đã tải[/green]", f"[green]{downloaded}[/green]")
result_table.add_row("[cyan]Tổng cộng[/cyan]", f"[cyan]{total}[/cyan]")
if total > 0:
percent = (downloaded / total) * 100
result_table.add_row("[blue]Tiến độ[/blue]", f"[blue]{percent:.1f}%[/blue]")
console.print()
console.print(result_table)
def show_user_guide():
"""Hiển thị hướng dẫn sử dụng"""
console.print()
# Title
guide_title = Panel(
Text("HƯỚNG DẪN SỬ DỤNG", style="bold bright_white", justify="center"),
box=box.DOUBLE,
border_style="bright_cyan"
)
console.print(guide_title)
console.print()
# Tổng quan
console.print("[bold bright_cyan]TỔNG QUAN[/bold bright_cyan]")
console.print("Image Format Converter là công cụ chuyển đổi định dạng ảnh từ URL với các tính năng:")
console.print(" • Chuyển đổi từ URL đơn lẻ hoặc hàng loạt")
console.print(" • Hỗ trợ 8 định dạng: PNG, JPEG, JPG, WEBP, BMP, GIF, TIFF, ICO")
console.print(" • Xử lý đa luồng tăng tốc độ")
console.print(" • Lưu tiến trình và tiếp tục khi bị gián đoạn")
console.print()
# Hướng dẫn chi tiết
features_table = Table(
title="CÁC CHỨC NĂNG",
box=box.ROUNDED,
border_style="bright_blue",
show_header=True,
header_style="bold bright_cyan"
)
features_table.add_column("Chức năng", style="bright_yellow", width=30)
features_table.add_column("Mô tả", style="white")
features_table.add_row(
"1️⃣ Chuyển đổi từ một URL",
"Tải và chuyển đổi một ảnh từ URL.\nPhù hợp khi bạn chỉ cần xử lý 1 ảnh."
)
features_table.add_row(
"2️⃣ Chuyển đổi từ file URL",
"Xử lý hàng loạt URL từ file .txt\nMỗi dòng là một URL.\nHỗ trợ Resume khi gián đoạn."
)
features_table.add_row(
"3️⃣ Chuyển đổi từ JSON",
"Xử lý file JSON với format movies.\nCần có trường 'url' (URL) và 'slug' (tên file).\nTự động bỏ qua file đã tồn tại."
)
features_table.add_row(
"4️⃣ Lọc phim chưa tải",
"So sánh file JSON với thư mục ảnh.\nTạo file mới chỉ chứa phim chưa tải.\nTiết kiệm thời gian xử lý."
)
features_table.add_row(
"5️⃣ Xóa checkpoint",
"Xóa tiến trình đã lưu.\nDùng khi muốn bắt đầu lại từ đầu."
)
features_table.add_row(
"6️⃣ Hướng dẫn sử dụng",
"Hiển thị hướng dẫn này."
)
console.print(features_table)
console.print()
# Format file
console.print("[bold bright_cyan]CẤU TRÚC FILE[/bold bright_cyan]")
console.print()
console.print("[bold yellow]File URL (.txt):[/bold yellow]")
console.print("[dim]https://example.com/image1.jpg[/dim]")
console.print("[dim]https://example.com/image2.png[/dim]")
console.print("[dim]# Comment lines start with #[/dim]")
console.print("[dim]https://example.com/image3.webp[/dim]")
console.print()
console.print("[bold yellow]File JSON (movies format):[/bold yellow]")
console.print('[dim][[/dim]')
console.print('[dim] {"slug": "movie-name-1", "url": "https://..."},[/dim]')
console.print('[dim] {"slug": "movie-name-2", "url": "https://..."}[/dim]')
console.print('[dim]][/dim]')
console.print()
# Tips
console.print("[bold bright_cyan]💡 MẸO SỬ DỤNG[/bold bright_cyan]")
tips_table = Table(show_header=False, box=None, padding=(0, 2))
tips_table.add_column("Icon", style="bright_green", width=5)
tips_table.add_column("Tip", style="white")
tips_table.add_row("✓", "Tăng số luồng (5-10) để xử lý nhanh hơn với nhiều ảnh")
tips_table.add_row("✓", "Dùng WEBP để giảm dung lượng tối đa (80% so với JPEG)")
tips_table.add_row("✓", "Nhấn Ctrl+C để dừng, tiến trình sẽ được lưu tự động")
tips_table.add_row("✓", "Chọn Resume để tiếp tục từ nơi đã dừng")
tips_table.add_row("✓", "Kiểm tra thư mục 'mock/' để xem file JSON mẫu")
console.print(tips_table)
console.print()
# Phím tắt
console.print("[bold bright_cyan]⌨️ PHÍM TẮT[/bold bright_cyan]")
console.print(" [bright_yellow]Ctrl+C[/bright_yellow] : Dừng và lưu tiến trình")
console.print(" [bright_yellow]Enter[/bright_yellow] : Sử dụng giá trị mặc định")
console.print()
Prompt.ask("\n[bold bright_green]Nhấn Enter để quay lại menu[/bold bright_green]")
def display_menu():
"""Hiển thị menu chính với Rich styling"""
console = Console()
# ASCII Art Logo với gradient màu
logo = Text()
logo_text = r"""
██╗ ██████╗ ██╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ ██████╗ ██████╗ ██████╗ ██████╗ ███████╗
╚██╗ ██╔══██╗██║ ██║██╔═══██╗██║ ██║██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
╚██╗ ██████╔╝███████║██║ ██║███████║██║ ██║██║ ██║ ██║ ██║██║ ██║█████╗
██╔╝ ██╔═══╝ ██╔══██║██║ ██║██╔══██║██║ ██║██║ ██║ ██║ ██║██║ ██║██╔══╝
██╔╝ ██║ ██║ ██║╚██████╔╝██║ ██║╚██████╔╝╚██████╗╚██████╗╚██████╔╝██████╔╝███████╗
╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝
"""
# Tạo gradient từ cyan sang magenta
lines = logo_text.strip().split('\n')
for i, line in enumerate(lines):
# Tạo màu gradient từ cyan -> blue -> magenta
color_progress = i / (len(lines) - 1)
if color_progress < 0.5:
color = f"rgb({int(0 + color_progress * 2 * 100)},{int(255 - color_progress * 2 * 100)},{255})"
else:
progress = (color_progress - 0.5) * 2
color = f"rgb({int(100 + progress * 155)},{int(155 - progress * 155)},{255})"
logo.append(line + "\n", style=color)
console.print(logo)
# Subtitle
subtitle = Text("IMAGE FORMAT CONVERTER BY PHOHOCCODE", style="bold bright_white")
console.print(Panel(subtitle, box=box.DOUBLE, border_style="bright_cyan"))
# Menu với table
table = Table(show_header=False, box=box.ROUNDED, border_style="bright_blue", padding=(0, 2))
table.add_column("Option", style="bright_cyan bold", width=8)
table.add_column("Description", style="bright_white")
table.add_row("1.", "Chuyển đổi từ một URL")
table.add_row("2.", "Chuyển đổi từ file chứa danh sách URL")
table.add_row("3.", "Chuyển đổi từ file JSON")
table.add_row("4.", "Lọc phim chưa tải từ JSON")
table.add_row("5.", "Xóa checkpoint (tiến trình đã lưu)")
table.add_row("6.", "Hướng dẫn sử dụng")
table.add_row("7.", "Thoát", style="bright_red")
console.print(table)
console.print()
def get_output_format(converter: ImageConverter) -> str:
"""Cho người dùng chọn định dạng đầu ra"""
console.print("\n[bold cyan]Chọn định dạng đầu ra:[/bold cyan]")
format_table = Table(show_header=False, box=None, padding=(0, 2))
format_table.add_column("Number", style="bright_cyan")
format_table.add_column("Format", style="bright_white")
for i, fmt in enumerate(converter.SUPPORTED_FORMATS, 1):
format_table.add_row(f"{i}.", fmt)
console.print(format_table)
while True:
try:
choice = Prompt.ask(f"\n[bold]Nhập số (1-{len(converter.SUPPORTED_FORMATS)})[/bold]", default="4")
index = int(choice) - 1
if 0 <= index < len(converter.SUPPORTED_FORMATS):
return converter.SUPPORTED_FORMATS[index]
print_error(f"Vui lòng nhập số từ 1 đến {len(converter.SUPPORTED_FORMATS)}")
except (ValueError, KeyboardInterrupt):
print_error("Lựa chọn không hợp lệ!")
raise
def get_output_directory() -> str:
"""Cho người dùng nhập đường dẫn lưu file"""
console.print("\n[bold cyan]Nhập đường dẫn thư mục lưu ảnh:[/bold cyan]")
console.print("[dim](Nhấn Enter để sử dụng thư mục hiện tại)[/dim]")
while True:
output_dir = Prompt.ask("[bold]Đường dẫn[/bold]", default=".")
try:
# Tạo thư mục nếu chưa tồn tại
os.makedirs(output_dir, exist_ok=True)
abs_path = os.path.abspath(output_dir)
print_success(f"Sẽ lưu vào: [cyan]{abs_path}[/cyan]")
return output_dir
except Exception as e:
print_error(f"Không thể tạo thư mục: {e}")
console.print("[yellow]Vui lòng nhập đường dẫn khác![/yellow]")
def process_single_url(converter: ImageConverter):
"""Xử lý chuyển đổi từ một URL"""
console.print()
url = Prompt.ask("[bold cyan]Nhập URL ảnh[/bold cyan]")
if not url:
print_error("URL không hợp lệ!")
return
# Validate URL format
if not converter.validate_url(url):
console.print()
print_error(f"URL không hợp lệ: {url}")
print_info("URL phải bắt đầu với http:// hoặc https://")
return
output_format = get_output_format(converter)
output_dir = get_output_directory()
custom_name = Prompt.ask("\n[bold cyan]Nhập tên file[/bold cyan] [dim](Enter để tự động)[/dim]", default="")
custom_name = custom_name if custom_name else None
console.print("\n[bold yellow]⏳ Bắt đầu chuyển đổi...[/bold yellow]")
if converter.process_url(url, output_format, output_dir, custom_name):
console.print()
print_success("Chuyển đổi thành công!")
console.print()
else:
console.print()
print_error("Chuyển đổi thất bại!")
console.print()
def process_file_urls(converter: ImageConverter):
"""Xử lý chuyển đổi từ file chứa danh sách URL"""
console.print()
# Kiểm tra checkpoint
resume = False
checkpoint = converter.load_checkpoint()
if checkpoint:
print_info("Phát hiện tiến trình chưa hoàn thành!")
console.print()
checkpoint_table = Table(show_header=False, box=box.SIMPLE, border_style="cyan")
checkpoint_table.add_column("Key", style="cyan")
checkpoint_table.add_column("Value", style="white")
checkpoint_table.add_row("File", checkpoint.get('file_path', 'N/A'))
checkpoint_table.add_row("Đã xử lý", f"{len(checkpoint.get('processed_indices', []))} ảnh")
console.print(checkpoint_table)
if Confirm.ask("\n[bold cyan]Tiếp tục từ tiến trình cũ?[/bold cyan]"):
resume = True
file_path = checkpoint.get('file_path')
output_format = checkpoint.get('output_format')
output_dir = checkpoint.get('output_dir')
else:
converter.clear_checkpoint()
if not resume:
file_path = Prompt.ask("[bold cyan]Nhập đường dẫn file chứa URL[/bold cyan]")
if not file_path:
console.print()
print_error("Đường dẫn file không hợp lệ!")
return
if not os.path.exists(file_path):