Divymakesml commited on
Commit
b5b9af8
·
verified ·
1 Parent(s): 61a9d5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -9
app.py CHANGED
@@ -1,21 +1,109 @@
1
  import streamlit as st
 
 
 
 
 
2
 
3
- st.title("🧠 AI Therapist")
 
 
 
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  if "history" not in st.session_state:
6
  st.session_state.history = []
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  user_input = st.text_input("How are you feeling today?")
9
 
10
  if user_input:
11
  response = therapist_pipeline(user_input)
12
- st.session_state.history.append((user_input, response))
13
 
14
- for user, bot in st.session_state.history:
15
- st.markdown(f"**You:** {user}")
16
- st.markdown(f"**AI Therapist:** {bot}")
17
-
18
- if st.button("🧾 Get Session Summary"):
19
- summary = summarize_session()
20
  st.markdown("### 🧠 Session Summary")
21
- st.markdown(summary)
 
 
 
 
 
 
1
  import streamlit as st
2
+ import numpy as np
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
4
+ from tensorflow.keras.models import load_model
5
+ from tensorflow.keras.preprocessing.text import Tokenizer
6
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
7
 
8
+ # Load tokenizer used in training
9
+ tokenizer = Tokenizer(num_words=10000)
10
+ # You must re-train or load tokenizer from a JSON if you saved it!
11
+ tokenizer.fit_on_texts(["dummy"]) # Temporary; replace with loaded tokenizer
12
 
13
+ # Preprocess text for models
14
+ def preprocess(text):
15
+ sequence = tokenizer.texts_to_sequences([text])
16
+ return pad_sequences(sequence, maxlen=100)
17
+
18
+ # Load Keras models
19
+ model1 = load_model("model1.h5") # Suicide risk
20
+ model2 = load_model("model2.h5") # Diagnosis classifier
21
+
22
+ # Model prediction wrappers
23
+ def model1_predict(text):
24
+ pred = model1.predict(preprocess(text))[0][0]
25
+ return int(pred > 0.5)
26
+
27
+ def model2_predict(text):
28
+ pred = model2.predict(preprocess(text))[0]
29
+ return int(np.argmax(pred))
30
+
31
+ diagnosis_labels = {
32
+ 1: "Anxiety",
33
+ 2: "Depression",
34
+ 3: "Bipolar disorder",
35
+ 4: "PTSD",
36
+ 5: "OCD",
37
+ 6: "ADHD",
38
+ 7: "General emotional distress"
39
+ }
40
+
41
+ @st.cache_resource
42
+ def load_llm():
43
+ model_id = "tiiuae/falcon-7b-instruct"
44
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
45
+ model = AutoModelForCausalLM.from_pretrained(
46
+ model_id,
47
+ device_map="auto",
48
+ trust_remote_code=True,
49
+ torch_dtype="auto"
50
+ )
51
+ return pipeline("text-generation", model=model, tokenizer=tokenizer, device_map="auto")
52
+
53
+ generator = load_llm()
54
+
55
+ # Session memory
56
  if "history" not in st.session_state:
57
  st.session_state.history = []
58
 
59
+ def therapist_pipeline(user_input):
60
+ st.session_state.history.append(f"User: {user_input}")
61
+ risk = model1_predict(user_input)
62
+
63
+ if risk == 1:
64
+ response = (
65
+ "I'm really sorry you're feeling this way. You're not alone — please talk to someone you trust "
66
+ "or a professional. I'm here to listen, but it's important to get real support too. 💙"
67
+ )
68
+ else:
69
+ diagnosis_code = model2_predict(user_input)
70
+ diagnosis = diagnosis_labels.get(diagnosis_code, "General emotional distress")
71
+
72
+ prompt = f"""You are an empathetic AI therapist. The user has been diagnosed with {diagnosis}. Respond supportively.
73
+
74
+ User: {user_input}
75
+ AI:"""
76
+
77
+ response = generator(prompt, max_new_tokens=150, temperature=0.7)[0]["generated_text"]
78
+ response = response.split("AI:")[-1].strip()
79
+
80
+ st.session_state.history.append(f"AI: {response}")
81
+ return response
82
+
83
+ def summarize_session():
84
+ session_text = "\n".join(st.session_state.history)
85
+ prompt = f"""Summarize the emotional state of the user based on the following conversation. Include emotional cues and possible diagnoses. Write it like a therapist note.
86
+
87
+ Conversation:
88
+ {session_text}
89
+
90
+ Summary:"""
91
+ summary = generator(prompt, max_new_tokens=250, temperature=0.5)[0]["generated_text"]
92
+ return summary.split("Summary:")[-1].strip()
93
+
94
+ # Streamlit UI
95
+ st.title("🧠 TARS.help")
96
  user_input = st.text_input("How are you feeling today?")
97
 
98
  if user_input:
99
  response = therapist_pipeline(user_input)
100
+ st.markdown(f"**AI Therapist:** {response}")
101
 
102
+ if st.button("🧾 Generate Therapist Summary"):
 
 
 
 
 
103
  st.markdown("### 🧠 Session Summary")
104
+ st.markdown(summarize_session())
105
+
106
+ # Show history
107
+ for i in range(0, len(st.session_state.history), 2):
108
+ st.markdown(f"**You:** {st.session_state.history[i][6:]}")
109
+ st.markdown(f"**AI:** {st.session_state.history[i+1][4:]}")