-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_cli.py
More file actions
2442 lines (2144 loc) · 91.7 KB
/
Copy pathmain_cli.py
File metadata and controls
2442 lines (2144 loc) · 91.7 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 subprocess
import argparse
import whisper
import datetime
from typing import Optional
import sys
import threading
import time
import torch
import json
from typing import List
import warnings
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import (
Progress,
SpinnerColumn,
BarColumn,
TextColumn,
TimeRemainingColumn,
TimeElapsedColumn,
)
from rich.text import Text
from rich import box
from rich.style import Style
from rich.live import Live
from rich.status import Status
# Initialize Rich console
console = Console()
# Tắt warning về Flash Attention (không ảnh hưởng đến chức năng)
warnings.filterwarnings(
"ignore", message=".*Torch was not compiled with flash attention.*"
)
class UserCancelled(Exception):
pass
def check_cancelled(args=None):
if args is not None:
stop_event = getattr(args, "stop_event", None)
if stop_event is not None and stop_event.is_set():
raise UserCancelled("Người dùng đã dừng tác vụ.")
def check_ffmpeg():
"""Kiểm tra FFmpeg đã cài đặt chưa"""
try:
subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
console.print(
Panel(
"[bold red]LỖI:[/bold red] Không tìm thấy FFmpeg!\n\n"
"[yellow]Vui lòng cài đặt FFmpeg:[/yellow]\n"
" • Windows: https://www.gyan.dev/ffmpeg/builds/\n"
" • Thêm vào PATH hoặc đặt trong thư mục script",
title="[bold red]FFmpeg Not Found[/bold red]",
border_style="red",
)
)
sys.exit(1)
def check_gpu():
"""Kiểm tra GPU và CUDA"""
try:
if torch.cuda.is_available():
gpu_name = torch.cuda.get_device_name(0)
gpu_count = torch.cuda.device_count()
console.print(
f"[bold green]GPU được phát hiện:[/bold green] [cyan]{gpu_name}[/cyan] [yellow](x{gpu_count})[/yellow]"
)
return True
else:
console.print("[yellow]Không tìm thấy GPU, sẽ dùng CPU (chậm hơn)[/yellow]")
return False
except Exception as e:
console.print(f"[yellow]Lỗi kiểm tra GPU:[/yellow] [red]{e}[/red]")
return False
def _get_config_path() -> str:
"""Return path to config file in current directory."""
return ".whisper_m3u8_transcriber_config.json"
def load_recent_paths() -> List[str]:
"""Load recent paths from config file. Returns list (may be empty)."""
cfg = _get_config_path()
try:
if os.path.exists(cfg):
with open(cfg, "r", encoding="utf-8") as f:
data = json.load(f)
paths = data.get("recent_paths", [])
# keep only strings and existing ones are optional
return [p for p in paths if isinstance(p, str)]
except Exception:
pass
return []
def save_recent_paths(paths: List[str]) -> None:
"""Save recent paths list to config file."""
cfg = _get_config_path()
try:
data = {"recent_paths": paths}
with open(cfg, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception:
pass
def _get_checkpoint_path() -> str:
"""Return path to checkpoint file in current directory."""
return ".whisper_m3u8_transcriber_checkpoint.json"
def load_checkpoint() -> dict:
"""Load checkpoint data from file. Returns dict with last_json_path, last_index, etc."""
cfg = _get_checkpoint_path()
try:
if os.path.exists(cfg):
with open(cfg, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return {}
def save_checkpoint(json_path: str, last_index: int, total: int) -> None:
"""Save checkpoint data to file."""
cfg = _get_checkpoint_path()
try:
data = {
"json_path": json_path,
"last_index": last_index,
"total": total,
"timestamp": time.time(),
}
with open(cfg, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception:
pass
def clear_checkpoint() -> None:
"""Clear checkpoint file."""
cfg = _get_checkpoint_path()
try:
if os.path.exists(cfg):
os.remove(cfg)
except Exception:
pass
def add_recent_path(path: str, max_entries: int = 10) -> None:
"""Add a path to recent list (move to front), cap to max_entries."""
try:
path = os.path.abspath(path)
paths = load_recent_paths()
if path in paths:
paths.remove(path)
paths.insert(0, path)
# remove duplicates and cap
seen = []
out = []
for p in paths:
if p not in seen:
seen.append(p)
out.append(p)
if len(out) >= max_entries:
break
save_recent_paths(out)
except Exception:
pass
def validate_url(url: str) -> bool:
"""Kiểm tra URL hợp lệ"""
return url.startswith(("http://", "https://")) and ".m3u8" in url.lower()
def is_cancel_requested(args=None) -> bool:
stop_event = getattr(args, "stop_event", None)
return bool(stop_event is not None and stop_event.is_set())
def terminate_process(process):
if process is None:
return
try:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=3)
except Exception:
process.kill()
except Exception:
pass
def check_cancel(args=None, process=None, temp_path: str | None = None):
if is_cancel_requested(args):
terminate_process(process)
if temp_path and os.path.exists(temp_path):
try:
os.remove(temp_path)
except Exception:
pass
raise UserCancelled("Đã dừng theo yêu cầu người dùng")
def gui_log(args, message: str):
q = getattr(args, "gui_queue", None)
if q is not None:
q.put(("log", message))
def gui_progress(args, value: float):
q = getattr(args, "gui_queue", None)
if q is not None:
q.put(("progress", max(0.0, min(1.0, float(value)))))
def download_from_m3u8(
m3u8_url: str,
output_path: str = "video.mp4",
args=None,
progress_start: float = 0.05,
progress_end: float = 0.40,
) -> str:
console.print("\n[bold cyan]Đang tải video từ m3u8...[/bold cyan]")
gui_log(args, "Đang tải video từ m3u8...")
gui_progress(args, progress_start)
last_gui_log = 0
try:
cmd = [
"ffmpeg",
"-y",
"-i",
m3u8_url,
"-c",
"copy",
"-progress",
"pipe:1",
output_path,
]
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if args is not None:
setattr(args, "_active_process", process)
last_time = 0
duration = 0
duration_found = False
# Thread để đọc stderr và tìm duration
def read_stderr():
nonlocal duration, duration_found
try:
for line in process.stderr:
if args is not None:
stop_event = getattr(args, "stop_event", None)
if stop_event is not None and stop_event.is_set():
if process.poll() is None:
process.terminate()
break
if "Duration:" in line and not duration_found:
try:
time_str = line.split("Duration:")[1].split(",")[0].strip()
h, m, s = time_str.split(":")
duration = int(h) * 3600 + int(m) * 60 + float(s)
duration_found = True
except:
pass
except:
pass
stderr_thread = threading.Thread(target=read_stderr, daemon=True)
stderr_thread.start()
# Sử dụng Rich Progress - đọc stdout TRONG LÚC process chạy
with Progress(
SpinnerColumn(),
TextColumn("[bold blue]{task.description}"),
BarColumn(complete_style="cyan", finished_style="green"),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
TimeElapsedColumn(),
console=console,
) as progress:
task = progress.add_task("Đang tải video...", total=100)
try:
while True:
# Check stop event
if args is not None:
stop_event = getattr(args, "stop_event", None)
if stop_event is not None and stop_event.is_set():
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=3)
except Exception:
process.kill()
raise UserCancelled("Người dùng đã dừng tác vụ.")
line = process.stdout.readline()
if not line:
break
line = line.strip()
if line.startswith("out_time_ms="):
try:
time_ms = int(line.split("=")[1])
current_time = time_ms / 1_000_000
if current_time > last_time:
last_time = current_time
if duration_found and duration > 0:
percent = min((current_time / duration) * 100, 100)
progress.update(
task,
completed=percent,
description=f"Đang tải video ({int(current_time)}s / {int(duration)}s)",
)
gui_value = progress_start + (
progress_end - progress_start
) * (percent / 100)
gui_progress(args, gui_value)
now = time.time()
if now - last_gui_log >= 2:
gui_log(
args,
f"Đang tải video: {percent:.1f}% ({int(current_time)}s / {int(duration)}s)",
)
last_gui_log = now
elif duration_found:
progress.update(
task,
description=f"Đã phát hiện video ({int(duration)}s)",
)
except:
pass
except KeyboardInterrupt:
progress.stop()
raise
finally:
if args is not None:
args._active_process = None
return_code = process.wait()
stderr_thread.join(timeout=1)
if return_code != 0:
stderr_output = process.stderr.read() if process.stderr else ""
raise subprocess.CalledProcessError(return_code, cmd, stderr=stderr_output)
console.print(f"[bold green]✓ Tải video thành công[/bold green]")
gui_log(args, "✓ Tải video thành công")
gui_progress(args, progress_end)
return output_path
except KeyboardInterrupt:
console.print("\n[yellow]Đã hủy tiến trình tải video[/yellow]")
if os.path.exists(output_path):
try:
os.remove(output_path)
console.print("[dim]Đã xóa file tạm[/dim]")
except:
pass
sys.exit(0)
except subprocess.CalledProcessError as e:
console.print(
Panel(
f"[bold red]LỖI:[/bold red] Không thể tải video từ URL\n"
f"[dim]{m3u8_url}[/dim]\n\n"
f"[yellow]Gợi ý:[/yellow] Kiểm tra URL m3u8 và kết nối internet"
+ (
f"\n\n[red]Chi tiết:[/red] {str(e.stderr)[:200]}"
if hasattr(e, "stderr") and e.stderr
else ""
),
title="[bold red]Download Error[/bold red]",
border_style="red",
)
)
sys.exit(1)
except Exception as e:
console.print(f"\n[bold red]LỖI:[/bold red] [red]{str(e)}[/red]")
sys.exit(1)
def extract_audio(
video_path: str,
audio_path: str = "audio.wav",
args=None,
progress_start: float = 0.40,
progress_end: float = 0.55,
) -> str:
console.print("\n[bold magenta]Đang tách audio...[/bold magenta]")
gui_log(args, "Đang tách audio...")
gui_progress(args, progress_start)
last_gui_log = 0
try:
# Get duration từ ffprobe (chính xác và nhanh hơn)
probe_cmd = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
video_path,
]
duration = 0
try:
probe_result = subprocess.run(
probe_cmd, capture_output=True, text=True, timeout=5
)
if probe_result.returncode == 0 and probe_result.stdout.strip():
duration = float(probe_result.stdout.strip())
else:
# Fallback: dùng ffmpeg -i
probe_cmd_fallback = ["ffmpeg", "-i", video_path, "-f", "null", "-"]
probe_result = subprocess.run(
probe_cmd_fallback, capture_output=True, text=True, timeout=5
)
output = probe_result.stderr if probe_result.stderr else ""
for line in output.split("\n"):
if "Duration:" in line:
time_str = line.split("Duration:")[1].split(",")[0].strip()
h, m, s = time_str.split(":")
duration = int(h) * 3600 + int(m) * 60 + float(s)
break
except subprocess.TimeoutExpired:
console.print(
" [yellow]Không thể lấy duration, sẽ hiển thị tiến độ ước lượng[/yellow]"
)
duration = 0
except Exception as e:
console.print(f" [dim]Probe error: {e}[/dim]")
duration = 0
# Extract audio with progress
cmd = [
"ffmpeg",
"-y",
"-i",
video_path,
"-vn",
"-acodec",
"pcm_s16le",
"-ar",
"16000",
"-ac",
"1",
"-progress",
"pipe:1",
audio_path,
]
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1
)
last_time = 0
# Sử dụng Rich Progress (giống download video)
with Progress(
SpinnerColumn(),
TextColumn("[bold magenta]{task.description}"),
BarColumn(complete_style="magenta", finished_style="green"),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
TimeElapsedColumn(),
console=console,
) as progress:
if duration > 0:
task = progress.add_task(
f"Đang tách audio (0s / {int(duration)}s)", total=100
)
else:
task = progress.add_task("Đang tách audio...", total=100)
try:
while True:
check_cancel(args, process, audio_path)
line = process.stdout.readline()
if not line:
break
line = line.strip()
if line.startswith("out_time_ms="):
try:
time_ms = int(line.split("=")[1])
current_time = time_ms / 1_000_000
if current_time > last_time:
last_time = current_time
if duration > 0:
percent = min((current_time / duration) * 100, 100)
progress.update(
task,
completed=percent,
description=f"Đang tách audio ({int(current_time)}s / {int(duration)}s)",
)
gui_value = progress_start + (
progress_end - progress_start
) * (percent / 100)
gui_progress(args, gui_value)
now = time.time()
if now - last_gui_log >= 2:
gui_log(
args,
f"Đang tách audio: {percent:.1f}% ({int(current_time)}s / {int(duration)}s)",
)
last_gui_log = now
else:
progress.update(
task,
description=f"Đang tách audio ({int(current_time)}s)",
)
except:
pass
except UserCancelled:
console.print(
"\n[yellow]Đã dừng tách audio theo yêu cầu người dùng[/yellow]"
)
raise
except KeyboardInterrupt:
progress.stop()
raise
return_code = process.wait(timeout=300)
if return_code != 0:
try:
stderr = process.stderr.read()
except:
stderr = ""
raise subprocess.CalledProcessError(return_code, cmd, stderr=stderr)
console.print(f"[bold green]✓ Tách audio thành công[/bold green]")
gui_log(args, "✓ Tách audio thành công")
gui_progress(args, progress_end)
return audio_path
except KeyboardInterrupt:
console.print("\n[yellow]Đã hủy tiến trình tách audio[/yellow]")
if os.path.exists(audio_path):
try:
os.remove(audio_path)
console.print("[dim]Đã xóa file tạm[/dim]")
except:
pass
sys.exit(0)
except subprocess.TimeoutExpired:
console.print(
Panel(
"[bold red]LỖI:[/bold red] Timeout khi tách audio (quá 5 phút)",
title="[bold red]Timeout Error[/bold red]",
border_style="red",
)
)
sys.exit(1)
except subprocess.CalledProcessError as e:
console.print(
Panel(
"[bold red]LỖI:[/bold red] Không thể tách audio từ video\n\n"
"[yellow]Gợi ý:[/yellow] Kiểm tra file video có lỗi không",
title="[bold red]Audio Extraction Error[/bold red]",
border_style="red",
)
)
sys.exit(1)
except Exception as e:
console.print(f"\n[bold red]LỖI:[/bold red] [red]{str(e)}[/red]")
sys.exit(1)
def _format_timestamp(seconds: float) -> str:
hrs = int(seconds // 3600)
mins = int((seconds % 3600) // 60)
secs = seconds % 60
return f"{hrs:02d}:{mins:02d}:{secs:06.3f}"
def result_to_vtt(result: dict) -> str:
if isinstance(result.get("vtt"), str):
return result["vtt"]
segments = result.get("segments") or []
lines = ["WEBVTT", ""]
for seg in segments:
start = _format_timestamp(seg.get("start", 0.0))
end = _format_timestamp(seg.get("end", 0.0))
text = seg.get("text", "").strip()
lines.append(f"{start} --> {end}")
lines.append(text)
lines.append("")
return "\n".join(lines)
def display_usage():
"""Hiển thị hướng dẫn sử dụng chi tiết"""
console.print("\n")
# Tiêu đề hướng dẫn
title = Text("HƯỚNG DẪN SỬ DỤNG", style="bold cyan")
console.print(Panel(title, box=box.DOUBLE, border_style="cyan", padding=(0, 2)))
console.print()
# Phần 1: Giới thiệu
console.print(
Panel(
"[bold yellow]Whisper M3U8 Transcriber[/bold yellow]\n\n"
"Công cụ tải video từ URL m3u8, tách âm thanh và nhận dạng giọng nói bằng OpenAI Whisper.\n"
"Hỗ trợ 2 chế độ xử lý: Direct (1 video) và Batch (nhiều video từ JSON).",
title="[bold]Giới thiệu[/bold]",
border_style="green",
)
)
console.print()
# Phần 2: Các chế độ xử lý
modes_table = Table(box=box.ROUNDED, show_header=True, border_style="blue")
modes_table.add_column("Chế độ", style="cyan bold", width=20)
modes_table.add_column("Mô tả", style="white", width=50)
modes_table.add_row(
"Direct Mode",
"• Nhập link m3u8 trực tiếp\n• Xử lý một video đơn lẻ\n• Menu tương tác từng bước",
)
modes_table.add_row(
"Batch Mode",
"• Xử lý nhiều video từ file JSON\n• Hỗ trợ checkpoint tự động\n• Tiếp tục khi bị gián đoạn",
)
console.print(
Panel(modes_table, title="[bold]Các chế độ xử lý[/bold]", border_style="blue")
)
console.print()
# Phần 3: Hướng dẫn nhanh
console.print(
Panel(
"[bold cyan]Chạy đơn giản:[/bold cyan]\n"
" [yellow]python main.py[/yellow]\n\n"
"[bold cyan]Direct Mode:[/bold cyan]\n"
" 1. Chọn chế độ [green]1[/green]\n"
" 2. Nhập URL m3u8 hoặc đường dẫn file\n"
" 3. Chọn thư mục lưu trữ\n"
" 4. Chọn file cần lưu (Video/Audio/VTT/Thumbnails)\n"
" 5. Chọn ngôn ngữ nhận dạng\n\n"
"[bold cyan]Batch Mode:[/bold cyan]\n"
" 1. Chọn chế độ [green]2[/green]\n"
" 2. Nhập đường dẫn file JSON\n"
" 3. Hệ thống tự động xử lý từng item",
title="[bold]Hướng dẫn nhanh[/bold]",
border_style="magenta",
)
)
console.print()
# Phần 4: Cấu trúc file JSON
console.print(
Panel(
"[bold cyan]Ví dụ file JSON:[/bold cyan]\n\n"
"[yellow]{\n"
' "root_path": "E:\\\\Videos\\\\Subtitles",\n'
' "items": [\n'
" {\n"
' "slug": "video-001",\n'
' "m3u8_url": "https://example.com/stream.m3u8",\n'
' "folder_name": "video-phần-1"\n'
" }\n"
" ]\n"
"}[/yellow]\n\n"
"[dim]• root_path: Thư mục gốc\n"
"• slug: Tên thư mục con\n"
"• m3u8_url: URL video m3u8\n"
"• folder_name: Tên nhóm file[/dim]",
title="[bold]Cấu trúc file JSON (Batch Mode)[/bold]",
border_style="yellow",
)
)
console.print()
# Phần 5: Tính năng nổi bật
features_table = Table(box=box.SIMPLE, show_header=False, border_style="green")
features_table.add_column("Feature", style="white", width=70)
features_table.add_row(
"[bold]Checkpoint System:[/bold] Tự động lưu tiến trình, tiếp tục khi gián đoạn"
)
features_table.add_row(
"[bold]Sprite Sheet Thumbnails:[/bold] Tạo ảnh thumbnails và VTT với tọa độ"
)
features_table.add_row(
"[bold]Hỗ trợ đa ngôn ngữ:[/bold] 99+ ngôn ngữ qua Whisper AI"
)
features_table.add_row(
"[bold]Lựa chọn file lưu:[/bold] Chọn Video/Audio/VTT/Thumbnails"
)
features_table.add_row(
"[bold]GPU Support:[/bold] Tự động phát hiện và sử dụng CUDA nếu có"
)
features_table.add_row(
"[bold]Rich Console:[/bold] Progress bars, tables, panels đẹp mắt"
)
console.print(
Panel(
features_table, title="[bold]Tính năng nổi bật[/bold]", border_style="green"
)
)
console.print()
# Phần 6: Yêu cầu hệ thống
console.print(
Panel(
"[bold cyan]Phần mềm cần thiết:[/bold cyan]\n"
" • Python 3.8+\n"
" • FFmpeg (xử lý video/audio)\n\n"
"[bold cyan]Thư viện Python:[/bold cyan]\n"
" [yellow]pip install openai-whisper rich[/yellow]\n\n"
"[bold cyan]GPU (tùy chọn, tăng tốc):[/bold cyan]\n"
" [yellow]pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118[/yellow]",
title="[bold]Yêu cầu hệ thống[/bold]",
border_style="red",
)
)
console.print()
console.print("[bold green]Chi tiết xem thêm trong README.md[/bold green]\n")
console.input("[dim]Nhấn Enter để quay lại menu chính...[/dim]")
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("WHISPER M3U8 TRANSCRIBER BY PHOHOCCODE", style="bold bright_white")
console.print(Panel(subtitle, box=box.DOUBLE, border_style="bright_cyan"))
console.print()
def transcribe_audio(
audio_path: str,
model_name: str = "small",
lang: Optional[str] = None,
task: str = "transcribe",
use_gpu: bool = True,
) -> dict:
console.print("\n[bold blue]Đang nhận dạng giọng nói bằng Whisper...[/bold blue]")
try:
# Xác định device
device = "cuda" if use_gpu and torch.cuda.is_available() else "cpu"
device_color = "green" if device == "cuda" else "yellow"
console.print(
f" [bold]Dùng:[/bold] [{device_color}]{device.upper()}[/{device_color}]"
)
# Load model với device
model = whisper.load_model(model_name, device=device)
# Cấu hình transcribe với các tham số tối ưu chống lặp
kwargs = {
"task": task,
"verbose": True,
"fp16": device == "cuda", # Sử dụng FP16 nếu có GPU
"condition_on_previous_text": False, # Tắt để tránh lặp lại context
"temperature": (
0.0,
0.2,
0.4,
0.6,
0.8,
1.0,
), # Fallback temperatures để giảm lặp
"compression_ratio_threshold": 2.4, # Phát hiện lỗi tốt hơn
"logprob_threshold": -1.0, # Lọc kết quả không chắc chắn
"no_speech_threshold": 0.6, # Tăng ngưỡng để lọc nhạc/noise
"best_of": 5, # Lấy kết quả tốt nhất trong 5 lần decode (giảm lặp)
"initial_prompt": None, # Không dùng prompt để tránh bias sang ngôn ngữ khác
}
# Nếu chỉ định ngôn ngữ, bắt buộc sử dụng ngôn ngữ đó
if lang:
kwargs["language"] = lang
# Thêm prompt để ép Whisper chỉ dịch ngôn ngữ được chọn
if lang == "zh":
kwargs["initial_prompt"] = "以下是普通话的句子。" # Prompt tiếng Trung
elif lang == "vi":
kwargs["initial_prompt"] = "Đây là câu tiếng Việt."
elif lang == "en":
kwargs["initial_prompt"] = "The following is in English."
elif lang == "ja":
kwargs["initial_prompt"] = "以下は日本語の文章です。"
elif lang == "ko":
kwargs["initial_prompt"] = "다음은 한국어 문장입니다."
console.print(
f" [cyan]Ngôn ngữ:[/cyan] [yellow]{lang}[/yellow] [dim](chỉ nhận dạng ngôn ngữ này)[/dim]"
)
else:
kwargs["initial_prompt"] = None # Auto-detect không dùng prompt
console.print(f" [yellow]Tự động nhận diện ngôn ngữ[/yellow]")
result = model.transcribe(audio_path, **kwargs)
# Kiểm tra nếu kết quả có vấn đề
if result.get("language") == "music" or not result.get("text", "").strip():
console.print(
"\n[yellow]Cảnh báo: Whisper phát hiện chủ yếu là nhạc/noise![/yellow]"
)
if lang is None:
console.print(
" [yellow]💡 Gợi ý: Hãy chỉ định rõ ngôn ngữ để cải thiện kết quả[/yellow]"
)
else:
console.print(
f"\n[bold green]✓ Nhận dạng hoàn tất[/bold green] [dim]({len(result.get('segments', []))} đoạn)[/dim]"
)
return result
except KeyboardInterrupt:
console.print("\n[yellow]Đã hủy tiến trình nhận dạng giọng nói[/yellow]")
sys.exit(0)
except Exception as e:
console.print(
Panel(
f"[bold red]LỖI:[/bold red] Không thể nhận dạng giọng nói\n\n"
f"[red]Chi tiết:[/red] {e}",
title="[bold red]Transcription Error[/bold red]",
border_style="red",
)
)
sys.exit(1)
def save_subtitles(result: dict, output_vtt: str = "subtitle.vtt") -> None:
with console.status("[bold yellow]Đang lưu phụ đề...", spinner="dots"):
vtt_text = result_to_vtt(result)
with open(output_vtt, "w", encoding="utf-8") as f:
f.write(vtt_text)
console.print(
f"[bold green]✓ Đã lưu phụ đề:[/bold green] [cyan]{output_vtt}[/cyan]"
)
def extract_thumbnails(
video_path: str,
output_dir: str,
interval: int = 5,
thumb_width: int = 160,
thumb_height: int = 90,
cols: int = 10,
image_format: str = "webp",
) -> dict:
"""
Tạo sprite sheet từ video - tất cả thumbnails trong 1 ảnh duy nhất
Args:
video_path: Đường dẫn đến file video
output_dir: Thư mục lưu sprite sheet
interval: Khoảng thời gian giữa các thumbnail (giây)
thumb_width: Chiều rộng mỗi thumbnail
thumb_height: Chiều cao mỗi thumbnail
cols: Số cột trong sprite sheet
image_format: Định dạng ảnh ('webp' hoặc 'jpg')
Returns:
Dict chứa thông tin sprite sheet và timestamps
"""
console.print(
f"\n[bold cyan]Đang tạo sprite sheet[/bold cyan] [dim](mỗi {interval}s, định dạng: {image_format.upper()})[/dim]"
)
# Tạo thư mục thumbnails
thumb_dir = os.path.join(output_dir, "thumbnails")
os.makedirs(thumb_dir, exist_ok=True)
# Khởi tạo biến cleanup sớm để tránh lỗi UnboundLocalError khi KeyboardInterrupt
temp_thumbs = []
temp_dir = os.path.join(thumb_dir, "temp")
try:
# Lấy độ dài video
probe_cmd = ["ffmpeg", "-i", video_path, "-f", "null", "-"]
result = subprocess.run(probe_cmd, capture_output=True, text=True)
# Parse duration từ stderr
duration = 0
output = result.stderr if result.stderr else ""
for line in output.split("\n"):
if "Duration:" in line:
time_str = line.split("Duration:")[1].split(",")[0].strip()
h, m, s = time_str.split(":")
duration = int(h) * 3600 + int(m) * 60 + float(s)
break
if duration == 0:
console.print("[yellow]Không thể xác định độ dài video[/yellow]")
return {}
console.print(f"[green]Độ dài video:[/green] [yellow]{int(duration)}s[/yellow]")
# Tính số thumbnails cần tạo
timestamps = list(range(0, int(duration), interval))
thumb_count = len(timestamps)
if thumb_count == 0:
console.print("[yellow]Không có thumbnail nào để tạo[/yellow]")
return {}
console.print(f"[green]Số thumbnails:[/green] [yellow]{thumb_count}[/yellow]")
# Tạo thư mục temp cho các thumbnail riêng lẻ
os.makedirs(temp_dir, exist_ok=True)
# Sử dụng Rich Progress
with Progress(
SpinnerColumn(),
TextColumn("[bold cyan]{task.description}"),
BarColumn(complete_style="cyan", finished_style="green"),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
TextColumn("({task.completed}/{task.total})"),
TimeElapsedColumn(),
console=console,
) as progress:
task = progress.add_task(
f"Tạo thumbnails (mỗi {interval}s)", total=thumb_count
)
for i, timestamp in enumerate(timestamps):
thumb_filename = f"thumb{i:04d}.jpg"
thumb_path = os.path.join(temp_dir, thumb_filename)
cmd = [
"ffmpeg",
"-y",
"-ss",
str(timestamp),
"-i",
video_path,
"-vframes",
"1",
"-vf",
f"scale={thumb_width}:{thumb_height}",
"-q:v",