Sakil commited on
Commit
028c9bc
·
1 Parent(s): 557cbdf

app file is updated

Browse files
Files changed (1) hide show
  1. app.py +61 -61
app.py CHANGED
@@ -1,81 +1,81 @@
1
- import streamlit as st
2
- from langchain.document_loaders import PyPDFLoader, DirectoryLoader
3
- from langchain import PromptTemplate
 
4
  from langchain.embeddings import HuggingFaceEmbeddings
5
  from langchain.vectorstores import FAISS
6
  from langchain.llms import CTransformers
7
- from langchain.chains import RetrievalQA
8
- import chainlit as cl
9
 
10
  DB_FAISS_PATH = 'vectorstore/db_faiss'
11
 
12
- custom_prompt_template = """Use the following pieces of information to answer the user's question.
13
- If you don't know the answer, just say that you don't know, don't try to make up an answer.
14
-
15
- Context: {context}
16
- Question: {question}
17
-
18
- Only return the helpful answer below and nothing else.
19
- Helpful answer:
20
- """
21
-
22
- def set_custom_prompt():
23
- """
24
- Prompt template for QA retrieval for each vectorstore
25
- """
26
- prompt = PromptTemplate(template=custom_prompt_template,
27
- input_variables=['context', 'question'])
28
- return prompt
29
-
30
- # Retrieval QA Chain
31
- def retrieval_qa_chain(llm, prompt, db):
32
- qa_chain = RetrievalQA.from_chain_type(llm=llm,
33
- chain_type='stuff',
34
- retriever=db.as_retriever(search_kwargs={'k': 2}),
35
- return_source_documents=True,
36
- chain_type_kwargs={'prompt': prompt}
37
- )
38
- return qa_chain
39
-
40
- # Loading the model
41
  def load_llm():
42
  # Load the locally downloaded model here
43
  llm = CTransformers(
44
- model="llama-2-7b-chat.ggmlv3.q8_0.bin",
45
  model_type="llama",
46
- max_new_tokens=512,
47
- temperature=0.5
48
  )
49
  return llm
50
 
51
- # QA Model Function
52
- def qa_bot():
53
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",
54
- model_kwargs={'device': 'cpu'})
55
- db = FAISS.load_local(DB_FAISS_PATH, embeddings)
56
- llm = load_llm()
57
- qa_prompt = set_custom_prompt()
58
- qa = retrieval_qa_chain(llm, qa_prompt, db)
59
 
60
- return qa
 
 
 
 
61
 
62
- def main():
63
- st.title("Medical Assistance AI ChatBot")
 
 
 
 
64
 
65
- qa_result = qa_bot()
 
 
 
66
 
67
- user_input = st.text_input("Enter your question:")
 
 
 
68
 
69
- if st.button("Ask"):
70
- response = qa_result({'query': user_input})
71
- answer = response["result"]
72
- sources = response["source_documents"]
 
 
 
 
 
 
 
 
 
73
 
74
- st.write("Answer:", answer)
75
- if sources:
76
- st.write("Sources:", sources)
77
- else:
78
- st.write("No sources found")
 
 
 
 
 
 
79
 
80
- if __name__ == "__main__":
81
- main()
 
 
 
 
1
+ import streamlit as st
2
+ from streamlit_chat import message
3
+ import tempfile
4
+ from langchain.document_loaders.csv_loader import CSVLoader
5
  from langchain.embeddings import HuggingFaceEmbeddings
6
  from langchain.vectorstores import FAISS
7
  from langchain.llms import CTransformers
8
+ from langchain.chains import ConversationalRetrievalChain
 
9
 
10
  DB_FAISS_PATH = 'vectorstore/db_faiss'
11
 
12
+ #Loading the model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  def load_llm():
14
  # Load the locally downloaded model here
15
  llm = CTransformers(
16
+ model = "llama-2-7b-chat.ggmlv3.q8_0.bin",
17
  model_type="llama",
18
+ max_new_tokens = 512,
19
+ temperature = 0.5
20
  )
21
  return llm
22
 
23
+ st.title("Chat with CSV using Llama2 🦙🦜")
24
+ st.markdown("<h3 style='text-align: center; color: white;'> A Very Good Bot For CSV</h3>", unsafe_allow_html=True)
25
+
26
+ uploaded_file = st.sidebar.file_uploader("Upload your Data", type="csv")
 
 
 
 
27
 
28
+ if uploaded_file :
29
+ #use tempfile because CSVLoader only accepts a file_path
30
+ with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
31
+ tmp_file.write(uploaded_file.getvalue())
32
+ tmp_file_path = tmp_file.name
33
 
34
+ loader = CSVLoader(file_path=tmp_file_path, encoding="utf-8", csv_args={
35
+ 'delimiter': ','})
36
+ data = loader.load()
37
+ #st.json(data)
38
+ embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2',
39
+ model_kwargs={'device': 'cpu'})
40
 
41
+ db = FAISS.from_documents(data, embeddings)
42
+ db.save_local(DB_FAISS_PATH)
43
+ llm = load_llm()
44
+ chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=db.as_retriever())
45
 
46
+ def conversational_chat(query):
47
+ result = chain({"question": query, "chat_history": st.session_state['history']})
48
+ st.session_state['history'].append((query, result["answer"]))
49
+ return result["answer"]
50
 
51
+ if 'history' not in st.session_state:
52
+ st.session_state['history'] = []
53
+
54
+ if 'generated' not in st.session_state:
55
+ st.session_state['generated'] = ["Hello ! Ask me anything about " + uploaded_file.name + " 🤗"]
56
+
57
+ if 'past' not in st.session_state:
58
+ st.session_state['past'] = ["Hey ! 👋"]
59
+
60
+ #container for the chat history
61
+ response_container = st.container()
62
+ #container for the user's text input
63
+ container = st.container()
64
 
65
+ with container:
66
+ with st.form(key='my_form', clear_on_submit=True):
67
+
68
+ user_input = st.text_input("Query:", placeholder="Talk to your csv data here (:", key='input')
69
+ submit_button = st.form_submit_button(label='Send')
70
+
71
+ if submit_button and user_input:
72
+ output = conversational_chat(user_input)
73
+
74
+ st.session_state['past'].append(user_input)
75
+ st.session_state['generated'].append(output)
76
 
77
+ if st.session_state['generated']:
78
+ with response_container:
79
+ for i in range(len(st.session_state['generated'])):
80
+ message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="big-smile")
81
+ message(st.session_state["generated"][i], key=str(i), avatar_style="thumbs")