hashirehtisham commited on
Commit
ad24a3c
·
verified ·
1 Parent(s): 3dec315

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -96
app.py CHANGED
@@ -11,12 +11,12 @@ import onnxruntime as ort
11
  from huggingface_hub import hf_hub_download, InferenceClient
12
  import requests
13
  from bs4 import BeautifulSoup
14
- import urllib.parse
15
  import random
16
  import re
17
 
18
- # List of user agents for requests
19
- user_agents = [
20
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
21
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
22
  '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',
@@ -26,122 +26,128 @@ user_agents = [
26
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0'
27
  ]
28
 
29
- def get_random_user_agent():
30
- """Selects a random user agent from the list."""
31
- return random.choice(user_agents)
32
 
33
- def extract_visible_text(html):
34
- """Extracts visible text from HTML content, removing unwanted tags."""
35
- soup = BeautifulSoup(html, "html.parser")
 
36
  for tag in soup(["script", "style", "header", "footer", "nav"]):
37
- tag.decompose()
38
- visible_text = soup.get_text(separator=' ', strip=True)
39
- return visible_text[:8000] # Truncate to a reasonable length
40
-
41
- def perform_search(query, num_results=2, timeout=5, ssl_verify=None):
42
- """Conducts a Google search and retrieves the visible text from the results."""
43
- escaped_query = urllib.parse.quote_plus(query)
44
- search_results = []
45
- response = requests.get(
46
- url="https://www.google.com/search",
47
- headers={"User-Agent": get_random_user_agent()},
48
- params={"q": escaped_query, "num": num_results},
49
- timeout=timeout,
50
- verify=ssl_verify,
51
- )
52
- response.raise_for_status()
53
- soup = BeautifulSoup(response.text, "html.parser")
54
- result_blocks = soup.find_all("div", class_="g")
55
-
56
- for block in result_blocks:
57
- link_tag = block.find("a", href=True)
58
- if link_tag:
59
- link = link_tag["href"]
 
 
 
 
 
60
  try:
61
- webpage_response = requests.get(link, headers={"User-Agent": get_random_user_agent()})
62
- webpage_response.raise_for_status()
63
- visible_text = extract_visible_text(webpage_response.text)
64
- search_results.append({"link": link, "text": visible_text})
 
 
65
  except requests.exceptions.RequestException as e:
66
- print(f"Error processing {link}: {e}")
67
- search_results.append({"link": link, "text": None})
68
  else:
69
- search_results.append({"link": None, "text": None})
70
-
71
- return search_results
72
 
73
- # Speech Recognition Model Setup
74
  model_name = "neongeckocom/stt_en_citrinet_512_gamma_0_25"
75
  sample_rate = 16000
76
 
77
- # Download necessary components
78
  preprocessor = torch.jit.load(hf_hub_download(model_name, "preprocessor.ts", subfolder="onnx"))
79
  encoder = ort.InferenceSession(hf_hub_download(model_name, "model.onnx", subfolder="onnx"))
80
  tokenizer = spm.SentencePieceProcessor(hf_hub_download(model_name, "tokenizer.spm", subfolder="onnx"))
81
 
82
- # Mistral Model Setup
83
- client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
84
- system_prompt = "<s>[SYSTEM] Respond as OpenGPT 4o, a friendly, concise virtual assistant developed by 'KingNish'. Please keep your responses clear, direct, and supportive.[USER]"
85
 
86
- def resample_audio(audio_data, original_sr):
87
- """Resamples the audio to the desired sample rate."""
88
- return soxr.resample(audio_data, original_sr, sample_rate)
89
 
90
- def convert_to_float32(audio_buffer):
91
- """Converts audio buffer to float32 format."""
92
  return np.divide(audio_buffer, np.iinfo(audio_buffer.dtype).max, dtype=np.float32)
93
 
94
- def transcribe_audio(audio_path):
95
- """Transcribes speech from an audio file."""
96
- audio = AudioSegment.from_file(audio_path)
97
- audio_buffer = np.array(audio.get_array_of_samples())
98
- audio_fp32 = convert_to_float32(audio_buffer)
99
- resampled_audio = resample_audio(audio_fp32, audio.frame_rate)
100
-
101
- input_tensor = torch.tensor(resampled_audio).unsqueeze(0)
102
- length_tensor = torch.tensor(len(resampled_audio)).unsqueeze(0)
103
- processed_signal, _ = preprocessor.forward(input_signal=input_tensor, length=length_tensor)
104
-
105
- logits = encoder.run(None, {'audio_signal': processed_signal.numpy(), 'length': length_tensor.numpy()})[0][0]
106
- blank_id = tokenizer.vocab_size()
107
- decoded_ids = [p for p in logits.argmax(axis=1).tolist() if p != blank_id]
108
- transcript = tokenizer.decode_ids(decoded_ids)
109
 
110
- return transcript
 
111
 
112
- def generate_response(text, perform_web_search):
113
- """Generates a response using the language model, optionally including web search results."""
114
- if perform_web_search:
115
- web_results = perform_search(text)
116
- web_summary = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
117
- full_prompt = system_prompt + text + "[WEB]" + str(web_summary) + "[OpenGPT 4o]"
118
- else:
119
- full_prompt = system_prompt + text + "[OpenGPT 4o]"
120
-
121
- response_stream = client.text_generation(full_prompt, max_new_tokens=300, stream=True, details=True, return_full_text=False)
122
- response_text = "".join([resp.token.text for resp in response_stream if resp.token.text != "</s>"])
123
- return response_text
124
-
125
- async def handle_interaction(audio_input, perform_web_search):
126
- """Handles user interaction by transcribing audio, generating a response, and converting it to speech."""
127
- user_query = transcribe_audio(audio_input)
128
- ai_reply = generate_response(user_query, perform_web_search)
129
- tts_engine = edge_tts.Communicate(ai_reply)
130
 
131
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_file:
132
- temp_filepath = temp_file.name
133
- await tts_engine.save(temp_filepath)
134
- return temp_filepath
135
 
136
- with gr.Blocks() as interface:
137
- gr.Markdown("# Emotional Support Assistant\nI'm here to offer emotional support and answer your questions. How are you today?")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  gr.Markdown("<p style='color:green;'>Developed by Hashir Ehtisham</p>")
139
 
140
  with gr.Row():
141
- web_search_toggle = gr.Checkbox(label="Perform Web Search", value=False)
142
- audio_input = gr.Audio(label="Speak Your Query", source="microphone", type="filepath")
143
- audio_output = gr.Audio(label="Response", autoplay=True)
144
- gr.Interface(fn=handle_interaction, inputs=[audio_input, web_search_toggle], outputs=[audio_output], live=True)
145
 
146
  if __name__ == "__main__":
147
- interface.queue(max_size=200).launch()
 
11
  from huggingface_hub import hf_hub_download, InferenceClient
12
  import requests
13
  from bs4 import BeautifulSoup
14
+ import urllib
15
  import random
16
  import re
17
 
18
+ # List of user agents to choose from for requests
19
+ _useragent_list = [
20
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
21
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
22
  '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',
 
26
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0'
27
  ]
28
 
29
+ def get_useragent():
30
+ """Returns a random user agent from the list."""
31
+ return random.choice(_useragent_list)
32
 
33
+ def extract_text_from_webpage(html_content):
34
+ """Extracts visible text from HTML content using BeautifulSoup."""
35
+ soup = BeautifulSoup(html_content, "html.parser")
36
+ # Remove unwanted tags
37
  for tag in soup(["script", "style", "header", "footer", "nav"]):
38
+ tag.extract()
39
+ # Get the remaining visible text
40
+ visible_text = soup.get_text(strip=True)
41
+ visible_text = visible_text[:8000]
42
+ return visible_text
43
+
44
+ def search(term, num_results=2, timeout=5, ssl_verify=None):
45
+ """Performs a Google search and returns the results."""
46
+ escaped_term = urllib.parse.quote_plus(term)
47
+ all_results = []
48
+ resp = requests.get(
49
+ url="https://www.google.com/search",
50
+ headers={"User-Agent": get_useragent()}, # Set random user agent
51
+ params={
52
+ "q": term,
53
+ "num": num_results,
54
+ "udm": 14,
55
+ },
56
+ timeout=timeout,
57
+ verify=ssl_verify,
58
+ )
59
+ resp.raise_for_status() # Raise an exception if request fails
60
+ soup = BeautifulSoup(resp.text, "html.parser")
61
+ result_block = soup.find_all("div", attrs={"class": "g"})
62
+ for result in result_block:
63
+ link = result.find("a", href=True)
64
+ if link:
65
+ link = link["href"]
66
  try:
67
+ # Fetch webpage content
68
+ webpage = requests.get(link, headers={"User-Agent": get_useragent()})
69
+ webpage.raise_for_status()
70
+ # Extract visible text from webpage
71
+ visible_text = extract_text_from_webpage(webpage.text)
72
+ all_results.append({"link": link, "text": visible_text})
73
  except requests.exceptions.RequestException as e:
74
+ print(f"Error fetching or processing {link}: {e}")
75
+ all_results.append({"link": link, "text": None})
76
  else:
77
+ all_results.append({"link": None, "text": None})
78
+ print(all_results)
79
+ return all_results
80
 
81
+ # Speech Recognition Model Configuration
82
  model_name = "neongeckocom/stt_en_citrinet_512_gamma_0_25"
83
  sample_rate = 16000
84
 
85
+ # Download preprocessor, encoder and tokenizer
86
  preprocessor = torch.jit.load(hf_hub_download(model_name, "preprocessor.ts", subfolder="onnx"))
87
  encoder = ort.InferenceSession(hf_hub_download(model_name, "model.onnx", subfolder="onnx"))
88
  tokenizer = spm.SentencePieceProcessor(hf_hub_download(model_name, "tokenizer.spm", subfolder="onnx"))
89
 
90
+ # Mistral Model Configuration
91
+ client1 = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
92
+ 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]"
93
 
94
+ def resample(audio_fp32, sr):
95
+ return soxr.resample(audio_fp32, sr, sample_rate)
 
96
 
97
+ def to_float32(audio_buffer):
 
98
  return np.divide(audio_buffer, np.iinfo(audio_buffer.dtype).max, dtype=np.float32)
99
 
100
+ def transcribe(audio_path):
101
+ audio_file = AudioSegment.from_file(audio_path)
102
+ sr = audio_file.frame_rate
103
+ audio_buffer = np.array(audio_file.get_array_of_samples())
 
 
 
 
 
 
 
 
 
 
 
104
 
105
+ audio_fp32 = to_float32(audio_buffer)
106
+ audio_16k = resample(audio_fp32, sr)
107
 
108
+ input_signal = torch.tensor(audio_16k).unsqueeze(0)
109
+ length = torch.tensor(len(audio_16k)).unsqueeze(0)
110
+ processed_signal, _ = preprocessor.forward(input_signal=input_signal, length=length)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
+ logits = encoder.run(None, {'audio_signal': processed_signal.numpy(), 'length': length.numpy()})[0][0]
 
 
 
113
 
114
+ blank_id = tokenizer.vocab_size()
115
+ decoded_prediction = [p for p in logits.argmax(axis=1).tolist() if p != blank_id]
116
+ text = tokenizer.decode_ids(decoded_prediction)
117
+
118
+ return text
119
+
120
+ def model(text, web_search):
121
+ if web_search is True:
122
+ """Performs a web search, feeds the results to a language model, and returns the answer."""
123
+ web_results = search(text)
124
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
125
+ formatted_prompt = system_instructions1 + text + "[WEB]" + str(web2) + "[OpenGPT 4o]"
126
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=300, stream=True, details=True, return_full_text=False)
127
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
128
+ else:
129
+ formatted_prompt = system_instructions1 + text + "[OpenGPT 4o]"
130
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=300, stream=True, details=True, return_full_text=False)
131
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
132
+
133
+ async def respond(audio, web_search):
134
+ user = transcribe(audio)
135
+ reply = model(user, web_search)
136
+ communicate = edge_tts.Communicate(reply)
137
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
138
+ tmp_path = tmp_file.name
139
+ await communicate.save(tmp_path)
140
+ return tmp_path
141
+
142
+ with gr.Blocks() as demo:
143
+ gr.Markdown("# Emotional Support\nHello! I'm here to support you emotionally and answer any questions. How are you feeling today?")
144
  gr.Markdown("<p style='color:green;'>Developed by Hashir Ehtisham</p>")
145
 
146
  with gr.Row():
147
+ web_search = gr.Checkbox(label="Web Search", value=False)
148
+ audio_input = gr.Audio(label="Speak Your Query", type="filepath")
149
+ output = gr.Audio(label="AI Response", autoplay=True)
150
+ gr.Interface(fn=respond, inputs=[audio_input, web_search], outputs=[output], live=True)
151
 
152
  if __name__ == "__main__":
153
+ demo.queue(max_size=200).launch()