forked from fqscfqj/parakeet-api-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2276 lines (2029 loc) · 106 KB
/
app.py
File metadata and controls
2276 lines (2029 loc) · 106 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,sys,json,math
# Set environment variables to solve numba cache issues
os.environ['NUMBA_CACHE_DIR'] = '/tmp/numba_cache'
os.environ['NUMBA_DISABLE_JIT'] = '0'
# Set matplotlib config directory to avoid permission issues
# Prioritize using directory set by startup script, fallback to backup directory if not exists
if 'MPLCONFIGDIR' not in os.environ:
os.environ['MPLCONFIGDIR'] = '/tmp/matplotlib_config'
os.makedirs('/tmp/matplotlib_config', exist_ok=True)
os.chmod('/tmp/matplotlib_config', 0o777)
else:
# Ensure set directory exists and has correct permissions
mpl_dir = os.environ['MPLCONFIGDIR']
try:
os.makedirs(mpl_dir, exist_ok=True)
os.chmod(mpl_dir, 0o755)
except (PermissionError, OSError):
# If unable to create or set permissions, fallback to tmp directory
os.environ['MPLCONFIGDIR'] = '/tmp/matplotlib_config'
os.makedirs('/tmp/matplotlib_config', exist_ok=True)
os.chmod('/tmp/matplotlib_config', 0o777)
host = '0.0.0.0'
port = 5092
# Default thread count is more memory-efficient; increase for concurrency if needed
threads = int(os.environ.get('APP_THREADS', '2'))
# By default, cut audio/video into segments every N minutes to reduce GPU memory usage. Can now be adjusted via CHUNK_MINITE environment variable.
# For 8GB GPU memory, it's recommended to set to 10-15 minutes for optimal performance.
CHUNK_MINITE = int(os.environ.get('CHUNK_MINITE', '10'))
# Automatically unload model after service is idle for N minutes to free GPU memory; set to 0 to disable (default 30 minutes)
IDLE_TIMEOUT_MINUTES = int(os.environ.get('IDLE_TIMEOUT_MINUTES', '30'))
# Lazy load toggle, defaults to true. Set to 'false' to preload model on startup.
ENABLE_LAZY_LOAD = os.environ.get('ENABLE_LAZY_LOAD', 'true').lower() not in ['false', '0', 'f']
# Whisper-compatible API Key. If left empty, no authentication is performed.
API_KEY = os.environ.get('API_KEY', None)
import shutil
from typing import Any, Dict
import uuid
import subprocess
import datetime
import threading
import time
from werkzeug.utils import secure_filename
from flask import Flask, request, jsonify, Response
from waitress import serve
from pathlib import Path
# ROOT_DIR is not needed in Docker environment
# Only set HF mirror when not explicitly configured (can be overridden via environment variables)
if 'HF_ENDPOINT' not in os.environ:
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
# HF_HOME is set in the Dockerfile
os.environ['HF_HUB_DISABLE_SYMLINKS_WARNING'] = 'true'
# PATH for ffmpeg is handled by the Docker image's system PATH
# Reduce PyTorch CUDA allocation fragmentation, lowering OOM chances (can be overridden via external environment variables)
if 'PYTORCH_CUDA_ALLOC_CONF' not in os.environ:
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True,max_split_size_mb:128'
import nemo.collections.asr as nemo_asr # type: ignore
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import gc
import psutil
import ctypes
import ctypes.util
try:
# huggingface_hub may not be present in the editor environment; import defensively
from huggingface_hub import HfApi, hf_hub_download # type: ignore
except Exception:
# Provide fallbacks so static checkers and runtime in minimal environments won't crash.
HfApi = None # type: ignore
def hf_hub_download(*args, **kwargs):
raise RuntimeError("huggingface_hub is not installed")
# --- Global Settings and Model State ---
asr_model = None
last_request_time = None
model_lock = threading.Lock()
cuda_available = False # Global CUDA compatibility flag
# Supported languages (ISO 639-1, two-letter lowercase), based on parakeet-tdt-0.6b-v3 announcement
SUPPORTED_LANG_CODES = {
'bg','hr','cs','da','nl','en','et','fi','fr','de','el','hu','it','lv','lt','mt','pl','pt','ro','sk','sl','es','sv','ru','uk'
}
# Automatic language rejection (when language is not explicitly passed, first perform language detection on short segments; return Whisper-style error if not supported)
ENABLE_AUTO_LANGUAGE_REJECTION = os.environ.get('ENABLE_AUTO_LANGUAGE_REJECTION', 'true').lower() in ['true', '1', 't']
LID_CLIP_SECONDS = int(os.environ.get('LID_CLIP_SECONDS', '45'))
# Inference concurrency control (avoid multiple requests simultaneously occupying GPU memory causing OOM)
MAX_CONCURRENT_INFERENCES = int(os.environ.get('MAX_CONCURRENT_INFERENCES', '1'))
inference_semaphore = threading.Semaphore(MAX_CONCURRENT_INFERENCES)
# GPU memory optimization configuration
AGGRESSIVE_MEMORY_CLEANUP = os.environ.get('AGGRESSIVE_MEMORY_CLEANUP', 'true').lower() in ['true', '1', 't']
ENABLE_GRADIENT_CHECKPOINTING = os.environ.get('ENABLE_GRADIENT_CHECKPOINTING', 'true').lower() in ['true', '1', 't']
MAX_CHUNK_MEMORY_MB = int(os.environ.get('MAX_CHUNK_MEMORY_MB', '1500'))
FORCE_CLEANUP_THRESHOLD = float(os.environ.get('FORCE_CLEANUP_THRESHOLD', '0.8'))
ENABLE_MALLOC_TRIM = os.environ.get('ENABLE_MALLOC_TRIM', 'true').lower() in ['true', '1', 't']
# Idle resource optimization configuration
IDLE_MEMORY_CLEANUP_INTERVAL = int(os.environ.get('IDLE_MEMORY_CLEANUP_INTERVAL', '120')) # Memory cleanup interval during idle (seconds), default 2 minutes
IDLE_DEEP_CLEANUP_THRESHOLD = int(os.environ.get('IDLE_DEEP_CLEANUP_THRESHOLD', '600')) # Deep cleanup threshold (seconds), default 10 minutes
ENABLE_IDLE_CPU_OPTIMIZATION = os.environ.get('ENABLE_IDLE_CPU_OPTIMIZATION', 'true').lower() in ['true', '1', 't']
IDLE_MONITORING_INTERVAL = int(os.environ.get('IDLE_MONITORING_INTERVAL', '30')) # Idle monitoring interval (seconds), default 30 seconds
# Memory optimization configuration - simplified to reasonable default values, no user configuration needed
ENABLE_AGGRESSIVE_IDLE_OPTIMIZATION = os.environ.get('ENABLE_AGGRESSIVE_IDLE_OPTIMIZATION', 'true').lower() in ['true', '1', 't']
IMMEDIATE_CLEANUP_AFTER_REQUEST = os.environ.get('IMMEDIATE_CLEANUP_AFTER_REQUEST', 'true').lower() in ['true', '1', 't']
MEMORY_USAGE_ALERT_THRESHOLD_GB = float(os.environ.get('MEMORY_USAGE_ALERT_THRESHOLD_GB', '12.0')) # Set higher threshold to avoid frequent cleanup
AUTO_MODEL_UNLOAD_THRESHOLD_MINUTES = int(os.environ.get('AUTO_MODEL_UNLOAD_THRESHOLD_MINUTES', '30')) # Keep consistent with IDLE_TIMEOUT_MINUTES
# Tensor Core optimization configuration
ENABLE_TENSOR_CORE = os.environ.get('ENABLE_TENSOR_CORE', 'true').lower() in ['true', '1', 't']
ENABLE_CUDNN_BENCHMARK = os.environ.get('ENABLE_CUDNN_BENCHMARK', 'true').lower() in ['true', '1', 't']
TENSOR_CORE_PRECISION = os.environ.get('TENSOR_CORE_PRECISION', 'highest') # highest, high, medium
GPU_MEMORY_FRACTION = float(os.environ.get('GPU_MEMORY_FRACTION', '0.95')) # GPU memory fraction allowed for process
# Sentence integrity optimization configuration
ENABLE_OVERLAP_CHUNKING = os.environ.get('ENABLE_OVERLAP_CHUNKING', 'true').lower() in ['true', '1', 't']
CHUNK_OVERLAP_SECONDS = float(os.environ.get('CHUNK_OVERLAP_SECONDS', '30')) # Overlap duration
SENTENCE_BOUNDARY_THRESHOLD = float(os.environ.get('SENTENCE_BOUNDARY_THRESHOLD', '0.5')) # Sentence boundary detection threshold
# Silence-aligned slicing and preprocessing configuration
ENABLE_SILENCE_ALIGNED_CHUNKING = os.environ.get('ENABLE_SILENCE_ALIGNED_CHUNKING', 'true').lower() in ['true', '1', 't']
SILENCE_THRESHOLD_DB = os.environ.get('SILENCE_THRESHOLD_DB', '-38dB') # ffmpeg silencedetect noise threshold
MIN_SILENCE_DURATION = float(os.environ.get('MIN_SILENCE_DURATION', '0.35')) # Minimum duration considered as silence (seconds)
SILENCE_MAX_SHIFT_SECONDS = float(os.environ.get('SILENCE_MAX_SHIFT_SECONDS', '2.0')) # Maximum offset allowed for alignment to silence near target split point (seconds)
ENABLE_FFMPEG_DENOISE = os.environ.get('ENABLE_FFMPEG_DENOISE', 'false').lower() in ['true', '1', 't']
# Reasonable default denoise/equalizer/dynamic range settings, as gentle as possible to avoid overfitting
DENOISE_FILTER = os.environ.get(
'DENOISE_FILTER',
'afftdn=nf=-25,highpass=f=50,lowpass=f=8000,dynaudnorm=m=7:s=5'
)
# Decoding strategy (if model supports)
DECODING_STRATEGY = os.environ.get('DECODING_STRATEGY', 'greedy') # Options: greedy, beam
RNNT_BEAM_SIZE = int(os.environ.get('RNNT_BEAM_SIZE', '4'))
# Nemo transcription runtime configuration (batch and DataLoader)
TRANSCRIBE_BATCH_SIZE = int(os.environ.get('TRANSCRIBE_BATCH_SIZE', '1'))
TRANSCRIBE_NUM_WORKERS = int(os.environ.get('TRANSCRIBE_NUM_WORKERS', '0'))
# Subtitle post-processing configuration (to prevent subtitles from displaying too briefly)
MERGE_SHORT_SUBTITLES = os.environ.get('MERGE_SHORT_SUBTITLES', 'true').lower() in ['true', '1', 't']
MIN_SUBTITLE_DURATION_SECONDS = float(os.environ.get('MIN_SUBTITLE_DURATION_SECONDS', '1.5'))
SHORT_SUBTITLE_MERGE_MAX_GAP_SECONDS = float(os.environ.get('SHORT_SUBTITLE_MERGE_MAX_GAP_SECONDS', '0.3'))
SHORT_SUBTITLE_MIN_CHARS = int(os.environ.get('SHORT_SUBTITLE_MIN_CHARS', '6'))
SUBTITLE_MIN_GAP_SECONDS = float(os.environ.get('SUBTITLE_MIN_GAP_SECONDS', '0.06'))
# Long subtitle splitting and line breaks (optional)
# - Split overly long/long-duration subtitles into multiple entries; also wrap text within each subtitle for easier viewing
SPLIT_LONG_SUBTITLES = os.environ.get('SPLIT_LONG_SUBTITLES', 'true').lower() in ['true', '1', 't']
MAX_SUBTITLE_DURATION_SECONDS = float(os.environ.get('MAX_SUBTITLE_DURATION_SECONDS', '6.0'))
MAX_SUBTITLE_CHARS_PER_SEGMENT = int(os.environ.get('MAX_SUBTITLE_CHARS_PER_SEGMENT', '84')) # Approximately two lines, ~42 per line
PREFERRED_LINE_LENGTH = int(os.environ.get('PREFERRED_LINE_LENGTH', '42'))
MAX_SUBTITLE_LINES = int(os.environ.get('MAX_SUBTITLE_LINES', '2'))
# If true, try to use word-level timestamps for more precise splitting (automatically fallback if model doesn't return words)
ENABLE_WORD_TIMESTAMPS_FOR_SPLIT = os.environ.get('ENABLE_WORD_TIMESTAMPS_FOR_SPLIT', 'false').lower() in ['true', '1', 't']
# Prioritize splitting by punctuation: comma/period/question mark/exclamation mark/semicolon, etc.
SUBTITLE_SPLIT_PUNCTUATION = os.environ.get('SUBTITLE_SPLIT_PUNCTUATION', '。!?!?.,;;,,')
# Simplified configuration: presets and GPU VRAM (GB)
PRESET = os.environ.get('PRESET', 'balanced').lower() # speed | balanced | quality | simple(=balanced)
GPU_VRAM_GB_ENV = os.environ.get('GPU_VRAM_GB', '').strip()
# Ensure temporary upload directory exists
if not os.path.exists('./app/temp_uploads'):
os.makedirs('./app/temp_uploads')
def setup_tensor_core_optimization():
"""Configure Tensor Core optimization settings"""
global cuda_available
if not cuda_available:
print("CUDA unavailable, skipping Tensor Core optimization configuration")
return
print("Configuring Tensor Core optimization...")
try:
# Enable cuDNN benchmark mode
if ENABLE_CUDNN_BENCHMARK:
cudnn.benchmark = True
cudnn.deterministic = False # Allow nondeterministic for performance
print("✅ cuDNN benchmark enabled")
else:
cudnn.benchmark = False
cudnn.deterministic = True
print("❌ cuDNN benchmark disabled (deterministic mode)")
# Enable cuDNN to allow TensorCore
if ENABLE_TENSOR_CORE:
cudnn.allow_tf32 = True # Allow TF32 (supported by A100, etc.)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
print("✅ Tensor Core (TF32) enabled")
else:
cudnn.allow_tf32 = False
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
print("❌ Tensor Core disabled")
# Set Tensor Core precision strategy
if TENSOR_CORE_PRECISION == 'highest':
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False
print("✅ Set to highest precision mode")
elif TENSOR_CORE_PRECISION == 'high':
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = True
print("✅ Set to high precision mode")
else: # medium
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = True
print("✅ Set to medium precision mode")
# Set memory allocation strategy to optimize Tensor Core usage
try:
torch.cuda.set_per_process_memory_fraction(GPU_MEMORY_FRACTION)
print(f"✅ GPU memory allocation ratio: {GPU_MEMORY_FRACTION*100:.0f}%")
except Exception as e:
print(f"⚠️ Failed to set memory allocation ratio: {e}")
print("✅ GPU memory allocation strategy optimized")
except Exception as e:
print(f"⚠️ Tensor Core optimization configuration failed: {e}")
def get_tensor_core_info():
"""Get Tensor Core support information"""
global cuda_available
if not cuda_available:
return "N/A - CUDA unavailable"
try:
device = torch.cuda.get_device_properties(0)
major, minor = device.major, device.minor
# Detect Tensor Core support
if major >= 7: # V100, T4, RTX 20/30/40 series, etc.
if major == 7:
return f"✅ Tensor Core 1.0 (compute capability {major}.{minor})"
elif major == 8:
if minor >= 0:
return f"✅ Tensor Core 2.0 + TF32 (compute capability {major}.{minor})"
else:
return f"✅ Tensor Core 2.0 (compute capability {major}.{minor})"
elif major >= 9:
return f"✅ Tensor Core 3.0+ (compute capability {major}.{minor})"
elif major >= 6: # P100, etc.
return f"⚠️ Limited Tensor Core support (compute capability {major}.{minor})"
else:
return f"❌ Tensor Core not supported (compute capability {major}.{minor})"
return f"Unknown (compute capability {major}.{minor})"
except Exception as e:
return f"❌ Failed to get GPU information: {e}"
def optimize_tensor_operations():
"""Optimize tensor operations to better utilize Tensor Core"""
global cuda_available
if not cuda_available:
print("CUDA unavailable, skipping Tensor Core warmup")
return
try:
# Set optimized CUDA streams
torch.cuda.set_sync_debug_mode(0) # Disable sync debugging to improve performance
# Warm up GPU, ensuring Tensor Core is properly activated
# Create some matrices aligned to 8/16 multiples for warmup
device = torch.cuda.current_device()
dummy_a = torch.randn(128, 128, device=device, dtype=torch.float16)
dummy_b = torch.randn(128, 128, device=device, dtype=torch.float16)
# Execute matrix multiplication to warm up Tensor Core
with torch.cuda.amp.autocast():
_ = torch.matmul(dummy_a, dummy_b)
torch.cuda.synchronize()
del dummy_a, dummy_b
torch.cuda.empty_cache()
print("✅ Tensor Core warmup completed")
except Exception as e:
print(f"⚠️ Tensor Core warmup failed: {e}")
def detect_sentence_boundaries(text: str) -> list:
"""Detect sentence boundaries, return list of sentence end positions"""
import re
# Chinese/English periods, question marks, exclamation marks, etc.
sentence_endings = re.finditer(r'[.!?。!?]+[\s]*', text)
boundaries = [match.end() for match in sentence_endings]
return boundaries
def find_best_split_point(segments: list, target_time: float, tolerance: float = 2.0) -> int:
"""Find the best sentence split point near the target time"""
if not segments:
return 0
best_index = 0
min_distance = float('inf')
# Find the sentence end point closest to target time
for i, segment in enumerate(segments):
segment_end = segment.get('end', 0)
distance = abs(segment_end - target_time)
# Check if it's a sentence end (contains punctuation)
text = segment.get('segment', '').strip()
if text and (text.endswith('.') or text.endswith('。') or
text.endswith('!') or text.endswith('!') or
text.endswith('?') or text.endswith('?')):
# Sentence end point, weight is higher
distance *= 0.5
if distance < min_distance and distance <= tolerance:
min_distance = distance
best_index = i + 1 # Return next paragraph's index
return min(best_index, len(segments))
def merge_overlapping_segments(all_segments: list, chunk_boundaries: list, overlap_seconds: float) -> list:
"""Merge overlapping segments, remove duplicate content"""
if not ENABLE_OVERLAP_CHUNKING or len(chunk_boundaries) <= 1:
return all_segments
# Simplified and more robust: sort by time, then deduplicate same-text segments based on overlap window
if not all_segments:
return []
all_segments_sorted = sorted(all_segments, key=lambda s: (s.get('start', 0.0), s.get('end', 0.0)))
merged = []
for seg in all_segments_sorted:
text = seg.get('segment', '').strip()
if not text:
continue
if not merged:
merged.append(seg)
continue
prev = merged[-1]
# If highly overlapping in time and text is highly similar (or identical), keep the longer/higher-confidence one
overlap = min(prev['end'], seg['end']) - max(prev['start'], seg['start'])
window = overlap_seconds * 0.9 if overlap_seconds else 0.0
def normalized(t: str) -> str:
return ''.join(t.split()).lower()
same_text = normalized(prev.get('segment', '')) == normalized(text)
if overlap > 0 and overlap >= min(prev['end'] - prev['start'], seg['end'] - seg['start']) * 0.5:
if same_text or overlap >= window:
# Choose the segment with longer duration
if (prev['end'] - prev['start']) >= (seg['end'] - seg['start']):
# Possibly extend the end
prev['end'] = max(prev['end'], seg['end'])
else:
merged[-1] = seg
continue
# Otherwise directly append
merged.append(seg)
print(f"Merging completed, final {len(merged)} segments")
return merged
def enforce_min_subtitle_duration(
segments: list,
min_duration: float,
merge_max_gap: float,
min_chars: int,
min_gap: float,
) -> list:
"""Post-process the transcribed segments to avoid subtitles displaying too briefly:
1) Try to merge adjacent segments that are too short or have too little text (gap between segments does not exceed merge_max_gap).
2) If still shorter than min_duration, try to extend the current segment's end time to min_duration, but do not overlap with the next segment (reserve min_gap).
segments: [{'start': float, 'end': float, 'segment': str}, ...]
returns: processed segments (sorted by start time, and non-overlapping)
"""
if not segments:
return []
# Sort by start time, deep copy to avoid modifying original object
segments_sorted = sorted(
[
{
'start': float(s.get('start', 0.0)),
'end': float(s.get('end', 0.0)),
'segment': str(s.get('segment', '')),
}
for s in segments
],
key=lambda s: (s['start'], s['end'])
)
result: list = []
i = 0
n = len(segments_sorted)
while i < n:
current = segments_sorted[i]
current_text = str(current.get('segment', '')).strip()
# Try forward merging until minimum duration is satisfied or no more mergeable objects
while MERGE_SHORT_SUBTITLES:
duration = max(0.0, float(current.get('end', 0.0)) - float(current.get('start', 0.0)))
too_short = duration < min_duration or len(current_text) <= min_chars
if not too_short or i + 1 >= n:
break
next_seg = segments_sorted[i + 1]
gap = max(0.0, float(next_seg.get('start', 0.0)) - float(current.get('end', 0.0)))
if gap > merge_max_gap:
break
# Merge to current
next_text = str(next_seg.get('segment', '')).strip()
current['end'] = max(float(current.get('end', 0.0)), float(next_seg.get('end', 0.0)))
current_text = (current_text + ' ' + next_text).strip()
current['segment'] = current_text
i += 1 # Swallow the next segment
# After merging, if still short, try to extend, but must not overlap with next segment
duration = max(0.0, float(current.get('end', 0.0)) - float(current.get('start', 0.0)))
if duration < float(min_duration):
desired_end = float(current.get('start', 0.0)) + float(min_duration)
if i + 1 < n:
next_start = float(segments_sorted[i + 1].get('start', 0.0))
safe_end = max(float(current.get('end', 0.0)), min(desired_end, next_start - float(min_gap)))
# Only update if it doesn't result in an invalid interval
if safe_end > float(current.get('start', 0.0)):
current['end'] = safe_end
else:
# Already the last segment, extend directly
current['end'] = desired_end
result.append(current)
i += 1
# Finally ensure no overlaps and monotonic increase
cleaned: list = []
for seg in result:
if not cleaned:
cleaned.append(seg)
continue
prev = cleaned[-1]
if seg['start'] < prev['end']:
seg['start'] = prev['end'] + min_gap
if seg['start'] > seg['end']:
seg['start'] = seg['end']
cleaned.append(seg)
return cleaned
def process_chunk_segments(segments: list, overlap_start: float, overlap_seconds: float) -> list:
"""处理单个chunk的segments,处理重叠区域"""
if not segments:
return []
processed = []
overlap_end = overlap_start + overlap_seconds
for segment in segments:
segment_start = segment['start']
segment_end = segment['end']
# 如果segment完全在重叠区域之前,直接添加
if segment_end <= overlap_start:
processed.append(segment)
# 如果segment跨越重叠区域开始,需要检查是否截断
elif segment_start < overlap_start < segment_end:
# 检查是否在句子中间截断
text = segment.get('segment', '').strip()
if text and not any(punct in text for punct in ['.', '。', '!', '!', '?', '?']):
# 在句子中间,保留完整segment
processed.append(segment)
else:
# 可以安全截断的句子结束
processed.append(segment)
return processed
def create_overlap_chunks(total_duration: float, chunk_duration: float, overlap_seconds: float) -> list:
"""Create overlapping chunk time periods"""
chunks = []
current_start = 0.0
while current_start < total_duration:
chunk_end = min(current_start + chunk_duration, total_duration)
chunk_info = {
'start': current_start,
'end': chunk_end,
'duration': chunk_end - current_start
}
chunks.append(chunk_info)
# Next chunk's start time (considering overlap)
if chunk_end >= total_duration:
break
current_start = chunk_end - overlap_seconds
print(f"Created {len(chunks)} overlapping chunks:")
for i, chunk in enumerate(chunks):
print(f" Chunk {i}: {chunk['start']:.1f}s - {chunk['end']:.1f}s (duration: {chunk['duration']:.1f}s)")
return chunks
def check_cuda_compatibility():
"""Check CUDA compatibility, disable CUDA if incompatible"""
global cuda_available
try:
if not torch.cuda.is_available():
print("CUDA unavailable, will use CPU mode")
cuda_available = False
return False
# Try to get device count to test CUDA compatibility
device_count = torch.cuda.device_count()
if device_count == 0:
print("No CUDA devices detected, will use CPU mode")
cuda_available = False
return False
# Try to get device properties to further test compatibility
device_props = torch.cuda.get_device_properties(0)
print(f"✅ Compatible GPU detected: {device_props.name}")
cuda_available = True
return True
except RuntimeError as e:
if "forward compatibility was attempted on non supported HW" in str(e):
print("⚠️ CUDA compatibility error: GPU hardware does not support current CUDA version")
print("This is usually because the host GPU driver version is too old to support CUDA 13.x runtime in container")
print("Will automatically switch to CPU mode")
elif "CUDA" in str(e):
print(f"⚠️ CUDA initialization failed: {e}")
print("Will automatically switch to CPU mode")
else:
print(f"⚠️ Unknown CUDA error: {e}")
print("Will automatically switch to CPU mode")
cuda_available = False
return False
except Exception as e:
print(f"⚠️ GPU compatibility check failed: {e}")
print("Will automatically switch to CPU mode")
cuda_available = False
return False
def get_gpu_memory_usage():
"""Get GPU memory usage"""
global cuda_available
if not cuda_available:
return 0, 0, 0
try:
allocated = torch.cuda.memory_allocated() / 1024**3 # GB
reserved = torch.cuda.memory_reserved() / 1024**3 # GB
total = torch.cuda.get_device_properties(0).total_memory / 1024**3 # GB
return allocated, reserved, total
except Exception as e:
print(f"⚠️ Failed to get GPU memory information: {e}")
return 0, 0, 0
def aggressive_memory_cleanup():
"""Aggressive GPU memory cleanup function"""
global cuda_available
if cuda_available:
try:
# Clear CUDA cache
torch.cuda.empty_cache()
# Synchronize all CUDA operations
torch.cuda.synchronize()
# Reset peak memory statistics
torch.cuda.reset_peak_memory_stats()
except Exception as e:
print(f"⚠️ CUDA cleanup operation failed: {e}")
# Force Python garbage collection
for _ in range(3):
gc.collect()
if cuda_available:
try:
torch.cuda.empty_cache()
except Exception as e:
print(f"⚠️ CUDA cache cleanup failed: {e}")
# Return glibc memory to OS
try_malloc_trim()
def try_malloc_trim():
"""Try to return free memory to the OS through glibc's malloc_trim or available allocator.
- For glibc: call malloc_trim(0)
- If jemalloc is enabled and available, try to trigger background release (usually managed by MALLOC_CONF)
"""
if not ENABLE_MALLOC_TRIM:
return
# glibc
try:
libc_path = ctypes.util.find_library('c') or 'libc.so.6'
libc = ctypes.CDLL(libc_path)
# malloc_trim(size_t) -> int
try:
libc.malloc_trim.argtypes = [ctypes.c_size_t]
libc.malloc_trim.restype = ctypes.c_int
except Exception:
pass
res = libc.malloc_trim(0)
if res != 0:
print("✅ Called malloc_trim to return free memory")
else:
# Returning 0 may also indicate no trimmable fragments
print("ℹ️ malloc_trim called, no trimmable or already optimal")
except Exception as e:
# Optional jemalloc handling (if enabled via LD_PRELOAD, usually automatically reclaimed by background_thread)
print(f"⚠️ malloc_trim call failed or unavailable: {e}")
def idle_deep_memory_cleanup():
"""Deep memory cleanup function during idle - simplified to basic cleanup"""
global cuda_available
print("🧹 Executing idle memory cleanup...")
# Execute standard memory cleanup
aggressive_memory_cleanup()
# Additional cleanup measures
if cuda_available:
try:
# Clear CUDA cache
torch.cuda.empty_cache()
torch.cuda.synchronize()
# Reset memory statistics
torch.cuda.reset_peak_memory_stats()
torch.cuda.reset_accumulated_memory_stats()
except Exception as e:
print(f"⚠️ CUDA cleanup failed: {e}")
# Garbage collection
for _ in range(2):
gc.collect()
try_malloc_trim()
if cuda_available:
allocated, reserved, total = get_gpu_memory_usage()
print(f"✅ Cleanup completed, current GPU memory usage: {allocated:.2f}GB / {total:.2f}GB")
else:
memory = psutil.virtual_memory()
print(f"✅ Cleanup completed, current memory usage: {memory.used/1024**3:.2f}GB / {memory.total/1024**3:.2f}GB")
def immediate_post_request_cleanup():
"""Basic memory cleanup executed after request completion"""
print("🧽 Executing post-request cleanup...")
global cuda_available
if cuda_available:
try:
torch.cuda.empty_cache()
torch.cuda.synchronize()
except Exception:
pass
# Basic garbage collection
gc.collect()
try_malloc_trim()
def check_memory_usage_and_cleanup():
"""Check memory usage and trigger cleanup when necessary - only clean when usage is extremely high"""
global cuda_available
if cuda_available:
allocated, _, total = get_gpu_memory_usage()
# Only clean when GPU memory usage exceeds high threshold to avoid frequent interference
if allocated > MEMORY_USAGE_ALERT_THRESHOLD_GB and allocated / total > 0.9:
print(f"🚨 GPU memory usage too high ({allocated:.2f}GB), executing cleanup")
aggressive_memory_cleanup()
return True
else:
memory = psutil.virtual_memory()
# Only clean when memory usage exceeds 90%
if memory.percent > 90:
print(f"🚨 Memory usage too high ({memory.percent:.1f}%), executing cleanup")
aggressive_memory_cleanup()
return True
return False
def should_force_cleanup():
"""Check if GPU memory should be forcibly cleaned"""
global cuda_available
if not cuda_available:
return False
allocated, reserved, total = get_gpu_memory_usage()
usage_ratio = allocated / total if total > 0 else 0
return usage_ratio > FORCE_CLEANUP_THRESHOLD
def optimize_model_for_inference(model):
"""Optimize model to reduce GPU memory usage during inference"""
if model is None:
return model
# Set to evaluation mode
model.eval()
# Enable gradient checkpointing (if supported)
if ENABLE_GRADIENT_CHECKPOINTING and hasattr(model, 'encoder'):
try:
if hasattr(model.encoder, 'use_gradient_checkpointing'):
model.encoder.use_gradient_checkpointing = True
elif hasattr(model.encoder, 'gradient_checkpointing'):
model.encoder.gradient_checkpointing = True
except Exception as e:
print(f"Cannot enable gradient checkpointing: {e}")
# Disable automatic differentiation (gradients not needed for inference)
for param in model.parameters():
param.requires_grad = False
return model
def create_streaming_config():
"""Create streaming processing configuration to reduce GPU memory occupancy"""
return {
'batch_size': 1, # Single batch processing to reduce GPU memory usage
'num_workers': 0, # Avoid additional memory overhead from multiprocessing
'pin_memory': False, # Don't use page-locked memory to save system memory
'drop_last': False,
'persistent_workers': False # Don't keep worker processes
}
def load_model_if_needed():
"""Load model on demand, if model is not loaded, load it."""
global asr_model, cuda_available
# Use lock to ensure model is only loaded once in multi-threaded environment
with model_lock:
if asr_model is None:
print("="*50)
print("Model not currently loaded, initializing...")
# New model default: v3; supports overriding via environment variable
model_id = os.environ.get('MODEL_ID', 'nvidia/parakeet-tdt-0.6b-v3').strip()
model_local_path_env = os.environ.get('MODEL_LOCAL_PATH', '').strip()
print(f"Preferred model: {model_id}")
try:
# First check CUDA compatibility
cuda_available = check_cuda_compatibility()
# Ensure numba cache directory exists
numba_cache_dir = os.environ.get('NUMBA_CACHE_DIR', '/tmp/numba_cache')
if not os.path.exists(numba_cache_dir):
os.makedirs(numba_cache_dir, exist_ok=True)
os.chmod(numba_cache_dir, 0o777)
# Local priority strategy: prioritize using MODEL_LOCAL_PATH; otherwise try common filenames; otherwise auto-download from HF
candidate_local_paths = []
if model_local_path_env:
candidate_local_paths.append(model_local_path_env)
# New v3 default filename (if user manually downloaded .nemo)
candidate_local_paths.append("./app/models/parakeet-tdt-0.6b-v3.nemo")
# Compatible with old v2 filename (backward compatibility)
candidate_local_paths.append("./app/models/parakeet-tdt-0.6b-v2.nemo")
model_path = next((p for p in candidate_local_paths if os.path.exists(p)), None)
if cuda_available:
print(f"✅ Compatible CUDA environment detected, will use GPU acceleration and enable half-precision (FP16) optimization.")
# Set Tensor Core optimization
setup_tensor_core_optimization()
optimize_tensor_operations()
# Show GPU and Tensor Core information
device_info = torch.cuda.get_device_properties(0)
print(f"GPU: {device_info.name}")
print(f"Tensor Core support: {get_tensor_core_info()}")
# First load model on CPU, then transfer to GPU and enable FP16
if model_path:
# Local .nemo
# Check file permissions
if not os.access(model_path, os.R_OK):
raise PermissionError(f"Cannot read model file: {model_path}, please check file permissions.")
print(f"Restoring from local .nemo: {model_path}")
loaded_model = nemo_asr.models.ASRModel.restore_from(restore_path=model_path, map_location=torch.device('cpu'))
else:
# Auto-download from HF or try to directly fetch .nemo file to local cache directory
print(f"Attempting to get model file from Hugging Face: {model_id}")
os.makedirs('./app/models', exist_ok=True)
downloaded_path = None
try:
if HfApi is None:
raise RuntimeError("huggingface_hub not available")
api = HfApi()
repo_files = api.list_repo_files(model_id)
nemo_files = [f for f in repo_files if f.endswith('.nemo')]
if nemo_files:
target_fname = nemo_files[0]
print(f"Found remote .nemo file: {target_fname}, starting download...")
downloaded_path = hf_hub_download(repo_id=model_id, filename=target_fname, cache_dir='./app/models')
print(f"Model downloaded to: {downloaded_path}")
else:
print("No .nemo file found in remote repository, falling back to NeMo.from_pretrained() method to load")
except Exception as e:
print(f"Failed to get .nemo from Hugging Face: {e}")
if downloaded_path and os.path.exists(downloaded_path):
loaded_model = nemo_asr.models.ASRModel.restore_from(restore_path=downloaded_path, map_location=torch.device('cpu'))
else:
print(f"Using NeMo's from_pretrained to load model: {model_id}")
loaded_model = nemo_asr.models.ASRModel.from_pretrained(model_name=model_id)
loaded_model = loaded_model.cuda()
loaded_model = loaded_model.half()
# Apply inference optimization
loaded_model = optimize_model_for_inference(loaded_model)
# Show GPU memory usage
allocated, reserved, total = get_gpu_memory_usage()
print(f"GPU memory usage after model loading: {allocated:.2f}GB / {total:.2f}GB ({allocated/total*100:.1f}%)")
else:
print("🔄 Using CPU mode.")
print("Note: Inference speed will be slower in CPU mode, recommend using a compatible GPU.")
if model_path:
# Local .nemo
if not os.access(model_path, os.R_OK):
raise PermissionError(f"Cannot read model file: {model_path}, please check file permissions.")
print(f"Restoring from local .nemo: {model_path}")
loaded_model = nemo_asr.models.ASRModel.restore_from(restore_path=model_path)
else:
# Auto-download from HF or try to directly fetch .nemo file to local cache directory (CPU branch)
print(f"Attempting to get model file from Hugging Face: {model_id}")
os.makedirs('./app/models', exist_ok=True)
downloaded_path = None
try:
if HfApi is None:
raise RuntimeError("huggingface_hub not available")
api = HfApi()
repo_files = api.list_repo_files(model_id)
nemo_files = [f for f in repo_files if f.endswith('.nemo')]
if nemo_files:
target_fname = nemo_files[0]
print(f"Found remote .nemo file: {target_fname}, starting download...")
downloaded_path = hf_hub_download(repo_id=model_id, filename=target_fname, cache_dir='./app/models')
print(f"Model downloaded to: {downloaded_path}")
else:
print("No .nemo file found in remote repository, falling back to NeMo.from_pretrained() method to load")
except Exception as e:
print(f"Failed to get .nemo from Hugging Face: {e}")
if downloaded_path and os.path.exists(downloaded_path):
loaded_model = nemo_asr.models.ASRModel.restore_from(restore_path=downloaded_path)
else:
print(f"Using NeMo's from_pretrained to load model: {model_id}")
loaded_model = nemo_asr.models.ASRModel.from_pretrained(model_name=model_id)
loaded_model = optimize_model_for_inference(loaded_model)
# Configure decoding strategy (if model supports)
try:
configure_decoding_strategy(loaded_model)
except Exception as e:
print(f"⚠️ Failed to configure decoding strategy, will use default decoding: {e}")
asr_model = loaded_model
print("✅ NeMo ASR model loaded successfully!")
print("="*50)
except Exception as e:
print(f"❌ Model loading failed: {e}")
print("="*50)
import traceback
traceback.print_exc()
# Re-raise exception so interface can catch and return error information
raise e
return asr_model
def predownload_model_artifacts():
"""Download model files to local cache directory in the background, but don't load into memory.
This function is used to pre-download large files to `/app/models` when lazy loading is enabled to reduce subsequent first load delay.
"""
try:
model_id = os.environ.get('MODEL_ID', 'nvidia/parakeet-tdt-0.6b-v3').strip()
model_local_path_env = os.environ.get('MODEL_LOCAL_PATH', '').strip()
print(f"[predownload] Starting model pre-download check: {model_id}")
# Local priority: if local file already exists, no need to download
candidate_local_paths = []
if model_local_path_env:
candidate_local_paths.append(model_local_path_env)
candidate_local_paths.append('./app/models/parakeet-tdt-0.6b-v3.nemo')
candidate_local_paths.append('./app/models/parakeet-tdt-0.6b-v2.nemo')
for p in candidate_local_paths:
if p and os.path.exists(p):
print(f"[predownload] Found local model file, no need to download: {p}")
return
# Create cache directory
os.makedirs('./app/models', exist_ok=True)
# Try to use huggingface_hub to download remote .nemo file (download only, don't restore/load)
if HfApi is None:
print("[predownload] huggingface_hub not available, skipping pre-download")
return
try:
api = HfApi()
repo_files = api.list_repo_files(model_id)
nemo_files = [f for f in repo_files if f.endswith('.nemo')]
if not nemo_files:
print(f"[predownload] No .nemo files found in remote repository: {model_id}, skipping pre-download")
return
target_fname = nemo_files[0]
print(f"[predownload] Found remote .nemo file: {target_fname}, starting download to ./app/models ...")
try:
downloaded_path = hf_hub_download(repo_id=model_id, filename=target_fname, cache_dir='./app/models')
if downloaded_path and os.path.exists(downloaded_path):
print(f"[predownload] Model file downloaded: {downloaded_path}")
else:
print(f"[predownload] Download returned path is invalid or doesn't exist: {downloaded_path}")
except Exception as e:
print(f"[predownload] hf_hub_download failed: {e}")
except Exception as e:
print(f"[predownload] Query remote repository file list failed: {e}")
except Exception as e:
print(f"[predownload] Pre-download thread exception: {e}")
def unload_model():
"""Unload model from memory/GPU memory."""
global asr_model, last_request_time, cuda_available
with model_lock:
if asr_model is not None:
print(f"Model idle for more than {IDLE_TIMEOUT_MINUTES} minutes, unloading from memory...")
# Show GPU memory usage before unloading
if cuda_available:
allocated_before, _, total = get_gpu_memory_usage()
print(f"GPU memory usage before unloading: {allocated_before:.2f}GB / {total:.2f}GB")
asr_model = None
# Execute deep cleanup immediately after unloading
idle_deep_memory_cleanup()
try_malloc_trim()
# Show GPU memory usage after unloading
if cuda_available:
allocated_after, _, total = get_gpu_memory_usage()
print(f"GPU memory usage after unloading: {allocated_after:.2f}GB / {total:.2f}GB")
print(f"GPU memory freed: {allocated_before - allocated_after:.2f}GB")
last_request_time = None # Reset timer to prevent duplicate unloading
print("✅ Model successfully unloaded and deep cleanup completed.")
def model_cleanup_checker():
"""Background thread, periodically check if model has been idle too long and execute unloading."""
last_cleanup_time = datetime.datetime.now()
while True:
# Adaptively adjust check interval based on system status
current_time = datetime.datetime.now()
# Base monitoring interval - use shorter intervals for more frequent checks
sleep_interval = IDLE_MONITORING_INTERVAL
# Periodically check memory usage and clean when extremely high
if check_memory_usage_and_cleanup():
last_cleanup_time = current_time
if asr_model is not None and last_request_time is not None:
idle_duration = (current_time - last_request_time).total_seconds()
# Use configured model unload threshold
model_unload_threshold = IDLE_TIMEOUT_MINUTES * 60
# Check if model needs to be unloaded
if idle_duration > model_unload_threshold:
print(f"Model idle for {idle_duration/60:.1f} minutes, exceeding threshold of {model_unload_threshold/60:.1f} minutes")
unload_model()
# Execute deep cleanup immediately after model unload
idle_deep_memory_cleanup()
last_cleanup_time = current_time
# Adjust check frequency based on idle time
elif idle_duration > IDLE_DEEP_CLEANUP_THRESHOLD:
# When idle for long periods, reduce check frequency but execute deep cleanup
sleep_interval = max(60, IDLE_MONITORING_INTERVAL * 2) # At least 1 minute interval
if (current_time - last_cleanup_time).total_seconds() > IDLE_MEMORY_CLEANUP_INTERVAL:
print(f"Executing regular deep cleanup (idle for {idle_duration/60:.1f} minutes)")
idle_deep_memory_cleanup()
last_cleanup_time = current_time
elif idle_duration > IDLE_MEMORY_CLEANUP_INTERVAL:
# Medium idle time, execute light cleanup
if (current_time - last_cleanup_time).total_seconds() > IDLE_MEMORY_CLEANUP_INTERVAL:
print(f"Executing regular memory cleanup (idle for {idle_duration/60:.1f} minutes)")
if AGGRESSIVE_MEMORY_CLEANUP and should_force_cleanup():
print("🧹 Executing idle memory cleanup...")
aggressive_memory_cleanup()
else:
# Even if forced cleanup not needed, perform basic cleanup
if cuda_available:
try:
torch.cuda.empty_cache()
except Exception:
pass
gc.collect()
last_cleanup_time = current_time