KingNish commited on
Commit
995e163
1 Parent(s): c28f584

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -6
app.py CHANGED
@@ -22,6 +22,169 @@ theme = gr.themes.Soft(
22
  color_accent_soft_dark="transparent"
23
  )
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # Create Gradio blocks for different functionalities
26
 
27
  # Chat interface block
@@ -69,12 +232,7 @@ with gr.Blocks(
69
  top_p,
70
  gr.Checkbox(label="Web Search", value=True),
71
  ],
72
- )
73
-
74
- # Voice chat block
75
- with gr.Blocks() as voice:
76
- gr.HTML("<iframe src='https://kingnish-voice-chat-ai.hf.space' width='100%' height='2000px' style='border-radius: 8px;'></iframe>")
77
-
78
 
79
  # Live chat block
80
  with gr.Blocks() as livechat:
 
22
  color_accent_soft_dark="transparent"
23
  )
24
 
25
+ import edge_tts
26
+ import asyncio
27
+ import tempfile
28
+ import numpy as np
29
+ import soxr
30
+ from pydub import AudioSegment
31
+ import torch
32
+ import sentencepiece as spm
33
+ import onnxruntime as ort
34
+ from huggingface_hub import hf_hub_download, InferenceClient
35
+ import requests
36
+ from bs4 import BeautifulSoup
37
+ import urllib
38
+ import random
39
+
40
+ # List of user agents to choose from for requests
41
+ _useragent_list = [
42
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
43
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
44
+ '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',
45
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
46
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
47
+ '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',
48
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0'
49
+ ]
50
+
51
+ def get_useragent():
52
+ """Returns a random user agent from the list."""
53
+ return random.choice(_useragent_list)
54
+
55
+ def extract_text_from_webpage(html_content):
56
+ """Extracts visible text from HTML content using BeautifulSoup."""
57
+ soup = BeautifulSoup(html_content, "html.parser")
58
+ # Remove unwanted tags
59
+ for tag in soup(["script", "style", "header", "footer", "nav"]):
60
+ tag.extract()
61
+ # Get the remaining visible text
62
+ visible_text = soup.get_text(strip=True)
63
+ return visible_text
64
+
65
+ def search(term, num_results=1, lang="en", advanced=True, sleep_interval=0, timeout=5, safe="active", ssl_verify=None):
66
+ """Performs a Google search and returns the results."""
67
+ escaped_term = urllib.parse.quote_plus(term)
68
+ start = 0
69
+ all_results = []
70
+
71
+ # Fetch results in batches
72
+ while start < num_results:
73
+ resp = requests.get(
74
+ url="https://www.google.com/search",
75
+ headers={"User-Agent": get_useragent()}, # Set random user agent
76
+ params={
77
+ "q": term,
78
+ "num": num_results - start, # Number of results to fetch in this batch
79
+ "hl": lang,
80
+ "start": start,
81
+ "safe": safe,
82
+ },
83
+ timeout=timeout,
84
+ verify=ssl_verify,
85
+ )
86
+ resp.raise_for_status() # Raise an exception if request fails
87
+
88
+ soup = BeautifulSoup(resp.text, "html.parser")
89
+ result_block = soup.find_all("div", attrs={"class": "g"})
90
+
91
+ # If no results, continue to the next batch
92
+ if not result_block:
93
+ start += 1
94
+ continue
95
+
96
+ # Extract link and text from each result
97
+ for result in result_block:
98
+ link = result.find("a", href=True)
99
+ if link:
100
+ link = link["href"]
101
+ try:
102
+ # Fetch webpage content
103
+ webpage = requests.get(link, headers={"User-Agent": get_useragent()})
104
+ webpage.raise_for_status()
105
+ # Extract visible text from webpage
106
+ visible_text = extract_text_from_webpage(webpage.text)
107
+ all_results.append({"link": link, "text": visible_text})
108
+ except requests.exceptions.RequestException as e:
109
+ # Handle errors fetching or processing webpage
110
+ print(f"Error fetching or processing {link}: {e}")
111
+ all_results.append({"link": link, "text": None})
112
+ else:
113
+ all_results.append({"link": None, "text": None})
114
+
115
+ start += len(result_block) # Update starting index for next batch
116
+
117
+ return all_results
118
+
119
+ # Speech Recognition Model Configuration
120
+ model_name = "neongeckocom/stt_en_citrinet_512_gamma_0_25"
121
+ sample_rate = 16000
122
+
123
+ # Download preprocessor, encoder and tokenizer
124
+ preprocessor = torch.jit.load(hf_hub_download(model_name, "preprocessor.ts", subfolder="onnx"))
125
+ encoder = ort.InferenceSession(hf_hub_download(model_name, "model.onnx", subfolder="onnx"))
126
+ tokenizer = spm.SentencePieceProcessor(hf_hub_download(model_name, "tokenizer.spm", subfolder="onnx"))
127
+
128
+ # Mistral Model Configuration
129
+ client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
130
+ system_instructions1 = "<s>[SYSTEM] Answer as Real 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]"
131
+
132
+ def resample(audio_fp32, sr):
133
+ return soxr.resample(audio_fp32, sr, sample_rate)
134
+
135
+ def to_float32(audio_buffer):
136
+ return np.divide(audio_buffer, np.iinfo(audio_buffer.dtype).max, dtype=np.float32)
137
+
138
+ def transcribe(audio_path):
139
+ audio_file = AudioSegment.from_file(audio_path)
140
+ sr = audio_file.frame_rate
141
+ audio_buffer = np.array(audio_file.get_array_of_samples())
142
+
143
+ audio_fp32 = to_float32(audio_buffer)
144
+ audio_16k = resample(audio_fp32, sr)
145
+
146
+ input_signal = torch.tensor(audio_16k).unsqueeze(0)
147
+ length = torch.tensor(len(audio_16k)).unsqueeze(0)
148
+ processed_signal, _ = preprocessor.forward(input_signal=input_signal, length=length)
149
+
150
+ logits = encoder.run(None, {'audio_signal': processed_signal.numpy(), 'length': length.numpy()})[0][0]
151
+
152
+ blank_id = tokenizer.vocab_size()
153
+ decoded_prediction = [p for p in logits.argmax(axis=1).tolist() if p != blank_id]
154
+ text = tokenizer.decode_ids(decoded_prediction)
155
+
156
+ return text
157
+
158
+ def model(text, web_search):
159
+ if web_search is True:
160
+ """Performs a web search, feeds the results to a language model, and returns the answer."""
161
+ web_results = search(text)
162
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
163
+ formatted_prompt = system_instructions1 + text + "[WEB]" + str(web2) + "[OpenGPT 4o]"
164
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
165
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
166
+ else:
167
+ formatted_prompt = system_instructions1 + text + "[OpenGPT 4o]"
168
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
169
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
170
+
171
+ async def respond(audio, web_search):
172
+ user = transcribe(audio)
173
+ reply = model(user, web_search)
174
+ communicate = edge_tts.Communicate(reply)
175
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
176
+ tmp_path = tmp_file.name
177
+ await communicate.save(tmp_path)
178
+ return tmp_path
179
+
180
+ with gr.Blocks() as voice:
181
+ with gr.Row():
182
+ web_search = gr.Checkbox(label="Web Search", value=False)
183
+ input = gr.Audio(label="User Input", sources="microphone", type="filepath")
184
+ output = gr.Audio(label="AI", autoplay=True)
185
+ gr.Interface(fn=respond, inputs=[input, web_search], outputs=[output], live=True)
186
+
187
+
188
  # Create Gradio blocks for different functionalities
189
 
190
  # Chat interface block
 
232
  top_p,
233
  gr.Checkbox(label="Web Search", value=True),
234
  ],
235
+ )
 
 
 
 
 
236
 
237
  # Live chat block
238
  with gr.Blocks() as livechat: