Pant0x commited on
Commit
f5504e8
·
verified ·
1 Parent(s): fad696b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -46
app.py CHANGED
@@ -3,27 +3,18 @@ from huggingface_hub import InferenceClient
3
  import random
4
  import re
5
 
6
- # ✅ Keywords & Logic
7
- MENTAL_KEYWORDS = [
8
- "ocd", "adhd", "ptsd", "bipolar", "disorder", "anxiety", "depressed", "suicide",
9
- "panic", "stress", "lonely", "trauma", "mental", "therapy", "mood", "overwhelmed",
10
- "ana", "zahqan", "daye2", "mota3ab", "za3lan", "حزين", "تعبان", "قلق", "خايف"
11
- ]
12
 
13
- OFF_TOPIC = ["recipe", "code", "python", "crypto", "football", "نكتة", "طبخ", "كورة"]
 
 
 
 
 
 
 
14
 
15
- OFF_TOPIC_RESPONSES = [
16
- "I'm here to focus on your emotional well-being. How are you feeling today?",
17
- "Let’s talk about what’s on your mind emotionally.",
18
- ]
19
-
20
- def is_mental_health_related(text: str) -> bool:
21
- text_lower = text.lower()
22
- if any(word in text_lower for word in OFF_TOPIC): return False
23
- if any(word in text_lower for word in MENTAL_KEYWORDS): return True
24
- return bool(re.search(r"[\u0600-\u06FF]", text_lower))
25
-
26
- # ✅ The "Perfect" Respond Function
27
  def respond(
28
  message,
29
  history: list[dict[str, str]],
@@ -33,35 +24,34 @@ def respond(
33
  top_p,
34
  hf_token: gr.OAuthToken,
35
  ):
36
- if not is_mental_health_related(message):
37
- yield random.choice(OFF_TOPIC_RESPONSES)
 
38
  return
39
 
40
  if not hf_token:
41
- yield "Please log in via the Sidebar."
42
  return
43
 
 
44
  client = InferenceClient(token=hf_token.token, model="HuggingFaceH4/zephyr-7b-beta")
45
 
46
- # 1. SLIDING WINDOW MEMORY: Only take last 6 messages to prevent "infinite loops"
47
- trimmed_history = history[-6:]
48
-
49
  messages = [{"role": "system", "content": system_message}]
50
- messages.extend(trimmed_history)
51
  messages.append({"role": "user", "content": message})
52
 
53
  response = ""
54
  try:
55
- # 2. ADVANCED PARAMETERS: Adding repetition penalty to the extra_body
56
  for msg in client.chat_completion(
57
  messages,
58
  max_tokens=max_tokens,
59
  stream=True,
60
- temperature=max(temperature, 0.1), # Avoid 0
61
- top_p=top_p,
62
- stop=["User:", "Assistant:"], # Prevents model from talking to itself
63
  extra_body={
64
- "repetition_penalty": 1.15,
65
  "presence_penalty": 0.3
66
  }
67
  ):
@@ -69,31 +59,37 @@ def respond(
69
  response += token
70
  yield response
71
  except Exception as e:
72
- yield f"API Error: {str(e)}. Try refreshing or checking your HF token."
73
 
74
- # ✅ Optimized Interface
75
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
76
  with gr.Sidebar():
77
- gr.Markdown("### 🛠 Settings")
78
  gr.LoginButton()
79
  gr.Markdown("---")
80
- st_msg = gr.Textbox(
81
- value="You are a compassionate mental health assistant. Respond to the user's specific problem IMMEDIATELY. No generic intros. Tone: Empathetic & Short.",
82
- label="System Prompt",
83
- lines=4
 
 
 
 
 
 
84
  )
85
- tokens = gr.Slider(128, 1024, value=512, label="Max Tokens")
86
- temp = gr.Slider(0.1, 1.5, value=0.7, label="Temperature (Randomness)")
87
- top_p_slider = gr.Slider(0.1, 1.0, value=0.9, label="Top-p (Focus)")
88
 
89
  chatbot_ui = gr.ChatInterface(
90
  respond,
91
  type="messages",
92
- additional_inputs=[st_msg, tokens, temp, top_p_slider],
93
  examples=[
94
- ["I've been feeling very anxious lately.", st_msg.value, 512, 0.7, 0.9],
95
- ["How do I deal with OCD thoughts?", st_msg.value, 512, 0.7, 0.9],
96
- ["Ana ta3ban awee.", st_msg.value, 512, 0.7, 0.9]
97
  ],
98
  cache_examples=False,
99
  )
 
3
  import random
4
  import re
5
 
6
+ # ✅ Smart Detection: Only blocks obvious garbage (ads/links/spam), everything else goes to AI
7
+ OFF_TOPIC_REGEX = r"(http|www|buy now|discount|subscribe|follow me|click here)"
 
 
 
 
8
 
9
+ def is_safe_to_process(text: str) -> bool:
10
+ # If it's a very short message with no meaning, we use a friendly nudge
11
+ if len(text.strip()) < 2:
12
+ return False
13
+ # If it matches spam patterns
14
+ if re.search(OFF_TOPIC_REGEX, text.lower()):
15
+ return False
16
+ return True
17
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  def respond(
19
  message,
20
  history: list[dict[str, str]],
 
24
  top_p,
25
  hf_token: gr.OAuthToken,
26
  ):
27
+ # 1. Basic Safety Check
28
+ if not is_safe_to_process(message):
29
+ yield "I'm here to listen and support your emotional well-being. How can I help you today?"
30
  return
31
 
32
  if not hf_token:
33
+ yield "Please log in via the Sidebar to start our session."
34
  return
35
 
36
+ # 2. Using Zephyr-7B: Faster, smarter, and doesn't 'hang' on free tier
37
  client = InferenceClient(token=hf_token.token, model="HuggingFaceH4/zephyr-7b-beta")
38
 
39
+ # 3. Memory Management: Last 8 messages to keep the context sharp but fast
 
 
40
  messages = [{"role": "system", "content": system_message}]
41
+ messages.extend(history[-8:])
42
  messages.append({"role": "user", "content": message})
43
 
44
  response = ""
45
  try:
46
+ # 4. Perfect Parameters for ChatGPT-like flow
47
  for msg in client.chat_completion(
48
  messages,
49
  max_tokens=max_tokens,
50
  stream=True,
51
+ temperature=0.7, # The "Sweet Spot"
52
+ top_p=0.9,
 
53
  extra_body={
54
+ "repetition_penalty": 1.15, # Stops the "I specialize in..." loop
55
  "presence_penalty": 0.3
56
  }
57
  ):
 
59
  response += token
60
  yield response
61
  except Exception as e:
62
+ yield f"Connection error: {str(e)}. Please try refreshing the page."
63
 
64
+ # ✅ Professional UI Setup
65
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
66
  with gr.Sidebar():
67
+ gr.Markdown("## 🌿 Therapy Assistant Settings")
68
  gr.LoginButton()
69
  gr.Markdown("---")
70
+ sys_msg = gr.Textbox(
71
+ value=(
72
+ "You are a professional mental health assistant. "
73
+ "1. Respond directly to the user's specific problem in the first sentence. "
74
+ "2. Be empathetic but professional. "
75
+ "3. If the user mentions symptoms (like washing hands), explain them gently as a supportive peer. "
76
+ "4. Never use a repetitive introductory phrase."
77
+ ),
78
+ label="System Persona",
79
+ lines=6
80
  )
81
+ tokens = gr.Slider(128, 1024, value=512, label="Response Length")
82
+ temp = gr.Slider(0.1, 1.5, value=0.7, label="Empathy Level (Temperature)")
83
+ top_p_val = gr.Slider(0.1, 1.0, value=0.9, label="Focus (Top-p)")
84
 
85
  chatbot_ui = gr.ChatInterface(
86
  respond,
87
  type="messages",
88
+ additional_inputs=[sys_msg, tokens, temp, top_p_val],
89
  examples=[
90
+ ["I think my sister has OCD, she washes her hands constantly.", sys_msg.value, 512, 0.7, 0.9],
91
+ ["Ana 7ases b de2 fashkh w msh 3aref anam.", sys_msg.value, 512, 0.7, 0.9],
92
+ ["I've been feeling very lonely lately.", sys_msg.value, 512, 0.7, 0.9]
93
  ],
94
  cache_examples=False,
95
  )