Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,25 +1,35 @@
|
|
1 |
import os
|
2 |
-
|
3 |
-
|
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
|
|
|
|
|
|
|
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',
|
@@ -31,86 +41,58 @@ _useragent_list = [
|
|
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
|
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()},
|
58 |
params={
|
59 |
"q": term,
|
60 |
-
"num": num_results - start,
|
61 |
-
"hl":
|
62 |
"start": start,
|
63 |
-
"safe":
|
64 |
},
|
65 |
-
timeout=
|
66 |
-
verify=ssl_verify,
|
67 |
)
|
68 |
-
resp.raise_for_status()
|
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)
|
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 |
|
@@ -128,7 +110,7 @@ def transcribe(audio_path):
|
|
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()
|
@@ -138,8 +120,7 @@ def transcribe(audio_path):
|
|
138 |
return text
|
139 |
|
140 |
def model(text, web_search):
|
141 |
-
if web_search
|
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]"
|
@@ -162,11 +143,33 @@ async def respond(audio, web_search):
|
|
162 |
# Streamlit interface
|
163 |
st.title("OpenGPT 4o DEMO")
|
164 |
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
# Install necessary libraries
|
3 |
+
os.system('pip install streamlit torch onnxruntime transformers sentencepiece pydub soxr edge-tts requests beautifulsoup4')
|
|
|
4 |
|
5 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
import torch
|
7 |
import sentencepiece as spm
|
8 |
import onnxruntime as ort
|
9 |
+
from pydub import AudioSegment
|
10 |
+
import numpy as np
|
11 |
+
import soxr
|
12 |
+
import edge_tts
|
13 |
import requests
|
14 |
from bs4 import BeautifulSoup
|
15 |
import urllib
|
16 |
import random
|
17 |
+
from huggingface_hub import hf_hub_download, InferenceClient
|
18 |
+
import tempfile
|
19 |
+
|
20 |
+
# Install necessary libraries
|
21 |
+
os.system('pip install streamlit torch onnxruntime transformers sentencepiece pydub soxr edge-tts requests beautifulsoup4')
|
22 |
+
|
23 |
+
# Load models
|
24 |
+
model_name = "neongeckocom/stt_en_citrinet_512_gamma_0_25"
|
25 |
+
sample_rate = 16000
|
26 |
+
preprocessor = torch.jit.load(hf_hub_download(model_name, "preprocessor.ts", subfolder="onnx"))
|
27 |
+
encoder = ort.InferenceSession(hf_hub_download(model_name, "model.onnx", subfolder="onnx"))
|
28 |
+
tokenizer = spm.SentencePieceProcessor(hf_hub_download(model_name, "tokenizer.spm", subfolder="onnx"))
|
29 |
+
|
30 |
+
client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
31 |
+
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]"
|
32 |
|
|
|
33 |
_useragent_list = [
|
34 |
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
|
35 |
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
|
|
|
41 |
]
|
42 |
|
43 |
def get_useragent():
|
|
|
44 |
return random.choice(_useragent_list)
|
45 |
|
46 |
def extract_text_from_webpage(html_content):
|
|
|
47 |
soup = BeautifulSoup(html_content, "html.parser")
|
|
|
48 |
for tag in soup(["script", "style", "header", "footer", "nav"]):
|
49 |
tag.extract()
|
|
|
50 |
visible_text = soup.get_text(strip=True)
|
51 |
return visible_text
|
52 |
|
53 |
+
def search(term, num_results=1):
|
|
|
54 |
escaped_term = urllib.parse.quote_plus(term)
|
55 |
start = 0
|
56 |
all_results = []
|
57 |
|
|
|
58 |
while start < num_results:
|
59 |
resp = requests.get(
|
60 |
url="https://www.google.com/search",
|
61 |
+
headers={"User-Agent": get_useragent()},
|
62 |
params={
|
63 |
"q": term,
|
64 |
+
"num": num_results - start,
|
65 |
+
"hl": "en",
|
66 |
"start": start,
|
67 |
+
"safe": "active",
|
68 |
},
|
69 |
+
timeout=5,
|
|
|
70 |
)
|
71 |
+
resp.raise_for_status()
|
|
|
72 |
soup = BeautifulSoup(resp.text, "html.parser")
|
73 |
result_block = soup.find_all("div", attrs={"class": "g"})
|
|
|
|
|
74 |
if not result_block:
|
75 |
start += 1
|
76 |
continue
|
77 |
|
|
|
78 |
for result in result_block:
|
79 |
link = result.find("a", href=True)
|
80 |
if link:
|
81 |
link = link["href"]
|
82 |
try:
|
|
|
83 |
webpage = requests.get(link, headers={"User-Agent": get_useragent()})
|
84 |
webpage.raise_for_status()
|
|
|
85 |
visible_text = extract_text_from_webpage(webpage.text)
|
86 |
all_results.append({"link": link, "text": visible_text})
|
87 |
except requests.exceptions.RequestException as e:
|
|
|
|
|
88 |
all_results.append({"link": link, "text": None})
|
89 |
else:
|
90 |
all_results.append({"link": None, "text": None})
|
91 |
|
92 |
+
start += len(result_block)
|
93 |
|
94 |
return all_results
|
95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
def resample(audio_fp32, sr):
|
97 |
return soxr.resample(audio_fp32, sr, sample_rate)
|
98 |
|
|
|
110 |
input_signal = torch.tensor(audio_16k).unsqueeze(0)
|
111 |
length = torch.tensor(len(audio_16k)).unsqueeze(0)
|
112 |
processed_signal, _ = preprocessor.forward(input_signal=input_signal, length=length)
|
113 |
+
|
114 |
logits = encoder.run(None, {'audio_signal': processed_signal.numpy(), 'length': length.numpy()})[0][0]
|
115 |
|
116 |
blank_id = tokenizer.vocab_size()
|
|
|
120 |
return text
|
121 |
|
122 |
def model(text, web_search):
|
123 |
+
if web_search:
|
|
|
124 |
web_results = search(text)
|
125 |
web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
|
126 |
formatted_prompt = system_instructions1 + text + "[WEB]" + str(web2) + "[OpenGPT 4o]"
|
|
|
143 |
# Streamlit interface
|
144 |
st.title("OpenGPT 4o DEMO")
|
145 |
|
146 |
+
# Chat input interface
|
147 |
+
st.subheader("💬 SuperChat")
|
148 |
+
prompt = st.text_input("Say something")
|
149 |
+
if prompt:
|
150 |
+
web_search = st.checkbox("Web Search", value=True)
|
151 |
+
response = model(prompt, web_search)
|
152 |
+
st.write(response)
|
153 |
+
|
154 |
+
# Audio input interface
|
155 |
+
st.subheader("🗣️ Voice Chat")
|
156 |
+
audio_file = st.file_uploader("Upload an audio file", type=["wav", "mp3"])
|
157 |
+
if audio_file:
|
158 |
+
web_search = st.checkbox("Web Search", value=False)
|
159 |
+
with st.spinner("Transcribing and generating response..."):
|
160 |
+
audio_path = audio_file.name
|
161 |
+
with open(audio_path, "wb") as f:
|
162 |
+
f.write(audio_file.getbuffer())
|
163 |
+
response_audio = await respond(audio_path, web_search)
|
164 |
+
st.audio(response_audio)
|
165 |
+
```
|
166 |
+
|
167 |
+
### Explanation:
|
168 |
+
1. **Library Installation**: Uses `os.system()` to install the required libraries at the beginning of the script.
|
169 |
+
2. **Streamlit Application**: The rest of the script remains the same as previously explained, including the Streamlit UI and the functionalities.
|
170 |
+
|
171 |
+
### How to Run:
|
172 |
+
Save this script as `app.py` and run it using the following command:
|
173 |
+
|
174 |
+
```bash
|
175 |
+
streamlit run app.py
|