Preetham04 commited on
Commit
b31b797
Β·
verified Β·
1 Parent(s): d84c217

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -0
app.py CHANGED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
20
+ device = torch.device('cpu')
21
+
22
+ checkpoint = "MBZUAI/LaMini-T5-738M"
23
+ print(f"Checkpoint path: {checkpoint}") # Add this line for debugging
24
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint)
25
+ base_model = AutoModelForSeq2SeqLM.from_pretrained(
26
+ checkpoint,
27
+ device_map=device,
28
+ torch_dtype=torch.float32
29
+ )
30
+
31
+ persist_directory = "db"
32
+
33
+ @st.cache_resource
34
+ def data_ingestion():
35
+ for root, dirs, files in os.walk("docs"):
36
+ for file in files:
37
+ if file.endswith(".pdf"):
38
+ print(file)
39
+ loader = PDFMinerLoader(os.path.join(root, file))
40
+ documents = loader.load()
41
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=500)
42
+ texts = text_splitter.split_documents(documents)
43
+ #create embeddings here
44
+ embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
45
+ #create vector store here
46
+ db = Chroma.from_documents(texts, embeddings, persist_directory=persist_directory, client_settings=CHROMA_SETTINGS)
47
+ db.persist()
48
+ db=None
49
+
50
+ @st.cache_resource
51
+ def llm_pipeline():
52
+ pipe = pipeline(
53
+ 'text2text-generation',
54
+ model = base_model,
55
+ tokenizer = tokenizer,
56
+ max_length = 256,
57
+ do_sample = True,
58
+ temperature = 0.3,
59
+ top_p= 0.95,
60
+ device=device
61
+ )
62
+ local_llm = HuggingFacePipeline(pipeline=pipe)
63
+ return local_llm
64
+
65
+ @st.cache_resource
66
+ def qa_llm():
67
+ llm = llm_pipeline()
68
+ embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
69
+ db = Chroma(persist_directory="db", embedding_function = embeddings, client_settings=CHROMA_SETTINGS)
70
+ retriever = db.as_retriever()
71
+ qa = RetrievalQA.from_chain_type(
72
+ llm = llm,
73
+ chain_type = "stuff",
74
+ retriever = retriever,
75
+ return_source_documents=True
76
+ )
77
+ return qa
78
+
79
+ def process_answer(instruction):
80
+ response = ''
81
+ instruction = instruction
82
+ qa = qa_llm()
83
+ generated_text = qa(instruction)
84
+ answer = generated_text['result']
85
+ return answer
86
+
87
+ def get_file_size(file):
88
+ file.seek(0, os.SEEK_END)
89
+ file_size = file.tell()
90
+ file.seek(0)
91
+ return file_size
92
+
93
+ @st.cache_data
94
+ #function to display the PDF of a given file
95
+ def displayPDF(file):
96
+ # Opening file from file path
97
+ with open(file, "rb") as f:
98
+ base64_pdf = base64.b64encode(f.read()).decode('utf-8')
99
+
100
+ # Embedding PDF in HTML
101
+ pdf_display = F'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
102
+
103
+ # Displaying File
104
+ st.markdown(pdf_display, unsafe_allow_html=True)
105
+
106
+ # Display conversation history using Streamlit messages
107
+ def display_conversation(history):
108
+ for i in range(len(history["generated"])):
109
+ message(history["past"][i], is_user=True, key=str(i) + "_user")
110
+ message(history["generated"][i],key=str(i))
111
+
112
+ def main():
113
+ st.markdown("<h1 style='text-align: center; color: blue;'>Chat with your PDF πŸ¦œπŸ“„ </h1>", unsafe_allow_html=True)
114
+ 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)
115
+
116
+ st.markdown("<h2 style='text-align: center; color:red;'>Upload your PDF πŸ‘‡</h2>", unsafe_allow_html=True)
117
+
118
+ uploaded_file = st.file_uploader("", type=["pdf"])
119
+
120
+ if uploaded_file is not None:
121
+ file_details = {
122
+ "Filename": uploaded_file.name,
123
+ "File size": get_file_size(uploaded_file)
124
+ }
125
+ filepath = "docs/"+uploaded_file.name
126
+ with open(filepath, "wb") as temp_file:
127
+ temp_file.write(uploaded_file.read())
128
+
129
+ col1, col2= st.columns([1,2])
130
+ with col1:
131
+ st.markdown("<h4 style color:black;'>File details</h4>", unsafe_allow_html=True)
132
+ st.json(file_details)
133
+ st.markdown("<h4 style color:black;'>File preview</h4>", unsafe_allow_html=True)
134
+ pdf_view = displayPDF(filepath)
135
+
136
+ with col2:
137
+ with st.spinner('Embeddings are in process...'):
138
+ ingested_data = data_ingestion()
139
+ st.success('Embeddings are created successfully!')
140
+ st.markdown("<h4 style color:black;'>Chat Here</h4>", unsafe_allow_html=True)
141
+
142
+
143
+ user_input = st.text_input("", key="input")
144
+
145
+ # Initialize session state for generated responses and past messages
146
+ if "generated" not in st.session_state:
147
+ st.session_state["generated"] = ["I am ready to help you"]
148
+ if "past" not in st.session_state:
149
+ st.session_state["past"] = ["Hey there!"]
150
+
151
+ # Search the database for a response based on user input and update session state
152
+ if user_input:
153
+ answer = process_answer({'query': user_input})
154
+ st.session_state["past"].append(user_input)
155
+ response = answer
156
+ st.session_state["generated"].append(response)
157
+
158
+ # Display conversation history using Streamlit messages
159
+ if st.session_state["generated"]:
160
+ display_conversation(st.session_state)
161
+
162
+
163
+
164
+
165
+
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()