-
Notifications
You must be signed in to change notification settings - Fork 57
/
subgen.py
1445 lines (1187 loc) · 59.6 KB
/
subgen.py
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
subgen_version = '2024.12.9'
from language_code import LanguageCode
from datetime import datetime
import os
import json
import xml.etree.ElementTree as ET
import threading
import sys
import time
import queue
import logging
import gc
import random
from typing import Union, Any, Optional
from fastapi import FastAPI, File, UploadFile, Query, Header, Body, Form, Request
from fastapi.responses import StreamingResponse
import numpy as np
import stable_whisper
from stable_whisper import Segment
import requests
import av
import ffmpeg
import whisper
import ast
from watchdog.observers.polling import PollingObserver as Observer
from watchdog.events import FileSystemEventHandler
import faster_whisper
from io import BytesIO
import io
def get_key_by_value(d, value):
reverse_dict = {v: k for k, v in d.items()}
return reverse_dict.get(value)
def convert_to_bool(in_bool):
# Convert the input to string and lower case, then check against true values
return str(in_bool).lower() in ('true', 'on', '1', 'y', 'yes')
plextoken = os.getenv('PLEXTOKEN', 'token here')
plexserver = os.getenv('PLEXSERVER', 'http://192.168.1.111:32400')
jellyfintoken = os.getenv('JELLYFINTOKEN', 'token here')
jellyfinserver = os.getenv('JELLYFINSERVER', 'http://192.168.1.111:8096')
whisper_model = os.getenv('WHISPER_MODEL', 'medium')
whisper_threads = int(os.getenv('WHISPER_THREADS', 4))
concurrent_transcriptions = int(os.getenv('CONCURRENT_TRANSCRIPTIONS', 2))
transcribe_device = os.getenv('TRANSCRIBE_DEVICE', 'cpu')
procaddedmedia = convert_to_bool(os.getenv('PROCADDEDMEDIA', True))
procmediaonplay = convert_to_bool(os.getenv('PROCMEDIAONPLAY', True))
namesublang = os.getenv('NAMESUBLANG', '')
webhookport = int(os.getenv('WEBHOOKPORT', 9000))
word_level_highlight = convert_to_bool(os.getenv('WORD_LEVEL_HIGHLIGHT', False))
debug = convert_to_bool(os.getenv('DEBUG', True))
use_path_mapping = convert_to_bool(os.getenv('USE_PATH_MAPPING', False))
path_mapping_from = os.getenv('PATH_MAPPING_FROM', r'/tv')
path_mapping_to = os.getenv('PATH_MAPPING_TO', r'/Volumes/TV')
model_location = os.getenv('MODEL_PATH', './models')
monitor = convert_to_bool(os.getenv('MONITOR', False))
transcribe_folders = os.getenv('TRANSCRIBE_FOLDERS', '')
transcribe_or_translate = os.getenv('TRANSCRIBE_OR_TRANSLATE', 'transcribe')
clear_vram_on_complete = convert_to_bool(os.getenv('CLEAR_VRAM_ON_COMPLETE', True))
compute_type = os.getenv('COMPUTE_TYPE', 'auto')
append = convert_to_bool(os.getenv('APPEND', False))
reload_script_on_change = convert_to_bool(os.getenv('RELOAD_SCRIPT_ON_CHANGE', False))
lrc_for_audio_files = convert_to_bool(os.getenv('LRC_FOR_AUDIO_FILES', True))
custom_regroup = os.getenv('CUSTOM_REGROUP', 'cm_sl=84_sl=42++++++1')
detect_language_length = int(os.getenv('DETECT_LANGUAGE_LENGTH', 30))
detect_language_offset = int(os.getenv('DETECT_LANGUAGE_START_OFFSET', 0))
skipifexternalsub = convert_to_bool(os.getenv('SKIPIFEXTERNALSUB', False))
skip_if_to_transcribe_sub_already_exist = convert_to_bool(os.getenv('SKIP_IF_TO_TRANSCRIBE_SUB_ALREADY_EXIST', True))
skipifinternalsublang = LanguageCode.from_string(os.getenv('SKIPIFINTERNALSUBLANG', ''))
skip_lang_codes_list = (
[LanguageCode.from_string(code) for code in os.getenv("SKIP_LANG_CODES", "").split("|")]
if os.getenv('SKIP_LANG_CODES')
else []
)
force_detected_language_to = LanguageCode.from_string(os.getenv('FORCE_DETECTED_LANGUAGE_TO', ''))
preferred_audio_languages = (
[LanguageCode.from_string(code) for code in os.getenv('PREFERRED_AUDIO_LANGUAGES', 'eng').split("|")]
if os.getenv('PREFERRED_AUDIO_LANGUAGES')
else []
) # in order of preferrence
limit_to_preferred_audio_languages = convert_to_bool(os.getenv('LIMIT_TO_PREFERRED_AUDIO_LANGUAGE', False)) #TODO: add support for this
skip_if_audio_track_is_in_list = (
[LanguageCode.from_string(code) for code in os.getenv('SKIP_IF_AUDIO_TRACK_IS', '').split("|")]
if os.getenv('SKIP_IF_AUDIO_TRACK_IS')
else []
)
subtitle_language_naming_type = os.getenv('SUBTITLE_LANGUAGE_NAMING_TYPE', 'ISO_639_2_B')
only_skip_if_subgen_subtitle = convert_to_bool(os.getenv('ONLY_SKIP_IF_SUBGEN_SUBTITLE', False))
skip_unknown_language = convert_to_bool(os.getenv('SKIP_UNKNOWN_LANGUAGE', False))
skip_if_language_is_not_set_but_subtitles_exist = convert_to_bool(os.getenv('SKIP_IF_LANGUAGE_IS_NOT_SET_BUT_SUBTITLES_EXIST', False))
should_whiser_detect_audio_language = convert_to_bool(os.getenv('SHOULD_WHISPER_DETECT_AUDIO_LANGUAGE', False))
try:
kwargs = ast.literal_eval(os.getenv('SUBGEN_KWARGS', '{}') or '{}')
except ValueError:
kwargs = {}
logging.info("kwargs (SUBGEN_KWARGS) is an invalid dictionary, defaulting to empty '{}'")
if transcribe_device == "gpu":
transcribe_device = "cuda"
VIDEO_EXTENSIONS = (
".mp4", ".mkv", ".avi", ".mov", ".wmv", ".flv", ".webm", ".mpg", ".mpeg",
".3gp", ".ogv", ".vob", ".rm", ".rmvb", ".ts", ".m4v", ".f4v", ".svq3",
".asf", ".m2ts", ".divx", ".xvid"
)
AUDIO_EXTENSIONS = (
".mp3", ".wav", ".aac", ".flac", ".ogg", ".wma", ".alac", ".m4a", ".opus",
".aiff", ".aif", ".pcm", ".ra", ".ram", ".mid", ".midi", ".ape", ".wv",
".amr", ".vox", ".tak", ".spx", '.m4b'
)
app = FastAPI()
model = None
in_docker = os.path.exists('/.dockerenv')
docker_status = "Docker" if in_docker else "Standalone"
last_print_time = None
#start queue
task_queue = queue.Queue()
def transcription_worker():
while True:
task = task_queue.get()
if "type" in task and task["type"] == "detect_language":
detect_language_task(task['path'])
elif 'Bazarr-' in task['path']:
logging.info(f"Task {task['path']} is being handled by ASR.")
else:
logging.info(f"Task {task['path']} is being handled by Subgen.")
gen_subtitles(task['path'], task['transcribe_or_translate'], task['force_language'])
task_queue.task_done()
# show queue
logging.debug(f"There are {task_queue.qsize()} tasks left in the queue.")
for _ in range(concurrent_transcriptions):
threading.Thread(target=transcription_worker, daemon=True).start()
# Define a filter class to hide common logging we don't want to see
class MultiplePatternsFilter(logging.Filter):
def filter(self, record):
# Define the patterns to search for
patterns = [
"Compression ratio threshold is not met",
"Processing segment at",
"Log probability threshold is",
"Reset prompt",
"Attempting to release",
"released on ",
"Attempting to acquire",
"acquired on",
"header parsing failed",
"timescale not set",
"misdetection possible",
"srt was added",
"doesn't have any audio to transcribe",
"Calling on_"
]
# Return False if any of the patterns are found, True otherwise
return not any(pattern in record.getMessage() for pattern in patterns)
# Configure logging
if debug:
level = logging.DEBUG
logging.basicConfig(stream=sys.stderr, level=level, format="%(asctime)s %(levelname)s: %(message)s")
else:
level = logging.INFO
logging.basicConfig(stream=sys.stderr, level=level)
# Get the root logger
logger = logging.getLogger()
logger.setLevel(level) # Set the logger level
for handler in logger.handlers:
handler.addFilter(MultiplePatternsFilter())
logging.getLogger("multipart").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("asyncio").setLevel(logging.WARNING)
logging.getLogger("watchfiles").setLevel(logging.WARNING)
#This forces a flush to print progress correctly
def progress(seek, total):
sys.stdout.flush()
sys.stderr.flush()
if(docker_status) == 'Docker':
global last_print_time
# Get the current time
current_time = time.time()
# Check if 5 seconds have passed since the last print
if last_print_time is None or (current_time - last_print_time) >= 5:
# Update the last print time
last_print_time = current_time
# Log the message
logging.debug("Force Update...")
TIME_OFFSET = 5
def appendLine(result):
if append:
lastSegment = result.segments[-1]
date_time_str = datetime.now().strftime("%d %b %Y - %H:%M:%S")
appended_text = f"Transcribed by whisperAI with faster-whisper ({whisper_model}) on {date_time_str}"
# Create a new segment with the updated information
newSegment = Segment(
start=lastSegment.start + TIME_OFFSET,
end=lastSegment.end + TIME_OFFSET,
text=appended_text,
words=[], # Empty list for words
id=lastSegment.id + 1
)
# Append the new segment to the result's segments
result.segments.append(newSegment)
@app.get("/plex")
@app.get("/webhook")
@app.get("/jellyfin")
@app.get("/asr")
@app.get("/emby")
@app.get("/detect-language")
@app.get("/tautulli")
def handle_get_request(request: Request):
return {"You accessed this request incorrectly via a GET request. See https://github.com/McCloudS/subgen for proper configuration"}
@app.get("/")
def webui():
return {"The webui for configuration was removed on 1 October 2024, please configure via environment variables or in your Docker settings."}
@app.get("/status")
def status():
return {"version" : f"Subgen {subgen_version}, stable-ts {stable_whisper.__version__}, faster-whisper {faster_whisper.__version__} ({docker_status})"}
@app.post("/tautulli")
def receive_tautulli_webhook(
source: Union[str, None] = Header(None),
event: str = Body(None),
file: str = Body(None),
):
if source == "Tautulli":
logging.debug(f"Tautulli event detected is: {event}")
if((event == "added" and procaddedmedia) or (event == "played" and procmediaonplay)):
fullpath = file
logging.debug("Path of file: " + fullpath)
gen_subtitles_queue(path_mapping(fullpath), transcribe_or_translate)
else:
return {
"message": "This doesn't appear to be a properly configured Tautulli webhook, please review the instructions again!"}
return ""
@app.post("/plex")
def receive_plex_webhook(
user_agent: Union[str] = Header(None),
payload: Union[str] = Form(),
):
try:
plex_json = json.loads(payload)
logging.debug(f"Raw response: {payload}")
if "PlexMediaServer" not in user_agent:
return {"message": "This doesn't appear to be a properly configured Plex webhook, please review the instructions again"}
event = plex_json["event"]
logging.debug(f"Plex event detected is: {event}")
if (event == "library.new" and procaddedmedia) or (event == "media.play" and procmediaonplay):
fullpath = get_plex_file_name(plex_json['Metadata']['ratingKey'], plexserver, plextoken)
logging.debug("Path of file: " + fullpath)
gen_subtitles_queue(path_mapping(fullpath), transcribe_or_translate)
refresh_plex_metadata(plex_json['Metadata']['ratingKey'], plexserver, plextoken)
logging.info(f"Metadata for item {plex_json['Metadata']['ratingKey']} refreshed successfully.")
except Exception as e:
logging.error(f"Failed to process Plex webhook: {e}")
return ""
@app.post("/jellyfin")
def receive_jellyfin_webhook(
user_agent: str = Header(None),
NotificationType: str = Body(None),
file: str = Body(None),
ItemId: str = Body(None),
):
if "Jellyfin-Server" in user_agent:
logging.debug(f"Jellyfin event detected is: {NotificationType}")
logging.debug(f"itemid is: {ItemId}")
if (NotificationType == "ItemAdded" and procaddedmedia) or (NotificationType == "PlaybackStart" and procmediaonplay):
fullpath = get_jellyfin_file_name(ItemId, jellyfinserver, jellyfintoken)
logging.debug(f"Path of file: {fullpath}")
gen_subtitles_queue(path_mapping(fullpath), transcribe_or_translate)
try:
refresh_jellyfin_metadata(ItemId, jellyfinserver, jellyfintoken)
logging.info(f"Metadata for item {ItemId} refreshed successfully.")
except Exception as e:
logging.error(f"Failed to refresh metadata for item {ItemId}: {e}")
else:
return {
"message": "This doesn't appear to be a properly configured Jellyfin webhook, please review the instructions again!"}
return ""
@app.post("/emby")
def receive_emby_webhook(
user_agent: Union[str, None] = Header(None),
data: Union[str, None] = Form(None),
):
logging.debug("Raw response: %s", data)
if not data:
return ""
data_dict = json.loads(data)
event = data_dict['Event']
logging.debug("Emby event detected is: " + event)
# Check if it's a notification test event
if event == "system.notificationtest":
logging.info("Emby test message received!")
return {"message": "Notification test received successfully!"}
if (event == "library.new" and procaddedmedia) or (event == "playback.start" and procmediaonplay):
fullpath = data_dict['Item']['Path']
logging.debug("Path of file: " + fullpath)
gen_subtitles_queue(path_mapping(fullpath), transcribe_or_translate)
return ""
@app.post("/batch")
def batch(
directory: Union[str, None] = Query(default=None),
forceLanguage: Union[str, None] = Query(default=None)
):
transcribe_existing(directory, LanguageCode.from_string(forceLanguage))
# idea and some code for asr and detect language from https://github.com/ahmetoner/whisper-asr-webservice
@app.post("//asr")
@app.post("/asr")
async def asr(
task: Union[str, None] = Query(default="transcribe", enum=["transcribe", "translate"]),
language: Union[str, None] = Query(default=None),
video_file: Union[str, None] = Query(default=None),
initial_prompt: Union[str, None] = Query(default=None), # Not used by Bazarr
audio_file: UploadFile = File(...),
encode: bool = Query(default=True, description="Encode audio first through ffmpeg"), # Not used by Bazarr/always False
output: Union[str, None] = Query(default="srt", enum=["txt", "vtt", "srt", "tsv", "json"]),
word_timestamps: bool = Query(default=False, description="Word-level timestamps"), # Not used by Bazarr
):
try:
logging.info(f"Transcribing file '{video_file}' from Bazarr/ASR webhook" if video_file else "Transcribing file from Bazarr/ASR webhook")
result = None
random_name = ''.join(random.choices("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", k=6))
if force_detected_language_to:
language = force_detected_language_to.to_iso_639_1()
logging.info(f"ENV FORCE_DETECTED_LANGUAGE_TO is set: Forcing detected language to {force_detected_language_to}")
start_time = time.time()
start_model()
task_id = {'path': f"Bazarr-asr-{random_name}"}
task_queue.put(task_id)
args = {}
args['progress_callback'] = progress
file_content = audio_file.file.read()
if encode:
args['audio'] = file_content
else:
args['audio'] = np.frombuffer(file_content, np.int16).flatten().astype(np.float32) / 32768.0
args['input_sr'] = 16000
if custom_regroup:
args['regroup'] = custom_regroup
args.update(kwargs)
result = model.transcribe_stable(task=task, language=language, **args)
appendLine(result)
elapsed_time = time.time() - start_time
minutes, seconds = divmod(int(elapsed_time), 60)
logging.info(
f"Transcription of '{video_file}' from Bazarr complete, it took {minutes} minutes and {seconds} seconds to complete." if video_file
else f"Transcription complete, it took {minutes} minutes and {seconds} seconds to complete.")
except Exception as e:
logging.error(
f"Error processing or transcribing Bazarr file: {video_file} -- Exception: {e}" if video_file
else f"Error processing or transcribing Bazarr file Exception: {e}"
)
finally:
await audio_file.close()
task_queue.task_done()
delete_model()
if result:
return StreamingResponse(
iter(result.to_srt_vtt(filepath=None, word_level=word_level_highlight)),
media_type="text/plain",
headers={
'Source': 'Transcribed using stable-ts from Subgen!',
}
)
else:
return
@app.post("//detect-language")
@app.post("/detect-language")
async def detect_language(
audio_file: UploadFile = File(...),
encode: bool = Query(default=True, description="Encode audio first through ffmpeg"), # This is always false from Bazarr
detect_lang_length: int = Query(default=detect_language_length, description="Detect language on X seconds of the file"),
detect_lang_offset: int = Query(default=detect_language_offset, description="Start Detect language X seconds into the file")
):
if force_detected_language_to:
logging.info(f"language is: {force_detected_language_to.to_name()}")
logging.debug(f"Skipping detect language, we have forced it as {force_detected_language_to.to_name()}")
return {
"detected_language": force_detected_language_to.to_name(),
"language_code": force_detected_language_to.to_iso_639_1()
}
global detect_language_length, detect_language_offset
detected_language = LanguageCode.NONE
language_code = 'und'
if force_detected_language_to:
logging.info(f"ENV FORCE_DETECTED_LANGUAGE_TO is set: Forcing detected language to {force_detected_language_to}\n Returning without detection")
return {"detected_language": force_detected_language_to.to_name(), "language_code": force_detected_language_to.to_iso_639_1()}
# Log custom detection time settings if modified
if detect_lang_length != detect_language_length:
logging.info(f"Detecting language on the first {detect_lang_length} seconds of the audio.")
detect_language_length = detect_lang_length
if detect_lang_offset != detect_language_offset:
logging.info(f"Offsetting language detection by {detect_language_offset} seconds.")
detect_language_offset = detect_lang_offset
#audio_file = extract_audio_segment_to_memory(audio_file, detect_language_offset, detect_language_length)
try:
start_model()
random_name = ''.join(random.choices("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", k=6))
task_id = { 'path': f"Bazarr-detect-language-{random_name}" }
task_queue.put(task_id)
args = {}
#sample_rate = next(stream.rate for stream in av.open(audio_file.file).streams if stream.type == 'audio')
#logging.info(f"Sample rate is: {sample_rate}")
audio_file.file.seek(0)
args['progress_callback'] = progress
if encode:
args['audio'] = extract_audio_segment_to_memory(audio_file, detect_language_offset, detect_language_length).read()
args['input_sr'] = 16000
else:
#args['audio'] = whisper.pad_or_trim(np.frombuffer(audio_file.file.read(), np.int16).flatten().astype(np.float32) / 32768.0, args['input_sr'] * int(detect_language_length))
args['audio'] = await get_audio_chunk(audio_file, detect_lang_offset, detect_lang_length)
args['input_sr'] = 16000
args.update(kwargs)
detected_language = LanguageCode.from_name(model.transcribe_stable(**args).language)
logging.debug(f"Detected language: {detected_language.to_name()}")
# reverse lookup of language -> code, ex: "english" -> "en", "nynorsk" -> "nn", ...
language_code = detected_language.to_iso_639_1()
logging.debug(f"Language Code: {language_code}")
except Exception as e:
logging.info(f"Error processing or transcribing Bazarr {audio_file.filename}: {e}")
finally:
#await audio_file.close()
task_queue.task_done()
delete_model()
return {"detected_language": detected_language.to_name(), "language_code": language_code}
async def get_audio_chunk(audio_file, offset=detect_language_offset, length=detect_language_length, sample_rate=16000, audio_format=np.int16):
"""
Extract a chunk of audio from a file, starting at the given offset and of the given length.
:param audio_file: The audio file (UploadFile or file-like object).
:param offset: The offset in seconds to start the extraction.
:param length: The length in seconds for the chunk to be extracted.
:param sample_rate: The sample rate of the audio (default 16000).
:param audio_format: The audio format to interpret (default int16, 2 bytes per sample).
:return: A numpy array containing the extracted audio chunk.
"""
# Number of bytes per sample (for int16, 2 bytes per sample)
bytes_per_sample = np.dtype(audio_format).itemsize
# Calculate the start byte based on offset and sample rate
start_byte = offset * sample_rate * bytes_per_sample
# Calculate the length in bytes based on the length in seconds
length_in_bytes = length * sample_rate * bytes_per_sample
# Seek to the start position (this assumes the audio_file is a file-like object)
await audio_file.seek(start_byte)
# Read the required chunk of audio (length_in_bytes)
chunk = await audio_file.read(length_in_bytes)
# Convert the chunk into a numpy array (normalized to float32)
audio_data = np.frombuffer(chunk, dtype=audio_format).flatten().astype(np.float32) / 32768.0
return audio_data
def detect_language_task(path):
detected_language = LanguageCode.NONE
language_code = 'und'
global detect_language_length
logger.info(f"Detecting language of file: {path} on the first {detect_language_length} seconds of the file")
try:
start_model()
audio_segment = extract_audio_segment_to_memory(path, detect_language_offset, int(detect_language_length)).read()
detected_language = LanguageCode.from_name(model.transcribe_stable(audio_segment).language)
logging.debug(f"Detected language: {detected_language.to_name()}")
# reverse lookup of language -> code, ex: "english" -> "en", "nynorsk" -> "nn", ...
language_code = detected_language.to_iso_639_1()
logging.debug(f"Language Code: {language_code}")
except Exception as e:
logging.info(f"Error detectign language of file with whisper: {e}")
finally:
task_queue.task_done()
delete_model()
# put task to transcribe this with the detected language
task_id = { 'path': path, "transcribe_or_translate": transcribe_or_translate, 'force_language': detected_language }
task_queue.put(task_id)
#maybe modify the file to contain detected language so we won't trigger this again
return
def extract_audio_segment_to_memory(input_file, start_time, duration):
"""
Extract a segment of audio from input_file, starting at start_time for duration seconds.
:param input_file: UploadFile object or path to the input audio file
:param start_time: Start time in seconds (e.g., 60 for 1 minute)
:param duration: Duration in seconds (e.g., 30 for 30 seconds)
:return: BytesIO object containing the audio segment
"""
try:
if hasattr(input_file, 'file') and hasattr(input_file.file, 'read'): # Handling UploadFile
input_file.file.seek(0) # Ensure the file pointer is at the beginning
input_stream = 'pipe:0'
input_kwargs = {'input': input_file.file.read()}
elif isinstance(input_file, str): # Handling local file path
input_stream = input_file
input_kwargs = {}
else:
raise ValueError("Invalid input: input_file must be a file path or an UploadFile object.")
logging.info(f"Extracting audio from: {input_stream}, start_time: {start_time}, duration: {duration}")
# Run FFmpeg to extract the desired segment
out, _ = (
ffmpeg
.input(input_stream, ss=start_time, t=duration) # Set start time and duration
.output('pipe:1', format='wav', acodec='pcm_s16le', ar=16000) # Output to pipe as WAV
.run(capture_stdout=True, capture_stderr=True, **input_kwargs)
)
# Check if the output is empty or null
if not out:
raise ValueError("FFmpeg output is empty, possibly due to invalid input.")
return io.BytesIO(out) # Convert output to BytesIO for in-memory processing
except ffmpeg.Error as e:
logging.error(f"FFmpeg error: {e.stderr.decode()}")
return None
except Exception as e:
logging.error(f"Error: {str(e)}")
return None
except ffmpeg.Error as e:
logging.error(f"FFmpeg error: {e.stderr.decode()}")
return None
except Exception as e:
logging.error(f"Error: {str(e)}")
return None
def start_model():
global model
if model is None:
logging.debug("Model was purged, need to re-create")
model = stable_whisper.load_faster_whisper(whisper_model, download_root=model_location, device=transcribe_device, cpu_threads=whisper_threads, num_workers=concurrent_transcriptions, compute_type=compute_type)
def delete_model():
gc.collect()
if clear_vram_on_complete and task_queue.qsize() == 0:
global model
logging.debug("Queue is empty, clearing/releasing VRAM")
model = None
def isAudioFileExtension(file_extension):
return file_extension.casefold() in \
AUDIO_EXTENSIONS
def write_lrc(result, file_path):
with open(file_path, "w") as file:
for segment in result.segments:
minutes, seconds = divmod(int(segment.start), 60)
fraction = int((segment.start - int(segment.start)) * 100)
# remove embedded newlines in text, since some players ignore text after newlines
text = segment.text[:].replace('\n', '')
file.write(f"[{minutes:02d}:{seconds:02d}.{fraction:02d}]{text}\n")
def gen_subtitles(file_path: str, transcription_type: str, force_language : LanguageCode = LanguageCode.NONE) -> None:
"""Generates subtitles for a video file.
Args:
file_path: str - The path to the video file.
transcription_type: str - The type of transcription or translation to perform.
force_language: str - The language to force for transcription or translation. Default is None.
"""
try:
logging.info(f"Added {os.path.basename(file_path)} for transcription.")
logging.info(f"Transcribing file: {os.path.basename(file_path)}")
logging.info(f"Transcribing file language: {force_language}")
start_time = time.time()
start_model()
# Check if the file is an audio file before trying to extract audio
file_name, file_extension = os.path.splitext(file_path)
is_audio_file = isAudioFileExtension(file_extension)
data = file_path
# Extract audio from the file if it has multiple audio tracks
extracted_audio_file = handle_multiple_audio_tracks(file_path, force_language)
if extracted_audio_file:
data = extracted_audio_file.read()
args = {}
args['progress_callback'] = progress
if custom_regroup:
args['regroup'] = custom_regroup
args.update(kwargs)
result = model.transcribe_stable(data, language=force_language.to_iso_639_1(), task=transcription_type, **args)
appendLine(result)
# If it is an audio file, write the LRC file
if is_audio_file and lrc_for_audio_files:
write_lrc(result, file_name + '.lrc')
else:
if not force_language:
force_language = LanguageCode.from_string(result.language)
result.to_srt_vtt(name_subtitle(file_path, force_language), word_level=word_level_highlight)
elapsed_time = time.time() - start_time
minutes, seconds = divmod(int(elapsed_time), 60)
logging.info(
f"Transcription of {os.path.basename(file_path)} is completed, it took {minutes} minutes and {seconds} seconds to complete.")
except Exception as e:
logging.info(f"Error processing or transcribing {file_path} in {force_language}: {e}")
finally:
delete_model()
def define_subtitle_language_naming(language: LanguageCode, type):
"""
Determines the naming format for a subtitle language based on the given type.
Args:
language (LanguageCode): The language code object containing methods to get different formats of the language name.
type (str): The type of naming format desired, such as 'ISO_639_1', 'ISO_639_2_T', 'ISO_639_2_B', 'NAME', or 'NATIVE'.
Returns:
str: The language name in the specified format. If an invalid type is provided, it defaults to the language's name.
"""
if namesublang:
return namesublang
switch_dict = {
"ISO_639_1": language.to_iso_639_1,
"ISO_639_2_T": language.to_iso_639_2_t,
"ISO_639_2_B": language.to_iso_639_2_b,
"NAME": language.to_name,
"NATIVE": lambda : language.to_name(in_english=False)
}
return switch_dict.get(type, language.to_name)()
def name_subtitle(file_path: str, language: LanguageCode) -> str:
"""
Name the the subtitle file to be written, based on the source file and the language of the subtitle.
Args:
file_path: The path to the source file.
language: The language of the subtitle.
Returns:
The name of the subtitle file to be written.
"""
return f"{os.path.splitext(file_path)[0]}.subgen.{whisper_model.split('.')[0]}.{define_subtitle_language_naming(language, subtitle_language_naming_type)}.srt"
def handle_multiple_audio_tracks(file_path: str, language: LanguageCode | None = None) -> BytesIO | None:
"""
Handles the possibility of a media file having multiple audio tracks.
If the media file has multiple audio tracks, it will extract the audio track of the selected language. Otherwise, it will extract the first audio track.
Parameters:
file_path (str): The path to the media file.
language (LanguageCode | None): The language of the audio track to search for. If None, it will extract the first audio track.
Returns:
io.BytesIO | None: The audio or None if no audio track was extracted.
"""
audio_bytes = None
audio_tracks = get_audio_tracks(file_path)
if len(audio_tracks) > 1:
logging.debug(f"Handling multiple audio tracks from {file_path} and planning to extract audio track of language {language}")
logging.debug(
"Audio tracks:\n"
+ "\n".join([f" - {track['index']}: {track['codec']} {track['language']} {('default' if track['default'] else '')}" for track in audio_tracks])
)
if language is not None:
audio_track = get_audio_track_by_language(audio_tracks, language)
if audio_track is None:
audio_track = audio_tracks[0]
audio_bytes = extract_audio_track_to_memory(file_path, audio_track["index"])
if audio_bytes is None:
logging.error(f"Failed to extract audio track {audio_track['index']} from {file_path}")
return None
return audio_bytes
def extract_audio_track_to_memory(input_video_path, track_index) -> BytesIO | None:
"""
Extract a specific audio track from a video file to memory using FFmpeg.
Args:
input_video_path (str): The path to the video file.
track_index (int): The index of the audio track to extract. If None, skip extraction.
Returns:
io.BytesIO | None: The audio data as a BytesIO object, or None if extraction failed.
"""
if track_index is None:
logging.warning(f"Skipping audio track extraction for {input_video_path} because track index is None")
return None
try:
# Use FFmpeg to extract the specific audio track and output to memory
out, _ = (
ffmpeg.input(input_video_path)
.output(
"pipe:", # Direct output to a pipe
map=f"0:{track_index}", # Select the specific audio track
format="wav", # Output format
ac=1, # Mono audio (optional)
ar=16000, # Sample rate 16 kHz (recommended for speech models)
loglevel="quiet"
)
.run(capture_stdout=True, capture_stderr=True) # Capture output in memory
)
# Return the audio data as a BytesIO object
return BytesIO(out)
except ffmpeg.Error as e:
print("An error occurred:", e.stderr.decode())
return None
def get_audio_track_by_language(audio_tracks, language):
"""
Returns the first audio track with the given language.
Args:
audio_tracks (list): A list of dictionaries containing information about each audio track.
language (str): The language of the audio track to search for.
Returns:
dict: The first audio track with the given language, or None if no match is found.
"""
for track in audio_tracks:
if track['language'] == language:
return track
return None
def choose_transcribe_language(file_path, forced_language):
"""
Determines the language to be used for transcription based on the provided
file path and language preferences.
Args:
file_path: The path to the file for which the audio tracks are analyzed.
forced_language: The language to force for transcription if specified.
Returns:
The language code to be used for transcription. It prioritizes the
`forced_language`, then the environment variable `force_detected_language_to`,
then the preferred audio language if available, and finally the default
language of the audio tracks. Returns None if no language preference is
determined.
"""
logger.debug(f"choose_transcribe_language({file_path}, {forced_language})")
if forced_language:
logger.debug(f"ENV FORCE_LANGUAGE is set: Forcing language to {forced_language}")
return forced_language
if force_detected_language_to:
logger.debug(f"ENV FORCE_DETECTED_LANGUAGE_TO is set: Forcing detected language to {force_detected_language_to}")
return force_detected_language_to
audio_tracks = get_audio_tracks(file_path)
found_track_in_language = find_language_audio_track(audio_tracks, preferred_audio_languages)
if found_track_in_language:
language = found_track_in_language
if language:
logger.debug(f"Preferred language found: {language}")
return language
default_language = find_default_audio_track_language(audio_tracks)
if default_language:
logger.debug(f"Default language found: {default_language}")
return default_language
return LanguageCode.NONE
def get_audio_tracks(video_file):
"""
Extracts information about the audio tracks in a file.
Returns:
List of dictionaries with information about each audio track.
Each dictionary has the following keys:
index (int): The stream index of the audio track.
codec (str): The name of the audio codec.
channels (int): The number of audio channels.
language (LanguageCode): The language of the audio track.
title (str): The title of the audio track.
default (bool): Whether the audio track is the default for the file.
forced (bool): Whether the audio track is forced.
original (bool): Whether the audio track is the original.
commentary (bool): Whether the audio track is a commentary.
Example:
>>> get_audio_tracks("french_movie_with_english_dub.mp4")
[
{
"index": 0,
"codec": "dts",
"channels": 6,
"language": LanguageCode.FRENCH,
"title": "French",
"default": True,
"forced": False,
"original": True,
"commentary": False
},
{
"index": 1,
"codec": "aac",
"channels": 2,
"language": LanguageCode.ENGLISH,
"title": "English",
"default": False,
"forced": False,
"original": False,
"commentary": False
}
]
Raises:
ffmpeg.Error: If FFmpeg fails to probe the file.
"""
try:
# Probe the file to get audio stream metadata
probe = ffmpeg.probe(video_file, select_streams='a')
audio_streams = probe.get('streams', [])
# Extract information for each audio track
audio_tracks = []
for stream in audio_streams:
audio_track = {
"index": int(stream.get("index", None)),
"codec": stream.get("codec_name", "Unknown"),
"channels": int(stream.get("channels", None)),
"language": LanguageCode.from_iso_639_2(stream.get("tags", {}).get("language", "Unknown")),
"title": stream.get("tags", {}).get("title", "None"),
"default": stream.get("disposition", {}).get("default", 0) == 1,
"forced": stream.get("disposition", {}).get("forced", 0) == 1,
"original": stream.get("disposition", {}).get("original", 0) == 1,
"commentary": "commentary" in stream.get("tags", {}).get("title", "").lower()
}
audio_tracks.append(audio_track)
return audio_tracks
except ffmpeg.Error as e:
logging.error(f"FFmpeg error: {e.stderr}")
return []
except Exception as e:
logging.error(f"An error occurred while reading audio track information: {str(e)}")
return []
def find_language_audio_track(audio_tracks, find_languages):
"""
Checks if an audio track with any of the given languages is present in the list of audio tracks.
Returns the first language from `find_languages` that matches.
Args:
audio_tracks (list): A list of dictionaries containing information about each audio track.
find_languages (list): A list language codes to search for.
Returns:
str or None: The first language found from `find_languages`, or None if no match is found.
"""
for language in find_languages:
for track in audio_tracks:
if track['language'] == language:
return language
return None
def find_default_audio_track_language(audio_tracks):
"""
Finds the language of the default audio track in the given list of audio tracks.
Args:
audio_tracks (list): A list of dictionaries containing information about each audio track.
Must contain the key "default" which is a boolean indicating if the track is the default track.
Returns:
str: The ISO 639-2 code of the language of the default audio track, or None if no default track was found.
"""
for track in audio_tracks:
if track['default'] is True:
return track['language']
return None
def gen_subtitles_queue(file_path: str, transcription_type: str, force_language: LanguageCode = LanguageCode.NONE) -> None:
global task_queue
if not has_audio(file_path):
logging.debug(f"{file_path} doesn't have any audio to transcribe!")
return
force_language = choose_transcribe_language(file_path, force_language)
# check if we would like to detect audio language in case of no audio language specified. Will return here again with specified language from whisper
if not force_language and should_whiser_detect_audio_language:
# make a detect language task
task_id = { 'path': file_path, 'type': "detect_language" }
task_queue.put(task_id)
logging.info(f"task_queue.put(task_id)({file_path}, detect_language)")
return
if have_to_skip(file_path, force_language):
logging.debug(f"{file_path} already has subtitles in {force_language}, skipping.")
return
task = {
'path': file_path,
'transcribe_or_translate': transcription_type,
'force_language': force_language
}
task['force_language'] = force_language
task_queue.put(task)