Spaces:
Build error
Build error
V22
Browse files5 unmodified lines6789101112131415161718192021222324252627282930313233345 unmodified lines40414243444546475 unmodified lines53545556575859606162636465666768697071727312 unmodified lines868788899091929394959697981 unmodified line10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614721 unmodified lines1691701711721731741751761771781791801811821831841851862 unmodified lines1891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922935 unmodified linesAutoProcessor,AutoModelForCTC,AutoModel,)import librosaimport numpy as npfrom jiwer import wer, cerimport time# Model configurationsMODEL_CONFIGS = {"AudioX-North (Jivi AI)": {"repo": "jiviai/audioX-north-v1","model_type": "seq2seq","description": "Supports Hindi, Gujarati, Marathi",},"IndicConformer (AI4Bharat)": {"repo": "ai4bharat/indic-conformer-600m-multilingual","model_type": "ctc_rnnt","description": "Supports 22 Indian languages","trust_remote_code": True,},"MMS (Facebook)": {"repo": "facebook/mms-1b-all","model_type": "ctc","description": "Supports over 1,400 languages (fine-tuning recommended)",},}5 unmodified linestrust_remote_code = config.get("trust_remote_code", False)try:if model_name == "IndicConformer (AI4Bharat)":# Use the working method for AI4Bharat modelprint(f"Loading {model_name}...")try:model = AutoModel.from_pretrained(5 unmodified linesexcept Exception as e1:print(f"Primary loading failed, trying fallback: {e1}")model = AutoModel.from_pretrained(repo, trust_remote_code=True)# AI4Bharat doesn't use a traditional processorprocessor = Nonereturn model, processor, model_typeelif model_name == "MMS (Facebook)":model = AutoModelForCTC.from_pretrained(repo)processor = AutoProcessor.from_pretrained(repo)else: # AudioX-Northprocessor = AutoProcessor.from_pretrained(repo, trust_remote_code=trust_remote_code)if model_type == "seq2seq":model = AutoModelForSpeechSeq2Seq.from_pretrained(repo, trust_remote_code=trust_remote_code)else:model = AutoModelForCTC.from_pretrained(repo, trust_remote_code=trust_remote_code)return model, processor, model_typeexcept Exception as e:return None, None, f"Error loading model: {str(e)}"12 unmodified linesreturn None, None, None, None# Main transcription functiondef transcribe_audio(audio_file, selected_models, reference_text=""):if not audio_file:return "Please upload an audio file.", [], ""if not selected_models:return "Please select at least one model.", [], ""table_data = []try:# Load and preprocess audio once1 unmodified lineaudio_duration = len(audio) / srfor model_name in selected_models:model, processor, model_type = load_model_and_processor(model_name)if isinstance(model_type, str) and model_type.startswith("Error"):table_data.append([model_name,f"Error: {model_type}","-","-","-","-"])continuestart_time = time.time()# Handle different model typestry:if model_name == "IndicConformer (AI4Bharat)":# Use AI4Bharat specific processingwav = torch.from_numpy(audio).unsqueeze(0) # Add batch dimensionif torch.max(torch.abs(wav)) > 0:wav = wav / torch.max(torch.abs(wav)) # Normalizewith torch.no_grad():# Default to Hindi and RNNT for AI4Bharattranscription = model(wav, "hi", "rnnt")if isinstance(transcription, list):transcription = transcription[0] if transcription else ""transcription = str(transcription).strip()else:# Standard processing for other modelsinputs = processor(audio, sampling_rate=16000, return_tensors="pt")with torch.no_grad():if model_type == "seq2seq":input_features = inputs["input_features"]outputs = model.generate(input_features)transcription = processor.batch_decode(outputs, skip_special_tokens=True)[0]else: # CTC or RNNTinput_values = inputs["input_values"]logits = model(input_values).logitspredicted_ids = torch.argmax(logits, dim=-1)transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]except Exception as e:transcription = f"Processing error: {str(e)}"21 unmodified lines])# Create summary textsummary = f"**Audio Duration:** {audio_duration:.2f}s\n"summary += f"**Models Tested:** {len(selected_models)}\n"if reference_text:summary += f"**Reference Text:** {reference_text[:100]}{'...' if len(reference_text) > 100 else ''}\n"# Create copyable text outputcopyable_text = "SPEECH-TO-TEXT BENCHMARK RESULTS\n" + "="*50 + "\n\n"copyable_text += f"Audio Duration: {audio_duration:.2f}s\n"copyable_text += f"Models Tested: {len(selected_models)}\n"if reference_text:copyable_text += f"Reference Text: {reference_text}\n"copyable_text += "\n" + "-"*50 + "\n\n"for i, row in enumerate(table_data):copyable_text += f"MODEL {i+1}: {row[0]}\n"2 unmodified linescopyable_text += f"CER: {row[3]}\n"copyable_text += f"RTF: {row[4]}\n"copyable_text += f"Time Taken: {row[5]}\n"copyable_text += "\n" + "-"*30 + "\n\n"return summary, table_data, copyable_textexcept Exception as e:error_msg = f"Error during transcription: {str(e)}"return error_msg, [], error_msg# Create Gradio interface with blocks for better controldef create_interface():model_choices = list(MODEL_CONFIGS.keys())with gr.Blocks(title="Multilingual Speech-to-Text Benchmark", css=""".paste-button { margin: 5px 0; }.copy-area { font-family: monospace; font-size: 12px; }""") as iface:gr.Markdown("""# Multilingual Speech-to-Text BenchmarkUpload an audio file, select one or more models, and optionally provide reference text.The app benchmarks WER, CER, RTF, and Time Taken for each model.""")with gr.Row():with gr.Column(scale=1):audio_input = gr.Audio(label="Upload Audio File (16kHz recommended)",type="filepath")model_selection = gr.CheckboxGroup(choices=model_choices,label="Select Models",value=[model_choices[0]], # Default to first modelinteractive=True)# Enhanced reference text input with paste functionalitywith gr.Group():gr.Markdown("### Reference Text (Optional for WER/CER)")reference_input = gr.Textbox(label="Reference Text (optional, paste supported)",placeholder="Paste reference transcription here...",lines=4,interactive=True)submit_btn = gr.Button("🚀 Transcribe", variant="primary", size="lg")with gr.Column(scale=2):summary_output = gr.Markdown(label="Summary", value="Upload an audio file and select models to begin...")results_table = gr.Dataframe(headers=["Model", "Transcription", "WER", "CER", "RTF", "Time Taken"],datatype=["str", "str", "str", "str", "str", "str"],label="Results Comparison",interactive=False,wrap=True,column_widths=[150, 400, 80, 80, 80, 100])# Copyable results sectionwith gr.Group():gr.Markdown("### 📋 Copy Results")copyable_output = gr.Textbox(label="Copy-Paste Friendly Results",lines=15,max_lines=30,show_copy_button=True,interactive=False,elem_classes="copy-area",placeholder="Results will appear here in copy-paste friendly format...")# Connect the functionsubmit_btn.click(fn=transcribe_audio,inputs=[audio_input, model_selection, reference_input],outputs=[summary_output, results_table, copyable_output])# Also allow triggering on Enter in reference textreference_input.submit(fn=transcribe_audio,inputs=[audio_input, model_selection, reference_input],outputs=[summary_output, results_table, copyable_output])# Add example and instructionsgr.Markdown("""---### 💡 Tips:- **Reference Text**: Paste your ground truth text to calculate WER/CER metrics- **Copy Results**: Use the copy button in the results section to copy formatted results- **AI4Bharat Model**: Automatically uses Hindi language with RNNT decoding- **Supported Formats**: WAV, MP3, FLAC, M4A (16kHz recommended for best results)""")return iface5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778795 unmodified lines858687888990915 unmodified lines97989910010110210310410510610710810911011111211311411511611712 unmodified lines1301311321331341351361371381391401411421431441451461471481491 unmodified line15115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321 unmodified lines2352362372382392402412422432442452462472482492502512522532542552 unmodified lines2582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054065 unmodified linesAutoProcessor,AutoModelForCTC,AutoModel,WhisperProcessor,WhisperForConditionalGeneration,)import librosaimport numpy as npfrom jiwer import wer, cerimport time# Language configurationsLANGUAGE_CONFIGS = {"Hindi (हिंदी)": {"code": "hi","script": "Devanagari","models": ["AudioX-North", "IndicConformer", "MMS"]},"Gujarati (ગુજરાતી)": {"code": "gu","script": "Gujarati","models": ["AudioX-North", "IndicConformer", "MMS"]},"Marathi (मराठी)": {"code": "mr","script": "Devanagari","models": ["AudioX-North", "IndicConformer", "MMS"]},"Tamil (தமிழ்)": {"code": "ta","script": "Tamil","models": ["AudioX-South", "IndicConformer", "MMS"]},"Telugu (తెలుగు)": {"code": "te","script": "Telugu","models": ["AudioX-South", "IndicConformer", "MMS"]},"Kannada (ಕನ್ನಡ)": {"code": "kn","script": "Kannada","models": ["AudioX-South", "IndicConformer", "MMS"]}}# Model configurationsMODEL_CONFIGS = {"AudioX-North": {"repo": "jiviai/audioX-north-v1","model_type": "whisper","description": "Supports Hindi, Gujarati, Marathi","languages": ["hi", "gu", "mr"]},"AudioX-South": {"repo": "jiviai/audioX-south-v1","model_type": "whisper","description": "Supports Tamil, Telugu, Kannada, Malayalam","languages": ["ta", "te", "kn", "ml"]},"IndicConformer": {"repo": "ai4bharat/indic-conformer-600m-multilingual","model_type": "ctc_rnnt","description": "Supports 22 Indian languages","trust_remote_code": True,"languages": ["hi", "gu", "mr", "ta", "te", "kn", "ml", "bn", "pa", "or", "as", "ur"]},"MMS": {"repo": "facebook/mms-1b-all","model_type": "ctc","description": "Supports 1,400+ languages","languages": ["hi", "gu", "mr", "ta", "te", "kn", "ml"]},}5 unmodified linestrust_remote_code = config.get("trust_remote_code", False)try:if model_name == "IndicConformer":print(f"Loading {model_name}...")try:model = AutoModel.from_pretrained(5 unmodified linesexcept Exception as e1:print(f"Primary loading failed, trying fallback: {e1}")model = AutoModel.from_pretrained(repo, trust_remote_code=True)processor = Nonereturn model, processor, model_typeelif model_name in ["AudioX-North", "AudioX-South"]:# Use Whisper processor and model for AudioX variantsprocessor = WhisperProcessor.from_pretrained(repo)model = WhisperForConditionalGeneration.from_pretrained(repo)model.config.forced_decoder_ids = Nonereturn model, processor, model_typeelif model_name == "MMS":model = AutoModelForCTC.from_pretrained(repo)processor = AutoProcessor.from_pretrained(repo)return model, processor, model_typeexcept Exception as e:return None, None, f"Error loading model: {str(e)}"12 unmodified linesreturn None, None, None, None# Main transcription functiondef transcribe_audio(audio_file, selected_language, selected_models, reference_text=""):if not audio_file:return "Please upload an audio file.", [], ""if not selected_models:return "Please select at least one model.", [], ""if not selected_language:return "Please select a language.", [], ""# Get language infolang_info = LANGUAGE_CONFIGS[selected_language]lang_code = lang_info["code"]table_data = []try:# Load and preprocess audio once1 unmodified lineaudio_duration = len(audio) / srfor model_name in selected_models:# Check if model supports the selected languageif model_name.replace("AudioX-", "AudioX-") not in lang_info["models"]:table_data.append([model_name,f"Language {selected_language} not supported by this model","-", "-", "-", "-"])continuemodel, processor, model_type = load_model_and_processor(model_name)if isinstance(model_type, str) and model_type.startswith("Error"):table_data.append([model_name,f"Error: {model_type}","-", "-", "-", "-"])continuestart_time = time.time()try:if model_name == "IndicConformer":# AI4Bharat specific processingwav = torch.from_numpy(audio).unsqueeze(0)if torch.max(torch.abs(wav)) > 0:wav = wav / torch.max(torch.abs(wav))with torch.no_grad():transcription = model(wav, lang_code, "rnnt")if isinstance(transcription, list):transcription = transcription[0] if transcription else ""transcription = str(transcription).strip()elif model_name in ["AudioX-North", "AudioX-South"]:# AudioX Whisper-based processingif sr != 16000:audio = librosa.resample(audio, orig_sr=sr, target_sr=16000)input_features = processor(audio, sampling_rate=16000, return_tensors="pt").input_featureswith torch.no_grad():predicted_ids = model.generate(input_features,task="transcribe",language=lang_code)transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]else: # MMS# Standard CTC processing for MMSinputs = processor(audio, sampling_rate=16000, return_tensors="pt")with torch.no_grad():input_values = inputs["input_values"]logits = model(input_values).logitspredicted_ids = torch.argmax(logits, dim=-1)transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]except Exception as e:transcription = f"Processing error: {str(e)}"21 unmodified lines])# Create summary textsummary = f"**Language:** {selected_language} ({lang_code})\n"summary += f"**Audio Duration:** {audio_duration:.2f}s\n"summary += f"**Models Tested:** {len(selected_models)}\n"if reference_text:summary += f"**Reference Text:** {reference_text[:100]}{'...' if len(reference_text) > 100 else ''}\n"# Create copyable text outputcopyable_text = "MULTILINGUAL SPEECH-TO-TEXT BENCHMARK RESULTS\n" + "="*55 + "\n\n"copyable_text += f"Language: {selected_language} ({lang_code})\n"copyable_text += f"Script: {lang_info['script']}\n"copyable_text += f"Audio Duration: {audio_duration:.2f}s\n"copyable_text += f"Models Tested: {len(selected_models)}\n"if reference_text:copyable_text += f"Reference Text: {reference_text}\n"copyable_text += "\n" + "-"*55 + "\n\n"for i, row in enumerate(table_data):copyable_text += f"MODEL {i+1}: {row[0]}\n"2 unmodified linescopyable_text += f"CER: {row[3]}\n"copyable_text += f"RTF: {row[4]}\n"copyable_text += f"Time Taken: {row[5]}\n"copyable_text += "\n" + "-"*35 + "\n\n"return summary, table_data, copyable_textexcept Exception as e:error_msg = f"Error during transcription: {str(e)}"return error_msg, [], error_msg# Create Gradio interfacedef create_interface():language_choices = list(LANGUAGE_CONFIGS.keys())with gr.Blocks(title="Multilingual Speech-to-Text Benchmark", css=""".language-info { background: #f0f8ff; padding: 10px; border-radius: 5px; margin: 10px 0; }.copy-area { font-family: monospace; font-size: 12px; }""") as iface:gr.Markdown("""# 🌏 Multilingual Speech-to-Text BenchmarkCompare ASR models across **6 Indian Languages** with comprehensive metrics.**Supported Languages:** Hindi, Gujarati, Marathi, Tamil, Telugu, Kannada""")with gr.Row():with gr.Column(scale=1):# Language selectionlanguage_selection = gr.Dropdown(choices=language_choices,label="🗣️ Select Language",value=language_choices[0],interactive=True)audio_input = gr.Audio(label="📹 Upload Audio File (16kHz recommended)",type="filepath")# Dynamic model selection based on languagemodel_selection = gr.CheckboxGroup(choices=["AudioX-North", "IndicConformer", "MMS"],label="🤖 Select Models",value=["AudioX-North", "IndicConformer"],interactive=True)reference_input = gr.Textbox(label="📝 Reference Text (optional, paste supported)",placeholder="Paste reference transcription here...",lines=4,interactive=True)submit_btn = gr.Button("🚀 Run Multilingual Benchmark", variant="primary", size="lg")with gr.Column(scale=2):summary_output = gr.Markdown(label="📊 Summary",value="Select language, upload audio file and choose models to begin...")results_table = gr.Dataframe(headers=["Model", "Transcription", "WER", "CER", "RTF", "Time"],datatype=["str", "str", "str", "str", "str", "str"],label="🏆 Results Comparison",interactive=False,wrap=True,column_widths=[120, 350, 60, 60, 60, 80])# Copyable results sectionwith gr.Group():gr.Markdown("### 📋 Export Results")copyable_output = gr.Textbox(label="Copy-Paste Friendly Results",lines=12,max_lines=25,show_copy_button=True,interactive=False,elem_classes="copy-area",placeholder="Benchmark results will appear here...")# Update model choices based on language selectiondef update_model_choices(selected_language):if not selected_language:return gr.CheckboxGroup(choices=[], value=[])lang_info = LANGUAGE_CONFIGS[selected_language]available_models = lang_info["models"]# Map display namesmodel_map = {"AudioX-North": "AudioX-North","AudioX-South": "AudioX-South","IndicConformer": "IndicConformer","MMS": "MMS"}available_choices = [model_map[model] for model in available_models if model in model_map]default_selection = available_choices[:2] if len(available_choices) >= 2 else available_choicesreturn gr.CheckboxGroup(choices=available_choices, value=default_selection)# Connect language selection to model updateslanguage_selection.change(fn=update_model_choices,inputs=[language_selection],outputs=[model_selection])# Connect the main functionsubmit_btn.click(fn=transcribe_audio,inputs=[audio_input, language_selection, model_selection, reference_input],outputs=[summary_output, results_table, copyable_output])reference_input.submit(fn=transcribe_audio,inputs=[audio_input, language_selection, model_selection, reference_input],outputs=[summary_output, results_table, copyable_output])# Language information displaygr.Markdown("""---### 🔤 Language & Model Support Matrix| Language | Script | AudioX-North | AudioX-South | IndicConformer | MMS ||----------|---------|-------------|-------------|---------------|-----|| Hindi | Devanagari | ✅ | ❌ | ✅ | ✅ || Gujarati | Gujarati | ✅ | ❌ | ✅ | ✅ || Marathi | Devanagari | ✅ | ❌ | ✅ | ✅ || Tamil | Tamil | ❌ | ✅ | ✅ | ✅ || Telugu | Telugu | ❌ | ✅ | ✅ | ✅ || Kannada | Kannada | ❌ | ✅ | ✅ | ✅ |### 💡 Tips:- **Models auto-filter** based on selected language- **Reference Text**: Enable WER/CER calculation by providing ground truth- **Copy Results**: Export formatted results using the copy button- **Best Performance**: Use AudioX models for their specialized languages""")return iface
app.py+202-89