Pijush2023 commited on
Commit
f383160
·
verified ·
1 Parent(s): 3fa8d86

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +851 -3
app.py CHANGED
@@ -1,3 +1,852 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os
@@ -466,7 +1315,7 @@ def show_map_if_details(history, choice):
466
  if choice in ["Details", "Conversational"]:
467
  return gr.update(visible=True), update_map_with_response(history)
468
  else:
469
- return gr.update(visible=False), ""
470
 
471
  def generate_audio_elevenlabs(text):
472
  XI_API_KEY = os.environ['ELEVENLABS_API']
@@ -642,7 +1491,7 @@ def fetch_local_events():
642
  api_key = os.environ['SERP_API']
643
  url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
644
  response = requests.get(url)
645
- if response.status_code == 200:
646
  events_results = response.json().get("events_results", [])
647
  events_html = """
648
  <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
@@ -852,4 +1701,3 @@ demo.launch(share=True)
852
 
853
 
854
 
855
-
 
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 huggingface_hub import login
23
+ # from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
24
+ # from parler_tts import ParlerTTSForConditionalGeneration
25
+ # from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
26
+ # from scipy.io.wavfile import write as write_wav
27
+ # from pydub import AudioSegment
28
+ # from string import punctuation
29
+ # import librosa
30
+ # from pathlib import Path
31
+ # import torchaudio
32
+ # import numpy as np
33
+
34
+ # # Neo4j imports
35
+ # from langchain.chains import GraphCypherQAChain
36
+ # from langchain_community.graphs import Neo4jGraph
37
+ # from langchain_community.document_loaders import HuggingFaceDatasetLoader
38
+ # from langchain_text_splitters import CharacterTextSplitter
39
+ # from langchain_experimental.graph_transformers import LLMGraphTransformer
40
+ # from langchain_core.prompts import ChatPromptTemplate
41
+ # from langchain_core.pydantic_v1 import BaseModel, Field
42
+ # from langchain_core.messages import AIMessage, HumanMessage
43
+ # from langchain_core.output_parsers import StrOutputParser
44
+ # from langchain_core.runnables import RunnableBranch, RunnableLambda, RunnableParallel, RunnablePassthrough
45
+
46
+
47
+ # # Set environment variables for CUDA
48
+ # os.environ['PYTORCH_USE_CUDA_DSA'] = '1'
49
+ # os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
50
+
51
+
52
+ # hf_token = os.getenv("HF_TOKEN")
53
+ # if hf_token is None:
54
+ # print("Please set your Hugging Face token in the environment variables.")
55
+ # else:
56
+ # login(token=hf_token)
57
+
58
+ # logging.basicConfig(level=logging.DEBUG)
59
+
60
+
61
+ # embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
62
+
63
+
64
+ # # Pinecone setup
65
+ # from pinecone import Pinecone
66
+ # pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
67
+
68
+ # index_name = "radardata07242024"
69
+ # vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
70
+ # retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
71
+
72
+ # chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
73
+
74
+ # conversational_memory = ConversationBufferWindowMemory(
75
+ # memory_key='chat_history',
76
+ # k=10,
77
+ # return_messages=True
78
+ # )
79
+
80
+ # # Prompt templates
81
+ # def get_current_date():
82
+ # return datetime.now().strftime("%B %d, %Y")
83
+
84
+ # current_date = get_current_date()
85
+
86
+ # template1 = f"""As an expert concierge in Birmingham, Alabama, known for being a helpful and renowned guide, I am here to assist you on this sunny bright day of {current_date}. Given the current weather conditions and date, I have access to a plethora of information regarding events, places, and activities in Birmingham that can enhance your experience.
87
+ # If you have any questions or need recommendations, feel free to ask. I have a wealth of knowledge of perennial events in Birmingham and can provide detailed information to ensure you make the most of your time here. Remember, I am here to assist you in any way possible.
88
+ # Now, let me guide you through some of the exciting events happening today in Birmingham, Alabama:
89
+ # Address: >>, Birmingham, AL
90
+ # Time: >>__
91
+ # Date: >>__
92
+ # Description: >>__
93
+ # Address: >>, Birmingham, AL
94
+ # Time: >>__
95
+ # Date: >>__
96
+ # Description: >>__
97
+ # Address: >>, Birmingham, AL
98
+ # Time: >>__
99
+ # Date: >>__
100
+ # Description: >>__
101
+ # Address: >>, Birmingham, AL
102
+ # Time: >>__
103
+ # Date: >>__
104
+ # Description: >>__
105
+ # Address: >>, Birmingham, AL
106
+ # Time: >>__
107
+ # Date: >>__
108
+ # Description: >>__
109
+ # If you have any specific preferences or questions about these events or any other inquiries, please feel free to ask. Remember, I am here to ensure you have a memorable and enjoyable experience in Birmingham, AL.
110
+ # It was my pleasure!
111
+ # {{context}}
112
+ # Question: {{question}}
113
+ # Helpful Answer:"""
114
+
115
+ # template2 = f"""As an expert concierge known for being helpful and a renowned guide for Birmingham, Alabama, I assist visitors in discovering the best that the city has to offer. Given today's sunny and bright weather on {current_date}, I am well-equipped to provide valuable insights and recommendations without revealing specific locations. I draw upon my extensive knowledge of the area, including perennial events and historical context.
116
+ # In light of this, how can I assist you today? Feel free to ask any questions or seek recommendations for your day in Birmingham. If there's anything specific you'd like to know or experience, please share, and I'll be glad to help. Remember, keep the question concise for a quick and accurate response.
117
+ # "It was my pleasure!"
118
+ # {{context}}
119
+ # Question: {{question}}
120
+ # Helpful Answer:"""
121
+
122
+ # QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
123
+ # QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
124
+
125
+ # # Neo4j setup
126
+ # graph = Neo4jGraph(
127
+ # url="neo4j+s://98f45cc0.databases.neo4j.io",
128
+ # username="neo4j",
129
+ # password="B_sZbapCTZoQDWj1JrhwqElsNa-jm5Zq1m_mAnyPYog"
130
+ # )
131
+
132
+ # # Avoid pushing the graph documents to Neo4j every time
133
+ # # Only push the documents once and comment the code below after the initial push
134
+ # # dataset_name = "Pijush2023/birmindata07312024"
135
+ # # page_content_column = 'events_description'
136
+ # # loader = HuggingFaceDatasetLoader(dataset_name, page_content_column)
137
+ # # data = loader.load()
138
+
139
+ # # text_splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=50)
140
+ # # documents = text_splitter.split_documents(data)
141
+
142
+ # # llm_transformer = LLMGraphTransformer(llm=chat_model)
143
+ # # graph_documents = llm_transformer.convert_to_graph_documents(documents)
144
+ # # graph.add_graph_documents(graph_documents, baseEntityLabel=True, include_source=True)
145
+
146
+ # class Entities(BaseModel):
147
+ # names: list[str] = Field(..., description="All the person, organization, or business entities that appear in the text")
148
+
149
+ # entity_prompt = ChatPromptTemplate.from_messages([
150
+ # ("system", "You are extracting organization and person entities from the text."),
151
+ # ("human", "Use the given format to extract information from the following input: {question}"),
152
+ # ])
153
+
154
+ # entity_chain = entity_prompt | chat_model.with_structured_output(Entities)
155
+
156
+ # def remove_lucene_chars(input: str) -> str:
157
+ # return input.translate(str.maketrans({"\\": r"\\", "+": r"\+", "-": r"\-", "&": r"\&", "|": r"\|", "!": r"\!",
158
+ # "(": r"\(", ")": r"\)", "{": r"\{", "}": r"\}", "[": r"\[", "]": r"\]",
159
+ # "^": r"\^", "~": r"\~", "*": r"\*", "?": r"\?", ":": r"\:", '"': r'\"',
160
+ # ";": r"\;", " ": r"\ "}))
161
+
162
+ # def generate_full_text_query(input: str) -> str:
163
+ # full_text_query = ""
164
+ # words = [el for el in remove_lucene_chars(input).split() if el]
165
+ # for word in words[:-1]:
166
+ # full_text_query += f" {word}~2 AND"
167
+ # full_text_query += f" {words[-1]}~2"
168
+ # return full_text_query.strip()
169
+
170
+ # def structured_retriever(question: str) -> str:
171
+ # result = ""
172
+ # entities = entity_chain.invoke({"question": question})
173
+ # for entity in entities.names:
174
+ # response = graph.query(
175
+ # """CALL db.index.fulltext.queryNodes('entity', $query, {limit:2})
176
+ # YIELD node,score
177
+ # CALL {
178
+ # WITH node
179
+ # MATCH (node)-[r:!MENTIONS]->(neighbor)
180
+ # RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS output
181
+ # UNION ALL
182
+ # WITH node
183
+ # MATCH (node)<-[r:!MENTIONS]-(neighbor)
184
+ # RETURN neighbor.id + ' - ' + type(r) + ' -> ' + node.id AS output
185
+ # }
186
+ # RETURN output LIMIT 50
187
+ # """,
188
+ # {"query": generate_full_text_query(entity)},
189
+ # )
190
+ # result += "\n".join([el['output'] for el in response])
191
+ # return result
192
+
193
+ # def retriever_neo4j(question: str):
194
+ # structured_data = structured_retriever(question)
195
+ # logging.debug(f"Structured data: {structured_data}")
196
+ # return structured_data
197
+
198
+ # _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
199
+ # in its original language.
200
+ # Chat History:
201
+ # {chat_history}
202
+ # Follow Up Input: {question}
203
+ # Standalone question:"""
204
+
205
+ # CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
206
+
207
+ # def _format_chat_history(chat_history: list[tuple[str, str]]) -> list:
208
+ # buffer = []
209
+ # for human, ai in chat_history:
210
+ # buffer.append(HumanMessage(content=human))
211
+ # buffer.append(AIMessage(content=ai))
212
+ # return buffer
213
+
214
+ # _search_query = RunnableBranch(
215
+ # (
216
+ # RunnableLambda(lambda x: bool(x.get("chat_history"))).with_config(
217
+ # run_name="HasChatHistoryCheck"
218
+ # ),
219
+ # RunnablePassthrough.assign(
220
+ # chat_history=lambda x: _format_chat_history(x["chat_history"])
221
+ # )
222
+ # | CONDENSE_QUESTION_PROMPT
223
+ # | ChatOpenAI(temperature=0, api_key=os.environ['OPENAI_API_KEY'])
224
+ # | StrOutputParser(),
225
+ # ),
226
+ # RunnableLambda(lambda x : x["question"]),
227
+ # )
228
+
229
+ # template = """Answer the question based only on the following context:
230
+ # {context}
231
+ # Question: {question}
232
+ # Use natural language and be concise.
233
+ # Answer:"""
234
+
235
+ # qa_prompt = ChatPromptTemplate.from_template(template)
236
+
237
+ # chain_neo4j = (
238
+ # RunnableParallel(
239
+ # {
240
+ # "context": _search_query | retriever_neo4j,
241
+ # "question": RunnablePassthrough(),
242
+ # }
243
+ # )
244
+ # | qa_prompt
245
+ # | chat_model
246
+ # | StrOutputParser()
247
+ # )
248
+
249
+ # # Define a function to select between Pinecone and Neo4j
250
+ # def generate_answer(message, choice, retrieval_mode):
251
+ # logging.debug(f"generate_answer called with choice: {choice} and retrieval_mode: {retrieval_mode}")
252
+
253
+ # prompt_template = QA_CHAIN_PROMPT_1 if choice == "Details" else QA_CHAIN_PROMPT_2
254
+
255
+ # if retrieval_mode == "Vector":
256
+ # qa_chain = RetrievalQA.from_chain_type(
257
+ # llm=chat_model,
258
+ # chain_type="stuff",
259
+ # retriever=retriever,
260
+ # chain_type_kwargs={"prompt": prompt_template}
261
+ # )
262
+ # response = qa_chain({"query": message})
263
+ # logging.debug(f"Vector response: {response}")
264
+ # return response['result'], extract_addresses(response['result'])
265
+ # elif retrieval_mode == "Knowledge-Graph":
266
+ # response = chain_neo4j.invoke({"question": message})
267
+ # logging.debug(f"Knowledge-Graph response: {response}")
268
+ # return response, extract_addresses(response)
269
+ # else:
270
+ # return "Invalid retrieval mode selected.", []
271
+
272
+ # def bot(history, choice, tts_choice, retrieval_mode):
273
+ # if not history:
274
+ # return history
275
+
276
+ # response, addresses = generate_answer(history[-1][0], choice, retrieval_mode)
277
+ # history[-1][1] = ""
278
+
279
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
280
+ # if tts_choice == "Alpha":
281
+ # audio_future = executor.submit(generate_audio_elevenlabs, response)
282
+ # elif tts_choice == "Beta":
283
+ # audio_future = executor.submit(generate_audio_parler_tts, response)
284
+ # elif tts_choice == "Gamma":
285
+ # audio_future = executor.submit(generate_audio_mars5, response)
286
+
287
+ # for character in response:
288
+ # history[-1][1] += character
289
+ # time.sleep(0.05)
290
+ # yield history, None
291
+
292
+ # audio_path = audio_future.result()
293
+ # yield history, audio_path
294
+
295
+ # history.append([response, None]) # Ensure the response is added in the correct format
296
+
297
+ # def add_message(history, message):
298
+ # history.append((message, None))
299
+ # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
300
+
301
+ # def print_like_dislike(x: gr.LikeData):
302
+ # print(x.index, x.value, x.liked)
303
+
304
+ # def extract_addresses(response):
305
+ # if not isinstance(response, str):
306
+ # response = str(response)
307
+ # address_patterns = [
308
+ # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
309
+ # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
310
+ # r'([A-Z].*,\sAL\s\d{5})',
311
+ # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
312
+ # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
313
+ # r'(\d{2}.*\sStreets)',
314
+ # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
315
+ # r'([a-zA-Z]\s Birmingham)',
316
+ # r'([a-zA-Z].*,\sBirmingham,\sAL)',
317
+ # r'(^Birmingham,AL$)'
318
+ # ]
319
+ # addresses = []
320
+ # for pattern in address_patterns:
321
+ # addresses.extend(re.findall(pattern, response))
322
+ # return addresses
323
+
324
+ # all_addresses = []
325
+
326
+ # def generate_map(location_names):
327
+ # global all_addresses
328
+ # all_addresses.extend(location_names)
329
+
330
+ # api_key = os.environ['GOOGLEMAPS_API_KEY']
331
+ # gmaps = GoogleMapsClient(key=api_key)
332
+
333
+ # m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
334
+
335
+ # for location_name in all_addresses:
336
+ # geocode_result = gmaps.geocode(location_name)
337
+ # if geocode_result:
338
+ # location = geocode_result[0]['geometry']['location']
339
+ # folium.Marker(
340
+ # [location['lat'], location['lng']],
341
+ # tooltip=f"{geocode_result[0]['formatted_address']}"
342
+ # ).add_to(m)
343
+
344
+ # map_html = m._repr_html_()
345
+ # return map_html
346
+
347
+ # def fetch_local_news():
348
+ # api_key = os.environ['SERP_API']
349
+ # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
350
+ # response = requests.get(url)
351
+ # if response.status_code == 200:
352
+ # results = response.json().get("news_results", [])
353
+ # news_html = """
354
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
355
+ # <style>
356
+ # .news-item {
357
+ # font-family: 'Verdana', sans-serif;
358
+ # color: #333;
359
+ # background-color: #f0f8ff;
360
+ # margin-bottom: 15px;
361
+ # padding: 10px;
362
+ # border-radius: 5px;
363
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
364
+ # font-weight: bold;
365
+ # }
366
+ # .news-item:hover {
367
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
368
+ # background-color: #e6f7ff;
369
+ # }
370
+ # .news-item a {
371
+ # color: #1E90FF;
372
+ # text-decoration: none;
373
+ # font-weight: bold;
374
+ # }
375
+ # .news-item a:hover {
376
+ # text-decoration: underline;
377
+ # }
378
+ # .news-preview {
379
+ # position: absolute;
380
+ # display: none;
381
+ # border: 1px solid #ccc;
382
+ # border-radius: 5px;
383
+ # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
384
+ # background-color: white;
385
+ # z-index: 1000;
386
+ # max-width: 300px;
387
+ # padding: 10px;
388
+ # font-family: 'Verdana', sans-serif;
389
+ # color: #333;
390
+ # }
391
+ # </style>
392
+ # <script>
393
+ # function showPreview(event, previewContent) {
394
+ # var previewBox = document.getElementById('news-preview');
395
+ # previewBox.innerHTML = previewContent;
396
+ # previewBox.style.left = event.pageX + 'px';
397
+ # previewBox.style.top = event.pageY + 'px';
398
+ # previewBox.style.display = 'block';
399
+ # }
400
+ # function hidePreview() {
401
+ # var previewBox = document.getElementById('news-preview');
402
+ # previewBox.style.display = 'none';
403
+ # }
404
+ # </script>
405
+ # <div id="news-preview" class="news-preview"></div>
406
+ # """
407
+ # for index, result in enumerate(results[:7]):
408
+ # title = result.get("title", "No title")
409
+ # link = result.get("link", "#")
410
+ # snippet = result.get("snippet", "")
411
+ # news_html += f"""
412
+ # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
413
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
414
+ # <p>{snippet}</p>
415
+ # </div>
416
+ # """
417
+ # return news_html
418
+ # else:
419
+ # return "<p>Failed to fetch local news</p>"
420
+
421
+ # import numpy as np
422
+ # import torch
423
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
424
+
425
+ # model_id = 'openai/whisper-large-v3'
426
+ # device = "cuda:0" if torch.cuda.is_available() else "cpu"
427
+ # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
428
+ # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
429
+ # processor = AutoProcessor.from_pretrained(model_id)
430
+
431
+ # 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)
432
+
433
+ # base_audio_drive = "/data/audio"
434
+
435
+ # def transcribe_function(stream, new_chunk):
436
+ # try:
437
+ # sr, y = new_chunk[0], new_chunk[1]
438
+ # except TypeError:
439
+ # print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
440
+ # return stream, "", None
441
+
442
+ # y = y.astype(np.float32) / np.max(np.abs(y))
443
+
444
+ # if stream is not None:
445
+ # stream = np.concatenate([stream, y])
446
+ # else:
447
+ # stream = y
448
+
449
+ # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
450
+
451
+ # full_text = result.get("text","")
452
+
453
+ # return stream, full_text, result
454
+
455
+ # def update_map_with_response(history):
456
+ # if not history:
457
+ # return ""
458
+ # response = history[-1][1]
459
+ # addresses = extract_addresses(response)
460
+ # return generate_map(addresses)
461
+
462
+ # def clear_textbox():
463
+ # return ""
464
+
465
+ # def show_map_if_details(history, choice):
466
+ # if choice in ["Details", "Conversational"]:
467
+ # return gr.update(visible=True), update_map_with_response(history)
468
+ # else:
469
+ # return gr.update(visible=False), ""
470
+
471
+ # def generate_audio_elevenlabs(text):
472
+ # XI_API_KEY = os.environ['ELEVENLABS_API']
473
+ # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
474
+ # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
475
+ # headers = {
476
+ # "Accept": "application/json",
477
+ # "xi-api-key": XI_API_KEY
478
+ # }
479
+ # data = {
480
+ # "text": str(text),
481
+ # "model_id": "eleven_multilingual_v2",
482
+ # "voice_settings": {
483
+ # "stability": 1.0,
484
+ # "similarity_boost": 0.0,
485
+ # "style": 0.60,
486
+ # "use_speaker_boost": False
487
+ # }
488
+ # }
489
+ # response = requests.post(tts_url, headers=headers, json=data, stream=True)
490
+ # if response.ok:
491
+ # audio_segments = []
492
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
493
+ # for chunk in response.iter_content(chunk_size=1024):
494
+ # if chunk:
495
+ # f.write(chunk)
496
+ # audio_segments.append(chunk)
497
+ # temp_audio_path = f.name
498
+
499
+ # # Combine all audio chunks into a single file
500
+ # combined_audio = AudioSegment.from_file(temp_audio_path, format="mp3")
501
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "elevenlabs_combined_audio.mp3")
502
+ # combined_audio.export(combined_audio_path, format="mp3")
503
+
504
+ # logging.debug(f"Audio saved to {combined_audio_path}")
505
+ # return combined_audio_path
506
+ # else:
507
+ # logging.error(f"Error generating audio: {response.text}")
508
+ # return None
509
+
510
+
511
+ # repo_id = "parler-tts/parler-tts-mini-expresso"
512
+
513
+ # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
514
+ # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
515
+ # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
516
+
517
+ # SAMPLE_RATE = parler_feature_extractor.sampling_rate
518
+ # SEED = 42
519
+
520
+ # def preprocess(text):
521
+ # number_normalizer = EnglishNumberNormalizer()
522
+ # text = number_normalizer(text).strip()
523
+ # if text[-1] not in punctuation:
524
+ # text = f"{text}."
525
+
526
+ # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
527
+
528
+ # def separate_abb(chunk):
529
+ # chunk = chunk.replace(".", "")
530
+ # return " ".join(chunk)
531
+
532
+ # abbreviations = re.findall(abbreviations_pattern, text)
533
+ # for abv in abbreviations:
534
+ # if abv in text:
535
+ # text is text.replace(abv, separate_abb(abv))
536
+ # return text
537
+
538
+ # def chunk_text(text, max_length=250):
539
+ # words = text.split()
540
+ # chunks = []
541
+ # current_chunk = []
542
+ # current_length = 0
543
+
544
+ # for word in words:
545
+ # if current_length + len(word) + 1 <= max_length:
546
+ # current_chunk.append(word)
547
+ # current_length += len(word) + 1
548
+ # else:
549
+ # chunks.append(' '.join(current_chunk))
550
+ # current_chunk = [word]
551
+ # current_length = len(word) + 1
552
+
553
+ # if current_chunk:
554
+ # chunks.append(' '.join(current_chunk))
555
+
556
+ # return chunks
557
+
558
+ # def generate_audio_parler_tts(text):
559
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
560
+ # chunks = chunk_text(preprocess(text))
561
+ # audio_segments = []
562
+
563
+ # for chunk in chunks:
564
+ # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
565
+ # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
566
+
567
+ # set_seed(SEED)
568
+ # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
569
+ # audio_arr = generation.cpu().numpy().squeeze()
570
+
571
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
572
+ # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
573
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
574
+
575
+ # combined_audio = sum(audio_segments)
576
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
577
+ # combined_audio.export(combined_audio_path, format="wav")
578
+
579
+ # logging.debug(f"Audio saved to {combined_audio_path}")
580
+ # return combined_audio_path
581
+
582
+ # # Load the MARS5 model
583
+ # mars5, config_class = torch.hub.load('Camb-ai/mars5-tts', 'mars5_english', trust_repo=True)
584
+
585
+ # def generate_audio_mars5(text):
586
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
587
+ # kwargs_dict = {
588
+ # 'temperature': 0.2,
589
+ # 'top_k': -1,
590
+ # 'top_p': 0.2,
591
+ # 'typical_p': 1.0,
592
+ # 'freq_penalty': 2.6,
593
+ # 'presence_penalty': 0.4,
594
+ # 'rep_penalty_window': 100,
595
+ # 'max_prompt_phones': 360,
596
+ # 'deep_clone': True,
597
+ # 'nar_guidance_w': 3
598
+ # }
599
+
600
+ # chunks = chunk_text(preprocess(text))
601
+ # audio_segments = []
602
+
603
+ # for chunk in chunks:
604
+ # wav = torch.zeros(1, mars5.sr) # Use a placeholder silent audio for the reference
605
+ # cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
606
+ # ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
607
+
608
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
609
+ # torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
610
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
611
+
612
+ # combined_audio = sum(audio_segments)
613
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "mars5_combined_audio.wav")
614
+ # combined_audio.export(combined_audio_path, format="wav")
615
+
616
+ # logging.debug(f"Audio saved to {combined_audio_path}")
617
+ # return combined_audio_path
618
+
619
+ # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
620
+ # pipe.to(device)
621
+
622
+ # def generate_image(prompt):
623
+ # with torch.cuda.amp.autocast():
624
+ # image = pipe(
625
+ # prompt,
626
+ # num_inference_steps=28,
627
+ # guidance_scale=3.0,
628
+ # ).images[0]
629
+ # return image
630
+
631
+ # 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"
632
+ # 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."
633
+ # 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."
634
+
635
+ # def update_images():
636
+ # image_1 = generate_image(hardcoded_prompt_1)
637
+ # image_2 = generate_image(hardcoded_prompt_2)
638
+ # image_3 = generate_image(hardcoded_prompt_3)
639
+ # return image_1, image_2, image_3
640
+
641
+ # def fetch_local_events():
642
+ # api_key = os.environ['SERP_API']
643
+ # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
644
+ # response = requests.get(url)
645
+ # if response.status_code == 200:
646
+ # events_results = response.json().get("events_results", [])
647
+ # events_html = """
648
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
649
+ # <style>
650
+ # table {
651
+ # font-family: 'Verdana', sans-serif;
652
+ # color: #333;
653
+ # border-collapse: collapse;
654
+ # width: 100%;
655
+ # }
656
+ # th, td {
657
+ # border: 1px solid #fff !important;
658
+ # padding: 8px;
659
+ # }
660
+ # th {
661
+ # background-color: #f2f2f2;
662
+ # color: #333;
663
+ # text-align: left;
664
+ # }
665
+ # tr:hover {
666
+ # background-color: #f5f5f5;
667
+ # }
668
+ # .event-link {
669
+ # color: #1E90FF;
670
+ # text-decoration: none;
671
+ # }
672
+ # .event-link:hover {
673
+ # text-decoration: underline;
674
+ # }
675
+ # </style>
676
+ # <table>
677
+ # <tr>
678
+ # <th>Title</th>
679
+ # <th>Date and Time</th>
680
+ # <th>Location</th>
681
+ # </tr>
682
+ # """
683
+ # for event in events_results:
684
+ # title = event.get("title", "No title")
685
+ # date_info = event.get("date", {})
686
+ # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
687
+ # location = event.get("address", "No location")
688
+ # if isinstance(location, list):
689
+ # location = " ".join(location)
690
+ # location = location.replace("[", "").replace("]", "")
691
+ # link = event.get("link", "#")
692
+ # events_html += f"""
693
+ # <tr>
694
+ # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
695
+ # <td>{date}</td>
696
+ # <td>{location}</td>
697
+ # </tr>
698
+ # """
699
+ # events_html += "</table>"
700
+ # return events_html
701
+ # else:
702
+ # return "<p>Failed to fetch local events</p>"
703
+
704
+ # def get_weather_icon(condition):
705
+ # condition_map = {
706
+ # "Clear": "c01d",
707
+ # "Partly Cloudy": "c02d",
708
+ # "Cloudy": "c03d",
709
+ # "Overcast": "c04d",
710
+ # "Mist": "a01d",
711
+ # "Patchy rain possible": "r01d",
712
+ # "Light rain": "r02d",
713
+ # "Moderate rain": "r03d",
714
+ # "Heavy rain": "r04d",
715
+ # "Snow": "s01d",
716
+ # "Thunderstorm": "t01d",
717
+ # "Fog": "a05d",
718
+ # }
719
+ # return condition_map.get(condition, "c04d")
720
+
721
+ # def fetch_local_weather():
722
+ # try:
723
+ # api_key = os.environ['WEATHER_API']
724
+ # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
725
+ # response = requests.get(url)
726
+ # response.raise_for_status()
727
+ # jsonData = response.json()
728
+
729
+ # current_conditions = jsonData.get("currentConditions", {})
730
+ # temp_celsius = current_conditions.get("temp", "N/A")
731
+
732
+ # if temp_celsius != "N/A":
733
+ # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
734
+ # else:
735
+ # temp_fahrenheit = "N/A"
736
+
737
+ # condition = current_conditions.get("conditions", "N/A")
738
+ # humidity = current_conditions.get("humidity", "N/A")
739
+
740
+ # weather_html = f"""
741
+ # <div class="weather-theme">
742
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
743
+ # <div class="weather-content">
744
+ # <div class="weather-icon">
745
+ # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
746
+ # </div>
747
+ # <div class="weather-details">
748
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
749
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
750
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
751
+ # </div>
752
+ # </div>
753
+ # </div>
754
+ # <style>
755
+ # .weather-theme {{
756
+ # animation: backgroundAnimation 10s infinite alternate;
757
+ # border-radius: 10px;
758
+ # padding: 10px;
759
+ # margin-bottom: 15px;
760
+ # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
761
+ # background-size: 400% 400%;
762
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
763
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
764
+ # }}
765
+ # .weather-theme:hover {{
766
+ # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
767
+ # background-position: 100% 100%;
768
+ # }}
769
+ # @keyframes backgroundAnimation {{
770
+ # 0% {{ background-position: 0% 50%; }}
771
+ # 100% {{ background-position: 100% 50%; }}
772
+ # }}
773
+ # .weather-content {{
774
+ # display: flex;
775
+ # align-items: center;
776
+ # }}
777
+ # .weather-icon {{
778
+ # flex: 1;
779
+ # }}
780
+ # .weather-details {{
781
+ # flex 3;
782
+ # }}
783
+ # </style>
784
+ # """
785
+ # return weather_html
786
+ # except requests.exceptions.RequestException as e:
787
+ # return f"<p>Failed to fetch local weather: {e}</p>"
788
+
789
+ # with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
790
+ # with gr.Row():
791
+ # with gr.Column():
792
+ # state = gr.State()
793
+
794
+ # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
795
+ # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
796
+ # retrieval_mode = gr.Radio(label="Retrieval Mode", choices=["Vector", "Knowledge-Graph"], value="Vector")
797
+
798
+ # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
799
+
800
+ # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!", placeholder="After Prompt,click Retriever Only")
801
+ # tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta", "Gamma"], value="Alpha")
802
+ # retriever_button = gr.Button("Retriever")
803
+
804
+ # clear_button = gr.Button("Clear")
805
+ # clear_button.click(lambda:[None,None] ,outputs=[chat_input, state])
806
+
807
+ # gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
808
+ # location_output = gr.HTML()
809
+
810
+ # # Define a single audio component
811
+ # audio_output = gr.Audio(interactive=False, autoplay=True)
812
+
813
+ # def stop_audio():
814
+ # audio_output.stop()
815
+ # return None
816
+
817
+ # # Define the sequence of actions for the "Retriever" button
818
+ # retriever_sequence = (
819
+ # retriever_button.click(fn=stop_audio, inputs=[], outputs=[audio_output],api_name="Ask_Retriever")
820
+ # .then(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input],api_name="voice_query")
821
+ # .then(fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode], outputs=[chatbot, audio_output],api_name="generate_voice_response" )
822
+ # .then(fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder")
823
+ # .then(fn=clear_textbox, inputs=[], outputs=[chat_input])
824
+ # )
825
+
826
+ # # Link the "Enter" key (submit event) to the same sequence of actions
827
+ # chat_input.submit(fn=stop_audio, inputs=[], outputs=[audio_output])
828
+ # chat_input.submit(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input],api_name="voice_query").then(
829
+ # fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode], outputs=[chatbot, audio_output], api_name="generate_voice_response"
830
+ # ).then(
831
+ # fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder"
832
+ # ).then(
833
+ # fn=clear_textbox, inputs=[], outputs=[chat_input]
834
+ # )
835
+
836
+ # audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy', every=0.1)
837
+ # audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
838
+
839
+ # with gr.Column():
840
+ # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
841
+ # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
842
+ # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
843
+
844
+ # refresh_button = gr.Button("Refresh Images")
845
+ # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3], api_name="update_image")
846
+
847
+ # demo.queue()
848
+ # demo.launch(share=True)
849
+
850
  import gradio as gr
851
  import requests
852
  import os
 
1315
  if choice in ["Details", "Conversational"]:
1316
  return gr.update(visible=True), update_map_with_response(history)
1317
  else:
1318
+ return gr.update(visible(False), "")
1319
 
1320
  def generate_audio_elevenlabs(text):
1321
  XI_API_KEY = os.environ['ELEVENLABS_API']
 
1491
  api_key = os.environ['SERP_API']
1492
  url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
1493
  response = requests.get(url)
1494
+ if response.status_code == 200):
1495
  events_results = response.json().get("events_results", [])
1496
  events_html = """
1497
  <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
 
1701
 
1702
 
1703