dineth554 commited on
Commit
9929ecc
·
verified ·
1 Parent(s): 8b5fa96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -2
app.py CHANGED
@@ -1,3 +1,172 @@
1
- import gradio as gr
2
 
3
- gr.load("models/mistralai/Mixtral-8x7B-Instruct-v0.1").launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
 
3
+ # Install required libraries
4
+ os.system("pip install streamlit edge_tts pydub soxr numpy onnxruntime sentencepiece huggingface_hub torch beautifulsoup4 requests urllib3")
5
+
6
+ import streamlit as st
7
+ import edge_tts
8
+ import asyncio
9
+ import tempfile
10
+ import numpy as np
11
+ import soxr
12
+ from pydub import AudioSegment
13
+ import torch
14
+ import sentencepiece as spm
15
+ import onnxruntime as ort
16
+ from huggingface_hub import hf_hub_download, InferenceClient
17
+ import requests
18
+ from bs4 import BeautifulSoup
19
+ import urllib
20
+ import random
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',
25
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
26
+ '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',
27
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
28
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
29
+ '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',
30
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0'
31
+ ]
32
+
33
+ def get_useragent():
34
+ """Returns a random user agent from the list."""
35
+ return random.choice(_useragent_list)
36
+
37
+ def extract_text_from_webpage(html_content):
38
+ """Extracts visible text from HTML content using BeautifulSoup."""
39
+ soup = BeautifulSoup(html_content, "html.parser")
40
+ # Remove unwanted tags
41
+ for tag in soup(["script", "style", "header", "footer", "nav"]):
42
+ tag.extract()
43
+ # Get the remaining visible text
44
+ visible_text = soup.get_text(strip=True)
45
+ return visible_text
46
+
47
+ def search(term, num_results=1, lang="en", advanced=True, sleep_interval=0, timeout=5, safe="active", ssl_verify=None):
48
+ """Performs a Google search and returns the results."""
49
+ escaped_term = urllib.parse.quote_plus(term)
50
+ start = 0
51
+ all_results = []
52
+
53
+ # Fetch results in batches
54
+ while start < num_results:
55
+ resp = requests.get(
56
+ url="https://www.google.com/search",
57
+ headers={"User-Agent": get_useragent()}, # Set random user agent
58
+ params={
59
+ "q": term,
60
+ "num": num_results - start, # Number of results to fetch in this batch
61
+ "hl": lang,
62
+ "start": start,
63
+ "safe": safe,
64
+ },
65
+ timeout=timeout,
66
+ verify=ssl_verify,
67
+ )
68
+ resp.raise_for_status() # Raise an exception if request fails
69
+
70
+ soup = BeautifulSoup(resp.text, "html.parser")
71
+ result_block = soup.find_all("div", attrs={"class": "g"})
72
+
73
+ # If no results, continue to the next batch
74
+ if not result_block:
75
+ start += 1
76
+ continue
77
+
78
+ # Extract link and text from each result
79
+ for result in result_block:
80
+ link = result.find("a", href=True)
81
+ if link:
82
+ link = link["href"]
83
+ try:
84
+ # Fetch webpage content
85
+ webpage = requests.get(link, headers={"User-Agent": get_useragent()})
86
+ webpage.raise_for_status()
87
+ # Extract visible text from webpage
88
+ visible_text = extract_text_from_webpage(webpage.text)
89
+ all_results.append({"link": link, "text": visible_text})
90
+ except requests.exceptions.RequestException as e:
91
+ # Handle errors fetching or processing webpage
92
+ print(f"Error fetching or processing {link}: {e}")
93
+ all_results.append({"link": link, "text": None})
94
+ else:
95
+ all_results.append({"link": None, "text": None})
96
+
97
+ start += len(result_block) # Update starting index for next batch
98
+
99
+ return all_results
100
+
101
+ # Speech Recognition Model Configuration
102
+ model_name = "neongeckocom/stt_en_citrinet_512_gamma_0_25"
103
+ sample_rate = 16000
104
+
105
+ # Download preprocessor, encoder and tokenizer
106
+ preprocessor = torch.jit.load(hf_hub_download(model_name, "preprocessor.ts", subfolder="onnx"))
107
+ encoder = ort.InferenceSession(hf_hub_download(model_name, "model.onnx", subfolder="onnx"))
108
+ tokenizer = spm.SentencePieceProcessor(hf_hub_download(model_name, "tokenizer.spm", subfolder="onnx"))
109
+
110
+ # Mistral Model Configuration
111
+ client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
112
+ 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]"
113
+
114
+ def resample(audio_fp32, sr):
115
+ return soxr.resample(audio_fp32, sr, sample_rate)
116
+
117
+ def to_float32(audio_buffer):
118
+ return np.divide(audio_buffer, np.iinfo(audio_buffer.dtype).max, dtype=np.float32)
119
+
120
+ def transcribe(audio_path):
121
+ audio_file = AudioSegment.from_file(audio_path)
122
+ sr = audio_file.frame_rate
123
+ audio_buffer = np.array(audio_file.get_array_of_samples())
124
+
125
+ audio_fp32 = to_float32(audio_buffer)
126
+ audio_16k = resample(audio_fp32, sr)
127
+
128
+ input_signal = torch.tensor(audio_16k).unsqueeze(0)
129
+ length = torch.tensor(len(audio_16k)).unsqueeze(0)
130
+ processed_signal, _ = preprocessor.forward(input_signal=input_signal, length=length)
131
+
132
+ logits = encoder.run(None, {'audio_signal': processed_signal.numpy(), 'length': length.numpy()})[0][0]
133
+
134
+ blank_id = tokenizer.vocab_size()
135
+ decoded_prediction = [p for p in logits.argmax(axis=1).tolist() if p != blank_id]
136
+ text = tokenizer.decode_ids(decoded_prediction)
137
+
138
+ return text
139
+
140
+ def model(text, web_search):
141
+ if web_search is True:
142
+ """Performs a web search, feeds the results to a language model, and returns the answer."""
143
+ web_results = search(text)
144
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
145
+ formatted_prompt = system_instructions1 + text + "[WEB]" + str(web2) + "[OpenGPT 4o]"
146
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
147
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
148
+ else:
149
+ formatted_prompt = system_instructions1 + text + "[OpenGPT 4o]"
150
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
151
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
152
+
153
+ async def respond(audio, web_search):
154
+ user = transcribe(audio)
155
+ reply = model(user, web_search)
156
+ communicate = edge_tts.Communicate(reply)
157
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
158
+ tmp_path = tmp_file.name
159
+ await communicate.save(tmp_path)
160
+ return tmp_path
161
+
162
+ # Streamlit interface
163
+ st.title("OpenGPT 4o DEMO")
164
+
165
+ web_search = st.checkbox("Web Search", value=False)
166
+ input_audio = st.file_uploader("Upload Audio", type=["wav", "mp3", "ogg"])
167
+ if st.button("Transcribe and Respond"):
168
+ if input_audio:
169
+ output_audio_path = asyncio.run(respond(input_audio, web_search))
170
+ audio_file = open(output_audio_path, "rb")
171
+ audio_bytes = audio_file.read()
172
+ st.audio(audio_bytes, format="audio/wav")