vsrinivas commited on
Commit
75f9996
1 Parent(s): fcaed4f

Update funcs.py

Browse files
Files changed (1) hide show
  1. funcs.py +95 -96
funcs.py CHANGED
@@ -72,99 +72,98 @@ def generate_triggers_img(items):
72
  triggers_img = Image.open('triggeres.png')
73
  return triggers_img
74
 
75
- class session_processor:
76
- session_conversation = []
77
-
78
- # Generate therapist responses and patient triggers
79
- def get_doc_response_emotions(user_message, therapy_session_conversation):
80
-
81
- user_messages = []
82
- user_messages.append(user_message)
83
- emotion_set = detect_emotions(user_message)
84
- print(emotion_set)
85
-
86
- emotions_msg = generate_triggers_img(emotion_set)
87
- user_embedding = embed_model.encode(user_message, device='cuda' if torch.cuda.is_available() else 'cpu')
88
-
89
- similarities =[]
90
- for v in dials_embeddings['embeddings']:
91
- similarities.append(cosine_distance(user_embedding,v))
92
-
93
- top_match_index = similarities.index(max(similarities))
94
- # doc_response = dials_embeddings.iloc[top_match_index+1]['Doctor']
95
- doc_response = dials_embeddings.iloc[top_match_index]['Doctor']
96
-
97
- therapy_session_conversation.append(["User: "+user_message, "Therapist: "+doc_response])
98
-
99
- session_conversation.extend(["User: "+user_message, "Therapist: "+doc_response])
100
-
101
- print(f"User's message: {user_message}")
102
- print(f"RAG Matching message: {dials_embeddings.iloc[top_match_index]['Patient']}")
103
- # print(f"Therapist's response: {dials_embeddings.iloc[top_match_index+1]['Doctor']}\n\n")
104
- print(f"Therapist's response: {dials_embeddings.iloc[top_match_index]['Doctor']}\n\n")
105
-
106
- return '', therapy_session_conversation, emotions_msg
107
-
108
- # Generate summarization and recommendations for teh session
109
- def summarize_and_recommend():
110
- session_time = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
111
- session_conversation_processed = session_conversation.copy()
112
- session_conversation_processed.insert(0, "Session_time: "+session_time)
113
- session_conversation_processed ='\n'.join(session_conversation_processed)
114
- print("Session conversation:", session_conversation_processed)
115
-
116
- AI71_BASE_URL = "https://api.ai71.ai/v1/"
117
-
118
- client = OpenAI(
119
- api_key=AI71_API_KEY,
120
- base_url=AI71_BASE_URL,
121
- )
122
-
123
- full_summary = ""
124
- for chunk in AI71(AI71_API_KEY).chat.completions.create(
125
- model="tiiuae/falcon-180b-chat",
126
- messages=[
127
- {"role": "system", "content": """You are an Expert Cognitive Behavioural Therapist and Precis writer.
128
- Summarize the below user content <<<session_conversation_processed>>> into useful, ethical, relevant and realistic phrases with a format
129
- Session Time:
130
- Summary of the patient messages: #in two to four sentences
131
- Summary of therapist messages: #in two to three sentences:
132
- Summary of the whole session: # in two to three sentences. Ensure the entire session summary strictly does not exceed 100 tokens."""},
133
- {"role": "user", "content": session_conversation_processed},
134
- ],
135
- stream=True,
136
- ):
137
- if chunk.choices[0].delta.content:
138
- summary = chunk.choices[0].delta.content
139
- # print("Chunk summary:", summary, sep="", end="", flush=True)
140
- full_summary += summary
141
- full_summary = full_summary.replace('User:', '').strip()
142
- print("\n")
143
- print("Full summary:", full_summary)
144
-
145
- full_recommendations = ""
146
- for chunk in AI71(AI71_API_KEY).chat.completions.create(
147
- model="tiiuae/falcon-180b-chat",
148
- messages=[
149
- {"role": "system", "content": """You are an expert Cognitive Behavioural Therapist.
150
- Based on the full summary <<<full_summary>>> provide clinically valid, useful, appropriate action plan for the Patient as a bullted list.
151
- The list shall contain both medical and non medical prescriptions, dos and donts. The format of response shall be in passive voice with proper tense.
152
- - The patient is referred to........ #in one sentence
153
- - The patient is advised to ........ #in one sentence
154
- - The patient is refrained from........ #in one sentence
155
- - It is suggested that tha patient ........ #in one sentence
156
- - Scheduled a follow-up session with the patient........#in one sentence
157
- *Ensure the list contains NOT MORE THAN 7 points"""},
158
- {"role": "user", "content": full_summary},
159
- ],
160
- stream=True,
161
- ):
162
- if chunk.choices[0].delta.content:
163
- rec = chunk.choices[0].delta.content
164
- # print("Chunk recommendation:", rec, sep="", end="", flush=True)
165
- full_recommendations += rec
166
- full_recommendations = full_recommendations.replace('User:', '').strip()
167
- print("\n")
168
- print("Full recommendations:", full_recommendations)
169
- session_conversation=[]
170
- return full_summary, full_recommendations
 
72
  triggers_img = Image.open('triggeres.png')
73
  return triggers_img
74
 
75
+ # Generate therapist responses and patient triggers
76
+ def get_doc_response_emotions(user_message, therapy_session_conversation):
77
+ global session_conversation
78
+
79
+ user_messages = []
80
+ user_messages.append(user_message)
81
+ emotion_set = detect_emotions(user_message)
82
+ print(emotion_set)
83
+
84
+ emotions_msg = generate_triggers_img(emotion_set)
85
+ user_embedding = embed_model.encode(user_message, device='cuda' if torch.cuda.is_available() else 'cpu')
86
+
87
+ similarities =[]
88
+ for v in dials_embeddings['embeddings']:
89
+ similarities.append(cosine_distance(user_embedding,v))
90
+
91
+ top_match_index = similarities.index(max(similarities))
92
+ # doc_response = dials_embeddings.iloc[top_match_index+1]['Doctor']
93
+ doc_response = dials_embeddings.iloc[top_match_index]['Doctor']
94
+
95
+ therapy_session_conversation.append(["User: "+user_message, "Therapist: "+doc_response])
96
+
97
+ session_conversation.extend(["User: "+user_message, "Therapist: "+doc_response])
98
+
99
+ print(f"User's message: {user_message}")
100
+ print(f"RAG Matching message: {dials_embeddings.iloc[top_match_index]['Patient']}")
101
+ # print(f"Therapist's response: {dials_embeddings.iloc[top_match_index+1]['Doctor']}\n\n")
102
+ print(f"Therapist's response: {dials_embeddings.iloc[top_match_index]['Doctor']}\n\n")
103
+
104
+ return '', therapy_session_conversation, emotions_msg
105
+
106
+ # Generate summarization and recommendations for teh session
107
+ def summarize_and_recommend():
108
+ global session_conversation
109
+ session_time = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
110
+ session_conversation_processed = session_conversation.copy()
111
+ session_conversation_processed.insert(0, "Session_time: "+session_time)
112
+ session_conversation_processed ='\n'.join(session_conversation_processed)
113
+ print("Session conversation:", session_conversation_processed)
114
+
115
+ AI71_BASE_URL = "https://api.ai71.ai/v1/"
116
+
117
+ client = OpenAI(
118
+ api_key=AI71_API_KEY,
119
+ base_url=AI71_BASE_URL,
120
+ )
121
+
122
+ full_summary = ""
123
+ for chunk in AI71(AI71_API_KEY).chat.completions.create(
124
+ model="tiiuae/falcon-180b-chat",
125
+ messages=[
126
+ {"role": "system", "content": """You are an Expert Cognitive Behavioural Therapist and Precis writer.
127
+ Summarize the below user content <<<session_conversation_processed>>> into useful, ethical, relevant and realistic phrases with a format
128
+ Session Time:
129
+ Summary of the patient messages: #in two to four sentences
130
+ Summary of therapist messages: #in two to three sentences:
131
+ Summary of the whole session: # in two to three sentences. Ensure the entire session summary strictly does not exceed 100 tokens."""},
132
+ {"role": "user", "content": session_conversation_processed},
133
+ ],
134
+ stream=True,
135
+ ):
136
+ if chunk.choices[0].delta.content:
137
+ summary = chunk.choices[0].delta.content
138
+ # print("Chunk summary:", summary, sep="", end="", flush=True)
139
+ full_summary += summary
140
+ full_summary = full_summary.replace('User:', '').strip()
141
+ print("\n")
142
+ print("Full summary:", full_summary)
143
+
144
+ full_recommendations = ""
145
+ for chunk in AI71(AI71_API_KEY).chat.completions.create(
146
+ model="tiiuae/falcon-180b-chat",
147
+ messages=[
148
+ {"role": "system", "content": """You are an expert Cognitive Behavioural Therapist.
149
+ Based on the full summary <<<full_summary>>> provide clinically valid, useful, appropriate action plan for the Patient as a bullted list.
150
+ The list shall contain both medical and non medical prescriptions, dos and donts. The format of response shall be in passive voice with proper tense.
151
+ - The patient is referred to........ #in one sentence
152
+ - The patient is advised to ........ #in one sentence
153
+ - The patient is refrained from........ #in one sentence
154
+ - It is suggested that tha patient ........ #in one sentence
155
+ - Scheduled a follow-up session with the patient........#in one sentence
156
+ *Ensure the list contains NOT MORE THAN 7 points"""},
157
+ {"role": "user", "content": full_summary},
158
+ ],
159
+ stream=True,
160
+ ):
161
+ if chunk.choices[0].delta.content:
162
+ rec = chunk.choices[0].delta.content
163
+ # print("Chunk recommendation:", rec, sep="", end="", flush=True)
164
+ full_recommendations += rec
165
+ full_recommendations = full_recommendations.replace('User:', '').strip()
166
+ print("\n")
167
+ print("Full recommendations:", full_recommendations)
168
+ session_conversation=[]
169
+ return full_summary, full_recommendations