-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
529 lines (440 loc) · 18.9 KB
/
Copy pathapp.py
File metadata and controls
529 lines (440 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
import streamlit as st
import json
from datetime import datetime
from database import init_db, Document, get_db
from auth import authenticate_admin, create_admin, admin_exists
from document_processor import process_document
from ai_analyzer import generate_summary, generate_questions, generate_mindmap_data
from mindmap_visualizer import create_mindmap_visualization
# Page configuration
st.set_page_config(
page_title="Document Analyzer Pro",
page_icon="📄",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for sleek design
st.markdown("""
<style>
/* Main gradient background */
.stApp {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
/* Custom containers */
.main-container {
background: white;
border-radius: 20px;
padding: 2rem;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
margin: 1rem 0;
}
/* Headers */
h1 {
color: #1f2937;
font-weight: 800;
text-align: center;
padding: 1rem 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
h2, h3 {
color: #374151;
font-weight: 700;
}
/* Buttons */
.stButton>button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 10px;
padding: 0.75rem 2rem;
font-weight: 600;
font-size: 1rem;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}
.stButton>button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}
/* Input fields */
.stTextInput>div>div>input, .stTextArea>div>div>textarea {
border-radius: 10px;
border: 2px solid #e5e7eb;
padding: 0.75rem;
transition: border-color 0.3s ease;
}
.stTextInput>div>div>input:focus, .stTextArea>div>div>textarea:focus {
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
/* File uploader */
.stFileUploader>div {
border-radius: 15px;
border: 3px dashed #667eea;
background: #f9fafb;
padding: 2rem;
text-align: center;
transition: all 0.3s ease;
}
.stFileUploader>div:hover {
border-color: #764ba2;
background: #f3f4f6;
}
/* Cards */
.stat-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 15px;
padding: 1.5rem;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
margin: 0.5rem 0;
}
/* Sidebar */
.css-1d391kg {
background: rgba(255, 255, 255, 0.95);
border-radius: 15px;
padding: 1rem;
}
/* Success/Error messages */
.stSuccess, .stError, .stWarning, .stInfo {
border-radius: 10px;
padding: 1rem;
}
/* Expander */
.streamlit-expanderHeader {
background: #f9fafb;
border-radius: 10px;
font-weight: 600;
}
/* Questions list */
.question-item {
background: linear-gradient(135deg, #1a1f2e 0%, #252b3a 100%);
border-left: 5px solid #00d4ff;
padding: 1.2rem;
margin: 0.7rem 0;
border-radius: 10px;
color: #ffffff;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
}
.question-item strong {
color: #00d4ff;
}
/* Summary container */
.summary-container {
background: linear-gradient(135deg, #1a1f2e 0%, #2a2f3e 100%);
color: #ffffff;
border-radius: 15px;
padding: 2rem;
box-shadow: 0 10px 30px rgba(102, 126, 234, 0.2);
margin: 1rem 0;
border-left: 5px solid #00d4ff;
}
.summary-container p, .summary-container div {
color: #ffffff;
line-height: 1.8;
}
</style>
""", unsafe_allow_html=True)
# Initialize database
init_db()
# Session state initialization
if 'logged_in' not in st.session_state:
st.session_state.logged_in = False
if 'username' not in st.session_state:
st.session_state.username = None
if 'current_page' not in st.session_state:
st.session_state.current_page = "upload"
def login_page():
"""Display login page"""
st.title("🔐 Document Analyzer Pro")
st.markdown("<br>", unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.markdown("<div class='main-container'>", unsafe_allow_html=True)
# Check if this is first admin
if not admin_exists():
st.info("👋 Welcome! Create your admin account to get started.")
with st.form("create_admin_form"):
new_username = st.text_input("Username", placeholder="Enter username")
new_password = st.text_input("Password", type="password", placeholder="Enter password")
confirm_password = st.text_input("Confirm Password", type="password", placeholder="Confirm password")
submit = st.form_submit_button("Create Admin Account", use_container_width=True)
if submit:
if not new_username or not new_password:
st.error("❌ Please fill in all fields")
elif new_password != confirm_password:
st.error("❌ Passwords do not match")
elif len(new_password) < 6:
st.error("❌ Password must be at least 6 characters")
else:
if create_admin(new_username, new_password):
st.success("✅ Admin account created! Please log in.")
st.rerun()
else:
st.error("❌ Failed to create admin account")
else:
st.markdown("### Admin Login")
with st.form("login_form"):
username = st.text_input("Username", placeholder="Enter your username")
password = st.text_input("Password", type="password", placeholder="Enter your password")
submit = st.form_submit_button("Login", use_container_width=True)
if submit:
if authenticate_admin(username, password):
st.session_state.logged_in = True
st.session_state.username = username
st.success("✅ Login successful!")
st.rerun()
else:
st.error("❌ Invalid username or password")
st.markdown("</div>", unsafe_allow_html=True)
def save_document_to_db(filename, file_type, content, summary, questions, mindmap_data):
"""Save document analysis to database"""
db = get_db()
try:
doc = Document(
filename=filename,
file_type=file_type,
content=content,
summary=summary,
questions=json.dumps(questions),
mindmap_data=json.dumps(mindmap_data),
uploaded_by=st.session_state.username
)
db.add(doc)
db.commit()
return True
except Exception as e:
db.rollback()
st.error(f"Error saving to database: {e}")
return False
finally:
db.close()
def upload_page():
"""Document upload and analysis page"""
st.title("📄 Upload & Analyze Document")
# Upload section
st.markdown("<div class='main-container'>", unsafe_allow_html=True)
st.markdown("### 📤 Upload Document")
uploaded_file = st.file_uploader(
"Drag and drop your document here or click to browse",
type=['pdf', 'docx', 'txt'],
help="Supported formats: PDF, DOCX, TXT"
)
if uploaded_file is not None:
st.success(f"✅ File uploaded: {uploaded_file.name}")
col1, col2 = st.columns([1, 3])
with col1:
analyze_btn = st.button("🔍 Analyze Document", use_container_width=True)
if analyze_btn:
try:
with st.spinner("🔄 Processing document..."):
# Extract text from document
file_bytes = uploaded_file.read()
file_extension = uploaded_file.name.split('.')[-1].lower()
text_content = process_document(file_bytes, file_extension)
if len(text_content) < 50:
st.error("❌ Document appears to be too short or empty. Please upload a document with more content.")
else:
st.success(f"✅ Extracted {len(text_content)} characters from document")
# Generate analysis
with st.spinner("🤖 Generating AI-powered summary..."):
summary = generate_summary(text_content)
with st.spinner("❓ Generating important questions..."):
questions = generate_questions(text_content)
with st.spinner("🧠 Creating mind map..."):
mindmap_data = generate_mindmap_data(text_content)
# Save to database
if save_document_to_db(
uploaded_file.name,
file_extension,
text_content[:5000], # Store first 5000 chars
summary,
questions,
mindmap_data
):
st.success("✅ Analysis completed and saved!")
# Display results
st.markdown("---")
# Summary section
st.markdown("### 📋 Summary")
st.markdown(f"<div class='summary-container'>{summary}</div>", unsafe_allow_html=True)
# Questions section
st.markdown("### ❓ 10 Important Questions")
for i, question in enumerate(questions, 1):
st.markdown(f"""
<div class='question-item'>
<strong>Q{i}:</strong> {question}
</div>
""", unsafe_allow_html=True)
# Mind map section
st.markdown("### 🧠 Mind Map")
fig = create_mindmap_visualization(mindmap_data)
st.plotly_chart(fig, use_container_width=True)
except Exception as e:
st.error(f"❌ Error analyzing document: {str(e)}")
st.markdown("</div>", unsafe_allow_html=True)
def history_page():
"""Document history dashboard"""
st.title("📚 Document History")
db = get_db()
try:
# Get all documents
documents = db.query(Document).order_by(Document.uploaded_at.desc()).all()
if not documents:
st.info("📭 No documents uploaded yet. Upload your first document to get started!")
else:
# Stats
col1, col2, col3 = st.columns(3)
with col1:
st.markdown(f"""
<div class='stat-card'>
<h2>{len(documents)}</h2>
<p>Total Documents</p>
</div>
""", unsafe_allow_html=True)
with col2:
pdf_count = sum(1 for d in documents if d.file_type == 'pdf')
st.markdown(f"""
<div class='stat-card'>
<h2>{pdf_count}</h2>
<p>PDF Documents</p>
</div>
""", unsafe_allow_html=True)
with col3:
recent_count = sum(1 for d in documents if (datetime.utcnow() - d.uploaded_at).days < 7)
st.markdown(f"""
<div class='stat-card'>
<h2>{recent_count}</h2>
<p>This Week</p>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# Search and filter
col1, col2 = st.columns([3, 1])
with col1:
search_term = st.text_input("🔍 Search documents", placeholder="Search by filename...")
with col2:
file_type_filter = st.selectbox("Filter by type", ["All", "PDF", "DOCX", "TXT"])
# Filter documents
filtered_docs = documents
if search_term:
filtered_docs = [d for d in filtered_docs if search_term.lower() in d.filename.lower()]
if file_type_filter != "All":
filtered_docs = [d for d in filtered_docs if d.file_type.upper() == file_type_filter]
st.markdown(f"### 📄 Documents ({len(filtered_docs)})")
# Display documents
for doc in filtered_docs:
with st.expander(f"📄 {doc.filename} - {doc.uploaded_at.strftime('%Y-%m-%d %H:%M')}"):
col1, col2 = st.columns([1, 3])
with col1:
st.markdown(f"**Type:** {doc.file_type.upper()}")
st.markdown(f"**Uploaded:** {doc.uploaded_at.strftime('%Y-%m-%d %H:%M')}")
st.markdown(f"**By:** {doc.uploaded_by}")
with col2:
# Summary
st.markdown("**📋 Summary:**")
st.write(doc.summary)
# Questions
if doc.questions:
questions = json.loads(doc.questions)
st.markdown("**❓ Questions:**")
for i, q in enumerate(questions[:5], 1): # Show first 5
st.write(f"{i}. {q}")
if len(questions) > 5:
st.write(f"*...and {len(questions) - 5} more questions*")
# Mind map
if doc.mindmap_data:
if st.button(f"View Mind Map", key=f"mindmap_{doc.id}"):
mindmap_data = json.loads(doc.mindmap_data)
fig = create_mindmap_visualization(mindmap_data)
st.plotly_chart(fig, use_container_width=True)
except Exception as e:
st.error(f"Error loading documents: {e}")
finally:
db.close()
def admin_management_page():
"""Admin management page for creating new admins"""
st.title("👥 Admin Management")
st.markdown("<div class='main-container'>", unsafe_allow_html=True)
st.markdown("### ➕ Create New Admin")
with st.form("create_new_admin_form"):
new_username = st.text_input("Username", placeholder="Enter new admin username")
new_password = st.text_input("Password", type="password", placeholder="Enter password")
confirm_password = st.text_input("Confirm Password", type="password", placeholder="Confirm password")
submit = st.form_submit_button("Create Admin Account", use_container_width=True)
if submit:
if not new_username or not new_password:
st.error("❌ Please fill in all fields")
elif new_password != confirm_password:
st.error("❌ Passwords do not match")
elif len(new_password) < 6:
st.error("❌ Password must be at least 6 characters")
else:
if create_admin(new_username, new_password):
st.success(f"✅ Admin account '{new_username}' created successfully!")
else:
st.error("❌ Username already exists. Please choose a different username.")
st.markdown("</div>", unsafe_allow_html=True)
# List existing admins
st.markdown("---")
st.markdown("<div class='main-container'>", unsafe_allow_html=True)
st.markdown("### 📋 Existing Admins")
db = get_db()
try:
from database import Admin
admins = db.query(Admin).order_by(Admin.created_at.desc()).all()
if admins:
for admin in admins:
col1, col2 = st.columns([2, 1])
with col1:
st.markdown(f"**👤 {admin.username}**")
with col2:
st.markdown(f"*Created: {admin.created_at.strftime('%Y-%m-%d')}*")
st.markdown("---")
else:
st.info("No admin accounts found.")
except Exception as e:
st.error(f"Error loading admins: {e}")
finally:
db.close()
st.markdown("</div>", unsafe_allow_html=True)
def main():
"""Main application"""
if not st.session_state.logged_in:
login_page()
else:
# Sidebar navigation
with st.sidebar:
st.markdown("### 👋 Welcome!")
st.markdown(f"**User:** {st.session_state.username}")
st.markdown("---")
# Navigation
st.markdown("### 📱 Navigation")
if st.button("📤 Upload Document", use_container_width=True):
st.session_state.current_page = "upload"
st.rerun()
if st.button("📚 Document History", use_container_width=True):
st.session_state.current_page = "history"
st.rerun()
if st.button("👥 Admin Management", use_container_width=True):
st.session_state.current_page = "admin"
st.rerun()
st.markdown("---")
# Logout
if st.button("🚪 Logout", use_container_width=True):
st.session_state.logged_in = False
st.session_state.username = None
st.rerun()
# Main content
if st.session_state.current_page == "upload":
upload_page()
elif st.session_state.current_page == "history":
history_page()
elif st.session_state.current_page == "admin":
admin_management_page()
if __name__ == "__main__":
main()