Spaces:
Running
Running
File size: 9,002 Bytes
aa99d75 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 |
# 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()
|