zeusmadeit commited on
Commit
0bdc732
β€’
1 Parent(s): 821622e

added the chat interface and chat-memory

Browse files
Files changed (1) hide show
  1. app.py +76 -2
app.py CHANGED
@@ -3,9 +3,11 @@ from llama_index.core import StorageContext, load_index_from_storage, VectorStor
3
  from llama_index.llms.huggingface import HuggingFaceInferenceAPI
4
  from dotenv import load_dotenv
5
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
 
6
  from llama_index.core import Settings
7
  import os
8
  import base64
 
9
 
10
 
11
  # Load environment variables
@@ -32,8 +34,80 @@ DATA_DIR = "data"
32
  os.makedirs(DATA_DIR, exist_ok=True)
33
  os.makedirs(PERSIST_DIR, exist_ok=True)
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  # Streamlit app initialization
36
- st.title("Chat with your Doc - PDF Assistant πŸ“„")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- st.markdown("Get insights from your data – just chat!πŸ‘‡")
 
 
39
 
 
3
  from llama_index.llms.huggingface import HuggingFaceInferenceAPI
4
  from dotenv import load_dotenv
5
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
6
+ from llama_index.memory import ChatMemoryBuffer
7
  from llama_index.core import Settings
8
  import os
9
  import base64
10
+ import datetime
11
 
12
 
13
  # Load environment variables
 
34
  os.makedirs(DATA_DIR, exist_ok=True)
35
  os.makedirs(PERSIST_DIR, exist_ok=True)
36
 
37
+
38
+ # Here, a memory token limit of 1500 is set
39
+ memory = ChatMemoryBuffer.from_defaults(token_limit=1500)
40
+
41
+
42
+ def displayPDF(file):
43
+ with open(file, "rb") as f:
44
+ base64_pdf = base64.b64encode(f.read()).decode('utf-8')
45
+ pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
46
+ st.markdown(pdf_display, unsafe_allow_html=True)
47
+
48
+
49
+ def data_ingestion():
50
+ documents = SimpleDirectoryReader(DATA_DIR).load_data()
51
+ storage_context = StorageContext.from_defaults()
52
+ index = VectorStoreIndex.from_documents(documents)
53
+ index.storage_context.persist(persist_dir=PERSIST_DIR)
54
+
55
+
56
+ def handle_query(query):
57
+ storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
58
+ index = load_index_from_storage(storage_context)
59
+ chat_text_qa_msgs = [
60
+ (
61
+ "user",
62
+ """You are a Q&A assistant. Created by Abraham Paul [linkedin](https://www.linkedin.com/in/abraham-paul-16317a235/) a Software / AI Engineer.
63
+ Your primary objective is to provide accurate and helpful answers based on the instructions and context provided.
64
+ If a question falls outside the given context or scope, kindly guide the user to ask questions that align with the provided context.
65
+ Context:
66
+ {context_str}
67
+ Question:
68
+ {query_str}
69
+ """
70
+ )
71
+ ]
72
+ text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
73
+ query_engine = index.as_query_engine(text_qa_template=text_qa_template, memory=memory)
74
+ answer = query_engine.query(query)
75
+
76
+ if hasattr(answer, 'response'):
77
+ return answer.response
78
+ elif isinstance(answer, dict) and 'response' in answer:
79
+ return answer['response']
80
+ else:
81
+ return "Sorry, I couldn't find an answer."
82
+
83
+
84
  # Streamlit app initialization
85
+ st.title("PDF Chatbot - with your doc")
86
+ st.markdown("Get insights from your data – just ask!πŸ‘‡")
87
+
88
+ if 'messages' not in st.session_state:
89
+ st.session_state.messages = [{'role': 'assistant', "content": 'Upload your pdf doc and ask me anything about it, Lets chat!!'}]
90
+
91
+ with st.sidebar:
92
+ st.markdown("**Created by [Abraham](https://www.linkedin.com/in/abraham-paul-16317a235/)**")
93
+ st.title(':blue[Get Started]:')
94
+ uploaded_file = st.file_uploader("Upload your PDF and Click Submit")
95
+ if st.button("Submit"):
96
+ with st.spinner("Processing..."):
97
+ filepath = "data/saved_pdf.pdf"
98
+ with open(filepath, "wb") as f:
99
+ f.write(uploaded_file.getbuffer())
100
+ data_ingestion() # Process PDF every time new file is uploaded
101
+ st.success("Done")
102
+
103
+ user_prompt = st.chat_input("Ask me anything from the uploaded document:")
104
+
105
+ if user_prompt:
106
+ st.session_state.messages.append({'role': 'user', "content": user_prompt})
107
+ response = handle_query(user_prompt)
108
+ st.session_state.messages.append({'role': 'assistant', "content": response})
109
 
110
+ for message in st.session_state.messages:
111
+ with st.chat_message(message['role']):
112
+ st.write(message['content'])
113