Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from sentence_transformers import SentenceTransformer, util
|
| 3 |
-
import openai
|
| 4 |
-
import os
|
| 5 |
|
|
|
|
| 6 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 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 therapy, destressing activities, and student opportunities."
|
| 15 |
messages = [{"role": "system", "content": system_message}]
|
| 16 |
messages.append({
|
|
@@ -25,6 +26,7 @@ try:
|
|
| 25 |
except Exception as e:
|
| 26 |
print(f"Failed to load models: {e}")
|
| 27 |
|
|
|
|
| 28 |
def load_and_preprocess_text(filename):
|
| 29 |
try:
|
| 30 |
with open(filename, 'r', encoding='utf-8') as file:
|
|
@@ -35,8 +37,10 @@ def load_and_preprocess_text(filename):
|
|
| 35 |
print(f"Failed to load or preprocess text: {e}")
|
| 36 |
return []
|
| 37 |
|
|
|
|
| 38 |
segments = load_and_preprocess_text(filename)
|
| 39 |
|
|
|
|
| 40 |
def find_relevant_segment(user_query, segments):
|
| 41 |
try:
|
| 42 |
lower_query = user_query.lower()
|
|
@@ -49,43 +53,32 @@ def find_relevant_segment(user_query, segments):
|
|
| 49 |
print(f"Error in finding relevant segment: {e}")
|
| 50 |
return ""
|
| 51 |
|
|
|
|
| 52 |
def generate_response(user_query, relevant_segment):
|
| 53 |
try:
|
|
|
|
| 54 |
user_message = f"Here's the information on your request: {relevant_segment}"
|
| 55 |
messages.append({"role": "user", "content": user_message})
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
# Generate the response using the model
|
| 64 |
-
output = model.generate(
|
| 65 |
-
input_ids,
|
| 66 |
-
attention_mask=attention_mask,
|
| 67 |
-
max_length=150,
|
| 68 |
-
num_return_sequences=1,
|
| 69 |
-
pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id
|
| 70 |
)
|
| 71 |
|
| 72 |
-
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
|
| 75 |
-
messages.append({"role": "user", "content": user_message})
|
| 76 |
-
|
| 77 |
-
response = openai.ChatCompletion.create(
|
| 78 |
-
model="gpt-4o",
|
| 79 |
-
messages=messages,
|
| 80 |
-
max_tokens=4000,
|
| 81 |
-
temperature=0.5,
|
| 82 |
-
return output_text
|
| 83 |
|
| 84 |
except Exception as e:
|
| 85 |
print(f"Error in generating response: {e}")
|
| 86 |
return f"Error in generating response: {e}"
|
| 87 |
|
| 88 |
-
|
| 89 |
def query_model(question):
|
| 90 |
if question == "":
|
| 91 |
return "Welcome to CalmConnect! Ask me anything about destressing strategies or student opportunities. Feel free to talk to our online therapist!"
|
|
@@ -95,7 +88,7 @@ def query_model(question):
|
|
| 95 |
response = generate_response(question, relevant_segment)
|
| 96 |
return response
|
| 97 |
|
| 98 |
-
#
|
| 99 |
iframe = '''
|
| 100 |
<iframe style="border-radius:12px" src="https://docs.google.com/spreadsheets/d/e/2PACX-1vRroWVBXq1Fa0x7SvRTzSBMHFIp59VtVEWCxeg8kWJU4ll1_o4yzBnt4ArT88s7g4TQrMKEXZUQAeHF/pubhtml?widget=true&headers=false" width="100%" height="352" frameBorder="0" allowfullscreen="true" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading="lazy"></iframe>
|
| 101 |
'''
|
|
@@ -104,16 +97,11 @@ iframe2 = '''
|
|
| 104 |
<iframe style="border-radius:12px" src="https://open.spotify.com/embed/playlist/6wwxTePuIKYMqt6RCytB7X?utm_source=generator" width="100%" height="300" frameBorder="0" allowfullscreen="" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading="lazy"></iframe>
|
| 105 |
'''
|
| 106 |
|
| 107 |
-
|
| 108 |
-
# Define the welcome message and specific topics the chatbot can provide information about
|
| 109 |
welcome_message = """
|
| 110 |
<span style="color:#718355; font-size:24px; font-weight:bold;"> 🪷 Welcome to CalmConnect! 🪷</span>
|
| 111 |
"""
|
| 112 |
|
| 113 |
-
"""
|
| 114 |
-
## Your AI-driven assistant for destressing and extracurricular opportunity queries. Created by Olivia W, Alice T, and Cindy W of the 2024 Kode With Klossy CITY Camp.
|
| 115 |
-
"""
|
| 116 |
-
|
| 117 |
topics = """
|
| 118 |
### If you are interested in the following below, click on our Student Opportunities Database!
|
| 119 |
- Engineering
|
|
@@ -123,7 +111,7 @@ topics = """
|
|
| 123 |
- Law / Political Science / Debate
|
| 124 |
- The Arts
|
| 125 |
- Business / Leadership
|
| 126 |
-
-
|
| 127 |
- Medicine / Biology
|
| 128 |
- Literature / Writing
|
| 129 |
- College Prep
|
|
@@ -132,7 +120,7 @@ topics = """
|
|
| 132 |
- Study Abroad
|
| 133 |
"""
|
| 134 |
|
| 135 |
-
topics2= """
|
| 136 |
### Feel Free to ask CalmBot (Our Therapist Bot) anything from the topics below!
|
| 137 |
- Arts and Crafts (When asking for arts and crafts ideas, state whether you have 15 min, 30 min, 45 min, 1 hour, 1 hour and a half, 2 hours, 2 hours and a half, 3 hours or greater)
|
| 138 |
- Destressing strategies (Breathing Exercises, stretches, etc.)
|
|
@@ -145,14 +133,14 @@ topics2= """
|
|
| 145 |
- Support Resources
|
| 146 |
"""
|
| 147 |
|
| 148 |
-
#
|
| 149 |
def display_iframe():
|
| 150 |
return iframe
|
| 151 |
|
| 152 |
def display_iframe2():
|
| 153 |
return iframe2
|
| 154 |
|
| 155 |
-
|
| 156 |
theme = gr.themes.Default(
|
| 157 |
primary_hue="neutral",
|
| 158 |
secondary_hue="neutral",
|
|
@@ -169,39 +157,33 @@ theme = gr.themes.Default(
|
|
| 169 |
button_primary_background_fill="#f8f1ea",
|
| 170 |
button_primary_background_fill_dark="#f8f1ea"
|
| 171 |
)
|
| 172 |
-
|
| 173 |
-
#
|
| 174 |
with gr.Blocks(theme=theme) as demo:
|
| 175 |
gr.Image("CalmConnect.jpg", show_label=False, show_share_button=False, show_download_button=False)
|
| 176 |
-
gr.Markdown(welcome_message) # Display
|
| 177 |
-
|
| 178 |
with gr.Row():
|
| 179 |
with gr.Column():
|
| 180 |
-
gr.Markdown(topics) # Show
|
| 181 |
-
gr.HTML(iframe) # Embed
|
| 182 |
-
gr.HTML(iframe2) # Embed
|
| 183 |
-
|
| 184 |
with gr.Column():
|
| 185 |
-
gr.Markdown(topics2) # Show
|
| 186 |
with gr.Row():
|
| 187 |
with gr.Column():
|
| 188 |
question = gr.Textbox(label="You", placeholder="What do you want to talk to CalmBot about?")
|
| 189 |
-
answer = gr.Textbox(label="CalmBot's Response :D", placeholder="CalmBot will respond here
|
| 190 |
submit_button = gr.Button("Submit")
|
| 191 |
submit_button.click(fn=query_model, inputs=question, outputs=answer)
|
| 192 |
-
|
| 193 |
-
with gr.Row():
|
| 194 |
-
big_block = gr.HTML("### <button><a href='https://www.headspace.com/teens'>FREE: HEADSPACE FOR TEENS </a></button>")
|
| 195 |
-
big_block2 = gr.HTML("<button><a href='https://calmconnect-flower.replit.app/'>PLAY FLOWER GAME</a></button>")
|
| 196 |
-
big_block3 = gr.HTML("<button><a href='https://www.nyc.gov/site/doh/health/health-topics/teenspace.page'>NYC: TEENSPACE (free services)</a></button>")
|
| 197 |
-
big_block4 =gr.HTML("<button><a href='https://www.teenlife.com/blog/mental-health-resources-for-teens/'>TEEN MENTAL HEALTH RESOURCES (free services)</a></button>")
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
demo.launch()
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
-
# Launch the Gradio app
|
| 207 |
-
demo.launch(share=True)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import openai
|
| 3 |
import gradio as gr
|
| 4 |
from sentence_transformers import SentenceTransformer, util
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
# Set up environment and variables
|
| 7 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 8 |
+
openai.api_key = os.environ.get("OPENAI_API_KEY") # Make sure your API key is set in the environment
|
| 9 |
|
| 10 |
+
# File and model configurations
|
| 11 |
+
filename = "output_topic_details.txt" # File containing details for specific topics
|
| 12 |
+
retrieval_model_name = 'output/sentence-transformer-finetuned/' # Path to the fine-tuned model
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Define initial system message for the chatbot
|
| 15 |
system_message = "You are a comfort chatbot specialized in providing information on therapy, destressing activities, and student opportunities."
|
| 16 |
messages = [{"role": "system", "content": system_message}]
|
| 17 |
messages.append({
|
|
|
|
| 26 |
except Exception as e:
|
| 27 |
print(f"Failed to load models: {e}")
|
| 28 |
|
| 29 |
+
# Function to load and preprocess the text file
|
| 30 |
def load_and_preprocess_text(filename):
|
| 31 |
try:
|
| 32 |
with open(filename, 'r', encoding='utf-8') as file:
|
|
|
|
| 37 |
print(f"Failed to load or preprocess text: {e}")
|
| 38 |
return []
|
| 39 |
|
| 40 |
+
# Load the segments from the text file
|
| 41 |
segments = load_and_preprocess_text(filename)
|
| 42 |
|
| 43 |
+
# Function to find the most relevant segment from the file
|
| 44 |
def find_relevant_segment(user_query, segments):
|
| 45 |
try:
|
| 46 |
lower_query = user_query.lower()
|
|
|
|
| 53 |
print(f"Error in finding relevant segment: {e}")
|
| 54 |
return ""
|
| 55 |
|
| 56 |
+
# Function to generate a response using OpenAI's gpt-4
|
| 57 |
def generate_response(user_query, relevant_segment):
|
| 58 |
try:
|
| 59 |
+
# Construct the user message with relevant information
|
| 60 |
user_message = f"Here's the information on your request: {relevant_segment}"
|
| 61 |
messages.append({"role": "user", "content": user_message})
|
| 62 |
|
| 63 |
+
# Use OpenAI's API to generate a response
|
| 64 |
+
response = openai.ChatCompletion.create(
|
| 65 |
+
model="gpt-4",
|
| 66 |
+
messages=messages,
|
| 67 |
+
max_tokens=150,
|
| 68 |
+
temperature=0.7,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
)
|
| 70 |
|
| 71 |
+
# Extract and return the response from gpt-4
|
| 72 |
+
assistant_reply = response['choices'][0]['message']['content']
|
| 73 |
+
messages.append({"role": "assistant", "content": assistant_reply})
|
| 74 |
|
| 75 |
+
return assistant_reply
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
except Exception as e:
|
| 78 |
print(f"Error in generating response: {e}")
|
| 79 |
return f"Error in generating response: {e}"
|
| 80 |
|
| 81 |
+
# Function to process user queries
|
| 82 |
def query_model(question):
|
| 83 |
if question == "":
|
| 84 |
return "Welcome to CalmConnect! Ask me anything about destressing strategies or student opportunities. Feel free to talk to our online therapist!"
|
|
|
|
| 88 |
response = generate_response(question, relevant_segment)
|
| 89 |
return response
|
| 90 |
|
| 91 |
+
# HTML content for embedded resources
|
| 92 |
iframe = '''
|
| 93 |
<iframe style="border-radius:12px" src="https://docs.google.com/spreadsheets/d/e/2PACX-1vRroWVBXq1Fa0x7SvRTzSBMHFIp59VtVEWCxeg8kWJU4ll1_o4yzBnt4ArT88s7g4TQrMKEXZUQAeHF/pubhtml?widget=true&headers=false" width="100%" height="352" frameBorder="0" allowfullscreen="true" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading="lazy"></iframe>
|
| 94 |
'''
|
|
|
|
| 97 |
<iframe style="border-radius:12px" src="https://open.spotify.com/embed/playlist/6wwxTePuIKYMqt6RCytB7X?utm_source=generator" width="100%" height="300" frameBorder="0" allowfullscreen="" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading="lazy"></iframe>
|
| 98 |
'''
|
| 99 |
|
| 100 |
+
# Markdown content for welcome and topics sections
|
|
|
|
| 101 |
welcome_message = """
|
| 102 |
<span style="color:#718355; font-size:24px; font-weight:bold;"> 🪷 Welcome to CalmConnect! 🪷</span>
|
| 103 |
"""
|
| 104 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
topics = """
|
| 106 |
### If you are interested in the following below, click on our Student Opportunities Database!
|
| 107 |
- Engineering
|
|
|
|
| 111 |
- Law / Political Science / Debate
|
| 112 |
- The Arts
|
| 113 |
- Business / Leadership
|
| 114 |
+
- Psychology
|
| 115 |
- Medicine / Biology
|
| 116 |
- Literature / Writing
|
| 117 |
- College Prep
|
|
|
|
| 120 |
- Study Abroad
|
| 121 |
"""
|
| 122 |
|
| 123 |
+
topics2 = """
|
| 124 |
### Feel Free to ask CalmBot (Our Therapist Bot) anything from the topics below!
|
| 125 |
- Arts and Crafts (When asking for arts and crafts ideas, state whether you have 15 min, 30 min, 45 min, 1 hour, 1 hour and a half, 2 hours, 2 hours and a half, 3 hours or greater)
|
| 126 |
- Destressing strategies (Breathing Exercises, stretches, etc.)
|
|
|
|
| 133 |
- Support Resources
|
| 134 |
"""
|
| 135 |
|
| 136 |
+
# Function to display the embedded HTML content
|
| 137 |
def display_iframe():
|
| 138 |
return iframe
|
| 139 |
|
| 140 |
def display_iframe2():
|
| 141 |
return iframe2
|
| 142 |
|
| 143 |
+
# Setup Gradio interface with customized theme
|
| 144 |
theme = gr.themes.Default(
|
| 145 |
primary_hue="neutral",
|
| 146 |
secondary_hue="neutral",
|
|
|
|
| 157 |
button_primary_background_fill="#f8f1ea",
|
| 158 |
button_primary_background_fill_dark="#f8f1ea"
|
| 159 |
)
|
| 160 |
+
|
| 161 |
+
# Create Gradio interface layout
|
| 162 |
with gr.Blocks(theme=theme) as demo:
|
| 163 |
gr.Image("CalmConnect.jpg", show_label=False, show_share_button=False, show_download_button=False)
|
| 164 |
+
gr.Markdown(welcome_message) # Display welcome message
|
| 165 |
+
|
| 166 |
with gr.Row():
|
| 167 |
with gr.Column():
|
| 168 |
+
gr.Markdown(topics) # Show topics on the left
|
| 169 |
+
gr.HTML(iframe) # Embed iframe content
|
| 170 |
+
gr.HTML(iframe2) # Embed additional iframe content
|
| 171 |
+
|
| 172 |
with gr.Column():
|
| 173 |
+
gr.Markdown(topics2) # Show therapy topics on the right
|
| 174 |
with gr.Row():
|
| 175 |
with gr.Column():
|
| 176 |
question = gr.Textbox(label="You", placeholder="What do you want to talk to CalmBot about?")
|
| 177 |
+
answer = gr.Textbox(label="CalmBot's Response :D", placeholder="CalmBot will respond here...", interactive=False, lines=20)
|
| 178 |
submit_button = gr.Button("Submit")
|
| 179 |
submit_button.click(fn=query_model, inputs=question, outputs=answer)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
+
# Add additional HTML buttons for resources
|
| 182 |
+
with gr.Row():
|
| 183 |
+
gr.HTML("### <button><a href='https://www.headspace.com/teens'>FREE: HEADSPACE FOR TEENS </a></button>")
|
| 184 |
+
gr.HTML("<button><a href='https://calmconnect-flower.replit.app/'>PLAY FLOWER GAME</a></button>")
|
| 185 |
+
gr.HTML("<button><a href='https://www.nyc.gov/site/doh/health/health-topics/teenspace.page'>NYC: TEENSPACE (free services)</a></button>")
|
| 186 |
+
gr.HTML("<button><a href='https://www.teenlife.com/blog/mental-health-resources-for-teens/'>TEEN MENTAL HEALTH RESOURCES (free services)</a></button>")
|
| 187 |
|
| 188 |
+
# Launch the Gradio app
|
| 189 |
+
demo.launch(share=True)
|