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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 3 |
+
from langchain_core.messages import SystemMessage, HumanMessage
|
| 4 |
+
from langchain_core.output_parsers import PydanticOutputParser
|
| 5 |
+
from langchain_core.prompts import PromptTemplate
|
| 6 |
+
from langchain.chains import LLMChain
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
from typing import List
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
import os
|
| 11 |
+
import time
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
import PyPDF2
|
| 14 |
+
from fpdf import FPDF
|
| 15 |
+
from docx import Document
|
| 16 |
+
import io
|
| 17 |
+
from langchain_community.embeddings import HuggingFaceInferenceAPIEmbeddings
|
| 18 |
+
from langchain_community.vectorstores import FAISS
|
| 19 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
load_dotenv()
|
| 23 |
+
api_key = os.getenv("GOOGLE_API_KEY")
|
| 24 |
+
|
| 25 |
+
llm = ChatGoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=api_key)
|
| 26 |
+
|
| 27 |
+
class KeyPoint(BaseModel):
|
| 28 |
+
point: str = Field(description="A key point extracted from the document.")
|
| 29 |
+
|
| 30 |
+
class Summary(BaseModel):
|
| 31 |
+
summary: str = Field(description="A brief summary of the document content.")
|
| 32 |
+
|
| 33 |
+
class DocumentAnalysis(BaseModel):
|
| 34 |
+
key_points: List[KeyPoint] = Field(description="List of key points from the document.")
|
| 35 |
+
summary: Summary = Field(description="Summary of the document.")
|
| 36 |
+
|
| 37 |
+
parser = PydanticOutputParser(pydantic_object=DocumentAnalysis)
|
| 38 |
+
|
| 39 |
+
prompt_template = """
|
| 40 |
+
Analyze the following text and extract key points and a summary.
|
| 41 |
+
{format_instructions}
|
| 42 |
+
Text: {text}
|
| 43 |
+
"""
|
| 44 |
+
prompt = PromptTemplate(
|
| 45 |
+
template=prompt_template,
|
| 46 |
+
input_variables=["text"],
|
| 47 |
+
partial_variables={"format_instructions": parser.get_format_instructions()}
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
chain = LLMChain(llm=llm, prompt=prompt, output_parser=parser)
|
| 51 |
+
|
| 52 |
+
def analyze_text_structured(text):
|
| 53 |
+
output = chain.run(text=text)
|
| 54 |
+
return output
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def extract_text_from_pdf(pdf_file):
|
| 58 |
+
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
| 59 |
+
text = ""
|
| 60 |
+
for page in pdf_reader.pages:
|
| 61 |
+
text += page.extract_text()
|
| 62 |
+
return text
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def json_to_text(analysis):
|
| 66 |
+
text_output = "=== Summary ===\n" + f"{analysis.summary.summary}\n\n"
|
| 67 |
+
text_output += "=== Key Points ===\n"
|
| 68 |
+
for i, key_point in enumerate(analysis.key_points, start=1):
|
| 69 |
+
text_output += f"{i}. {key_point.point}\n"
|
| 70 |
+
return text_output
|
| 71 |
+
|
| 72 |
+
def create_pdf_report(analysis):
|
| 73 |
+
pdf = FPDF()
|
| 74 |
+
pdf.add_page()
|
| 75 |
+
pdf.set_font('Helvetica', '', 12)
|
| 76 |
+
pdf.cell(200, 10, txt="PDF Analysis Report", ln=True, align='C')
|
| 77 |
+
pdf.cell(200, 10, txt=f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
|
| 78 |
+
clean_text = json_to_text(analysis)
|
| 79 |
+
pdf.multi_cell(0, 10, txt=clean_text)
|
| 80 |
+
return pdf.output(dest='S')
|
| 81 |
+
|
| 82 |
+
def create_word_report(analysis):
|
| 83 |
+
doc = Document()
|
| 84 |
+
doc.add_heading('PDF Analysis Report', 0)
|
| 85 |
+
doc.add_paragraph(f'Generated on: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
|
| 86 |
+
clean_text = json_to_text(analysis)
|
| 87 |
+
doc.add_heading('Analysis', level=1)
|
| 88 |
+
doc.add_paragraph(clean_text)
|
| 89 |
+
docx_bytes = io.BytesIO()
|
| 90 |
+
doc.save(docx_bytes)
|
| 91 |
+
docx_bytes.seek(0)
|
| 92 |
+
return docx_bytes.getvalue()
|
| 93 |
+
|
| 94 |
+
st.set_page_config(page_title="Chat With PDF", page_icon="😒")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def local_css():
|
| 98 |
+
st.markdown("""
|
| 99 |
+
<style>
|
| 100 |
+
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&family=Orbitron:wght@400;700&display=swap');
|
| 101 |
+
body {
|
| 102 |
+
font-family: 'Montserrat', sans-serif;
|
| 103 |
+
background: linear-gradient(135deg, #0A0A0A 0%, #1A1A1A 100%);
|
| 104 |
+
color: #FFFFFF;
|
| 105 |
+
}
|
| 106 |
+
h1, h2, h3 { font-family: 'Orbitron', sans-serif; }
|
| 107 |
+
.main-header {
|
| 108 |
+
position: fixed;
|
| 109 |
+
top: 0;
|
| 110 |
+
width: 100%;
|
| 111 |
+
text-align: center;
|
| 112 |
+
padding: 1.5rem;
|
| 113 |
+
background: rgba(0, 0, 0, 0.8);
|
| 114 |
+
border-bottom: 2px solid #00FFFF;
|
| 115 |
+
box-shadow: 0 0 15px #00FFFF;
|
| 116 |
+
animation: slideInLeft 0.5s ease-in;
|
| 117 |
+
z-index: 1000;
|
| 118 |
+
}
|
| 119 |
+
.flag-stripe {
|
| 120 |
+
height: 6px;
|
| 121 |
+
background: linear-gradient(90deg, #FF00FF 33%, #00FFFF 66%, #00FF00 100%);
|
| 122 |
+
animation: slideInLeft 0.5s ease-in;
|
| 123 |
+
}
|
| 124 |
+
.stTextInput > div > input {
|
| 125 |
+
border-radius: 20px;
|
| 126 |
+
padding: 0.8rem 2rem;
|
| 127 |
+
background: rgba(0, 0, 0, 0.7);
|
| 128 |
+
border: 2px solid #00FFFF;
|
| 129 |
+
color: #FFFFFF;
|
| 130 |
+
transition: all 0.3s ease;
|
| 131 |
+
}
|
| 132 |
+
.stTextInput > div > input:focus {
|
| 133 |
+
border-color: #FF00FF;
|
| 134 |
+
box-shadow: 0 0 15px #FF00FF;
|
| 135 |
+
}
|
| 136 |
+
.stButton > button {
|
| 137 |
+
border-radius: 20px;
|
| 138 |
+
padding: 0.6rem 1.5rem;
|
| 139 |
+
background: linear-gradient(135deg, #00FFFF, #FF00FF);
|
| 140 |
+
color: #000000;
|
| 141 |
+
border: none;
|
| 142 |
+
font-weight: bold;
|
| 143 |
+
text-transform: uppercase;
|
| 144 |
+
box-shadow: 0 0 10px #00FFFF;
|
| 145 |
+
transition: all 0.3s ease;
|
| 146 |
+
}
|
| 147 |
+
.stButton > button:hover {
|
| 148 |
+
transform: scale(1.05);
|
| 149 |
+
box-shadow: 0 0 20px #FF00FF;
|
| 150 |
+
}
|
| 151 |
+
.card {
|
| 152 |
+
background: rgba(255, 255, 255, 0.1);
|
| 153 |
+
backdrop-filter: blur(10px);
|
| 154 |
+
border-radius: 15px;
|
| 155 |
+
border: 1px solid rgba(0, 255, 255, 0.3);
|
| 156 |
+
padding: 1.5rem;
|
| 157 |
+
margin: 1rem 0;
|
| 158 |
+
transition: all 0.3s ease;
|
| 159 |
+
}
|
| 160 |
+
.card:hover {
|
| 161 |
+
transform: translateY(-5px);
|
| 162 |
+
box-shadow: 0 0 20px #FF00FF;
|
| 163 |
+
}
|
| 164 |
+
.footer {
|
| 165 |
+
position: fixed;
|
| 166 |
+
bottom: 0;
|
| 167 |
+
width: 100%;
|
| 168 |
+
background: rgba(0, 0, 0, 0.9);
|
| 169 |
+
padding: 1rem;
|
| 170 |
+
text-align: center;
|
| 171 |
+
border-top: 2px solid #00FFFF;
|
| 172 |
+
animation: fadeIn 0.5s ease-in;
|
| 173 |
+
}
|
| 174 |
+
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
| 175 |
+
@keyframes slideInLeft { from { transform: translateX(-100%); } to { transform: translateX(0); } }
|
| 176 |
+
</style>
|
| 177 |
+
""", unsafe_allow_html=True)
|
| 178 |
+
|
| 179 |
+
local_css()
|
| 180 |
+
|
| 181 |
+
if "current_file" not in st.session_state:
|
| 182 |
+
st.session_state.current_file = None
|
| 183 |
+
if "pdf_summary" not in st.session_state:
|
| 184 |
+
st.session_state.pdf_summary = None
|
| 185 |
+
if "analysis_time" not in st.session_state:
|
| 186 |
+
st.session_state.analysis_time = 0
|
| 187 |
+
if "pdf_report" not in st.session_state:
|
| 188 |
+
st.session_state.pdf_report = None
|
| 189 |
+
if "word_report" not in st.session_state:
|
| 190 |
+
st.session_state.word_report = None
|
| 191 |
+
if "vectorstore" not in st.session_state:
|
| 192 |
+
st.session_state.vectorstore = None
|
| 193 |
+
if "messages" not in st.session_state:
|
| 194 |
+
st.session_state.messages = []
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
st.markdown('<div class="main-header">', unsafe_allow_html=True)
|
| 198 |
+
st.markdown('<div class="flag-stripe"></div>', unsafe_allow_html=True)
|
| 199 |
+
st.title("😒 Chat With PDF")
|
| 200 |
+
st.caption("Your AI-powered Document Analyzer")
|
| 201 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 202 |
+
|
| 203 |
+
st.markdown('<div class="card animate-fadeIn">', unsafe_allow_html=True)
|
| 204 |
+
uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
|
| 205 |
+
if uploaded_file is not None:
|
| 206 |
+
if st.session_state.current_file != uploaded_file.name:
|
| 207 |
+
st.session_state.current_file = uploaded_file.name
|
| 208 |
+
st.session_state.pdf_summary = None
|
| 209 |
+
st.session_state.pdf_report = None
|
| 210 |
+
st.session_state.word_report = None
|
| 211 |
+
if "vectorstore" in st.session_state:
|
| 212 |
+
del st.session_state.vectorstore
|
| 213 |
+
if "messages" in st.session_state:
|
| 214 |
+
st.session_state.messages = []
|
| 215 |
+
text = extract_text_from_pdf(uploaded_file)
|
| 216 |
+
if st.button("Analyze Text"):
|
| 217 |
+
start_time = time.time()
|
| 218 |
+
with st.spinner("Analyzing..."):
|
| 219 |
+
analysis = analyze_text_structured(text)
|
| 220 |
+
st.session_state.pdf_summary = analysis
|
| 221 |
+
|
| 222 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 223 |
+
chunks = text_splitter.split_text(text)
|
| 224 |
+
embeddings = HuggingFaceInferenceAPIEmbeddings(
|
| 225 |
+
pi_key=os.getenv("HUGGINGFACE_ACCESS_TOKEN"),
|
| 226 |
+
model_name="BAAI/bge-small-en-v1.5"
|
| 227 |
+
)
|
| 228 |
+
st.session_state.vectorstore = FAISS.from_texts(chunks, embeddings)
|
| 229 |
+
|
| 230 |
+
st.session_state.pdf_report = create_pdf_report(analysis)
|
| 231 |
+
st.session_state.word_report = create_word_report(analysis)
|
| 232 |
+
end_time = time.time()
|
| 233 |
+
st.session_state.analysis_time = end_time - start_time
|
| 234 |
+
st.subheader("Analysis Results")
|
| 235 |
+
st.text(json_to_text(analysis))
|
| 236 |
+
st.download_button(
|
| 237 |
+
label="Download PDF Report",
|
| 238 |
+
data=st.session_state.pdf_report,
|
| 239 |
+
file_name="analysis_report.pdf",
|
| 240 |
+
mime="application/pdf"
|
| 241 |
+
)
|
| 242 |
+
st.download_button(
|
| 243 |
+
label="Download Word Report",
|
| 244 |
+
data=st.session_state.word_report,
|
| 245 |
+
file_name="analysis_report.docx",
|
| 246 |
+
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
| 247 |
+
)
|
| 248 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 249 |
+
|
| 250 |
+
if "vectorstore" in st.session_state:
|
| 251 |
+
st.subheader("Chat with the Document")
|
| 252 |
+
for message in st.session_state.messages:
|
| 253 |
+
with st.chat_message(message["role"]):
|
| 254 |
+
st.markdown(message["content"])
|
| 255 |
+
|
| 256 |
+
if prompt := st.chat_input("Ask a question about the document"):
|
| 257 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 258 |
+
with st.chat_message("user"):
|
| 259 |
+
st.markdown(prompt)
|
| 260 |
+
|
| 261 |
+
with st.chat_message("assistant"):
|
| 262 |
+
with st.spinner("Thinking..."):
|
| 263 |
+
|
| 264 |
+
docs = st.session_state.vectorstore.similarity_search(prompt, k=3)
|
| 265 |
+
context = "\n".join([doc.page_content for doc in docs])
|
| 266 |
+
|
| 267 |
+
messages = [
|
| 268 |
+
SystemMessage(content="You are a assistant. Answer the question based on the provided document context."),
|
| 269 |
+
HumanMessage(content=f"Context: {context}\n\nQuestion: {prompt}")
|
| 270 |
+
]
|
| 271 |
+
|
| 272 |
+
response = llm.invoke(messages)
|
| 273 |
+
st.markdown(response.content)
|
| 274 |
+
st.session_state.messages.append({"role": "assistant", "content": response.content})
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
st.markdown(f'<div class="footer">Analysis Time: {st.session_state.analysis_time:.1f}s | Powered by Google Generative AI</div>', unsafe_allow_html=True)
|