Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files
app.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.chat_models import ChatOpenAI
|
2 |
+
import streamlit as st
|
3 |
+
from gtts import gTTS
|
4 |
+
from io import BytesIO
|
5 |
+
from langchain.chains import RetrievalQA
|
6 |
+
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
|
7 |
+
from streamlit_mic_recorder import speech_to_text
|
8 |
+
from langchain.prompts import (
|
9 |
+
SystemMessagePromptTemplate,
|
10 |
+
HumanMessagePromptTemplate,
|
11 |
+
ChatPromptTemplate,
|
12 |
+
MessagesPlaceholder
|
13 |
+
)
|
14 |
+
from langchain_community.llms.huggingface_hub import HuggingFaceHub
|
15 |
+
from streamlit_chat import message
|
16 |
+
|
17 |
+
|
18 |
+
with st.sidebar:
|
19 |
+
if "name" not in st.session_state:
|
20 |
+
st.session_state["name"] =""
|
21 |
+
|
22 |
+
name= st.text_input("Enter name", st.session_state["name"])
|
23 |
+
|
24 |
+
if "age" not in st.session_state:
|
25 |
+
st.session_state["age"] =""
|
26 |
+
age= st.text_input("Enter age", st.session_state["age"])
|
27 |
+
submit = st.button("Submit")
|
28 |
+
|
29 |
+
if submit:
|
30 |
+
st.session_state["name"] = name
|
31 |
+
st.session_state["age"] = age
|
32 |
+
st.write("name and age submitted")
|
33 |
+
|
34 |
+
st.title("Mental Health Bot :heartpulse:")
|
35 |
+
st.subheader("Here to help")
|
36 |
+
|
37 |
+
if 'responses' not in st.session_state:
|
38 |
+
st.session_state['responses'] = ["How can I assist you?"]
|
39 |
+
|
40 |
+
if 'requests' not in st.session_state:
|
41 |
+
st.session_state['requests'] = []
|
42 |
+
|
43 |
+
access_token = HUGGING_FACE_API
|
44 |
+
hf_repo_id = 'mistralai/Mistral-7B-Instruct-v0.1'
|
45 |
+
|
46 |
+
|
47 |
+
llm =HuggingFaceHub(
|
48 |
+
repo_id=hf_repo_id,
|
49 |
+
model_kwargs={"temperature": 0.2, "max_length": 32000}, huggingfacehub_api_token = access_token
|
50 |
+
)
|
51 |
+
|
52 |
+
|
53 |
+
if 'buffer_memory' not in st.session_state:
|
54 |
+
st.session_state.buffer_memory=ConversationBufferWindowMemory(k=3,return_messages=True)
|
55 |
+
|
56 |
+
|
57 |
+
system_msg_template = SystemMessagePromptTemplate.from_template(template="""Answer the question as truthfully as possible using the provided context,
|
58 |
+
and if the answer is not contained within the text below, say 'I don't know'""")
|
59 |
+
|
60 |
+
|
61 |
+
human_msg_template = HumanMessagePromptTemplate.from_template(template="{input}")
|
62 |
+
|
63 |
+
prompt_template = ChatPromptTemplate.from_messages([system_msg_template, MessagesPlaceholder(variable_name="history"), human_msg_template])
|
64 |
+
|
65 |
+
#conversation = ConversationChain.from_template(memory=st.session_state.buffer_memory,
|
66 |
+
# prompt = prompt_template, llm=llm, verbose = True)
|
67 |
+
|
68 |
+
import re
|
69 |
+
from langchain.memory import ConversationBufferMemory
|
70 |
+
|
71 |
+
# Define the extract_helpful_answer function
|
72 |
+
def extract_helpful_answer(text):
|
73 |
+
match = re.search(r'Helpful Answer:(.*)', text)
|
74 |
+
if match:
|
75 |
+
return match.group(1).strip()
|
76 |
+
else:
|
77 |
+
return None
|
78 |
+
|
79 |
+
# Initialize the conversation buffer memory
|
80 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
81 |
+
|
82 |
+
from utils import retriever
|
83 |
+
# Create the RetrievalQA instance
|
84 |
+
qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, memory=memory)
|
85 |
+
|
86 |
+
# Function to process LLM response and extract helpful answer
|
87 |
+
def process_llm_response(llm_response):
|
88 |
+
if 'result' in llm_response:
|
89 |
+
helpful_answer = extract_helpful_answer(llm_response['result'])
|
90 |
+
if helpful_answer:
|
91 |
+
return helpful_answer
|
92 |
+
else:
|
93 |
+
return "No helpful answer found."
|
94 |
+
|
95 |
+
#container for chat history
|
96 |
+
response_container = st.container()
|
97 |
+
#container for text box
|
98 |
+
textcontainer = st.container()
|
99 |
+
|
100 |
+
#from utils import find_match
|
101 |
+
def speech_recognition_callback():
|
102 |
+
# Ensure that speech output is available
|
103 |
+
if st.session_state.my_stt_output is None:
|
104 |
+
st.session_state.p01_error_message = "Please record your response again."
|
105 |
+
return
|
106 |
+
|
107 |
+
# Clear any previous error messages
|
108 |
+
st.session_state.p01_error_message = None
|
109 |
+
|
110 |
+
# Store the speech output in the session state
|
111 |
+
st.session_state.speech_input = st.session_state.my_stt_output
|
112 |
+
|
113 |
+
def text_to_speech(text):
|
114 |
+
# Use gTTS to convert text to speech
|
115 |
+
tts = gTTS(text=text, lang='en')
|
116 |
+
# Save the speech as bytes in memory
|
117 |
+
fp = BytesIO()
|
118 |
+
tts.write_to_fp(fp)
|
119 |
+
return fp
|
120 |
+
|
121 |
+
# Add a text input field for both speech and text queries
|
122 |
+
# Add a text input field for both speech and text queries
|
123 |
+
with textcontainer:
|
124 |
+
# Use the speech_to_text function to capture speech input
|
125 |
+
speech_input = speech_to_text(
|
126 |
+
key='my_stt',
|
127 |
+
callback=speech_recognition_callback
|
128 |
+
)
|
129 |
+
|
130 |
+
# Check if speech input is available
|
131 |
+
if 'speech_input' in st.session_state and st.session_state.speech_input:
|
132 |
+
# Display the speech input
|
133 |
+
st.text(f"Speech Input: {st.session_state.speech_input}")
|
134 |
+
|
135 |
+
# Process the speech input as a query
|
136 |
+
query = st.session_state.speech_input
|
137 |
+
with st.spinner("processing....."):
|
138 |
+
response = qa(query)
|
139 |
+
helpful_answer = process_llm_response(response)
|
140 |
+
# Append the query and response to session state
|
141 |
+
st.session_state.requests.append(query)
|
142 |
+
st.session_state.responses.append(helpful_answer)
|
143 |
+
|
144 |
+
# Convert the response to speech
|
145 |
+
speech_fp = text_to_speech(helpful_answer)
|
146 |
+
# Play the speech
|
147 |
+
st.audio(speech_fp, format='audio/mp3')
|
148 |
+
|
149 |
+
# Add a text input field for query
|
150 |
+
query = st.text_input("Query: ", key="input")
|
151 |
+
|
152 |
+
# Process the query if it's not empty
|
153 |
+
if query:
|
154 |
+
with st.spinner("typing....."):
|
155 |
+
response = qa(query)
|
156 |
+
helpful_answer = process_llm_response(response)
|
157 |
+
# Append the query and response to session state
|
158 |
+
st.session_state.requests.append(query)
|
159 |
+
st.session_state.responses.append(helpful_answer)
|
160 |
+
|
161 |
+
# Convert the response to speech
|
162 |
+
speech_fp = text_to_speech(helpful_answer)
|
163 |
+
# Play the speech
|
164 |
+
st.audio(speech_fp, format='audio/mp3')
|
165 |
+
|
166 |
+
|
167 |
+
|
168 |
+
# Display the chat history and response
|
169 |
+
with response_container:
|
170 |
+
if st.session_state['responses']:
|
171 |
+
|
172 |
+
for i in range(len(st.session_state['responses'])):
|
173 |
+
message(st.session_state['responses'][i],key=str(i))
|
174 |
+
if i < len(st.session_state['requests']):
|
175 |
+
message(st.session_state["requests"][i], is_user=True,key=str(i)+ '_user')
|
main.py
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This is a sample Python script.
|
2 |
+
|
3 |
+
# Press Shift+F10 to execute it or replace it with your code.
|
4 |
+
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
|
5 |
+
|
6 |
+
|
7 |
+
def print_hi(name):
|
8 |
+
# Use a breakpoint in the code line below to debug your script.
|
9 |
+
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
|
10 |
+
|
11 |
+
|
12 |
+
# Press the green button in the gutter to run the script.
|
13 |
+
if __name__ == '__main__':
|
14 |
+
print_hi('PyCharm')
|
15 |
+
|
16 |
+
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
requirments.txt
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
sentence_transformers
|
2 |
+
langchain_community
|
3 |
+
streamlit
|
4 |
+
gtts
|
5 |
+
io
|
6 |
+
streamlit_mic_recorder
|
7 |
+
streamlit_chat
|
8 |
+
langchain
|
utils.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sentence_transformers import SentenceTransformer
|
2 |
+
from langchain_community.vectorstores import Chroma
|
3 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
4 |
+
from langchain_community.llms import HuggingFaceHub
|
5 |
+
import openai
|
6 |
+
import streamlit as st
|
7 |
+
import re
|
8 |
+
|
9 |
+
#openai_api_key = "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"
|
10 |
+
model = SentenceTransformer('sentence-transformers/multi-qa-MiniLM-L6-cos-v1')
|
11 |
+
# Define the embedding function using HuggingFaceEmbeddings
|
12 |
+
embeddings = HuggingFaceEmbeddings(model_name = 'sentence-transformers/multi-qa-MiniLM-L6-cos-v1')
|
13 |
+
|
14 |
+
vectordb = Chroma(persist_directory= r"C:\Users\Lakshita\PycharmProjects\trial_bot\vector db", #enter chroma directory
|
15 |
+
embedding_function=embeddings)
|
16 |
+
#index = pinecone.Index('langchain-chatbot')
|
17 |
+
|
18 |
+
# Create a retriever from the Chroma object
|
19 |
+
retriever = vectordb.as_retriever()
|
20 |
+
|
21 |
+
def find_match(input_text):
|
22 |
+
# Retrieve relevant documents based on the input query
|
23 |
+
docs = retriever.get_relevant_documents(input_text)
|
24 |
+
|
25 |
+
match_texts = [doc.page_content for doc in docs]
|
26 |
+
|
27 |
+
# Return the concatenated texts of the relevant documents
|
28 |
+
return "\n".join(match_texts)
|
29 |
+
|
30 |
+
|
31 |
+
from transformers import pipeline
|
32 |
+
|
33 |
+
# Load the text generation pipeline from Hugging Face
|
34 |
+
text_generator = pipeline("text-generation", model="gpt2")
|
35 |
+
|
36 |
+
def query_refiner(conversation, query):
|
37 |
+
# Formulate the prompt for the model
|
38 |
+
prompt = f"Given the following user query and conversation log, formulate a question that would be the most relevant to provide the user with an answer from a knowledge base.\n\nCONVERSATION LOG: \n{conversation}\n\nQuery: {query}\n\nRefined Query:"
|
39 |
+
|
40 |
+
# Generate the response using the Hugging Face model
|
41 |
+
response = text_generator(prompt, max_length=256, temperature=0.7, top_p=1.0, pad_token_id=text_generator.tokenizer.eos_token_id)
|
42 |
+
|
43 |
+
# Extract the refined query from the response
|
44 |
+
refined_query = response[0]['generated_text'].split('Refined Query:')[-1].strip()
|
45 |
+
|
46 |
+
return refined_query
|
47 |
+
|
48 |
+
|
49 |
+
def get_conversation_string():
|
50 |
+
conversation_string = ""
|
51 |
+
for i in range(len(st.session_state['responses'])-1):
|
52 |
+
|
53 |
+
conversation_string += "Human: "+st.session_state['requests'][i] + "\n"
|
54 |
+
conversation_string += "Bot: "+ st.session_state['responses'][i+1] + "\n"
|
55 |
+
return conversation_string
|
56 |
+
|
57 |
+
|
58 |
+
"""
|
59 |
+
from openai import OpenAI
|
60 |
+
from audio_recorder_streamlit import audio_recorder
|
61 |
+
|
62 |
+
client=OpenAI(api_key="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")
|
63 |
+
|
64 |
+
def speech_to_text(audio_data):
|
65 |
+
with open(audio_data, "rb") as audio_file:
|
66 |
+
transcript = client.audio.transcriptions.create(
|
67 |
+
model="whisper-1",
|
68 |
+
response_format="text",
|
69 |
+
file=audio_file
|
70 |
+
)
|
71 |
+
return transcript
|
72 |
+
"""
|