-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdictate.py
More file actions
2770 lines (2384 loc) · 152 KB
/
Copy pathdictate.py
File metadata and controls
2770 lines (2384 loc) · 152 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 streamlit as st
import torch
import numpy as np
import pyannote.audio as paa
#from pyannote.core import Segment
import tempfile
import os
import librosa
import soundfile as sf
from faster_whisper import WhisperModel
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
import torchaudio
import traceback
import time
import uuid
import warnings
import platform
import hashlib
import psutil
import importlib
import types
# import sys
import logging
#if you have / need to use a huggingface token, set it here
HF_TOKEN = ""
#keep streamlit from whining about torch.classes
torch.classes.__path__ = []
# Set to True to enable regular (non-debug) console output
# Set to False to suppress most console output
DEBUG_CONSOLE_OUTPUT = False
# Configure logging to suppress noisy messages
logging.getLogger("torch").setLevel(logging.ERROR)
logging.getLogger("torchaudio").setLevel(logging.ERROR)
logging.getLogger("pyannote").setLevel(logging.WARNING)
logging.getLogger("transformers").setLevel(logging.ERROR)
logging.getLogger("faster_whisper").setLevel(logging.WARNING)
logging.getLogger("librosa").setLevel(logging.WARNING)
logging.getLogger("streamlit").setLevel(logging.ERROR)
logging.getLogger("asyncio").setLevel(logging.ERROR)
# Suppress specific warnings
warnings.filterwarnings("ignore", message="Torchaudio's I/O functions now support par-call bakcend dispatch")
warnings.filterwarnings("ignore", message="torch.classes is an experimental")
warnings.filterwarnings("ignore", message="torch._C._get_custom_class_python_wrapper")
warnings.filterwarnings("ignore", message="Tried to instantiate class")
try:
import pynvml
PYNVML_AVAILABLE = True
except ImportError:
PYNVML_AVAILABLE = False
if DEBUG_CONSOLE_OUTPUT:
print("pynvml not found. Using PyTorch metrics for GPU memory usage.")
# Check for Apple Silicon (Metal) support
APPLE_SILICON_AVAILABLE = torch.backends.mps.is_available() if hasattr(torch.backends, 'mps') else False
# Check for AMD ROCm support
try:
import torch.utils.hipify
AMD_ROCM_AVAILABLE = hasattr(torch.version, 'hip') and torch.version.hip is not None
except (ImportError, AttributeError):
AMD_ROCM_AVAILABLE = False
# Add a comprehensive language map for Whisper at the top of the file, after the imports
# This defines all languages that Whisper supports for both transcription and translation
WHISPER_LANGUAGE_MAP = {
"en": "English",
"zh": "Chinese",
"de": "German",
"es": "Spanish",
"ru": "Russian",
"ko": "Korean",
"fr": "French",
"ja": "Japanese",
"pt": "Portuguese",
"tr": "Turkish",
"pl": "Polish",
"ca": "Catalan",
"nl": "Dutch",
"ar": "Arabic",
"sv": "Swedish",
"it": "Italian",
"id": "Indonesian",
"hi": "Hindi",
"fi": "Finnish",
"vi": "Vietnamese",
"he": "Hebrew",
"uk": "Ukrainian",
"el": "Greek",
"ms": "Malay",
"cs": "Czech",
"ro": "Romanian",
"da": "Danish",
"hu": "Hungarian",
"ta": "Tamil",
"no": "Norwegian",
"th": "Thai",
"ur": "Urdu",
"hr": "Croatian",
"bg": "Bulgarian",
"lt": "Lithuanian",
"la": "Latin",
"mi": "Maori",
"ml": "Malayalam",
"cy": "Welsh",
"sk": "Slovak",
"te": "Telugu",
"fa": "Persian",
"lv": "Latvian",
"bn": "Bengali",
"sr": "Serbian",
"az": "Azerbaijani",
"sl": "Slovenian",
"kn": "Kannada",
"et": "Estonian",
"mk": "Macedonian",
"br": "Breton",
"eu": "Basque",
"is": "Icelandic",
"hy": "Armenian",
"ne": "Nepali",
"mn": "Mongolian",
"bs": "Bosnian",
"kk": "Kazakh",
"sq": "Albanian",
"sw": "Swahili",
"gl": "Galician",
"mr": "Marathi",
"pa": "Punjabi",
"si": "Sinhala",
"km": "Khmer",
"sn": "Shona",
"yo": "Yoruba",
"so": "Somali",
"af": "Afrikaans",
"oc": "Occitan",
"ka": "Georgian",
"be": "Belarusian",
"tg": "Tajik",
"sd": "Sindhi",
"gu": "Gujarati",
"am": "Amharic",
"yi": "Yiddish",
"lo": "Lao",
"uz": "Uzbek",
"fo": "Faroese",
"ht": "Haitian Creole",
"ps": "Pashto",
"tk": "Turkmen",
"nn": "Nynorsk",
"mt": "Maltese",
"sa": "Sanskrit",
"lb": "Luxembourgish",
"my": "Myanmar",
"bo": "Tibetan",
"tl": "Tagalog",
"mg": "Malagasy",
"as": "Assamese",
"tt": "Tatar",
"haw": "Hawaiian",
"ln": "Lingala",
"ha": "Hausa",
"ba": "Bashkir",
"jw": "Javanese",
"su": "Sundanese",
}
# Helper functions to convert between language names and codes
def get_language_code(language_name):
"""Convert a language name to its code"""
for code, name in WHISPER_LANGUAGE_MAP.items():
if name == language_name:
return code
return None
def get_language_name(language_code):
"""Convert a language code to its name"""
return WHISPER_LANGUAGE_MAP.get(language_code, language_code)
# Add a debug logging function right after the imports and global variables
def debug_log(message):
"""Log debug information only when debug mode is enabled."""
if 'debug_mode' in st.session_state and st.session_state.debug_mode:
print(message)
# Function to get memory usage metrics
def get_system_memory_metrics(source="psutil", model=None):
"""Get system RAM usage metrics in a consistent format."""
memory = psutil.virtual_memory()
metrics = {
"used": memory.used / (1024**3), # GB
"total": memory.total / (1024**3), # GB
"free": memory.available / (1024**3), # GB
"usage_percent": memory.percent,
"source": source
}
# Add model info if provided
if model:
metrics["model"] = model
return metrics
def get_memory_metrics(use_gpu=False, gpu_type=None):
"""Get system RAM or GPU memory usage."""
if not use_gpu:
# System RAM usage
return get_system_memory_metrics()
# NVIDIA GPU
if gpu_type == "nvidia" and torch.cuda.is_available():
# Try using direct nvidia-smi call first (most accurate)
try:
import subprocess
# Run nvidia-smi command to get memory info
sp = subprocess.Popen(['nvidia-smi', '--query-gpu=memory.total,memory.used,memory.free', '--format=csv,noheader,nounits'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_str = sp.communicate()
out_list = out_str[0].decode("utf-8").strip().split(',')
if len(out_list) >= 3:
# Convert values from MiB to GB (1024 for binary conversion)
total_gpu_mem = float(out_list[0].strip()) / 1024
used_gpu_mem = float(out_list[1].strip()) / 1024
free_gpu_mem = float(out_list[2].strip()) / 1024
# Calculate percentage
usage_percent = (used_gpu_mem / total_gpu_mem) * 100 if total_gpu_mem > 0 else 0
# Print nvidia-smi values for debugging
debug_log("GPU Memory Debugging (nvidia-smi):")
debug_log(f" nvidia-smi total: {total_gpu_mem:.2f} GB")
debug_log(f" nvidia-smi used: {used_gpu_mem:.2f} GB")
debug_log(f" nvidia-smi free: {free_gpu_mem:.2f} GB")
debug_log(f" FINAL VALUES (nvidia-smi): used={used_gpu_mem:.2f}GB, total={total_gpu_mem:.2f}GB, percent={usage_percent:.2f}%")
return {
"used": used_gpu_mem,
"total": total_gpu_mem,
"free": free_gpu_mem,
"usage_percent": usage_percent,
"source": "nvidia-smi"
}
except Exception as e:
debug_log(f"Error getting GPU metrics from nvidia-smi: {e}")
# Fall back to other methods
# Fall back to NVML if nvidia-smi failed
if PYNVML_AVAILABLE:
try:
# Initialize NVML
pynvml.nvmlInit()
# Get the device handle for the first GPU (index 0)
handle = pynvml.nvmlDeviceGetHandleByIndex(0)
# Get memory info
mem_info = pynvml.nvmlDeviceGetMemoryInfo(handle)
# Convert to GB
total_gpu_mem = mem_info.total / (1024**3)
used_gpu_mem = mem_info.used / (1024**3)
free_gpu_mem = mem_info.free / (1024**3)
# Print NVML values for debugging
debug_log("GPU Memory Debugging (NVML):")
debug_log(f" NVML total: {total_gpu_mem:.2f} GB")
debug_log(f" NVML used: {used_gpu_mem:.2f} GB")
debug_log(f" NVML free: {free_gpu_mem:.2f} GB")
# Calculate percentage
usage_percent = (used_gpu_mem / total_gpu_mem) * 100
# Shut down NVML
pynvml.nvmlShutdown()
debug_log(f" FINAL VALUES (NVML): used={used_gpu_mem:.2f}GB, total={total_gpu_mem:.2f}GB, percent={usage_percent:.2f}%")
return {
"used": used_gpu_mem,
"total": total_gpu_mem,
"free": free_gpu_mem,
"usage_percent": usage_percent,
"source": "nvml"
}
except Exception as e:
debug_log(f"Error getting GPU metrics from NVML: {e}")
# Fall back to PyTorch metrics
pass
# Final fallback to PyTorch metrics if all else failed
debug_log("GPU Memory Debugging (PyTorch fallback):")
total_gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3) # GB
reserved_gpu_mem = torch.cuda.memory_reserved(0) / (1024**3) # GB
allocated_gpu_mem = torch.cuda.memory_allocated(0) / (1024**3) # GB
free_gpu_mem = total_gpu_mem - reserved_gpu_mem
# Final values to return
used_mem = reserved_gpu_mem # Use reserved memory with NO padding
usage_percent = (used_mem / total_gpu_mem) * 100 if total_gpu_mem > 0 else 0
debug_log(f" PyTorch total: {total_gpu_mem:.2f} GB")
debug_log(f" PyTorch reserved: {reserved_gpu_mem:.2f} GB")
debug_log(f" PyTorch allocated: {allocated_gpu_mem:.2f} GB")
debug_log(f" FINAL VALUES (PyTorch): used={used_mem:.2f}GB, total={total_gpu_mem:.2f}GB, percent={usage_percent:.2f}%")
return {
"used": used_mem,
"allocated": allocated_gpu_mem,
"total": total_gpu_mem,
"free": free_gpu_mem,
"usage_percent": usage_percent,
"source": "pytorch"
}
# Apple Silicon (M series)
elif gpu_type == "apple" and APPLE_SILICON_AVAILABLE:
try:
# Unfortunately, PyTorch doesn't provide memory info for MPS
# Use subprocess to run system command to get memory info
import subprocess
# Try to get Apple GPU information using sysctl
if platform.system() == "Darwin":
try:
# Get total GPU memory (this is an approximation)
# This command gets integrated GPU memory on Apple Silicon
# Note: The actual available GPU memory might be dynamic and share with system memory
result = subprocess.run(['sysctl', 'hw.memsize'], capture_output=True, text=True)
if result.returncode == 0:
# Parse the memory size (total system memory is used as an approximation)
total_mem_bytes = int(result.stdout.strip().split(':')[1].strip())
total_gpu_mem = total_mem_bytes / (1024**3) / 2 # Assume half of system memory
# Get Apple Silicon model info
model_result = subprocess.run(['sysctl', 'hw.model'], capture_output=True, text=True)
model_name = "Apple Silicon"
if model_result.returncode == 0:
model_name = model_result.stdout.strip().split(':')[1].strip()
# Get active memory usage - this is an approximation
# For M series, we don't have exact GPU memory usage, so estimate based on allocated tensor memory
if hasattr(torch.mps, 'current_allocated_memory'):
allocated_bytes = torch.mps.current_allocated_memory()
used_gpu_mem = allocated_bytes / (1024**3)
else:
# Assume 25% usage if we can't get actual numbers
used_gpu_mem = total_gpu_mem * 0.25
free_gpu_mem = total_gpu_mem - used_gpu_mem
usage_percent = (used_gpu_mem / total_gpu_mem) * 100
debug_log("GPU Memory Debugging (Apple Silicon):")
debug_log(f" Apple model: {model_name}")
debug_log(f" Approximate total: {total_gpu_mem:.2f} GB")
debug_log(f" Estimated used: {used_gpu_mem:.2f} GB")
debug_log(f" Estimated free: {free_gpu_mem:.2f} GB")
debug_log(f" FINAL VALUES (Apple Silicon): used={used_gpu_mem:.2f}GB, total={total_gpu_mem:.2f}GB, percent={usage_percent:.2f}%")
return {
"used": used_gpu_mem,
"total": total_gpu_mem,
"free": free_gpu_mem,
"usage_percent": usage_percent,
"source": "apple-sysctl",
"model": model_name
}
except Exception as e:
debug_log(f"Error getting Apple Silicon metrics: {e}")
# Fall back to a simple estimate
pass
# Fallback: Return estimated values
# For Apple Silicon, memory is dynamically shared with system memory,
# so return a simple approximation
system_memory = psutil.virtual_memory()
total_gpu_mem = system_memory.total / (1024**3) / 2 # Assume half of system memory is available for GPU
used_gpu_mem = total_gpu_mem * 0.25 # Just a placeholder
free_gpu_mem = total_gpu_mem - used_gpu_mem
usage_percent = 25.0 # Placeholder
return {
"used": used_gpu_mem,
"total": total_gpu_mem,
"free": free_gpu_mem,
"usage_percent": usage_percent,
"source": "estimated",
"model": "Apple Silicon"
}
except Exception as e:
debug_log(f"Error getting Apple Silicon metrics: {e}")
# Fall back to system memory info
return get_system_memory_metrics(source="system-ram-fallback", model="Apple Silicon")
# AMD GPU (ROCm)
elif gpu_type == "amd" and AMD_ROCM_AVAILABLE:
try:
# Use rocm-smi if available
import subprocess
try:
# Run rocm-smi command to get memory info
rocm_process = subprocess.Popen(
['rocm-smi', '--showmeminfo', 'vram', '--json'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
out_str, _ = rocm_process.communicate()
# Parse JSON output
import json
data = json.loads(out_str)
# Extract memory info from first GPU
card_data = next(iter(data.values()))
total_gpu_mem = int(card_data.get("VRAM Total", "0").split()[0]) / 1024 # Convert to GB
used_gpu_mem = int(card_data.get("VRAM Used", "0").split()[0]) / 1024
free_gpu_mem = total_gpu_mem - used_gpu_mem
usage_percent = (used_gpu_mem / total_gpu_mem) * 100 if total_gpu_mem > 0 else 0
# Get GPU name
name_process = subprocess.Popen(
['rocm-smi', '--showproductname'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
name_out, _ = name_process.communicate()
gpu_name = name_out.decode('utf-8').strip().split('\n')[-1].strip()
debug_log("GPU Memory Debugging (ROCm):")
debug_log(f" AMD GPU: {gpu_name}")
debug_log(f" rocm-smi total: {total_gpu_mem:.2f} GB")
debug_log(f" rocm-smi used: {used_gpu_mem:.2f} GB")
debug_log(f" rocm-smi free: {free_gpu_mem:.2f} GB")
debug_log(f" FINAL VALUES (rocm-smi): used={used_gpu_mem:.2f}GB, total={total_gpu_mem:.2f}GB, percent={usage_percent:.2f}%")
return {
"used": used_gpu_mem,
"total": total_gpu_mem,
"free": free_gpu_mem,
"usage_percent": usage_percent,
"source": "rocm-smi",
"model": gpu_name
}
except Exception as e:
debug_log(f"Error getting AMD GPU metrics from rocm-smi: {e}")
# Fall back to PyTorch metrics
pass
# Fall back to PyTorch metrics for AMD GPU
# HIP (ROCm) should provide memory stats similar to CUDA
if hasattr(torch.hip, 'get_device_properties'):
total_gpu_mem = torch.hip.get_device_properties(0).total_memory / (1024**3)
allocated_gpu_mem = torch.hip.memory_allocated(0) / (1024**3)
reserved_gpu_mem = torch.hip.memory_reserved(0) / (1024**3)
free_gpu_mem = total_gpu_mem - reserved_gpu_mem
usage_percent = (reserved_gpu_mem / total_gpu_mem) * 100 if total_gpu_mem > 0 else 0
debug_log("GPU Memory Debugging (PyTorch HIP):")
debug_log(f" PyTorch total: {total_gpu_mem:.2f} GB")
debug_log(f" PyTorch reserved: {reserved_gpu_mem:.2f} GB")
debug_log(f" PyTorch allocated: {allocated_gpu_mem:.2f} GB")
debug_log(f" FINAL VALUES (PyTorch HIP): used={reserved_gpu_mem:.2f}GB, total={total_gpu_mem:.2f}GB, percent={usage_percent:.2f}%")
return {
"used": reserved_gpu_mem,
"allocated": allocated_gpu_mem,
"total": total_gpu_mem,
"free": free_gpu_mem,
"usage_percent": usage_percent,
"source": "pytorch-hip"
}
except Exception as e:
debug_log(f"Error getting AMD GPU metrics: {e}")
# Fall back to system memory metrics
return get_system_memory_metrics(source="system-ram-fallback", model="AMD GPU")
# If no GPU or unsupported GPU type, return system RAM usage
return get_system_memory_metrics()
# Initialize session state variables if they don't exist
if 'debug_mode' not in st.session_state:
st.session_state.debug_mode = False
if 'speaker_names' not in st.session_state:
st.session_state.speaker_names = {}
if 'audio_samples' not in st.session_state:
st.session_state.audio_samples = {}
if 'transcript_data' not in st.session_state:
st.session_state.transcript_data = None
if 'current_file_hash' not in st.session_state:
st.session_state.current_file_hash = None
if 'preferred_language' not in st.session_state:
st.session_state.preferred_language = "English"
if 'translated_segments' not in st.session_state:
st.session_state.translated_segments = {}
if 'audio_data' not in st.session_state:
st.session_state.audio_data = None
if 'last_memory_update' not in st.session_state:
st.session_state.last_memory_update = 0
if 'memory_needs_update' not in st.session_state:
st.session_state.memory_needs_update = False
# Global variables
# transformers_debug = False
# Display CUDA information - helpful for debugging
gpu_info = {}
# Check for different GPU types
cuda_available = torch.cuda.is_available()
mps_available = APPLE_SILICON_AVAILABLE
rocm_available = AMD_ROCM_AVAILABLE
if cuda_available:
device_count = torch.cuda.device_count()
device_name = torch.cuda.get_device_name(0) if device_count > 0 else "Unknown"
cuda_version = torch.version.cuda if hasattr(torch.version, 'cuda') else "Unknown"
debug_log(f"CUDA is available: {cuda_available}")
debug_log(f"CUDA version: {cuda_version}")
debug_log(f"GPU count: {device_count}")
debug_log(f"GPU device name: {device_name}")
gpu_info = {
"type": "nvidia",
"name": device_name,
"count": device_count,
"version": cuda_version
}
elif mps_available:
debug_log("MPS (Apple Silicon) is available for GPU acceleration")
# Get Apple Silicon model info if possible
model_name = "Apple Silicon"
try:
import subprocess
model_result = subprocess.run(['sysctl', 'hw.model'], capture_output=True, text=True)
if model_result.returncode == 0:
model_name = model_result.stdout.strip().split(':')[1].strip()
except:
pass
debug_log(f"Apple Silicon model: {model_name}")
gpu_info = {
"type": "apple",
"name": model_name,
"count": 1,
"version": platform.mac_ver()[0] if platform.system() == "Darwin" else "Unknown"
}
elif rocm_available:
debug_log("ROCm is available for AMD GPU acceleration")
hip_version = torch.version.hip if hasattr(torch.version, 'hip') else "Unknown"
# Try to get AMD GPU name using rocm-smi
gpu_name = "AMD GPU"
try:
import subprocess
name_process = subprocess.Popen(
['rocm-smi', '--showproductname'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
name_out, _ = name_process.communicate()
gpu_name = name_out.decode('utf-8').strip().split('\n')[-1].strip()
except:
pass
debug_log(f"ROCm version: {hip_version}")
debug_log(f"AMD GPU name: {gpu_name}")
gpu_info = {
"type": "amd",
"name": gpu_name,
"count": 1,
"version": hip_version
}
else:
debug_log("No GPU acceleration is available. Running on CPU only.")
gpu_info = {
"type": "cpu",
"name": "CPU",
"count": 0,
"version": "N/A"
}
# Fix SpeechBrain deprecation warnings
os.environ["SPEECHBRAIN_SILENCE_DEPRECATION_PRETRAINED"] = "1"
# Fix PyAnnote std warning by setting a numeric computation environment variable
os.environ["PYTHONWARNINGS"] = "ignore::UserWarning,ignore::RuntimeWarning"
# For HuggingFace cache settings on Windows - properly handle without ignoring
if os.name == 'nt': # Windows
cache_dir = os.path.join(os.path.expanduser("~"), ".cache", "huggingface", "proper_cache")
os.makedirs(cache_dir, exist_ok=True)
os.environ["HF_HOME"] = cache_dir
# Fix for Streamlit's torch.classes inspection errors
def patch_streamlit_file_watcher():
"""Patch Streamlit's file watcher to handle torch.classes correctly."""
try:
import types
import importlib
from streamlit.watcher import local_sources_watcher
# Get original implementation to patch
original_extract_paths = local_sources_watcher._extract_module_paths
original_get_module_paths = local_sources_watcher.get_module_paths
# Make a fully comprehensive patch that excludes all torch modules from inspection
def is_torch_module(module):
"""Check if a module is a PyTorch module that should be excluded."""
if not hasattr(module, "__name__"):
return False
name = module.__name__
return (name.startswith("torch") or
"_torch" in name or
"torch_" in name or
"torchaudio" in name)
# Create patched version for module paths extraction
def patched_extract_paths(module):
"""Safe extraction of module paths that won't crash on torch modules."""
try:
# Skip any PyTorch module completely
if is_torch_module(module):
return []
# For other modules, use the original function
return original_extract_paths(module)
except Exception:
# For any other module that causes errors, return empty list
return []
# Patch get_module_paths to avoid processing torch modules
def patched_get_module_paths(module):
"""Safely get module paths."""
try:
# Skip any PyTorch module completely
if is_torch_module(module):
return []
# Handle the lambda m: list(m.__path__._path) case specifically
# This is the main source of errors with torch modules
if hasattr(module, "__name__") and not hasattr(module, "__path__"):
return []
return original_get_module_paths(module)
except Exception:
# For any other module that causes errors, return empty list
return []
# Create a safety wrapper for module.__path__ access
class SafePathWrapper:
def __init__(self, module):
self.module = module
@property
def __path__(self):
# Return a dummy path property with a safe _path attribute
if hasattr(self.module, "__path__") and hasattr(self.module.__path__, "_path"):
return self.module.__path__
else:
# Create a dummy object with a _path that won't crash when listed
dummy = types.SimpleNamespace()
dummy._path = []
return dummy
# Patch the specific pattern that causes the __path__._path access
original_import_module = importlib.import_module
def safe_import_module(name, package=None):
"""Wrapper for import_module that protects torch modules."""
module = original_import_module(name, package)
if is_torch_module(module):
# Return a wrapped module that won't crash on __path__._path access
return SafePathWrapper(module)
return module
# Apply the patches
local_sources_watcher._extract_module_paths = patched_extract_paths
local_sources_watcher.get_module_paths = patched_get_module_paths
importlib.import_module = safe_import_module
# For additional safety, directly modify the lambda in the local_sources_watcher
# This is a bit of a hack, but it targets the exact source of the error
if hasattr(local_sources_watcher, "_get_paths_from_module_spec"):
# The function that contains the problematic lambda - patch each handler
original_get_paths = local_sources_watcher._get_paths_from_module_spec
def patched_get_paths(spec):
"""A safer version of _get_paths_from_module_spec."""
# If it's a torch module, return an empty list
if spec and hasattr(spec, "name") and (
spec.name.startswith("torch") or
"_torch" in spec.name or
"torch_" in spec.name or
"torchaudio" in spec.name
):
return []
# Otherwise use the original function
return original_get_paths(spec)
# Apply this patch too
local_sources_watcher._get_paths_from_module_spec = patched_get_paths
except Exception as e:
if DEBUG_CONSOLE_OUTPUT:
print(f"Warning: Advanced Streamlit patch failed: {e}")
# Try simple patch as fallback
try:
from streamlit.watcher import local_sources_watcher
# Simple blacklist approach as fallback
def simple_extract_paths(module):
if (hasattr(module, "__name__") and
("torch" in module.__name__ or "torchaudio" in module.__name__)):
return []
try:
if hasattr(local_sources_watcher, "_extract_module_paths"):
original = local_sources_watcher._extract_module_paths
return original(module)
else:
return []
except:
return []
# Apply simple patch
if hasattr(local_sources_watcher, "_extract_module_paths"):
local_sources_watcher._extract_module_paths = simple_extract_paths
except Exception as e2:
if DEBUG_CONSOLE_OUTPUT:
print(f"Warning: Streamlit simple patch also failed: {e2}")
# Apply the Streamlit patch
patch_streamlit_file_watcher()
def safe_remove_file(file_path, max_retries=3, retry_delay=0.5):
"""Safely remove a file with retries, suppressing errors if the file can't be deleted."""
for attempt in range(max_retries):
try:
os.unlink(file_path)
return True # Successfully removed
except PermissionError:
if attempt < max_retries - 1:
time.sleep(retry_delay) # Wait before retrying
else:
# On last attempt, just log it and continue
if os.path.exists(file_path):
if DEBUG_CONSOLE_OUTPUT or st.session_state.get('debug_mode', False):
print(f"Warning: Could not remove temporary file: {file_path}")
return False
except FileNotFoundError:
# File already gone
return True
except Exception as e:
if DEBUG_CONSOLE_OUTPUT or st.session_state.get('debug_mode', False):
print(f"Error removing file {file_path}: {e}")
return False
def torch_parameter_hash(parameter):
return parameter.data.numpy().tobytes()
def get_device_for_model(use_gpu=False):
"""Helper function to get the appropriate device for loading models"""
if not use_gpu:
return "cpu"
if cuda_available:
return "cuda"
elif mps_available:
return "mps"
elif rocm_available:
return "cuda" # PyTorch ROCm uses "cuda" as device name for compatibility
else:
return "cpu"
# Model Selection with Hugging Face Authentication
@st.cache_resource(hash_funcs={torch.nn.parameter.Parameter: torch_parameter_hash})
def load_diarization_model(use_gpu=False):
'''Load the speaker diarization model'''
try:
hf_token = "HF_TOKEN"
pipeline = paa.Pipeline.from_pretrained(
"pyannote/speaker-diarization-3.1",
use_auth_token=hf_token
)
# Move to appropriate device if requested and available
if use_gpu:
device = get_device_for_model(use_gpu)
pipeline.to(torch.device(device))
return pipeline
except Exception as e:
st.error(f"Error loading diarization model: {e}")
raise
@st.cache_resource
def load_whisper_model(model_size="base", use_gpu=False):
'''Load the Whisper model using faster-whisper (CTranslate2 implementation)'''
try:
# Set device and compute type based on GPU availability
device = "cpu"
compute_type = "int8"
if use_gpu:
# CTranslate2 supports CUDA and CPU, but not MPS directly
# For Apple Silicon, we use CPU with optimized int8 computation
# For NVIDIA and AMD with CUDA/ROCm, we use GPU
if cuda_available or rocm_available:
device = "cuda"
compute_type = "float16"
else:
# On Apple Silicon, use optimized CPU mode (or auto which may use Metal via system libraries)
device = "auto" if platform.system() == "Darwin" else "cpu"
# Use GPU if requested and available
model = WhisperModel(model_size, device=device, compute_type=compute_type, download_root="./models")
return model
except Exception as e:
st.error(f"Error loading Whisper model: {e}")
raise
@st.cache_resource
def load_wav2vec2_model(model_name="facebook/wav2vec2-base-960h", use_gpu=False):
'''Load the Wav2Vec2 ASR model and processor'''
try:
processor = Wav2Vec2Processor.from_pretrained(model_name)
model = Wav2Vec2ForCTC.from_pretrained(model_name)
# Move to appropriate device if requested and available
if use_gpu:
device = get_device_for_model(use_gpu)
model = model.to(device)
return model, processor
except Exception as e:
st.error(f"Error loading Wav2Vec2 model: {e}")
raise
def transcribe_whisper_segment(audio_path, start_time, end_time, model, sample_rate=16000, language=None, task="transcribe"):
"""Transcribe or translate a specific audio segment using Whisper"""
try:
# Use librosa for more reliable segment extraction
audio, sr = librosa.load(audio_path, sr=sample_rate, offset=start_time, duration=(end_time-start_time))
# If segment is too short, return empty string
if len(audio) < 0.5 * sample_rate: # Less than 500ms
return "", None
# Create a uniquely named temporary file
temp_filename = f"whisper_segment_{uuid.uuid4().hex}.wav"
temp_filepath = os.path.join(tempfile.gettempdir(), temp_filename)
try:
# Save the segment to a temporary file
sf.write(temp_filepath, audio, sample_rate)
# Run the inference with explicit language if provided
if language and language.lower() != "auto-detect":
segments, info = model.transcribe(temp_filepath, beam_size=5, language=language.lower(), task=task)
else:
segments, info = model.transcribe(temp_filepath, beam_size=5, task=task)
# Get detected language from info
detected_language = None
# Add debug output to console
if hasattr(info, 'language') and info.language:
debug_log(f"Debug - TranscriptionInfo object found with language: {info.language}, Probability: {info.language_probability:.2f}")
# Check all available attributes of info
debug_log("Debug - TranscriptionInfo object attributes:" + str(dir(info)))
# Verify access to language attribute directly
try:
language_attr = getattr(info, 'language')
debug_log(f"Debug - Direct attribute access: info.language = '{language_attr}'")
except Exception as e:
debug_log(f"Debug - Error accessing language attribute: {e}")
# Try to get the language using __dict__ if available
if hasattr(info, '__dict__'):
debug_log(f"Debug - info.__dict__ = {info.__dict__}")
# Try alternative methods to get language
try:
language_str = str(info)
debug_log(f"Debug - info as string: {language_str}")
except Exception as e:
debug_log(f"Debug - Error converting info to string: {e}")
else:
debug_log("Debug - info object doesn't have language attribute or is None")
# Handle info whether it's a dictionary or TranscriptionInfo object
try:
# Try to get language as attribute (TranscriptionInfo object in newer versions)
if hasattr(info, 'language') and info.language:
lang_code = info.language
debug_log(f"Debug - Got lang_code='{lang_code}' from info.language attribute")
# Try to get language as dictionary key (older versions)
elif isinstance(info, dict) and "language" in info and info["language"]:
lang_code = info["language"]
debug_log(f"Debug - Got lang_code='{lang_code}' from info dictionary")
else:
lang_code = None
debug_log("Debug - No language code found in info object")
# Map language code to full name if we have a language code
if lang_code:
detected_language = WHISPER_LANGUAGE_MAP.get(lang_code, lang_code.title())
debug_log(f"Debug - Mapped language '{lang_code}' to '{detected_language}' from map: {WHISPER_LANGUAGE_MAP.get(lang_code)}")
except Exception as lang_err:
# If we can't get language info, just proceed without it
if st.session_state.get('debug_mode', False):
st.sidebar.warning(f"Language detection issue: {lang_err}")
debug_log(f"Debug - Language detection failed with error: {lang_err}")
traceback.print_exc() # Print the full error traceback
# Last attempt to extract language from string representation
try:
info_str = str(info)
if "language='" in info_str:
# Try to extract language from string representation
lang_start = info_str.find("language='") + 10
lang_end = info_str.find("'", lang_start)
if lang_start > 10 and lang_end > lang_start:
extracted_lang = info_str[lang_start:lang_end]
debug_log(f"Debug - Extracted language from string: '{extracted_lang}'")
detected_language = extracted_lang.title()
except Exception as e:
debug_log(f"Debug - Failed to extract language from string: {e}")
# Is this setting language to None?
detected_language = None
# Combine all segments into one text
# For newer versions, segments might be an iterable object
try:
transcription = " ".join([s.text for s in segments])
except TypeError:
# If segments is not iterable, it might be a single result or different format
if hasattr(segments, 'text'):
# Single segment result
transcription = segments.text
else:
# Last resort, try to convert to string
transcription = str(segments)
except Exception as e:
st.warning(f"Whisper transcription failed for segment: {e}")
transcription = ""
detected_language = None
finally:
# Safely remove the temporary file
safe_remove_file(temp_filepath)
return transcription.strip(), detected_language
except Exception as e:
st.error(f"Error during Whisper segment transcription: {e}")
traceback.print_exc()
return "", None
def transcribe_wav2vec2_segment(audio_array, start_time, end_time, model, processor, sample_rate=16000):
"""Transcribe a specific audio segment using Wav2Vec2"""
try:
# Calculate the indices in the audio array
start_idx = int(start_time * sample_rate)
end_idx = int(end_time * sample_rate)
# Safety check for bounds
if start_idx >= len(audio_array) or end_idx > len(audio_array):
st.warning(f"Segment indices out of bounds: {start_idx}-{end_idx}, array length: {len(audio_array)}")
return "", None
# Extract the segment
segment = audio_array[start_idx:end_idx]
# If segment is too short, return empty string
if len(segment) < 0.3 * sample_rate: # Less than 300ms
return "", None
# Process with ASR - explicitly create attention mask
inputs = processor(segment, sampling_rate=sample_rate, return_tensors="pt", padding=True)
# Always create a proper attention mask
attention_mask = torch.ones(inputs.input_values.shape[:2] if len(inputs.input_values.shape) > 2 else (1, inputs.input_values.shape[1]), dtype=torch.long)
# Move inputs to GPU if model is on GPU
device = next(model.parameters()).device
input_values = inputs.input_values.to(device)
attention_mask = attention_mask.to(device)
with torch.no_grad():