-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
581 lines (490 loc) · 18.9 KB
/
app.py
File metadata and controls
581 lines (490 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
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
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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
"""
Streamlit Web Interface for AI Document Summarizer
with integrated Groq API-powered document-grounded chatbot.
"""
import os
import streamlit as st
import tempfile
from typing import Dict, Any, List
import pandas as pd
import plotly.express as px
from src.chatbot import answer_question # only the Groq-based function (no pipeline)
from src.document_loader import DocumentLoader
from src.text_processor import TextProcessor
from src.summarizer import DocumentSummarizer, GENSIM_AVAILABLE
# Set page config upfront
st.set_page_config(
page_title="AI Document Summarizer",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded",
)
# Apply custom CSS styling
st.markdown(
"""
<style>
.main-header {
font-size: 2.5rem;
font-weight: bold;
color: #1f77b4;
text-align: center;
margin-bottom: 2rem;
}
.sub-header {
font-size: 1.5rem;
color: #2c3e50;
margin: 1rem 0;
}
.metric-card {
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
padding: 1rem;
border-radius: 10px;
color: white;
text-align: center;
margin: 0.5rem 0;
}
.success-box {
background-color: #d4edda;
border: 1px solid #c3e6cb;
border-radius: 5px;
padding: 1rem;
margin: 1rem 0;
}
.warning-box {
background-color: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 5px;
padding: 1rem;
margin: 1rem 0;
}
.error-box {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
border-radius: 5px;
padding: 1rem;
margin: 1rem 0;
}
</style>
""",
unsafe_allow_html=True,
)
@st.cache_resource
def initialize_components():
"""Initialize and cache backend AI components."""
with st.spinner("🔧 Initializing AI components..."):
try:
loader = DocumentLoader()
processor = TextProcessor()
summarizer = DocumentSummarizer()
return {
"loader": loader,
"processor": processor,
"summarizer": summarizer,
"status": "success",
"message": "All components initialized successfully!",
}
except Exception as e:
return {
"loader": None,
"processor": None,
"summarizer": None,
"status": "error",
"message": f"Initialization failed: {str(e)}",
}
def chatbot_interface(document_text: str):
"""Chat UI rendering with immediate update of latest messages side by side."""
if "chat_history" not in st.session_state:
st.session_state["chat_history"] = []
# Input form for user question
with st.form(key="chat_form", clear_on_submit=True):
user_question = st.text_input("Ask a question based on the document:")
submitted = st.form_submit_button("Send")
if submitted and user_question:
# Append user question immediately
st.session_state["chat_history"].append(("User", user_question))
# Generate answer synchronously now
try:
answer = answer_question(document_text, user_question)
answer = answer or "Sorry, I couldn't find an answer."
except Exception as e:
answer = "Sorry, something went wrong processing your question."
# Append bot answer immediately
st.session_state["chat_history"].append(("Bot", answer))
# After handling form submission above, render messages from session state:
st.markdown("### Conversation")
# Iterate through chat history in pairs (User question + Bot answer)
for i in range(0, len(st.session_state["chat_history"]), 2):
# Display User question
speaker, user_msg = st.session_state["chat_history"][i]
if speaker == "User":
st.markdown(f"**{user_msg}:**")
# Display Bot answer indented below question
if i + 1 < len(st.session_state["chat_history"]):
speaker, bot_msg = st.session_state["chat_history"][i + 1]
if speaker == "Bot":
st.markdown(
f"<div style='padding-left:20px'>{bot_msg}</div>",
unsafe_allow_html=True,
)
else:
st.markdown(
"<div style='padding-left:20px'><em>No answer yet.</em></div>",
unsafe_allow_html=True,
)
else:
st.markdown(
"<div style='padding-left:20px'><em>No answer yet.</em></div>",
unsafe_allow_html=True,
)
def main():
"""Main Streamlit app entry point."""
st.markdown(
'<h1 class="main-header">🤖 AI Document Summarizer</h1>', unsafe_allow_html=True
)
st.markdown(
'<p style="text-align: center; font-size: 1.2rem; color: #7f8c8d;">Transform any document into intelligent summaries using advanced AI</p>',
unsafe_allow_html=True,
)
components = initialize_components()
if components["status"] == "error":
st.error(f"❌ {components['message']}")
st.stop()
st.success(f"✅ {components['message']}")
# Sidebar for configuration
with st.sidebar:
st.markdown("## ⚙️ Configuration")
st.markdown("### 🤖 Summarization Methods")
available_methods = ["transformer", "textrank", "lsa", "luhn"]
if GENSIM_AVAILABLE:
available_methods.append("gensim")
selected_methods = st.multiselect(
"Choose methods:",
available_methods,
default=["transformer", "textrank", "lsa"],
help="Select one or more summarization methods to use",
)
st.markdown("### 📏 Summary Parameters")
max_length = st.slider(
"Maximum length (words)",
min_value=50,
max_value=300,
value=150,
step=25,
help="Maximum number of words in the summary",
)
min_length = st.slider(
"Minimum length (words)",
min_value=20,
max_value=100,
value=50,
step=10,
help="Minimum number of words in the summary",
)
sentence_count = st.slider(
"Sentences (for traditional methods)",
min_value=1,
max_value=10,
value=3,
help="Number of sentences for TextRank, LSA, etc.",
)
with st.expander("🔧 Advanced Settings"):
word_count = st.slider("Gensim word count", 50, 200, 100)
show_details = st.checkbox("Show detailed analysis", value=True)
show_performance = st.checkbox("Show performance metrics", value=True)
# Document upload UI
st.markdown(
'<h2 class="sub-header">📁 Upload Your Document</h2>', unsafe_allow_html=True
)
uploaded_file = st.file_uploader(
"Choose a document file",
type=["pdf", "docx", "txt", "xlsx", "pptx", "html", "md"],
help="Supported formats: PDF, Word, Text, Excel, PowerPoint, HTML, Markdown",
)
if uploaded_file is not None:
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("📄 File Name", uploaded_file.name)
with col2:
st.metric("📏 File Size", f"{uploaded_file.size:,} bytes")
with col3:
st.metric("📋 File Type", uploaded_file.type)
with col4:
st.metric("🔧 Methods", len(selected_methods))
if st.button("🚀 Process Document", type="primary"):
if not selected_methods:
st.error("❌ Please select at least one summarization method")
else:
# Clear chat history on new document to avoid conversation mixing
if "chat_history" in st.session_state:
st.session_state["chat_history"] = []
process_document(
uploaded_file,
components,
selected_methods,
{
"max_length": max_length,
"min_length": min_length,
"sentence_count": sentence_count,
"word_count": word_count,
"show_details": show_details,
"show_performance": show_performance,
},
)
# Show summaries, detailed analysis, and chatbot interface after processing
if "results" in st.session_state:
show_results_preview(st.session_state["results"])
results = st.session_state["results"]
document_text = results.get("processing_result", {}).get("cleaned_text", "")
st.markdown(
'<h2 class="sub-header">📊 Detailed Analysis</h2>', unsafe_allow_html=True
)
show_detailed_analysis(st.session_state["results"])
if document_text:
chatbot_interface(document_text)
# Analytics and About inside expanders
with st.expander("📈 Analytics", expanded=False):
analytics_section()
with st.expander("ℹ️ About", expanded=False):
about_section(components)
def process_document(
uploaded_file,
components: Dict[str, Any],
methods: List[str],
params: Dict[str, Any],
):
"""Save, load, process, and summarize document."""
progress_bar = st.progress(0)
status_text = st.empty()
try:
status_text.text("📥 Saving uploaded file...")
progress_bar.progress(10)
with tempfile.NamedTemporaryFile(
delete=False, suffix=f".{uploaded_file.name.split('.')[-1]}"
) as tmp_file:
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
status_text.text("📄 Loading document content...")
progress_bar.progress(25)
load_result = components["loader"].load_document(tmp_file_path)
if not load_result["success"]:
st.error(f"❌ Failed to load document: {load_result['error']}")
return
status_text.text("🔧 Processing text...")
progress_bar.progress(50)
processing_result = components["processor"].prepare_for_summarization(
load_result["text"]
)
status_text.text("🤖 Generating AI summaries...")
progress_bar.progress(75)
summary_result = components["summarizer"].summarize_document(
processing_result["cleaned_text"],
methods=methods,
max_length=params["max_length"],
min_length=params["min_length"],
sentence_count=params["sentence_count"],
word_count=params["word_count"],
)
status_text.text("✅ Processing complete!")
progress_bar.progress(100)
# Store results including cleaned text for chatbot
st.session_state["results"] = {
"load_result": load_result,
"processing_result": {
"cleaned_text": processing_result.get("cleaned_text", "")
},
"summary_result": summary_result,
"file_name": uploaded_file.name,
"methods_used": methods,
"parameters": params,
}
# Cleanup temp file
os.unlink(tmp_file_path)
except Exception as e:
st.error(f"❌ Processing failed: {str(e)}")
status_text.text("❌ Processing failed")
if "tmp_file_path" in locals():
try:
os.unlink(tmp_file_path)
except Exception:
pass
def show_results_preview(results: Dict[str, Any]):
"""Brief summary preview."""
st.markdown("---")
st.markdown(
'<h2 class="sub-header">📊 Processing Results</h2>', unsafe_allow_html=True
)
summary_result = results["summary_result"]
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric(
label="⏱️ Processing Time",
value=f"{summary_result['overall_performance']['total_processing_time']:.2f}s",
)
with col2:
st.metric(
label="✅ Success Rate",
value=f"{summary_result['overall_performance']['methods_successful']}/{summary_result['overall_performance']['methods_attempted']}",
)
with col3:
st.metric(
label="🎯 Avg Quality",
value=f"{summary_result['overall_performance']['average_quality_score']:.2f}",
)
with col4:
st.metric(
label="🏆 Best Method",
value=summary_result["recommended"]["method"].title(),
)
st.markdown("### 🏆 Recommended Summary")
recommended = summary_result["recommended"]
st.markdown(
f"""
<div class="success-box">
<strong>Method:</strong> {recommended['method'].title()}<br>
<strong>Quality Score:</strong> {recommended['quality_score']:.2f}<br>
<strong>Confidence:</strong> {recommended['confidence']:.2f}<br><br>
<strong>Summary:</strong><br>
{recommended['summary']}
</div>
""",
unsafe_allow_html=True,
)
def show_detailed_analysis(results: Dict[str, Any]):
"""Document stats & all summaries."""
input_analysis = results["summary_result"].get("input_analysis", {})
col1, col2 = st.columns(2)
with col1:
st.markdown("**Document Statistics:**")
st.write(
f"• **Original Length:** {input_analysis.get('original_length', 0):,} characters"
)
st.write(f"• **Word Count:** {input_analysis.get('word_count', 0):,} words")
st.write(f"• **Sentences:** {input_analysis.get('sentence_count', 0):,}")
st.write(f"• **Language:** {input_analysis.get('language', 'N/A')}")
st.write(f"• **Complexity:** {input_analysis.get('complexity', 'N/A')}")
with col2:
st.markdown("**Processing Quality:**")
readiness = input_analysis.get("readiness_score", 0)
st.write(f"• **Readiness Score:** {readiness:.2f}")
if readiness >= 0.8:
st.success("🎉 Excellent text quality for summarization!")
elif readiness >= 0.6:
st.warning("⚠️ Good text quality with minor issues")
else:
st.error("❌ Text quality needs improvement")
st.markdown("### 📝 All Generated Summaries")
for method, result in results["summary_result"]["summaries"].items():
if result["success"]:
with st.expander(
f"📋 {method.title()} Summary (Quality: {result['quality_score']:.2f})"
):
st.write(result["summary"])
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Word Count", result.get("word_count", 0))
with col2:
st.metric(
"Processing Time", f"{result.get('processing_time', 0):.2f}s"
)
with col3:
st.metric(
"Compression Ratio", f"{result.get('compression_ratio', 0):.3f}"
)
else:
with st.expander(f"❌ {method.title()} (Failed)"):
st.error(result["summary"])
def analytics_section():
"""Performance charts & tables."""
if "results" not in st.session_state:
st.info("📈 Process a document to see analytics and visualizations here.")
return
results = st.session_state["results"]
summary_result = results["summary_result"]
st.markdown(
'<h2 class="sub-header">📈 Performance Analytics</h2>', unsafe_allow_html=True
)
quality_data = [
{
"Method": method.title(),
"Quality Score": result["quality_score"],
"Processing Time": result["processing_time"],
}
for method, result in summary_result["summaries"].items()
if result["success"]
]
if quality_data:
df_quality = pd.DataFrame(quality_data)
fig = px.bar(
df_quality,
x="Method",
y="Quality Score",
title="Summary Quality by Method",
color="Quality Score",
color_continuous_scale="viridis",
)
st.plotly_chart(fig, use_container_width=True)
st.markdown("### ⏱️ Processing Time Analysis")
fig2 = px.scatter(
df_quality,
x="Processing Time",
y="Quality Score",
size=[1] * len(df_quality),
hover_name="Method",
title="Quality vs Processing Time",
labels={"Processing Time": "Processing Time (seconds)"},
)
st.plotly_chart(fig2, use_container_width=True)
st.markdown("### 📊 Performance Metrics")
performance = summary_result.get("performance", {})
perf_data = [
{
"Method": method.title(),
"Success": perf.get("success", False),
"Time (s)": perf.get("processing_time", 0),
"Words/sec": perf.get("words_per_second", 0),
}
for method, perf in performance.items()
]
df_perf = pd.DataFrame(perf_data)
st.dataframe(df_perf, use_container_width=True)
st.markdown("### 💡 System Recommendations")
for i, rec in enumerate(summary_result.get("recommendations", []), 1):
st.write(f"{i}. {rec}")
def about_section(components: Dict[str, Any]):
"""About application info."""
st.markdown(
'<h2 class="sub-header">ℹ️ About This Application</h2>', unsafe_allow_html=True
)
st.markdown(
"""
### 🤖 AI Document Summarizer
This application uses advanced AI and NLP to generate high-quality document summaries.
**Key Features:**
- 🤖 AI-powered summarization with transformer models
- 📊 Multiple traditional summarization methods
- 📄 Supports multiple file formats
- 🎯 Quality assessment and comparison
- ⚡ Fast and optimized processing
- 🔧 Customizable settings for different needs
"""
)
st.markdown("### 🔧 System Information")
if components["summarizer"]:
perf_stats = components["summarizer"].get_performance_stats()
col1, col2 = st.columns(2)
with col1:
st.markdown("**AI Model Information:**")
st.write(f"• **Current Model:** {perf_stats['current_model']}")
st.write(f"• **Device:** {perf_stats['device'].upper()}")
st.write(f"• **Available Models:** {len(perf_stats['available_models'])}")
with col2:
st.markdown("**Processing Statistics:**")
st.write(
f"• **Total Summaries:** {perf_stats['total_summaries_processed']}"
)
st.write(f"• **Success Rate:** {perf_stats['success_rate']:.1%}")
st.write(
f"• **Avg Processing Time:** {perf_stats['average_processing_time']:.2f}s"
)
if __name__ == "__main__":
main()