Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Mental Health Chatbot Application
|
3 |
+
|
4 |
+
This module implements a mental health chatbot using LangChain and Hugging Face models.
|
5 |
+
The chatbot provides supportive and non-judgmental guidance to users struggling with
|
6 |
+
mental health issues.
|
7 |
+
|
8 |
+
Author: Vicky 111
|
9 |
+
Date: October 27, 2024
|
10 |
+
"""
|
11 |
+
|
12 |
+
import os
|
13 |
+
from typing import List, Optional, Tuple
|
14 |
+
|
15 |
+
import gradio as gr
|
16 |
+
from langchain.prompts import PromptTemplate
|
17 |
+
from langchain_community.llms import HuggingFaceEndpoint
|
18 |
+
from transformers import pipeline
|
19 |
+
|
20 |
+
# Configuration Constants
|
21 |
+
#DEFAULT_MODEL = "google/gemma-1.1-7b-it"
|
22 |
+
DEFAULT_MODEL = "meta-llama/Llama-3.2-3B"
|
23 |
+
MAX_NEW_TOKENS = 512
|
24 |
+
TOP_K = 5
|
25 |
+
TEMPERATURE = 0.2
|
26 |
+
REPETITION_PENALTY = 1.03
|
27 |
+
SUICIDE_HELPLINE = "+91 91529 87821"
|
28 |
+
|
29 |
+
class MentalHealthChatbot:
|
30 |
+
"""
|
31 |
+
A chatbot class specifically designed for mental health support and guidance.
|
32 |
+
|
33 |
+
This class handles the initialization of the language model and provides
|
34 |
+
methods for processing user inputs and generating appropriate responses.
|
35 |
+
"""
|
36 |
+
|
37 |
+
def __init__(
|
38 |
+
self,
|
39 |
+
model_id: str = DEFAULT_MODEL,
|
40 |
+
api_token: Optional[str] = None
|
41 |
+
) -> None:
|
42 |
+
"""
|
43 |
+
Initialize the chatbot with specified model and configurations.
|
44 |
+
|
45 |
+
Args:
|
46 |
+
model_id: The Hugging Face model identifier to use
|
47 |
+
api_token: Hugging Face API token for authentication
|
48 |
+
"""
|
49 |
+
self.api_token = api_token or os.getenv("HF_TOKEN")
|
50 |
+
if not self.api_token:
|
51 |
+
raise ValueError("Hugging Face API token not found")
|
52 |
+
|
53 |
+
self.llm = self._initialize_llm(model_id)
|
54 |
+
self.prompt_template = self._create_prompt_template()
|
55 |
+
|
56 |
+
def _initialize_llm(self, model_id: str) -> HuggingFaceEndpoint:
|
57 |
+
"""Initialize the language model with specified configurations."""
|
58 |
+
return HuggingFaceEndpoint(
|
59 |
+
repo_id=model_id,
|
60 |
+
task="text-generation",
|
61 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
62 |
+
top_k=TOP_K,
|
63 |
+
temperature=TEMPERATURE,
|
64 |
+
repetition_penalty=REPETITION_PENALTY,
|
65 |
+
huggingfacehub_api_token=self.api_token
|
66 |
+
)
|
67 |
+
|
68 |
+
def _create_prompt_template(self) -> PromptTemplate:
|
69 |
+
"""Create and return the prompt template for the chatbot."""
|
70 |
+
template = """
|
71 |
+
You are a Mental Health Chatbot named "CalmCompass", your purpose is to provide supportive and
|
72 |
+
non-judgmental guidance to users who are struggling with their mental health.
|
73 |
+
Your goal is to help users identify their concerns, offer resources and coping
|
74 |
+
strategies, and encourage them to seek professional help when needed.
|
75 |
+
If the user asks anything apart from mental health or speaks about other disesases,
|
76 |
+
or medical condition inform them polietly that you only respond to mental health related conversations
|
77 |
+
|
78 |
+
User Context: {context}
|
79 |
+
Question: {question}
|
80 |
+
|
81 |
+
Guidelines:
|
82 |
+
1. If symptoms are not mental health-related, clarify your scope
|
83 |
+
2. Ask relevant follow-up questions when needed (age, status, interests)
|
84 |
+
3. Provide motivation stories only when specifically needed
|
85 |
+
4. For suicidal thoughts, immediately provide the helpline: {suicide_helpline}
|
86 |
+
5. Always maintain a supportive, friendly and professional tone
|
87 |
+
|
88 |
+
Helpful Answer:
|
89 |
+
"""
|
90 |
+
return PromptTemplate(
|
91 |
+
input_variables=["context", "question", "suicide_helpline"],
|
92 |
+
template=template
|
93 |
+
)
|
94 |
+
|
95 |
+
def generate_response(
|
96 |
+
self,
|
97 |
+
message: str,
|
98 |
+
history: List[Tuple[str, str]]
|
99 |
+
) -> str:
|
100 |
+
"""
|
101 |
+
Generate a response based on the user's message and conversation history.
|
102 |
+
|
103 |
+
Args:
|
104 |
+
message: The user's input message
|
105 |
+
history: List of previous conversation turns
|
106 |
+
|
107 |
+
Returns:
|
108 |
+
str: The generated response from the chatbot
|
109 |
+
"""
|
110 |
+
try:
|
111 |
+
input_prompt = self.prompt_template.format(
|
112 |
+
question=message,
|
113 |
+
context=history,
|
114 |
+
suicide_helpline=SUICIDE_HELPLINE
|
115 |
+
)
|
116 |
+
result = self.llm.generate([input_prompt])
|
117 |
+
|
118 |
+
if result.generations:
|
119 |
+
return result.generations[0][0].text
|
120 |
+
return "I apologize, but I couldn't generate a response. Please try rephrasing your question."
|
121 |
+
|
122 |
+
except Exception as e:
|
123 |
+
print(f"Error generating response: {str(e)}")
|
124 |
+
return "I'm experiencing technical difficulties. Please try again later."
|
125 |
+
|
126 |
+
def main():
|
127 |
+
"""Initialize and launch the Gradio interface for the chatbot."""
|
128 |
+
try:
|
129 |
+
chatbot = MentalHealthChatbot()
|
130 |
+
interface = gr.ChatInterface(chatbot.generate_response)
|
131 |
+
interface.launch()
|
132 |
+
|
133 |
+
except Exception as e:
|
134 |
+
print(f"Failed to initialize chatbot: {str(e)}")
|
135 |
+
|
136 |
+
if __name__ == "__main__":
|
137 |
+
main()
|