Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,18 +6,20 @@ import os
|
|
| 6 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 7 |
|
| 8 |
# Initialize paths and model identifiers for easy configuration and maintenance
|
| 9 |
-
filename = "output_topic_details.txt"
|
| 10 |
retrieval_model_name = 'output/sentence-transformer-finetuned/'
|
| 11 |
|
| 12 |
# openai.api_key = os.environ["OPENAI_API_KEY"]
|
| 13 |
|
| 14 |
system_message = "You are a comfort chatbot specialized in providing information on destressing activities."
|
|
|
|
| 15 |
messages = [{"role": "system", "content": system_message}]
|
| 16 |
messages.append({
|
| 17 |
-
|
| 18 |
-
|
| 19 |
})
|
| 20 |
|
|
|
|
| 21 |
try:
|
| 22 |
retrieval_model = SentenceTransformer(retrieval_model_name)
|
| 23 |
print("Models loaded successfully.")
|
|
@@ -25,6 +27,9 @@ except Exception as e:
|
|
| 25 |
print(f"Failed to load models: {e}")
|
| 26 |
|
| 27 |
def load_and_preprocess_text(filename):
|
|
|
|
|
|
|
|
|
|
| 28 |
try:
|
| 29 |
with open(filename, 'r', encoding='utf-8') as file:
|
| 30 |
segments = [line.strip() for line in file if line.strip()]
|
|
@@ -37,20 +42,38 @@ def load_and_preprocess_text(filename):
|
|
| 37 |
segments = load_and_preprocess_text(filename)
|
| 38 |
|
| 39 |
def find_relevant_segment(user_query, segments):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
try:
|
|
|
|
| 41 |
lower_query = user_query.lower()
|
|
|
|
|
|
|
| 42 |
query_embedding = retrieval_model.encode(lower_query)
|
| 43 |
segment_embeddings = retrieval_model.encode(segments)
|
|
|
|
|
|
|
| 44 |
similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
|
|
|
|
|
|
|
| 45 |
best_idx = similarities.argmax()
|
|
|
|
|
|
|
| 46 |
return segments[best_idx]
|
| 47 |
except Exception as e:
|
| 48 |
print(f"Error in finding relevant segment: {e}")
|
| 49 |
return ""
|
| 50 |
|
| 51 |
def generate_response(user_query, relevant_segment):
|
|
|
|
|
|
|
|
|
|
| 52 |
try:
|
| 53 |
user_message = f"Here's the information on your request: {relevant_segment}"
|
|
|
|
|
|
|
| 54 |
messages.append({"role": "user", "content": user_message})
|
| 55 |
|
| 56 |
response = openai.ChatCompletion.create(
|
|
@@ -63,8 +86,12 @@ def generate_response(user_query, relevant_segment):
|
|
| 63 |
presence_penalty=0.5,
|
| 64 |
)
|
| 65 |
|
|
|
|
| 66 |
output_text = response['choices'][0]['message']['content'].strip()
|
|
|
|
|
|
|
| 67 |
messages.append({"role": "assistant", "content": output_text})
|
|
|
|
| 68 |
return output_text
|
| 69 |
|
| 70 |
except Exception as e:
|
|
@@ -72,6 +99,9 @@ def generate_response(user_query, relevant_segment):
|
|
| 72 |
return f"Error in generating response: {e}"
|
| 73 |
|
| 74 |
def query_model(question):
|
|
|
|
|
|
|
|
|
|
| 75 |
if question == "":
|
| 76 |
return "Welcome to CalmConnect's CalmBot! Ask me anything about destressing strategies and we'll provide you ways to unlock your inner calm!"
|
| 77 |
relevant_segment = find_relevant_segment(question, segments)
|
|
@@ -83,16 +113,6 @@ def query_model(question):
|
|
| 83 |
welcome_message = ""
|
| 84 |
topics = ""
|
| 85 |
|
| 86 |
-
# Custom CSS to center content
|
| 87 |
-
custom_css = """
|
| 88 |
-
#centered-container {
|
| 89 |
-
display: flex;
|
| 90 |
-
justify-content: center;
|
| 91 |
-
align-items: center;
|
| 92 |
-
height: 100vh; /* Full viewport height */
|
| 93 |
-
}
|
| 94 |
-
"""
|
| 95 |
-
|
| 96 |
theme = gr.themes.Default(
|
| 97 |
primary_hue="neutral",
|
| 98 |
secondary_hue="neutral",
|
|
@@ -109,24 +129,26 @@ theme = gr.themes.Default(
|
|
| 109 |
button_primary_background_fill="#f8f1ea",
|
| 110 |
button_primary_background_fill_dark="#f8f1ea"
|
| 111 |
)
|
| 112 |
-
|
| 113 |
# Setup the Gradio Blocks interface with custom layout components
|
| 114 |
-
with gr.Blocks(
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
| 119 |
with gr.Row():
|
| 120 |
-
with gr.Column(
|
| 121 |
-
gr.
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
submit_button = gr.Button("Submit")
|
| 128 |
-
submit_button.click(fn=query_model, inputs=question, outputs=answer)
|
| 129 |
|
| 130 |
# Launch the Gradio app to allow user interaction
|
| 131 |
demo.launch(share=True)
|
| 132 |
-
|
|
|
|
| 6 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 7 |
|
| 8 |
# Initialize paths and model identifiers for easy configuration and maintenance
|
| 9 |
+
filename = "output_topic_details.txt" # Path to the file storing destress-specific details
|
| 10 |
retrieval_model_name = 'output/sentence-transformer-finetuned/'
|
| 11 |
|
| 12 |
# openai.api_key = os.environ["OPENAI_API_KEY"]
|
| 13 |
|
| 14 |
system_message = "You are a comfort chatbot specialized in providing information on destressing activities."
|
| 15 |
+
# Initial system message to set the behavior of the assistant
|
| 16 |
messages = [{"role": "system", "content": system_message}]
|
| 17 |
messages.append({
|
| 18 |
+
"role": "system",
|
| 19 |
+
"content": "Do not use Markdown Format. Do not include hashtags or asterisks"
|
| 20 |
})
|
| 21 |
|
| 22 |
+
# Attempt to load the necessary models and provide feedback on success or failure
|
| 23 |
try:
|
| 24 |
retrieval_model = SentenceTransformer(retrieval_model_name)
|
| 25 |
print("Models loaded successfully.")
|
|
|
|
| 27 |
print(f"Failed to load models: {e}")
|
| 28 |
|
| 29 |
def load_and_preprocess_text(filename):
|
| 30 |
+
"""
|
| 31 |
+
Load and preprocess text from a file, removing empty lines and stripping whitespace.
|
| 32 |
+
"""
|
| 33 |
try:
|
| 34 |
with open(filename, 'r', encoding='utf-8') as file:
|
| 35 |
segments = [line.strip() for line in file if line.strip()]
|
|
|
|
| 42 |
segments = load_and_preprocess_text(filename)
|
| 43 |
|
| 44 |
def find_relevant_segment(user_query, segments):
|
| 45 |
+
"""
|
| 46 |
+
Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.
|
| 47 |
+
This version finds the best match based on the content of the query.
|
| 48 |
+
"""
|
| 49 |
try:
|
| 50 |
+
# Lowercase the query for better matching
|
| 51 |
lower_query = user_query.lower()
|
| 52 |
+
|
| 53 |
+
# Encode the query and the segments
|
| 54 |
query_embedding = retrieval_model.encode(lower_query)
|
| 55 |
segment_embeddings = retrieval_model.encode(segments)
|
| 56 |
+
|
| 57 |
+
# Compute cosine similarities between the query and the segments
|
| 58 |
similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
|
| 59 |
+
|
| 60 |
+
# Find the index of the most similar segment
|
| 61 |
best_idx = similarities.argmax()
|
| 62 |
+
|
| 63 |
+
# Return the most relevant segment
|
| 64 |
return segments[best_idx]
|
| 65 |
except Exception as e:
|
| 66 |
print(f"Error in finding relevant segment: {e}")
|
| 67 |
return ""
|
| 68 |
|
| 69 |
def generate_response(user_query, relevant_segment):
|
| 70 |
+
"""
|
| 71 |
+
Generate a response emphasizing the bot's capability in providing therapy, destressing activites, and student opportunities information.
|
| 72 |
+
"""
|
| 73 |
try:
|
| 74 |
user_message = f"Here's the information on your request: {relevant_segment}"
|
| 75 |
+
|
| 76 |
+
# Append user's message to messages list
|
| 77 |
messages.append({"role": "user", "content": user_message})
|
| 78 |
|
| 79 |
response = openai.ChatCompletion.create(
|
|
|
|
| 86 |
presence_penalty=0.5,
|
| 87 |
)
|
| 88 |
|
| 89 |
+
# Extract the response text
|
| 90 |
output_text = response['choices'][0]['message']['content'].strip()
|
| 91 |
+
|
| 92 |
+
# Append assistant's message to messages list for context
|
| 93 |
messages.append({"role": "assistant", "content": output_text})
|
| 94 |
+
|
| 95 |
return output_text
|
| 96 |
|
| 97 |
except Exception as e:
|
|
|
|
| 99 |
return f"Error in generating response: {e}"
|
| 100 |
|
| 101 |
def query_model(question):
|
| 102 |
+
"""
|
| 103 |
+
Process a question, find relevant information, and generate a response.
|
| 104 |
+
"""
|
| 105 |
if question == "":
|
| 106 |
return "Welcome to CalmConnect's CalmBot! Ask me anything about destressing strategies and we'll provide you ways to unlock your inner calm!"
|
| 107 |
relevant_segment = find_relevant_segment(question, segments)
|
|
|
|
| 113 |
welcome_message = ""
|
| 114 |
topics = ""
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
theme = gr.themes.Default(
|
| 117 |
primary_hue="neutral",
|
| 118 |
secondary_hue="neutral",
|
|
|
|
| 129 |
button_primary_background_fill="#f8f1ea",
|
| 130 |
button_primary_background_fill_dark="#f8f1ea"
|
| 131 |
)
|
| 132 |
+
|
| 133 |
# Setup the Gradio Blocks interface with custom layout components
|
| 134 |
+
with gr.Blocks(theme=theme) as demo:
|
| 135 |
+
|
| 136 |
+
gr.Markdown(welcome_message) # Display the formatted welcome message
|
| 137 |
|
| 138 |
+
with gr.Row():
|
| 139 |
+
with gr.Column(scale=0.8):
|
| 140 |
+
gr.Markdown(topics)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# Show the topics on the left side
|
| 144 |
with gr.Row():
|
| 145 |
+
with gr.Column():
|
| 146 |
+
question = gr.Textbox(label="You", placeholder="What do you want to talk to CalmBot about?")
|
| 147 |
+
answer = gr.Textbox(label="CalmBot's Response :D", placeholder="CalmBot will respond here..", interactive=False, lines=20)
|
| 148 |
+
submit_button = gr.Button("Submit")
|
| 149 |
+
submit_button.click(fn=query_model, inputs=question, outputs=answer)
|
| 150 |
+
|
| 151 |
+
demo.launch()
|
|
|
|
|
|
|
| 152 |
|
| 153 |
# Launch the Gradio app to allow user interaction
|
| 154 |
demo.launch(share=True)
|
|
|