Update app.py
Browse files
app.py
CHANGED
@@ -1,124 +1,131 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
import os
|
3 |
-
import logging
|
4 |
-
import faiss
|
5 |
-
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
6 |
-
from langchain_community.embeddings import HuggingFaceEmbeddings
|
7 |
-
from langchain_community.vectorstores import FAISS
|
8 |
-
from langchain_community.llms import HuggingFacePipeline
|
9 |
-
from langchain.chains import RetrievalQA
|
10 |
-
from ingest import create_faiss_index
|
11 |
-
|
12 |
-
# Set up logging
|
13 |
-
logging.basicConfig(level=logging.INFO)
|
14 |
-
logger = logging.getLogger(__name__)
|
15 |
-
|
16 |
-
checkpoint = "LaMini-T5-738M"
|
17 |
-
|
18 |
-
@st.cache_resource
|
19 |
-
def load_llm():
|
20 |
-
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
|
21 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
|
22 |
-
pipe = pipeline(
|
23 |
-
'text2text-generation',
|
24 |
-
model=model,
|
25 |
-
tokenizer=tokenizer,
|
26 |
-
max_length=256,
|
27 |
-
do_sample=True,
|
28 |
-
temperature=0.3,
|
29 |
-
top_p=0.95
|
30 |
-
)
|
31 |
-
return HuggingFacePipeline(pipeline=pipe)
|
32 |
-
|
33 |
-
def validate_index_file(index_path):
|
34 |
-
try:
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
logger.
|
41 |
-
return
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
if not os.path.exists(index_path):
|
50 |
-
st.
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
)
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
st.
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
import logging
|
4 |
+
import faiss
|
5 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
6 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
7 |
+
from langchain_community.vectorstores import FAISS
|
8 |
+
from langchain_community.llms import HuggingFacePipeline
|
9 |
+
from langchain.chains import RetrievalQA
|
10 |
+
from ingest import create_faiss_index
|
11 |
+
|
12 |
+
# Set up logging
|
13 |
+
logging.basicConfig(level=logging.INFO)
|
14 |
+
logger = logging.getLogger(__name__)
|
15 |
+
|
16 |
+
checkpoint = "LaMini-T5-738M"
|
17 |
+
|
18 |
+
@st.cache_resource
|
19 |
+
def load_llm():
|
20 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
|
21 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
|
22 |
+
pipe = pipeline(
|
23 |
+
'text2text-generation',
|
24 |
+
model=model,
|
25 |
+
tokenizer=tokenizer,
|
26 |
+
max_length=256,
|
27 |
+
do_sample=True,
|
28 |
+
temperature=0.3,
|
29 |
+
top_p=0.95
|
30 |
+
)
|
31 |
+
return HuggingFacePipeline(pipeline=pipe)
|
32 |
+
|
33 |
+
def validate_index_file(index_path):
|
34 |
+
try:
|
35 |
+
if os.path.getsize(index_path) == 0:
|
36 |
+
st.error(f"Index file '{index_path}' is empty.")
|
37 |
+
return False
|
38 |
+
with open(index_path, 'rb') as f:
|
39 |
+
data = f.read(100)
|
40 |
+
logger.info(f"Successfully read {len(data)} bytes from the index file")
|
41 |
+
return True
|
42 |
+
except Exception as e:
|
43 |
+
logger.error(f"Error validating index file: {e}")
|
44 |
+
return False
|
45 |
+
|
46 |
+
def load_faiss_index():
|
47 |
+
index_path = "faiss_index/index.faiss"
|
48 |
+
|
49 |
+
if not os.path.exists(index_path) or not validate_index_file(index_path):
|
50 |
+
st.warning("Index file is missing or corrupted. Creating a new one...")
|
51 |
+
if os.path.exists(index_path):
|
52 |
+
os.remove(index_path)
|
53 |
+
st.info("Deleted the corrupted index file.")
|
54 |
+
create_faiss_index()
|
55 |
+
|
56 |
+
if not os.path.exists(index_path):
|
57 |
+
st.error("Failed to create the FAISS index. Please check the 'docs' directory and try again.")
|
58 |
+
raise RuntimeError("FAISS index creation failed.")
|
59 |
+
|
60 |
+
try:
|
61 |
+
index = faiss.read_index(index_path)
|
62 |
+
if index is None:
|
63 |
+
raise ValueError("Failed to read FAISS index.")
|
64 |
+
|
65 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
66 |
+
db = FAISS.load_local("faiss_index", embeddings)
|
67 |
+
if db.index is None or db.index_to_docstore_id is None:
|
68 |
+
raise ValueError("FAISS index or docstore_id mapping is None.")
|
69 |
+
|
70 |
+
return db.as_retriever()
|
71 |
+
except Exception as e:
|
72 |
+
st.error(f"Failed to load FAISS index: {e}")
|
73 |
+
logger.exception("Exception in load_faiss_index")
|
74 |
+
raise
|
75 |
+
|
76 |
+
def process_answer(instruction):
|
77 |
+
try:
|
78 |
+
retriever = load_faiss_index()
|
79 |
+
llm = load_llm()
|
80 |
+
qa = RetrievalQA.from_chain_type(
|
81 |
+
llm=llm,
|
82 |
+
chain_type="stuff",
|
83 |
+
retriever=retriever,
|
84 |
+
return_source_documents=True
|
85 |
+
)
|
86 |
+
generated_text = qa.invoke(instruction)
|
87 |
+
answer = generated_text['result']
|
88 |
+
return answer, generated_text
|
89 |
+
except Exception as e:
|
90 |
+
st.error(f"An error occurred while processing the answer: {e}")
|
91 |
+
logger.exception("Exception in process_answer")
|
92 |
+
return "An error occurred while processing your request.", {}
|
93 |
+
|
94 |
+
def diagnose_faiss_index():
|
95 |
+
index_path = "faiss_index/index.faiss"
|
96 |
+
if os.path.exists(index_path):
|
97 |
+
st.write(f"Index file size: {os.path.getsize(index_path)} bytes")
|
98 |
+
st.write(f"Index file permissions: {oct(os.stat(index_path).st_mode)[-3:]}")
|
99 |
+
st.write(f"Index file owner: {os.stat(index_path).st_uid}")
|
100 |
+
st.write(f"Current process user ID: {os.getuid()}")
|
101 |
+
validate_index_file(index_path)
|
102 |
+
else:
|
103 |
+
st.warning("Index file does not exist.")
|
104 |
+
|
105 |
+
def main():
|
106 |
+
st.title("Search Your PDF ππ")
|
107 |
+
|
108 |
+
with st.expander("About the App"):
|
109 |
+
st.markdown(
|
110 |
+
"""
|
111 |
+
This is a Generative AI powered Question and Answering app that responds to questions about your PDF File.
|
112 |
+
"""
|
113 |
+
)
|
114 |
+
|
115 |
+
diagnose_faiss_index()
|
116 |
+
|
117 |
+
question = st.text_area("Enter your Question")
|
118 |
+
|
119 |
+
if st.button("Ask"):
|
120 |
+
st.info("Your Question: " + question)
|
121 |
+
st.info("Your Answer")
|
122 |
+
try:
|
123 |
+
answer, metadata = process_answer(question)
|
124 |
+
st.write(answer)
|
125 |
+
st.write(metadata)
|
126 |
+
except Exception as e:
|
127 |
+
st.error(f"An unexpected error occurred: {e}")
|
128 |
+
logger.exception("Unexpected error in main function")
|
129 |
+
|
130 |
+
if __name__ == '__main__':
|
131 |
+
main()
|