tahirsher commited on
Commit
26768c0
·
verified ·
1 Parent(s): be722e2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -56
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
- # Groq API Configuration
51
- api_key = os.environ.get("LawersGuideAPIKey") # Ensure GROQ_API_KEY is set in your environment variables
52
- base_url = "https://api.groq.com/openai/v1/models/google/gemma-2-9b-it/completions"
 
53
 
54
- headers = {
55
- "Authorization": f"Bearer {api_key}",
56
- "Content-Type": "application/json"
57
- }
58
 
59
- # Function to query Groq model
60
  @st.cache_resource
61
- def query_groq_model(prompt, max_tokens=100, temperature=0.7):
62
- try:
63
- payload = {
64
- "prompt": prompt,
65
- "max_tokens": max_tokens,
66
- "temperature": temperature,
67
- "top_p": 1.0,
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
- # Streamlit App
80
- st.title("Mental Health Counseling Chat")
81
- st.markdown("""
82
- Welcome to the **Mental Health Counseling Chat Application**.
83
- This platform is designed to provide **supportive, positive, and encouraging responses** using the Groq `google/gemma-2-9b-it` model.
84
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
- # Load example dataset for user exploration (optional)
 
 
 
 
 
 
 
 
 
 
87
  @st.cache_resource
88
- def load_counseling_dataset():
89
- from datasets import load_dataset
90
- return load_dataset("Amod/mental_health_counseling_conversations")
91
 
92
- dataset = load_counseling_dataset()
93
 
94
- # Display example questions and answers from dataset
95
- if st.checkbox("Show Example Questions and Answers from Dataset"):
96
- sample = dataset["train"].shuffle(seed=42).select(range(3)) # Display 3 random samples
97
- for example in sample:
98
- st.markdown(f"**Question:** {example.get('context', 'N/A')}")
99
- st.markdown(f"**Answer:** {example.get('response', 'N/A')}")
100
- st.markdown("---")
101
 
102
  # User input for mental health concerns
103
- user_input = st.text_area("Your question or concern:", placeholder="Type your question here...")
104
 
105
  if st.button("Get Supportive Response"):
106
  if user_input.strip():
107
- try:
108
- # Query Groq model
109
- prompt = f"User: {user_input}\nCounselor:"
110
- counselor_reply = query_groq_model(prompt, max_tokens=150, temperature=0.7)
111
- st.subheader("Counselor's Response:")
112
- st.write(counselor_reply)
113
- except Exception as e:
114
- st.error(f"An error occurred while querying the model: {e}")
 
 
115
  else:
116
- st.error("Please enter a question or concern to receive a response.")
117
 
118
- # Sidebar resources
119
- st.sidebar.header("Additional Mental Health Resources")
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 are in crisis, please seek professional help immediately.")
 
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.")