ameerazam08's picture
Update app.py
0959063 verified
import gradio as gr
from gradio_unifiedaudio import UnifiedAudio
from huggingface_hub import InferenceClient
from transformers import pipeline
import torch
import tempfile
import subprocess
import spaces
MODEL_NAME = "openai/whisper-large-v3"
BATCH_SIZE = 8
FILE_LIMIT_MB = 1000
YT_LENGTH_LIMIT_S = 3600
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize ASR pipeline
asr_pipe = pipeline(
task="automatic-speech-recognition",
model=MODEL_NAME,
chunk_length_s=30,
device=device,
)
# Initialize Mistral model client
client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
system_instructions1 = "[SYSTEM] Answer as Real Jarvis JARVIS, Made by 'Tony Stark', Keep conversation very short, clear, friendly and concise. The text provided is a request for a specific type of response from you, the virtual assistant. The request asks you to provide friendly responses as if You are the character Jarvis, made by 'Tony Stark.' The expectation is that I will avoid introductions and start answering the query directly, elaborating on all aspects of the request. As an AI-powered assistant, your task is to generate responses that appear as if they are created by the user and not an AI-powered assistant. [USER]"
# History of interactions
history = []
def transcribe(inputs, task="translate"):
if inputs is None:
raise ValueError("No audio file submitted! Please record an audio file before submitting your request.")
text = asr_pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
return text
def model(text):
generate_kwargs = dict(
temperature=0.7,
max_new_tokens=512,
top_p=0.95,
repetition_penalty=1,
do_sample=True,
seed=42,
)
formatted_prompt = system_instructions1 + text + "[JARVIS]"
stream = client1.text_generation(
formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
output = ""
for response in stream:
if not response.token.text == "</s>":
output += response.token.text
return output
@spaces.GPU
def process_audio(audio):
if not audio:
return "Please record an audio.", None
# Provide user feedback
print("Processing audio...")
text = transcribe(audio)
print("Whisper Response -> ", text)
history.append(text)
history_text = " ".join(history)
mistral_response = model(history_text)
print("Mistral Response -> ", mistral_response)
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
tmp_path = tmp_file.name
command = ["edge-tts", "-t", mistral_response, "--write-media", tmp_path]
print(' '.join(command))
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode == 0:
print("Command executed successfully.")
else:
print(f"Command failed with return code {result.returncode}")
print(f"Error message: {result.stderr}")
return mistral_response,tmp_path
def clear_audio(audio):
return UnifiedAudio(value=None),UnifiedAudio(value=None)
DESCRIPTION = """ # <center><b>Voice-Mistral-Voice ๐Ÿค—</b></center>
### <center>Voice-Mistral-Voice</center>
"""
MORE = """ ## TRY Other Models
### https://huggingface.co/spaces/KingNish/Instant-Video
### Instant Image: 4k images in 5 Second -> https://huggingface.co/spaces/KingNish/Instant-Image
"""
BETA = """ ### Voice Chat (BETA)"""
FAST = """## Fastest Model"""
with gr.Blocks() as demo:
gr.Markdown(DESCRIPTION)
with gr.Row():
audio_input = UnifiedAudio(sources="microphone", type="filepath", image="./robot.png")
output_audio = UnifiedAudio(sources="microphone", type="filepath", image="./logo.png")
audio_text = gr.Text()
gr.Markdown(FAST)
clear_audio_button = gr.Button("Record Again")
audio_input.change(process_audio, inputs=audio_input, outputs=[audio_text,output_audio])
clear_audio_button.click(clear_audio, inputs=None, outputs=[audio_input, output_audio])
gr.Markdown(MORE)
if __name__ == '__main__':
demo.queue(max_size=200).launch()