Pant0x commited on
Commit
99728d3
·
verified ·
1 Parent(s): b3fb7c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -69
app.py CHANGED
@@ -3,7 +3,7 @@ from huggingface_hub import InferenceClient
3
  import random
4
  import re
5
 
6
- # ✅ Allowed mental health keywords (EN + AR + transliterated Arabic)
7
  MENTAL_KEYWORDS = [
8
  # English
9
  "depression", "depressed", "anxiety", "anxious", "panic", "stress", "sad", "lonely",
@@ -12,6 +12,8 @@ MENTAL_KEYWORDS = [
12
  "relax", "calm", "sleep", "emotion", "feeling", "feel", "thoughts", "help", "life", "advice",
13
  "unmotivated", "lost", "hopeless", "tired", "burnout", "cry", "hurt", "love", "breakup",
14
  "friend", "family", "alone", "heartbroken", "scared", "fearful",
 
 
15
  # Transliterated Arabic
16
  "ana", "zahqan", "daye2", "ha2t", "mota3ab", "mota3eb", "za3lan", "malo", "khalni", "mash3or",
17
  "bakhaf", "w7ed", "msh 3aref", "mash fahem", "malish", "3ayez", "ayez", "7azeen", "mdaye2",
@@ -20,55 +22,38 @@ MENTAL_KEYWORDS = [
20
  "مشاعر", "مضغوط", "قلقان", "وحدي", "مش مبسوط", "زهقان", "ضايق", "تعب", "مش مرتاح",
21
  ]
22
 
23
- # ✅ Off-topic keywords (EN + AR)
24
  OFF_TOPIC = [
25
- # English
26
  "recipe", "song", "music", "lyrics", "joke", "funny", "laugh", "code", "python", "program",
27
  "game", "food", "cook", "movie", "film", "series", "sport", "football", "instagram",
28
  "tiktok", "money", "business", "crypto", "ai", "computer",
29
- # Arabic
30
  "نكتة", "ضحك", "اغنية", "اغاني", "طبخ", "اكل", "فيلم", "مسلسل", "كورة", "رياضة",
31
  "بيزنس", "فلوس", "العاب", "لعبة", "كود", "برمجة", "ذكاء اصطناعي"
32
  ]
33
 
34
- # ✅ Random natural off-topic responses
35
  OFF_TOPIC_RESPONSES = [
36
- "I'm here to help with emotional and mental well-being. Let's focus on how you're feeling, coping, or managing your emotions today.",
37
- "I specialize in mental and emotional health conversations. Tell me what’s been on your mind lately.",
38
- "Let’s bring it back to how you’ve been feeling — I’m here to help you talk through emotions, stress, or challenges.",
39
- "My goal is to support your mental health. How have things been emotionally for you lately?",
40
- "I’m here for emotional and mental support only. What’s been bothering you recently?",
41
- "Let's focus on your thoughts and feelings — I can help you process or manage them better.",
42
- "It sounds like you might be going off-topic. Can we talk about how you’ve been feeling instead?",
43
- "Let’s keep this space focused on your emotions and well-being. What’s been heavy on your mind lately?",
44
  ]
45
 
46
- # ✅ Detect Arabic characters
47
  def contains_arabic(text: str) -> bool:
48
  return bool(re.search(r"[\u0600-\u06FF]", text))
49
 
50
- # ✅ Function to check if input is related to mental health
51
  def is_mental_health_related(text: str) -> bool:
52
  text_lower = text.lower()
53
- has_arabic = contains_arabic(text_lower)
54
-
55
- # If message includes off-topic Arabic or English terms → block it
56
  if any(word in text_lower for word in OFF_TOPIC):
57
  return False
58
-
59
- # If it has mental-related Arabic/English → allow
60
  if any(word in text_lower for word in MENTAL_KEYWORDS):
61
  return True
62
-
63
- # If purely Arabic but not off-topic → assume emotional (allow)
64
- if has_arabic:
65
  return True
66
-
67
- # Default fallback
68
  return False
69
 
70
-
71
- # ✅ Main response function
72
  def respond(
73
  message,
74
  history: list[dict[str, str]],
@@ -78,61 +63,57 @@ def respond(
78
  top_p,
79
  hf_token: gr.OAuthToken,
80
  ):
 
81
  if not is_mental_health_related(message):
82
  yield random.choice(OFF_TOPIC_RESPONSES)
83
  return
84
 
85
- locked_system_message = (
86
- "You are a licensed mental health therapy assistant. "
87
- "You respond with empathy, emotional intelligence, and a therapeutic tone. "
88
- "Never answer questions unrelated to emotional or mental wellness, even if they are in another language."
89
- )
90
 
91
  client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
92
 
93
- messages = [{"role": "system", "content": locked_system_message}]
 
94
  messages.extend(history)
95
  messages.append({"role": "user", "content": message})
96
 
 
97
  response = ""
98
-
99
- for message in client.chat_completion(
100
- messages,
101
- max_tokens=max_tokens,
102
- stream=True,
103
- temperature=temperature,
104
- top_p=top_p,
105
- ):
106
- choices = message.choices
107
- token = ""
108
- if len(choices) and choices[0].delta.content:
109
- token = choices[0].delta.content
110
- response += token
111
- yield response
112
-
113
-
114
- # ✅ Gradio interface setup
115
- chatbot = gr.ChatInterface(
116
- respond,
117
- type="messages",
118
- additional_inputs=[
119
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
120
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
121
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
122
- gr.Slider(
123
- minimum=0.1,
124
- maximum=1.0,
125
- value=0.95,
126
- step=0.05,
127
- label="Top-p (nucleus sampling)",
128
- ),
129
- ],
130
- )
131
-
132
  with gr.Blocks() as demo:
133
  with gr.Sidebar():
134
  gr.LoginButton()
135
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
  if __name__ == "__main__":
138
- demo.launch()
 
3
  import random
4
  import re
5
 
6
+ # ✅ Expanded mental health keywords to include common disorders (fixes the OCD bug)
7
  MENTAL_KEYWORDS = [
8
  # English
9
  "depression", "depressed", "anxiety", "anxious", "panic", "stress", "sad", "lonely",
 
12
  "relax", "calm", "sleep", "emotion", "feeling", "feel", "thoughts", "help", "life", "advice",
13
  "unmotivated", "lost", "hopeless", "tired", "burnout", "cry", "hurt", "love", "breakup",
14
  "friend", "family", "alone", "heartbroken", "scared", "fearful",
15
+ # Specific Disorders & Mental Health Terms
16
+ "ocd", "adhd", "ptsd", "bipolar", "disorder", "eating disorder", "schizophrenia", "borderline",
17
  # Transliterated Arabic
18
  "ana", "zahqan", "daye2", "ha2t", "mota3ab", "mota3eb", "za3lan", "malo", "khalni", "mash3or",
19
  "bakhaf", "w7ed", "msh 3aref", "mash fahem", "malish", "3ayez", "ayez", "7azeen", "mdaye2",
 
22
  "مشاعر", "مضغوط", "قلقان", "وحدي", "مش مبسوط", "زهقان", "ضايق", "تعب", "مش مرتاح",
23
  ]
24
 
25
+ # ✅ Off-topic keywords
26
  OFF_TOPIC = [
 
27
  "recipe", "song", "music", "lyrics", "joke", "funny", "laugh", "code", "python", "program",
28
  "game", "food", "cook", "movie", "film", "series", "sport", "football", "instagram",
29
  "tiktok", "money", "business", "crypto", "ai", "computer",
 
30
  "نكتة", "ضحك", "اغنية", "اغاني", "طبخ", "اكل", "فيلم", "مسلسل", "كورة", "رياضة",
31
  "بيزنس", "فلوس", "العاب", "لعبة", "كود", "برمجة", "ذكاء اصطناعي"
32
  ]
33
 
 
34
  OFF_TOPIC_RESPONSES = [
35
+ "I'm here to help with emotional and mental well-being. Let's focus on how you're feeling today.",
36
+ "I specialize in mental and emotional health. What’s been on your mind lately?",
37
+ "Let’s bring it back to your well-being — I’m here to help you talk through emotions.",
38
+ "My goal is to support your mental health. How have things been emotionally for you?",
 
 
 
 
39
  ]
40
 
 
41
  def contains_arabic(text: str) -> bool:
42
  return bool(re.search(r"[\u0600-\u06FF]", text))
43
 
 
44
  def is_mental_health_related(text: str) -> bool:
45
  text_lower = text.lower()
46
+ # Check off-topic first
 
 
47
  if any(word in text_lower for word in OFF_TOPIC):
48
  return False
49
+ # Check keywords
 
50
  if any(word in text_lower for word in MENTAL_KEYWORDS):
51
  return True
52
+ # Default to true if Arabic characters are present to avoid blocking natural dialect
53
+ if contains_arabic(text_lower):
 
54
  return True
 
 
55
  return False
56
 
 
 
57
  def respond(
58
  message,
59
  history: list[dict[str, str]],
 
63
  top_p,
64
  hf_token: gr.OAuthToken,
65
  ):
66
+ # 1. Check if input is blocked by local logic
67
  if not is_mental_health_related(message):
68
  yield random.choice(OFF_TOPIC_RESPONSES)
69
  return
70
 
71
+ # 2. Connect to model
72
+ if not hf_token:
73
+ yield "Please log in to use the chatbot."
74
+ return
 
75
 
76
  client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
77
 
78
+ # 3. Build message list (Using the UI's system message)
79
+ messages = [{"role": "system", "content": system_message}]
80
  messages.extend(history)
81
  messages.append({"role": "user", "content": message})
82
 
83
+ # 4. Stream response
84
  response = ""
85
+ try:
86
+ for msg in client.chat_completion(
87
+ messages,
88
+ max_tokens=max_tokens,
89
+ stream=True,
90
+ temperature=temperature,
91
+ top_p=top_p,
92
+ ):
93
+ token = msg.choices[0].delta.content or ""
94
+ response += token
95
+ yield response
96
+ except Exception as e:
97
+ yield f"An error occurred: {str(e)}"
98
+
99
+ # ✅ Gradio Interface Setup
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  with gr.Blocks() as demo:
101
  with gr.Sidebar():
102
  gr.LoginButton()
103
+
104
+ chatbot = gr.ChatInterface(
105
+ respond,
106
+ type="messages",
107
+ additional_inputs=[
108
+ gr.Textbox(
109
+ value="You are a compassionate mental health assistant. Prioritize the user's specific concern in your first sentence. Do not repeat a generic intro if the user shares a problem. Always validate feelings.",
110
+ label="System message"
111
+ ),
112
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
113
+ gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
114
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p"),
115
+ ],
116
+ )
117
 
118
  if __name__ == "__main__":
119
+ demo.launch()