Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -118,23 +118,14 @@ gpt4o_mini_model = initialize_gpt4o_mini_model()
|
|
118 |
|
119 |
|
120 |
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
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="
|
133 |
gpt_retriever = gpt_vectorstore.as_retriever(search_kwargs={'k': 5})
|
134 |
|
135 |
# New vector store setup for Phi-3.5
|
136 |
phi_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
|
137 |
-
phi_vectorstore = PineconeVectorStore(index_name="
|
138 |
phi_retriever = phi_vectorstore.as_retriever(search_kwargs={'k': 5})
|
139 |
|
140 |
|
@@ -158,10 +149,10 @@ conversational_memory = ConversationBufferWindowMemory(
|
|
158 |
)
|
159 |
|
160 |
# Prompt templates
|
161 |
-
def get_current_date():
|
162 |
-
|
163 |
|
164 |
-
current_date = get_current_date()
|
165 |
|
166 |
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.
|
167 |
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.
|
@@ -192,15 +183,6 @@ It was my pleasure!
|
|
192 |
Question: {{question}}
|
193 |
Helpful Answer:"""
|
194 |
|
195 |
-
# 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.
|
196 |
-
# 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.
|
197 |
-
# "It was my pleasure!"
|
198 |
-
# {{context}}
|
199 |
-
# Question: {{question}}
|
200 |
-
# Helpful Answer:"""
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
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.
|
205 |
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!
|
206 |
"It’s always a pleasure to assist you!"
|
@@ -213,10 +195,10 @@ QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], temp
|
|
213 |
QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
|
214 |
|
215 |
# Neo4j setup
|
216 |
-
graph = Neo4jGraph(url="neo4j+s://6457770f.databases.neo4j.io",
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
# Avoid pushing the graph documents to Neo4j every time
|
221 |
# Only push the documents once and comment the code below after the initial push
|
222 |
# dataset_name = "Pijush2023/birmindata07312024"
|
@@ -231,115 +213,118 @@ graph = Neo4jGraph(url="neo4j+s://6457770f.databases.neo4j.io",
|
|
231 |
# graph_documents = llm_transformer.convert_to_graph_documents(documents)
|
232 |
# graph.add_graph_documents(graph_documents, baseEntityLabel=True, include_source=True)
|
233 |
|
234 |
-
class Entities(BaseModel):
|
235 |
-
names: list[str] = Field(..., description="All the person, organization, or business entities that appear in the text")
|
236 |
-
|
237 |
-
entity_prompt = ChatPromptTemplate.from_messages([
|
238 |
-
("system", "You are extracting organization and person entities from the text."),
|
239 |
-
("human", "Use the given format to extract information from the following input: {question}"),
|
240 |
-
])
|
241 |
-
|
242 |
-
entity_chain = entity_prompt | chat_model.with_structured_output(Entities)
|
243 |
-
|
244 |
-
def remove_lucene_chars(input: str) -> str:
|
245 |
-
return input.translate(str.maketrans({"\\": r"\\", "+": r"\+", "-": r"\-", "&": r"\&", "|": r"\|", "!": r"\!",
|
246 |
-
"(": r"\(", ")": r"\)", "{": r"\{", "}": r"\}", "[": r"\[", "]": r"\]",
|
247 |
-
"^": r"\^", "~": r"\~", "*": r"\*", "?": r"\?", ":": r"\:", '"': r'\"',
|
248 |
-
";": r"\;", " ": r"\ "}))
|
249 |
-
|
250 |
-
def generate_full_text_query(input: str) -> str:
|
251 |
-
full_text_query = ""
|
252 |
-
words = [el for el in remove_lucene_chars(input).split() if el]
|
253 |
-
for word in words[:-1]:
|
254 |
-
full_text_query += f" {word}~2 AND"
|
255 |
-
full_text_query += f" {words[-1]}~2"
|
256 |
-
return full_text_query.strip()
|
257 |
-
|
258 |
-
def structured_retriever(question: str) -> str:
|
259 |
-
result = ""
|
260 |
-
entities = entity_chain.invoke({"question": question})
|
261 |
-
for entity in entities.names:
|
262 |
-
response = graph.query(
|
263 |
-
"""CALL db.index.fulltext.queryNodes('entity', $query, {limit:2})
|
264 |
-
YIELD node,score
|
265 |
-
CALL {
|
266 |
-
WITH node
|
267 |
-
MATCH (node)-[r:!MENTIONS]->(neighbor)
|
268 |
-
RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS output
|
269 |
-
UNION ALL
|
270 |
-
WITH node
|
271 |
-
MATCH (node)<-[r:!MENTIONS]-(neighbor)
|
272 |
-
RETURN neighbor.id + ' - ' + type(r) + ' -> ' + node.id AS output
|
273 |
-
}
|
274 |
-
RETURN output LIMIT 50
|
275 |
-
""",
|
276 |
-
{"query": generate_full_text_query(entity)},
|
277 |
-
)
|
278 |
-
result += "\n".join([el['output'] for el in response])
|
279 |
-
return result
|
280 |
-
|
281 |
-
def retriever_neo4j(question: str):
|
282 |
-
structured_data = structured_retriever(question)
|
283 |
-
logging.debug(f"Structured data: {structured_data}")
|
284 |
-
return structured_data
|
285 |
-
|
286 |
-
_template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
|
287 |
-
in its original language.
|
288 |
-
Chat History:
|
289 |
-
{chat_history}
|
290 |
-
Follow Up Input: {question}
|
291 |
-
Standalone question:"""
|
292 |
-
|
293 |
-
CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
|
294 |
-
|
295 |
-
def _format_chat_history(chat_history: list[tuple[str, str]]) -> list:
|
296 |
-
buffer = []
|
297 |
-
for human, ai in chat_history:
|
298 |
-
buffer.append(HumanMessage(content=human))
|
299 |
-
buffer.append(AIMessage(content=ai))
|
300 |
-
return buffer
|
301 |
-
|
302 |
-
_search_query = RunnableBranch(
|
303 |
-
(
|
304 |
-
RunnableLambda(lambda x: bool(x.get("chat_history"))).with_config(
|
305 |
-
run_name="HasChatHistoryCheck"
|
306 |
-
),
|
307 |
-
RunnablePassthrough.assign(
|
308 |
-
chat_history=lambda x: _format_chat_history(x["chat_history"])
|
309 |
-
)
|
310 |
-
| CONDENSE_QUESTION_PROMPT
|
311 |
-
| ChatOpenAI(temperature=0, api_key=os.environ['OPENAI_API_KEY'])
|
312 |
-
| StrOutputParser(),
|
313 |
-
),
|
314 |
-
RunnableLambda(lambda x : x["question"]),
|
315 |
-
)
|
316 |
|
317 |
-
|
318 |
-
|
319 |
-
#
|
320 |
-
#
|
321 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
322 |
|
323 |
-
|
324 |
-
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.
|
325 |
-
"It was my pleasure!"
|
326 |
-
{{context}}
|
327 |
-
Question: {{question}}
|
328 |
-
Helpful Answer:"""
|
329 |
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
| StrOutputParser()
|
342 |
-
)
|
343 |
|
344 |
|
345 |
|
@@ -441,20 +426,6 @@ def bot(history, choice, tts_choice, retrieval_mode, model_choice):
|
|
441 |
|
442 |
|
443 |
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
# def generate_audio_after_text(response, tts_choice):
|
452 |
-
# # Generate TTS audio after text response is completed
|
453 |
-
# with concurrent.futures.ThreadPoolExecutor() as executor:
|
454 |
-
# tts_future = executor.submit(generate_tts_response, response, tts_choice)
|
455 |
-
# audio_path = tts_future.result()
|
456 |
-
# return audio_path
|
457 |
-
|
458 |
import re
|
459 |
|
460 |
def clean_response(response_text):
|
@@ -493,15 +464,6 @@ def generate_answer(message, choice, retrieval_mode, selected_model):
|
|
493 |
choice = None
|
494 |
retrieval_mode = None
|
495 |
|
496 |
-
# try:
|
497 |
-
# # Select the appropriate template based on the choice
|
498 |
-
# if choice == "Details":
|
499 |
-
# prompt_template = QA_CHAIN_PROMPT_1
|
500 |
-
# elif choice == "Conversational":
|
501 |
-
# prompt_template = QA_CHAIN_PROMPT_2
|
502 |
-
# else:
|
503 |
-
# prompt_template = QA_CHAIN_PROMPT_1 # Fallback to template1
|
504 |
-
|
505 |
try:
|
506 |
# Select the appropriate template based on the choice and model
|
507 |
if choice == "Details" and selected_model == chat_model1: # GPT-4o-mini
|
@@ -513,26 +475,26 @@ def generate_answer(message, choice, retrieval_mode, selected_model):
|
|
513 |
else:
|
514 |
prompt_template = QA_CHAIN_PROMPT_1 # Fallback to template1
|
515 |
|
516 |
-
# Handle hotel-related queries
|
517 |
-
if "hotel" in message.lower() or "hotels" in message.lower() and "birmingham" in message.lower():
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
# Handle restaurant-related queries
|
524 |
-
if "restaurant" in message.lower() or "restaurants" in message.lower() and "birmingham" in message.lower():
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
# Handle flight-related queries
|
531 |
-
if "flight" in message.lower() or "flights" in message.lower() and "birmingham" in message.lower():
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
|
537 |
# Retrieval-based response
|
538 |
if retrieval_mode == "VDB":
|
@@ -633,72 +595,63 @@ def add_message(history, message):
|
|
633 |
def print_like_dislike(x: gr.LikeData):
|
634 |
print(x.index, x.value, x.liked)
|
635 |
|
636 |
-
def extract_addresses(response):
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
all_addresses = []
|
667 |
-
|
668 |
-
def generate_map(location_names):
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
|
689 |
from diffusers import DiffusionPipeline
|
690 |
import torch
|
691 |
|
692 |
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
def fetch_local_news():
|
703 |
api_key = os.environ['SERP_API']
|
704 |
url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
|
@@ -815,21 +768,21 @@ def transcribe_function(stream, new_chunk):
|
|
815 |
|
816 |
|
817 |
|
818 |
-
def update_map_with_response(history):
|
819 |
-
|
820 |
-
|
821 |
-
|
822 |
-
|
823 |
-
|
824 |
|
825 |
def clear_textbox():
|
826 |
return ""
|
827 |
|
828 |
-
def show_map_if_details(history, choice):
|
829 |
-
|
830 |
-
|
831 |
-
|
832 |
-
|
833 |
|
834 |
|
835 |
|
@@ -1330,45 +1283,45 @@ def fetch_google_flights(departure_id="JFK", arrival_id="BHM", outbound_date=cur
|
|
1330 |
return flight_info
|
1331 |
|
1332 |
|
1333 |
-
examples = [
|
1334 |
-
|
1335 |
-
|
1336 |
-
|
1337 |
-
|
1338 |
-
|
1339 |
-
|
1340 |
-
|
1341 |
-
|
1342 |
-
|
1343 |
-
|
1344 |
-
|
1345 |
-
|
1346 |
-
|
1347 |
-
|
1348 |
-
|
1349 |
-
|
1350 |
-
|
1351 |
-
|
1352 |
-
|
1353 |
-
|
1354 |
-
|
1355 |
-
|
1356 |
-
|
1357 |
-
|
1358 |
-
|
1359 |
-
|
1360 |
-
|
1361 |
-
|
1362 |
-
|
1363 |
-
|
1364 |
-
|
1365 |
-
|
1366 |
-
|
1367 |
-
]
|
1368 |
-
|
1369 |
-
# Function to insert the prompt into the textbox when clicked
|
1370 |
-
def insert_prompt(current_text, prompt):
|
1371 |
-
|
1372 |
|
1373 |
|
1374 |
|
@@ -1387,9 +1340,9 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
|
|
1387 |
# Link the dropdown change to handle_model_choice_change
|
1388 |
model_choice.change(fn=handle_model_choice_change, inputs=model_choice, outputs=[retrieval_mode, choice, choice])
|
1389 |
|
1390 |
-
gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
|
1391 |
|
1392 |
-
chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!"
|
1393 |
tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta"], value="Alpha")
|
1394 |
|
1395 |
retriever_button = gr.Button("Retriever")
|
@@ -1397,8 +1350,8 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
|
|
1397 |
clear_button = gr.Button("Clear")
|
1398 |
clear_button.click(lambda: [None, None], outputs=[chat_input, state])
|
1399 |
|
1400 |
-
gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
|
1401 |
-
location_output = gr.HTML()
|
1402 |
audio_output = gr.Audio(interactive=False, autoplay=True)
|
1403 |
|
1404 |
def stop_audio():
|
@@ -1416,7 +1369,6 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
|
|
1416 |
.then(fn=generate_bot_response, inputs=[chatbot, choice, retrieval_mode, model_choice], outputs=[chatbot], api_name="api_generate_bot_response")
|
1417 |
# Then, generate the TTS response based on the bot's response
|
1418 |
.then(fn=generate_tts_response, inputs=[chatbot, tts_choice], outputs=[audio_output], api_name="api_generate_tts_response")
|
1419 |
-
.then(fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="api_show_map_details")
|
1420 |
.then(fn=clear_textbox, inputs=[], outputs=[chat_input], api_name="api_clear_textbox")
|
1421 |
)
|
1422 |
|
@@ -1435,8 +1387,6 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
|
|
1435 |
).then(
|
1436 |
# Then, generate the TTS response based on the bot's response
|
1437 |
fn=generate_tts_response, inputs=[chatbot, tts_choice], outputs=[audio_output], api_name="api_generate_tts_response"
|
1438 |
-
).then(
|
1439 |
-
fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="api_show_map_details"
|
1440 |
).then(
|
1441 |
fn=clear_textbox, inputs=[], outputs=[chat_input], api_name="api_clear_textbox"
|
1442 |
)
|
@@ -1450,28 +1400,28 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
|
|
1450 |
audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy', every=0.1)
|
1451 |
audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="api_voice_to_text")
|
1452 |
|
1453 |
-
|
1454 |
-
|
1455 |
|
1456 |
-
with gr.Column():
|
1457 |
-
|
1458 |
-
|
1459 |
-
|
1460 |
|
1461 |
-
with gr.Column():
|
1462 |
|
1463 |
|
1464 |
-
|
1465 |
-
|
1466 |
|
1467 |
-
|
1468 |
-
|
1469 |
-
|
1470 |
-
|
1471 |
|
1472 |
-
|
1473 |
-
|
1474 |
-
|
1475 |
|
1476 |
|
1477 |
|
|
|
118 |
|
119 |
|
120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
121 |
# Existing embeddings and vector store for GPT-4o
|
122 |
gpt_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
|
123 |
+
gpt_vectorstore = PineconeVectorStore(index_name="italy-dataset-gpt", embedding=gpt_embeddings)
|
124 |
gpt_retriever = gpt_vectorstore.as_retriever(search_kwargs={'k': 5})
|
125 |
|
126 |
# New vector store setup for Phi-3.5
|
127 |
phi_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
|
128 |
+
phi_vectorstore = PineconeVectorStore(index_name="phi-italy-dataset-gpt", embedding=phi_embeddings)
|
129 |
phi_retriever = phi_vectorstore.as_retriever(search_kwargs={'k': 5})
|
130 |
|
131 |
|
|
|
149 |
)
|
150 |
|
151 |
# Prompt templates
|
152 |
+
# def get_current_date():
|
153 |
+
# return datetime.now().strftime("%B %d, %Y")
|
154 |
|
155 |
+
# current_date = get_current_date()
|
156 |
|
157 |
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.
|
158 |
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.
|
|
|
183 |
Question: {{question}}
|
184 |
Helpful Answer:"""
|
185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
186 |
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.
|
187 |
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!
|
188 |
"It’s always a pleasure to assist you!"
|
|
|
195 |
QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
|
196 |
|
197 |
# Neo4j setup
|
198 |
+
# graph = Neo4jGraph(url="neo4j+s://6457770f.databases.neo4j.io",
|
199 |
+
# username="neo4j",
|
200 |
+
# password="Z10duoPkKCtENuOukw3eIlvl0xJWKtrVSr-_hGX1LQ4"
|
201 |
+
# )
|
202 |
# Avoid pushing the graph documents to Neo4j every time
|
203 |
# Only push the documents once and comment the code below after the initial push
|
204 |
# dataset_name = "Pijush2023/birmindata07312024"
|
|
|
213 |
# graph_documents = llm_transformer.convert_to_graph_documents(documents)
|
214 |
# graph.add_graph_documents(graph_documents, baseEntityLabel=True, include_source=True)
|
215 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
216 |
|
217 |
+
#-------------------------------Comment Out------------------------------------------------------------------------------------------------------------------------
|
218 |
+
|
219 |
+
# class Entities(BaseModel):
|
220 |
+
# names: list[str] = Field(..., description="All the person, organization, or business entities that appear in the text")
|
221 |
+
|
222 |
+
# entity_prompt = ChatPromptTemplate.from_messages([
|
223 |
+
# ("system", "You are extracting organization and person entities from the text."),
|
224 |
+
# ("human", "Use the given format to extract information from the following input: {question}"),
|
225 |
+
# ])
|
226 |
+
|
227 |
+
# entity_chain = entity_prompt | chat_model.with_structured_output(Entities)
|
228 |
+
|
229 |
+
# def remove_lucene_chars(input: str) -> str:
|
230 |
+
# return input.translate(str.maketrans({"\\": r"\\", "+": r"\+", "-": r"\-", "&": r"\&", "|": r"\|", "!": r"\!",
|
231 |
+
# "(": r"\(", ")": r"\)", "{": r"\{", "}": r"\}", "[": r"\[", "]": r"\]",
|
232 |
+
# "^": r"\^", "~": r"\~", "*": r"\*", "?": r"\?", ":": r"\:", '"': r'\"',
|
233 |
+
# ";": r"\;", " ": r"\ "}))
|
234 |
+
|
235 |
+
# def generate_full_text_query(input: str) -> str:
|
236 |
+
# full_text_query = ""
|
237 |
+
# words = [el for el in remove_lucene_chars(input).split() if el]
|
238 |
+
# for word in words[:-1]:
|
239 |
+
# full_text_query += f" {word}~2 AND"
|
240 |
+
# full_text_query += f" {words[-1]}~2"
|
241 |
+
# return full_text_query.strip()
|
242 |
+
|
243 |
+
# def structured_retriever(question: str) -> str:
|
244 |
+
# result = ""
|
245 |
+
# entities = entity_chain.invoke({"question": question})
|
246 |
+
# for entity in entities.names:
|
247 |
+
# response = graph.query(
|
248 |
+
# """CALL db.index.fulltext.queryNodes('entity', $query, {limit:2})
|
249 |
+
# YIELD node,score
|
250 |
+
# CALL {
|
251 |
+
# WITH node
|
252 |
+
# MATCH (node)-[r:!MENTIONS]->(neighbor)
|
253 |
+
# RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS output
|
254 |
+
# UNION ALL
|
255 |
+
# WITH node
|
256 |
+
# MATCH (node)<-[r:!MENTIONS]-(neighbor)
|
257 |
+
# RETURN neighbor.id + ' - ' + type(r) + ' -> ' + node.id AS output
|
258 |
+
# }
|
259 |
+
# RETURN output LIMIT 50
|
260 |
+
# """,
|
261 |
+
# {"query": generate_full_text_query(entity)},
|
262 |
+
# )
|
263 |
+
# result += "\n".join([el['output'] for el in response])
|
264 |
+
# return result
|
265 |
+
|
266 |
+
# def retriever_neo4j(question: str):
|
267 |
+
# structured_data = structured_retriever(question)
|
268 |
+
# logging.debug(f"Structured data: {structured_data}")
|
269 |
+
# return structured_data
|
270 |
+
|
271 |
+
# _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
|
272 |
+
# in its original language.
|
273 |
+
# Chat History:
|
274 |
+
# {chat_history}
|
275 |
+
# Follow Up Input: {question}
|
276 |
+
# Standalone question:"""
|
277 |
+
|
278 |
+
# CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
|
279 |
+
|
280 |
+
# def _format_chat_history(chat_history: list[tuple[str, str]]) -> list:
|
281 |
+
# buffer = []
|
282 |
+
# for human, ai in chat_history:
|
283 |
+
# buffer.append(HumanMessage(content=human))
|
284 |
+
# buffer.append(AIMessage(content=ai))
|
285 |
+
# return buffer
|
286 |
+
|
287 |
+
# _search_query = RunnableBranch(
|
288 |
+
# (
|
289 |
+
# RunnableLambda(lambda x: bool(x.get("chat_history"))).with_config(
|
290 |
+
# run_name="HasChatHistoryCheck"
|
291 |
+
# ),
|
292 |
+
# RunnablePassthrough.assign(
|
293 |
+
# chat_history=lambda x: _format_chat_history(x["chat_history"])
|
294 |
+
# )
|
295 |
+
# | CONDENSE_QUESTION_PROMPT
|
296 |
+
# | ChatOpenAI(temperature=0, api_key=os.environ['OPENAI_API_KEY'])
|
297 |
+
# | StrOutputParser(),
|
298 |
+
# ),
|
299 |
+
# RunnableLambda(lambda x : x["question"]),
|
300 |
+
# )
|
301 |
+
|
302 |
+
# # template = """Answer the question based only on the following context:
|
303 |
+
# # {context}
|
304 |
+
# # Question: {question}
|
305 |
+
# # Use natural language and be concise.
|
306 |
+
# # Answer:"""
|
307 |
+
|
308 |
+
# 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.
|
309 |
+
# 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.
|
310 |
+
# "It was my pleasure!"
|
311 |
+
# {{context}}
|
312 |
+
# Question: {{question}}
|
313 |
+
# Helpful Answer:"""
|
314 |
|
315 |
+
# qa_prompt = ChatPromptTemplate.from_template(template)
|
|
|
|
|
|
|
|
|
|
|
316 |
|
317 |
+
# chain_neo4j = (
|
318 |
+
# RunnableParallel(
|
319 |
+
# {
|
320 |
+
# "context": _search_query | retriever_neo4j,
|
321 |
+
# "question": RunnablePassthrough(),
|
322 |
+
# }
|
323 |
+
# )
|
324 |
+
# | qa_prompt
|
325 |
+
# | chat_model
|
326 |
+
# | StrOutputParser()
|
327 |
+
# )
|
|
|
|
|
328 |
|
329 |
|
330 |
|
|
|
426 |
|
427 |
|
428 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
429 |
import re
|
430 |
|
431 |
def clean_response(response_text):
|
|
|
464 |
choice = None
|
465 |
retrieval_mode = None
|
466 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
467 |
try:
|
468 |
# Select the appropriate template based on the choice and model
|
469 |
if choice == "Details" and selected_model == chat_model1: # GPT-4o-mini
|
|
|
475 |
else:
|
476 |
prompt_template = QA_CHAIN_PROMPT_1 # Fallback to template1
|
477 |
|
478 |
+
# # Handle hotel-related queries
|
479 |
+
# if "hotel" in message.lower() or "hotels" in message.lower() and "birmingham" in message.lower():
|
480 |
+
# logging.debug("Handling hotel-related query")
|
481 |
+
# response = fetch_google_hotels()
|
482 |
+
# logging.debug(f"Hotel response: {response}")
|
483 |
+
# return response, extract_addresses(response)
|
484 |
+
|
485 |
+
# # Handle restaurant-related queries
|
486 |
+
# if "restaurant" in message.lower() or "restaurants" in message.lower() and "birmingham" in message.lower():
|
487 |
+
# logging.debug("Handling restaurant-related query")
|
488 |
+
# response = fetch_yelp_restaurants()
|
489 |
+
# logging.debug(f"Restaurant response: {response}")
|
490 |
+
# return response, extract_addresses(response)
|
491 |
+
|
492 |
+
# # Handle flight-related queries
|
493 |
+
# if "flight" in message.lower() or "flights" in message.lower() and "birmingham" in message.lower():
|
494 |
+
# logging.debug("Handling flight-related query")
|
495 |
+
# response = fetch_google_flights()
|
496 |
+
# logging.debug(f"Flight response: {response}")
|
497 |
+
# return response, extract_addresses(response)
|
498 |
|
499 |
# Retrieval-based response
|
500 |
if retrieval_mode == "VDB":
|
|
|
595 |
def print_like_dislike(x: gr.LikeData):
|
596 |
print(x.index, x.value, x.liked)
|
597 |
|
598 |
+
# def extract_addresses(response):
|
599 |
+
# if not isinstance(response, str):
|
600 |
+
# response = str(response)
|
601 |
+
# address_patterns = [
|
602 |
+
# r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
|
603 |
+
# r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
|
604 |
+
# r'([A-Z].*,\sAL\s\d{5})',
|
605 |
+
# r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
|
606 |
+
# r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
|
607 |
+
# r'(\d{2}.*\sStreets)',
|
608 |
+
# r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
|
609 |
+
# r'([a-zA-Z]\s Birmingham)',
|
610 |
+
# r'([a-zA-Z].*,\sBirmingham,\sAL)',
|
611 |
+
# r'(.*),(Birmingham, AL,USA)$'
|
612 |
+
# r'(^Birmingham,AL$)',
|
613 |
+
# r'((.*)(Stadium|Field),.*,\sAL$)',
|
614 |
+
# r'((.*)(Stadium|Field),.*,\sFL$)',
|
615 |
+
# r'((.*)(Stadium|Field),.*,\sMS$)',
|
616 |
+
# r'((.*)(Stadium|Field),.*,\sAR$)',
|
617 |
+
# r'((.*)(Stadium|Field),.*,\sKY$)',
|
618 |
+
# r'((.*)(Stadium|Field),.*,\sTN$)',
|
619 |
+
# r'((.*)(Stadium|Field),.*,\sLA$)',
|
620 |
+
# r'((.*)(Stadium|Field),.*,\sFL$)'
|
621 |
+
|
622 |
+
# ]
|
623 |
+
# addresses = []
|
624 |
+
# for pattern in address_patterns:
|
625 |
+
# addresses.extend(re.findall(pattern, response))
|
626 |
+
# return addresses
|
627 |
+
|
628 |
+
# all_addresses = []
|
629 |
+
|
630 |
+
# def generate_map(location_names):
|
631 |
+
# global all_addresses
|
632 |
+
# all_addresses.extend(location_names)
|
633 |
+
|
634 |
+
# api_key = os.environ['GOOGLEMAPS_API_KEY']
|
635 |
+
# gmaps = GoogleMapsClient(key=api_key)
|
636 |
+
|
637 |
+
# m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
|
638 |
+
|
639 |
+
# for location_name in all_addresses:
|
640 |
+
# geocode_result = gmaps.geocode(location_name)
|
641 |
+
# if geocode_result:
|
642 |
+
# location = geocode_result[0]['geometry']['location']
|
643 |
+
# folium.Marker(
|
644 |
+
# [location['lat'], location['lng']],
|
645 |
+
# tooltip=f"{geocode_result[0]['formatted_address']}"
|
646 |
+
# ).add_to(m)
|
647 |
+
|
648 |
+
# map_html = m._repr_html_()
|
649 |
+
# return map_html
|
650 |
|
651 |
from diffusers import DiffusionPipeline
|
652 |
import torch
|
653 |
|
654 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
655 |
def fetch_local_news():
|
656 |
api_key = os.environ['SERP_API']
|
657 |
url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
|
|
|
768 |
|
769 |
|
770 |
|
771 |
+
# def update_map_with_response(history):
|
772 |
+
# if not history:
|
773 |
+
# return ""
|
774 |
+
# response = history[-1][1]
|
775 |
+
# addresses = extract_addresses(response)
|
776 |
+
# return generate_map(addresses)
|
777 |
|
778 |
def clear_textbox():
|
779 |
return ""
|
780 |
|
781 |
+
# def show_map_if_details(history, choice):
|
782 |
+
# if choice in ["Details", "Conversational"]:
|
783 |
+
# return gr.update(visible=True), update_map_with_response(history)
|
784 |
+
# else:
|
785 |
+
# return gr.update(visible(False), "")
|
786 |
|
787 |
|
788 |
|
|
|
1283 |
return flight_info
|
1284 |
|
1285 |
|
1286 |
+
# examples = [
|
1287 |
+
# [
|
1288 |
+
# "What are the concerts in Birmingham?",
|
1289 |
+
# ],
|
1290 |
+
# [
|
1291 |
+
# "what are some of the upcoming matches of crimson tide?",
|
1292 |
+
# ],
|
1293 |
+
# [
|
1294 |
+
# "where from i will get a Hamburger?",
|
1295 |
+
# ],
|
1296 |
+
# [
|
1297 |
+
# "What are some of the hotels at birmingham?",
|
1298 |
+
# ],
|
1299 |
+
# [
|
1300 |
+
# "how can i connect the alexa to the radio?"
|
1301 |
+
# ],
|
1302 |
+
# [
|
1303 |
+
# "What are some of the good clubs at birmingham?"
|
1304 |
+
# ],
|
1305 |
+
# [
|
1306 |
+
# "How do I call the radio station?",
|
1307 |
+
# ],
|
1308 |
+
# [
|
1309 |
+
# "What’s the spread?"
|
1310 |
+
# ],
|
1311 |
+
# [
|
1312 |
+
# "What time is Crimson Tide Rewind?"
|
1313 |
+
# ],
|
1314 |
+
# [
|
1315 |
+
# "What time is Alabama kick-off?"
|
1316 |
+
# ],
|
1317 |
+
# [
|
1318 |
+
# "who are some of the popular players of crimson tide?"
|
1319 |
+
# ]
|
1320 |
+
# ]
|
1321 |
+
|
1322 |
+
# # Function to insert the prompt into the textbox when clicked
|
1323 |
+
# def insert_prompt(current_text, prompt):
|
1324 |
+
# return prompt[0] if prompt else current_text
|
1325 |
|
1326 |
|
1327 |
|
|
|
1340 |
# Link the dropdown change to handle_model_choice_change
|
1341 |
model_choice.change(fn=handle_model_choice_change, inputs=model_choice, outputs=[retrieval_mode, choice, choice])
|
1342 |
|
1343 |
+
# gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
|
1344 |
|
1345 |
+
chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!")
|
1346 |
tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta"], value="Alpha")
|
1347 |
|
1348 |
retriever_button = gr.Button("Retriever")
|
|
|
1350 |
clear_button = gr.Button("Clear")
|
1351 |
clear_button.click(lambda: [None, None], outputs=[chat_input, state])
|
1352 |
|
1353 |
+
# gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
|
1354 |
+
# location_output = gr.HTML()
|
1355 |
audio_output = gr.Audio(interactive=False, autoplay=True)
|
1356 |
|
1357 |
def stop_audio():
|
|
|
1369 |
.then(fn=generate_bot_response, inputs=[chatbot, choice, retrieval_mode, model_choice], outputs=[chatbot], api_name="api_generate_bot_response")
|
1370 |
# Then, generate the TTS response based on the bot's response
|
1371 |
.then(fn=generate_tts_response, inputs=[chatbot, tts_choice], outputs=[audio_output], api_name="api_generate_tts_response")
|
|
|
1372 |
.then(fn=clear_textbox, inputs=[], outputs=[chat_input], api_name="api_clear_textbox")
|
1373 |
)
|
1374 |
|
|
|
1387 |
).then(
|
1388 |
# Then, generate the TTS response based on the bot's response
|
1389 |
fn=generate_tts_response, inputs=[chatbot, tts_choice], outputs=[audio_output], api_name="api_generate_tts_response"
|
|
|
|
|
1390 |
).then(
|
1391 |
fn=clear_textbox, inputs=[], outputs=[chat_input], api_name="api_clear_textbox"
|
1392 |
)
|
|
|
1400 |
audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy', every=0.1)
|
1401 |
audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="api_voice_to_text")
|
1402 |
|
1403 |
+
# gr.Markdown("<h1 style='color: red;'>Example Prompts</h1>", elem_id="Example-Prompts")
|
1404 |
+
# gr.Examples(examples=examples, fn=insert_prompt,inputs=chat_input, outputs=chat_input)
|
1405 |
|
1406 |
+
# with gr.Column():
|
1407 |
+
# weather_output = gr.HTML(value=fetch_local_weather())
|
1408 |
+
# news_output = gr.HTML(value=fetch_local_news())
|
1409 |
+
# events_output = gr.HTML(value=fetch_local_events())
|
1410 |
|
1411 |
+
# with gr.Column():
|
1412 |
|
1413 |
|
1414 |
+
# # Call update_images during the initial load to display images when the interface appears
|
1415 |
+
# initial_images = update_images()
|
1416 |
|
1417 |
+
# # Displaying the images generated using Flux API directly
|
1418 |
+
# image_output_1 = gr.Image(value=initial_images[0], label="Image 1", elem_id="flux_image_1", width=400, height=400)
|
1419 |
+
# image_output_2 = gr.Image(value=initial_images[1], label="Image 2", elem_id="flux_image_2", width=400, height=400)
|
1420 |
+
# image_output_3 = gr.Image(value=initial_images[2], label="Image 3", elem_id="flux_image_3", width=400, height=400)
|
1421 |
|
1422 |
+
# # Refresh button to update images
|
1423 |
+
# refresh_button = gr.Button("Refresh Images")
|
1424 |
+
# refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
|
1425 |
|
1426 |
|
1427 |
|