Pijush2023 commited on
Commit
8b52216
·
verified ·
1 Parent(s): fc1a408

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1389
app.py DELETED
@@ -1,1389 +0,0 @@
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
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
34
-
35
-
36
- # Neo4j imports
37
- from langchain.chains import GraphCypherQAChain
38
- from langchain_community.graphs import Neo4jGraph
39
- from langchain_community.document_loaders import HuggingFaceDatasetLoader
40
- from langchain_text_splitters import CharacterTextSplitter
41
- from langchain_experimental.graph_transformers import LLMGraphTransformer
42
- from langchain_core.prompts import ChatPromptTemplate
43
- from langchain_core.pydantic_v1 import BaseModel, Field
44
- from langchain_core.messages import AIMessage, HumanMessage
45
- from langchain_core.output_parsers import StrOutputParser
46
- from langchain_core.runnables import RunnableBranch, RunnableLambda, RunnableParallel, RunnablePassthrough
47
- from serpapi.google_search import GoogleSearch
48
-
49
- #Parler TTS v1 Modules
50
-
51
- import os
52
- import re
53
- import tempfile
54
- import soundfile as sf
55
- from string import punctuation
56
- from pydub import AudioSegment
57
- from transformers import AutoTokenizer, AutoFeatureExtractor
58
-
59
-
60
-
61
- #API AutoDate Fix Up
62
- def get_current_date1():
63
- return datetime.now().strftime("%Y-%m-%d")
64
-
65
- # Usage
66
- current_date1 = get_current_date1()
67
-
68
-
69
-
70
- # Set environment variables for CUDA
71
- os.environ['PYTORCH_USE_CUDA_DSA'] = '1'
72
- os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
73
-
74
-
75
- hf_token = os.getenv("HF_TOKEN")
76
- if hf_token is None:
77
- print("Please set your Hugging Face token in the environment variables.")
78
- else:
79
- login(token=hf_token)
80
-
81
- logging.basicConfig(level=logging.DEBUG)
82
-
83
-
84
- embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
85
-
86
-
87
- #Initialization
88
-
89
- # Initialize the models
90
- def initialize_phi_model():
91
- model = AutoModelForCausalLM.from_pretrained(
92
- "microsoft/Phi-3.5-mini-instruct",
93
- device_map="cuda",
94
- torch_dtype="auto",
95
- trust_remote_code=True,
96
- )
97
- tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3.5-mini-instruct")
98
- return pipeline("text-generation", model=model, tokenizer=tokenizer)
99
-
100
- def initialize_gpt_model():
101
- return ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
102
-
103
- # Initialize both models
104
- phi_pipe = initialize_phi_model()
105
- gpt_model = initialize_gpt_model()
106
-
107
-
108
- # Existing embeddings and vector store for GPT-4o
109
- gpt_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
110
- gpt_vectorstore = PineconeVectorStore(index_name="radarfinaldata08192024", embedding=gpt_embeddings)
111
- gpt_retriever = gpt_vectorstore.as_retriever(search_kwargs={'k': 5})
112
-
113
- # New vector store setup for Phi-3.5
114
- phi_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
115
- phi_vectorstore = PineconeVectorStore(index_name="phivector08252024", embedding=phi_embeddings)
116
- phi_retriever = phi_vectorstore.as_retriever(search_kwargs={'k': 5})
117
-
118
-
119
-
120
- # Pinecone setup
121
- from pinecone import Pinecone
122
- pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
123
-
124
- index_name = "radarfinaldata08192024"
125
- vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
126
- retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
127
-
128
- chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
129
-
130
- conversational_memory = ConversationBufferWindowMemory(
131
- memory_key='chat_history',
132
- k=10,
133
- return_messages=True
134
- )
135
-
136
- # Prompt templates
137
- def get_current_date():
138
- return datetime.now().strftime("%B %d, %Y")
139
-
140
- current_date = get_current_date()
141
-
142
- 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.
143
- 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.
144
- Now, let me guide you through some of the exciting events happening today in Birmingham, Alabama:
145
- Address: >>, Birmingham, AL
146
- Time: >>__
147
- Date: >>__
148
- Description: >>__
149
- Address: >>, Birmingham, AL
150
- Time: >>__
151
- Date: >>__
152
- Description: >>__
153
- Address: >>, Birmingham, AL
154
- Time: >>__
155
- Date: >>__
156
- Description: >>__
157
- Address: >>, Birmingham, AL
158
- Time: >>__
159
- Date: >>__
160
- Description: >>__
161
- Address: >>, Birmingham, AL
162
- Time: >>__
163
- Date: >>__
164
- Description: >>__
165
- 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.
166
- It was my pleasure!
167
- {{context}}
168
- Question: {{question}}
169
- Helpful Answer:"""
170
-
171
- 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.
172
- 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.
173
- "It was my pleasure!"
174
- {{context}}
175
- Question: {{question}}
176
- Helpful Answer:"""
177
-
178
- QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
179
- QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
180
-
181
- # Neo4j setup
182
- graph = Neo4jGraph(url="neo4j+s://6457770f.databases.neo4j.io",
183
- username="neo4j",
184
- password="Z10duoPkKCtENuOukw3eIlvl0xJWKtrVSr-_hGX1LQ4"
185
- )
186
- # Avoid pushing the graph documents to Neo4j every time
187
- # Only push the documents once and comment the code below after the initial push
188
- # dataset_name = "Pijush2023/birmindata07312024"
189
- # page_content_column = 'events_description'
190
- # loader = HuggingFaceDatasetLoader(dataset_name, page_content_column)
191
- # data = loader.load()
192
-
193
- # text_splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=50)
194
- # documents = text_splitter.split_documents(data)
195
-
196
- # llm_transformer = LLMGraphTransformer(llm=chat_model)
197
- # graph_documents = llm_transformer.convert_to_graph_documents(documents)
198
- # graph.add_graph_documents(graph_documents, baseEntityLabel=True, include_source=True)
199
-
200
- class Entities(BaseModel):
201
- names: list[str] = Field(..., description="All the person, organization, or business entities that appear in the text")
202
-
203
- entity_prompt = ChatPromptTemplate.from_messages([
204
- ("system", "You are extracting organization and person entities from the text."),
205
- ("human", "Use the given format to extract information from the following input: {question}"),
206
- ])
207
-
208
- entity_chain = entity_prompt | chat_model.with_structured_output(Entities)
209
-
210
- def remove_lucene_chars(input: str) -> str:
211
- return input.translate(str.maketrans({"\\": r"\\", "+": r"\+", "-": r"\-", "&": r"\&", "|": r"\|", "!": r"\!",
212
- "(": r"\(", ")": r"\)", "{": r"\{", "}": r"\}", "[": r"\[", "]": r"\]",
213
- "^": r"\^", "~": r"\~", "*": r"\*", "?": r"\?", ":": r"\:", '"': r'\"',
214
- ";": r"\;", " ": r"\ "}))
215
-
216
- def generate_full_text_query(input: str) -> str:
217
- full_text_query = ""
218
- words = [el for el in remove_lucene_chars(input).split() if el]
219
- for word in words[:-1]:
220
- full_text_query += f" {word}~2 AND"
221
- full_text_query += f" {words[-1]}~2"
222
- return full_text_query.strip()
223
-
224
- def structured_retriever(question: str) -> str:
225
- result = ""
226
- entities = entity_chain.invoke({"question": question})
227
- for entity in entities.names:
228
- response = graph.query(
229
- """CALL db.index.fulltext.queryNodes('entity', $query, {limit:2})
230
- YIELD node,score
231
- CALL {
232
- WITH node
233
- MATCH (node)-[r:!MENTIONS]->(neighbor)
234
- RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS output
235
- UNION ALL
236
- WITH node
237
- MATCH (node)<-[r:!MENTIONS]-(neighbor)
238
- RETURN neighbor.id + ' - ' + type(r) + ' -> ' + node.id AS output
239
- }
240
- RETURN output LIMIT 50
241
- """,
242
- {"query": generate_full_text_query(entity)},
243
- )
244
- result += "\n".join([el['output'] for el in response])
245
- return result
246
-
247
- def retriever_neo4j(question: str):
248
- structured_data = structured_retriever(question)
249
- logging.debug(f"Structured data: {structured_data}")
250
- return structured_data
251
-
252
- _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
253
- in its original language.
254
- Chat History:
255
- {chat_history}
256
- Follow Up Input: {question}
257
- Standalone question:"""
258
-
259
- CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
260
-
261
- def _format_chat_history(chat_history: list[tuple[str, str]]) -> list:
262
- buffer = []
263
- for human, ai in chat_history:
264
- buffer.append(HumanMessage(content=human))
265
- buffer.append(AIMessage(content=ai))
266
- return buffer
267
-
268
- _search_query = RunnableBranch(
269
- (
270
- RunnableLambda(lambda x: bool(x.get("chat_history"))).with_config(
271
- run_name="HasChatHistoryCheck"
272
- ),
273
- RunnablePassthrough.assign(
274
- chat_history=lambda x: _format_chat_history(x["chat_history"])
275
- )
276
- | CONDENSE_QUESTION_PROMPT
277
- | ChatOpenAI(temperature=0, api_key=os.environ['OPENAI_API_KEY'])
278
- | StrOutputParser(),
279
- ),
280
- RunnableLambda(lambda x : x["question"]),
281
- )
282
-
283
- # template = """Answer the question based only on the following context:
284
- # {context}
285
- # Question: {question}
286
- # Use natural language and be concise.
287
- # Answer:"""
288
-
289
- 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.
290
- 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.
291
- "It was my pleasure!"
292
- {{context}}
293
- Question: {{question}}
294
- Helpful Answer:"""
295
-
296
- qa_prompt = ChatPromptTemplate.from_template(template)
297
-
298
- chain_neo4j = (
299
- RunnableParallel(
300
- {
301
- "context": _search_query | retriever_neo4j,
302
- "question": RunnablePassthrough(),
303
- }
304
- )
305
- | qa_prompt
306
- | chat_model
307
- | StrOutputParser()
308
- )
309
-
310
- # def bot(history, choice, tts_choice, retrieval_mode, model_choice):
311
- # if not history:
312
- # return history
313
-
314
- # # Select the model
315
- # selected_model = chat_model if model_choice == "GPT-4o" else phi_pipe
316
-
317
- # response, addresses = generate_answer(history[-1][0], choice, retrieval_mode, selected_model)
318
- # history[-1][1] = ""
319
-
320
- # with concurrent.futures.ThreadPoolExecutor() as executor:
321
- # if tts_choice == "Alpha":
322
- # audio_future = executor.submit(generate_audio_elevenlabs, response)
323
- # elif tts_choice == "Beta":
324
- # audio_future = executor.submit(generate_audio_parler_tts, response)
325
- # # elif tts_choice == "Gamma":
326
- # # audio_future = executor.submit(generate_audio_mars5, response)
327
-
328
- # for character in response:
329
- # history[-1][1] += character
330
- # time.sleep(0.05)
331
- # yield history, None
332
-
333
- # audio_path = audio_future.result()
334
- # yield history, audio_path
335
-
336
- # history.append([response, None])
337
-
338
-
339
-
340
- #perfect
341
-
342
-
343
- def bot(history, choice, tts_choice, retrieval_mode, model_choice):
344
- if not history:
345
- return history
346
-
347
- # Select the model
348
- selected_model = chat_model if model_choice == "GPT-4o" else phi_pipe
349
-
350
- response, addresses = generate_answer(history[-1][0], choice, retrieval_mode, selected_model)
351
- history[-1][1] = ""
352
-
353
- with concurrent.futures.ThreadPoolExecutor() as executor:
354
- if tts_choice == "Alpha":
355
- audio_future = executor.submit(generate_audio_elevenlabs, response)
356
- elif tts_choice == "Beta":
357
- audio_future = executor.submit(generate_audio_parler_tts, response)
358
- # elif tts_choice == "Gamma":
359
- # audio_future = executor.submit(generate_audio_mars5, response)
360
-
361
- for character in response:
362
- history[-1][1] += character
363
- time.sleep(0.05)
364
- yield history, None
365
-
366
- audio_path = audio_future.result()
367
- yield history, audio_path
368
-
369
- history.append([response, None])
370
-
371
-
372
- #Bot response withstream and flicker with time
373
-
374
- # def bot(history, choice, tts_choice, retrieval_mode, model_choice):
375
- # if not history:
376
- # return history
377
-
378
- # # Select the model
379
- # selected_model = chat_model if model_choice == "GPT-4o" else phi_pipe
380
-
381
- # response, addresses = generate_answer(history[-1][0], choice, retrieval_mode, selected_model)
382
- # history[-1][1] = response # Set the full response in the history immediately
383
-
384
- # with concurrent.futures.ThreadPoolExecutor() as executor:
385
- # if tts_choice == "Alpha":
386
- # audio_stream = generate_audio_elevenlabs(response)
387
- # elif tts_choice == "Beta":
388
- # audio_stream = generate_audio_parler_tts(response)
389
-
390
- # # Stream audio chunks in real-time without interrupting text output
391
- # for audio_chunk_path in audio_stream:
392
- # yield history, audio_chunk_path # Yield audio chunks as they are generated
393
-
394
- # history.append([response, None])
395
-
396
-
397
-
398
-
399
-
400
- phi_custom_template = """
401
- <|system|>
402
- 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|>
403
- <|user|>
404
- {context}
405
- Question: {question}<|end|>
406
- <|assistant|>
407
- Sure! Here's the information you requested:
408
- """
409
-
410
-
411
-
412
- import re
413
-
414
- def clean_response(response_text):
415
- # Remove system and user tags
416
- response_text = re.sub(r'<\|system\|>.*?<\|end\|>', '', response_text, flags=re.DOTALL)
417
- response_text = re.sub(r'<\|user\|>.*?<\|end\|>', '', response_text, flags=re.DOTALL)
418
- response_text = re.sub(r'<\|assistant\|>', '', response_text, flags=re.DOTALL)
419
-
420
- # Clean up the text by removing extra whitespace
421
- cleaned_response = response_text.strip()
422
- cleaned_response = re.sub(r'\s+', ' ', cleaned_response)
423
-
424
- # Ensure the response is conversational and organized
425
- cleaned_response = cleaned_response.replace('1.', '\n1.').replace('2.', '\n2.').replace('3.', '\n3.').replace('4.', '\n4.').replace('5.', '\n5.')
426
-
427
- return cleaned_response
428
-
429
-
430
-
431
-
432
- import traceback
433
- def generate_answer(message, choice, retrieval_mode, selected_model):
434
- logging.debug(f"generate_answer called with choice: {choice}, retrieval_mode: {retrieval_mode}, and selected_model: {selected_model}")
435
-
436
- # Logic for disabling options for Phi-3.5
437
- if selected_model == "Phi-3.5":
438
- choice = None
439
- retrieval_mode = None
440
-
441
- try:
442
- # Handle hotel-related queries
443
- if "hotel" in message.lower() or "hotels" in message.lower() and "birmingham" in message.lower():
444
- logging.debug("Handling hotel-related query")
445
- response = fetch_google_hotels()
446
- logging.debug(f"Hotel response: {response}")
447
- return response, extract_addresses(response)
448
-
449
- # Handle restaurant-related queries
450
- if "restaurant" in message.lower() or "restaurants" in message.lower() and "birmingham" in message.lower():
451
- logging.debug("Handling restaurant-related query")
452
- response = fetch_yelp_restaurants()
453
- logging.debug(f"Restaurant response: {response}")
454
- return response, extract_addresses(response)
455
-
456
- # Handle flight-related queries
457
- if "flight" in message.lower() or "flights" in message.lower() and "birmingham" in message.lower():
458
- logging.debug("Handling flight-related query")
459
- response = fetch_google_flights()
460
- logging.debug(f"Flight response: {response}")
461
- return response, extract_addresses(response)
462
-
463
- # Retrieval-based response
464
- if retrieval_mode == "VDB":
465
- logging.debug("Using VDB retrieval mode")
466
- if selected_model == chat_model:
467
- logging.debug("Selected model: GPT-4o")
468
- retriever = gpt_retriever
469
- prompt_template = QA_CHAIN_PROMPT_1 if choice == "Details" else QA_CHAIN_PROMPT_2
470
- context = retriever.get_relevant_documents(message)
471
- logging.debug(f"Retrieved context: {context}")
472
-
473
- prompt = prompt_template.format(context=context, question=message)
474
- logging.debug(f"Generated prompt: {prompt}")
475
-
476
- qa_chain = RetrievalQA.from_chain_type(
477
- llm=chat_model,
478
- chain_type="stuff",
479
- retriever=retriever,
480
- chain_type_kwargs={"prompt": prompt_template}
481
- )
482
- response = qa_chain({"query": message})
483
- logging.debug(f"GPT-4o response: {response}")
484
- return response['result'], extract_addresses(response['result'])
485
-
486
- elif selected_model == phi_pipe:
487
- logging.debug("Selected model: Phi-3.5")
488
- retriever = phi_retriever
489
- context_documents = retriever.get_relevant_documents(message)
490
- context = "\n".join([doc.page_content for doc in context_documents])
491
- logging.debug(f"Retrieved context for Phi-3.5: {context}")
492
-
493
- # Use the correct template variable
494
- prompt = phi_custom_template.format(context=context, question=message)
495
- logging.debug(f"Generated Phi-3.5 prompt: {prompt}")
496
-
497
- response = selected_model(prompt, **{
498
- "max_new_tokens": 400,
499
- "return_full_text": True,
500
- "temperature": 0.7,
501
- "do_sample": True,
502
- })
503
-
504
- if response:
505
- generated_text = response[0]['generated_text']
506
- logging.debug(f"Phi-3.5 Response: {generated_text}")
507
- cleaned_response = clean_response(generated_text)
508
- return cleaned_response, extract_addresses(cleaned_response)
509
- else:
510
- logging.error("Phi-3.5 did not return any response.")
511
- return "No response generated.", []
512
-
513
- elif retrieval_mode == "KGF":
514
- logging.debug("Using KGF retrieval mode")
515
- response = chain_neo4j.invoke({"question": message})
516
- logging.debug(f"KGF response: {response}")
517
- return response, extract_addresses(response)
518
- else:
519
- logging.error("Invalid retrieval mode selected.")
520
- return "Invalid retrieval mode selected.", []
521
-
522
- except Exception as e:
523
- logging.error(f"Error in generate_answer: {str(e)}")
524
- logging.error(traceback.format_exc())
525
- return "Sorry, I encountered an error while processing your request.", []
526
-
527
- def handle_retrieval_mode_change(choice):
528
- if choice == "KGF":
529
- return gr.update(interactive=False), gr.update(interactive=False)
530
- else:
531
- return gr.update(interactive=True), gr.update(interactive=True)
532
-
533
-
534
-
535
-
536
- def add_message(history, message):
537
- history.append((message, None))
538
- return history, gr.Textbox(value="", interactive=True, show_label=False)
539
-
540
- def print_like_dislike(x: gr.LikeData):
541
- print(x.index, x.value, x.liked)
542
-
543
- def extract_addresses(response):
544
- if not isinstance(response, str):
545
- response = str(response)
546
- address_patterns = [
547
- r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
548
- r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
549
- r'([A-Z].*,\sAL\s\d{5})',
550
- r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
551
- r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
552
- r'(\d{2}.*\sStreets)',
553
- r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
554
- r'([a-zA-Z]\s Birmingham)',
555
- r'([a-zA-Z].*,\sBirmingham,\sAL)',
556
- r'(.*),(Birmingham, AL,USA)$'
557
- r'(^Birmingham,AL$)',
558
- r'((.*)(Stadium|Field),.*,\sAL$)',
559
- r'((.*)(Stadium|Field),.*,\sFL$)',
560
- r'((.*)(Stadium|Field),.*,\sMS$)',
561
- r'((.*)(Stadium|Field),.*,\sAR$)',
562
- r'((.*)(Stadium|Field),.*,\sKY$)',
563
- r'((.*)(Stadium|Field),.*,\sTN$)',
564
- r'((.*)(Stadium|Field),.*,\sLA$)',
565
- r'((.*)(Stadium|Field),.*,\sFL$)'
566
-
567
- ]
568
- addresses = []
569
- for pattern in address_patterns:
570
- addresses.extend(re.findall(pattern, response))
571
- return addresses
572
-
573
- all_addresses = []
574
-
575
- def generate_map(location_names):
576
- global all_addresses
577
- all_addresses.extend(location_names)
578
-
579
- api_key = os.environ['GOOGLEMAPS_API_KEY']
580
- gmaps = GoogleMapsClient(key=api_key)
581
-
582
- m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
583
-
584
- for location_name in all_addresses:
585
- geocode_result = gmaps.geocode(location_name)
586
- if geocode_result:
587
- location = geocode_result[0]['geometry']['location']
588
- folium.Marker(
589
- [location['lat'], location['lng']],
590
- tooltip=f"{geocode_result[0]['formatted_address']}"
591
- ).add_to(m)
592
-
593
- map_html = m._repr_html_()
594
- return map_html
595
-
596
-
597
- def fetch_local_news():
598
- api_key = os.environ['SERP_API']
599
- url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
600
- response = requests.get(url)
601
- if response.status_code == 200:
602
- results = response.json().get("news_results", [])
603
- news_html = """
604
- <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
605
- <style>
606
- .news-item {
607
- font-family: 'Verdana', sans-serif;
608
- color: #333;
609
- background-color: #f0f8ff;
610
- margin-bottom: 15px;
611
- padding: 10px;
612
- border-radius: 5px;
613
- transition: box-shadow 0.3s ease, background-color 0.3s ease;
614
- font-weight: bold;
615
- }
616
- .news-item:hover {
617
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
618
- background-color: #e6f7ff;
619
- }
620
- .news-item a {
621
- color: #1E90FF;
622
- text-decoration: none;
623
- font-weight: bold;
624
- }
625
- .news-item a:hover {
626
- text-decoration: underline;
627
- }
628
- .news-preview {
629
- position: absolute;
630
- display: none;
631
- border: 1px solid #ccc;
632
- border-radius: 5px;
633
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
634
- background-color: white;
635
- z-index: 1000;
636
- max-width: 300px;
637
- padding: 10px;
638
- font-family: 'Verdana', sans-serif;
639
- color: #333;
640
- }
641
- </style>
642
- <script>
643
- function showPreview(event, previewContent) {
644
- var previewBox = document.getElementById('news-preview');
645
- previewBox.innerHTML = previewContent;
646
- previewBox.style.left = event.pageX + 'px';
647
- previewBox.style.top = event.pageY + 'px';
648
- previewBox.style.display = 'block';
649
- }
650
- function hidePreview() {
651
- var previewBox = document.getElementById('news-preview');
652
- previewBox.style.display = 'none';
653
- }
654
- </script>
655
- <div id="news-preview" class="news-preview"></div>
656
- """
657
- for index, result in enumerate(results[:7]):
658
- title = result.get("title", "No title")
659
- link = result.get("link", "#")
660
- snippet = result.get("snippet", "")
661
- news_html += f"""
662
- <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
663
- <a href='{link}' target='_blank'>{index + 1}. {title}</a>
664
- <p>{snippet}</p>
665
- </div>
666
- """
667
- return news_html
668
- else:
669
- return "<p>Failed to fetch local news</p>"
670
-
671
- import numpy as np
672
- import torch
673
- from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
674
-
675
- model_id = 'openai/whisper-large-v3'
676
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
677
- torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
678
- model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
679
- processor = AutoProcessor.from_pretrained(model_id)
680
-
681
- 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)
682
-
683
- base_audio_drive = "/data/audio"
684
-
685
- #Normal Code with sample rate is 44100 Hz
686
-
687
- def transcribe_function(stream, new_chunk):
688
- try:
689
- sr, y = new_chunk[0], new_chunk[1]
690
- except TypeError:
691
- print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
692
- return stream, "", None
693
-
694
- y = y.astype(np.float32) / np.max(np.abs(y))
695
-
696
- if stream is not None:
697
- stream = np.concatenate([stream, y])
698
- else:
699
- stream = y
700
-
701
- result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
702
-
703
- full_text = result.get("text","")
704
-
705
- return stream, full_text, result
706
-
707
-
708
-
709
-
710
-
711
-
712
-
713
- def update_map_with_response(history):
714
- if not history:
715
- return ""
716
- response = history[-1][1]
717
- addresses = extract_addresses(response)
718
- return generate_map(addresses)
719
-
720
- def clear_textbox():
721
- return ""
722
-
723
- def show_map_if_details(history, choice):
724
- if choice in ["Details", "Conversational"]:
725
- return gr.update(visible=True), update_map_with_response(history)
726
- else:
727
- return gr.update(visible(False), "")
728
-
729
-
730
-
731
-
732
-
733
-
734
-
735
-
736
- def generate_audio_elevenlabs(text):
737
- XI_API_KEY = os.environ['ELEVENLABS_API']
738
- VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
739
- tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
740
- headers = {
741
- "Accept": "application/json",
742
- "xi-api-key": XI_API_KEY
743
- }
744
- data = {
745
- "text": str(text),
746
- "model_id": "eleven_multilingual_v2",
747
- "voice_settings": {
748
- "stability": 1.0,
749
- "similarity_boost": 0.0,
750
- "style": 0.60,
751
- "use_speaker_boost": False
752
- }
753
- }
754
- response = requests.post(tts_url, headers=headers, json=data, stream=True)
755
- if response.ok:
756
- audio_segments = []
757
- with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
758
- for chunk in response.iter_content(chunk_size=1024):
759
- if chunk:
760
- f.write(chunk)
761
- audio_segments.append(chunk)
762
- temp_audio_path = f.name
763
-
764
- # Combine all audio chunks into a single file
765
- combined_audio = AudioSegment.from_file(temp_audio_path, format="mp3")
766
- combined_audio_path = os.path.join(tempfile.gettempdir(), "elevenlabs_combined_audio.mp3")
767
- combined_audio.export(combined_audio_path, format="mp3")
768
-
769
- logging.debug(f"Audio saved to {combined_audio_path}")
770
- return combined_audio_path
771
- else:
772
- logging.error(f"Error generating audio: {response.text}")
773
- return None
774
-
775
-
776
- #Normal cases
777
-
778
- # from parler_tts import ParlerTTSForConditionalGeneration, ParlerTTSStreamer
779
- # from transformers import AutoTokenizer
780
- # from threading import Thread
781
-
782
- # repo_id = "parler-tts/parler-tts-mini-v1"
783
-
784
-
785
-
786
-
787
- # def generate_audio_parler_tts(text):
788
- # description = "A female speaker delivers a slightly expressive and animated speech with a moderate speed and pitch. The recording is of very high quality, with the speaker's voice sounding clear and very close up."
789
- # chunk_size_in_s = 0.5
790
-
791
- # # Initialize the tokenizer and model
792
- # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
793
- # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
794
- # sampling_rate = parler_model.audio_encoder.config.sampling_rate
795
- # frame_rate = parler_model.audio_encoder.config.frame_rate
796
-
797
- # def generate(text, description, play_steps_in_s=0.5):
798
- # play_steps = int(frame_rate * play_steps_in_s)
799
- # streamer = ParlerTTSStreamer(parler_model, device=device, play_steps=play_steps)
800
-
801
- # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
802
- # prompt = parler_tokenizer(text, return_tensors="pt").to(device)
803
-
804
- # generation_kwargs = dict(
805
- # input_ids=inputs.input_ids,
806
- # prompt_input_ids=prompt.input_ids,
807
- # attention_mask=inputs.attention_mask,
808
- # prompt_attention_mask=prompt.attention_mask,
809
- # streamer=streamer,
810
- # do_sample=True,
811
- # temperature=1.0,
812
- # min_new_tokens=10,
813
- # )
814
-
815
- # thread = Thread(target=parler_model.generate, kwargs=generation_kwargs)
816
- # thread.start()
817
-
818
- # for new_audio in streamer:
819
- # if new_audio.shape[0] == 0:
820
- # break
821
- # # Save or process each audio chunk as it is generated
822
- # yield sampling_rate, new_audio
823
-
824
- # audio_segments = []
825
- # for (sampling_rate, audio_chunk) in generate(text, description, chunk_size_in_s):
826
- # audio_segments.append(audio_chunk)
827
-
828
- # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_chunk_{len(audio_segments)}.wav")
829
- # write_wav(temp_audio_path, sampling_rate, audio_chunk.astype(np.float32))
830
- # logging.debug(f"Saved chunk to {temp_audio_path}")
831
-
832
-
833
- # # Combine all the audio chunks into one audio file
834
- # combined_audio = np.concatenate(audio_segments)
835
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio_stream.wav")
836
-
837
- # write_wav(combined_audio_path, sampling_rate, combined_audio.astype(np.float32))
838
-
839
- # logging.debug(f"Combined audio saved to {combined_audio_path}")
840
- # return combined_audio_path
841
-
842
-
843
- # chunking audio and then Process
844
-
845
- import concurrent.futures
846
- import tempfile
847
- import os
848
- import numpy as np
849
- import logging
850
- from queue import Queue
851
- from threading import Thread
852
- from scipy.io.wavfile import write as write_wav
853
- from parler_tts import ParlerTTSForConditionalGeneration, ParlerTTSStreamer
854
- from transformers import AutoTokenizer
855
-
856
- # Ensure your device is set to CUDA
857
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
858
-
859
- repo_id = "parler-tts/parler-tts-mini-v1"
860
-
861
- def generate_audio_parler_tts(text):
862
- description = "A female speaker delivers a slightly expressive and animated speech with a moderate speed and pitch. The recording is of very high quality, with the speaker's voice sounding clear and very close up."
863
- chunk_size_in_s = 0.5
864
-
865
- # Initialize the tokenizer and model
866
- parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
867
- parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
868
- sampling_rate = parler_model.audio_encoder.config.sampling_rate
869
- frame_rate = parler_model.audio_encoder.config.frame_rate
870
-
871
- def generate(text, description, play_steps_in_s=0.5):
872
- play_steps = int(frame_rate * play_steps_in_s)
873
- streamer = ParlerTTSStreamer(parler_model, device=device, play_steps=play_steps)
874
-
875
- inputs = parler_tokenizer(description, return_tensors="pt").to(device)
876
- prompt = parler_tokenizer(text, return_tensors="pt").to(device)
877
-
878
- generation_kwargs = dict(
879
- input_ids=inputs.input_ids,
880
- prompt_input_ids=prompt.input_ids,
881
- attention_mask=inputs.attention_mask,
882
- prompt_attention_mask=prompt.attention_mask,
883
- streamer=streamer,
884
- do_sample=True,
885
- temperature=1.0,
886
- min_new_tokens=10,
887
- )
888
-
889
- thread = Thread(target=parler_model.generate, kwargs=generation_kwargs)
890
- thread.start()
891
-
892
- for new_audio in streamer:
893
- if new_audio.shape[0] == 0:
894
- break
895
- # Save or process each audio chunk as it is generated
896
- yield sampling_rate, new_audio
897
-
898
- audio_segments = []
899
- for (sampling_rate, audio_chunk) in generate(text, description, chunk_size_in_s):
900
- audio_segments.append(audio_chunk)
901
-
902
- temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_chunk_{len(audio_segments)}.wav")
903
- write_wav(temp_audio_path, sampling_rate, audio_chunk.astype(np.float32))
904
- logging.debug(f"Saved chunk to {temp_audio_path}")
905
-
906
-
907
- # Combine all the audio chunks into one audio file
908
- combined_audio = np.concatenate(audio_segments)
909
- combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio_stream.wav")
910
-
911
- write_wav(combined_audio_path, sampling_rate, combined_audio.astype(np.float32))
912
-
913
- logging.debug(f"Combined audio saved to {combined_audio_path}")
914
- return combined_audio_path
915
-
916
-
917
- # #streaming code in chunk
918
-
919
-
920
- # import concurrent.futures
921
- # import tempfile
922
- # import os
923
- # import numpy as np
924
- # import logging
925
- # from queue import Queue
926
- # from threading import Thread
927
- # from scipy.io.wavfile import write as write_wav
928
- # from transformers import AutoTokenizer
929
- # from parler_tts import ParlerTTSForConditionalGeneration, ParlerTTSStreamer
930
-
931
- # # Ensure your device is set to CUDA
932
- # device = "cuda:0" if torch.cuda.is_available() else "cpu"
933
-
934
- # repo_id = "parler-tts/parler-tts-mini-v1"
935
-
936
- # def generate_audio_parler_tts(text):
937
- # description = "A female speaker delivers a slightly expressive and animated speech with a moderate speed and pitch. The recording is of very high quality, with the speaker's voice sounding clear and very close up."
938
- # chunk_size_in_s = 0.5
939
-
940
- # # Initialize the tokenizer and model
941
- # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
942
- # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
943
- # sampling_rate = parler_model.audio_encoder.config.sampling_rate
944
- # frame_rate = parler_model.audio_encoder.config.frame_rate
945
-
946
- # def generate(text, description, play_steps_in_s=0.5):
947
- # play_steps = int(frame_rate * play_steps_in_s)
948
- # streamer = ParlerTTSStreamer(parler_model, device=device, play_steps=play_steps)
949
-
950
- # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
951
- # prompt = parler_tokenizer(text, return_tensors="pt").to(device)
952
-
953
- # generation_kwargs = dict(
954
- # input_ids=inputs.input_ids,
955
- # prompt_input_ids=prompt.input_ids,
956
- # attention_mask=inputs.attention_mask,
957
- # prompt_attention_mask=prompt.attention_mask,
958
- # streamer=streamer,
959
- # do_sample=True,
960
- # temperature=1.0,
961
- # min_new_tokens=10,
962
- # )
963
-
964
- # thread = Thread(target=parler_model.generate, kwargs=generation_kwargs)
965
- # thread.start()
966
-
967
- # for new_audio in streamer:
968
- # if new_audio.shape[0] == 0:
969
- # break
970
- # # Save each audio chunk as it is generated
971
- # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_chunk_{len(audio_segments)}.wav")
972
- # write_wav(temp_audio_path, sampling_rate, new_audio.astype(np.float32))
973
- # yield temp_audio_path
974
-
975
- # audio_segments = []
976
- # for audio_chunk_path in generate(text, description, chunk_size_in_s):
977
- # audio_segments.append(audio_chunk_path)
978
- # yield audio_chunk_path # Yield each audio chunk path immediately
979
-
980
- # # Combine all the audio chunks into one audio file
981
- # combined_audio = np.concatenate(audio_segments)
982
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio_stream.wav")
983
- # write_wav(combined_audio_path, sampling_rate, combined_audio.astype(np.float32))
984
-
985
- # logging.debug(f"Combined audio saved to {combined_audio_path}")
986
-
987
-
988
-
989
-
990
-
991
-
992
-
993
-
994
-
995
-
996
- def fetch_local_events():
997
- api_key = os.environ['SERP_API']
998
- url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
999
- response = requests.get(url)
1000
- if response.status_code == 200:
1001
- events_results = response.json().get("events_results", [])
1002
- events_html = """
1003
- <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
1004
- <style>
1005
- table {
1006
- font-family: 'Verdana', sans-serif;
1007
- color: #333;
1008
- border-collapse: collapse;
1009
- width: 100%;
1010
- }
1011
- th, td {
1012
- border: 1px solid #fff !important;
1013
- padding: 8px;
1014
- }
1015
- th {
1016
- background-color: #f2f2f2;
1017
- color: #333;
1018
- text-align: left;
1019
- }
1020
- tr:hover {
1021
- background-color: #f5f5f5;
1022
- }
1023
- .event-link {
1024
- color: #1E90FF;
1025
- text-decoration: none;
1026
- }
1027
- .event-link:hover {
1028
- text-decoration: underline;
1029
- }
1030
- </style>
1031
- <table>
1032
- <tr>
1033
- <th>Title</th>
1034
- <th>Date and Time</th>
1035
- <th>Location</th>
1036
- </tr>
1037
- """
1038
- for event in events_results:
1039
- title = event.get("title", "No title")
1040
- date_info = event.get("date", {})
1041
- date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
1042
- location = event.get("address", "No location")
1043
- if isinstance(location, list):
1044
- location = " ".join(location)
1045
- location = location.replace("[", "").replace("]", "")
1046
- link = event.get("link", "#")
1047
- events_html += f"""
1048
- <tr>
1049
- <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
1050
- <td>{date}</td>
1051
- <td>{location}</td>
1052
- </tr>
1053
- """
1054
- events_html += "</table>"
1055
- return events_html
1056
- else:
1057
- return "<p>Failed to fetch local events</p>"
1058
-
1059
- def get_weather_icon(condition):
1060
- condition_map = {
1061
- "Clear": "c01d",
1062
- "Partly Cloudy": "c02d",
1063
- "Cloudy": "c03d",
1064
- "Overcast": "c04d",
1065
- "Mist": "a01d",
1066
- "Patchy rain possible": "r01d",
1067
- "Light rain": "r02d",
1068
- "Moderate rain": "r03d",
1069
- "Heavy rain": "r04d",
1070
- "Snow": "s01d",
1071
- "Thunderstorm": "t01d",
1072
- "Fog": "a05d",
1073
- }
1074
- return condition_map.get(condition, "c04d")
1075
-
1076
- def fetch_local_weather():
1077
- try:
1078
- api_key = os.environ['WEATHER_API']
1079
- url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
1080
- response = requests.get(url)
1081
- response.raise_for_status()
1082
- jsonData = response.json()
1083
-
1084
- current_conditions = jsonData.get("currentConditions", {})
1085
- temp_celsius = current_conditions.get("temp", "N/A")
1086
-
1087
- if temp_celsius != "N/A":
1088
- temp_fahrenheit = int((temp_celsius * 9/5) + 32)
1089
- else:
1090
- temp_fahrenheit = "N/A"
1091
-
1092
- condition = current_conditions.get("conditions", "N/A")
1093
- humidity = current_conditions.get("humidity", "N/A")
1094
-
1095
- weather_html = f"""
1096
- <div class="weather-theme">
1097
- <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
1098
- <div class="weather-content">
1099
- <div class="weather-icon">
1100
- <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
1101
- </div>
1102
- <div class="weather-details">
1103
- <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
1104
- <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
1105
- <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
1106
- </div>
1107
- </div>
1108
- </div>
1109
- <style>
1110
- .weather-theme {{
1111
- animation: backgroundAnimation 10s infinite alternate;
1112
- border-radius: 10px;
1113
- padding: 10px;
1114
- margin-bottom: 15px;
1115
- background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
1116
- background-size: 400% 400%;
1117
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
1118
- transition: box-shadow 0.3s ease, background-color 0.3s ease;
1119
- }}
1120
- .weather-theme:hover {{
1121
- box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
1122
- background-position: 100% 100%;
1123
- }}
1124
- @keyframes backgroundAnimation {{
1125
- 0% {{ background-position: 0% 50%; }}
1126
- 100% {{ background-position: 100% 50%; }}
1127
- }}
1128
- .weather-content {{
1129
- display: flex;
1130
- align-items: center;
1131
- }}
1132
- .weather-icon {{
1133
- flex: 1;
1134
- }}
1135
- .weather-details {{
1136
- flex 3;
1137
- }}
1138
- </style>
1139
- """
1140
- return weather_html
1141
- except requests.exceptions.RequestException as e:
1142
- return f"<p>Failed to fetch local weather: {e}</p>"
1143
-
1144
-
1145
- def handle_retrieval_mode_change(choice):
1146
- if choice == "KGF":
1147
- return gr.update(interactive=False), gr.update(interactive=False)
1148
- else:
1149
- return gr.update(interactive=True), gr.update(interactive=True)
1150
-
1151
- def handle_model_choice_change(selected_model):
1152
- if selected_model == "Phi-3.5":
1153
- # Disable retrieval mode and select style when Phi-3.5 is selected
1154
- return gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False)
1155
- elif selected_model == "GPT-4o":
1156
- # Enable retrieval mode and select style for GPT-4o
1157
- return gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True)
1158
- else:
1159
- # Default case: allow interaction
1160
- return gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True)
1161
-
1162
-
1163
-
1164
-
1165
- def format_restaurant_hotel_info(name, link, location, phone, rating, reviews, snippet):
1166
- return f"""
1167
- {name}
1168
- - Link: {link}
1169
- - Location: {location}
1170
- - Contact No: {phone}
1171
- - Rating: {rating} stars ({reviews} reviews)
1172
- - Snippet: {snippet}
1173
- """
1174
-
1175
- def fetch_yelp_restaurants():
1176
- # Introductory prompt for restaurants
1177
- intro_prompt = "Here are some of the top-rated restaurants in Birmingham, Alabama. I hope these suggestions help you find the perfect place to enjoy your meal:"
1178
-
1179
- params = {
1180
- "engine": "yelp",
1181
- "find_desc": "Restaurant",
1182
- "find_loc": "Birmingham, AL, USA",
1183
- "api_key": os.getenv("SERP_API")
1184
- }
1185
-
1186
- search = GoogleSearch(params)
1187
- results = search.get_dict()
1188
- organic_results = results.get("organic_results", [])
1189
-
1190
- response_text = f"{intro_prompt}\n"
1191
-
1192
- for result in organic_results[:5]: # Limiting to top 5 restaurants
1193
- name = result.get("title", "No name")
1194
- rating = result.get("rating", "No rating")
1195
- reviews = result.get("reviews", "No reviews")
1196
- phone = result.get("phone", "Not Available")
1197
- snippet = result.get("snippet", "Not Available")
1198
- location = f"{name}, Birmingham, AL,USA"
1199
- link = result.get("link", "#")
1200
-
1201
- response_text += format_restaurant_hotel_info(name, link, location, phone, rating, reviews, snippet)
1202
-
1203
-
1204
- return response_text
1205
-
1206
-
1207
-
1208
-
1209
-
1210
-
1211
- def format_hotel_info(name, link, location, rate_per_night, total_rate, description, check_in_time, check_out_time, amenities):
1212
- return f"""
1213
- {name}
1214
- - Link: {link}
1215
- - Location: {location}
1216
- - Rate per Night: {rate_per_night} (Before taxes/fees: {total_rate})
1217
- - Check-in Time: {check_in_time}
1218
- - Check-out Time: {check_out_time}
1219
- - Amenities: {amenities}
1220
- - Description: {description}
1221
- """
1222
-
1223
- def fetch_google_hotels(query="Birmingham Hotel", check_in=current_date1, check_out="2024-09-02", adults=2):
1224
- # Introductory prompt for hotels
1225
- intro_prompt = "Here are some of the best hotels in Birmingham, Alabama, for your stay. Each of these options offers a unique experience, whether you're looking for luxury, comfort, or convenience:"
1226
-
1227
- params = {
1228
- "engine": "google_hotels",
1229
- "q": query,
1230
- "check_in_date": check_in,
1231
- "check_out_date": check_out,
1232
- "adults": str(adults),
1233
- "currency": "USD",
1234
- "gl": "us",
1235
- "hl": "en",
1236
- "api_key": os.getenv("SERP_API")
1237
- }
1238
-
1239
- search = GoogleSearch(params)
1240
- results = search.get_dict()
1241
- hotel_results = results.get("properties", [])
1242
-
1243
- hotel_info = f"{intro_prompt}\n"
1244
- for hotel in hotel_results[:5]: # Limiting to top 5 hotels
1245
- name = hotel.get('name', 'No name')
1246
- description = hotel.get('description', 'No description')
1247
- link = hotel.get('link', '#')
1248
- check_in_time = hotel.get('check_in_time', 'N/A')
1249
- check_out_time = hotel.get('check_out_time', 'N/A')
1250
- rate_per_night = hotel.get('rate_per_night', {}).get('lowest', 'N/A')
1251
- before_taxes_fees = hotel.get('rate_per_night', {}).get('before_taxes_fees', 'N/A')
1252
- total_rate = hotel.get('total_rate', {}).get('lowest', 'N/A')
1253
- amenities = ", ".join(hotel.get('amenities', [])) if hotel.get('amenities') else "Not Available"
1254
-
1255
- location = f"{name}, Birmingham, AL,USA"
1256
-
1257
- hotel_info += format_hotel_info(
1258
- name,
1259
- link,
1260
- location,
1261
- rate_per_night,
1262
- total_rate,
1263
- description,
1264
- check_in_time,
1265
- check_out_time,
1266
- amenities
1267
- )
1268
-
1269
-
1270
- return hotel_info
1271
-
1272
-
1273
-
1274
-
1275
- def format_flight_info(flight_number, departure_airport, departure_time, arrival_airport, arrival_time, duration, airplane):
1276
- return f"""
1277
- Flight {flight_number}
1278
- - Departure: {departure_airport} at {departure_time}
1279
- - Arrival: {arrival_airport} at {arrival_time}
1280
- - Duration: {duration} minutes
1281
- - Airplane: {airplane}
1282
- """
1283
-
1284
- def fetch_google_flights(departure_id="JFK", arrival_id="BHM", outbound_date=current_date1, return_date="2024-08-20"):
1285
- # Introductory prompt for flights
1286
- intro_prompt = "Here are some available flights from JFK to Birmingham, Alabama. These options provide a range of times and durations to fit your travel needs:"
1287
-
1288
- params = {
1289
- "engine": "google_flights",
1290
- "departure_id": departure_id,
1291
- "arrival_id": arrival_id,
1292
- "outbound_date": outbound_date,
1293
- "return_date": return_date,
1294
- "currency": "USD",
1295
- "hl": "en",
1296
- "api_key": os.getenv("SERP_API")
1297
- }
1298
-
1299
- search = GoogleSearch(params)
1300
- results = search.get_dict()
1301
-
1302
- # Extract flight details from the results
1303
- best_flights = results.get('best_flights', [])
1304
- flight_info = f"{intro_prompt}\n"
1305
-
1306
- # Process each flight in the best_flights list
1307
- for i, flight in enumerate(best_flights, start=1):
1308
- for segment in flight.get('flights', []):
1309
- departure_airport = segment.get('departure_airport', {}).get('name', 'Unknown Departure Airport')
1310
- departure_time = segment.get('departure_airport', {}).get('time', 'Unknown Time')
1311
- arrival_airport = segment.get('arrival_airport', {}).get('name', 'Unknown Arrival Airport')
1312
- arrival_time = segment.get('arrival_airport', {}).get('time', 'Unknown Time')
1313
- duration = segment.get('duration', 'Unknown Duration')
1314
- airplane = segment.get('airplane', 'Unknown Airplane')
1315
-
1316
- # Format the flight segment details
1317
- flight_info += format_flight_info(
1318
- flight_number=i,
1319
- departure_airport=departure_airport,
1320
- departure_time=departure_time,
1321
- arrival_airport=arrival_airport,
1322
- arrival_time=arrival_time,
1323
- duration=duration,
1324
- airplane=airplane
1325
- )
1326
-
1327
-
1328
- return flight_info
1329
-
1330
-
1331
-
1332
-
1333
- with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1334
- with gr.Row():
1335
- with gr.Column():
1336
- state = gr.State()
1337
-
1338
- chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
1339
- choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
1340
- retrieval_mode = gr.Radio(label="Retrieval Mode", choices=["VDB", "KGF"], value="VDB")
1341
- model_choice = gr.Dropdown(label="Choose Model", choices=["GPT-4o", "Phi-3.5"], value="GPT-4o")
1342
-
1343
- # Link the dropdown change to handle_model_choice_change
1344
- model_choice.change(fn=handle_model_choice_change, inputs=model_choice, outputs=[retrieval_mode, choice, choice])
1345
-
1346
- gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
1347
-
1348
- chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!", placeholder="Hey Radar...!!")
1349
- tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta"], value="Alpha")
1350
- retriever_button = gr.Button("Retriever")
1351
-
1352
- clear_button = gr.Button("Clear")
1353
- clear_button.click(lambda: [None, None], outputs=[chat_input, state])
1354
-
1355
- gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
1356
- location_output = gr.HTML()
1357
- audio_output = gr.Audio(interactive=False, autoplay=True)
1358
-
1359
- def stop_audio():
1360
- audio_output.stop()
1361
- return None
1362
-
1363
- retriever_sequence = (
1364
- retriever_button.click(fn=stop_audio, inputs=[], outputs=[audio_output], api_name="Ask_Retriever")
1365
- .then(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input], api_name="voice_query")
1366
- .then(fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode, model_choice], outputs=[chatbot, audio_output], api_name="generate_voice_response")
1367
- .then(fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder")
1368
- .then(fn=clear_textbox, inputs=[], outputs=[chat_input])
1369
- )
1370
-
1371
- chat_input.submit(fn=stop_audio, inputs=[], outputs=[audio_output])
1372
- chat_input.submit(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input], api_name="voice_query").then(
1373
- fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode, model_choice], outputs=[chatbot, audio_output], api_name="generate_voice_response"
1374
- ).then(
1375
- fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder"
1376
- ).then(
1377
- fn=clear_textbox, inputs=[], outputs=[chat_input]
1378
- )
1379
-
1380
- audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy', every=0.1)
1381
- audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
1382
-
1383
- # with gr.Column():
1384
- # weather_output = gr.HTML(value=fetch_local_weather())
1385
- # news_output = gr.HTML(value=fetch_local_news())
1386
- # events_output = gr.HTML(value=fetch_local_events())
1387
-
1388
- demo.queue()
1389
- demo.launch(share=True)