drkareemkamal commited on
Commit
166d466
·
verified ·
1 Parent(s): 2f962ea

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -0
app.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from streamlit_chat import message
3
+ import tempfile
4
+ #from langchain_community.documentloader.csv_loader import CSVLoader
5
+ from langchain_community.document_loaders.csv_loader import CSVLoader
6
+ from langchain_community.embeddings import HuggingFaceEmbeddings
7
+ #from langchain_community.embeddings import HuggingFaceBgeEmbeddings
8
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
9
+ from langchain_community.vectorstores import FAISS
10
+ #from langchain_community.llms import CTransformers
11
+ from langchain_community.llms.ctransformers import CTransformers
12
+
13
+ from langchain.chains.conversational_retrieval.base import ConversationalRetrievalChain
14
+
15
+ #from langchain.chains.conversational_retrieval.base import ConversationalRetreievalChain
16
+
17
+
18
+ DB_FAISS_PATH = 'vectorstore/db_faiss'
19
+
20
+ def load_llm():
21
+ # load model from hugging face repo
22
+ llm = CTransformers(
23
+ model = 'TheBloke/Llama-2-7B-Chat-GGML',
24
+ model_type = 'llma',
25
+ max_new_token = 512,
26
+ temperature = 0.5
27
+ )
28
+ return llm
29
+
30
+ st.title("Chat with CSV using Llma 2")
31
+ st.markdown("<h1 style='text-align: center; color: blue;'>Chat with your PDF 📄 </h1>", unsafe_allow_html=True)
32
+ st.markdown("<h3 style='text-align: center; color: grey;'>Built by <a href='https://github.com/DrKareemKAmal'>MindSparks ❤️ </a></h3>", unsafe_allow_html=True)
33
+
34
+ uploaded_file = st.sidebar.file_uploader('Upload your data', type=['csv'])
35
+
36
+ if uploaded_file:
37
+ with tempfile.NamedTemporaryFile(delete=False)as temp_file :
38
+ temp_file.write(uploaded_file.getvalue())
39
+ tempfile_path = temp_file.name
40
+
41
+ loader = CSVLoader(file_path = tempfile_path, encoding = 'utf-8',
42
+ csv_args = {'delimiter': ','} )
43
+ data = loader.load()
44
+ #st.json(data)
45
+
46
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size = 500 , chunk_overlap = 20)
47
+ text_chunks = text_splitter.split_documents(data)
48
+ st.write (f"Total text chunks : {len(text_chunks)}")
49
+
50
+ embeddings = HuggingFaceEmbeddings(
51
+ model = 'sentence-transformers/all-MiniLM-L6-v2',
52
+ model_kwargs = {'device': 'cpu'}
53
+ )
54
+
55
+
56
+ db = FAISS.from_documents(text_chunks, embeddings)
57
+ db.save_local (DB_FAISS_PATH)
58
+ llm = load_llm()
59
+
60
+ chain = ConversationalRetrievalChain.from_llm(llm= llm , retriever = db.as_retriever())
61
+
62
+ def conversational_chat(query):
63
+ result = chain({"quetion": query ,
64
+ "chat_history": st.session_state['history']})
65
+ st.session_state['history'].append((query , result['answer']))
66
+ return result['answer']
67
+
68
+ if 'history' not in st.session_state :
69
+ st.session_state['history'] = []
70
+
71
+ if 'generated' not in st.session_state :
72
+ st.session_state['generated'] = ['Hello, Ask me anything about ' + uploaded_file.name]
73
+
74
+ if 'past' not in st.session_state :
75
+ st.session_state['past'] = ['Hey !']
76
+
77
+ # Container for the chat history
78
+ response_container = st.container()
79
+ container = st.container()
80
+
81
+ with container :
82
+ with st.form(key = 'my_form',
83
+ clear_on_submit=True):
84
+ user_input = st.text_input('Query:', placeholder= "Talk to youur CSV Data here ")
85
+ submit_button = st.from_submit_button(label = 'chat')
86
+
87
+ if submit_button and user_input :
88
+ output = conversational_chat(user_input)
89
+
90
+ st.session_state['past'].append(user_input)
91
+ st.session_state['generated'].append(output)
92
+
93
+ if st.session_state['generated'] :
94
+ with response_container:
95
+ for i in range(len(st.session_state['generated'])):
96
+ message(st.session_state['past'][i], is_user = True , key=str(i) + '_user',
97
+ avatar_style='big-smile')
98
+ message(st.session_state['generated'][i], key = str(i), avatar_style='thumb')
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+