ameerazam08's picture
Create app.py
aa99d75 verified
raw
history blame
9 kB
# import gradio as gr
# from gradio_unifiedaudio import UnifiedAudio
# from huggingface_hub import InferenceClient
# from transformers import pipeline
# import tempfile
# import torch
# import subprocess
# MODEL_NAME = "openai/whisper-large-v3"
# BATCH_SIZE = 8
# FILE_LIMIT_MB = 1000
# YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
# device = 0 if torch.cuda.is_available() else "cpu"
# print( torch.cuda.is_available())
# pipe = pipeline(
# task="automatic-speech-recognition",
# model=MODEL_NAME,
# chunk_length_s=30,
# device=device,
# )
# def transcribe(inputs, task="translate"):
# if inputs is None:
# raise gr.Error("No audio file submitted! Please record an audio file before submitting your request.")
# text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
# return text
# # Initialize the Hugging Face inference 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]"
# # Maintain history of interactions
# history = []
# 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
# def process_audio(audio):
# if not audio:
# return "Please record an audio.", None
# print("Received audio: ", audio)
# text = transcribe(audio)
# print("Whisper Response -> ", text)
# # Append the transcribed text to the history
# history.append(text)
# history_text = " ".join(history)
# mistral_response = model(history_text)
# print("Mistral Response -> ", mistral_response)
# # Using a temporary file to save the TTS output
# with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
# tmp_path = tmp_file.name
# # Construct the edge-tts command
# command = ["edge-tts", "-t", mistral_response, "--write-media", tmp_path]
# print(' '.join(command))
# # Run the command using subprocess.run
# result = subprocess.run(command, capture_output=True, text=True)
# # Check for errors
# 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 tmp_path
# def clear_audio(audio):
# return UnifiedAudio(value=None)
# DESCRIPTION = """ # <center><b>JARVISโšก</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"""
# # Gradio interface
# with gr.Blocks() as demo:
# gr.Markdown(DESCRIPTION)
# with gr.Column():
# with gr.Row():
# audio_input = UnifiedAudio(sources="microphone", type="filepath", image="./robot.png",container=True)
# output_audio = UnifiedAudio(sources="microphone", type="filepath", image="./logo.png",autoplay=True)
# gr.Markdown(FAST)
# clear_audio_button = gr.Button("Record Again")
# # Link the audio input change to process_audio function
# audio_input.change(process_audio, inputs=audio_input, outputs=[output_audio])
# # Link the clear audio button to the clear_audio function
# clear_audio_button.click(clear_audio, inputs=None, outputs=[audio_input, output_audio])
# gr.Markdown(MORE)
# if __name__ == '__main__':
# demo.launch()
import gradio as gr
from gradio_unifiedaudio import UnifiedAudio
from huggingface_hub import InferenceClient
from transformers import pipeline
import torch
import tempfile
import subprocess
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
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.Column():
with gr.Row():
audio_input = UnifiedAudio(sources="microphone", type="filepath", image="./robot.png", container=True)
output_audio = UnifiedAudio(sources="microphone", type="filepath", image="./logo.png", autoplay=True)
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()