sravyaa02 commited on
Commit
8850eab
·
verified ·
1 Parent(s): b3391d7

Update chatbot.py

Browse files
Files changed (1) hide show
  1. chatbot.py +200 -163
chatbot.py CHANGED
@@ -1,164 +1,201 @@
1
- import streamlit as st
2
- from langchain_core.prompts import PromptTemplate
3
- from langchain_core.output_parsers import StrOutputParser
4
- from transformers import pipeline
5
- from langchain_huggingface import HuggingFaceEndpoint
6
- import numpy as np
7
- from pydub import AudioSegment
8
- import os
9
-
10
- # Model IDs
11
- model_id = "unsloth/Llama-3.2-1B-Instruct"
12
- model2_id = "mistralai/Mistral-7B-Instruct-v0.3"
13
- whisper_model = "openai/whisper-small" # Using Whisper model for audio transcription
14
-
15
- def get_llm_hf_inference(model_id, max_new_tokens=128, temperature=0.1):
16
- """Returns a language model for HuggingFace inference."""
17
- try:
18
- llm = HuggingFaceEndpoint(
19
- repo_id=model_id,
20
- max_new_tokens=max_new_tokens,
21
- temperature=temperature,
22
- token=os.getenv("HF_TOKEN")
23
- )
24
- return llm
25
- except Exception as e:
26
- st.error(f"Error initializing model: {e}")
27
- return None
28
-
29
- # Initialize Whisper transcription model
30
- def load_transcription_model():
31
- try:
32
- transcriber = pipeline("automatic-speech-recognition", model=whisper_model)
33
- return transcriber
34
- except Exception as e:
35
- st.error(f"Error loading Whisper model: {e}")
36
- return None
37
-
38
- # Preprocess audio to 16kHz mono
39
- def preprocess_audio(file):
40
- audio = AudioSegment.from_file(file).set_frame_rate(16000).set_channels(1)
41
- audio_samples = np.array(audio.get_array_of_samples()).astype(np.float32) / (2**15)
42
- return audio_samples
43
-
44
- # Function to transcribe audio with preprocessing
45
- def transcribe_audio(file, transcriber):
46
- audio = preprocess_audio(file)
47
- transcription = transcriber(audio)["text"]
48
- return transcription
49
-
50
- # Chatbot page content
51
- def display_chatbot():
52
- st.title("Personal Psychologist Chatbot")
53
- st.markdown(f"*This is a simple chatbot that acts as a psychologist and gives solutions to your psychological problems. It uses the {model_id}.*")
54
-
55
- # Sidebar for settings
56
- with st.sidebar:
57
- # Reset Chat History
58
- reset_history = st.button("Reset Chat History")
59
- go_home = st.button("Back to Home")
60
- if go_home:
61
- st.session_state.page = "home"
62
- st.experimental_rerun() # Go back to homepage
63
-
64
- # Initialize or reset chat history
65
- if reset_history:
66
- st.session_state.chat_history = [{"role": "assistant", "content": st.session_state.starter_message}]
67
-
68
- def get_response(system_message, chat_history, user_text, model_id, max_new_tokens=256):
69
- """Generates a response from the chatbot model."""
70
- hf = get_llm_hf_inference(model_id=model_id, max_new_tokens=max_new_tokens)
71
- if hf is None:
72
- return "Error: Model not initialized.", chat_history
73
-
74
- # Create the prompt template
75
- prompt = PromptTemplate.from_template(
76
- (
77
- "[INST] {system_message}"
78
- "\nCurrent Conversation:\n{chat_history}\n\n"
79
- "\nUser: {user_text}.\n [/INST]"
80
- "\nAI:"
81
- )
82
- )
83
- chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
84
-
85
- # Generate the response
86
- response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))
87
- response = response.split("AI:")[-1].strip()
88
-
89
- # Check for "thank you" in the user's input and prompt for report
90
- if "thank you" in user_text.lower():
91
- follow_up_question = "Would you like to have a report of your current health?"
92
- response += f"\n\n{follow_up_question}"
93
-
94
- # Update the chat history
95
- chat_history.append({'role': 'user', 'content': user_text})
96
- chat_history.append({'role': 'assistant', 'content': response})
97
- return response, chat_history
98
-
99
- def get_summary_of_chat_history(chat_history, model2_id):
100
- """Generates a summary of the entire chat history using GPT-2."""
101
- hf = get_llm_hf_inference(model_id=model2_id, max_new_tokens=256)
102
- if hf is None:
103
- return "Error: Model not initialized."
104
-
105
- # Create the summary prompt
106
- chat_content = "\n".join([f"{message['role']}: {message['content']}" for message in chat_history])
107
- prompt = PromptTemplate.from_template(
108
- f"Please summarize the following conversation and generate a report of the user's current health:\n\n{chat_content}"
109
- )
110
-
111
- summary = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
112
- summary_response = summary.invoke(input={})
113
-
114
- return summary_response
115
-
116
- # Load Whisper model for transcription
117
- transcriber = load_transcription_model()
118
-
119
- # User input for audio and text
120
- st.markdown("### Choose your input:")
121
- audio_file = st.file_uploader("Upload an audio file for transcription", type=["mp3", "wav", "m4a"])
122
- st.session_state.user_text = st.chat_input(placeholder="Or enter your text here.")
123
-
124
- # Check if audio file is uploaded and transcribe if available
125
- if audio_file is not None and transcriber:
126
- with st.spinner("Transcribing audio..."):
127
- try:
128
- st.session_state.user_text = transcribe_audio(audio_file, transcriber)
129
- st.success("Audio transcribed successfully!")
130
- except Exception as e:
131
- st.error(f"Error transcribing audio: {e}")
132
-
133
- # Chat interface
134
- output_container = st.container()
135
-
136
- # Display chat messages
137
- with output_container:
138
- for message in st.session_state.chat_history:
139
- if message['role'] == 'system':
140
- continue
141
- with st.chat_message(message['role'], avatar=st.session_state['avatars'][message['role']]):
142
- st.markdown(message['content'])
143
-
144
- # Process text input for chatbot response
145
- if st.session_state.user_text:
146
- with st.chat_message("user", avatar=st.session_state.avatars['user']):
147
- st.markdown(st.session_state.user_text)
148
-
149
- with st.chat_message("assistant", avatar=st.session_state.avatars['assistant']):
150
- with st.spinner("Addressing your concerns..."):
151
- response, st.session_state.chat_history = get_response(
152
- system_message=st.session_state.system_message,
153
- user_text=st.session_state.user_text,
154
- chat_history=st.session_state.chat_history,
155
- model_id=model_id,
156
- max_new_tokens=st.session_state.max_response_length,
157
- )
158
- st.markdown(response)
159
-
160
- # Check if the user has agreed to the report
161
- if "yes" in st.session_state.user_text.lower() and "Would you like to have a report of your current health?" in response:
162
- with st.spinner("Generating your health report..."):
163
- report = get_summary_of_chat_history(st.session_state.chat_history, model2_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  st.markdown(report)
 
1
+ import streamlit as st
2
+ from langchain_core.prompts import PromptTemplate
3
+ from langchain_core.output_parsers import StrOutputParser
4
+ from transformers import pipeline
5
+ from langchain_huggingface import HuggingFaceEndpoint
6
+ import numpy as np
7
+ from pydub import AudioSegment
8
+ import os
9
+
10
+ # Model IDs
11
+ model_id = "meta-llama/Llama-3.2-1B-Instruct"
12
+ model2_id = "meta-llama/Llama-3.2-1B-Instruct"
13
+ whisper_model = "openai/whisper-small" # Using Whisper model for audio transcription
14
+
15
+ def get_llm_hf_inference(model_id, max_new_tokens=128, temperature=0.1):
16
+ """Returns a language model for HuggingFace inference."""
17
+ try:
18
+ llm = HuggingFaceEndpoint(
19
+ repo_id=model_id,
20
+ max_new_tokens=max_new_tokens,
21
+ temperature=temperature,
22
+ token=os.getenv("HF_TOKEN")
23
+ )
24
+ return llm
25
+ except Exception as e:
26
+ st.error(f"Error initializing model: {e}")
27
+ return None
28
+
29
+ # Initialize Whisper transcription model
30
+ def load_transcription_model():
31
+ try:
32
+ transcriber = pipeline("automatic-speech-recognition", model=whisper_model)
33
+ return transcriber
34
+ except Exception as e:
35
+ st.error(f"Error loading Whisper model: {e}")
36
+ return None
37
+
38
+ # Preprocess audio to 16kHz mono
39
+ def preprocess_audio(file):
40
+ audio = AudioSegment.from_file(file).set_frame_rate(16000).set_channels(1)
41
+ audio_samples = np.array(audio.get_array_of_samples()).astype(np.float32) / (2**15)
42
+ return audio_samples
43
+
44
+ # Function to transcribe audio with preprocessing
45
+ def transcribe_audio(file, transcriber):
46
+ audio = preprocess_audio(file)
47
+ transcription = transcriber(audio)["text"]
48
+ return transcription
49
+
50
+ # Chatbot page content
51
+ def display_chatbot():
52
+ st.title("Personal Psychologist Chatbot")
53
+ st.markdown(f"*This is a simple chatbot that acts as a psychologist and gives solutions to your psychological problems. It uses the {model_id}.*")
54
+
55
+ # Sidebar for settings
56
+ with st.sidebar:
57
+ # Reset Chat History
58
+ reset_history = st.button("Reset Chat History")
59
+ go_home = st.button("Back to Home")
60
+ if go_home:
61
+ st.session_state.chat_started = False
62
+ st.experimental_rerun() # This will reload the app to show the homepage
63
+
64
+ # Initialize or reset chat history
65
+ if reset_history:
66
+ st.session_state.chat_history = [{"role": "assistant", "content": st.session_state.starter_message}]
67
+
68
+ def get_response(system_message, chat_history, user_text, model_id, max_new_tokens=256):
69
+ """Generates a response from the chatbot model."""
70
+ hf = get_llm_hf_inference(model_id=model_id, max_new_tokens=max_new_tokens)
71
+ if hf is None:
72
+ return "Error: Model not initialized.", chat_history
73
+
74
+ # Create the prompt template
75
+ prompt = PromptTemplate.from_template(
76
+ (
77
+ "[INST] {system_message}"
78
+ "\nCurrent Conversation:\n{chat_history}\n\n"
79
+ "\nUser: {user_text}.\n [/INST]"
80
+ "\nAI:"
81
+ )
82
+ )
83
+ chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
84
+
85
+ # Generate the response
86
+ response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))
87
+ response = response.split("AI:")[-1].strip()
88
+
89
+ # Enhanced end-of-conversation detection:
90
+ # Check if response contains low engagement or end-of-conversation patterns
91
+ low_engagement_threshold = 3 # Threshold for short responses
92
+ end_keywords = ["thank you", "thanks", "goodbye", "bye", "that's all", "done"]
93
+
94
+ # Check for short responses over multiple turns
95
+ short_responses = len(user_text.split()) <= low_engagement_threshold
96
+ end_pattern_match = any(keyword in user_text.lower() for keyword in end_keywords)
97
+
98
+ # Recent short responses pattern
99
+ recent_short_responses = all(len(msg["content"].split()) <= low_engagement_threshold for msg in chat_history[-2:])
100
+ response_is_acknowledgment = user_text.lower() in ["yes", "okay", "alright"]
101
+
102
+ # Trigger health report prompt based on combination of patterns
103
+ if (end_pattern_match or (short_responses and recent_short_responses)) and not response_is_acknowledgment:
104
+ follow_up_question = "Would you like to have a report of your current health? Yes/No"
105
+ response += f"\n\n{follow_up_question}"
106
+
107
+ # Update the chat history
108
+ chat_history.append({'role': 'user', 'content': user_text})
109
+ chat_history.append({'role': 'assistant', 'content': response})
110
+ return response, chat_history
111
+
112
+ def get_summary_of_chat_history(chat_history, model2_id):
113
+ """Generates a comprehensive summary of the chat history and a health report."""
114
+ hf = get_llm_hf_inference(model_id=model2_id, max_new_tokens=256)
115
+ if hf is None:
116
+ return "Error: Model not initialized."
117
+
118
+ # Format the chat content
119
+ chat_content = "\n".join([f"{message['role']}: {message['content']}" for message in chat_history])
120
+
121
+ # Improved summary prompt
122
+ prompt = PromptTemplate.from_template(
123
+ (
124
+ """
125
+ Generate a detailed report based on the following conversation between a therapist and patient. The report should include:
126
+
127
+ 1. **Patient Information:**
128
+ - Include placeholders for Name, Age, Gender, Date of Session.
129
+
130
+ 2. **Conversation Summary:**
131
+ - Summarize the main points of the conversation, focusing on the patient’s primary concerns and emotional state. Note any specific causes of stress or distress, how these issues affect the patient's personal life, and their expressed desires or goals.
132
+
133
+ 3. **Preliminary Diagnosis:**
134
+ - Identify the main symptoms observed in the conversation, such as mood, energy levels, motivation, etc.
135
+ - Suggest a potential preliminary diagnosis based on the symptoms described, e.g., stress-induced burnout or other relevant concerns. Mention the need for further assessment if applicable.
136
+
137
+ 4. **Recommendations & Strategies:**
138
+ - Provide practical, achievable strategies tailored to the patient’s needs.
139
+
140
+
141
+ Format the report neatly with headings and subheadings as shown in the example. Aim to keep the language supportive and professional.
142
+ """
143
+ )
144
+ )
145
+
146
+ summary = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
147
+ summary_response = summary.invoke(input={"chat_content": chat_content})
148
+
149
+ return summary_response
150
+
151
+
152
+
153
+ # Load Whisper model for transcription
154
+ transcriber = load_transcription_model()
155
+
156
+ # User input for audio and text
157
+ st.markdown("### Choose your input:")
158
+ audio_file = st.file_uploader("Upload an audio file for transcription", type=["mp3", "wav", "m4a"])
159
+ st.session_state.user_text = st.chat_input(placeholder="Or enter your text here.")
160
+
161
+ # Check if audio file is uploaded and transcribe if available
162
+ if audio_file is not None and transcriber:
163
+ with st.spinner("Transcribing audio..."):
164
+ try:
165
+ st.session_state.user_text = transcribe_audio(audio_file, transcriber)
166
+ st.success("Audio transcribed successfully!")
167
+ except Exception as e:
168
+ st.error(f"Error transcribing audio: {e}")
169
+
170
+ # Chat interface
171
+ output_container = st.container()
172
+
173
+ # Display chat messages
174
+ with output_container:
175
+ for message in st.session_state.chat_history:
176
+ if message['role'] == 'system':
177
+ continue
178
+ with st.chat_message(message['role'], avatar=st.session_state['avatars'][message['role']]):
179
+ st.markdown(message['content'])
180
+
181
+ # Process text input for chatbot response
182
+ if st.session_state.user_text:
183
+ with st.chat_message("user", avatar=st.session_state.avatars['user']):
184
+ st.markdown(st.session_state.user_text)
185
+
186
+ with st.chat_message("assistant", avatar=st.session_state.avatars['assistant']):
187
+ with st.spinner("Addressing your concerns..."):
188
+ response, st.session_state.chat_history = get_response(
189
+ system_message=st.session_state.system_message,
190
+ user_text=st.session_state.user_text,
191
+ chat_history=st.session_state.chat_history,
192
+ model_id=model_id,
193
+ max_new_tokens=st.session_state.max_response_length,
194
+ )
195
+ st.markdown(response)
196
+
197
+ # Check if the user has agreed to the report
198
+ if "yes" in st.session_state.user_text.lower() and "Would you like to have a report of your current health?" in response:
199
+ with st.spinner("Generating your health report..."):
200
+ report = get_summary_of_chat_history(st.session_state.chat_history, model2_id)
201
  st.markdown(report)