Update app.py
Browse files
app.py
CHANGED
|
@@ -2,115 +2,94 @@ import gradio as gr
|
|
| 2 |
from sentence_transformers import SentenceTransformer, util
|
| 3 |
import openai
|
| 4 |
import os
|
| 5 |
-
import pandas as pd
|
| 6 |
-
|
| 7 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 8 |
-
|
| 9 |
-
#
|
| 10 |
-
filename = "output_topic_details.txt"
|
| 11 |
retrieval_model_name = 'output/sentence-transformer-finetuned/'
|
| 12 |
-
|
| 13 |
openai.api_key = os.environ["OPENAI_API_KEY"]
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
"You are a restaurant recommending chatbot that takes details about a restaurant including type of restaurant, "
|
| 17 |
-
"dietary restrictions, and budget and chooses a restaurant in Seattle which best fits the user's criteria. "
|
| 18 |
-
"Then you output the restaurant name and website link."
|
| 19 |
-
)
|
| 20 |
messages = [{"role": "system", "content": system_message}]
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
try:
|
| 25 |
with open(filename, 'r', encoding='utf-8') as file:
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
restaurant_data = []
|
| 30 |
-
|
| 31 |
-
for section in sections[1:]:
|
| 32 |
-
lines = section.strip().split("\n")
|
| 33 |
-
topic = lines[0]
|
| 34 |
-
description = "\n".join(lines[1:])
|
| 35 |
-
if topic == "Details about Restaurants":
|
| 36 |
-
lines = description.split("\n")
|
| 37 |
-
# Convert to a DataFrame
|
| 38 |
-
df = pd.DataFrame([line.split(",") for line in lines[1:]], columns=lines[0].split(","))
|
| 39 |
-
restaurant_data.append(df)
|
| 40 |
-
|
| 41 |
-
# Concatenate all DataFrames into one
|
| 42 |
-
full_df = pd.concat(restaurant_data, ignore_index=True)
|
| 43 |
-
full_df.columns = full_df.columns.str.strip() # Strip any extra whitespace from column names
|
| 44 |
-
print("Data loaded and preprocessed successfully.")
|
| 45 |
-
return full_df
|
| 46 |
except Exception as e:
|
| 47 |
-
print(f"Failed to load or preprocess
|
| 48 |
-
return
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
def generate_response(user_query):
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
results = filter_restaurants(cuisine=cuisine, dietary_restrictions=dietary_restrictions, budget=budget)
|
| 97 |
-
if isinstance(results, str): # If no restaurants found
|
| 98 |
-
return results
|
| 99 |
-
|
| 100 |
-
response = "\n".join([f"{r['Restaurant']}: {r['Website']}" for r in results])
|
| 101 |
-
return response
|
| 102 |
-
|
| 103 |
def query_model(question):
|
|
|
|
|
|
|
|
|
|
| 104 |
if question == "":
|
| 105 |
-
return "
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
| 107 |
return response
|
| 108 |
-
|
| 109 |
welcome_message = """
|
| 110 |
# Welcome to Ethical Eats Explorer!
|
| 111 |
-
## Your AI-driven assistant for restaurant recs in Seattle. Created by Saranya, Cindy, and Liana of the 2024 Kode With Klossy Seattle Camp.
|
| 112 |
"""
|
| 113 |
-
|
| 114 |
topics = """
|
| 115 |
### Please give me your restaurant preferences:
|
| 116 |
- Dietary Restrictions
|
|
@@ -119,17 +98,17 @@ topics = """
|
|
| 119 |
- Budget Preferences (Low: $0 - $20, Moderate: $20 - $30, High: $30+ - per person)
|
| 120 |
Please send your message in the format: "Could you give me a (cuisine) restaurant with (dietary restriction) options that is (budget) budget?"
|
| 121 |
"""
|
| 122 |
-
|
| 123 |
with gr.Blocks(theme='JohnSmith9982/small_and_pretty') as demo:
|
| 124 |
-
gr.Markdown(welcome_message)
|
| 125 |
with gr.Row():
|
| 126 |
with gr.Column():
|
| 127 |
-
gr.Markdown(topics)
|
| 128 |
with gr.Row():
|
| 129 |
with gr.Column():
|
| 130 |
question = gr.Textbox(label="Your question", placeholder="Give me your information...")
|
| 131 |
answer = gr.Textbox(label="Explorer's Response", placeholder="Explorer will respond here...", interactive=False, lines=10)
|
| 132 |
submit_button = gr.Button("Submit")
|
| 133 |
submit_button.click(fn=query_model, inputs=question, outputs=answer)
|
| 134 |
-
|
| 135 |
demo.launch(share=True)
|
|
|
|
| 2 |
from sentence_transformers import SentenceTransformer, util
|
| 3 |
import openai
|
| 4 |
import os
|
|
|
|
|
|
|
| 5 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 6 |
+
# Initialize paths and model identifiers for easy configuration and maintenance
|
| 7 |
+
filename = "output_topic_details.txt" # Path to the file storing chess-specific details
|
|
|
|
| 8 |
retrieval_model_name = 'output/sentence-transformer-finetuned/'
|
|
|
|
| 9 |
openai.api_key = os.environ["OPENAI_API_KEY"]
|
| 10 |
+
system_message = "You are a restaurant recommending chatbot that suggests one restaurant based on the criteria the user provides."
|
| 11 |
+
# Initial system message to set the behavior of the assistant
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
messages = [{"role": "system", "content": system_message}]
|
| 13 |
+
# Attempt to load the necessary models and provide feedback on success or failure
|
| 14 |
+
try:
|
| 15 |
+
retrieval_model = SentenceTransformer(retrieval_model_name)
|
| 16 |
+
print("Models loaded successfully.")
|
| 17 |
+
except Exception as e:
|
| 18 |
+
print(f"Failed to load models: {e}")
|
| 19 |
+
def load_and_preprocess_text(filename):
|
| 20 |
+
"""
|
| 21 |
+
Load and preprocess text from a file, removing empty lines and stripping whitespace.
|
| 22 |
+
"""
|
| 23 |
try:
|
| 24 |
with open(filename, 'r', encoding='utf-8') as file:
|
| 25 |
+
segments = [line.strip() for line in file if line.strip()]
|
| 26 |
+
print("Text loaded and preprocessed successfully.")
|
| 27 |
+
return segments
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
except Exception as e:
|
| 29 |
+
print(f"Failed to load or preprocess text: {e}")
|
| 30 |
+
return []
|
| 31 |
+
segments = load_and_preprocess_text(filename)
|
| 32 |
+
def find_relevant_segment(user_query, segments):
|
| 33 |
+
"""
|
| 34 |
+
Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.
|
| 35 |
+
This version finds the best match based on the content of the query.
|
| 36 |
+
"""
|
| 37 |
+
try:
|
| 38 |
+
# Lowercase the query for better matching
|
| 39 |
+
lower_query = user_query.lower()
|
| 40 |
+
# Encode the query and the segments
|
| 41 |
+
query_embedding = retrieval_model.encode(lower_query)
|
| 42 |
+
segment_embeddings = retrieval_model.encode(segments)
|
| 43 |
+
# Compute cosine similarities between the query and the segments
|
| 44 |
+
similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
|
| 45 |
+
# Find the index of the most similar segment
|
| 46 |
+
best_idx = similarities.argmax()
|
| 47 |
+
# Return the most relevant segment
|
| 48 |
+
return segments[best_idx]
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"Error in finding relevant segment: {e}")
|
| 51 |
+
return ""
|
| 52 |
+
def generate_response(user_query, relevant_segment):
|
| 53 |
+
"""
|
| 54 |
+
Generate a response emphasizing the bot's capability in suggesting a restaurant.
|
| 55 |
+
"""
|
| 56 |
+
try:
|
| 57 |
+
user_message = f"Here is a local restaurant based on your information: {relevant_segment}"
|
| 58 |
+
# Append user's message to messages list
|
| 59 |
+
messages.append({"role": "user", "content": user_message})
|
| 60 |
+
response = openai.ChatCompletion.create(
|
| 61 |
+
model="gpt-4o",
|
| 62 |
+
messages=messages,
|
| 63 |
+
max_tokens=150,
|
| 64 |
+
temperature=0.2,
|
| 65 |
+
top_p=1,
|
| 66 |
+
frequency_penalty=0,
|
| 67 |
+
presence_penalty=0
|
| 68 |
+
)
|
| 69 |
+
# Extract the response text
|
| 70 |
+
output_text = response['choices'][0]['message']['content'].strip()
|
| 71 |
+
# Append assistant's message to messages list for context
|
| 72 |
+
messages.append({"role": "assistant", "content": output_text})
|
| 73 |
+
return output_text
|
| 74 |
+
except Exception as e:
|
| 75 |
+
print(f"Error in generating response: {e}")
|
| 76 |
+
return f"Error in generating response: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
def query_model(question):
|
| 78 |
+
"""
|
| 79 |
+
Process a question, find relevant information, and generate a response.
|
| 80 |
+
"""
|
| 81 |
if question == "":
|
| 82 |
+
return "Give me your preferences..."
|
| 83 |
+
relevant_segment = find_relevant_segment(question, segments)
|
| 84 |
+
if not relevant_segment:
|
| 85 |
+
return "Could not find specific information. Please refine your question."
|
| 86 |
+
response = generate_response(question, relevant_segment)
|
| 87 |
return response
|
| 88 |
+
# Define the welcome message and specific topics the chatbot can provide information about
|
| 89 |
welcome_message = """
|
| 90 |
# Welcome to Ethical Eats Explorer!
|
| 91 |
+
## Your AI-driven assistant for restaurant recs in Seattle. Created by Saranya, Cindy, and Liana of the 2024 Kode With Klossy Seattle Camp.
|
| 92 |
"""
|
|
|
|
| 93 |
topics = """
|
| 94 |
### Please give me your restaurant preferences:
|
| 95 |
- Dietary Restrictions
|
|
|
|
| 98 |
- Budget Preferences (Low: $0 - $20, Moderate: $20 - $30, High: $30+ - per person)
|
| 99 |
Please send your message in the format: "Could you give me a (cuisine) restaurant with (dietary restriction) options that is (budget) budget?"
|
| 100 |
"""
|
| 101 |
+
# Setup the Gradio Blocks interface with custom layout components
|
| 102 |
with gr.Blocks(theme='JohnSmith9982/small_and_pretty') as demo:
|
| 103 |
+
gr.Markdown(welcome_message) # Display the formatted welcome message
|
| 104 |
with gr.Row():
|
| 105 |
with gr.Column():
|
| 106 |
+
gr.Markdown(topics) # Show the topics on the left side
|
| 107 |
with gr.Row():
|
| 108 |
with gr.Column():
|
| 109 |
question = gr.Textbox(label="Your question", placeholder="Give me your information...")
|
| 110 |
answer = gr.Textbox(label="Explorer's Response", placeholder="Explorer will respond here...", interactive=False, lines=10)
|
| 111 |
submit_button = gr.Button("Submit")
|
| 112 |
submit_button.click(fn=query_model, inputs=question, outputs=answer)
|
| 113 |
+
# Launch the Gradio app to allow user interaction
|
| 114 |
demo.launch(share=True)
|