Files

138 lines
4.7 KiB
Python

import os
import json
import urllib.request
import asyncio
SARVAM_API_KEY = None
if os.path.exists('.env'):
with open('.env', encoding='utf-8') as f:
for line in f:
if line.startswith('SARVAM_API_KEY='):
SARVAM_API_KEY = line.strip().split('=', 1)[1].strip('"\' ')
async def main():
audio_file = "test.wav"
if not os.path.exists(audio_file):
print(f"File {audio_file} not found. Trying dummy.wav...")
audio_file = "dummy.wav"
if not os.path.exists(audio_file):
print("No audio file found!")
return
print(f"Processing {audio_file} with Sarvam API...")
with open(audio_file, "rb") as f:
audio_data = f.read()
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
body = (
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="file"; filename="audio.wav"\r\n'
f'Content-Type: audio/wav\r\n\r\n'
).encode('utf-8') + audio_data + (
f'\r\n--{boundary}\r\n'
f'Content-Disposition: form-data; name="model"\r\n\r\n'
f'saaras:v4\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="mode"\r\n\r\n'
f'translate\r\n'
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="with_diarization"\r\n\r\n'
f'true\r\n'
f'--{boundary}--\r\n'
).encode('utf-8')
req = urllib.request.Request(
"https://api.sarvam.ai/speech-to-text",
data=body,
headers={
"api-subscription-key": SARVAM_API_KEY or "",
"Content-Type": f"multipart/form-data; boundary={boundary}"
}
)
try:
with urllib.request.urlopen(req) as resp:
res = json.loads(resp.read().decode('utf-8'))
except Exception as e:
print("Sarvam API Error:", e)
return
print("Sarvam API Error:", resp.status_code, resp.text)
# Let's try just speech-to-text if translate fails
print("Falling back to speech-to-text...")
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",
"with_diarization": "true"
}
)
if resp.status_code != 200:
print("Fallback Sarvam API Error:", resp.status_code, resp.text)
return
res = resp.json()
print("\n--- Sarvam Output ---\n")
# Determine format
transcript_text = res.get("transcript", "")
print("Transcript:", transcript_text)
# Diarization logic might be in "words" array or "transcript" format
conversation = transcript_text
if "words" in res and res["words"]:
words = res["words"]
current_speaker = None
sentences = []
current_sentence = []
for w in words:
speaker = w.get("speaker", "Unknown")
word = w.get("word", "")
if speaker != current_speaker:
if current_speaker is not None:
sentences.append(f"Speaker {current_speaker}: {' '.join(current_sentence)}")
current_speaker = speaker
current_sentence = [word]
else:
current_sentence.append(word)
if current_sentence:
sentences.append(f"Speaker {current_speaker}: {' '.join(current_sentence)}")
conversation = "\n".join(sentences)
print("\n--- Diarized Conversation ---")
print(conversation)
# 2. Summarization using Qwen2.5 (Ollama)
if not conversation:
print("No transcription found to summarize.")
return
print("\n--- Requesting Summary from Qwen2.5 ---")
prompt = f"Please summarize the following conversation:\n\n{conversation}"
ollama_resp = await client.post(
"http://localhost:11434/api/generate",
json={
"model": "qwen2.5",
"prompt": prompt,
"stream": False
}
)
if ollama_resp.status_code == 200:
summary = ollama_resp.json().get("response", "")
print("\n--- Summary ---")
print(summary)
else:
print("Ollama Error:", ollama_resp.status_code, ollama_resp.text)
if __name__ == "__main__":
asyncio.run(main())