Pijush2023 commited on
Commit
6ef7b9a
·
verified ·
1 Parent(s): 9cad0ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +313 -903
app.py CHANGED
@@ -1,887 +1,3 @@
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 = "birminghumsummary1"
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
-
67
- # # def fetch_local_events():
68
- # # api_key = os.environ['SERP_API']
69
- # # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
70
- # # response = requests.get(url)
71
- # # if response.status_code == 200:
72
- # # events_results = response.json().get("events_results", [])
73
- # # events_html = """
74
- # # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
75
- # # <style>
76
- # # table {
77
- # # font-family: 'Verdana', sans-serif;
78
- # # color: #333;
79
- # # border-collapse: collapse;
80
- # # width: 100%;
81
- # # }
82
- # # th, td {
83
- # # border: 1px solid #ddd;
84
- # # padding: 8px;
85
- # # }
86
- # # th {
87
- # # background-color: #f2f2f2;
88
- # # color: #333;
89
- # # text-align: left;
90
- # # }
91
- # # tr:hover {
92
- # # background-color: #f5f5f5;
93
- # # }
94
- # # .event-link {
95
- # # color: #1E90FF;
96
- # # text-decoration: none;
97
- # # }
98
- # # .event-link:hover {
99
- # # text-decoration: underline;
100
- # # }
101
- # # </style>
102
- # # <table>
103
- # # <tr>
104
- # # <th>Title</th>
105
- # # <th>Date and Time</th>
106
- # # <th>Location</th>
107
- # # </tr>
108
- # # """
109
- # # for event in events_results:
110
- # # title = event.get("title", "No title")
111
- # # date_info = event.get("date", {})
112
- # # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
113
- # # location = event.get("address", "No location")
114
- # # if isinstance(location, list):
115
- # # location = " ".join(location)
116
- # # location = location.replace("[", "").replace("]", "")
117
- # # link = event.get("link", "#")
118
- # # events_html += f"""
119
- # # <tr>
120
- # # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
121
- # # <td>{date}</td>
122
- # # <td>{location}</td>
123
- # # </tr>
124
- # # """
125
- # # events_html += "</table>"
126
- # # return events_html
127
- # # else:
128
- # # return "<p>Failed to fetch local events</p>"
129
-
130
- # def fetch_local_events():
131
-
132
-
133
- # api_key = os.environ['SERP_API']
134
- # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
135
- # response = requests.get(url)
136
- # if response.status_code == 200:
137
- # events_results = response.json().get("events_results", [])
138
- # events_html = """
139
- # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
140
- # <style>
141
- # table {
142
- # font-family: 'Verdana', sans-serif;
143
- # color: #333;
144
- # border-collapse: collapse;
145
- # width: 100%;
146
- # }
147
- # th, td {
148
- # border: 1px solid #fff !important;
149
- # padding: 8px;
150
- # }
151
- # th {
152
- # background-color: #f2f2f2;
153
- # color: #333;
154
- # text-align: left;
155
- # }
156
- # tr:hover {
157
- # background-color: #f5f5f5;
158
- # }
159
- # .event-link {
160
- # color: #1E90FF;
161
- # text-decoration: none;
162
- # }
163
- # .event-link:hover {
164
- # text-decoration: underline;
165
- # }
166
- # </style>
167
- # <table>
168
- # <tr>
169
- # <th>Title</th>
170
- # <th>Date and Time</th>
171
- # <th>Location</th>
172
- # </tr>
173
- # """
174
- # for event in events_results:
175
- # title = event.get("title", "No title")
176
- # date_info = event.get("date", {})
177
- # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
178
- # location = event.get("address", "No location")
179
- # if isinstance(location, list):
180
- # location = " ".join(location)
181
- # location = location.replace("[", "").replace("]", "")
182
- # link = event.get("link", "#")
183
- # events_html += f"""
184
- # <tr>
185
- # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
186
- # <td>{date}</td>
187
- # <td>{location}</td>
188
- # </tr>
189
- # """
190
- # events_html += "</table>"
191
- # return events_html
192
- # else:
193
- # return "<p>Failed to fetch local events</p>"
194
-
195
-
196
-
197
-
198
- # def fetch_local_weather():
199
- # try:
200
- # api_key = os.environ['WEATHER_API']
201
- # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
202
- # response = requests.get(url)
203
- # response.raise_for_status()
204
- # jsonData = response.json()
205
-
206
- # current_conditions = jsonData.get("currentConditions", {})
207
- # temp_celsius = current_conditions.get("temp", "N/A")
208
-
209
- # if temp_celsius != "N/A":
210
- # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
211
- # else:
212
- # temp_fahrenheit = "N/A"
213
-
214
- # condition = current_conditions.get("conditions", "N/A")
215
- # humidity = current_conditions.get("humidity", "N/A")
216
-
217
- # weather_html = f"""
218
- # <div class="weather-theme">
219
- # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
220
- # <div class="weather-content">
221
- # <div class="weather-icon">
222
- # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
223
- # </div>
224
- # <div class="weather-details">
225
- # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
226
- # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
227
- # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
228
- # </div>
229
- # </div>
230
- # </div>
231
- # <style>
232
- # .weather-theme {{
233
- # animation: backgroundAnimation 10s infinite alternate;
234
- # border-radius: 10px;
235
- # padding: 10px;
236
- # margin-bottom: 15px;
237
- # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
238
- # background-size: 400% 400%;
239
- # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
240
- # transition: box-shadow 0.3s ease, background-color 0.3s ease;
241
- # }}
242
- # .weather-theme:hover {{
243
- # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
244
- # background-position: 100% 100%;
245
- # }}
246
- # @keyframes backgroundAnimation {{
247
- # 0% {{ background-position: 0% 50%; }}
248
- # 100% {{ background-position: 100% 50%; }}
249
- # }}
250
- # .weather-content {{
251
- # display: flex;
252
- # align-items: center;
253
- # }}
254
- # .weather-icon {{
255
- # flex: 1;
256
- # }}
257
- # .weather-details {{
258
- # flex: 3;
259
- # }}
260
- # </style>
261
- # """
262
- # return weather_html
263
- # except requests.exceptions.RequestException as e:
264
- # return f"<p>Failed to fetch local weather: {e}</p>"
265
-
266
- # def get_weather_icon(condition):
267
- # condition_map = {
268
- # "Clear": "c01d",
269
- # "Partly Cloudy": "c02d",
270
- # "Cloudy": "c03d",
271
- # "Overcast": "c04d",
272
- # "Mist": "a01d",
273
- # "Patchy rain possible": "r01d",
274
- # "Light rain": "r02d",
275
- # "Moderate rain": "r03d",
276
- # "Heavy rain": "r04d",
277
- # "Snow": "s01d",
278
- # "Thunderstorm": "t01d",
279
- # "Fog": "a05d",
280
- # }
281
- # return condition_map.get(condition, "c04d")
282
-
283
- # 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,
284
- # 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.
285
- # Use fifteen sentences maximum. Keep the answer as detailed as possible. Always include the address, time, date, and
286
- # 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.
287
- # {context}
288
- # Question: {question}
289
- # Helpful Answer:"""
290
-
291
-
292
- # # 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 1st 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,
293
- # # 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.
294
- # # Keep the answer short and sweet and crisp. Always say "It was my pleasure!" at the end of the answer.
295
- # # {context}
296
- # # Question: {question}
297
- # # Helpful Answer:"""
298
-
299
- # 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,
300
- # 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.
301
- # Keep the answer short ,sweet and crisp and in one shot. Always say "It was my pleasure!" at the end of the answer.
302
- # {context}
303
- # Question: {question}
304
- # Helpful Answer:"""
305
-
306
- # QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
307
- # QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
308
-
309
- # def build_qa_chain(prompt_template):
310
- # qa_chain = RetrievalQA.from_chain_type(
311
- # llm=chat_model,
312
- # chain_type="stuff",
313
- # retriever=retriever,
314
- # chain_type_kwargs={"prompt": prompt_template}
315
- # )
316
- # tools = [
317
- # Tool(
318
- # name='Knowledge Base',
319
- # func=qa_chain,
320
- # description='Use this tool when answering general knowledge queries to get more information about the topic'
321
- # )
322
- # ]
323
- # return qa_chain, tools
324
-
325
- # def initialize_agent_with_prompt(prompt_template):
326
- # qa_chain, tools = build_qa_chain(prompt_template)
327
- # agent = initialize_agent(
328
- # agent='chat-conversational-react-description',
329
- # tools=tools,
330
- # llm=chat_model,
331
- # verbose=False,
332
- # max_iteration=5,
333
- # early_stopping_method='generate',
334
- # memory=conversational_memory
335
- # )
336
- # return agent
337
-
338
-
339
- # def generate_answer(message, choice):
340
- # logging.debug(f"generate_answer called with prompt_choice: {choice}")
341
-
342
- # if choice == "Details":
343
- # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_1)
344
- # elif choice == "Conversational":
345
- # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
346
- # else:
347
- # logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
348
- # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
349
-
350
- # response = agent(message)
351
- # addresses = extract_addresses(response['output'])
352
- # return response['output'], addresses
353
-
354
- # def bot(history, choice, tts_choice):
355
- # if not history:
356
- # return history
357
-
358
- # user_message = history[-1][0]
359
- # response_text, addresses = generate_answer(user_message, choice)
360
-
361
- # # Ensure history has the correct format
362
- # if len(history[-1]) == 1:
363
- # history[-1].append(response_text)
364
- # else:
365
- # history[-1][1] = response_text
366
-
367
- # with concurrent.futures.ThreadPoolExecutor() as executor:
368
- # if tts_choice == "Alpha":
369
- # audio_future = executor.submit(generate_audio_elevenlabs, response_text)
370
- # elif tts_choice == "Beta":
371
- # audio_future = executor.submit(generate_audio_parler_tts, response_text)
372
- # elif tts_choice == "Gamma":
373
- # audio_future = executor.submit(generate_audio_mars5, response_text)
374
-
375
- # for character in response_text:
376
- # history[-1][1] += character
377
- # time.sleep(0.05)
378
- # yield history, None
379
-
380
- # audio_path = audio_future.result()
381
- # yield history, audio_path
382
-
383
- # def add_message(history, message):
384
- # history = history or []
385
- # history.append([message, ""]) # Ensure it is a list with two elements: message and empty response
386
- # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
387
- # #----------------------------------part 1-------------------------
388
- # # def generate_answer(message, choice):
389
- # # logging.debug(f"generate_answer called with prompt_choice: {choice}")
390
-
391
- # # if choice == "Details":
392
- # # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_1)
393
- # # elif choice == "Conversational":
394
- # # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
395
- # # else:
396
- # # logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
397
- # # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
398
- # # response = agent(message)
399
-
400
- # # addresses = extract_addresses(response['output'])
401
- # # return response['output'], addresses
402
-
403
-
404
-
405
- # # # def bot(history, choice, tts_choice):
406
- # # # if not history:
407
- # # # return history
408
- # # # response_pair, addresses = generate_answer(history[-1][0], choice)
409
- # # # history[-1] = response_pair # Update bot response correctly
410
-
411
- # # # with concurrent.futures.ThreadPoolExecutor() as executor:
412
- # # # if tts_choice == "Alpha":
413
- # # # audio_future = executor.submit(generate_audio_elevenlabs, response_pair[1])
414
- # # # elif tts_choice == "Beta":
415
- # # # audio_future = executor.submit(generate_audio_parler_tts, response_pair[1])
416
- # # # elif tts_choice == "Gamma":
417
- # # # audio_future = executor.submit(generate_audio_mars5, response_pair[1])
418
-
419
- # # # for character in response_pair[1]:
420
- # # # history[-1][1] += character
421
- # # # time.sleep(0.05)
422
- # # # yield history, None
423
-
424
- # # # audio_path = audio_future.result()
425
- # # # yield history, audio_path
426
-
427
- # # # def add_message(history, message):
428
- # # # history = history or []
429
- # # # history.append([message, ""]) # Ensure it is a list with two elements: message and empty response
430
- # # # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
431
-
432
- # # def bot(history, choice, tts_choice):
433
- # # if not history:
434
- # # return history
435
- # # response_pair, addresses = generate_answer(history[-1][0], choice)
436
- # # # Ensure history has the correct format
437
- # # if len(history[-1]) == 1:
438
- # # history[-1].append("")
439
- # # elif len(history[-1]) == 0:
440
- # # history[-1] = [history[-1][0], ""]
441
-
442
- # # with concurrent.futures.ThreadPoolExecutor() as executor:
443
- # # if tts_choice == "Alpha":
444
- # # audio_future = executor.submit(generate_audio_elevenlabs, response_pair[1])
445
- # # elif tts_choice == "Beta":
446
- # # audio_future = executor.submit(generate_audio_parler_tts, response_pair[1])
447
- # # elif tts_choice == "Gamma":
448
- # # audio_future = executor.submit(generate_audio_mars5, response_pair[1])
449
-
450
- # # for character in response_pair[1]:
451
- # # history[-1][1] += character
452
- # # time.sleep(0.05)
453
- # # yield history, None
454
-
455
- # # audio_path = audio_future.result()
456
- # # yield history, audio_path
457
-
458
- # # def add_message(history, message):
459
- # # history = history or []
460
- # # history.append([message, ""]) # Ensure it is a list with two elements: message and empty response
461
- # # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
462
- # #--------------------------------------------------------
463
- # # def generate_voice_response(history, tts_choice):
464
- # # if not history:
465
- # # return None
466
-
467
- # # response = history[-1][1]
468
- # # with concurrent.futures.ThreadPoolExecutor() as executor:
469
- # # if tts_choice == "Alpha":
470
- # # audio_future = executor.submit(generate_audio_elevenlabs, response)
471
- # # elif tts_choice == "Beta":
472
- # # audio_future = executor.submit(generate_audio_parler_tts, response)
473
- # # elif tts_choice == "Gamma":
474
- # # audio_future = executor.submit(generate_audio_mars5, response)
475
-
476
- # # audio_path = audio_future.result()
477
- # # return audio_path
478
-
479
- # def print_like_dislike(x: gr.LikeData):
480
- # print(x.index, x.value, x.liked)
481
-
482
- # def extract_addresses(response):
483
- # if not isinstance(response, str):
484
- # response = str(response)
485
- # address_patterns = [
486
- # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
487
- # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
488
- # r'([A-Z].*,\sAL\s\d{5})',
489
- # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
490
- # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
491
- # r'(\d{2}.*\sStreets)',
492
- # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
493
- # r'([a-zA-Z]\s Birmingham)',
494
- # r'([a-zA-Z].*,\sBirmingham,\sAL)'
495
- # ]
496
- # addresses = []
497
- # for pattern in address_patterns:
498
- # addresses.extend(re.findall(pattern, response))
499
- # return addresses
500
-
501
- # all_addresses = []
502
-
503
- # # def generate_map(location_names):
504
- # # global all_addresses
505
- # # all_addresses.extend(location_names)
506
-
507
- # # api_key = os.environ['GOOGLEMAPS_API_KEY']
508
- # # gmaps = GoogleMapsClient(key=api_key)
509
-
510
- # # m = folium.Map(location=[33.5175,-86.809444], zoom_start=16)
511
-
512
- # # for location_name in all_addresses:
513
- # # geocode_result = gmaps.geocode(location_name)
514
- # # if geocode_result:
515
- # # location = geocode_result[0]['geometry']['location']
516
- # # folium.Marker(
517
- # # [location['lat'], 'lng'],
518
- # # tooltip=f"{geocode_result[0]['formatted_address']}"
519
- # # ).add_to(m)
520
-
521
- # # map_html = m._repr_html_()
522
- # # return map_html
523
-
524
- # def generate_map(location_names):
525
- # global all_addresses
526
- # all_addresses.extend(location_names)
527
-
528
- # api_key = os.environ['GOOGLEMAPS_API_KEY']
529
- # gmaps = GoogleMapsClient(key=api_key)
530
-
531
- # m = folium.Map(location=[33.5175, -86.809444], zoom_start=20)
532
-
533
- # for location_name in all_addresses:
534
- # geocode_result = gmaps.geocode(location_name)
535
- # if geocode_result:
536
- # location = geocode_result[0]['geometry']['location']
537
- # folium.Marker(
538
- # [location['lat'], location['lng']],
539
- # tooltip=f"{geocode_result[0]['formatted_address']}"
540
- # ).add_to(m)
541
-
542
- # map_html = m._repr_html_()
543
- # return map_html
544
-
545
-
546
- # def fetch_local_news():
547
- # api_key = os.environ['SERP_API']
548
- # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
549
- # response = requests.get(url)
550
- # if response.status_code == 200:
551
- # results = response.json().get("news_results", [])
552
- # news_html = """
553
- # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
554
- # <style>
555
- # .news-item {
556
- # font-family: 'Verdana', sans-serif;
557
- # color: #333;
558
- # background-color: #f0f8ff;
559
- # margin-bottom: 15px;
560
- # padding: 10px;
561
- # border-radius: 5px;
562
- # transition: box-shadow 0.3s ease, background-color 0.3s ease;
563
- # font-weight: bold;
564
- # }
565
- # .news-item:hover {
566
- # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
567
- # background-color: #e6f7ff;
568
- # }
569
- # .news-item a {
570
- # color: #1E90FF;
571
- # text-decoration: none;
572
- # font-weight: bold;
573
- # }
574
- # .news-item a:hover {
575
- # text-decoration: underline;
576
- # }
577
- # .news-preview {
578
- # position: absolute;
579
- # display: none;
580
- # border: 1px solid #ccc;
581
- # border-radius: 5px;
582
- # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
583
- # background-color: white;
584
- # z-index: 1000;
585
- # max-width: 300px;
586
- # padding: 10px;
587
- # font-family: 'Verdana', sans-serif;
588
- # color: #333;
589
- # }
590
- # </style>
591
- # <script>
592
- # function showPreview(event, previewContent) {
593
- # var previewBox = document.getElementById('news-preview');
594
- # previewBox.innerHTML = previewContent;
595
- # previewBox.style.left = event.pageX + 'px';
596
- # previewBox.style.top = event.pageY + 'px';
597
- # previewBox.style.display = 'block';
598
- # }
599
- # function hidePreview() {
600
- # var previewBox = document.getElementById('news-preview');
601
- # previewBox.style.display = 'none';
602
- # }
603
- # </script>
604
- # <div id="news-preview" class="news-preview"></div>
605
- # """
606
- # for index, result in enumerate(results[:7]):
607
- # title = result.get("title", "No title")
608
- # link = result.get("link", "#")
609
- # snippet = result.get("snippet", "")
610
- # news_html += f"""
611
- # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
612
- # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
613
- # <p>{snippet}</p>
614
- # </div>
615
- # """
616
- # return news_html
617
- # else:
618
- # return "<p>Failed to fetch local news</p>"
619
-
620
- # import numpy as np
621
- # import torch
622
- # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
623
-
624
- # model_id = 'openai/whisper-large-v3'
625
- # device = "cuda:0" if torch.cuda.is_available() else "cpu"
626
- # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
627
- # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
628
- # processor = AutoProcessor.from_pretrained(model_id)
629
-
630
- # 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)
631
-
632
- # base_audio_drive = "/data/audio"
633
-
634
- # def transcribe_function(stream, new_chunk):
635
- # try:
636
- # sr, y = new_chunk[0], new_chunk[1]
637
- # except TypeError:
638
- # print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
639
- # return stream, "", None
640
-
641
- # y = y.astype(np.float32) / np.max(np.abs(y))
642
-
643
- # if stream is not None:
644
- # stream = np.concatenate([stream, y])
645
- # else:
646
- # stream = y
647
-
648
- # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
649
-
650
- # full_text = result.get("text", "")
651
-
652
- # return stream, full_text, result
653
-
654
- # def update_map_with_response(history):
655
- # if not history:
656
- # return ""
657
- # response = history[-1][1]
658
- # addresses = extract_addresses(response)
659
- # return generate_map(addresses)
660
-
661
- # def clear_textbox():
662
- # return ""
663
-
664
- # def show_map_if_details(history,choice):
665
- # if choice in ["Details", "Conversational"]:
666
- # return gr.update(visible=True), update_map_with_response(history)
667
- # else:
668
- # return gr.update(visible=False), ""
669
-
670
- # def generate_audio_elevenlabs(text):
671
- # XI_API_KEY = os.environ['ELEVENLABS_API']
672
- # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
673
- # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
674
- # headers = {
675
- # "Accept": "application/json",
676
- # "xi-api-key": XI_API_KEY
677
- # }
678
- # data = {
679
- # "text": str(text),
680
- # "model_id": "eleven_multilingual_v2",
681
- # "voice_settings": {
682
- # "stability": 1.0,
683
- # "similarity_boost": 0.0,
684
- # "style": 0.60,
685
- # "use_speaker_boost": False
686
- # }
687
- # }
688
- # response = requests.post(tts_url, headers=headers, json=data, stream=True)
689
- # if response.ok:
690
- # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
691
- # for chunk in response.iter_content(chunk_size=1024):
692
- # f.write(chunk)
693
- # temp_audio_path = f.name
694
- # logging.debug(f"Audio saved to {temp_audio_path}")
695
- # return temp_audio_path
696
- # else:
697
- # logging.error(f"Error generating audio: {response.text}")
698
- # return None
699
-
700
- # repo_id = "parler-tts/parler-tts-mini-expresso"
701
-
702
- # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
703
- # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
704
- # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
705
-
706
- # SAMPLE_RATE = parler_feature_extractor.sampling_rate
707
- # SEED = 42
708
-
709
- # def preprocess(text):
710
- # number_normalizer = EnglishNumberNormalizer()
711
- # text = number_normalizer(text).strip()
712
- # if text[-1] not in punctuation:
713
- # text = f"{text}."
714
-
715
- # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
716
-
717
- # def separate_abb(chunk):
718
- # chunk = chunk.replace(".", "")
719
- # return " ".join(chunk)
720
-
721
- # abbreviations = re.findall(abbreviations_pattern, text)
722
- # for abv in abbreviations:
723
- # if abv in text:
724
- # text = text.replace(abv, separate_abb(abv))
725
- # return text
726
-
727
- # def chunk_text(text, max_length=250):
728
- # words = text.split()
729
- # chunks = []
730
- # current_chunk = []
731
- # current_length = 0
732
-
733
- # for word in words:
734
- # if current_length + len(word) + 1 <= max_length:
735
- # current_chunk.append(word)
736
- # current_length += len(word) + 1
737
- # else:
738
- # chunks.append(' '.join(current_chunk))
739
- # current_chunk = [word]
740
- # current_length = len(word) + 1
741
-
742
- # if current_chunk:
743
- # chunks.append(' '.join(current_chunk))
744
-
745
- # return chunks
746
-
747
- # def generate_audio_parler_tts(text):
748
- # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
749
- # chunks = chunk_text(preprocess(text))
750
- # audio_segments = []
751
-
752
- # for chunk in chunks:
753
- # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
754
- # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
755
-
756
- # set_seed(SEED)
757
- # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
758
- # audio_arr = generation.cpu().numpy().squeeze()
759
-
760
- # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
761
- # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
762
- # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
763
-
764
- # combined_audio = sum(audio_segments)
765
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
766
- # combined_audio.export(combined_audio_path, format="wav")
767
-
768
- # logging.debug(f"Audio saved to {combined_audio_path}")
769
- # return combined_audio_path
770
-
771
- # # Load the MARS5 model
772
- # mars5, config_class = torch.hub.load('Camb-ai/mars5-tts', 'mars5_english', trust_repo=True)
773
-
774
- # def generate_audio_mars5(text):
775
- # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
776
- # kwargs_dict = {
777
- # 'temperature': 0.2,
778
- # 'top_k': -1,
779
- # 'top_p': 0.2,
780
- # 'typical_p': 1.0,
781
- # 'freq_penalty': 2.6,
782
- # 'presence_penalty': 0.4,
783
- # 'rep_penalty_window': 100,
784
- # 'max_prompt_phones': 360,
785
- # 'deep_clone': True,
786
- # 'nar_guidance_w': 3
787
- # }
788
-
789
- # chunks = chunk_text(preprocess(text))
790
- # audio_segments = []
791
-
792
- # for chunk in chunks:
793
- # wav = torch.zeros(1, mars5.sr) # Use a placeholder silent audio for the reference
794
- # cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
795
- # ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
796
-
797
-
798
- # temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
799
- # torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
800
- # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
801
-
802
- # combined_audio = sum(audio_segments)
803
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "mars5_combined_audio.wav")
804
- # combined_audio.export(combined_audio_path, format="wav")
805
-
806
- # logging.debug(f"Audio saved to {combined_audio_path}")
807
- # return combined_audio_path
808
-
809
- # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
810
- # pipe.to(device)
811
-
812
- # def generate_image(prompt):
813
- # with torch.cuda.amp.autocast():
814
- # image = pipe(
815
- # prompt,
816
- # num_inference_steps=28,
817
- # guidance_scale=3.0,
818
- # ).images[0]
819
- # return image
820
-
821
- # 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"
822
- # 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."
823
- # 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."
824
-
825
- # def update_images():
826
- # image_1 = generate_image(hardcoded_prompt_1)
827
- # image_2 = generate_image(hardcoded_prompt_2)
828
- # image_3 = generate_image(hardcoded_prompt_3)
829
- # return image_1, image_2, image_3
830
-
831
- # with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
832
- # with gr.Row():
833
- # with gr.Column():
834
- # state = gr.State()
835
-
836
- # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
837
- # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
838
-
839
- # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
840
-
841
- # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!")
842
- # chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input],api_name="voice_query")
843
- # tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta", "Gamma"], value="Alpha")
844
- # retriver_button = gr.Button("Retriver")
845
- # retriver_button.click(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input]).then(
846
- # fn=bot, inputs=[chatbot, choice, tts_choice], outputs=[chatbot],api_name="Ask_Retriever")
847
- # #gr.Audio(interactive=False, autoplay=True)]
848
-
849
- # # voice_response_button = gr.Button("Voice Response")
850
- # # voice_response_button.click(fn=generate_voice_response, inputs=[chatbot, tts_choice], outputs=[gr.Audio(interactive=False, autoplay=True)],api_name="generate_voice_response")
851
-
852
- # bot_msg = chat_msg.then(bot, [chatbot, choice, tts_choice], [chatbot, gr.Audio(interactive=False, autoplay=True)],api_name="generate_voice_response")
853
- # # bot_msg = chat_msg.then(bot, [chatbot, choice, tts_choice], [chatbot, gr.Audio(interactive=False, autoplay=True)])
854
- # bot_msg.then(lambda: gr.Textbox(value="", interactive=True, placeholder="Ask Radar!!!...", show_label=False), None, [chat_input])
855
- # chatbot.like(print_like_dislike, None, None)
856
- # clear_button = gr.Button("Clear")
857
- # clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
858
-
859
- # audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy')
860
- # audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
861
-
862
-
863
- # gr.Markdown("<h1 style='color: red;'>Map</h1>", elem_id="location-markdown")
864
- # location_output = gr.HTML()
865
- # bot_msg.then(show_map_if_details, [chatbot, choice], [location_output, location_output],api_name="map_finder")
866
-
867
-
868
- # # with gr.Column():
869
- # # weather_output = gr.HTML(value=fetch_local_weather())
870
- # # news_output = gr.HTML(value=fetch_local_news())
871
- # # news_output = gr.HTML(value=fetch_local_events())
872
-
873
- # with gr.Column():
874
- # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
875
- # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
876
- # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
877
-
878
- # refresh_button = gr.Button("Refresh Images")
879
- # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
880
-
881
- # demo.queue()
882
- # demo.launch(share=True)
883
-
884
-
885
  import gradio as gr
886
  import requests
887
  import os
@@ -915,8 +31,6 @@ import librosa
915
  from pathlib import Path
916
  import torchaudio
917
 
918
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
919
-
920
  # Check if the token is already set in the environment variables
921
  hf_token = os.getenv("HF_TOKEN")
922
  if hf_token is None:
@@ -949,7 +63,73 @@ def get_current_time_and_date():
949
 
950
  current_time_and_date = get_current_time_and_date()
951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
952
  def fetch_local_events():
 
 
953
  api_key = os.environ['SERP_API']
954
  url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
955
  response = requests.get(url)
@@ -1012,6 +192,9 @@ def fetch_local_events():
1012
  else:
1013
  return "<p>Failed to fetch local events</p>"
1014
 
 
 
 
1015
  def fetch_local_weather():
1016
  try:
1017
  api_key = os.environ['WEATHER_API']
@@ -1105,6 +288,14 @@ event type and description.And also add this Birmingham,AL at the end of each ad
1105
  Question: {question}
1106
  Helpful Answer:"""
1107
 
 
 
 
 
 
 
 
 
1108
  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,
1109
  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.
1110
  Keep the answer short ,sweet and crisp and in one shot. Always say "It was my pleasure!" at the end of the answer.
@@ -1144,6 +335,7 @@ def initialize_agent_with_prompt(prompt_template):
1144
  )
1145
  return agent
1146
 
 
1147
  def generate_answer(message, choice):
1148
  logging.debug(f"generate_answer called with prompt_choice: {choice}")
1149
 
@@ -1154,33 +346,28 @@ def generate_answer(message, choice):
1154
  else:
1155
  logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
1156
  agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
1157
-
1158
  response = agent(message)
 
1159
  addresses = extract_addresses(response['output'])
1160
  return response['output'], addresses
1161
 
1162
  def bot(history, choice, tts_choice):
1163
  if not history:
1164
  return history
 
 
1165
 
1166
- user_message = history[-1][0]
1167
- response_text, addresses = generate_answer(user_message, choice)
1168
-
1169
- # Ensure history has the correct format
1170
- if len(history[-1]) == 1:
1171
- history[-1].append(response_text)
1172
- else:
1173
- history[-1][1] = response_text
1174
-
1175
  with concurrent.futures.ThreadPoolExecutor() as executor:
1176
  if tts_choice == "Alpha":
1177
- audio_future = executor.submit(generate_audio_elevenlabs, response_text)
1178
  elif tts_choice == "Beta":
1179
- audio_future = executor.submit(generate_audio_parler_tts, response_text)
1180
  elif tts_choice == "Gamma":
1181
- audio_future = executor.submit(generate_audio_mars5, response_text)
 
 
1182
 
1183
- for character in response_text:
1184
  history[-1][1] += character
1185
  time.sleep(0.05)
1186
  yield history, None
@@ -1189,9 +376,99 @@ def bot(history, choice, tts_choice):
1189
  yield history, audio_path
1190
 
1191
  def add_message(history, message):
1192
- history = history or []
1193
- history.append([message, ""]) # Ensure it is a list with two elements: message and empty response
1194
  return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1195
 
1196
  def print_like_dislike(x: gr.LikeData):
1197
  print(x.index, x.value, x.liked)
@@ -1217,6 +494,27 @@ def extract_addresses(response):
1217
 
1218
  all_addresses = []
1219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1220
  def generate_map(location_names):
1221
  global all_addresses
1222
  all_addresses.extend(location_names)
@@ -1238,6 +536,115 @@ def generate_map(location_names):
1238
  map_html = m._repr_html_()
1239
  return map_html
1240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1241
  def update_map_with_response(history):
1242
  if not history:
1243
  return ""
@@ -1248,7 +655,7 @@ def update_map_with_response(history):
1248
  def clear_textbox():
1249
  return ""
1250
 
1251
- def show_map_if_details(history, choice):
1252
  if choice in ["Details", "Conversational"]:
1253
  return gr.update(visible=True), update_map_with_response(history)
1254
  else:
@@ -1468,3 +875,6 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1468
  demo.queue()
1469
  demo.launch(share=True)
1470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os
 
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:
 
63
 
64
  current_time_and_date = get_current_time_and_date()
65
 
66
+
67
+ # def fetch_local_events():
68
+ # api_key = os.environ['SERP_API']
69
+ # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
70
+ # response = requests.get(url)
71
+ # if response.status_code == 200:
72
+ # events_results = response.json().get("events_results", [])
73
+ # events_html = """
74
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
75
+ # <style>
76
+ # table {
77
+ # font-family: 'Verdana', sans-serif;
78
+ # color: #333;
79
+ # border-collapse: collapse;
80
+ # width: 100%;
81
+ # }
82
+ # th, td {
83
+ # border: 1px solid #ddd;
84
+ # padding: 8px;
85
+ # }
86
+ # th {
87
+ # background-color: #f2f2f2;
88
+ # color: #333;
89
+ # text-align: left;
90
+ # }
91
+ # tr:hover {
92
+ # background-color: #f5f5f5;
93
+ # }
94
+ # .event-link {
95
+ # color: #1E90FF;
96
+ # text-decoration: none;
97
+ # }
98
+ # .event-link:hover {
99
+ # text-decoration: underline;
100
+ # }
101
+ # </style>
102
+ # <table>
103
+ # <tr>
104
+ # <th>Title</th>
105
+ # <th>Date and Time</th>
106
+ # <th>Location</th>
107
+ # </tr>
108
+ # """
109
+ # for event in events_results:
110
+ # title = event.get("title", "No title")
111
+ # date_info = event.get("date", {})
112
+ # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
113
+ # location = event.get("address", "No location")
114
+ # if isinstance(location, list):
115
+ # location = " ".join(location)
116
+ # location = location.replace("[", "").replace("]", "")
117
+ # link = event.get("link", "#")
118
+ # events_html += f"""
119
+ # <tr>
120
+ # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
121
+ # <td>{date}</td>
122
+ # <td>{location}</td>
123
+ # </tr>
124
+ # """
125
+ # events_html += "</table>"
126
+ # return events_html
127
+ # else:
128
+ # return "<p>Failed to fetch local events</p>"
129
+
130
  def fetch_local_events():
131
+
132
+
133
  api_key = os.environ['SERP_API']
134
  url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
135
  response = requests.get(url)
 
192
  else:
193
  return "<p>Failed to fetch local events</p>"
194
 
195
+
196
+
197
+
198
  def fetch_local_weather():
199
  try:
200
  api_key = os.environ['WEATHER_API']
 
288
  Question: {question}
289
  Helpful Answer:"""
290
 
291
+
292
+ # 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 1st 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,
293
+ # 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.
294
+ # Keep the answer short and sweet and crisp. Always say "It was my pleasure!" at the end of the answer.
295
+ # {context}
296
+ # Question: {question}
297
+ # Helpful Answer:"""
298
+
299
  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,
300
  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.
301
  Keep the answer short ,sweet and crisp and in one shot. Always say "It was my pleasure!" at the end of the answer.
 
335
  )
336
  return agent
337
 
338
+
339
  def generate_answer(message, choice):
340
  logging.debug(f"generate_answer called with prompt_choice: {choice}")
341
 
 
346
  else:
347
  logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
348
  agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
 
349
  response = agent(message)
350
+
351
  addresses = extract_addresses(response['output'])
352
  return response['output'], addresses
353
 
354
  def bot(history, choice, tts_choice):
355
  if not history:
356
  return history
357
+ response, addresses = generate_answer(history[-1][0], choice)
358
+ history[-1][1] = ""
359
 
 
 
 
 
 
 
 
 
 
360
  with concurrent.futures.ThreadPoolExecutor() as executor:
361
  if tts_choice == "Alpha":
362
+ audio_future = executor.submit(generate_audio_elevenlabs, response)
363
  elif tts_choice == "Beta":
364
+ audio_future = executor.submit(generate_audio_parler_tts, response)
365
  elif tts_choice == "Gamma":
366
+ audio_future = executor.submit(generate_audio_mars5, response)
367
+ elif tts_choice == "Delta":
368
+ audio_future = executor.submit(generate_audio_fishaudio, response)
369
 
370
+ for character in response:
371
  history[-1][1] += character
372
  time.sleep(0.05)
373
  yield history, None
 
376
  yield history, audio_path
377
 
378
  def add_message(history, message):
379
+ history.append((message, None))
 
380
  return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
381
+ #----------------------------------part 1-------------------------
382
+ # def generate_answer(message, choice):
383
+ # logging.debug(f"generate_answer called with prompt_choice: {choice}")
384
+
385
+ # if choice == "Details":
386
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_1)
387
+ # elif choice == "Conversational":
388
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
389
+ # else:
390
+ # logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
391
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
392
+ # response = agent(message)
393
+
394
+ # addresses = extract_addresses(response['output'])
395
+ # return response['output'], addresses
396
+
397
+
398
+
399
+ # # def bot(history, choice, tts_choice):
400
+ # # if not history:
401
+ # # return history
402
+ # # response_pair, addresses = generate_answer(history[-1][0], choice)
403
+ # # history[-1] = response_pair # Update bot response correctly
404
+
405
+ # # with concurrent.futures.ThreadPoolExecutor() as executor:
406
+ # # if tts_choice == "Alpha":
407
+ # # audio_future = executor.submit(generate_audio_elevenlabs, response_pair[1])
408
+ # # elif tts_choice == "Beta":
409
+ # # audio_future = executor.submit(generate_audio_parler_tts, response_pair[1])
410
+ # # elif tts_choice == "Gamma":
411
+ # # audio_future = executor.submit(generate_audio_mars5, response_pair[1])
412
+
413
+ # # for character in response_pair[1]:
414
+ # # history[-1][1] += character
415
+ # # time.sleep(0.05)
416
+ # # yield history, None
417
+
418
+ # # audio_path = audio_future.result()
419
+ # # yield history, audio_path
420
+
421
+ # # def add_message(history, message):
422
+ # # history = history or []
423
+ # # history.append([message, ""]) # Ensure it is a list with two elements: message and empty response
424
+ # # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
425
+
426
+ # def bot(history, choice, tts_choice):
427
+ # if not history:
428
+ # return history
429
+ # response_pair, addresses = generate_answer(history[-1][0], choice)
430
+ # # Ensure history has the correct format
431
+ # if len(history[-1]) == 1:
432
+ # history[-1].append("")
433
+ # elif len(history[-1]) == 0:
434
+ # history[-1] = [history[-1][0], ""]
435
+
436
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
437
+ # if tts_choice == "Alpha":
438
+ # audio_future = executor.submit(generate_audio_elevenlabs, response_pair[1])
439
+ # elif tts_choice == "Beta":
440
+ # audio_future = executor.submit(generate_audio_parler_tts, response_pair[1])
441
+ # elif tts_choice == "Gamma":
442
+ # audio_future = executor.submit(generate_audio_mars5, response_pair[1])
443
+
444
+ # for character in response_pair[1]:
445
+ # history[-1][1] += character
446
+ # time.sleep(0.05)
447
+ # yield history, None
448
+
449
+ # audio_path = audio_future.result()
450
+ # yield history, audio_path
451
+
452
+ # def add_message(history, message):
453
+ # history = history or []
454
+ # history.append([message, ""]) # Ensure it is a list with two elements: message and empty response
455
+ # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
456
+ #--------------------------------------------------------
457
+ # def generate_voice_response(history, tts_choice):
458
+ # if not history:
459
+ # return None
460
+
461
+ # response = history[-1][1]
462
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
463
+ # if tts_choice == "Alpha":
464
+ # audio_future = executor.submit(generate_audio_elevenlabs, response)
465
+ # elif tts_choice == "Beta":
466
+ # audio_future = executor.submit(generate_audio_parler_tts, response)
467
+ # elif tts_choice == "Gamma":
468
+ # audio_future = executor.submit(generate_audio_mars5, response)
469
+
470
+ # audio_path = audio_future.result()
471
+ # return audio_path
472
 
473
  def print_like_dislike(x: gr.LikeData):
474
  print(x.index, x.value, x.liked)
 
494
 
495
  all_addresses = []
496
 
497
+ # def generate_map(location_names):
498
+ # global all_addresses
499
+ # all_addresses.extend(location_names)
500
+
501
+ # api_key = os.environ['GOOGLEMAPS_API_KEY']
502
+ # gmaps = GoogleMapsClient(key=api_key)
503
+
504
+ # m = folium.Map(location=[33.5175,-86.809444], zoom_start=16)
505
+
506
+ # for location_name in all_addresses:
507
+ # geocode_result = gmaps.geocode(location_name)
508
+ # if geocode_result:
509
+ # location = geocode_result[0]['geometry']['location']
510
+ # folium.Marker(
511
+ # [location['lat'], 'lng'],
512
+ # tooltip=f"{geocode_result[0]['formatted_address']}"
513
+ # ).add_to(m)
514
+
515
+ # map_html = m._repr_html_()
516
+ # return map_html
517
+
518
  def generate_map(location_names):
519
  global all_addresses
520
  all_addresses.extend(location_names)
 
536
  map_html = m._repr_html_()
537
  return map_html
538
 
539
+
540
+ def fetch_local_news():
541
+ api_key = os.environ['SERP_API']
542
+ url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
543
+ response = requests.get(url)
544
+ if response.status_code == 200:
545
+ results = response.json().get("news_results", [])
546
+ news_html = """
547
+ <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
548
+ <style>
549
+ .news-item {
550
+ font-family: 'Verdana', sans-serif;
551
+ color: #333;
552
+ background-color: #f0f8ff;
553
+ margin-bottom: 15px;
554
+ padding: 10px;
555
+ border-radius: 5px;
556
+ transition: box-shadow 0.3s ease, background-color 0.3s ease;
557
+ font-weight: bold;
558
+ }
559
+ .news-item:hover {
560
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
561
+ background-color: #e6f7ff;
562
+ }
563
+ .news-item a {
564
+ color: #1E90FF;
565
+ text-decoration: none;
566
+ font-weight: bold;
567
+ }
568
+ .news-item a:hover {
569
+ text-decoration: underline;
570
+ }
571
+ .news-preview {
572
+ position: absolute;
573
+ display: none;
574
+ border: 1px solid #ccc;
575
+ border-radius: 5px;
576
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
577
+ background-color: white;
578
+ z-index: 1000;
579
+ max-width: 300px;
580
+ padding: 10px;
581
+ font-family: 'Verdana', sans-serif;
582
+ color: #333;
583
+ }
584
+ </style>
585
+ <script>
586
+ function showPreview(event, previewContent) {
587
+ var previewBox = document.getElementById('news-preview');
588
+ previewBox.innerHTML = previewContent;
589
+ previewBox.style.left = event.pageX + 'px';
590
+ previewBox.style.top = event.pageY + 'px';
591
+ previewBox.style.display = 'block';
592
+ }
593
+ function hidePreview() {
594
+ var previewBox = document.getElementById('news-preview');
595
+ previewBox.style.display = 'none';
596
+ }
597
+ </script>
598
+ <div id="news-preview" class="news-preview"></div>
599
+ """
600
+ for index, result in enumerate(results[:7]):
601
+ title = result.get("title", "No title")
602
+ link = result.get("link", "#")
603
+ snippet = result.get("snippet", "")
604
+ news_html += f"""
605
+ <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
606
+ <a href='{link}' target='_blank'>{index + 1}. {title}</a>
607
+ <p>{snippet}</p>
608
+ </div>
609
+ """
610
+ return news_html
611
+ else:
612
+ return "<p>Failed to fetch local news</p>"
613
+
614
+ import numpy as np
615
+ import torch
616
+ from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
617
+
618
+ model_id = 'openai/whisper-large-v3'
619
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
620
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
621
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
622
+ processor = AutoProcessor.from_pretrained(model_id)
623
+
624
+ 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)
625
+
626
+ base_audio_drive = "/data/audio"
627
+
628
+ def transcribe_function(stream, new_chunk):
629
+ try:
630
+ sr, y = new_chunk[0], new_chunk[1]
631
+ except TypeError:
632
+ print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
633
+ return stream, "", None
634
+
635
+ y = y.astype(np.float32) / np.max(np.abs(y))
636
+
637
+ if stream is not None:
638
+ stream = np.concatenate([stream, y])
639
+ else:
640
+ stream = y
641
+
642
+ result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
643
+
644
+ full_text = result.get("text", "")
645
+
646
+ return stream, full_text, result
647
+
648
  def update_map_with_response(history):
649
  if not history:
650
  return ""
 
655
  def clear_textbox():
656
  return ""
657
 
658
+ def show_map_if_details(history,choice):
659
  if choice in ["Details", "Conversational"]:
660
  return gr.update(visible=True), update_map_with_response(history)
661
  else:
 
875
  demo.queue()
876
  demo.launch(share=True)
877
 
878
+
879
+
880
+