Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -47,79 +47,99 @@ st.markdown('<div class="blurred-background"></div>', unsafe_allow_html=True)
|
|
47 |
|
48 |
#""""""""""""""""""""""""" Application Code Starts here """""""""""""""""""""""""""""""""""""""""""""
|
49 |
|
50 |
-
#
|
51 |
-
|
52 |
-
|
|
|
53 |
|
54 |
-
|
55 |
-
"Authorization": f"Bearer {api_key}",
|
56 |
-
"Content-Type": "application/json"
|
57 |
-
}
|
58 |
|
59 |
-
#
|
60 |
@st.cache_resource
|
61 |
-
def
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
"frequency_penalty": 0.0,
|
69 |
-
"presence_penalty": 0.0,
|
70 |
-
"n": 1
|
71 |
-
}
|
72 |
-
response = requests.post(base_url, headers=headers, json=payload)
|
73 |
-
response.raise_for_status()
|
74 |
-
result = response.json()
|
75 |
-
return result["choices"][0]["text"].strip()
|
76 |
-
except Exception as e:
|
77 |
-
return f"Error querying the model: {e}"
|
78 |
|
79 |
-
#
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
@st.cache_resource
|
88 |
-
def
|
89 |
-
|
90 |
-
return load_dataset("Amod/mental_health_counseling_conversations")
|
91 |
|
92 |
-
|
93 |
|
94 |
-
#
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
st.markdown("---")
|
101 |
|
102 |
# User input for mental health concerns
|
103 |
-
user_input = st.text_area("
|
104 |
|
105 |
if st.button("Get Supportive Response"):
|
106 |
if user_input.strip():
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
|
|
|
|
115 |
else:
|
116 |
-
st.error("Please enter a
|
117 |
|
118 |
-
# Sidebar resources
|
119 |
-
st.sidebar.header("Additional
|
120 |
st.sidebar.markdown("""
|
121 |
- [Mental Health Foundation](https://www.mentalhealth.org)
|
122 |
- [Mind](https://www.mind.org.uk)
|
123 |
- [National Suicide Prevention Lifeline](https://suicidepreventionlifeline.org)
|
124 |
""")
|
125 |
-
st.sidebar.info("This application is not a replacement for professional counseling. If you
|
|
|
47 |
|
48 |
#""""""""""""""""""""""""" Application Code Starts here """""""""""""""""""""""""""""""""""""""""""""
|
49 |
|
50 |
+
# Load the dataset
|
51 |
+
@st.cache_resource
|
52 |
+
def load_counseling_dataset():
|
53 |
+
return load_dataset("Amod/mental_health_counseling_conversations")
|
54 |
|
55 |
+
dataset = load_counseling_dataset()
|
|
|
|
|
|
|
56 |
|
57 |
+
# Fine-tune the model and save it
|
58 |
@st.cache_resource
|
59 |
+
def fine_tune_model():
|
60 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, DataCollatorForLanguageModeling
|
61 |
+
|
62 |
+
# Load base model and tokenizer
|
63 |
+
model_name = "prabureddy/Mental-Health-FineTuned-Mistral-7B-Instruct-v0.2"
|
64 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
65 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
|
67 |
+
# Prepare dataset for training
|
68 |
+
def preprocess_function(examples):
|
69 |
+
return tokenizer(examples["context"] + "\n" + examples["response"], truncation=True)
|
70 |
+
|
71 |
+
tokenized_datasets = dataset.map(preprocess_function, batched=True)
|
72 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
|
73 |
+
|
74 |
+
# Training arguments
|
75 |
+
training_args = TrainingArguments(
|
76 |
+
output_dir="./fine_tuned_model",
|
77 |
+
evaluation_strategy="epoch",
|
78 |
+
learning_rate=2e-5,
|
79 |
+
per_device_train_batch_size=1,
|
80 |
+
num_train_epochs=3,
|
81 |
+
weight_decay=0.01,
|
82 |
+
save_total_limit=2,
|
83 |
+
save_strategy="epoch"
|
84 |
+
)
|
85 |
+
|
86 |
+
# Trainer
|
87 |
+
trainer = Trainer(
|
88 |
+
model=model,
|
89 |
+
args=training_args,
|
90 |
+
train_dataset=tokenized_datasets["train"],
|
91 |
+
eval_dataset=tokenized_datasets["validation"],
|
92 |
+
tokenizer=tokenizer,
|
93 |
+
data_collator=data_collator,
|
94 |
+
)
|
95 |
|
96 |
+
trainer.train()
|
97 |
+
|
98 |
+
# Save the fine-tuned model
|
99 |
+
trainer.save_model("./fine_tuned_model")
|
100 |
+
tokenizer.save_pretrained("./fine_tuned_model")
|
101 |
+
return "./fine_tuned_model"
|
102 |
+
|
103 |
+
# Load or fine-tune the model
|
104 |
+
model_dir = fine_tune_model()
|
105 |
+
|
106 |
+
# Load the fine-tuned model for inference
|
107 |
@st.cache_resource
|
108 |
+
def load_pipeline(model_dir):
|
109 |
+
return pipeline("text-generation", model=model_dir)
|
|
|
110 |
|
111 |
+
pipe = load_pipeline(model_dir)
|
112 |
|
113 |
+
# Streamlit App
|
114 |
+
st.title("Mental Health Support Assistant")
|
115 |
+
st.markdown("""
|
116 |
+
Welcome to the **Mental Health Support Assistant**.
|
117 |
+
This tool helps detect potential mental health concerns based on user input and provides **uplifting and positive suggestions** to boost morale.
|
118 |
+
""")
|
|
|
119 |
|
120 |
# User input for mental health concerns
|
121 |
+
user_input = st.text_area("Please share your concern:", placeholder="Type your question or concern here...")
|
122 |
|
123 |
if st.button("Get Supportive Response"):
|
124 |
if user_input.strip():
|
125 |
+
with st.spinner("Analyzing your input and generating a response..."):
|
126 |
+
try:
|
127 |
+
# Construct the messages for the pipeline
|
128 |
+
messages = [{"role": "user", "content": user_input}]
|
129 |
+
# Generate a response
|
130 |
+
response = pipe(messages)[0]["generated_text"]
|
131 |
+
st.subheader("Supportive Suggestion:")
|
132 |
+
st.markdown(f"**{response}**")
|
133 |
+
except Exception as e:
|
134 |
+
st.error(f"An error occurred while generating the response: {e}")
|
135 |
else:
|
136 |
+
st.error("Please enter a concern to receive suggestions.")
|
137 |
|
138 |
+
# Sidebar for additional resources
|
139 |
+
st.sidebar.header("Additional Resources")
|
140 |
st.sidebar.markdown("""
|
141 |
- [Mental Health Foundation](https://www.mentalhealth.org)
|
142 |
- [Mind](https://www.mind.org.uk)
|
143 |
- [National Suicide Prevention Lifeline](https://suicidepreventionlifeline.org)
|
144 |
""")
|
145 |
+
st.sidebar.info("This application is not a replacement for professional counseling. If you're in crisis, seek professional help immediately.")
|