ameerazam08 commited on
Commit
aa99d75
โ€ข
1 Parent(s): 36c5d73

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +257 -0
app.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import gradio as gr
2
+ # from gradio_unifiedaudio import UnifiedAudio
3
+ # from huggingface_hub import InferenceClient
4
+ # from transformers import pipeline
5
+ # import tempfile
6
+ # import torch
7
+ # import subprocess
8
+
9
+ # MODEL_NAME = "openai/whisper-large-v3"
10
+ # BATCH_SIZE = 8
11
+ # FILE_LIMIT_MB = 1000
12
+ # YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
13
+
14
+ # device = 0 if torch.cuda.is_available() else "cpu"
15
+ # print( torch.cuda.is_available())
16
+
17
+ # pipe = pipeline(
18
+ # task="automatic-speech-recognition",
19
+ # model=MODEL_NAME,
20
+ # chunk_length_s=30,
21
+ # device=device,
22
+ # )
23
+
24
+
25
+ # def transcribe(inputs, task="translate"):
26
+ # if inputs is None:
27
+ # raise gr.Error("No audio file submitted! Please record an audio file before submitting your request.")
28
+
29
+ # text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
30
+ # return text
31
+
32
+ # # Initialize the Hugging Face inference client
33
+ # client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
34
+ # 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]"
35
+
36
+ # # Maintain history of interactions
37
+ # history = []
38
+
39
+ # def model(text):
40
+ # generate_kwargs = dict(
41
+ # temperature=0.7,
42
+ # max_new_tokens=512,
43
+ # top_p=0.95,
44
+ # repetition_penalty=1,
45
+ # do_sample=True,
46
+ # seed=42,
47
+ # )
48
+
49
+ # formatted_prompt = system_instructions1 + text + "[JARVIS]"
50
+ # stream = client1.text_generation(
51
+ # formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
52
+ # output = ""
53
+ # for response in stream:
54
+ # if not response.token.text == "</s>":
55
+ # output += response.token.text
56
+ # return output
57
+
58
+ # def process_audio(audio):
59
+ # if not audio:
60
+ # return "Please record an audio.", None
61
+
62
+ # print("Received audio: ", audio)
63
+ # text = transcribe(audio)
64
+ # print("Whisper Response -> ", text)
65
+
66
+ # # Append the transcribed text to the history
67
+ # history.append(text)
68
+ # history_text = " ".join(history)
69
+
70
+ # mistral_response = model(history_text)
71
+ # print("Mistral Response -> ", mistral_response)
72
+
73
+ # # Using a temporary file to save the TTS output
74
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
75
+ # tmp_path = tmp_file.name
76
+
77
+ # # Construct the edge-tts command
78
+ # command = ["edge-tts", "-t", mistral_response, "--write-media", tmp_path]
79
+ # print(' '.join(command))
80
+
81
+ # # Run the command using subprocess.run
82
+ # result = subprocess.run(command, capture_output=True, text=True)
83
+
84
+ # # Check for errors
85
+ # if result.returncode == 0:
86
+ # print("Command executed successfully.")
87
+ # else:
88
+ # print(f"Command failed with return code {result.returncode}")
89
+ # print(f"Error message: {result.stderr}")
90
+
91
+ # return tmp_path
92
+
93
+ # def clear_audio(audio):
94
+ # return UnifiedAudio(value=None)
95
+
96
+
97
+
98
+ # DESCRIPTION = """ # <center><b>JARVISโšก</b></center>
99
+ # ### <center>Voice-Mistral-Voice</center>
100
+ # """
101
+
102
+ # MORE = """ ## TRY Other Models
103
+ # ### https://huggingface.co/spaces/KingNish/Instant-Video
104
+ # ### Instant Image: 4k images in 5 Second -> https://huggingface.co/spaces/KingNish/Instant-Image
105
+ # """
106
+
107
+ # BETA = """ ### Voice Chat (BETA)"""
108
+
109
+ # FAST = """## Fastest Model"""
110
+
111
+ # # Gradio interface
112
+ # with gr.Blocks() as demo:
113
+ # gr.Markdown(DESCRIPTION)
114
+
115
+
116
+ # with gr.Column():
117
+ # with gr.Row():
118
+ # audio_input = UnifiedAudio(sources="microphone", type="filepath", image="./robot.png",container=True)
119
+ # output_audio = UnifiedAudio(sources="microphone", type="filepath", image="./logo.png",autoplay=True)
120
+
121
+ # gr.Markdown(FAST)
122
+ # clear_audio_button = gr.Button("Record Again")
123
+ # # Link the audio input change to process_audio function
124
+ # audio_input.change(process_audio, inputs=audio_input, outputs=[output_audio])
125
+ # # Link the clear audio button to the clear_audio function
126
+ # clear_audio_button.click(clear_audio, inputs=None, outputs=[audio_input, output_audio])
127
+
128
+ # gr.Markdown(MORE)
129
+ # if __name__ == '__main__':
130
+ # demo.launch()
131
+
132
+
133
+ import gradio as gr
134
+ from gradio_unifiedaudio import UnifiedAudio
135
+ from huggingface_hub import InferenceClient
136
+ from transformers import pipeline
137
+ import torch
138
+ import tempfile
139
+ import subprocess
140
+
141
+ MODEL_NAME = "openai/whisper-large-v3"
142
+ BATCH_SIZE = 8
143
+ FILE_LIMIT_MB = 1000
144
+ YT_LENGTH_LIMIT_S = 3600
145
+
146
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
147
+
148
+ # Initialize ASR pipeline
149
+ asr_pipe = pipeline(
150
+ task="automatic-speech-recognition",
151
+ model=MODEL_NAME,
152
+ chunk_length_s=30,
153
+ device=device,
154
+ )
155
+
156
+ # Initialize Mistral model client
157
+ client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
158
+ 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]"
159
+
160
+ # History of interactions
161
+ history = []
162
+
163
+ def transcribe(inputs, task="translate"):
164
+ if inputs is None:
165
+ raise ValueError("No audio file submitted! Please record an audio file before submitting your request.")
166
+
167
+ text = asr_pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
168
+ return text
169
+
170
+ def model(text):
171
+ generate_kwargs = dict(
172
+ temperature=0.7,
173
+ max_new_tokens=512,
174
+ top_p=0.95,
175
+ repetition_penalty=1,
176
+ do_sample=True,
177
+ seed=42,
178
+ )
179
+
180
+ formatted_prompt = system_instructions1 + text + "[JARVIS]"
181
+ stream = client1.text_generation(
182
+ formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
183
+ output = ""
184
+ for response in stream:
185
+ if not response.token.text == "</s>":
186
+ output += response.token.text
187
+ return output
188
+
189
+
190
+
191
+
192
+ def process_audio(audio):
193
+ if not audio:
194
+ return "Please record an audio.", None
195
+
196
+ # Provide user feedback
197
+ print("Processing audio...")
198
+
199
+ text = transcribe(audio)
200
+ print("Whisper Response -> ", text)
201
+
202
+ history.append(text)
203
+ history_text = " ".join(history)
204
+
205
+ mistral_response = model(history_text)
206
+ print("Mistral Response -> ", mistral_response)
207
+
208
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
209
+ tmp_path = tmp_file.name
210
+
211
+ command = ["edge-tts", "-t", mistral_response, "--write-media", tmp_path]
212
+ print(' '.join(command))
213
+
214
+ result = subprocess.run(command, capture_output=True, text=True)
215
+
216
+ if result.returncode == 0:
217
+ print("Command executed successfully.")
218
+ else:
219
+ print(f"Command failed with return code {result.returncode}")
220
+ print(f"Error message: {result.stderr}")
221
+
222
+ return mistral_response,tmp_path
223
+
224
+ def clear_audio(audio):
225
+ return UnifiedAudio(value=None),UnifiedAudio(value=None)
226
+
227
+
228
+ DESCRIPTION = """ # <center><b>Voice-Mistral-Voice ๐Ÿค—</b></center>
229
+ ### <center>Voice-Mistral-Voice</center>
230
+ """
231
+
232
+ MORE = """ ## TRY Other Models
233
+ ### https://huggingface.co/spaces/KingNish/Instant-Video
234
+ ### Instant Image: 4k images in 5 Second -> https://huggingface.co/spaces/KingNish/Instant-Image
235
+ """
236
+
237
+ BETA = """ ### Voice Chat (BETA)"""
238
+
239
+ FAST = """## Fastest Model"""
240
+
241
+ with gr.Blocks() as demo:
242
+ gr.Markdown(DESCRIPTION)
243
+
244
+ with gr.Column():
245
+ with gr.Row():
246
+ audio_input = UnifiedAudio(sources="microphone", type="filepath", image="./robot.png", container=True)
247
+ output_audio = UnifiedAudio(sources="microphone", type="filepath", image="./logo.png", autoplay=True)
248
+ audio_text = gr.Text()
249
+ gr.Markdown(FAST)
250
+ clear_audio_button = gr.Button("Record Again")
251
+ audio_input.change(process_audio, inputs=audio_input, outputs=[audio_text,output_audio])
252
+ clear_audio_button.click(clear_audio, inputs=None, outputs=[audio_input, output_audio])
253
+
254
+ gr.Markdown(MORE)
255
+
256
+ if __name__ == '__main__':
257
+ demo.queue(max_size=200).launch()