Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404 unmodified lines45464748495051525354552 unmodified lines5859606162636465666768697071import gradio as grfrom gtts import gTTSimport timeimport difflibimport tempfileimport osimport speech_recognition as srfrom faster_whisper import WhisperModel# Function to play the text (optional)def play_text(text):tts = gTTS(text=text, lang='hi', slow=False)temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')tts.save(temp_file.name)os.system(f"start {temp_file.name}") # Windowsreturn "✅ Text is being read out. Please listen and read it yourself."# Load model once (outside function for efficiency)model = WhisperModel("small", compute_type="float32") # Or "medium" for better accuracydef transcribe_audio(audio, original_text):try:# Run inferencesegments, info = model.transcribe(audio, language='hi')transcription = " ".join([segment.text for segment in segments])# Clean and split the text betterimport reoriginal_words = re.findall(r'\w+', original_text.strip())transcribed_words = re.findall(r'\w+', transcription.strip())matcher = difflib.SequenceMatcher(None, original_words, transcribed_words)accuracy = round(matcher.ratio() * 100, 2)# Speaking speed (approximate)speed = round(len(transcribed_words) / info.duration, 2)result = {"📝 Transcribed Text": transcription,4 unmodified linesexcept Exception as e:return {"error": str(e)}# Gradio Appwith gr.Blocks() as app:gr.Markdown("## 🗣️ Hindi Reading & Pronunciation Practice App")with gr.Row():input_text = gr.Textbox(label="Paste Hindi Text Here", placeholder="यहाँ हिंदी टेक्स्ट लिखें...")play_button = gr.Button("🔊 Listen to Text")2 unmodified linesgr.Markdown("### 🎤 Now upload or record yourself reading the text aloud below:")audio_input = gr.Audio(type="filepath", label="Upload or Record Your Voice")submit_button = gr.Button("✅ Submit Recording for Checking")output = gr.JSON(label="Results")submit_button.click(transcribe_audio, inputs=[audio_input, input_text], outputs=[output])# Launch the appapp.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051524 unmodified lines5758596061626364652 unmodified lines68697071727374757677import gradio as grfrom gtts import gTTSimport tempfileimport osimport difflibimport torchimport refrom transformers import Wav2Vec2ForCTC, Wav2Vec2Processorimport torchaudio# Load AI4Bharat Hindi model & processorMODEL_NAME = "ai4bharat/indicwav2vec-hindi"processor = Wav2Vec2Processor.from_pretrained(MODEL_NAME)model = Wav2Vec2ForCTC.from_pretrained(MODEL_NAME)def play_text(text):tts = gTTS(text=text, lang='hi', slow=False)temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')tts.save(temp_file.name)# Windows: "start", Mac: "afplay", Linux: "mpg123" (edit as needed)os.system(f"start {temp_file.name}")return "✅ Text is being read out. Please listen and read it yourself."def transcribe_audio(audio_path, original_text):try:# 1. Load audio & convert to mono, 16kHz if neededwaveform, sample_rate = torchaudio.load(audio_path)if waveform.shape[0] > 1:waveform = waveform.mean(dim=0, keepdim=True)if sample_rate != 16000:transform = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)waveform = transform(waveform)input_values = processor(waveform.squeeze().numpy(), sampling_rate=16000, return_tensors="pt").input_values# 2. Transcribe with AI4Bharat modelwith torch.no_grad():logits = model(input_values).logitspredicted_ids = torch.argmax(logits, dim=-1)transcription = processor.decode(predicted_ids[0])# 3. Calculate accuracy etc.original_words = re.findall(r'\w+', original_text.strip())transcribed_words = re.findall(r'\w+', transcription.strip())matcher = difflib.SequenceMatcher(None, original_words, transcribed_words)accuracy = round(matcher.ratio() * 100, 2)# Speaking speed approximation (needs duration, which torchaudio gives)duration = waveform.shape[1] / 16000speed = round(len(transcribed_words) / duration, 2) if duration > 0 else 0result = {"📝 Transcribed Text": transcription,4 unmodified linesexcept Exception as e:return {"error": str(e)}with gr.Blocks() as app:gr.Markdown("## 🗣️ Hindi Reading & Pronunciation Practice App (AI4Bharat Model)")with gr.Row():input_text = gr.Textbox(label="Paste Hindi Text Here", placeholder="यहाँ हिंदी टेक्स्ट लिखें...")play_button = gr.Button("🔊 Listen to Text")2 unmodified linesgr.Markdown("### 🎤 Now upload or record yourself reading the text aloud below:")audio_input = gr.Audio(type="filepath", label="Upload or Record Your Voice")submit_button = gr.Button("✅ Submit Recording for Checking")output = gr.JSON(label="Results")submit_button.click(transcribe_audio, inputs=[audio_input, input_text], outputs=[output])app.launch()
app.py+34-28