allyyy commited on
Commit
09ab37f
·
verified ·
1 Parent(s): 5c29029

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -109
app.py CHANGED
@@ -1,33 +1,35 @@
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({
18
- "role": "system",
19
- "content": "Do not use Markdown Format. Do not include hashtags or asterisks"
20
  })
21
 
22
- # Load the retrieval model
23
  try:
24
  retrieval_model = SentenceTransformer(retrieval_model_name)
25
  print("Models loaded successfully.")
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:
33
  segments = [line.strip() for line in file if line.strip()]
@@ -37,110 +39,80 @@ def load_and_preprocess_text(filename):
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()
 
 
47
  query_embedding = retrieval_model.encode(lower_query)
48
  segment_embeddings = retrieval_model.encode(segments)
 
 
49
  similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
 
 
50
  best_idx = similarities.argmax()
 
 
51
  return segments[best_idx]
52
  except Exception as e:
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-4o",
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!"
85
  relevant_segment = find_relevant_segment(question, segments)
86
  if not relevant_segment:
87
  return "Could not find specific information. Please refine your question or head to our resources page."
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&amp;headers=false" width="100%" height="352" frameBorder="0" allowfullscreen="true" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading="lazy"></iframe>
94
- '''
95
-
96
- iframe2 = '''
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
108
- - Technology / Computer Science
109
- - Research : STEM
110
- - Finance
111
- - Law / Political Science / Debate
112
- - The Arts
113
- - Business / Leadership
114
- - Psychology
115
- - Medicine / Biology
116
- - Literature / Writing
117
- - College Prep
118
- - Advocacy: Non-Profit, Environment or Identity
119
- - Volunteering
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.)
127
- - Mental Health
128
- - Identity (Sexual, Gender, etc.)
129
- - Bullying
130
- - Racism
131
- - Relationships (Family, Friends, etc.)
132
- - Abuse (Emotional, Physical, Sexual, Mental, 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,33 +129,32 @@ theme = gr.themes.Default(
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)
 
 
 
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
+ # 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.")
26
  except Exception as e:
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()]
 
39
  print(f"Failed to load or preprocess text: {e}")
40
  return []
41
 
 
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(
80
+ model="gpt-4",
81
  messages=messages,
82
+ max_tokens=4000,
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'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)
108
  if not relevant_segment:
109
  return "Could not find specific information. Please refine your question or head to our resources page."
110
  response = generate_response(question, relevant_segment)
111
  return response
112
 
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
+
152
+
153
+ demo.launch()
154
+
155
+
156
+
157
+
 
158
 
159
+ # Launch the Gradio app to allow user interaction
160
  demo.launch(share=True)