Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from sentence_transformers import SentenceTransformer, util
|
| 3 |
-
|
| 4 |
import os
|
| 5 |
|
| 6 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
@@ -9,17 +9,14 @@ os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
| 9 |
filename = "output_topic_details.txt" # Path to the file storing destress-specific details
|
| 10 |
retrieval_model_name = 'output/sentence-transformer-finetuned/'
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
gpt2_model_name = "gpt2"
|
| 14 |
-
tokenizer = GPT2Tokenizer.from_pretrained(gpt2_model_name)
|
| 15 |
-
gpt2_model = GPT2LMHeadModel.from_pretrained(gpt2_model_name)
|
| 16 |
|
|
|
|
| 17 |
# Initial system message to set the behavior of the assistant
|
| 18 |
-
system_message = "You are a comfort chatbot specialized in providing information on therapy, destressing activities, and student opportunities."
|
| 19 |
messages = [{"role": "system", "content": system_message}]
|
| 20 |
messages.append({
|
| 21 |
-
|
| 22 |
-
|
| 23 |
})
|
| 24 |
|
| 25 |
# Attempt to load the necessary models and provide feedback on success or failure
|
|
@@ -30,7 +27,9 @@ except Exception as e:
|
|
| 30 |
print(f"Failed to load models: {e}")
|
| 31 |
|
| 32 |
def load_and_preprocess_text(filename):
|
| 33 |
-
"""
|
|
|
|
|
|
|
| 34 |
try:
|
| 35 |
with open(filename, 'r', encoding='utf-8') as file:
|
| 36 |
segments = [line.strip() for line in file if line.strip()]
|
|
@@ -43,7 +42,10 @@ def load_and_preprocess_text(filename):
|
|
| 43 |
segments = load_and_preprocess_text(filename)
|
| 44 |
|
| 45 |
def find_relevant_segment(user_query, segments):
|
| 46 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 47 |
try:
|
| 48 |
# Lowercase the query for better matching
|
| 49 |
lower_query = user_query.lower()
|
|
@@ -65,31 +67,41 @@ def find_relevant_segment(user_query, segments):
|
|
| 65 |
return ""
|
| 66 |
|
| 67 |
def generate_response(user_query, relevant_segment):
|
| 68 |
-
"""
|
|
|
|
|
|
|
| 69 |
try:
|
| 70 |
-
user_message = f"Here's the information on your request: {relevant_segment}
|
| 71 |
-
|
| 72 |
-
#
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
| 80 |
)
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
#
|
| 83 |
-
|
| 84 |
|
| 85 |
-
return output_text
|
| 86 |
|
| 87 |
except Exception as e:
|
| 88 |
print(f"Error in generating response: {e}")
|
| 89 |
return f"Error in generating response: {e}"
|
| 90 |
|
| 91 |
def query_model(question):
|
| 92 |
-
"""
|
|
|
|
|
|
|
| 93 |
if question == "":
|
| 94 |
return "Welcome to CalmConnect! Ask me anything about destressing strategies or student opportunities. Feel free to talk to our online therapist!"
|
| 95 |
relevant_segment = find_relevant_segment(question, segments)
|
|
@@ -107,11 +119,16 @@ iframe2 = '''
|
|
| 107 |
<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>
|
| 108 |
'''
|
| 109 |
|
|
|
|
| 110 |
# Define the welcome message and specific topics the chatbot can provide information about
|
| 111 |
welcome_message = """
|
| 112 |
<span style="color:#718355; font-size:24px; font-weight:bold;"> 🪷 Welcome to CalmConnect! 🪷</span>
|
| 113 |
"""
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
topics = """
|
| 116 |
### If you are interested in the following below, click on our Student Opportunities Database!
|
| 117 |
- Engineering
|
|
@@ -121,7 +138,7 @@ topics = """
|
|
| 121 |
- Law / Political Science / Debate
|
| 122 |
- The Arts
|
| 123 |
- Business / Leadership
|
| 124 |
-
-
|
| 125 |
- Medicine / Biology
|
| 126 |
- Literature / Writing
|
| 127 |
- College Prep
|
|
@@ -192,10 +209,7 @@ with gr.Blocks(theme=theme) as demo:
|
|
| 192 |
big_block = gr.HTML("### <button><a href='https://www.headspace.com/teens'>FREE: HEADSPACE FOR TEENS </a></button>")
|
| 193 |
big_block2 = gr.HTML("<button><a href='https://calmconnect-flower.replit.app/'>PLAY FLOWER GAME</a></button>")
|
| 194 |
big_block3 = gr.HTML("<button><a href='https://www.nyc.gov/site/doh/health/health-topics/teenspace.page'>NYC: TEENSPACE (free services)</a></button>")
|
| 195 |
-
big_block4 =
|
| 196 |
-
|
| 197 |
-
# Launch the Gradio app to
|
| 198 |
-
|
| 199 |
|
| 200 |
|
| 201 |
demo.launch()
|
|
|
|
| 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"
|
|
|
|
| 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 therapy, destressing activites, and student opportunities."
|
| 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
|
|
|
|
| 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()
|
|
|
|
| 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(
|
| 80 |
+
model="gpt-3.5-turbo", # or "gpt-4" if you have access
|
| 81 |
+
messages=messages,
|
| 82 |
+
max_tokens=500,
|
| 83 |
+
temperature=0.5,
|
| 84 |
+
top_p=1,
|
| 85 |
+
frequency_penalty=0.5,
|
| 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:
|
| 98 |
print(f"Error in generating response: {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! Ask me anything about destressing strategies or student opportunities. Feel free to talk to our online therapist!"
|
| 107 |
relevant_segment = find_relevant_segment(question, segments)
|
|
|
|
| 119 |
<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>
|
| 120 |
'''
|
| 121 |
|
| 122 |
+
|
| 123 |
# Define the welcome message and specific topics the chatbot can provide information about
|
| 124 |
welcome_message = """
|
| 125 |
<span style="color:#718355; font-size:24px; font-weight:bold;"> 🪷 Welcome to CalmConnect! 🪷</span>
|
| 126 |
"""
|
| 127 |
|
| 128 |
+
"""
|
| 129 |
+
## 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.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
topics = """
|
| 133 |
### If you are interested in the following below, click on our Student Opportunities Database!
|
| 134 |
- Engineering
|
|
|
|
| 138 |
- Law / Political Science / Debate
|
| 139 |
- The Arts
|
| 140 |
- Business / Leadership
|
| 141 |
+
- Pyschology
|
| 142 |
- Medicine / Biology
|
| 143 |
- Literature / Writing
|
| 144 |
- College Prep
|
|
|
|
| 209 |
big_block = gr.HTML("### <button><a href='https://www.headspace.com/teens'>FREE: HEADSPACE FOR TEENS </a></button>")
|
| 210 |
big_block2 = gr.HTML("<button><a href='https://calmconnect-flower.replit.app/'>PLAY FLOWER GAME</a></button>")
|
| 211 |
big_block3 = gr.HTML("<button><a href='https://www.nyc.gov/site/doh/health/health-topics/teenspace.page'>NYC: TEENSPACE (free services)</a></button>")
|
| 212 |
+
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>")
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
|
| 215 |
demo.launch()
|