Update src/app.py
Browse files- src/app.py +306 -267
src/app.py
CHANGED
|
@@ -1,267 +1,306 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import os
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
from rag_pipeline import RAGPipeline
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
# Page configuration
|
| 8 |
-
st.set_page_config(
|
| 9 |
-
page_title="Local Multimodal RAG",
|
| 10 |
-
page_icon="π",
|
| 11 |
-
layout="wide",
|
| 12 |
-
initial_sidebar_state="expanded"
|
| 13 |
-
)
|
| 14 |
-
|
| 15 |
-
st.title("π Local Multimodal RAG System")
|
| 16 |
-
st.markdown("**Analyze PDF documents locally with Mistral + CLIP embeddings**")
|
| 17 |
-
|
| 18 |
-
# Initialize session state
|
| 19 |
-
if "uploaded_files" not in st.session_state:
|
| 20 |
-
st.session_state.uploaded_files = []
|
| 21 |
-
if "rag_pipeline" not in st.session_state:
|
| 22 |
-
st.session_state.rag_pipeline = None
|
| 23 |
-
if "
|
| 24 |
-
st.session_state.
|
| 25 |
-
|
| 26 |
-
# Sidebar configuration
|
| 27 |
-
with st.sidebar:
|
| 28 |
-
st.header("βοΈ Configuration")
|
| 29 |
-
|
| 30 |
-
pdf_dir = st.text_input(
|
| 31 |
-
"π PDF Directory",
|
| 32 |
-
value="./pdfs",
|
| 33 |
-
help="Path to directory containing PDF files"
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
st.
|
| 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 |
-
|
| 91 |
-
|
| 92 |
-
st.
|
| 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 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
#
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
st.
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from rag_pipeline import RAGPipeline
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
# Page configuration
|
| 8 |
+
st.set_page_config(
|
| 9 |
+
page_title="Local Multimodal RAG",
|
| 10 |
+
page_icon="π",
|
| 11 |
+
layout="wide",
|
| 12 |
+
initial_sidebar_state="expanded"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
st.title("π Local Multimodal RAG System")
|
| 16 |
+
st.markdown("**Analyze PDF documents locally with Mistral + CLIP embeddings**")
|
| 17 |
+
|
| 18 |
+
# Initialize session state
|
| 19 |
+
if "uploaded_files" not in st.session_state:
|
| 20 |
+
st.session_state.uploaded_files = []
|
| 21 |
+
if "rag_pipeline" not in st.session_state:
|
| 22 |
+
st.session_state.rag_pipeline = None
|
| 23 |
+
if "last_upload_time" not in st.session_state:
|
| 24 |
+
st.session_state.last_upload_time = 0
|
| 25 |
+
|
| 26 |
+
# Sidebar configuration
|
| 27 |
+
with st.sidebar:
|
| 28 |
+
st.header("βοΈ Configuration")
|
| 29 |
+
|
| 30 |
+
pdf_dir = st.text_input(
|
| 31 |
+
"π PDF Directory",
|
| 32 |
+
value="./pdfs",
|
| 33 |
+
help="Path to directory containing PDF files"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Ensure directory exists
|
| 37 |
+
os.makedirs(pdf_dir, exist_ok=True)
|
| 38 |
+
|
| 39 |
+
device = st.selectbox(
|
| 40 |
+
"π₯οΈ Device",
|
| 41 |
+
["cpu", "cuda"],
|
| 42 |
+
help="Device for model inference"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
n_context_docs = st.slider(
|
| 46 |
+
"π Context Documents",
|
| 47 |
+
min_value=1,
|
| 48 |
+
max_value=10,
|
| 49 |
+
value=3,
|
| 50 |
+
help="Number of documents to retrieve for context"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
st.divider()
|
| 54 |
+
|
| 55 |
+
# PDF Upload Section with Form
|
| 56 |
+
st.subheader("π€ Upload PDF Files")
|
| 57 |
+
|
| 58 |
+
# Use a form to separate file upload from submission
|
| 59 |
+
with st.form("pdf_upload_form", clear_on_submit=True):
|
| 60 |
+
uploaded_pdfs = st.file_uploader(
|
| 61 |
+
"Choose PDF files to upload",
|
| 62 |
+
type="pdf",
|
| 63 |
+
accept_multiple_files=True,
|
| 64 |
+
help="Select one or more PDF files to add to the system"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
submit_button = st.form_submit_button("β¬οΈ Upload PDFs", use_container_width=True)
|
| 68 |
+
|
| 69 |
+
if submit_button and uploaded_pdfs:
|
| 70 |
+
upload_successful = True
|
| 71 |
+
uploaded_count = 0
|
| 72 |
+
|
| 73 |
+
for uploaded_file in uploaded_pdfs:
|
| 74 |
+
try:
|
| 75 |
+
file_path = os.path.join(pdf_dir, uploaded_file.name)
|
| 76 |
+
|
| 77 |
+
# Save file to disk
|
| 78 |
+
with open(file_path, "wb") as f:
|
| 79 |
+
f.write(uploaded_file.getbuffer())
|
| 80 |
+
|
| 81 |
+
st.session_state.uploaded_files.append(uploaded_file.name)
|
| 82 |
+
uploaded_count += 1
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
st.error(f"Failed to upload {uploaded_file.name}: {str(e)}")
|
| 86 |
+
upload_successful = False
|
| 87 |
+
|
| 88 |
+
if upload_successful and uploaded_count > 0:
|
| 89 |
+
st.session_state.last_upload_time = time.time()
|
| 90 |
+
st.success(f"β
Uploaded {uploaded_count} PDF(s) successfully!")
|
| 91 |
+
st.info("π Click 'Reload & Index PDFs' below to process them.")
|
| 92 |
+
# Don't call st.rerun() here - let form handle clear_on_submit
|
| 93 |
+
|
| 94 |
+
st.divider()
|
| 95 |
+
|
| 96 |
+
# Display uploaded files
|
| 97 |
+
pdf_files = list(Path(pdf_dir).glob("*.pdf"))
|
| 98 |
+
if pdf_files:
|
| 99 |
+
st.subheader(f"π Documents ({len(pdf_files)})")
|
| 100 |
+
|
| 101 |
+
for pdf_file in pdf_files:
|
| 102 |
+
col1, col2 = st.columns([4, 1])
|
| 103 |
+
with col1:
|
| 104 |
+
st.write(f"β’ {pdf_file.name}")
|
| 105 |
+
with col2:
|
| 106 |
+
if st.button("ποΈ", key=f"delete_{pdf_file.name}", help="Delete this file"):
|
| 107 |
+
try:
|
| 108 |
+
os.remove(pdf_file)
|
| 109 |
+
st.session_state.rag_pipeline = None # Clear pipeline
|
| 110 |
+
st.success(f"Deleted {pdf_file.name}")
|
| 111 |
+
time.sleep(0.5)
|
| 112 |
+
st.rerun()
|
| 113 |
+
except Exception as e:
|
| 114 |
+
st.error(f"Failed to delete: {str(e)}")
|
| 115 |
+
else:
|
| 116 |
+
st.info("π No PDF files in directory yet")
|
| 117 |
+
|
| 118 |
+
st.divider()
|
| 119 |
+
|
| 120 |
+
# Reload/Index button
|
| 121 |
+
col1, col2 = st.columns(2)
|
| 122 |
+
with col1:
|
| 123 |
+
if st.button("π Reload & Index", use_container_width=True):
|
| 124 |
+
st.session_state.rag_pipeline = None # Clear cached pipeline
|
| 125 |
+
st.rerun()
|
| 126 |
+
|
| 127 |
+
with col2:
|
| 128 |
+
if st.button("ποΈ Clear All", use_container_width=True):
|
| 129 |
+
# Delete all PDFs
|
| 130 |
+
for pdf_file in Path(pdf_dir).glob("*.pdf"):
|
| 131 |
+
try:
|
| 132 |
+
os.remove(pdf_file)
|
| 133 |
+
except:
|
| 134 |
+
pass
|
| 135 |
+
st.session_state.rag_pipeline = None
|
| 136 |
+
st.session_state.uploaded_files = []
|
| 137 |
+
st.success("All PDFs cleared")
|
| 138 |
+
time.sleep(0.5)
|
| 139 |
+
st.rerun()
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# Initialize pipeline
|
| 143 |
+
@st.cache_resource
|
| 144 |
+
def init_rag_pipeline(_device, _pdf_dir):
|
| 145 |
+
"""Initialize RAG pipeline (cached)"""
|
| 146 |
+
os.makedirs(_pdf_dir, exist_ok=True)
|
| 147 |
+
|
| 148 |
+
pdf_files = list(Path(_pdf_dir).glob("*.pdf"))
|
| 149 |
+
if not pdf_files:
|
| 150 |
+
return None, f"No PDF files found in {_pdf_dir}"
|
| 151 |
+
|
| 152 |
+
try:
|
| 153 |
+
with st.spinner("β³ Initializing models..."):
|
| 154 |
+
pipeline = RAGPipeline(pdf_dir=_pdf_dir, device=_device)
|
| 155 |
+
|
| 156 |
+
with st.spinner("β³ Indexing PDFs..."):
|
| 157 |
+
pipeline.index_pdfs()
|
| 158 |
+
|
| 159 |
+
return pipeline, None
|
| 160 |
+
except Exception as e:
|
| 161 |
+
return None, str(e)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# Get or initialize pipeline
|
| 165 |
+
if st.session_state.rag_pipeline is None:
|
| 166 |
+
pdf_files = list(Path(pdf_dir).glob("*.pdf"))
|
| 167 |
+
|
| 168 |
+
if pdf_files:
|
| 169 |
+
pipeline, error = init_rag_pipeline(device, pdf_dir)
|
| 170 |
+
if error:
|
| 171 |
+
st.error(f"β Error: {error}")
|
| 172 |
+
st.stop()
|
| 173 |
+
st.session_state.rag_pipeline = pipeline
|
| 174 |
+
else:
|
| 175 |
+
st.warning("π No PDF files found")
|
| 176 |
+
st.info("""
|
| 177 |
+
**How to get started:**
|
| 178 |
+
1. π€ Upload PDF files using the sidebar file uploader
|
| 179 |
+
2. β
Click 'Upload PDFs' to save them
|
| 180 |
+
3. π Click 'Reload & Index PDFs' to process
|
| 181 |
+
4. β Ask questions in the Q&A tab
|
| 182 |
+
""")
|
| 183 |
+
st.stop()
|
| 184 |
+
else:
|
| 185 |
+
pipeline = st.session_state.rag_pipeline
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# Main content
|
| 189 |
+
if pipeline:
|
| 190 |
+
# Tabs
|
| 191 |
+
tab1, tab2, tab3 = st.tabs(["β Q&A", "π Summary", "π Retrieval"])
|
| 192 |
+
|
| 193 |
+
# Tab 1: Question Answering
|
| 194 |
+
with tab1:
|
| 195 |
+
st.subheader("Ask Questions about Your Documents")
|
| 196 |
+
|
| 197 |
+
question = st.text_area(
|
| 198 |
+
"Your question (in Russian or English):",
|
| 199 |
+
height=100,
|
| 200 |
+
placeholder="What is this document about? What are the main points? Etc.",
|
| 201 |
+
key="qa_question"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
col1, col2 = st.columns(2)
|
| 205 |
+
with col1:
|
| 206 |
+
get_answer_btn = st.button("π Get Answer", use_container_width=True)
|
| 207 |
+
with col2:
|
| 208 |
+
clear_btn = st.button("ποΈ Clear", use_container_width=True)
|
| 209 |
+
|
| 210 |
+
if clear_btn:
|
| 211 |
+
st.rerun()
|
| 212 |
+
|
| 213 |
+
if get_answer_btn:
|
| 214 |
+
if question.strip():
|
| 215 |
+
with st.spinner("β³ Retrieving documents and generating answer..."):
|
| 216 |
+
try:
|
| 217 |
+
result = pipeline.answer_question(question, n_context_docs=n_context_docs)
|
| 218 |
+
except Exception as e:
|
| 219 |
+
st.error(f"Error: {str(e)}")
|
| 220 |
+
result = None
|
| 221 |
+
|
| 222 |
+
if result and result.get("answer"):
|
| 223 |
+
st.success("β Answer generated!")
|
| 224 |
+
|
| 225 |
+
st.subheader("π Answer")
|
| 226 |
+
st.write(result["answer"])
|
| 227 |
+
|
| 228 |
+
with st.expander("π Sources Used"):
|
| 229 |
+
for i, source in enumerate(result["sources"], 1):
|
| 230 |
+
st.write(f"{i}. {source}")
|
| 231 |
+
|
| 232 |
+
col1, col2 = st.columns(2)
|
| 233 |
+
with col1:
|
| 234 |
+
st.metric("Documents Used", result.get("context_used", 0))
|
| 235 |
+
with col2:
|
| 236 |
+
st.metric("Answer Length", len(result["answer"]))
|
| 237 |
+
else:
|
| 238 |
+
st.warning("Please enter a question")
|
| 239 |
+
|
| 240 |
+
# Tab 2: Document Summary
|
| 241 |
+
with tab2:
|
| 242 |
+
st.subheader("Summary of Indexed Documents")
|
| 243 |
+
|
| 244 |
+
if st.button("π Generate Summary", use_container_width=True):
|
| 245 |
+
with st.spinner("β³ Generating summary..."):
|
| 246 |
+
try:
|
| 247 |
+
summary = pipeline.summarize_documents()
|
| 248 |
+
st.success("β Summary generated!")
|
| 249 |
+
st.subheader("π Document Summary")
|
| 250 |
+
st.write(summary)
|
| 251 |
+
except Exception as e:
|
| 252 |
+
st.error(f"Error: {str(e)}")
|
| 253 |
+
|
| 254 |
+
# Tab 3: Document Retrieval
|
| 255 |
+
with tab3:
|
| 256 |
+
st.subheader("Search and Retrieve Documents")
|
| 257 |
+
|
| 258 |
+
search_query = st.text_input(
|
| 259 |
+
"Search query:",
|
| 260 |
+
placeholder="Enter search terms...",
|
| 261 |
+
key="retrieval_search"
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
col1, col2 = st.columns(2)
|
| 265 |
+
with col1:
|
| 266 |
+
search_btn = st.button("π Search", use_container_width=True)
|
| 267 |
+
with col2:
|
| 268 |
+
clear_search_btn = st.button("Clear Search", use_container_width=True)
|
| 269 |
+
|
| 270 |
+
if clear_search_btn:
|
| 271 |
+
st.rerun()
|
| 272 |
+
|
| 273 |
+
if search_btn:
|
| 274 |
+
if search_query.strip():
|
| 275 |
+
with st.spinner("β³ Searching..."):
|
| 276 |
+
try:
|
| 277 |
+
results = pipeline.retrieve_documents(search_query, n_results=n_context_docs)
|
| 278 |
+
except Exception as e:
|
| 279 |
+
st.error(f"Search error: {str(e)}")
|
| 280 |
+
results = []
|
| 281 |
+
|
| 282 |
+
if results:
|
| 283 |
+
st.success(f"β Found {len(results)} documents")
|
| 284 |
+
|
| 285 |
+
for i, doc in enumerate(results, 1):
|
| 286 |
+
with st.expander(f"π Document {i} - {doc['source']}", expanded=(i==1)):
|
| 287 |
+
st.write(doc["content"])
|
| 288 |
+
else:
|
| 289 |
+
st.warning("No documents found matching your query")
|
| 290 |
+
else:
|
| 291 |
+
st.warning("Please enter a search query")
|
| 292 |
+
|
| 293 |
+
# Footer
|
| 294 |
+
st.divider()
|
| 295 |
+
with st.expander("βΉοΈ System Information"):
|
| 296 |
+
info = pipeline.vector_store.get_collection_info()
|
| 297 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 298 |
+
with col1:
|
| 299 |
+
st.metric("π Chunks", info.get("document_count", 0))
|
| 300 |
+
with col2:
|
| 301 |
+
st.metric("π₯οΈ Device", device.upper())
|
| 302 |
+
with col3:
|
| 303 |
+
st.metric("π Context", n_context_docs)
|
| 304 |
+
with col4:
|
| 305 |
+
pdf_count = len(list(Path(pdf_dir).glob("*.pdf")))
|
| 306 |
+
st.metric("π PDFs", pdf_count)
|