File size: 7,488 Bytes
63ab978
67cc6b1
40f2b57
91b9b83
63ab978
 
 
 
91b9b83
2ff01cb
91b9b83
67cc6b1
63ab978
67cc6b1
5845bfc
 
f9abd83
 
63ab978
5845bfc
 
63ab978
91b9b83
63ab978
91b9b83
 
6074f61
 
 
 
a70c074
6074f61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a70c074
6074f61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67cc6b1
6074f61
67cc6b1
 
63ab978
6074f61
 
 
63ab978
6074f61
 
21c25c6
6074f61
 
 
 
a70c074
91b9b83
6074f61
 
 
 
 
 
21c25c6
91b9b83
21c25c6
91b9b83
 
 
 
 
21c25c6
91b9b83
21c25c6
6074f61
21c25c6
a70c074
21c25c6
 
 
40f2b57
21c25c6
 
40f2b57
21c25c6
6074f61
 
67cc6b1
6074f61
 
 
67cc6b1
 
91b9b83
5845bfc
 
91b9b83
63ab978
 
91b9b83
 
6074f61
 
 
 
a70c074
63ab978
6074f61
 
63ab978
6074f61
63ab978
6074f61
 
 
 
 
 
 
63ab978
6074f61
63ab978
6074f61
a70c074
63ab978
6074f61
 
 
 
 
 
91b9b83
6074f61
 
67cc6b1
6074f61
67cc6b1
 
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
import whisper
from .base_interface import BaseInterface
from modules.subtitle_manager import get_srt, get_vtt, write_file, safe_filename
from modules.youtube_manager import get_ytdata, get_ytaudio
import gradio as gr
import os
from datetime import datetime

DEFAULT_MODEL_SIZE = "large-v2"


class WhisperInference(BaseInterface):
    def __init__(self):
        super().__init__()
        self.current_model_size = None
        self.model = None
        self.available_models = whisper.available_models()
        self.available_langs = sorted(list(whisper.tokenizer.LANGUAGES.values()))

    def transcribe_file(self, fileobjs,
                        model_size, lang, subformat, istranslate,
                        progress=gr.Progress()):

        def progress_callback(progress_value):
            progress(progress_value, desc="Transcribing..")

        try:
            if model_size != self.current_model_size or self.model is None:
                progress(0, desc="Initializing Model..")
                self.current_model_size = model_size
                self.model = whisper.load_model(name=model_size, download_root=os.path.join("models", "Whisper"))

            if lang == "Automatic Detection":
                lang = None

            progress(0, desc="Loading Audio..")

            files_info = {}
            for fileobj in fileobjs:

                audio = whisper.load_audio(fileobj.name)

                translatable_model = ["large", "large-v1", "large-v2"]
                if istranslate and self.current_model_size in translatable_model:
                    result = self.model.transcribe(audio=audio, language=lang, verbose=False, task="translate",
                                                   progress_callback=progress_callback)
                else:
                    result = self.model.transcribe(audio=audio, language=lang, verbose=False,
                                                   progress_callback=progress_callback)

                progress(1, desc="Completed!")

                file_name, file_ext = os.path.splitext(os.path.basename(fileobj.orig_name))
                file_name = file_name[:-9]
                file_name = safe_filename(file_name)
                timestamp = datetime.now().strftime("%m%d%H%M%S")
                output_path = os.path.join("outputs", f"{file_name}-{timestamp}")

                if subformat == "SRT":
                    subtitle = get_srt(result["segments"])
                    write_file(subtitle, f"{output_path}.srt")
                elif subformat == "WebVTT":
                    subtitle = get_vtt(result["segments"])
                    write_file(subtitle, f"{output_path}.vtt")

                files_info[file_name] = subtitle

            total_result = ''
            for file_name, subtitle in files_info.items():
                total_result += '------------------------------------\n'
                total_result += f'{file_name}\n\n'
                total_result += f'{subtitle}'

            return f"Done! Subtitle is in the outputs folder.\n\n{total_result}"
        except Exception as e:
            return f"Error: {str(e)}"
        finally:
            self.release_cuda_memory()
            self.remove_input_files([fileobj.name for fileobj in fileobjs])

    def transcribe_youtube(self, youtubelink,
                           model_size, lang, subformat, istranslate,
                           progress=gr.Progress()):

        def progress_callback(progress_value):
            progress(progress_value, desc="Transcribing..")

        try:
            if model_size != self.current_model_size or self.model is None:
                progress(0, desc="Initializing Model..")
                self.current_model_size = model_size
                self.model = whisper.load_model(name=model_size, download_root=os.path.join("models", "Whisper"))

            if lang == "Automatic Detection":
                lang = None

            progress(0, desc="Loading Audio from Youtube..")
            yt = get_ytdata(youtubelink)
            audio = whisper.load_audio(get_ytaudio(yt))

            translatable_model = ["large", "large-v1", "large-v2"]
            if istranslate and self.current_model_size in translatable_model:
                result = self.model.transcribe(audio=audio, language=lang, verbose=False, task="translate",
                                               progress_callback=progress_callback)
            else:
                result = self.model.transcribe(audio=audio, language=lang, verbose=False,
                                               progress_callback=progress_callback)

            progress(1, desc="Completed!")

            file_name = safe_filename(yt.title)
            timestamp = datetime.now().strftime("%m%d%H%M%S")
            output_path = os.path.join("outputs", f"{file_name}-{timestamp}")

            if subformat == "SRT":
                subtitle = get_srt(result["segments"])
                write_file(subtitle, f"{output_path}.srt")
            elif subformat == "WebVTT":
                subtitle = get_vtt(result["segments"])
                write_file(subtitle, f"{output_path}.vtt")

            return f"Done! Subtitle file is in the outputs folder.\n\n{subtitle}"
        except Exception as e:
            return f"Error: {str(e)}"
        finally:
            yt = get_ytdata(youtubelink)
            file_path = get_ytaudio(yt)
            self.release_cuda_memory()
            self.remove_input_files([file_path])

    def transcribe_mic(self, micaudio,
                       model_size, lang, subformat, istranslate,
                       progress=gr.Progress()):

        def progress_callback(progress_value):
            progress(progress_value, desc="Transcribing..")

        try:
            if model_size != self.current_model_size or self.model is None:
                progress(0, desc="Initializing Model..")
                self.current_model_size = model_size
                self.model = whisper.load_model(name=model_size, download_root=os.path.join("models", "Whisper"))

            if lang == "Automatic Detection":
                lang = None

            progress(0, desc="Loading Audio..")

            translatable_model = ["large", "large-v1", "large-v2"]
            if istranslate and self.current_model_size in translatable_model:
                result = self.model.transcribe(audio=micaudio, language=lang, verbose=False, task="translate",
                                               progress_callback=progress_callback)
            else:
                result = self.model.transcribe(audio=micaudio, language=lang, verbose=False,
                                               progress_callback=progress_callback)

            progress(1, desc="Completed!")

            timestamp = datetime.now().strftime("%m%d%H%M%S")
            output_path = os.path.join("outputs", f"{file_name}-{timestamp}")

            if subformat == "SRT":
                subtitle = get_srt(result["segments"])
                write_file(subtitle, f"{output_path}.srt")
            elif subformat == "WebVTT":
                subtitle = get_vtt(result["segments"])
                write_file(subtitle, f"{output_path}.vtt")

            return f"Done! Subtitle file is in the outputs folder.\n\n{subtitle}"
        except Exception as e:
            return f"Error: {str(e)}"
        finally:
            self.release_cuda_memory()
            self.remove_input_files([micaudio])