import asyncio import httpx # type: ignore import os import json from dotenv import load_dotenv # type: ignore # Optional: You might need to install these: # pip install nemo_toolkit[asr] torch torchaudio try: from nemo.collections.asr.models import SortformerEncLabelModel # type: ignore NEMO_AVAILABLE = True except ImportError: NEMO_AVAILABLE = False print("Warning: NeMo toolkit not found. Please install using: pip install nemo_toolkit[asr]") load_dotenv('backend/.env') SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "") async def get_sarvam_transcription(audio_file_path): """ Calls Sarvam AI real-time API with timestamps enabled """ try: with open(audio_file_path, "rb") as f: audio_data = f.read() print("Fetching transcription from Sarvam AI...") async with httpx.AsyncClient(timeout=120) as client: resp = await client.post( "https://api.sarvam.ai/speech-to-text", headers={"api-subscription-key": SARVAM_API_KEY}, files={"file": ("audio.wav", audio_data, "audio/wav")}, data={ "model": "saaras:v4", # Update model if needed "mode": "codemix", "with_timestamps": "true", "with_diarization": "false", # Diarization is done locally } ) if resp.status_code != 200: print("Sarvam API Error:", resp.status_code, resp.text) return None print("Successfully fetched transcription.") return resp.json() except Exception as e: print(f"Exception during Sarvam API call: {e}") return None def get_nemo_diarization(audio_file_path): """ Runs NVIDIA Sortformer for Speaker Diarization locally """ if not NEMO_AVAILABLE: print("Cannot run diarization. NeMo is not installed.") return [] print("Loading NVIDIA Sortformer model...") # Load the pre-trained Sortformer model diar_model = SortformerEncLabelModel.from_pretrained("nvidia/diar_sortformer_4spk-v1").eval() print("Running diarization...") predicted_segments = diar_model.diarize(audio=[audio_file_path], batch_size=1) # Extract segments for the first file # Format of segment in predicted_segments[0]: [start_time, end_time, speaker_id] if isinstance(predicted_segments, tuple): predicted_segments = predicted_segments[0] return predicted_segments[0] if len(predicted_segments) > 0 else [] def align_transcription_and_diarization(sarvam_data, nemo_segments): """ Aligns the word-level timestamps from Sarvam API with the speaker segments from NeMo """ if not sarvam_data or 'words' not in sarvam_data: print("No words found in Sarvam transcription.") return words = sarvam_data['words'] aligned_transcript = [] print("\n--- Merged Output ---") current_speaker = None speaker_sentence = [] for word_info in words: word = word_info.get('word', '') word_start = word_info.get('start_time', 0) word_end = word_info.get('end_time', 0) # Find which speaker was speaking during this word's time assigned_speaker = "Unknown" for segment in nemo_segments: seg_start, seg_end, spk_id = segment # Simple overlap check: if the midpoint of the word falls in the segment midpoint = (word_start + word_end) / 2 if seg_start <= midpoint <= seg_end: assigned_speaker = f"Speaker {int(spk_id)}" break # Group words by speaker for clean display if assigned_speaker != current_speaker: if current_speaker is not None: print(f"[{current_speaker}]: {' '.join(speaker_sentence)}") current_speaker = assigned_speaker speaker_sentence = [word] else: speaker_sentence.append(word) # Print the last sentence if current_speaker is not None and speaker_sentence: print(f"[{current_speaker}]: {' '.join(speaker_sentence)}") async def main(): audio_path = "backend/test.wav" # Ensure this path is correct if not os.path.exists(audio_path): # Fallback to test.wav in current directory audio_path = "test.wav" if not os.path.exists(audio_path): print(f"Audio file '{audio_path}' not found!") return # 1. Run Sarvam API sarvam_result = await get_sarvam_transcription(audio_path) # 2. Run Local NVIDIA Model nemo_segments = get_nemo_diarization(audio_path) # 3. Align and Print Result if sarvam_result and nemo_segments: align_transcription_and_diarization(sarvam_result, nemo_segments) else: print("Could not complete alignment due to missing data.") if __name__ == "__main__": asyncio.run(main())