Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
import edge_tts
|
3 |
import asyncio
|
@@ -13,12 +14,12 @@ import requests
|
|
13 |
from bs4 import BeautifulSoup
|
14 |
import urllib
|
15 |
import random
|
16 |
-
import speech_recognition as sr
|
17 |
|
18 |
theme = gr.themes.Soft(
|
19 |
primary_hue="blue",
|
20 |
secondary_hue="orange")
|
21 |
|
|
|
22 |
# List of user agents to choose from for requests
|
23 |
_useragent_list = [
|
24 |
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
|
@@ -159,204 +160,17 @@ async def respond(audio, web_search):
|
|
159 |
await communicate.save(tmp_path)
|
160 |
return tmp_path
|
161 |
|
162 |
-
def listen_for_speech(web_search):
|
163 |
-
recognizer = sr.Recognizer()
|
164 |
-
with sr.Microphone() as source:
|
165 |
-
print("Listening for speech...")
|
166 |
-
audio_data = recognizer.listen(source)
|
167 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
|
168 |
-
tmp_path = tmp_file.name
|
169 |
-
with open(tmp_path, 'wb') as f:
|
170 |
-
f.write(audio_data.get_wav_data())
|
171 |
-
return asyncio.run(respond(tmp_path, web_search))
|
172 |
-
|
173 |
with gr.Blocks(theme=theme) as demo:
|
174 |
with gr.Row():
|
175 |
web_search = gr.Checkbox(label="Web Search", value=False)
|
|
|
176 |
output = gr.Audio(label="AI", autoplay=True)
|
177 |
-
|
178 |
|
179 |
if __name__ == "__main__":
|
180 |
demo.queue(max_size=200).launch()
|
181 |
|
182 |
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
# import gradio as gr
|
189 |
-
# import edge_tts
|
190 |
-
# import asyncio
|
191 |
-
# import tempfile
|
192 |
-
# import numpy as np
|
193 |
-
# import soxr
|
194 |
-
# from pydub import AudioSegment
|
195 |
-
# import torch
|
196 |
-
# import sentencepiece as spm
|
197 |
-
# import onnxruntime as ort
|
198 |
-
# from huggingface_hub import hf_hub_download, InferenceClient
|
199 |
-
# import requests
|
200 |
-
# from bs4 import BeautifulSoup
|
201 |
-
# import urllib
|
202 |
-
# import random
|
203 |
-
|
204 |
-
# theme = gr.themes.Soft(
|
205 |
-
# primary_hue="blue",
|
206 |
-
# secondary_hue="orange")
|
207 |
-
|
208 |
-
|
209 |
-
# # List of user agents to choose from for requests
|
210 |
-
# _useragent_list = [
|
211 |
-
# 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
|
212 |
-
# 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
|
213 |
-
# 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
|
214 |
-
# 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
|
215 |
-
# 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
|
216 |
-
# 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.62',
|
217 |
-
# 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0'
|
218 |
-
# ]
|
219 |
-
|
220 |
-
# def get_useragent():
|
221 |
-
# """Returns a random user agent from the list."""
|
222 |
-
# return random.choice(_useragent_list)
|
223 |
-
|
224 |
-
# def extract_text_from_webpage(html_content):
|
225 |
-
# """Extracts visible text from HTML content using BeautifulSoup."""
|
226 |
-
# soup = BeautifulSoup(html_content, "html.parser")
|
227 |
-
# # Remove unwanted tags
|
228 |
-
# for tag in soup(["script", "style", "header", "footer", "nav"]):
|
229 |
-
# tag.extract()
|
230 |
-
# # Get the remaining visible text
|
231 |
-
# visible_text = soup.get_text(strip=True)
|
232 |
-
# return visible_text
|
233 |
-
|
234 |
-
# def search(term, num_results=1, lang="en", advanced=True, sleep_interval=0, timeout=5, safe="active", ssl_verify=None):
|
235 |
-
# """Performs a Google search and returns the results."""
|
236 |
-
# escaped_term = urllib.parse.quote_plus(term)
|
237 |
-
# start = 0
|
238 |
-
# all_results = []
|
239 |
-
|
240 |
-
# # Fetch results in batches
|
241 |
-
# while start < num_results:
|
242 |
-
# resp = requests.get(
|
243 |
-
# url="https://www.google.com/search",
|
244 |
-
# headers={"User-Agent": get_useragent()}, # Set random user agent
|
245 |
-
# params={
|
246 |
-
# "q": term,
|
247 |
-
# "num": num_results - start, # Number of results to fetch in this batch
|
248 |
-
# "hl": lang,
|
249 |
-
# "start": start,
|
250 |
-
# "safe": safe,
|
251 |
-
# },
|
252 |
-
# timeout=timeout,
|
253 |
-
# verify=ssl_verify,
|
254 |
-
# )
|
255 |
-
# resp.raise_for_status() # Raise an exception if request fails
|
256 |
-
|
257 |
-
# soup = BeautifulSoup(resp.text, "html.parser")
|
258 |
-
# result_block = soup.find_all("div", attrs={"class": "g"})
|
259 |
-
|
260 |
-
# # If no results, continue to the next batch
|
261 |
-
# if not result_block:
|
262 |
-
# start += 1
|
263 |
-
# continue
|
264 |
-
|
265 |
-
# # Extract link and text from each result
|
266 |
-
# for result in result_block:
|
267 |
-
# link = result.find("a", href=True)
|
268 |
-
# if link:
|
269 |
-
# link = link["href"]
|
270 |
-
# try:
|
271 |
-
# # Fetch webpage content
|
272 |
-
# webpage = requests.get(link, headers={"User-Agent": get_useragent()})
|
273 |
-
# webpage.raise_for_status()
|
274 |
-
# # Extract visible text from webpage
|
275 |
-
# visible_text = extract_text_from_webpage(webpage.text)
|
276 |
-
# all_results.append({"link": link, "text": visible_text})
|
277 |
-
# except requests.exceptions.RequestException as e:
|
278 |
-
# # Handle errors fetching or processing webpage
|
279 |
-
# print(f"Error fetching or processing {link}: {e}")
|
280 |
-
# all_results.append({"link": link, "text": None})
|
281 |
-
# else:
|
282 |
-
# all_results.append({"link": None, "text": None})
|
283 |
-
|
284 |
-
# start += len(result_block) # Update starting index for next batch
|
285 |
-
|
286 |
-
# return all_results
|
287 |
-
|
288 |
-
# # Speech Recognition Model Configuration
|
289 |
-
# model_name = "neongeckocom/stt_en_citrinet_512_gamma_0_25"
|
290 |
-
# sample_rate = 16000
|
291 |
-
|
292 |
-
# # Download preprocessor, encoder and tokenizer
|
293 |
-
# preprocessor = torch.jit.load(hf_hub_download(model_name, "preprocessor.ts", subfolder="onnx"))
|
294 |
-
# encoder = ort.InferenceSession(hf_hub_download(model_name, "model.onnx", subfolder="onnx"))
|
295 |
-
# tokenizer = spm.SentencePieceProcessor(hf_hub_download(model_name, "tokenizer.spm", subfolder="onnx"))
|
296 |
-
|
297 |
-
# # Mistral Model Configuration
|
298 |
-
# client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
299 |
-
# system_instructions1 = "<s>[SYSTEM] Answer as OpenGPT 4o, Made by 'KingNish', 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. 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]"
|
300 |
-
|
301 |
-
# def resample(audio_fp32, sr):
|
302 |
-
# return soxr.resample(audio_fp32, sr, sample_rate)
|
303 |
-
|
304 |
-
# def to_float32(audio_buffer):
|
305 |
-
# return np.divide(audio_buffer, np.iinfo(audio_buffer.dtype).max, dtype=np.float32)
|
306 |
-
|
307 |
-
# def transcribe(audio_path):
|
308 |
-
# audio_file = AudioSegment.from_file(audio_path)
|
309 |
-
# sr = audio_file.frame_rate
|
310 |
-
# audio_buffer = np.array(audio_file.get_array_of_samples())
|
311 |
-
|
312 |
-
# audio_fp32 = to_float32(audio_buffer)
|
313 |
-
# audio_16k = resample(audio_fp32, sr)
|
314 |
-
|
315 |
-
# input_signal = torch.tensor(audio_16k).unsqueeze(0)
|
316 |
-
# length = torch.tensor(len(audio_16k)).unsqueeze(0)
|
317 |
-
# processed_signal, _ = preprocessor.forward(input_signal=input_signal, length=length)
|
318 |
-
|
319 |
-
# logits = encoder.run(None, {'audio_signal': processed_signal.numpy(), 'length': length.numpy()})[0][0]
|
320 |
-
|
321 |
-
# blank_id = tokenizer.vocab_size()
|
322 |
-
# decoded_prediction = [p for p in logits.argmax(axis=1).tolist() if p != blank_id]
|
323 |
-
# text = tokenizer.decode_ids(decoded_prediction)
|
324 |
-
|
325 |
-
# return text
|
326 |
-
|
327 |
-
# def model(text, web_search):
|
328 |
-
# if web_search is True:
|
329 |
-
# """Performs a web search, feeds the results to a language model, and returns the answer."""
|
330 |
-
# web_results = search(text)
|
331 |
-
# web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
|
332 |
-
# formatted_prompt = system_instructions1 + text + "[WEB]" + str(web2) + "[OpenGPT 4o]"
|
333 |
-
# stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
|
334 |
-
# return "".join([response.token.text for response in stream if response.token.text != "</s>"])
|
335 |
-
# else:
|
336 |
-
# formatted_prompt = system_instructions1 + text + "[OpenGPT 4o]"
|
337 |
-
# stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
|
338 |
-
# return "".join([response.token.text for response in stream if response.token.text != "</s>"])
|
339 |
-
|
340 |
-
# async def respond(audio, web_search):
|
341 |
-
# user = transcribe(audio)
|
342 |
-
# reply = model(user, web_search)
|
343 |
-
# communicate = edge_tts.Communicate(reply)
|
344 |
-
# with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
|
345 |
-
# tmp_path = tmp_file.name
|
346 |
-
# await communicate.save(tmp_path)
|
347 |
-
# return tmp_path
|
348 |
-
|
349 |
-
# with gr.Blocks(theme=theme) as demo:
|
350 |
-
# with gr.Row():
|
351 |
-
# web_search = gr.Checkbox(label="Web Search", value=False)
|
352 |
-
# input = gr.Audio(label="User Input", sources="microphone", type="filepath")
|
353 |
-
# output = gr.Audio(label="AI", autoplay=True)
|
354 |
-
# gr.Interface(fn=respond, inputs=[input, web_search], outputs=[output], live=True)
|
355 |
-
|
356 |
-
# if __name__ == "__main__":
|
357 |
-
# demo.queue(max_size=200).launch()
|
358 |
-
|
359 |
-
|
360 |
# import gradio as gr
|
361 |
# import edge_tts
|
362 |
# import asyncio
|
|
|
1 |
+
|
2 |
import gradio as gr
|
3 |
import edge_tts
|
4 |
import asyncio
|
|
|
14 |
from bs4 import BeautifulSoup
|
15 |
import urllib
|
16 |
import random
|
|
|
17 |
|
18 |
theme = gr.themes.Soft(
|
19 |
primary_hue="blue",
|
20 |
secondary_hue="orange")
|
21 |
|
22 |
+
|
23 |
# List of user agents to choose from for requests
|
24 |
_useragent_list = [
|
25 |
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
|
|
|
160 |
await communicate.save(tmp_path)
|
161 |
return tmp_path
|
162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
with gr.Blocks(theme=theme) as demo:
|
164 |
with gr.Row():
|
165 |
web_search = gr.Checkbox(label="Web Search", value=False)
|
166 |
+
input = gr.Audio(label="User Input", sources="microphone", type="filepath")
|
167 |
output = gr.Audio(label="AI", autoplay=True)
|
168 |
+
gr.Interface(fn=respond, inputs=[input, web_search], outputs=[output], live=True)
|
169 |
|
170 |
if __name__ == "__main__":
|
171 |
demo.queue(max_size=200).launch()
|
172 |
|
173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
# import gradio as gr
|
175 |
# import edge_tts
|
176 |
# import asyncio
|