Pijush2023 commited on
Commit
b53a225
·
verified ·
1 Parent(s): 415a57d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +712 -5
app.py CHANGED
@@ -1,3 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os
@@ -186,7 +882,7 @@ def fetch_local_weather():
186
  flex: 1;
187
  }}
188
  .weather-details {{
189
- flex: 3;
190
  }}
191
  </style>
192
  """
@@ -338,7 +1034,7 @@ def generate_map(location_names):
338
  if geocode_result:
339
  location = geocode_result[0]['geometry']['location']
340
  folium.Marker(
341
- [location['lat'], location['lng']],
342
  tooltip=f"{geocode_result[0]['formatted_address']}"
343
  ).add_to(m)
344
 
@@ -637,7 +1333,14 @@ def transcribe_and_update_textbox(audio, chat_input):
637
  transcribed_text = transcribe(audio)
638
  # return "",transcribed_text
639
  return transcribed_text
640
-
 
 
 
 
 
 
 
641
 
642
  with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
643
  with gr.Row():
@@ -675,6 +1378,12 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
675
  transcribe_button = gr.Button("Transcribe")
676
  transcribe_button.click(fn=transcribe_and_update_textbox, inputs=[audio_input], outputs=[chat_input],api_name="voice_to_text")
677
 
 
 
 
 
 
 
678
  with gr.Column():
679
  weather_output = gr.HTML(value=fetch_local_weather())
680
  news_output = gr.HTML(value=fetch_local_news())
@@ -695,5 +1404,3 @@ demo.launch(share=True)
695
 
696
 
697
 
698
-
699
-
 
1
+ # import gradio as gr
2
+ # import requests
3
+ # import os
4
+ # import time
5
+ # import re
6
+ # import logging
7
+ # import tempfile
8
+ # import folium
9
+ # import concurrent.futures
10
+ # import torch
11
+ # from PIL import Image
12
+ # from datetime import datetime
13
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
14
+ # from googlemaps import Client as GoogleMapsClient
15
+ # from gtts import gTTS
16
+ # from diffusers import StableDiffusionPipeline
17
+ # from langchain_openai import OpenAIEmbeddings, ChatOpenAI
18
+ # from langchain_pinecone import PineconeVectorStore
19
+ # from langchain.prompts import PromptTemplate
20
+ # from langchain.chains import RetrievalQA
21
+ # from langchain.chains.conversation.memory import ConversationBufferWindowMemory
22
+ # from langchain.agents import Tool, initialize_agent
23
+ # from huggingface_hub import login
24
+ # from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
25
+ # from parler_tts import ParlerTTSForConditionalGeneration
26
+ # from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
27
+ # from scipy.io.wavfile import write as write_wav
28
+ # from pydub import AudioSegment
29
+ # from string import punctuation
30
+ # import librosa
31
+ # from pathlib import Path
32
+ # import torchaudio
33
+
34
+ # # Check if the token is already set in the environment variables
35
+ # hf_token = os.getenv("HF_TOKEN")
36
+ # if hf_token is None:
37
+ # print("Please set your Hugging Face token in the environment variables.")
38
+ # else:
39
+ # login(token=hf_token)
40
+
41
+ # logging.basicConfig(level=logging.DEBUG)
42
+
43
+ # embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
44
+
45
+ # from pinecone import Pinecone
46
+ # pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
47
+
48
+ # index_name = "birmingham-dataset"
49
+ # vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
50
+ # retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
51
+
52
+ # chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
53
+
54
+ # conversational_memory = ConversationBufferWindowMemory(
55
+ # memory_key='chat_history',
56
+ # k=10,
57
+ # return_messages=True
58
+ # )
59
+
60
+ # def get_current_time_and_date():
61
+ # now = datetime.now()
62
+ # return now.strftime("%Y-%m-%d %H:%M:%S")
63
+
64
+ # current_time_and_date = get_current_time_and_date()
65
+
66
+ # def fetch_local_events():
67
+ # api_key = os.environ['SERP_API']
68
+ # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
69
+ # response = requests.get(url)
70
+ # if response.status_code == 200:
71
+ # events_results = response.json().get("events_results", [])
72
+ # events_html = """
73
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
74
+ # <style>
75
+ # table {
76
+ # font-family: 'Verdana', sans-serif;
77
+ # color: #333;
78
+ # border-collapse: collapse;
79
+ # width: 100%;
80
+ # }
81
+ # th, td {
82
+ # border: 1px solid #fff !important;
83
+ # padding: 8px;
84
+ # }
85
+ # th {
86
+ # background-color: #f2f2f2;
87
+ # color: #333;
88
+ # text-align: left;
89
+ # }
90
+ # tr:hover {
91
+ # background-color: #f5f5f5;
92
+ # }
93
+ # .event-link {
94
+ # color: #1E90FF;
95
+ # text-decoration: none;
96
+ # }
97
+ # .event-link:hover {
98
+ # text-decoration: underline;
99
+ # }
100
+ # </style>
101
+ # <table>
102
+ # <tr>
103
+ # <th>Title</th>
104
+ # <th>Date and Time</th>
105
+ # <th>Location</th>
106
+ # </tr>
107
+ # """
108
+ # for event in events_results:
109
+ # title = event.get("title", "No title")
110
+ # date_info = event.get("date", {})
111
+ # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
112
+ # location = event.get("address", "No location")
113
+ # if isinstance(location, list):
114
+ # location = " ".join(location)
115
+ # location = location.replace("[", "").replace("]", "")
116
+ # link = event.get("link", "#")
117
+ # events_html += f"""
118
+ # <tr>
119
+ # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
120
+ # <td>{date}</td>
121
+ # <td>{location}</td>
122
+ # </tr>
123
+ # """
124
+ # events_html += "</table>"
125
+ # return events_html
126
+ # else:
127
+ # return "<p>Failed to fetch local events</p>"
128
+
129
+ # def fetch_local_weather():
130
+ # try:
131
+ # api_key = os.environ['WEATHER_API']
132
+ # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
133
+ # response = requests.get(url)
134
+ # response.raise_for_status()
135
+ # jsonData = response.json()
136
+
137
+ # current_conditions = jsonData.get("currentConditions", {})
138
+ # temp_celsius = current_conditions.get("temp", "N/A")
139
+
140
+ # if temp_celsius != "N/A":
141
+ # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
142
+ # else:
143
+ # temp_fahrenheit = "N/A"
144
+
145
+ # condition = current_conditions.get("conditions", "N/A")
146
+ # humidity = current_conditions.get("humidity", "N/A")
147
+
148
+ # weather_html = f"""
149
+ # <div class="weather-theme">
150
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
151
+ # <div class="weather-content">
152
+ # <div class="weather-icon">
153
+ # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
154
+ # </div>
155
+ # <div class="weather-details">
156
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
157
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
158
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
159
+ # </div>
160
+ # </div>
161
+ # </div>
162
+ # <style>
163
+ # .weather-theme {{
164
+ # animation: backgroundAnimation 10s infinite alternate;
165
+ # border-radius: 10px;
166
+ # padding: 10px;
167
+ # margin-bottom: 15px;
168
+ # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
169
+ # background-size: 400% 400%;
170
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
171
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
172
+ # }}
173
+ # .weather-theme:hover {{
174
+ # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
175
+ # background-position: 100% 100%;
176
+ # }}
177
+ # @keyframes backgroundAnimation {{
178
+ # 0% {{ background-position: 0% 50%; }}
179
+ # 100% {{ background-position: 100% 50%; }}
180
+ # }}
181
+ # .weather-content {{
182
+ # display: flex;
183
+ # align-items: center;
184
+ # }}
185
+ # .weather-icon {{
186
+ # flex: 1;
187
+ # }}
188
+ # .weather-details {{
189
+ # flex: 3;
190
+ # }}
191
+ # </style>
192
+ # """
193
+ # return weather_html
194
+ # except requests.exceptions.RequestException as e:
195
+ # return f"<p>Failed to fetch local weather: {e}</p>"
196
+
197
+ # def get_weather_icon(condition):
198
+ # condition_map = {
199
+ # "Clear": "c01d",
200
+ # "Partly Cloudy": "c02d",
201
+ # "Cloudy": "c03d",
202
+ # "Overcast": "c04d",
203
+ # "Mist": "a01d",
204
+ # "Patchy rain possible": "r01d",
205
+ # "Light rain": "r02d",
206
+ # "Moderate rain": "r03d",
207
+ # "Heavy rain": "r04d",
208
+ # "Snow": "s01d",
209
+ # "Thunderstorm": "t01d",
210
+ # "Fog": "a05d",
211
+ # }
212
+ # return condition_map.get(condition, "c04d")
213
+
214
+ # template1 = """You are an expert concierge who is helpful and a renowned guide for Birmingham,Alabama. Based on weather being a sunny bright day and the today's date is 1st july 2024, use the following pieces of context,
215
+ # memory, and message history, along with your knowledge of perennial events in Birmingham,Alabama, to answer the question at the end. If you don't know the answer, just say "Homie, I need to get more data for this," and don't try to make up an answer.
216
+ # Use fifteen sentences maximum. Keep the answer as detailed as possible. Always include the address, time, date, and
217
+ # event type and description.And also add this Birmingham,AL at the end of each address, Always say "It was my pleasure!" at the end of the answer.
218
+ # {context}
219
+ # Question: {question}
220
+ # Helpful Answer:"""
221
+
222
+ # template2 = """You are an expert concierge who is helpful and a renowned guide for Birmingham,Alabama. Based on today's weather being a sunny bright day and today's date is 16th july 2024, take the location or address but don't show the location or address on the output prompts. Use the following pieces of context,
223
+ # memory, and message history, along with your knowledge of perennial events in Birmingham,Alabama, to answer the question at the end. If you don't know the answer, just say "Homie, I need to get more data for this," and don't try to make up an answer.
224
+ # Keep the answer short ,sweet and crisp and in one shot. Always say "It was my pleasure!" at the end of the answer.
225
+ # {context}
226
+ # Question: {question}
227
+ # Helpful Answer:"""
228
+
229
+ # QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
230
+ # QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
231
+
232
+ # def build_qa_chain(prompt_template):
233
+ # qa_chain = RetrievalQA.from_chain_type(
234
+ # llm=chat_model,
235
+ # chain_type="stuff",
236
+ # retriever=retriever,
237
+ # chain_type_kwargs={"prompt": prompt_template}
238
+ # )
239
+ # tools = [
240
+ # Tool(
241
+ # name='Knowledge Base',
242
+ # func=qa_chain,
243
+ # description='Use this tool when answering general knowledge queries to get more information about the topic'
244
+ # )
245
+ # ]
246
+ # return qa_chain, tools
247
+
248
+ # def initialize_agent_with_prompt(prompt_template):
249
+ # qa_chain, tools = build_qa_chain(prompt_template)
250
+ # agent = initialize_agent(
251
+ # agent='chat-conversational-react-description',
252
+ # tools=tools,
253
+ # llm=chat_model,
254
+ # verbose=False,
255
+ # max_iteration=5,
256
+ # early_stopping_method='generate',
257
+ # memory=conversational_memory
258
+ # )
259
+ # return agent
260
+
261
+ # def generate_answer(message, choice):
262
+ # logging.debug(f"generate_answer called with prompt_choice: {choice}")
263
+
264
+ # if choice == "Details":
265
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_1)
266
+ # elif choice == "Conversational":
267
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
268
+ # else:
269
+ # logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
270
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
271
+ # response = agent(message)
272
+
273
+ # addresses = extract_addresses(response['output'])
274
+ # return response['output'], addresses
275
+
276
+ # def bot(history, choice, tts_choice, state):
277
+ # if not history:
278
+ # return history
279
+ # response, addresses = generate_answer(history[-1][0], choice)
280
+ # history[-1][1] = ""
281
+
282
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
283
+ # if tts_choice == "Alpha":
284
+ # audio_future = executor.submit(generate_audio_elevenlabs, response)
285
+ # elif tts_choice == "Beta":
286
+ # audio_future = executor.submit(generate_audio_parler_tts, response)
287
+ # elif tts_choice == "Gamma":
288
+ # audio_future = executor.submit(generate_audio_mars5, response)
289
+
290
+ # for character in response:
291
+ # history[-1][1] += character
292
+ # time.sleep(0.05)
293
+ # yield history, None
294
+
295
+ # audio_path = audio_future.result()
296
+ # yield history, audio_path
297
+
298
+ # def add_message(history, message):
299
+ # history.append((message, None))
300
+ # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
301
+
302
+ # def print_like_dislike(x: gr.LikeData):
303
+ # print(x.index, x.value, x.liked)
304
+
305
+ # def extract_addresses(response):
306
+ # if not isinstance(response, str):
307
+ # response = str(response)
308
+ # address_patterns = [
309
+ # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
310
+ # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
311
+ # r'([A-Z].*,\sAL\s\d{5})',
312
+ # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
313
+ # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
314
+ # r'(\d{2}.*\sStreets)',
315
+ # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
316
+ # r'([a-zA-Z]\s Birmingham)',
317
+ # r'([a-zA-Z].*,\sBirmingham,\sAL)',
318
+ # r'(^Birmingham,AL$)'
319
+ # ]
320
+ # addresses = []
321
+ # for pattern in address_patterns:
322
+ # addresses.extend(re.findall(pattern, response))
323
+ # return addresses
324
+
325
+ # all_addresses = []
326
+
327
+ # def generate_map(location_names):
328
+ # global all_addresses
329
+ # all_addresses.extend(location_names)
330
+
331
+ # api_key = os.environ['GOOGLEMAPS_API_KEY']
332
+ # gmaps = GoogleMapsClient(key=api_key)
333
+
334
+ # m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
335
+
336
+ # for location_name in all_addresses:
337
+ # geocode_result = gmaps.geocode(location_name)
338
+ # if geocode_result:
339
+ # location = geocode_result[0]['geometry']['location']
340
+ # folium.Marker(
341
+ # [location['lat'], location['lng']],
342
+ # tooltip=f"{geocode_result[0]['formatted_address']}"
343
+ # ).add_to(m)
344
+
345
+ # map_html = m._repr_html_()
346
+ # return map_html
347
+
348
+ # def fetch_local_news():
349
+ # api_key = os.environ['SERP_API']
350
+ # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
351
+ # response = requests.get(url)
352
+ # if response.status_code == 200:
353
+ # results = response.json().get("news_results", [])
354
+ # news_html = """
355
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
356
+ # <style>
357
+ # .news-item {
358
+ # font-family: 'Verdana', sans-serif;
359
+ # color: #333;
360
+ # background-color: #f0f8ff;
361
+ # margin-bottom: 15px;
362
+ # padding: 10px;
363
+ # border-radius: 5px;
364
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
365
+ # font-weight: bold;
366
+ # }
367
+ # .news-item:hover {
368
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
369
+ # background-color: #e6f7ff;
370
+ # }
371
+ # .news-item a {
372
+ # color: #1E90FF;
373
+ # text-decoration: none;
374
+ # font-weight: bold;
375
+ # }
376
+ # .news-item a:hover {
377
+ # text-decoration: underline;
378
+ # }
379
+ # .news-preview {
380
+ # position: absolute;
381
+ # display: none;
382
+ # border: 1px solid #ccc;
383
+ # border-radius: 5px;
384
+ # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
385
+ # background-color: white;
386
+ # z-index: 1000;
387
+ # max-width: 300px;
388
+ # padding: 10px;
389
+ # font-family: 'Verdana', sans-serif;
390
+ # color: #333;
391
+ # }
392
+ # </style>
393
+ # <script>
394
+ # function showPreview(event, previewContent) {
395
+ # var previewBox = document.getElementById('news-preview');
396
+ # previewBox.innerHTML = previewContent;
397
+ # previewBox.style.left = event.pageX + 'px';
398
+ # previewBox.style.top = event.pageY + 'px';
399
+ # previewBox.style.display = 'block';
400
+ # }
401
+ # function hidePreview() {
402
+ # var previewBox = document.getElementById('news-preview');
403
+ # previewBox.style.display = 'none';
404
+ # }
405
+ # </script>
406
+ # <div id="news-preview" class="news-preview"></div>
407
+ # """
408
+ # for index, result in enumerate(results[:7]):
409
+ # title = result.get("title", "No title")
410
+ # link = result.get("link", "#")
411
+ # snippet = result.get("snippet", "")
412
+ # news_html += f"""
413
+ # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
414
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
415
+ # <p>{snippet}</p>
416
+ # </div>
417
+ # """
418
+ # return news_html
419
+ # else:
420
+ # return "<p>Failed to fetch local news</p>"
421
+
422
+ # import numpy as np
423
+ # import torch
424
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
425
+
426
+ # model_id = 'openai/whisper-large-v3'
427
+ # device = "cuda:0" if torch.cuda.is_available() else "cpu"
428
+ # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
429
+ # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
430
+ # processor = AutoProcessor.from_pretrained(model_id)
431
+
432
+ # pipe_asr = pipeline("automatic-speech-recognition", model=model, tokenizer=processor.tokenizer, feature_extractor=processor.feature_extractor, max_new_tokens=128, chunk_length_s=15, batch_size=16, torch_dtype=torch_dtype, device=device, return_timestamps=True)
433
+
434
+ # base_audio_drive = "/data/audio"
435
+
436
+ # # Integrate the transcriber function
437
+ # transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-base.en")
438
+
439
+ # def transcribe(audio):
440
+ # sr, y = audio
441
+ # y = y.astype(np.float32)
442
+ # y /= np.max(np.abs(y))
443
+ # return transcriber({"sampling_rate": sr, "raw": y})["text"] # type: ignore
444
+
445
+ # def transcribe_function(stream, new_chunk):
446
+ # sr, y = new_chunk[0], new_chunk[1]
447
+ # y = y.astype(np.float32) / np.max(np.abs(y))
448
+ # if stream is not None:
449
+ # stream = np.concatenate([stream, y])
450
+ # else:
451
+ # stream = y
452
+ # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
453
+ # full_text = result.get("text", "")
454
+ # return stream, full_text # Return the transcribed text
455
+
456
+ # def update_map_with_response(history):
457
+ # if not history:
458
+ # return ""
459
+ # response = history[-1][1]
460
+ # addresses = extract_addresses(response)
461
+ # return generate_map(addresses)
462
+
463
+ # def clear_textbox():
464
+ # return ""
465
+
466
+ # def show_map_if_details(history, choice):
467
+ # if choice in ["Details", "Conversational"]:
468
+ # return gr.update(visible=True), update_map_with_response(history)
469
+ # else:
470
+ # return gr.update(visible=False), ""
471
+
472
+ # def generate_audio_elevenlabs(text):
473
+ # XI_API_KEY = os.environ['ELEVENLABS_API']
474
+ # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
475
+ # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
476
+ # headers = {
477
+ # "Accept": "application/json",
478
+ # "xi-api-key": XI_API_KEY
479
+ # }
480
+ # data = {
481
+ # "text": str(text),
482
+ # "model_id": "eleven_multilingual_v2",
483
+ # "voice_settings": {
484
+ # "stability": 1.0,
485
+ # "similarity_boost": 0.0,
486
+ # "style": 0.60,
487
+ # "use_speaker_boost": False
488
+ # }
489
+ # }
490
+ # response = requests.post(tts_url, headers=headers, json=data, stream=True)
491
+ # if response.ok:
492
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
493
+ # for chunk in response.iter_content(chunk_size=1024):
494
+ # f.write(chunk)
495
+ # temp_audio_path = f.name
496
+ # logging.debug(f"Audio saved to {temp_audio_path}")
497
+ # return temp_audio_path
498
+ # else:
499
+ # logging.error(f"Error generating audio: {response.text}")
500
+ # return None
501
+
502
+ # repo_id = "parler-tts/parler-tts-mini-expresso"
503
+
504
+ # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
505
+ # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
506
+ # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
507
+
508
+ # SAMPLE_RATE = parler_feature_extractor.sampling_rate
509
+ # SEED = 42
510
+
511
+ # def preprocess(text):
512
+ # number_normalizer = EnglishNumberNormalizer()
513
+ # text = number_normalizer(text).strip()
514
+ # if text[-1] not in punctuation:
515
+ # text = f"{text}."
516
+
517
+ # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
518
+
519
+ # def separate_abb(chunk):
520
+ # chunk = chunk.replace(".", "")
521
+ # return " ".join(chunk)
522
+
523
+ # abbreviations = re.findall(abbreviations_pattern, text)
524
+ # for abv in abbreviations:
525
+ # if abv in text:
526
+ # text = text.replace(abv, separate_abb(abv))
527
+ # return text
528
+
529
+ # def chunk_text(text, max_length=250):
530
+ # words = text.split()
531
+ # chunks = []
532
+ # current_chunk = []
533
+ # current_length = 0
534
+
535
+ # for word in words:
536
+ # if current_length + len(word) + 1 <= max_length:
537
+ # current_chunk.append(word)
538
+ # current_length += len(word) + 1
539
+ # else:
540
+ # chunks.append(' '.join(current_chunk))
541
+ # current_chunk = [word]
542
+ # current_length = len(word) + 1
543
+
544
+ # if current_chunk:
545
+ # chunks.append(' '.join(current_chunk))
546
+
547
+ # return chunks
548
+
549
+ # def generate_audio_parler_tts(text):
550
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
551
+ # chunks = chunk_text(preprocess(text))
552
+ # audio_segments = []
553
+
554
+ # for chunk in chunks:
555
+ # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
556
+ # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
557
+
558
+ # set_seed(SEED)
559
+ # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
560
+ # audio_arr = generation.cpu().numpy().squeeze()
561
+
562
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
563
+ # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
564
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
565
+
566
+ # combined_audio = sum(audio_segments)
567
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
568
+ # combined_audio.export(combined_audio_path, format="wav")
569
+
570
+ # logging.debug(f"Audio saved to {combined_audio_path}")
571
+ # return combined_audio_path
572
+
573
+ # # Load the MARS5 model
574
+ # mars5, config_class = torch.hub.load('Camb-ai/mars5-tts', 'mars5_english', trust_repo=True)
575
+
576
+ # def generate_audio_mars5(text):
577
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
578
+ # kwargs_dict = {
579
+ # 'temperature': 0.2,
580
+ # 'top_k': -1,
581
+ # 'top_p': 0.2,
582
+ # 'typical_p': 1.0,
583
+ # 'freq_penalty': 2.6,
584
+ # 'presence_penalty': 0.4,
585
+ # 'rep_penalty_window': 100,
586
+ # 'max_prompt_phones': 360,
587
+ # 'deep_clone': True,
588
+ # 'nar_guidance_w': 3
589
+ # }
590
+
591
+ # chunks = chunk_text(preprocess(text))
592
+ # audio_segments = []
593
+
594
+ # for chunk in chunks:
595
+ # wav = torch.zeros(1, mars5.sr) # Use a placeholder silent audio for the reference
596
+ # cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
597
+ # ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
598
+
599
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
600
+ # torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
601
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
602
+
603
+ # combined_audio = sum(audio_segments)
604
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "mars5_combined_audio.wav")
605
+ # combined_audio.export(combined_audio_path, format="wav")
606
+
607
+ # logging.debug(f"Audio saved to {combined_audio_path}")
608
+ # return combined_audio_path
609
+
610
+ # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
611
+ # pipe.to(device)
612
+
613
+ # def generate_image(prompt):
614
+ # with torch.cuda.amp.autocast():
615
+ # image = pipe(
616
+ # prompt,
617
+ # num_inference_steps=28,
618
+ # guidance_scale=3.0,
619
+ # ).images[0]
620
+ # return image
621
+
622
+ # hardcoded_prompt_1 = "Give a high quality photograph of a great looking red 2026 Toyota coupe against a skyline setting in the night, michael mann style in omaha enticing the consumer to buy this product"
623
+ # hardcoded_prompt_2 = "A vibrant and dynamic football game scene in the style of Peter Paul Rubens, showcasing the intense match between Alabama and Nebraska. The players are depicted with the dramatic, muscular physiques and expressive faces typical of Rubens' style. The Alabama team is wearing their iconic crimson and white uniforms, while the Nebraska team is in their classic red and white attire. The scene is filled with action, with players in mid-motion, tackling, running, and catching the ball. The background features a grand stadium filled with cheering fans, banners, and the natural landscape in the distance. The colors are rich and vibrant, with a strong use of light and shadow to create depth and drama. The overall atmosphere captures the intensity and excitement of the game, infused with the grandeur and dynamism characteristic of Rubens' work."
624
+ # hardcoded_prompt_3 = "Create a high-energy scene of a DJ performing on a large stage with vibrant lights, colorful lasers, a lively dancing crowd, and various electronic equipment in the background."
625
+
626
+ # def update_images():
627
+ # image_1 = generate_image(hardcoded_prompt_1)
628
+ # image_2 = generate_image(hardcoded_prompt_2)
629
+ # image_3 = generate_image(hardcoded_prompt_3)
630
+ # return image_1, image_2, image_3
631
+
632
+ # def clear_state_and_textbox():
633
+ # conversational_memory.clear()
634
+ # return ""
635
+
636
+ # def transcribe_and_update_textbox(audio, chat_input):
637
+ # transcribed_text = transcribe(audio)
638
+ # # return "",transcribed_text
639
+ # return transcribed_text
640
+
641
+
642
+ # with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
643
+ # with gr.Row():
644
+ # with gr.Column():
645
+ # state = gr.State()
646
+
647
+ # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
648
+ # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
649
+
650
+ # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
651
+
652
+ # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!", placeholder="After Prompt, click Retriever Only")
653
+ # chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input], api_name="voice_query")
654
+ # tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta", "Gamma"], value="Alpha")
655
+ # retriever_button = gr.Button("Retriever")
656
+
657
+ # gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
658
+ # location_output = gr.HTML()
659
+ # retriever_button.click(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input]).then(
660
+ # fn=bot, inputs=[chatbot, choice, tts_choice, state], outputs=[chatbot, gr.Audio(interactive=False, autoplay=True)], api_name="Ask_Retriever").then(
661
+ # fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder").then(
662
+ # fn=clear_state_and_textbox, inputs=[], outputs=[chat_input]
663
+ # )
664
+
665
+ # bot_msg = chat_msg.then(bot, [chatbot, choice, tts_choice], [chatbot], api_name="generate_voice_response")
666
+ # bot_msg.then(lambda: gr.Textbox(value="", interactive=True, placeholder="Ask Radar!!!...", show_label=False), None, [chat_input])
667
+ # chatbot.like(print_like_dislike, None, None)
668
+ # clear_button = gr.Button("Clear")
669
+ # clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
670
+
671
+ # # Recorder section
672
+
673
+ # gr.Markdown("<h2>Hey Radar</h2>")
674
+ # audio_input = gr.Audio(sources=["microphone"], type='numpy')
675
+ # transcribe_button = gr.Button("Transcribe")
676
+ # transcribe_button.click(fn=transcribe_and_update_textbox, inputs=[audio_input], outputs=[chat_input],api_name="voice_to_text")
677
+
678
+ # with gr.Column():
679
+ # weather_output = gr.HTML(value=fetch_local_weather())
680
+ # news_output = gr.HTML(value=fetch_local_news())
681
+ # news_output = gr.HTML(value=fetch_local_events())
682
+
683
+ # with gr.Column():
684
+ # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
685
+ # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
686
+ # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
687
+
688
+ # refresh_button = gr.Button("Refresh Images")
689
+ # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
690
+ # # location_output = gr.HTML()
691
+ # bot_msg.then(show_map_if_details, [chatbot, choice], [location_output, location_output], api_name="map_finder")
692
+
693
+ # demo.queue()
694
+ # demo.launch(share=True)
695
+
696
+
697
  import gradio as gr
698
  import requests
699
  import os
 
882
  flex: 1;
883
  }}
884
  .weather-details {{
885
+ flex 3;
886
  }}
887
  </style>
888
  """
 
1034
  if geocode_result:
1035
  location = geocode_result[0]['geometry']['location']
1036
  folium.Marker(
1037
+ [location['lat'], 'location['lng']],
1038
  tooltip=f"{geocode_result[0]['formatted_address']}"
1039
  ).add_to(m)
1040
 
 
1333
  transcribed_text = transcribe(audio)
1334
  # return "",transcribed_text
1335
  return transcribed_text
1336
+
1337
+ def transcribe_function_whisper(audio):
1338
+ sr, y = audio
1339
+ y = y.astype(np.float32)
1340
+ y /= np.max(np.abs(y))
1341
+ result = pipe_asr({"array": y, "sampling_rate": sr}, return_timestamps=False)
1342
+ full_text = result.get("text", "")
1343
+ return full_text
1344
 
1345
  with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1346
  with gr.Row():
 
1378
  transcribe_button = gr.Button("Transcribe")
1379
  transcribe_button.click(fn=transcribe_and_update_textbox, inputs=[audio_input], outputs=[chat_input],api_name="voice_to_text")
1380
 
1381
+ # New ASR Component with Whisper
1382
+ gr.Markdown("<h2>Whisper ASR</h2>")
1383
+ audio_input_whisper = gr.Audio(sources=["microphone"], type='numpy')
1384
+ transcribe_button_whisper = gr.Button("Transcribe with Whisper")
1385
+ transcribe_button_whisper.click(fn=transcribe_function_whisper, inputs=[audio_input_whisper], outputs=[chat_input], api_name="whisper_asr")
1386
+
1387
  with gr.Column():
1388
  weather_output = gr.HTML(value=fetch_local_weather())
1389
  news_output = gr.HTML(value=fetch_local_news())
 
1404
 
1405
 
1406