|
import os |
|
import gradio as gr |
|
import whisper |
|
from gtts import gTTS |
|
import io |
|
from openai import OpenAI |
|
|
|
|
|
base_url = "https://api.aimlapi.com/v1" |
|
api_key = "701b35863e6d4a7b81bdcad2e6f3c880" |
|
|
|
|
|
api = OpenAI(api_key=api_key, base_url=base_url) |
|
|
|
|
|
model = whisper.load_model("base") |
|
|
|
|
|
def call_aiml_api(user_prompt, system_prompt="You are a helpful assistant."): |
|
try: |
|
completion = api.chat.completions.create( |
|
model="mistralai/Mistral-7B-Instruct-v0.2", |
|
messages=[ |
|
{"role": "system", "content": system_prompt}, |
|
{"role": "user", "content": user_prompt}, |
|
], |
|
temperature=0.7, |
|
max_tokens=256, |
|
) |
|
|
|
|
|
return completion.choices[0].message.content.strip() |
|
|
|
except Exception as e: |
|
raise Exception(f"API request failed with error: {e}") |
|
|
|
|
|
def process_audio(file_path): |
|
try: |
|
|
|
audio = whisper.load_audio(file_path) |
|
result = model.transcribe(audio) |
|
user_prompt = result["text"] |
|
|
|
|
|
response_message = call_aiml_api(user_prompt) |
|
|
|
|
|
tts = gTTS(response_message) |
|
response_audio_io = io.BytesIO() |
|
tts.write_to_fp(response_audio_io) |
|
response_audio_io.seek(0) |
|
|
|
|
|
with open("response.mp3", "wb") as audio_file: |
|
audio_file.write(response_audio_io.getvalue()) |
|
|
|
|
|
return response_message, "response.mp3" |
|
|
|
except Exception as e: |
|
|
|
return f"An error occurred: {e}", None |
|
|
|
|
|
title = "Voice-to-Voice AI Chatbot with AI/ML API" |
|
description = "Developed by [Adnan Tariq](https://www.linkedin.com/in/adnaantariq/) with ❤️" |
|
article = "### Instructions\n1. Upload an audio file.\n2. Wait for the transcription.\n3. Listen to the chatbot's response." |
|
|
|
|
|
iface = gr.Interface( |
|
fn=process_audio, |
|
inputs=gr.Audio(type="filepath"), |
|
outputs=[gr.Textbox(label="Response Text"), gr.Audio(label="Response Audio")], |
|
live=True, |
|
title=title, |
|
description=description, |
|
theme="dark", |
|
article=article |
|
) |
|
|
|
|
|
iface.launch() |
|
|