-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtvs.py
More file actions
executable file
·1584 lines (1286 loc) · 52.2 KB
/
tvs.py
File metadata and controls
executable file
·1584 lines (1286 loc) · 52.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3.13
"""
TVS - Text-Video-Summarizer
A standalone tool for downloading, transcribing, and summarizing videos.
Usage:
python3.13 tvs.py -u <URL>
python3.13 tvs.py --url <URL>
Example:
python3.13 tvs.py -u https://youtube.com/watch?v=dQw4w9WgXcQ
"""
import argparse
import subprocess
import sys
import os
import time
import logging
from pathlib import Path
from datetime import datetime
# ============================================================================
# CONFIGURATION
# ============================================================================
# Get the directory where this script is located
SCRIPT_DIR = Path(__file__).parent.resolve()
# Directories (VIDEOS_DIR and LOG_DIR relative to script, WORK_DIR can be overridden)
VIDEOS_DIR = SCRIPT_DIR / "videos"
WORK_DIR = SCRIPT_DIR / "transcripts"
LOG_DIR = SCRIPT_DIR / "logs"
def set_work_dir(output_path):
"""Set custom work directory for transcripts and summaries."""
global WORK_DIR
WORK_DIR = Path(output_path).resolve()
# MLX-Whisper transcription configuration
MLX_WHISPER_DIR = Path("/Users/khaled/cc-project/insanely-fast-whisper")
MLX_WHISPER_BIN = MLX_WHISPER_DIR / ".venv" / "bin" / "mlx_whisper"
MLX_WHISPER_MODEL = "mlx-community/distil-whisper-large-v3"
# Cookies directory structure (organized by site)
COOKIES_DIR = SCRIPT_DIR / "cookies"
SITE_COOKIES = {
"instagram": COOKIES_DIR / "instagram" / "www.instagram.com_cookies.txt",
"threads": COOKIES_DIR / "threads" / "www.threads.net_cookies.txt",
"tiktok": COOKIES_DIR / "tiktok" / "www.tiktok.com_cookies.txt",
"x": COOKIES_DIR / "x" / "x.com_cookies.txt",
"youtube": COOKIES_DIR / "youtube" / "www.youtube.com_cookies.txt",
}
# Cookie expiration warning threshold (days)
COOKIE_WARNING_DAYS = 30
# Colors for terminal output (opencode-style)
class Colors:
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
GRAY = "\033[90m"
BOLD = "\033[1m"
DIM = "\033[2m"
UNDERLINE = "\033[4m"
RESET = "\033[0m"
SUCCESS = GREEN
WARNING = YELLOW
ERROR = RED
INFO = CYAN
HEADER = MAGENTA
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
def setup_logging():
"""
Set up dual logging system:
1. Debug log - Complete tool execution (all operations, errors, debug info)
2. Processed files log - Clean history of successfully processed files
"""
# Create logs directory
LOG_DIR.mkdir(parents=True, exist_ok=True)
# Create work directory for transcripts and summaries
WORK_DIR.mkdir(parents=True, exist_ok=True)
# Generate log filenames with format: debug-DD-M-YYYY.log and processed-DD-M-YYYY.log
now = datetime.now()
date_suffix = f"{now.day}-{now.month}-{now.year}"
debug_log_file = LOG_DIR / f"debug-{date_suffix}.log"
processed_log_file = LOG_DIR / f"processed-{date_suffix}.log"
# Clear any existing handlers
logger = logging.getLogger()
logger.handlers.clear()
logger.setLevel(logging.DEBUG)
# 1. DEBUG LOG - Verbose logging of all operations
debug_handler = logging.FileHandler(debug_log_file, mode="a", encoding="utf-8")
debug_handler.setLevel(logging.DEBUG)
debug_formatter = logging.Formatter(
"%(asctime)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
)
debug_handler.setFormatter(debug_formatter)
logger.addHandler(debug_handler)
# 2. PROCESSED FILES LOG - Clean summary handler (only for file processing results)
# We'll use this separately via a custom logger
processed_handler = logging.FileHandler(
processed_log_file, mode="a", encoding="utf-8"
)
processed_handler.setLevel(logging.INFO)
processed_formatter = logging.Formatter(
"%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
)
processed_handler.setFormatter(processed_formatter)
# Create separate logger for processed files
processed_logger = logging.getLogger("processed")
processed_logger.handlers.clear()
processed_logger.setLevel(logging.INFO)
processed_logger.addHandler(processed_handler)
processed_logger.propagate = False # Don't propagate to root logger
# Log session start in both logs
logging.info("=" * 60)
logging.info("TVS SESSION STARTED")
logging.info("=" * 60)
processed_logger.info("=" * 60)
processed_logger.info("SESSION START")
processed_logger.info("=" * 60)
return debug_log_file, processed_log_file
def detect_site(url):
"""
Detect which site a URL is from.
Args:
url: Video URL
Returns:
str: Site name ('instagram', 'youtube', 'tiktok', 'threads', 'x', or 'other')
"""
url_lower = url.lower()
if "instagram.com" in url_lower:
return "instagram"
elif "threads.net" in url_lower or "threads.com" in url_lower:
return "threads"
elif "tiktok.com" in url_lower:
return "tiktok"
elif "x.com" in url_lower or "twitter.com" in url_lower:
return "x"
elif "youtube.com" in url_lower or "youtu.be" in url_lower:
return "youtube"
else:
return "other"
def get_site_output_dir(site):
"""
Get the output directory for a specific site.
Args:
site: Site name
Returns:
Path: Site-specific subdirectory in VIDEOS_DIR
"""
site_dir = VIDEOS_DIR / site
site_dir.mkdir(parents=True, exist_ok=True)
return site_dir
def check_cookie_age(cookie_file):
"""
Check if cookie file is older than warning threshold.
Args:
cookie_file: Path to cookie file
Returns:
tuple: (age_in_days, is_expired_warning)
"""
if not cookie_file.exists():
return None, False
file_time = cookie_file.stat().st_mtime
age_seconds = time.time() - file_time
age_days = age_seconds / (24 * 3600)
is_old = age_days >= COOKIE_WARNING_DAYS
return int(age_days), is_old
def print_header(text):
"""Print colored header."""
print(f"\n{Colors.HEADER}{Colors.BOLD}{'=' * 60}{Colors.RESET}")
print(f"{Colors.HEADER}{Colors.BOLD}{text}{Colors.RESET}")
print(f"{Colors.HEADER}{Colors.BOLD}{'=' * 60}{Colors.RESET}\n", flush=True)
def print_step(step_num, text):
"""Print step number and description."""
print(
f"{Colors.BLUE}{Colors.BOLD}[Step {step_num}]{Colors.RESET} {text}", flush=True
)
def print_success(text):
"""Print success message."""
print(f"{Colors.SUCCESS}[+]{Colors.RESET} {text}", flush=True)
def print_error(text):
"""Print error message."""
print(f"{Colors.ERROR}[-]{Colors.RESET} {text}", flush=True)
def print_warning(text):
"""Print warning message."""
print(f"{Colors.WARNING}[!]{Colors.RESET} {text}", flush=True)
def print_info(text):
"""Print info message."""
print(f"{Colors.INFO}[*]{Colors.RESET} {text}", flush=True)
def print_color_demo():
"""Print a demo of all available colors."""
print(f"\n{Colors.BOLD}{'=' * 60}{Colors.RESET}")
print(f"{Colors.HEADER}{Colors.BOLD} TVS Color Demo{Colors.RESET}")
print(f"{Colors.BOLD}{'=' * 60}{Colors.RESET}\n")
print(f"{Colors.SUCCESS}[+]{Colors.RESET} Success - Successful operations")
print(f"{Colors.WARNING}[!]{Colors.RESET} Warning - Warnings and cautions")
print(f"{Colors.ERROR}[-]{Colors.RESET} Error - Errors and failures")
print(f"{Colors.INFO}[*]{Colors.RESET} Info - Information messages")
print(f"{Colors.BLUE}[Step]{Colors.RESET} Step - Step indicators")
print(f"{Colors.HEADER}[Header]{Colors.RESET} Header - Section headers")
print(f"{Colors.GRAY}[Dim]{Colors.RESET} Dim - Muted text")
print(f"{Colors.BOLD}Bold{Colors.RESET} - Emphasis")
print(f"{Colors.UNDERLINE}Underline{Colors.RESET} - Links/references")
print(f"{Colors.DIM}Dimmed{Colors.RESET} - Secondary text")
print(f"\n{Colors.BOLD}Standard Colors:{Colors.RESET}")
print(
f"{Colors.RED}Red{Colors.RESET} {Colors.GREEN}Green{Colors.RESET} {Colors.YELLOW}Yellow{Colors.RESET} {Colors.BLUE}Blue{Colors.RESET} {Colors.MAGENTA}Magenta{Colors.RESET} {Colors.CYAN}Cyan{Colors.RESET} {Colors.WHITE}White{Colors.RESET} {Colors.GRAY}Gray{Colors.RESET}"
)
print()
def run_command(cmd, cwd=None, timeout=600, shell=False, log_output=True):
"""
Run shell command and return output.
Args:
cmd: Command to run (list or string)
cwd: Working directory
timeout: Timeout in seconds (default: 600)
shell: Run as shell command
log_output: Log command output to debug log
Returns:
tuple: (success: bool, stdout: str, stderr: str)
"""
cmd_display = cmd if isinstance(cmd, str) else " ".join(cmd)
logging.debug(f"[CMD] Running: {cmd_display}")
start_time = time.time()
try:
result = subprocess.run(
cmd,
cwd=cwd,
capture_output=True,
text=True,
timeout=timeout,
shell=shell,
)
elapsed = time.time() - start_time
success = result.returncode == 0
if log_output:
logging.debug(
f"[CMD] Return code: {result.returncode} (elapsed: {elapsed:.1f}s)"
)
if result.stdout:
logging.debug(f"[CMD] stdout: {result.stdout[:1000]}")
if result.stderr:
logging.debug(f"[CMD] stderr: {result.stderr[:1000]}")
if not success:
logging.error(f"[CMD] FAILED: {cmd_display}")
if result.stdout:
logging.error(f"[CMD] Full stdout: {result.stdout}")
if result.stderr:
logging.error(f"[CMD] Full stderr: {result.stderr}")
return success, result.stdout, result.stderr
except subprocess.TimeoutExpired as e:
logging.error(f"[CMD] TIMEOUT after {timeout}s: {cmd_display}")
return False, "", f"Command timed out after {timeout}s"
except Exception as e:
logging.error(f"[CMD] EXCEPTION: {e}")
return False, "", str(e)
# ============================================================================
# VALIDATION FUNCTIONS
# ============================================================================
def validate_environment():
"""Validate that all required tools and paths exist."""
print_step(0, "Validating environment...")
logging.info("Starting environment validation")
errors = []
# Check yt-dlp
logging.debug("Checking for yt-dlp...")
success, _, _ = run_command(["yt-dlp", "--version"])
if not success:
errors.append("yt-dlp not found. Install with: brew install yt-dlp")
logging.error("yt-dlp not found")
else:
print_success("yt-dlp found")
logging.info("yt-dlp found")
# Check ffmpeg (needed for audio conversion)
logging.debug("Checking for ffmpeg...")
success, _, _ = run_command(["ffmpeg", "-version"])
if not success:
errors.append("ffmpeg not found. Install with: brew install ffmpeg")
logging.error("ffmpeg not found")
else:
print_success("ffmpeg found")
logging.info("ffmpeg found")
# Check mlx-whisper
logging.debug("Checking for mlx-whisper...")
if not MLX_WHISPER_BIN.exists():
errors.append(f"mlx-whisper not found at: {MLX_WHISPER_BIN}")
errors.append(
"Install it in the insanely-fast-whisper repo with: pip install mlx-whisper"
)
logging.error(f"mlx-whisper not found at {MLX_WHISPER_BIN}")
else:
print_success(f"mlx-whisper found ({MLX_WHISPER_BIN})")
logging.info(f"mlx-whisper found at {MLX_WHISPER_BIN}")
# Check mediainfo (optional but recommended)
logging.debug("Checking for mediainfo...")
success, _, _ = run_command(["mediainfo", "--version"])
if not success:
print_warning(
"mediainfo not found (optional). Install with: brew install mediainfo"
)
print_info(
"Without mediainfo, timeout estimation for long videos may be inaccurate"
)
logging.warning("mediainfo not found (optional)")
else:
print_success("mediainfo found")
logging.info("mediainfo found")
# Check directories
logging.debug(f"Creating directories: {VIDEOS_DIR}, {WORK_DIR}")
VIDEOS_DIR.mkdir(parents=True, exist_ok=True)
print_success(f"Videos directory: {VIDEOS_DIR}")
logging.info(f"Videos directory: {VIDEOS_DIR}")
WORK_DIR.mkdir(parents=True, exist_ok=True)
print_success(f"Work directory: {WORK_DIR}")
logging.info(f"Work directory: {WORK_DIR}")
if errors:
print_error("Environment validation failed:")
for error in errors:
print(f" • {error}")
logging.error(f"Validation error: {error}")
logging.error("Environment validation FAILED")
return False
print_success("Environment validation passed")
logging.info("Environment validation PASSED")
return True
# ============================================================================
# MAIN PROCESSING FUNCTIONS
# ============================================================================
def download_video(url, audio_only=False):
"""
Download video from URL using yt-dlp.
Args:
url: Video URL
audio_only: If True, download only audio (much smaller)
Returns:
tuple: (Path to video file or None, bool indicating if already existed, site name)
"""
logging.info(f"[DOWNLOAD] Starting download - URL: {url}, audio_only: {audio_only}")
if audio_only:
print_step(1, "Downloading audio only...")
print_info("Mode: Audio-only (faster, smaller file)")
else:
print_step(1, "Downloading video...")
print_info(f"URL: {url}")
# Detect site and get site-specific directory
site = detect_site(url)
print_info(f"Detected site: {site}")
logging.debug(f"[DOWNLOAD] Detected site: {site}")
site_dir = get_site_output_dir(site)
print_info(f"Output directory: {site_dir}")
# Get list of video/audio files before download
video_extensions = {
".mp4",
".webm",
".mkv",
".avi",
".mov",
".flv",
".wmv",
".m4v",
".m4a",
".opus",
}
videos_before = {
f.name for f in site_dir.glob("*") if f.suffix.lower() in video_extensions
}
# Determine filename pattern based on platform
# Instagram/Threads/TikTok: use ID + description (if available)
# YouTube: use title (more descriptive)
if site in ["instagram", "threads", "tiktok"]:
# Try to get description/caption, fall back to ID
filename_pattern = "%(id)s.%(ext)s"
else:
filename_pattern = "%(title)s.%(ext)s"
# Check for site-specific cookies file
use_cookies = False
cookie_file = SITE_COOKIES.get(site)
if cookie_file and cookie_file.exists():
use_cookies = True
print_info(f"Using {site} cookies for authentication")
# Check cookie age and warn if old
age_days, is_old = check_cookie_age(cookie_file)
if is_old:
print_warning(
f"Cookie file is {age_days} days old (threshold: {COOKIE_WARNING_DAYS} days)"
)
print_warning(
f"[WARN] {Colors.ERROR}COOKIES MAY HAVE EXPIRED - CONSIDER UPDATING{Colors.ENDC}"
)
print_info(f"Cookie location: {cookie_file}")
else:
print_info(f"Cookie age: {age_days} days (OK)")
if audio_only:
# Download only audio (much smaller, faster)
cmd = [
"yt-dlp",
"--restrict-filenames",
"-f",
"bestaudio/best", # Audio only
"-x", # Extract audio
"--audio-format",
"best", # Keep best audio format
"-o",
filename_pattern,
]
if use_cookies:
cmd.extend(["--cookies", str(cookie_file)])
cmd.append(url)
else:
# Download video with 480p max quality
# Prefer https (direct download) over m3u8/HLS (slow segment-by-segment)
# Fallback chain: https direct -> video+audio merge -> any
cmd = [
"yt-dlp",
"--restrict-filenames",
"-f",
"best[protocol=https][height<=480]/bestvideo[height<=480]+bestaudio/best[height<=480]/best",
"-o",
filename_pattern,
]
if use_cookies:
cmd.extend(["--cookies", str(cookie_file)])
cmd.append(url)
start_time = time.time()
logging.debug(f"[DOWNLOAD] Running yt-dlp with timeout=1200s")
success, stdout, stderr = run_command(
cmd, cwd=site_dir, timeout=1200
)
elapsed = time.time() - start_time
if not success:
print_error("Download failed")
print(f"Error: {stderr[:500]}")
logging.error(f"[DOWNLOAD] Failed after {elapsed:.1f}s")
logging.error(f"[DOWNLOAD] Full stderr: {stderr}")
logging.error(f"[DOWNLOAD] Full stdout: {stdout}")
# Special error handling for unsupported sites
if site == "threads" and "Unsupported URL" in stderr:
print_warning("Threads is not yet supported by yt-dlp")
print_info(
"Threads support is in development. Check yt-dlp updates: yt-dlp -U"
)
print_info(
"Alternative: Download manually and use the transcript/summary features"
)
logging.warning(f"[DOWNLOAD] Unsupported site: {site}")
return None, False, site
# Find the most recently created VIDEO file in site directory
try:
video_files = [
f for f in site_dir.glob("*") if f.suffix.lower() in video_extensions
]
if not video_files:
print_error("No video files found after download")
return None, False, site
# Sort by modification time and get the most recent
video_file = sorted(video_files, key=lambda p: p.stat().st_mtime, reverse=True)[
0
]
# Normalize filename: remove consecutive dots before extension (e.g. "title..opus" -> "title.opus")
import os as _os
name = video_file.name
ext = video_file.suffix
base = name[: -len(ext)] if ext else name
normalized_base = base.rstrip(".")
if normalized_base != base:
normalized = video_file.parent / f"{normalized_base}{ext}"
if normalized.resolve() != video_file.resolve():
if normalized.exists():
normalized.unlink()
_os.replace(str(video_file), str(normalized))
video_file = normalized
file_size = video_file.stat().st_size / (1024**2) # MB
# Check if file already existed
already_existed = video_file.name in videos_before
if already_existed:
print_warning(f"Video already exists: {video_file.name}")
print_info("Skipping download (file already present)")
logging.info(f"[DOWNLOAD] Skipped (already exists): {video_file.resolve()}")
else:
print_success(f"Downloaded: {video_file.name}")
print_info(f"Time: {elapsed:.1f}s")
logging.info(
f"[DOWNLOAD] Success in {elapsed:.1f}s: {video_file.resolve()} ({file_size:.1f} MB)"
)
print_info(f"Size: {file_size:.1f} MB")
return video_file, already_existed, site
except Exception as e:
print_error(f"Error finding downloaded file: {e}")
logging.error(f"[DOWNLOAD] Exception: {e}")
return None, False, site
def get_video_duration(video_file):
"""
Get video duration in minutes using mediainfo.
Args:
video_file: Path to video file
Returns:
int: Duration in minutes, or None if unable to determine
"""
try:
# Check if mediainfo is available
success, _, _ = run_command(["mediainfo", "--version"])
if not success:
return None
# Get duration string from mediainfo
cmd = ["mediainfo", "--Inform=General;%Duration/String%", str(video_file)]
success, stdout, stderr = run_command(cmd, timeout=10)
if not success or not stdout.strip():
return None
duration_str = stdout.strip()
# Parse duration string (examples: "43 min 50 s", "1 h 23 min", "2 min 15 s", "55 s 915 ms")
total_minutes = 0
# Extract hours
if "h" in duration_str:
hours_part = duration_str.split("h")[0].strip()
try:
total_minutes += int(hours_part.split()[-1]) * 60
except (ValueError, IndexError):
pass
# Extract minutes
if "min" in duration_str:
# Get the part with minutes
if "h" in duration_str:
min_part = duration_str.split("h")[1].split("min")[0].strip()
else:
min_part = duration_str.split("min")[0].strip()
try:
total_minutes += int(min_part.split()[-1])
except (ValueError, IndexError):
pass
# Handle seconds-only videos (e.g., "55 s 915 ms")
# If no hours or minutes found, check for seconds and round up to 1 minute
if total_minutes == 0 and "s" in duration_str and "min" not in duration_str:
try:
# Extract seconds (before " s")
seconds_part = duration_str.split("s")[0].strip()
seconds = int(seconds_part.split()[-1])
# Round up to at least 1 minute for short videos
total_minutes = max(1, (seconds + 59) // 60) # Round up
except (ValueError, IndexError):
pass
return total_minutes if total_minutes > 0 else None
except Exception as e:
print_warning(f"Could not determine video duration: {e}")
return None
def convert_audio_for_whisper(video_file):
"""
Convert audio to mono 16kHz WAV for transcription.
Whisper prefers:
- Mono channel (not stereo)
- 16kHz sample rate
- WAV format preferred
Args:
video_file: Path to video/audio file
Returns:
Path: Path to converted WAV file, or None on error
"""
logging.info(f"[CONVERT] Converting audio for whisper: {video_file.name}")
# Create converted filename
converted_file = video_file.parent / f"{video_file.stem}_mono16k.wav"
# Check if already converted
if converted_file.exists():
print_info(f"Using existing converted audio: {converted_file.name}")
logging.info(f"[CONVERT] Using existing: {converted_file}")
return converted_file
print_info("Converting audio to mono 16kHz WAV for whisper...")
# Use ffmpeg to convert: mono, 16kHz, 16-bit PCM WAV
cmd = [
"ffmpeg",
"-i",
str(video_file),
"-ac",
"1", # Mono
"-ar",
"16000", # 16kHz
"-acodec",
"pcm_s16le", # 16-bit PCM
"-y", # Overwrite
str(converted_file),
]
start_time = time.time()
success, stdout, stderr = run_command(cmd, timeout=300)
if not success:
print_error(f"Audio conversion failed: {stderr[:200]}")
logging.error(f"[CONVERT] Failed")
logging.error(f"[CONVERT] Full stderr: {stderr}")
logging.error(f"[CONVERT] Full stdout: {stdout}")
return None
elapsed = time.time() - start_time
file_size = converted_file.stat().st_size / (1024**2) # MB
print_success(f"Converted: {converted_file.name}")
print_info(f"Size: {file_size:.1f} MB")
print_info(f"Time: {elapsed:.1f}s")
logging.info(
f"[CONVERT] Success in {elapsed:.1f}s: {converted_file} ({file_size:.1f} MB)"
)
return converted_file
def _find_whisper_output(video_file):
"""
Find whisper transcript output file, handling truncated filenames.
mlx-whisper truncates long filenames (~80 chars). This function tries
the exact stem match first, then falls back to prefix-based search.
Args:
video_file: Path to the video file
Returns:
Path to transcript file, or None if not found
"""
# Try exact match patterns: audio_stem.txt and video_stem.txt
audio_stem = f"{video_file.stem}_mono16k"
for stem in [audio_stem, video_file.stem]:
candidate = video_file.parent / f"{stem}.txt"
if candidate.exists():
return candidate
# Fallback: mlx-whisper truncates long filenames
# Use first 60 chars as prefix (safe margin before truncation point)
# Also exclude our own "-transcript.txt" files from results
prefix = audio_stem[:60]
txt_files = sorted(
[
f
for f in video_file.parent.glob("*.txt")
if f.stem.startswith(prefix) and not f.stem.endswith("-transcript")
],
key=lambda p: p.stat().st_mtime,
reverse=True,
)
if txt_files:
logging.debug(f"[TRANSCRIBE] Whisper truncated filename. Found: {txt_files[0].name}")
return txt_files[0]
# Broader fallback: try video stem prefix too
prefix = video_file.stem[:60]
txt_files = sorted(
[
f
for f in video_file.parent.glob("*.txt")
if f.stem.startswith(prefix) and not f.stem.endswith("-transcript")
],
key=lambda p: p.stat().st_mtime,
reverse=True,
)
if txt_files:
logging.debug(f"[TRANSCRIBE] Found transcript by video stem: {txt_files[0].name}")
return txt_files[0]
return None
def transcribe_video(video_file, force=False):
"""
Transcribe video using mlx-whisper (distil-whisper-large-v3).
Requires:
- mlx-whisper installed in the insanely-fast-whisper venv
- ffmpeg for audio conversion
Args:
video_file: Path to video file
force: Force re-transcription even if transcript exists
Returns:
Path: Path to transcript file, or None on error
"""
logging.info(
f"[TRANSCRIBE] Starting - Video: {video_file.resolve()}, force: {force}"
)
print_step(2, "Transcribing video...")
print_info(f"Video: {video_file.name}")
print_info(f"Location: {video_file.parent}")
# Create transcript filename
transcript_file = video_file.parent / f"{video_file.stem}-transcript.txt"
# Check if transcript already exists (also check for whisper-truncated filename)
if not force:
existing_transcript = _find_whisper_output(video_file) or (
transcript_file if transcript_file.exists() else None
)
if existing_transcript:
target = transcript_file if transcript_file.exists() else existing_transcript
print_warning(f"Transcript already exists: {target.name}")
print_info("Skipping transcription (file already present)")
transcript_size = target.stat().st_size
with open(target, "r") as f:
transcript_text = f.read()
word_count = len(transcript_text.split())
print_info(f"Size: {transcript_size} bytes")
print_info(f"Words: {word_count}")
logging.info(
f"[TRANSCRIBE] Skipped (already exists): {target.resolve()} ({word_count} words)"
)
return target
# Convert audio to mono 16kHz WAV
converted_audio = convert_audio_for_whisper(video_file)
if not converted_audio:
print_error("Failed to convert audio for whisper")
return None
audio_path = str(converted_audio.resolve())
logging.debug(f"[TRANSCRIBE] Audio path: {audio_path}")
# Build mlx-whisper command
# mlx-whisper outputs to a .txt file in the output directory
cmd = [
str(MLX_WHISPER_BIN),
audio_path,
"--model",
MLX_WHISPER_MODEL,
"--output-dir",
str(video_file.parent),
"--output-format",
"txt",
]
print_info(f"Using {MLX_WHISPER_MODEL} model...")
logging.debug(f"[TRANSCRIBE] Running mlx-whisper")
# Get video duration for timeout
duration_minutes = get_video_duration(video_file)
if duration_minutes:
print_info(f"Duration: {duration_minutes} minutes")
# Timeout = video duration + 2 minutes buffer
# Whisper is fast, but we give generous timeout
timeout = (duration_minutes * 60) + 120
timeout = max(300, timeout) # At least 5 minutes
else:
timeout = 900 # 15 minutes default if duration unknown
print_info(f"Transcription timeout: {timeout // 60} minutes {timeout % 60} seconds")
start_time = time.time()
success, stdout, stderr = run_command(cmd, timeout=timeout)
elapsed = time.time() - start_time
if not success:
print_error("Transcription failed")
if stderr:
print(f"Error: {stderr[-500:]}")
logging.error(f"[TRANSCRIBE] Failed after {elapsed:.1f}s")
logging.error(f"[TRANSCRIBE] Full stderr: {stderr}")
logging.error(f"[TRANSCRIBE] Full stdout: {stdout}")
logging.error(f"[TRANSCRIBE] Command was: {' '.join(cmd)}")
print_warning("Troubleshooting:")
print(f" 1. Ensure mlx-whisper is installed in {MLX_WHISPER_DIR}")
print(
f" cd {MLX_WHISPER_DIR} && source .venv/bin/activate && pip install mlx-whisper"
)
print(" 2. Check video has audio:")
print(f" ffprobe -v error -select_streams a:0 {video_file}")
return None
# mlx-whisper creates a .txt file based on the audio filename
# BUT it truncates long filenames, so we can't rely on exact stem match
whisper_output_file = _find_whisper_output(video_file)
if not whisper_output_file:
print_error(f"Whisper output file not found: {whisper_output_file}")
logging.error(
f"[TRANSCRIBE] Whisper output file not found: {whisper_output_file}"
)
return None
# Read transcript from whisper output and write to our expected location
try:
transcript_text = whisper_output_file.read_text(encoding="utf-8").strip()
except Exception as e:
print_error(f"Failed to read whisper output: {e}")
logging.error(f"[TRANSCRIBE] Failed to read whisper output: {e}")
return None
if not transcript_text:
print_error("Transcription produced empty output")
logging.error(f"[TRANSCRIBE] Empty transcript")
return None
# Write transcript to expected location
transcript_file.write_text(transcript_text, encoding="utf-8")
# Clean up whisper's output file (we've copied it to our expected location)
try:
whisper_output_file.unlink()
except:
pass
# Get transcript info
transcript_size = transcript_file.stat().st_size
word_count = len(transcript_text.split())
print_success(f"Transcribed: {transcript_file.name}")
print_info(f"Size: {transcript_size} bytes")
print_info(f"Words: {word_count}")
print_info(f"Time: {elapsed:.1f}s")
logging.info(
f"[TRANSCRIBE] Success in {elapsed:.1f}s: {transcript_file.resolve()} ({word_count} words)"
)
return transcript_file
def transcribe_file_stt(file_path):
"""
Standalone STT mode: transcribe a local audio/video file.
Outputs transcript text to stdout, all diagnostics to stderr.
Args:
file_path: Path to audio/video file
Returns:
str: Transcript text, or None on error
"""
audio_file = Path(file_path).resolve()
if not audio_file.exists():
print(f"[-] File not found: {audio_file}", file=sys.stderr)
return None
if not MLX_WHISPER_BIN.exists():
print(f"[-] mlx-whisper not found at: {MLX_WHISPER_BIN}", file=sys.stderr)
print(
f" Install it in {MLX_WHISPER_DIR} with: pip install mlx-whisper",
file=sys.stderr,
)
return None
success, _, _ = run_command(["ffmpeg", "-version"], log_output=False)
if not success:
print(
"[-] ffmpeg not found. Install with: brew install ffmpeg", file=sys.stderr
)
return None
original_stdout = sys.stdout
sys.stdout = sys.stderr
converted_audio = convert_audio_for_whisper(audio_file)
sys.stdout = original_stdout
if not converted_audio:
print("[-] Failed to convert audio for whisper", file=sys.stderr)
return None
audio_path = str(converted_audio.resolve())
cmd = [
str(MLX_WHISPER_BIN),
audio_path,
"--model",
MLX_WHISPER_MODEL,
"--output-dir",
str(audio_file.parent),
"--output-format",
"txt",