allyyy commited on
Commit
c9037a3
·
verified ·
1 Parent(s): 85ad16f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -49
app.py CHANGED
@@ -1,6 +1,6 @@
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,14 +9,17 @@ 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,9 +30,7 @@ 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()]
@@ -42,10 +43,7 @@ def load_and_preprocess_text(filename):
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,41 +65,31 @@ def find_relevant_segment(user_query, segments):
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,16 +107,11 @@ iframe2 = '''
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,7 +121,7 @@ topics = """
138
  - Law / Political Science / Debate
139
  - The Arts
140
  - Business / Leadership
141
- - Pyschology
142
  - Medicine / Biology
143
  - Literature / Writing
144
  - College Prep
@@ -158,11 +141,6 @@ topics2= """
158
  - Relationships (Family, Friends, etc.)
159
  - Abuse (Emotional, Physical, Sexual, Mental, etc.)
160
  - Support Resources
161
-
162
-
163
-
164
-
165
-
166
  """
167
 
168
  # Create a Gradio HTML component
@@ -214,7 +192,10 @@ with gr.Blocks(theme=theme) as demo:
214
  big_block = gr.HTML("### <button><a href='https://www.headspace.com/teens'>FREE: HEADSPACE FOR TEENS </a></button>")
215
  big_block2 = gr.HTML("<button><a href='https://calmconnect-flower.replit.app/'>PLAY FLOWER GAME</a></button>")
216
  big_block3 = gr.HTML("<button><a href='https://www.nyc.gov/site/doh/health/health-topics/teenspace.page'>NYC: TEENSPACE (free services)</a></button>")
217
- 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>")
 
 
 
218
 
219
 
220
  demo.launch()
 
1
  import gradio as gr
2
  from sentence_transformers import SentenceTransformer, util
3
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer
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
+ # Load GPT-2 model and tokenizer
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
+ "role": "system",
22
+ "content": "Do not use Markdown Format. Do not include hashtags or asterisks"
23
  })
24
 
25
  # Attempt to load the necessary models and provide feedback on success or failure
 
30
  print(f"Failed to load models: {e}")
31
 
32
  def load_and_preprocess_text(filename):
33
+ """Load and preprocess text from a file, removing empty lines and stripping whitespace."""
 
 
34
  try:
35
  with open(filename, 'r', encoding='utf-8') as file:
36
  segments = [line.strip() for line in file if line.strip()]
 
43
  segments = load_and_preprocess_text(filename)
44
 
45
  def find_relevant_segment(user_query, segments):
46
+ """Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings."""
 
 
 
47
  try:
48
  # Lowercase the query for better matching
49
  lower_query = user_query.lower()
 
65
  return ""
66
 
67
  def generate_response(user_query, relevant_segment):
68
+ """Generate a response using GPT-2 emphasizing the bot's capability in providing therapy, destressing activities, and student opportunities information."""
 
 
69
  try:
70
+ user_message = f"Here's the information on your request: {relevant_segment}. Now I will elaborate:"
71
+
72
+ # Encode the input text and generate a response
73
+ input_ids = tokenizer.encode(user_message, return_tensors='pt')
74
+ output = gpt2_model.generate(
75
+ input_ids,
76
+ max_length=500,
77
+ num_return_sequences=1,
78
+ no_repeat_ngram_size=2,
79
+ early_stopping=True
 
 
 
80
  )
 
 
 
81
 
82
+ # Decode the generated response
83
+ output_text = tokenizer.decode(output[0], skip_special_tokens=True)
84
 
85
+ return output_text.strip()
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
+ """Process a question, find relevant information, and generate a response."""
 
 
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
  <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
  - Law / Political Science / Debate
122
  - The Arts
123
  - Business / Leadership
124
+ - Psychology
125
  - Medicine / Biology
126
  - Literature / Writing
127
  - College Prep
 
141
  - Relationships (Family, Friends, etc.)
142
  - Abuse (Emotional, Physical, Sexual, Mental, etc.)
143
  - Support Resources
 
 
 
 
 
144
  """
145
 
146
  # Create a Gradio HTML component
 
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 = gr.HTML("<button><a href='https://www.teenlife.com/blog/mental-health-resources-for-teens/'>TEEN MENTAL HEALTH RESOURCES (free services)</a></button>")
196
+
197
+ # Launch the Gradio app to
198
+
199
 
200
 
201
  demo.launch()