File size: 7,586 Bytes
75153af
 
 
 
2bfc660
57f7f52
 
 
 
 
 
 
 
75153af
 
 
 
57f7f52
 
75153af
 
 
57f7f52
 
75153af
594aeee
 
75153af
b55a3fa
594aeee
 
a5d7202
57f7f52
18bcd78
57f7f52
2bfc660
 
 
 
594aeee
57f7f52
 
 
2bfc660
 
57f7f52
2bfc660
 
 
 
57f7f52
2bfc660
 
57f7f52
2bfc660
 
 
 
57f7f52
2bfc660
 
57f7f52
 
 
2bfc660
57f7f52
18bcd78
2bfc660
 
75153af
 
2bfc660
75153af
 
2bfc660
57f7f52
 
 
 
2bfc660
57f7f52
 
 
 
2bfc660
 
57f7f52
 
2bfc660
 
57f7f52
2bfc660
57f7f52
 
2bfc660
57f7f52
 
 
 
 
2bfc660
57f7f52
2bfc660
 
57f7f52
2bfc660
57f7f52
2bfc660
57f7f52
 
2bfc660
57f7f52
75153af
57f7f52
 
2bfc660
57f7f52
18bcd78
2bfc660
 
 
 
 
57f7f52
 
 
18bcd78
594aeee
57f7f52
 
 
2bfc660
 
 
 
 
 
 
 
 
57f7f52
2bfc660
 
 
2b8223d
2bfc660
2b8223d
2bfc660
 
 
2b8223d
2bfc660
594aeee
 
 
 
 
 
 
 
 
 
 
 
 
2b8223d
2bfc660
2b8223d
2bfc660
 
 
57f7f52
2b8223d
57f7f52
2bfc660
 
 
 
 
 
 
594aeee
2bfc660
 
 
2b8223d
 
2bfc660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57f7f52
 
2b8223d
 
 
 
 
75153af
2bfc660
 
2b8223d
 
 
 
57f7f52
2bfc660
 
 
 
 
57f7f52
2b8223d
 
 
 
75153af
2bfc660
2b8223d
 
 
 
 
 
 
 
 
 
2bfc660
 
 
2b8223d
 
2bfc660
 
 
 
 
 
 
 
 
 
57f7f52
75153af
2bfc660
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
import gradio as gr
import torch
import gc
import time
import logging
from transformers import (
    pipeline,
    AutoProcessor,
    AutoModelForSpeechSeq2Seq,
    AutoModelForCTC,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class MultiASRApp:
    def __init__(self):
        self.pipe = None
        self.current_model = None
        self.current_kind = None  # "whisper" | "ctc"

        self.available_models = [
            "openai/whisper-tiny",
            "openai/whisper-base",
            "openai/whisper-small",
            "openai/whisper-medium",
            "openai/whisper-large-v2",
            "openai/whisper-large-v3",
            "ilsp/whisper_greek_dialect_of_lesbos",
            "ilsp/xls-r-greek-cretan",
        ]

    # ------------------------
    # Model detection
    # ------------------------
    def detect_model_kind(self, model_name):
        if "xls-r" in model_name.lower() or "xlsr" in model_name.lower():
            return "ctc"
        return "whisper"

    def is_fine_tuned_whisper(self, model_name):
        return "ilsp/" in model_name.lower() and "whisper" in model_name.lower()

    # ------------------------
    # Device & dtype
    # ------------------------
    def pick_device(self, conservative=True):
        if torch.cuda.is_available():
            return "cuda:0", torch.float32 if conservative else torch.float16
        return "cpu", torch.float32

    # ------------------------
    # Pipeline creation
    # ------------------------
    def create_whisper_pipe(self, model_name):
        conservative = self.is_fine_tuned_whisper(model_name)
        device, dtype = self.pick_device(conservative)

        try:
            model = WhisperForConditionalGeneration.from_pretrained(
                model_name,
                torch_dtype=dtype,
                low_cpu_mem_usage=True,
            )
            processor = WhisperProcessor.from_pretrained(model_name)
        except Exception:
            model = AutoModelForSpeechSeq2Seq.from_pretrained(
                model_name,
                torch_dtype=dtype,
                low_cpu_mem_usage=True,
            )
            processor = AutoProcessor.from_pretrained(model_name)

        model.to(device)

        return pipeline(
            "automatic-speech-recognition",
            model=model,
            tokenizer=processor.tokenizer,
            feature_extractor=processor.feature_extractor,
            device=device,
            torch_dtype=dtype,
            chunk_length_s=30,
        )

    def create_ctc_pipe(self, model_name):
        device, dtype = self.pick_device(conservative=True)

        processor = AutoProcessor.from_pretrained(model_name)
        model = AutoModelForCTC.from_pretrained(
            model_name,
            torch_dtype=dtype,
            low_cpu_mem_usage=True,
        )
        model.to(device)

        return pipeline(
            "automatic-speech-recognition",
            model=model,
            tokenizer=getattr(processor, "tokenizer", None),
            feature_extractor=getattr(processor, "feature_extractor", None),
            device=device,
            torch_dtype=dtype,
            chunk_length_s=20,
            stride_length_s=(4, 2),
        )

    def load_model(self, model_name):
        if self.current_model == model_name and self.pipe is not None:
            return True

        self.clear_model()
        kind = self.detect_model_kind(model_name)

        try:
            if kind == "ctc":
                self.pipe = self.create_ctc_pipe(model_name)
            else:
                self.pipe = self.create_whisper_pipe(model_name)

            self.current_model = model_name
            self.current_kind = kind
            return True
        except Exception as e:
            logger.error(e, exc_info=True)
            self.clear_model()
            return False

    def clear_model(self):
        if self.pipe is not None:
            del self.pipe
        self.pipe = None
        self.current_model = None
        self.current_kind = None
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        gc.collect()

    # ------------------------
    # Transcription
    # ------------------------
    def transcribe(self, audio, model_name):
        if audio is None:
            return "Ανέβασε ένα ηχητικό αρχείο.", ""

        start = time.time()
        if not self.load_model(model_name):
            return "Σφάλμα φόρτωσης μοντέλου.", ""

        # 🔒 FORCE GREEK FOR ALL WHISPER MODELS
        if self.current_kind == "whisper":
            result = self.pipe(
                audio,
                generate_kwargs={
                    "language": "greek",
                    "task": "transcribe",
                },
            )
        else:
            # XLS-R (CTC)
            result = self.pipe(audio)

        text = result.get("text", "")

        info = (
            f"Μοντέλο: {model_name}\n"
            f"Χρόνος επεξεργασίας: {time.time() - start:.2f} δευτ."
        )

        return text.strip(), info

    def status(self):
        if not self.current_model:
            return "Δεν έχει φορτωθεί μοντέλο"
        return f"✔ {self.current_model}"


# ------------------------
# Gradio App
# ------------------------
app = MultiASRApp()

def run(audio, model):
    return app.transcribe(audio, model)

def status():
    return app.status()


with gr.Blocks(title="Ίντα λαλείς;", theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
# Ίντα λαλείς;
## Η Τεχνητή Νοημοσύνη μαθαίνει ελληνικές διαλέκτους

🎧 Ανέβασε ένα ηχητικό αρχείο και δες πώς η Τεχνητή Νοημοσύνη
αναγνωρίζει την ελληνική γλώσσα και τις διαλέκτους της.

📍 Athens Science Festival 2025  
🏛 Ωδείο Αθηνών | 18–21 Δεκεμβρίου 2025
"""
    )

    model_status = gr.Textbox(
        label="Κατάσταση μοντέλου",
        value=status(),
        interactive=False,
    )

    with gr.Row():
        with gr.Column():
            audio = gr.Audio(
                label="🎵 Ανέβασε ηχητικό αρχείο",
                type="filepath",
            )

            model = gr.Dropdown(
                choices=app.available_models,
                value="openai/whisper-small",
                label="Μοντέλο αναγνώρισης ομιλίας",
            )

            btn = gr.Button(
                "🗣️ Μετατροπή ομιλίας σε κείμενο",
                variant="primary",
            )

        with gr.Column():
            text_out = gr.Textbox(
                label="📄 Κείμενο",
                lines=8,
                show_copy_button=True,
            )

            info_out = gr.Textbox(
                label="Πληροφορίες",
                lines=4,
            )

    btn.click(
        run,
        inputs=[audio, model],
        outputs=[text_out, info_out],
    )

    model.change(lambda _: status(), outputs=model_status)

    gr.Markdown(
        """
🔬 Έρευνα & τεχνολογία για τη γλωσσική ποικιλία  
🎙️ Η φωνή ως πολιτιστική κληρονομιά
"""
    )

if __name__ == "__main__":
    demo.launch()