Pijush2023 commited on
Commit
2531994
·
verified ·
1 Parent(s): c23859a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +489 -513
app.py CHANGED
@@ -129,7 +129,7 @@ gpt4o_mini_model = initialize_gpt4o_mini_model()
129
 
130
  # Existing embeddings and vector store for GPT-4o
131
  gpt_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
132
- gpt_vectorstore = PineconeVectorStore(index_name="radarfinaldata08192024", embedding=gpt_embeddings)
133
  gpt_retriever = gpt_vectorstore.as_retriever(search_kwargs={'k': 5})
134
 
135
 
@@ -138,7 +138,7 @@ gpt_retriever = gpt_vectorstore.as_retriever(search_kwargs={'k': 5})
138
 
139
  # New vector store setup for Phi-3.5
140
  phi_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
141
- phi_vectorstore = PineconeVectorStore(index_name="phivectornew09102024", embedding=phi_embeddings)
142
  phi_retriever = phi_vectorstore.as_retriever(search_kwargs={'k': 5})
143
 
144
 
@@ -149,7 +149,7 @@ phi_retriever = phi_vectorstore.as_retriever(search_kwargs={'k': 5})
149
  from pinecone import Pinecone
150
  pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
151
 
152
- index_name = "radarfinaldata08192024"
153
  vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
154
  retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
155
 
@@ -167,34 +167,10 @@ def get_current_date():
167
 
168
  current_date = get_current_date()
169
 
170
- 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,sports and activities in Birmingham that can enhance your experience.
171
- 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.
172
- Now, let me guide you through some of the exciting events happening today in Birmingham, Alabama:
173
- Address: >>, Birmingham, AL
174
- Time: >>__
175
- Date: >>__
176
- Description: >>__
177
- Address: >>, Birmingham, AL
178
- Time: >>__
179
- Date: >>__
180
- Description: >>__
181
- Address: >>, Birmingham, AL
182
- Time: >>__
183
- Date: >>__
184
- Description: >>__
185
- Address: >>, Birmingham, AL
186
- Time: >>__
187
- Date: >>__
188
- Description: >>__
189
- Address: >>, Birmingham, AL
190
- Time: >>__
191
- Date: >>__
192
- Description: >>__
193
- 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.
194
- It was my pleasure!
195
- {{context}}
196
  Question: {{question}}
197
- Helpful Answer:"""
198
 
199
  # 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 the locations. I draw upon my extensive knowledge of the area, including perennial events and historical context.
200
  # 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.
@@ -205,12 +181,10 @@ Helpful Answer:"""
205
 
206
 
207
 
208
- template2 =f"""Hello there! As your friendly and knowledgeable guide here in Birmingham, Alabama . I'm here to help you discover the best experiences this beautiful city has to offer. It's a bright and sunny day today, {current_date}, and I’m excited to assist you with any insights or recommendations you need.
209
- Whether you're looking for local events, sports ,clubs,concerts etc or just a great place to grab a bite, I've got you covered.Keep your response casual, short and sweet for the quickest response.Don't reveal the location and give the response in a descriptive way, I'm here to help make your time in Birmingham unforgettable!
210
- "It’s always a pleasure to assist you!"
211
- {{context}}
212
  Question: {{question}}
213
- Helpful Answer:"""
214
 
215
 
216
  QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
@@ -235,115 +209,115 @@ graph = Neo4jGraph(url="neo4j+s://6457770f.databases.neo4j.io",
235
  # graph_documents = llm_transformer.convert_to_graph_documents(documents)
236
  # graph.add_graph_documents(graph_documents, baseEntityLabel=True, include_source=True)
237
 
238
- class Entities(BaseModel):
239
- names: list[str] = Field(..., description="All the person, organization, or business entities that appear in the text")
240
-
241
- entity_prompt = ChatPromptTemplate.from_messages([
242
- ("system", "You are extracting organization and person entities from the text."),
243
- ("human", "Use the given format to extract information from the following input: {question}"),
244
- ])
245
-
246
- entity_chain = entity_prompt | chat_model.with_structured_output(Entities)
247
-
248
- def remove_lucene_chars(input: str) -> str:
249
- return input.translate(str.maketrans({"\\": r"\\", "+": r"\+", "-": r"\-", "&": r"\&", "|": r"\|", "!": r"\!",
250
- "(": r"\(", ")": r"\)", "{": r"\{", "}": r"\}", "[": r"\[", "]": r"\]",
251
- "^": r"\^", "~": r"\~", "*": r"\*", "?": r"\?", ":": r"\:", '"': r'\"',
252
- ";": r"\;", " ": r"\ "}))
253
-
254
- def generate_full_text_query(input: str) -> str:
255
- full_text_query = ""
256
- words = [el for el in remove_lucene_chars(input).split() if el]
257
- for word in words[:-1]:
258
- full_text_query += f" {word}~2 AND"
259
- full_text_query += f" {words[-1]}~2"
260
- return full_text_query.strip()
261
-
262
- def structured_retriever(question: str) -> str:
263
- result = ""
264
- entities = entity_chain.invoke({"question": question})
265
- for entity in entities.names:
266
- response = graph.query(
267
- """CALL db.index.fulltext.queryNodes('entity', $query, {limit:2})
268
- YIELD node,score
269
- CALL {
270
- WITH node
271
- MATCH (node)-[r:!MENTIONS]->(neighbor)
272
- RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS output
273
- UNION ALL
274
- WITH node
275
- MATCH (node)<-[r:!MENTIONS]-(neighbor)
276
- RETURN neighbor.id + ' - ' + type(r) + ' -> ' + node.id AS output
277
- }
278
- RETURN output LIMIT 50
279
- """,
280
- {"query": generate_full_text_query(entity)},
281
- )
282
- result += "\n".join([el['output'] for el in response])
283
- return result
284
-
285
- def retriever_neo4j(question: str):
286
- structured_data = structured_retriever(question)
287
- logging.debug(f"Structured data: {structured_data}")
288
- return structured_data
289
-
290
- _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
291
- in its original language.
292
- Chat History:
293
- {chat_history}
294
- Follow Up Input: {question}
295
- Standalone question:"""
296
-
297
- CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
298
-
299
- def _format_chat_history(chat_history: list[tuple[str, str]]) -> list:
300
- buffer = []
301
- for human, ai in chat_history:
302
- buffer.append(HumanMessage(content=human))
303
- buffer.append(AIMessage(content=ai))
304
- return buffer
305
-
306
- _search_query = RunnableBranch(
307
- (
308
- RunnableLambda(lambda x: bool(x.get("chat_history"))).with_config(
309
- run_name="HasChatHistoryCheck"
310
- ),
311
- RunnablePassthrough.assign(
312
- chat_history=lambda x: _format_chat_history(x["chat_history"])
313
- )
314
- | CONDENSE_QUESTION_PROMPT
315
- | ChatOpenAI(temperature=0, api_key=os.environ['OPENAI_API_KEY'])
316
- | StrOutputParser(),
317
- ),
318
- RunnableLambda(lambda x : x["question"]),
319
- )
320
-
321
- # template = """Answer the question based only on the following context:
322
- # {context}
323
- # Question: {question}
324
- # Use natural language and be concise.
325
- # Answer:"""
326
-
327
- template = 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.I also assist the visitors about various sports and activities. 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.
328
- 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,short ,crisp and accurate response.
329
- "It was my pleasure!"
330
- {{context}}
331
- Question: {{question}}
332
- Helpful Answer:"""
333
 
334
- qa_prompt = ChatPromptTemplate.from_template(template)
335
 
336
- chain_neo4j = (
337
- RunnableParallel(
338
- {
339
- "context": _search_query | retriever_neo4j,
340
- "question": RunnablePassthrough(),
341
- }
342
- )
343
- | qa_prompt
344
- | chat_model
345
- | StrOutputParser()
346
- )
347
 
348
 
349
 
@@ -353,7 +327,9 @@ chain_neo4j = (
353
 
354
  phi_custom_template = """
355
  <|system|>
356
- You are a helpful assistant who provides clear, organized, crisp and conversational responses about an events,concerts,sports and all other activities of Birmingham,Alabama .<|end|>
 
 
357
  <|user|>
358
  {context}
359
  Question: {question}<|end|>
@@ -483,13 +459,16 @@ def clean_response(response_text):
483
  return cleaned_response
484
 
485
  # Define a new template specifically for GPT-4o-mini in VDB Details mode
486
- gpt4o_mini_template_details = f"""
487
- As a highly specialized assistant, I provide precise, detailed, and informative responses. On this bright day of {current_date}, I'm equipped to assist with all your queries about Birmingham, Alabama, offering detailed insights tailored to your needs.
488
- Given your request, here is the detailed information you're seeking:
 
 
 
 
489
  {{context}}
490
  Question: {{question}}
491
- Detailed Answer:
492
- """
493
 
494
 
495
 
@@ -523,26 +502,26 @@ def generate_answer(message, choice, retrieval_mode, selected_model):
523
  else:
524
  prompt_template = QA_CHAIN_PROMPT_1 # Fallback to template1
525
 
526
- # Handle hotel-related queries
527
- if "hotel" in message.lower() or "hotels" in message.lower() and "birmingham" in message.lower():
528
- logging.debug("Handling hotel-related query")
529
- response = fetch_google_hotels()
530
- logging.debug(f"Hotel response: {response}")
531
- return response, extract_addresses(response)
532
-
533
- # Handle restaurant-related queries
534
- if "restaurant" in message.lower() or "restaurants" in message.lower() and "birmingham" in message.lower():
535
- logging.debug("Handling restaurant-related query")
536
- response = fetch_yelp_restaurants()
537
- logging.debug(f"Restaurant response: {response}")
538
- return response, extract_addresses(response)
539
-
540
- # Handle flight-related queries
541
- if "flight" in message.lower() or "flights" in message.lower() and "birmingham" in message.lower():
542
- logging.debug("Handling flight-related query")
543
- response = fetch_google_flights()
544
- logging.debug(f"Flight response: {response}")
545
- return response, extract_addresses(response)
546
 
547
  # Retrieval-based response
548
  if retrieval_mode == "VDB":
@@ -641,61 +620,61 @@ def add_message(history, message):
641
  def print_like_dislike(x: gr.LikeData):
642
  print(x.index, x.value, x.liked)
643
 
644
- def extract_addresses(response):
645
- if not isinstance(response, str):
646
- response = str(response)
647
- address_patterns = [
648
- r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
649
- r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
650
- r'([A-Z].*,\sAL\s\d{5})',
651
- r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
652
- r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
653
- r'(\d{2}.*\sStreets)',
654
- r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
655
- r'([a-zA-Z]\s Birmingham)',
656
- r'([a-zA-Z].*,\sBirmingham,\sAL)',
657
- r'(.*),(Birmingham, AL,USA)$'
658
- r'(^Birmingham,AL$)',
659
- r'((.*)(Stadium|Field),.*,\sAL$)',
660
- r'((.*)(Stadium|Field),.*,\sFL$)',
661
- r'((.*)(Stadium|Field),.*,\sMS$)',
662
- r'((.*)(Stadium|Field),.*,\sAR$)',
663
- r'((.*)(Stadium|Field),.*,\sKY$)',
664
- r'((.*)(Stadium|Field),.*,\sTN$)',
665
- r'((.*)(Stadium|Field),.*,\sLA$)',
666
- r'((.*)(Stadium|Field),.*,\sFL$)'
667
-
668
- ]
669
- addresses = []
670
- for pattern in address_patterns:
671
- addresses.extend(re.findall(pattern, response))
672
- return addresses
673
-
674
- all_addresses = []
675
-
676
- def generate_map(location_names):
677
- global all_addresses
678
- all_addresses.extend(location_names)
679
-
680
- api_key = os.environ['GOOGLEMAPS_API_KEY']
681
- gmaps = GoogleMapsClient(key=api_key)
682
-
683
- m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
684
-
685
- for location_name in all_addresses:
686
- geocode_result = gmaps.geocode(location_name)
687
- if geocode_result:
688
- location = geocode_result[0]['geometry']['location']
689
- folium.Marker(
690
- [location['lat'], location['lng']],
691
- tooltip=f"{geocode_result[0]['formatted_address']}"
692
- ).add_to(m)
693
-
694
- map_html = m._repr_html_()
695
- return map_html
696
-
697
- from diffusers import DiffusionPipeline
698
- import torch
699
 
700
 
701
 
@@ -707,79 +686,79 @@ import torch
707
 
708
 
709
 
710
- def fetch_local_news():
711
- api_key = os.environ['SERP_API']
712
- url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
713
- response = requests.get(url)
714
- if response.status_code == 200:
715
- results = response.json().get("news_results", [])
716
- news_html = """
717
- <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
718
- <style>
719
- .news-item {
720
- font-family: 'Verdana', sans-serif;
721
- color: #333;
722
- background-color: #f0f8ff;
723
- margin-bottom: 15px;
724
- padding: 10px;
725
- border-radius: 5px;
726
- transition: box-shadow 0.3s ease, background-color 0.3s ease;
727
- font-weight: bold;
728
- }
729
- .news-item:hover {
730
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
731
- background-color: #e6f7ff;
732
- }
733
- .news-item a {
734
- color: #1E90FF;
735
- text-decoration: none;
736
- font-weight: bold;
737
- }
738
- .news-item a:hover {
739
- text-decoration: underline;
740
- }
741
- .news-preview {
742
- position: absolute;
743
- display: none;
744
- border: 1px solid #ccc;
745
- border-radius: 5px;
746
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
747
- background-color: white;
748
- z-index: 1000;
749
- max-width: 300px;
750
- padding: 10px;
751
- font-family: 'Verdana', sans-serif;
752
- color: #333;
753
- }
754
- </style>
755
- <script>
756
- function showPreview(event, previewContent) {
757
- var previewBox = document.getElementById('news-preview');
758
- previewBox.innerHTML = previewContent;
759
- previewBox.style.left = event.pageX + 'px';
760
- previewBox.style.top = event.pageY + 'px';
761
- previewBox.style.display = 'block';
762
- }
763
- function hidePreview() {
764
- var previewBox = document.getElementById('news-preview');
765
- previewBox.style.display = 'none';
766
- }
767
- </script>
768
- <div id="news-preview" class="news-preview"></div>
769
- """
770
- for index, result in enumerate(results[:7]):
771
- title = result.get("title", "No title")
772
- link = result.get("link", "#")
773
- snippet = result.get("snippet", "")
774
- news_html += f"""
775
- <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
776
- <a href='{link}' target='_blank'>{index + 1}. {title}</a>
777
- <p>{snippet}</p>
778
- </div>
779
- """
780
- return news_html
781
- else:
782
- return "<p>Failed to fetch local news</p>"
783
 
784
  import numpy as np
785
  import torch
@@ -823,21 +802,21 @@ def transcribe_function(stream, new_chunk):
823
 
824
 
825
 
826
- def update_map_with_response(history):
827
- if not history:
828
- return ""
829
- response = history[-1][1]
830
- addresses = extract_addresses(response)
831
- return generate_map(addresses)
832
 
833
  def clear_textbox():
834
  return ""
835
 
836
- def show_map_if_details(history, choice):
837
- if choice in ["Details", "Conversational"]:
838
- return gr.update(visible=True), update_map_with_response(history)
839
- else:
840
- return gr.update(visible(False), "")
841
 
842
 
843
 
@@ -962,153 +941,153 @@ def generate_audio_parler_tts(text):
962
  return combined_audio_path
963
 
964
 
965
- def fetch_local_events():
966
- api_key = os.environ['SERP_API']
967
- url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
968
- response = requests.get(url)
969
- if response.status_code == 200:
970
- events_results = response.json().get("events_results", [])
971
- events_html = """
972
- <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
973
- <style>
974
- table {
975
- font-family: 'Verdana', sans-serif;
976
- color: #333;
977
- border-collapse: collapse;
978
- width: 100%;
979
- }
980
- th, td {
981
- border: 1px solid #fff !important;
982
- padding: 8px;
983
- }
984
- th {
985
- background-color: #f2f2f2;
986
- color: #333;
987
- text-align: left;
988
- }
989
- tr:hover {
990
- background-color: #f5f5f5;
991
- }
992
- .event-link {
993
- color: #1E90FF;
994
- text-decoration: none;
995
- }
996
- .event-link:hover {
997
- text-decoration: underline;
998
- }
999
- </style>
1000
- <table>
1001
- <tr>
1002
- <th>Title</th>
1003
- <th>Date and Time</th>
1004
- <th>Location</th>
1005
- </tr>
1006
- """
1007
- for event in events_results:
1008
- title = event.get("title", "No title")
1009
- date_info = event.get("date", {})
1010
- date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
1011
- location = event.get("address", "No location")
1012
- if isinstance(location, list):
1013
- location = " ".join(location)
1014
- location = location.replace("[", "").replace("]", "")
1015
- link = event.get("link", "#")
1016
- events_html += f"""
1017
- <tr>
1018
- <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
1019
- <td>{date}</td>
1020
- <td>{location}</td>
1021
- </tr>
1022
- """
1023
- events_html += "</table>"
1024
- return events_html
1025
- else:
1026
- return "<p>Failed to fetch local events</p>"
1027
-
1028
- def get_weather_icon(condition):
1029
- condition_map = {
1030
- "Clear": "c01d",
1031
- "Partly Cloudy": "c02d",
1032
- "Cloudy": "c03d",
1033
- "Overcast": "c04d",
1034
- "Mist": "a01d",
1035
- "Patchy rain possible": "r01d",
1036
- "Light rain": "r02d",
1037
- "Moderate rain": "r03d",
1038
- "Heavy rain": "r04d",
1039
- "Snow": "s01d",
1040
- "Thunderstorm": "t01d",
1041
- "Fog": "a05d",
1042
- }
1043
- return condition_map.get(condition, "c04d")
1044
-
1045
- def fetch_local_weather():
1046
- try:
1047
- api_key = os.environ['WEATHER_API']
1048
- url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
1049
- response = requests.get(url)
1050
- response.raise_for_status()
1051
- jsonData = response.json()
1052
-
1053
- current_conditions = jsonData.get("currentConditions", {})
1054
- temp_celsius = current_conditions.get("temp", "N/A")
1055
-
1056
- if temp_celsius != "N/A":
1057
- temp_fahrenheit = int((temp_celsius * 9/5) + 32)
1058
- else:
1059
- temp_fahrenheit = "N/A"
1060
-
1061
- condition = current_conditions.get("conditions", "N/A")
1062
- humidity = current_conditions.get("humidity", "N/A")
1063
-
1064
- weather_html = f"""
1065
- <div class="weather-theme">
1066
- <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
1067
- <div class="weather-content">
1068
- <div class="weather-icon">
1069
- <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
1070
- </div>
1071
- <div class="weather-details">
1072
- <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
1073
- <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
1074
- <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
1075
- </div>
1076
- </div>
1077
- </div>
1078
- <style>
1079
- .weather-theme {{
1080
- animation: backgroundAnimation 10s infinite alternate;
1081
- border-radius: 10px;
1082
- padding: 10px;
1083
- margin-bottom: 15px;
1084
- background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
1085
- background-size: 400% 400%;
1086
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
1087
- transition: box-shadow 0.3s ease, background-color 0.3s ease;
1088
- }}
1089
- .weather-theme:hover {{
1090
- box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
1091
- background-position: 100% 100%;
1092
- }}
1093
- @keyframes backgroundAnimation {{
1094
- 0% {{ background-position: 0% 50%; }}
1095
- 100% {{ background-position: 100% 50%; }}
1096
- }}
1097
- .weather-content {{
1098
- display: flex;
1099
- align-items: center;
1100
- }}
1101
- .weather-icon {{
1102
- flex: 1;
1103
- }}
1104
- .weather-details {{
1105
- flex 3;
1106
- }}
1107
- </style>
1108
- """
1109
- return weather_html
1110
- except requests.exceptions.RequestException as e:
1111
- return f"<p>Failed to fetch local weather: {e}</p>"
1112
 
1113
 
1114
  def handle_retrieval_mode_change(choice):
@@ -1338,45 +1317,45 @@ def fetch_google_flights(departure_id="JFK", arrival_id="BHM", outbound_date=cur
1338
  return flight_info
1339
 
1340
 
1341
- examples = [
1342
- [
1343
- "What are the concerts in Birmingham?",
1344
- ],
1345
- [
1346
- "what are some of the upcoming matches of crimson tide?",
1347
- ],
1348
- [
1349
- "where from i will get a Hamburger?",
1350
- ],
1351
- [
1352
- "What are some of the hotels at birmingham?",
1353
- ],
1354
- [
1355
- "how can i connect the alexa to the radio?"
1356
- ],
1357
- [
1358
- "What are some of the good clubs at birmingham?"
1359
- ],
1360
- [
1361
- "How do I call the radio station?",
1362
- ],
1363
- [
1364
- "What’s the spread?"
1365
- ],
1366
- [
1367
- "What time is Crimson Tide Rewind?"
1368
- ],
1369
- [
1370
- "What time is Alabama kick-off?"
1371
- ],
1372
- [
1373
- "who are some of the popular players of crimson tide?"
1374
- ]
1375
- ]
1376
-
1377
- # Function to insert the prompt into the textbox when clicked
1378
- def insert_prompt(current_text, prompt):
1379
- return prompt[0] if prompt else current_text
1380
 
1381
 
1382
 
@@ -1389,7 +1368,7 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1389
 
1390
  chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
1391
  choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
1392
- retrieval_mode = gr.Radio(label="Retrieval Mode", choices=["VDB", "KGF"], value="VDB")
1393
  model_choice = gr.Dropdown(label="Choose Model", choices=["LM-1", "LM-2", "LM-3"], value="LM-1")
1394
 
1395
  # Link the dropdown change to handle_model_choice_change
@@ -1405,8 +1384,8 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1405
  clear_button = gr.Button("Clear")
1406
  clear_button.click(lambda: [None, None], outputs=[chat_input, state])
1407
 
1408
- gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
1409
- location_output = gr.HTML()
1410
  audio_output = gr.Audio(interactive=False, autoplay=True)
1411
 
1412
  def stop_audio():
@@ -1424,7 +1403,6 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1424
  .then(fn=generate_bot_response, inputs=[chatbot, choice, retrieval_mode, model_choice], outputs=[chatbot], api_name="api_generate_bot_response")
1425
  # Then, generate the TTS response based on the bot's response
1426
  .then(fn=generate_tts_response, inputs=[chatbot, tts_choice], outputs=[audio_output], api_name="api_generate_tts_response")
1427
- .then(fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="api_show_map_details")
1428
  .then(fn=clear_textbox, inputs=[], outputs=[chat_input], api_name="api_clear_textbox")
1429
  )
1430
 
@@ -1443,8 +1421,6 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1443
  ).then(
1444
  # Then, generate the TTS response based on the bot's response
1445
  fn=generate_tts_response, inputs=[chatbot, tts_choice], outputs=[audio_output], api_name="api_generate_tts_response"
1446
- ).then(
1447
- fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="api_show_map_details"
1448
  ).then(
1449
  fn=clear_textbox, inputs=[], outputs=[chat_input], api_name="api_clear_textbox"
1450
  )
@@ -1461,25 +1437,25 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1461
  gr.Markdown("<h1 style='color: red;'>Example Prompts</h1>", elem_id="Example-Prompts")
1462
  gr.Examples(examples=examples, fn=insert_prompt,inputs=chat_input, outputs=chat_input)
1463
 
1464
- with gr.Column():
1465
- weather_output = gr.HTML(value=fetch_local_weather())
1466
- news_output = gr.HTML(value=fetch_local_news())
1467
- events_output = gr.HTML(value=fetch_local_events())
1468
 
1469
- with gr.Column():
1470
 
1471
 
1472
- # Call update_images during the initial load to display images when the interface appears
1473
- initial_images = update_images()
1474
 
1475
- # Displaying the images generated using Flux API directly
1476
- image_output_1 = gr.Image(value=initial_images[0], label="Image 1", elem_id="flux_image_1", width=400, height=400)
1477
- image_output_2 = gr.Image(value=initial_images[1], label="Image 2", elem_id="flux_image_2", width=400, height=400)
1478
- image_output_3 = gr.Image(value=initial_images[2], label="Image 3", elem_id="flux_image_3", width=400, height=400)
1479
 
1480
- # Refresh button to update images
1481
- refresh_button = gr.Button("Refresh Images")
1482
- refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
1483
 
1484
 
1485
 
 
129
 
130
  # Existing embeddings and vector store for GPT-4o
131
  gpt_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
132
+ gpt_vectorstore = PineconeVectorStore(index_name="italyv109102024", embedding=gpt_embeddings)
133
  gpt_retriever = gpt_vectorstore.as_retriever(search_kwargs={'k': 5})
134
 
135
 
 
138
 
139
  # New vector store setup for Phi-3.5
140
  phi_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
141
+ phi_vectorstore = PineconeVectorStore(index_name="italyv109102024", embedding=phi_embeddings)
142
  phi_retriever = phi_vectorstore.as_retriever(search_kwargs={'k': 5})
143
 
144
 
 
149
  from pinecone import Pinecone
150
  pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
151
 
152
+ index_name = "italyv109102024"
153
  vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
154
  retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
155
 
 
167
 
168
  current_date = get_current_date()
169
 
170
+ template1 = f"""You are an expert Italian speaker witg unrelah extensive knowledge of the language and culture. Your responses should be brief, to the point, and limited to one or two lines without providing excessive details. Please refrain from discussinted topics. Your signature phrase is, "It’s always a pleasure to assist you!"
171
+ Context: {{context}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  Question: {{question}}
173
+ Helpful Answer: """
174
 
175
  # 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 the locations. I draw upon my extensive knowledge of the area, including perennial events and historical context.
176
  # 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.
 
181
 
182
 
183
 
184
+ template2 =f"""You are an expert Italian speaker witg unrelah extensive knowledge of the language and culture. Your responses should be brief, to the point, and limited to one or two lines without providing excessive details. Please refrain from discussinted topics. Your signature phrase is, "It’s always a pleasure to assist you!"
185
+ Context: {{context}}
 
 
186
  Question: {{question}}
187
+ Helpful Answer: """
188
 
189
 
190
  QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
 
209
  # graph_documents = llm_transformer.convert_to_graph_documents(documents)
210
  # graph.add_graph_documents(graph_documents, baseEntityLabel=True, include_source=True)
211
 
212
+ # class Entities(BaseModel):
213
+ # names: list[str] = Field(..., description="All the person, organization, or business entities that appear in the text")
214
+
215
+ # entity_prompt = ChatPromptTemplate.from_messages([
216
+ # ("system", "You are extracting organization and person entities from the text."),
217
+ # ("human", "Use the given format to extract information from the following input: {question}"),
218
+ # ])
219
+
220
+ # entity_chain = entity_prompt | chat_model.with_structured_output(Entities)
221
+
222
+ # def remove_lucene_chars(input: str) -> str:
223
+ # return input.translate(str.maketrans({"\\": r"\\", "+": r"\+", "-": r"\-", "&": r"\&", "|": r"\|", "!": r"\!",
224
+ # "(": r"\(", ")": r"\)", "{": r"\{", "}": r"\}", "[": r"\[", "]": r"\]",
225
+ # "^": r"\^", "~": r"\~", "*": r"\*", "?": r"\?", ":": r"\:", '"': r'\"',
226
+ # ";": r"\;", " ": r"\ "}))
227
+
228
+ # def generate_full_text_query(input: str) -> str:
229
+ # full_text_query = ""
230
+ # words = [el for el in remove_lucene_chars(input).split() if el]
231
+ # for word in words[:-1]:
232
+ # full_text_query += f" {word}~2 AND"
233
+ # full_text_query += f" {words[-1]}~2"
234
+ # return full_text_query.strip()
235
+
236
+ # def structured_retriever(question: str) -> str:
237
+ # result = ""
238
+ # entities = entity_chain.invoke({"question": question})
239
+ # for entity in entities.names:
240
+ # response = graph.query(
241
+ # """CALL db.index.fulltext.queryNodes('entity', $query, {limit:2})
242
+ # YIELD node,score
243
+ # CALL {
244
+ # WITH node
245
+ # MATCH (node)-[r:!MENTIONS]->(neighbor)
246
+ # RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS output
247
+ # UNION ALL
248
+ # WITH node
249
+ # MATCH (node)<-[r:!MENTIONS]-(neighbor)
250
+ # RETURN neighbor.id + ' - ' + type(r) + ' -> ' + node.id AS output
251
+ # }
252
+ # RETURN output LIMIT 50
253
+ # """,
254
+ # {"query": generate_full_text_query(entity)},
255
+ # )
256
+ # result += "\n".join([el['output'] for el in response])
257
+ # return result
258
+
259
+ # def retriever_neo4j(question: str):
260
+ # structured_data = structured_retriever(question)
261
+ # logging.debug(f"Structured data: {structured_data}")
262
+ # return structured_data
263
+
264
+ # _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
265
+ # in its original language.
266
+ # Chat History:
267
+ # {chat_history}
268
+ # Follow Up Input: {question}
269
+ # Standalone question:"""
270
+
271
+ # CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
272
+
273
+ # def _format_chat_history(chat_history: list[tuple[str, str]]) -> list:
274
+ # buffer = []
275
+ # for human, ai in chat_history:
276
+ # buffer.append(HumanMessage(content=human))
277
+ # buffer.append(AIMessage(content=ai))
278
+ # return buffer
279
+
280
+ # _search_query = RunnableBranch(
281
+ # (
282
+ # RunnableLambda(lambda x: bool(x.get("chat_history"))).with_config(
283
+ # run_name="HasChatHistoryCheck"
284
+ # ),
285
+ # RunnablePassthrough.assign(
286
+ # chat_history=lambda x: _format_chat_history(x["chat_history"])
287
+ # )
288
+ # | CONDENSE_QUESTION_PROMPT
289
+ # | ChatOpenAI(temperature=0, api_key=os.environ['OPENAI_API_KEY'])
290
+ # | StrOutputParser(),
291
+ # ),
292
+ # RunnableLambda(lambda x : x["question"]),
293
+ # )
294
+
295
+ # # template = """Answer the question based only on the following context:
296
+ # # {context}
297
+ # # Question: {question}
298
+ # # Use natural language and be concise.
299
+ # # Answer:"""
300
+
301
+ # template = 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.I also assist the visitors about various sports and activities. 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.
302
+ # 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,short ,crisp and accurate response.
303
+ # "It was my pleasure!"
304
+ # {{context}}
305
+ # Question: {{question}}
306
+ # Helpful Answer:"""
307
 
308
+ # qa_prompt = ChatPromptTemplate.from_template(template)
309
 
310
+ # chain_neo4j = (
311
+ # RunnableParallel(
312
+ # {
313
+ # "context": _search_query | retriever_neo4j,
314
+ # "question": RunnablePassthrough(),
315
+ # }
316
+ # )
317
+ # | qa_prompt
318
+ # | chat_model
319
+ # | StrOutputParser()
320
+ # )
321
 
322
 
323
 
 
327
 
328
  phi_custom_template = """
329
  <|system|>
330
+ You are an expert Italian speaker with extensive knowledge of the language and culture.
331
+ Your responses should be brief, to the point, and limited to one or two lines without providing excessive details.
332
+ Please refrain from discussing unrelated topics. Your signature phrase is, "It’s always a pleasure to assist you!"<|end|>
333
  <|user|>
334
  {context}
335
  Question: {question}<|end|>
 
459
  return cleaned_response
460
 
461
  # Define a new template specifically for GPT-4o-mini in VDB Details mode
462
+ gpt4o_mini_template_details = f"""You’re an expert in Italian culture and language with a deep understanding of various topics related to Italy, including history, cuisine, art, and traditions. Your role is to provide clear and concise responses in Italian while remaining focused strictly on the question at hand.
463
+ Your task is to answer questions posed to you. Here are the details about the inquiries I would like you to address:
464
+ - Topic:
465
+ - Specific Question:
466
+ - Context (if any):
467
+
468
+ Please ensure that your answers remain relevant to the topic and avoid discussing unrelated subjects.
469
  {{context}}
470
  Question: {{question}}
471
+ Helpful Answer:"""
 
472
 
473
 
474
 
 
502
  else:
503
  prompt_template = QA_CHAIN_PROMPT_1 # Fallback to template1
504
 
505
+ # # Handle hotel-related queries
506
+ # if "hotel" in message.lower() or "hotels" in message.lower() and "birmingham" in message.lower():
507
+ # logging.debug("Handling hotel-related query")
508
+ # response = fetch_google_hotels()
509
+ # logging.debug(f"Hotel response: {response}")
510
+ # return response, extract_addresses(response)
511
+
512
+ # # Handle restaurant-related queries
513
+ # if "restaurant" in message.lower() or "restaurants" in message.lower() and "birmingham" in message.lower():
514
+ # logging.debug("Handling restaurant-related query")
515
+ # response = fetch_yelp_restaurants()
516
+ # logging.debug(f"Restaurant response: {response}")
517
+ # return response, extract_addresses(response)
518
+
519
+ # # Handle flight-related queries
520
+ # if "flight" in message.lower() or "flights" in message.lower() and "birmingham" in message.lower():
521
+ # logging.debug("Handling flight-related query")
522
+ # response = fetch_google_flights()
523
+ # logging.debug(f"Flight response: {response}")
524
+ # return response, extract_addresses(response)
525
 
526
  # Retrieval-based response
527
  if retrieval_mode == "VDB":
 
620
  def print_like_dislike(x: gr.LikeData):
621
  print(x.index, x.value, x.liked)
622
 
623
+ # def extract_addresses(response):
624
+ # if not isinstance(response, str):
625
+ # response = str(response)
626
+ # address_patterns = [
627
+ # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
628
+ # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
629
+ # r'([A-Z].*,\sAL\s\d{5})',
630
+ # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
631
+ # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
632
+ # r'(\d{2}.*\sStreets)',
633
+ # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
634
+ # r'([a-zA-Z]\s Birmingham)',
635
+ # r'([a-zA-Z].*,\sBirmingham,\sAL)',
636
+ # r'(.*),(Birmingham, AL,USA)$'
637
+ # r'(^Birmingham,AL$)',
638
+ # r'((.*)(Stadium|Field),.*,\sAL$)',
639
+ # r'((.*)(Stadium|Field),.*,\sFL$)',
640
+ # r'((.*)(Stadium|Field),.*,\sMS$)',
641
+ # r'((.*)(Stadium|Field),.*,\sAR$)',
642
+ # r'((.*)(Stadium|Field),.*,\sKY$)',
643
+ # r'((.*)(Stadium|Field),.*,\sTN$)',
644
+ # r'((.*)(Stadium|Field),.*,\sLA$)',
645
+ # r'((.*)(Stadium|Field),.*,\sFL$)'
646
+
647
+ # ]
648
+ # addresses = []
649
+ # for pattern in address_patterns:
650
+ # addresses.extend(re.findall(pattern, response))
651
+ # return addresses
652
+
653
+ # all_addresses = []
654
+
655
+ # def generate_map(location_names):
656
+ # global all_addresses
657
+ # all_addresses.extend(location_names)
658
+
659
+ # api_key = os.environ['GOOGLEMAPS_API_KEY']
660
+ # gmaps = GoogleMapsClient(key=api_key)
661
+
662
+ # m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
663
+
664
+ # for location_name in all_addresses:
665
+ # geocode_result = gmaps.geocode(location_name)
666
+ # if geocode_result:
667
+ # location = geocode_result[0]['geometry']['location']
668
+ # folium.Marker(
669
+ # [location['lat'], location['lng']],
670
+ # tooltip=f"{geocode_result[0]['formatted_address']}"
671
+ # ).add_to(m)
672
+
673
+ # map_html = m._repr_html_()
674
+ # return map_html
675
+
676
+ # from diffusers import DiffusionPipeline
677
+ # import torch
678
 
679
 
680
 
 
686
 
687
 
688
 
689
+ # def fetch_local_news():
690
+ # api_key = os.environ['SERP_API']
691
+ # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
692
+ # response = requests.get(url)
693
+ # if response.status_code == 200:
694
+ # results = response.json().get("news_results", [])
695
+ # news_html = """
696
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
697
+ # <style>
698
+ # .news-item {
699
+ # font-family: 'Verdana', sans-serif;
700
+ # color: #333;
701
+ # background-color: #f0f8ff;
702
+ # margin-bottom: 15px;
703
+ # padding: 10px;
704
+ # border-radius: 5px;
705
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
706
+ # font-weight: bold;
707
+ # }
708
+ # .news-item:hover {
709
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
710
+ # background-color: #e6f7ff;
711
+ # }
712
+ # .news-item a {
713
+ # color: #1E90FF;
714
+ # text-decoration: none;
715
+ # font-weight: bold;
716
+ # }
717
+ # .news-item a:hover {
718
+ # text-decoration: underline;
719
+ # }
720
+ # .news-preview {
721
+ # position: absolute;
722
+ # display: none;
723
+ # border: 1px solid #ccc;
724
+ # border-radius: 5px;
725
+ # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
726
+ # background-color: white;
727
+ # z-index: 1000;
728
+ # max-width: 300px;
729
+ # padding: 10px;
730
+ # font-family: 'Verdana', sans-serif;
731
+ # color: #333;
732
+ # }
733
+ # </style>
734
+ # <script>
735
+ # function showPreview(event, previewContent) {
736
+ # var previewBox = document.getElementById('news-preview');
737
+ # previewBox.innerHTML = previewContent;
738
+ # previewBox.style.left = event.pageX + 'px';
739
+ # previewBox.style.top = event.pageY + 'px';
740
+ # previewBox.style.display = 'block';
741
+ # }
742
+ # function hidePreview() {
743
+ # var previewBox = document.getElementById('news-preview');
744
+ # previewBox.style.display = 'none';
745
+ # }
746
+ # </script>
747
+ # <div id="news-preview" class="news-preview"></div>
748
+ # """
749
+ # for index, result in enumerate(results[:7]):
750
+ # title = result.get("title", "No title")
751
+ # link = result.get("link", "#")
752
+ # snippet = result.get("snippet", "")
753
+ # news_html += f"""
754
+ # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
755
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
756
+ # <p>{snippet}</p>
757
+ # </div>
758
+ # """
759
+ # return news_html
760
+ # else:
761
+ # return "<p>Failed to fetch local news</p>"
762
 
763
  import numpy as np
764
  import torch
 
802
 
803
 
804
 
805
+ # def update_map_with_response(history):
806
+ # if not history:
807
+ # return ""
808
+ # response = history[-1][1]
809
+ # addresses = extract_addresses(response)
810
+ # return generate_map(addresses)
811
 
812
  def clear_textbox():
813
  return ""
814
 
815
+ # def show_map_if_details(history, choice):
816
+ # if choice in ["Details", "Conversational"]:
817
+ # return gr.update(visible=True), update_map_with_response(history)
818
+ # else:
819
+ # return gr.update(visible(False), "")
820
 
821
 
822
 
 
941
  return combined_audio_path
942
 
943
 
944
+ # def fetch_local_events():
945
+ # api_key = os.environ['SERP_API']
946
+ # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
947
+ # response = requests.get(url)
948
+ # if response.status_code == 200:
949
+ # events_results = response.json().get("events_results", [])
950
+ # events_html = """
951
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
952
+ # <style>
953
+ # table {
954
+ # font-family: 'Verdana', sans-serif;
955
+ # color: #333;
956
+ # border-collapse: collapse;
957
+ # width: 100%;
958
+ # }
959
+ # th, td {
960
+ # border: 1px solid #fff !important;
961
+ # padding: 8px;
962
+ # }
963
+ # th {
964
+ # background-color: #f2f2f2;
965
+ # color: #333;
966
+ # text-align: left;
967
+ # }
968
+ # tr:hover {
969
+ # background-color: #f5f5f5;
970
+ # }
971
+ # .event-link {
972
+ # color: #1E90FF;
973
+ # text-decoration: none;
974
+ # }
975
+ # .event-link:hover {
976
+ # text-decoration: underline;
977
+ # }
978
+ # </style>
979
+ # <table>
980
+ # <tr>
981
+ # <th>Title</th>
982
+ # <th>Date and Time</th>
983
+ # <th>Location</th>
984
+ # </tr>
985
+ # """
986
+ # for event in events_results:
987
+ # title = event.get("title", "No title")
988
+ # date_info = event.get("date", {})
989
+ # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
990
+ # location = event.get("address", "No location")
991
+ # if isinstance(location, list):
992
+ # location = " ".join(location)
993
+ # location = location.replace("[", "").replace("]", "")
994
+ # link = event.get("link", "#")
995
+ # events_html += f"""
996
+ # <tr>
997
+ # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
998
+ # <td>{date}</td>
999
+ # <td>{location}</td>
1000
+ # </tr>
1001
+ # """
1002
+ # events_html += "</table>"
1003
+ # return events_html
1004
+ # else:
1005
+ # return "<p>Failed to fetch local events</p>"
1006
+
1007
+ # def get_weather_icon(condition):
1008
+ # condition_map = {
1009
+ # "Clear": "c01d",
1010
+ # "Partly Cloudy": "c02d",
1011
+ # "Cloudy": "c03d",
1012
+ # "Overcast": "c04d",
1013
+ # "Mist": "a01d",
1014
+ # "Patchy rain possible": "r01d",
1015
+ # "Light rain": "r02d",
1016
+ # "Moderate rain": "r03d",
1017
+ # "Heavy rain": "r04d",
1018
+ # "Snow": "s01d",
1019
+ # "Thunderstorm": "t01d",
1020
+ # "Fog": "a05d",
1021
+ # }
1022
+ # return condition_map.get(condition, "c04d")
1023
+
1024
+ # def fetch_local_weather():
1025
+ # try:
1026
+ # api_key = os.environ['WEATHER_API']
1027
+ # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
1028
+ # response = requests.get(url)
1029
+ # response.raise_for_status()
1030
+ # jsonData = response.json()
1031
+
1032
+ # current_conditions = jsonData.get("currentConditions", {})
1033
+ # temp_celsius = current_conditions.get("temp", "N/A")
1034
+
1035
+ # if temp_celsius != "N/A":
1036
+ # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
1037
+ # else:
1038
+ # temp_fahrenheit = "N/A"
1039
+
1040
+ # condition = current_conditions.get("conditions", "N/A")
1041
+ # humidity = current_conditions.get("humidity", "N/A")
1042
+
1043
+ # weather_html = f"""
1044
+ # <div class="weather-theme">
1045
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
1046
+ # <div class="weather-content">
1047
+ # <div class="weather-icon">
1048
+ # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
1049
+ # </div>
1050
+ # <div class="weather-details">
1051
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
1052
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
1053
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
1054
+ # </div>
1055
+ # </div>
1056
+ # </div>
1057
+ # <style>
1058
+ # .weather-theme {{
1059
+ # animation: backgroundAnimation 10s infinite alternate;
1060
+ # border-radius: 10px;
1061
+ # padding: 10px;
1062
+ # margin-bottom: 15px;
1063
+ # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
1064
+ # background-size: 400% 400%;
1065
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
1066
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
1067
+ # }}
1068
+ # .weather-theme:hover {{
1069
+ # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
1070
+ # background-position: 100% 100%;
1071
+ # }}
1072
+ # @keyframes backgroundAnimation {{
1073
+ # 0% {{ background-position: 0% 50%; }}
1074
+ # 100% {{ background-position: 100% 50%; }}
1075
+ # }}
1076
+ # .weather-content {{
1077
+ # display: flex;
1078
+ # align-items: center;
1079
+ # }}
1080
+ # .weather-icon {{
1081
+ # flex: 1;
1082
+ # }}
1083
+ # .weather-details {{
1084
+ # flex 3;
1085
+ # }}
1086
+ # </style>
1087
+ # """
1088
+ # return weather_html
1089
+ # except requests.exceptions.RequestException as e:
1090
+ # return f"<p>Failed to fetch local weather: {e}</p>"
1091
 
1092
 
1093
  def handle_retrieval_mode_change(choice):
 
1317
  return flight_info
1318
 
1319
 
1320
+ # examples = [
1321
+ # [
1322
+ # "What are the concerts in Birmingham?",
1323
+ # ],
1324
+ # [
1325
+ # "what are some of the upcoming matches of crimson tide?",
1326
+ # ],
1327
+ # [
1328
+ # "where from i will get a Hamburger?",
1329
+ # ],
1330
+ # [
1331
+ # "What are some of the hotels at birmingham?",
1332
+ # ],
1333
+ # [
1334
+ # "how can i connect the alexa to the radio?"
1335
+ # ],
1336
+ # [
1337
+ # "What are some of the good clubs at birmingham?"
1338
+ # ],
1339
+ # [
1340
+ # "How do I call the radio station?",
1341
+ # ],
1342
+ # [
1343
+ # "What’s the spread?"
1344
+ # ],
1345
+ # [
1346
+ # "What time is Crimson Tide Rewind?"
1347
+ # ],
1348
+ # [
1349
+ # "What time is Alabama kick-off?"
1350
+ # ],
1351
+ # [
1352
+ # "who are some of the popular players of crimson tide?"
1353
+ # ]
1354
+ # ]
1355
+
1356
+ # # Function to insert the prompt into the textbox when clicked
1357
+ # def insert_prompt(current_text, prompt):
1358
+ # return prompt[0] if prompt else current_text
1359
 
1360
 
1361
 
 
1368
 
1369
  chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
1370
  choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
1371
+ retrieval_mode = gr.Radio(label="Retrieval Mode", choices=["VDB"], value="VDB")
1372
  model_choice = gr.Dropdown(label="Choose Model", choices=["LM-1", "LM-2", "LM-3"], value="LM-1")
1373
 
1374
  # Link the dropdown change to handle_model_choice_change
 
1384
  clear_button = gr.Button("Clear")
1385
  clear_button.click(lambda: [None, None], outputs=[chat_input, state])
1386
 
1387
+ # gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
1388
+ # location_output = gr.HTML()
1389
  audio_output = gr.Audio(interactive=False, autoplay=True)
1390
 
1391
  def stop_audio():
 
1403
  .then(fn=generate_bot_response, inputs=[chatbot, choice, retrieval_mode, model_choice], outputs=[chatbot], api_name="api_generate_bot_response")
1404
  # Then, generate the TTS response based on the bot's response
1405
  .then(fn=generate_tts_response, inputs=[chatbot, tts_choice], outputs=[audio_output], api_name="api_generate_tts_response")
 
1406
  .then(fn=clear_textbox, inputs=[], outputs=[chat_input], api_name="api_clear_textbox")
1407
  )
1408
 
 
1421
  ).then(
1422
  # Then, generate the TTS response based on the bot's response
1423
  fn=generate_tts_response, inputs=[chatbot, tts_choice], outputs=[audio_output], api_name="api_generate_tts_response"
 
 
1424
  ).then(
1425
  fn=clear_textbox, inputs=[], outputs=[chat_input], api_name="api_clear_textbox"
1426
  )
 
1437
  gr.Markdown("<h1 style='color: red;'>Example Prompts</h1>", elem_id="Example-Prompts")
1438
  gr.Examples(examples=examples, fn=insert_prompt,inputs=chat_input, outputs=chat_input)
1439
 
1440
+ # with gr.Column():
1441
+ # weather_output = gr.HTML(value=fetch_local_weather())
1442
+ # news_output = gr.HTML(value=fetch_local_news())
1443
+ # events_output = gr.HTML(value=fetch_local_events())
1444
 
1445
+ # with gr.Column():
1446
 
1447
 
1448
+ # # Call update_images during the initial load to display images when the interface appears
1449
+ # initial_images = update_images()
1450
 
1451
+ # # Displaying the images generated using Flux API directly
1452
+ # image_output_1 = gr.Image(value=initial_images[0], label="Image 1", elem_id="flux_image_1", width=400, height=400)
1453
+ # image_output_2 = gr.Image(value=initial_images[1], label="Image 2", elem_id="flux_image_2", width=400, height=400)
1454
+ # image_output_3 = gr.Image(value=initial_images[2], label="Image 3", elem_id="flux_image_3", width=400, height=400)
1455
 
1456
+ # # Refresh button to update images
1457
+ # refresh_button = gr.Button("Refresh Images")
1458
+ # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
1459
 
1460
 
1461