aaporosh commited on
Commit
11694c7
·
verified ·
1 Parent(s): fecb449

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -82
app.py CHANGED
@@ -1,93 +1,157 @@
 
1
  import streamlit as st
2
- import pdfplumber
3
- import re
 
 
4
  from langchain.text_splitter import RecursiveCharacterTextSplitter
5
- from langchain.vectorstores import FAISS
6
- from langchain.embeddings import HuggingFaceEmbeddings
7
- from langchain.chat_models import ChatOpenAI
8
- from langchain.chains import ConversationalRetrievalChain
9
  from transformers import pipeline
 
10
 
11
- # -------------------- PAGE CONFIG --------------------
12
- st.set_page_config(page_title="Smart PDF Chatbot", layout="wide")
13
 
14
- # -------------------- MODELS --------------------
15
- @st.cache_resource
16
- def load_models():
17
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
18
- summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
19
- return embeddings, summarizer
 
 
 
 
 
 
 
 
20
 
21
- embeddings, summarizer = load_models()
 
 
 
 
 
22
 
23
- # -------------------- TITLE --------------------
24
- st.title("📄 Smart PDF Chatbot & Summarizer")
 
25
 
26
- # -------------------- UPLOAD PDF --------------------
27
- uploaded_file = st.file_uploader("📤 Upload your PDF file", type=["pdf"])
 
28
 
29
- if uploaded_file:
30
- # Extract text from PDF
31
- with pdfplumber.open(uploaded_file) as pdf:
32
- text = "\n".join([page.extract_text() for page in pdf.pages if page.extract_text()])
33
 
34
- if not text.strip():
35
- st.error("⚠️ Could not extract text from this PDF.")
36
- else:
37
- # Split into chunks for better retrieval
38
- splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
39
- chunks = splitter.split_text(text)
40
-
41
- # Build vector store for retrieval
42
- vector_store = FAISS.from_texts(chunks, embedding=embeddings)
43
- retriever = vector_store.as_retriever()
44
-
45
- # Create conversational chain with memory
46
- llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
47
- qa_chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=retriever)
48
-
49
- # Tabs for Chat, Summary, and Code
50
- tabs = st.tabs(["💬 Chat with PDF", "📝 Summarize PDF", "💻 Extract Code"])
51
-
52
- # -------------------- CHAT TAB --------------------
53
- with tabs[0]:
54
- st.subheader("Ask Questions About Your PDF")
55
- if "chat_history" not in st.session_state:
56
- st.session_state.chat_history = []
57
-
58
- user_input = st.text_input("Enter your question:", key="chat_input")
59
- if st.button("Send"):
60
- result = qa_chain({"question": user_input, "chat_history": st.session_state.chat_history})
61
- st.session_state.chat_history.append((user_input, result["answer"]))
62
-
63
- for q, a in st.session_state.chat_history:
64
- st.markdown(f"**You:** {q}")
65
- st.markdown(f"**Bot:** {a}")
66
-
67
- # -------------------- SUMMARY TAB --------------------
68
- with tabs[1]:
69
- st.subheader("📘 PDF Summary")
70
- if st.button("Generate Summary", key="sum"):
71
  try:
72
- # Summarize in chunks for long PDFs
73
- summaries = []
74
- for i in range(0, len(chunks), 3):
75
- chunk_text = " ".join(chunks[i:i+3])
76
- summary = summarizer(chunk_text, max_length=150, min_length=30, do_sample=False)
77
- summaries.append(summary[0]['summary_text'])
78
- final_summary = " ".join(summaries)
79
- st.info(final_summary)
80
- except Exception as e:
81
- st.error(f"Summarization error: {e}")
82
-
83
- # -------------------- CODE EXTRACTION TAB --------------------
84
- with tabs[2]:
85
- st.subheader("🧑‍💻 Extracted Code Blocks")
86
- code_blocks = re.findall(r"```[a-zA-Z]*([\s\S]*?)```", text)
87
- if code_blocks:
88
- for idx, code in enumerate(code_blocks, 1):
89
- st.code(code, language="python")
90
- else:
91
- st.warning("No code blocks found in this PDF.")
92
- else:
93
- st.info("👆 Please upload a PDF to get started.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------- app.py -------------
2
  import streamlit as st
3
+ from pathlib import Path
4
+ from io import BytesIO
5
+ import pdfplumber, pytesseract, time, re, logging, os
6
+ from PIL import Image
7
  from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain_community.vectorstores import FAISS
9
+ from sentence_transformers import SentenceTransformer
 
 
10
  from transformers import pipeline
11
+ import numpy as np
12
 
13
+ logging.basicConfig(level=logging.INFO)
14
+ logger = logging.getLogger(__name__)
15
 
16
+ ###############################################################################
17
+ # Page layout
18
+ ###############################################################################
19
+ st.set_page_config(page_title="PDF Chat & Summarize", layout="wide")
20
+ st.markdown("""
21
+ <style>
22
+ .block-container { padding-top: 1rem; padding-bottom: 0; }
23
+ .stTabs [data-baseweb="tab-list"] { gap: 4px; }
24
+ .stTabs [data-baseweb="tab"] { padding: 8px 24px; }
25
+ .chat-msg { padding: 0.5rem 1rem; border-radius: 8px; margin: 0.3rem 0; }
26
+ .user { background-color: #e3f2fd; margin-left: 20%; }
27
+ .assistant { background-color: #f1f3f4; margin-right: 20%; }
28
+ </style>
29
+ """, unsafe_allow_html=True)
30
 
31
+ ###############################################################################
32
+ # Cached heavy objects
33
+ ###############################################################################
34
+ @st.cache_resource(show_spinner=False)
35
+ def load_embed():
36
+ return SentenceTransformer("all-MiniLM-L6-v2")
37
 
38
+ @st.cache_resource(show_spinner=False)
39
+ def load_qa():
40
+ return pipeline("text2text-generation", model="google/flan-t5-large", max_length=512)
41
 
42
+ @st.cache_resource(show_spinner=False)
43
+ def load_sum():
44
+ return pipeline("summarization", model="facebook/bart-large-cnn", max_length=250)
45
 
46
+ embed = load_embed()
47
+ qa_pipe = load_qa()
48
+ sum_pipe = load_sum()
 
49
 
50
+ ###############################################################################
51
+ # Helpers
52
+ ###############################################################################
53
+ def extract_pdf(uploaded_file):
54
+ """Return (plain text, image_list)"""
55
+ text = ""
56
+ images = []
57
+ with pdfplumber.open(BytesIO(uploaded_file.getbuffer())) as pdf:
58
+ for page in pdf.pages:
59
+ txt = page.extract_text_layout() or page.extract_text()
60
+ if not txt:
61
+ img = page.to_image(resolution=200).original
62
+ txt = pytesseract.image_to_string(img)
63
+ text += txt + "\n"
64
+ for img in page.images:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  try:
66
+ x0, y0, x1, y1 = img["x0"], img["y0"], img["x1"], img["y1"]
67
+ pil = page.within_bbox((x0, y0, x1, y1)).to_image(resolution=200).original
68
+ images.append(pil)
69
+ except Exception:
70
+ pass
71
+ return text.strip(), images
72
+
73
+ def build_index(text):
74
+ splitter = RecursiveCharacterTextSplitter(chunk_size=600, chunk_overlap=80)
75
+ chunks = splitter.split_text(text)
76
+ vectors = embed.encode(chunks, show_progress_bar=False, batch_size=64)
77
+ index = FAISS.from_embeddings(list(zip(chunks, vectors)), embed)
78
+ return index
79
+
80
+ def summarize(text):
81
+ if len(text) < 50:
82
+ return "Document too short to summarize."
83
+ # pick top 3k chars to stay within model limit
84
+ truncated = text[:3000]
85
+ return sum_pipe(truncated, max_length=250, min_length=60, do_sample=False)[0]["summary_text"]
86
+
87
+ def answer(question, index):
88
+ if index is None:
89
+ return "Please upload & process a PDF first."
90
+ docs = index.similarity_search(question, k=4)
91
+ context = "\n".join([d.page_content for d in docs])
92
+ prompt = f"Answer the question using ONLY the context below.\n\nContext:\n{context}\n\nQuestion: {question}"
93
+ return qa_pipe(prompt, max_length=256, do_sample=False)[0]["generated_text"]
94
+
95
+ ###############################################################################
96
+ # Session init
97
+ ###############################################################################
98
+ if "messages" not in st.session_state:
99
+ st.session_state.messages = []
100
+ if "index" not in st.session_state:
101
+ st.session_state.index = None
102
+ if "raw_text" not in st.session_state:
103
+ st.session_state.raw_text = ""
104
+ if "images" not in st.session_state:
105
+ st.session_state.images = []
106
+
107
+ ###############################################################################
108
+ # Sidebar
109
+ ###############################################################################
110
+ with st.sidebar:
111
+ st.subheader("📁 Upload PDF")
112
+ uploaded = st.file_uploader("Choose a file", type="pdf", label_visibility="collapsed")
113
+ if uploaded and st.button("Process PDF"):
114
+ with st.spinner("Extracting text & images…"):
115
+ st.session_state.raw_text, st.session_state.images = extract_pdf(uploaded)
116
+ st.session_state.index = build_index(st.session_state.raw_text)
117
+ st.session_state.messages = []
118
+ st.toast("PDF ready!")
119
+
120
+ if st.session_state.images:
121
+ st.subheader("🖼️ Extracted Images")
122
+ for im in st.session_state.images:
123
+ st.image(im, use_column_width=True)
124
+
125
+ ###############################################################################
126
+ # Main Tabs
127
+ ###############################################################################
128
+ tab_chat, tab_sum = st.tabs(["💬 Chat", "📄 Summarize"])
129
+
130
+ with tab_chat:
131
+ if st.session_state.index is None:
132
+ st.info("Upload & process a PDF first using the sidebar.")
133
+ else:
134
+ # history
135
+ for role, msg in st.session_state.messages:
136
+ css = "user" if role == "user" else "assistant"
137
+ st.markdown(f'<div class="chat-msg {css}">{msg}</div>', unsafe_allow_html=True)
138
+
139
+ # input
140
+ if question := st.chat_input("Ask anything about the PDF…"):
141
+ st.session_state.messages.append(("user", question))
142
+ st.markdown(f'<div class="chat-msg user">{question}</div>', unsafe_allow_html=True)
143
+
144
+ with st.spinner("Thinking…"):
145
+ resp = answer(question, st.session_state.index)
146
+ st.session_state.messages.append(("assistant", resp))
147
+ st.markdown(f'<div class="chat-msg assistant">{resp}</div>', unsafe_allow_html=True)
148
+
149
+ with tab_sum:
150
+ if not st.session_state.raw_text:
151
+ st.info("Upload & process a PDF first.")
152
+ else:
153
+ if st.button("Generate Summary"):
154
+ with st.spinner("Summarizing…"):
155
+ summary = summarize(st.session_state.raw_text)
156
+ st.subheader("Summary")
157
+ st.write(summary)