badrex's picture
Update app.py
6f55dac verified
raw
history blame
2.63 kB
import gradio as gr
from transformers import pipeline
import os
import numpy as np
import spaces
print("=== Application Starting ===")
# define dialect mapping
dialect_mapping = {
"MSA": "Modern Standard Arabic (MSA) - العربية الفصحى الحديثة",
"Egyptian": "Egyptian Arabic - اللهجة المصرية العامية",
"Gulf": "Peninsular Arabic - لهجة الجزيرة العربية",
"Levantine": "Levantine Arabic - لهجة بلاد الشام",
"Maghrebi": "Maghrebi Arabic - اللهجة المغاربية"
}
@spaces.GPU
def predict_dialect(audio):
# load model inside the GPU function
print("Loading model on GPU...")
model_id = "badrex/mms-300m-arabic-dialect-identifier"
classifier = pipeline("audio-classification", model=model_id) # no device specified
print("Model loaded successfully")
if audio is None:
return {"Error": 1.0}
sr, audio_array = audio
if len(audio_array.shape) > 1:
audio_array = audio_array.mean(axis=1)
if audio_array.dtype != np.float32:
if audio_array.dtype == np.int16:
audio_array = audio_array.astype(np.float32) / 32768.0
else:
audio_array = audio_array.astype(np.float32)
print(f"Processing audio: sample rate={sr}, shape={audio_array.shape}")
# classify the dialect
predictions = classifier({"sampling_rate": sr, "raw": audio_array})
# format results
results = {}
for pred in predictions:
dialect_name = dialect_mapping.get(pred['label'], pred['label'])
results[dialect_name] = float(pred['score'])
return results
# prepare examples
examples = []
examples_dir = "examples"
if os.path.exists(examples_dir):
for filename in os.listdir(examples_dir):
if filename.endswith((".wav", ".mp3", ".ogg")):
examples.append([os.path.join(examples_dir, filename)])
print(f"Found {len(examples)} example files")
description = """
By <a href="https://badrex.github.io/">Badr Alabsi</a> with ❤️🤍💚
This demo uses a Transformer-based model for Spoken Arabic Dialect Identification.
Upload an audio file or record yourself speaking to identify the Arabic dialect!
"""
demo = gr.Interface(
fn=predict_dialect,
inputs=gr.Audio(),
outputs=gr.Label(num_top_classes=5, label="Predicted Dialect"),
title="Tamyïz 🍉 Arabic Dialect Identification in Speech",
description=description,
examples=examples if examples else None,
cache_examples=False,
flagging_mode=None
)
print("=== Launching demo ===")
demo.launch()