themanas021 commited on
Commit
08f62dc
·
1 Parent(s): ac44904

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -40
app.py CHANGED
@@ -1,12 +1,19 @@
1
- import streamlit as st
2
  import os
3
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
 
 
4
  from transformers import pipeline
5
- import torch
6
- from langchain.embeddings import SentenceTransformerEmbeddings
7
- from langchain.vectorstores import Chroma
 
 
 
8
  from langchain.llms import HuggingFacePipeline
9
- from langchain.chains import RetrievalQA
 
 
10
 
11
  st.set_page_config(layout="wide")
12
 
@@ -21,28 +28,45 @@ base_model = AutoModelForSeq2SeqLM.from_pretrained(
21
  torch_dtype=torch.float32
22
  )
23
 
24
- persist_directory = "db"
25
 
26
- @st.cache_resource
27
- def data_ingestion(pdf_content):
28
- # Process the PDF content here and generate a brief summary.
29
- # You can use libraries like PyPDF2, pdfminer, or other PDF processing tools.
 
 
 
 
30
 
31
- # For now, let's assume we have extracted the text from the PDF.
32
- pdf_text = "This is a brief summary of the PDF content."
33
 
34
- return pdf_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  @st.cache_resource
37
  def llm_pipeline():
38
  pipe = pipeline(
39
  'text2text-generation',
40
- model=base_model,
41
- tokenizer=tokenizer,
42
- max_length=256,
43
- do_sample=True,
44
- temperature=0.3,
45
- top_p=0.95,
46
  device=device
47
  )
48
  local_llm = HuggingFacePipeline(pipeline=pipe)
@@ -52,12 +76,12 @@ def llm_pipeline():
52
  def qa_llm():
53
  llm = llm_pipeline()
54
  embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
55
- db = Chroma(persist_directory="db", embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
56
  retriever = db.as_retriever()
57
  qa = RetrievalQA.from_chain_type(
58
- llm=llm,
59
- chain_type="stuff",
60
- retriever=retriever,
61
  return_source_documents=True
62
  )
63
  return qa
@@ -70,29 +94,87 @@ def process_answer(instruction):
70
  answer = generated_text['result']
71
  return answer
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  def main():
74
  st.markdown("<h1 style='text-align: center; color: blue;'>Chat with your PDF 🦜📄 </h1>", unsafe_allow_html=True)
75
- st.markdown("<h3 style='text-align: center; color: grey;'>Built by <a href='https://github.com/manas95826'>The Manas with ❤️ </a></h3>", unsafe_allow_html=True)
76
 
77
- st.markdown("<h2 style='text-align: center; color:red;'>Ask Questions about your PDF 👇</h2>", unsafe_allow_html=True)
78
 
79
- user_input = st.text_input("Ask a question:", key="input")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- # Initialize session state for generated responses
82
- if "generated" not in st.session_state:
83
- st.session_state["generated"] = []
84
 
85
- # Search the database for a response based on user input and update session state
86
- if user_input:
87
- answer = process_answer({'query': user_input})
88
- st.session_state["generated"].append(answer)
89
 
90
- # Display conversation history using Streamlit messages
91
- if st.session_state["generated"]:
92
- st.markdown("<h4>Conversation History:</h4>", unsafe_allow_html=True)
93
- for i, response in enumerate(st.session_state["generated"]):
94
- st.text(f"Q{i+1}: {user_input}")
95
- st.text(f"A{i+1}: {response}")
96
 
97
  if __name__ == "__main__":
98
  main()
 
 
1
+ import streamlit as st
2
  import os
3
+ import base64
4
+ import time
5
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
6
  from transformers import pipeline
7
+ import torch
8
+ import textwrap
9
+ from langchain.document_loaders import PyPDFLoader, DirectoryLoader, PDFMinerLoader
10
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
11
+ from langchain.embeddings import SentenceTransformerEmbeddings
12
+ from langchain.vectorstores import Chroma
13
  from langchain.llms import HuggingFacePipeline
14
+ from langchain.chains import RetrievalQA
15
+ from constants import CHROMA_SETTINGS
16
+ from streamlit_chat import message
17
 
18
  st.set_page_config(layout="wide")
19
 
 
28
  torch_dtype=torch.float32
29
  )
30
 
 
31
 
32
+ # checkpoint = "LaMini-T5-738M"
33
+ # tokenizer = AutoTokenizer.from_pretrained(checkpoint)
34
+ # base_model = AutoModelForSeq2SeqLM.from_pretrained(
35
+ # checkpoint,
36
+ # device_map="auto",
37
+ # torch_dtype = torch.float32,
38
+ # from_tf=True
39
+ # )
40
 
41
+ persist_directory = "db"
 
42
 
43
+ @st.cache_resource
44
+ def data_ingestion():
45
+ for root, dirs, files in os.walk("docs"):
46
+ for file in files:
47
+ if file.endswith(".pdf"):
48
+ print(file)
49
+ loader = PDFMinerLoader(os.path.join(root, file))
50
+ documents = loader.load()
51
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=500)
52
+ texts = text_splitter.split_documents(documents)
53
+ #create embeddings here
54
+ embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
55
+ #create vector store here
56
+ db = Chroma.from_documents(texts, embeddings, persist_directory=persist_directory, client_settings=CHROMA_SETTINGS)
57
+ db.persist()
58
+ db=None
59
 
60
  @st.cache_resource
61
  def llm_pipeline():
62
  pipe = pipeline(
63
  'text2text-generation',
64
+ model = base_model,
65
+ tokenizer = tokenizer,
66
+ max_length = 256,
67
+ do_sample = True,
68
+ temperature = 0.3,
69
+ top_p= 0.95,
70
  device=device
71
  )
72
  local_llm = HuggingFacePipeline(pipeline=pipe)
 
76
  def qa_llm():
77
  llm = llm_pipeline()
78
  embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
79
+ db = Chroma(persist_directory="db", embedding_function = embeddings, client_settings=CHROMA_SETTINGS)
80
  retriever = db.as_retriever()
81
  qa = RetrievalQA.from_chain_type(
82
+ llm = llm,
83
+ chain_type = "stuff",
84
+ retriever = retriever,
85
  return_source_documents=True
86
  )
87
  return qa
 
94
  answer = generated_text['result']
95
  return answer
96
 
97
+ def get_file_size(file):
98
+ file.seek(0, os.SEEK_END)
99
+ file_size = file.tell()
100
+ file.seek(0)
101
+ return file_size
102
+
103
+ @st.cache_data
104
+ #function to display the PDF of a given file
105
+ def displayPDF(file):
106
+ # Opening file from file path
107
+ with open(file, "rb") as f:
108
+ base64_pdf = base64.b64encode(f.read()).decode('utf-8')
109
+
110
+ # Embedding PDF in HTML
111
+ pdf_display = F'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
112
+
113
+ # Displaying File
114
+ st.markdown(pdf_display, unsafe_allow_html=True)
115
+
116
+ # Display conversation history using Streamlit messages
117
+ def display_conversation(history):
118
+ for i in range(len(history["generated"])):
119
+ message(history["past"][i], is_user=True, key=str(i) + "_user")
120
+ message(history["generated"][i],key=str(i))
121
+
122
  def main():
123
  st.markdown("<h1 style='text-align: center; color: blue;'>Chat with your PDF 🦜📄 </h1>", unsafe_allow_html=True)
124
+ st.markdown("<h3 style='text-align: center; color: grey;'>Built by <a href='https://github.com/AIAnytime'>AI Anytime with ❤️ </a></h3>", unsafe_allow_html=True)
125
 
126
+ st.markdown("<h2 style='text-align: center; color:red;'>Upload your PDF 👇</h2>", unsafe_allow_html=True)
127
 
128
+ uploaded_file = st.file_uploader("", type=["pdf"])
129
+
130
+ if uploaded_file is not None:
131
+ file_details = {
132
+ "Filename": uploaded_file.name,
133
+ "File size": get_file_size(uploaded_file)
134
+ }
135
+ filepath = "docs/"+uploaded_file.name
136
+ with open(filepath, "wb") as temp_file:
137
+ temp_file.write(uploaded_file.read())
138
+
139
+ col1, col2= st.columns([1,2])
140
+ with col1:
141
+ st.markdown("<h4 style color:black;'>File details</h4>", unsafe_allow_html=True)
142
+ st.json(file_details)
143
+ st.markdown("<h4 style color:black;'>File preview</h4>", unsafe_allow_html=True)
144
+ pdf_view = displayPDF(filepath)
145
+
146
+ with col2:
147
+ with st.spinner('Embeddings are in process...'):
148
+ ingested_data = data_ingestion()
149
+ st.success('Embeddings are created successfully!')
150
+ st.markdown("<h4 style color:black;'>Chat Here</h4>", unsafe_allow_html=True)
151
+
152
+
153
+ user_input = st.text_input("", key="input")
154
+
155
+ # Initialize session state for generated responses and past messages
156
+ if "generated" not in st.session_state:
157
+ st.session_state["generated"] = ["I am ready to help you"]
158
+ if "past" not in st.session_state:
159
+ st.session_state["past"] = ["Hey there!"]
160
+
161
+ # Search the database for a response based on user input and update session state
162
+ if user_input:
163
+ answer = process_answer({'query': user_input})
164
+ st.session_state["past"].append(user_input)
165
+ response = answer
166
+ st.session_state["generated"].append(response)
167
+
168
+ # Display conversation history using Streamlit messages
169
+ if st.session_state["generated"]:
170
+ display_conversation(st.session_state)
171
+
172
+
173
+
174
 
 
 
 
175
 
 
 
 
 
176
 
 
 
 
 
 
 
177
 
178
  if __name__ == "__main__":
179
  main()
180
+