-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1151 lines (955 loc) · 39.8 KB
/
app.py
File metadata and controls
1151 lines (955 loc) · 39.8 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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
🤖 AI Agent PDF Extractor with Google Gemini
Ultra-Modern 2025 UI Design with Glassmorphism & Bento Grid
"""
import streamlit as st
import google.generativeai as genai
from pathlib import Path
import PyPDF2
import tempfile
import time
import json
from datetime import datetime
from config import Config
# ============================================================================
# PAGE CONFIG
# ============================================================================
st.set_page_config(
page_title="AI PDF Extractor | Gemini",
page_icon="🤖",
layout="wide",
initial_sidebar_state="collapsed"
)
# Validate config
try:
Config.validate()
genai.configure(api_key=Config.GOOGLE_API_KEY)
except Exception as e:
st.error(f"⚠️ Configuration Error: {e}")
st.info("💡 Get your free API key: https://aistudio.google.com/app/apikey")
st.stop()
# ============================================================================
# ULTRA-MODERN UI STYLING (2025 TRENDS)
# ============================================================================
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
/* ========== GLOBAL RESET ========== */
* {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
margin: 0;
padding: 0;
}
/* Hide Streamlit Branding */
#MainMenu, footer, header {visibility: hidden;}
/* ========== ANIMATED GRADIENT BACKGROUND ========== */
.main {
background: linear-gradient(-45deg, #667eea, #764ba2, #f093fb, #4facfe);
background-size: 400% 400%;
animation: gradientShift 15s ease infinite;
padding: 0;
min-height: 100vh;
}
@keyframes gradientShift {
0% {background-position: 0% 50%;}
50% {background-position: 100% 50%;}
100% {background-position: 0% 50%;}
}
/* ========== GLASSMORPHISM HEADER (FIXED VISIBILITY) ========== */
.glass-header {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.95) 0%, rgba(118, 75, 162, 0.95) 100%);
backdrop-filter: blur(20px) saturate(180%);
-webkit-backdrop-filter: blur(20px) saturate(180%);
border: 1px solid rgba(255, 255, 255, 0.3);
padding: 3rem 3rem;
border-radius: 24px;
margin: 2rem auto 1rem auto;
max-width: 1400px;
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.5), 0 0 60px rgba(102, 126, 234, 0.3);
text-align: center;
position: relative;
overflow: hidden;
}
.glass-header::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.15), transparent);
animation: shimmer 3s infinite;
z-index: 1;
}
@keyframes shimmer {
0% {left: -100%;}
100% {left: 100%;}
}
.glass-header h1 {
font-size: 3.5rem !important;
font-weight: 900 !important;
color: #ffffff !important;
letter-spacing: -2px !important;
margin-bottom: 0.5rem !important;
position: relative !important;
z-index: 10 !important;
text-shadow: 3px 3px 6px rgba(0,0,0,0.4) !important;
line-height: 1.2 !important;
}
.glass-header p {
color: rgba(255, 255, 255, 0.95) !important;
font-size: 1.2rem !important;
font-weight: 500 !important;
letter-spacing: 0.5px !important;
text-shadow: 2px 2px 4px rgba(0,0,0,0.3) !important;
position: relative !important;
z-index: 10 !important;
}
/* ========== BENTO GRID CONTAINER ========== */
.bento-container {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(10px);
padding: 0;
border-radius: 24px;
margin: 0rem auto;
max-width: 1400px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
}
/* ========== STAT CARDS (BENTO STYLE) ========== */
.stat-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1.25rem;
margin: 2rem 0;
}
.stat-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 2rem;
border-radius: 20px;
text-align: center;
color: white;
box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
position: relative;
overflow: hidden;
}
.stat-card::before {
content: '';
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
opacity: 0;
transition: opacity 0.3s;
}
.stat-card:hover {
transform: translateY(-8px) scale(1.02);
box-shadow: 0 15px 40px rgba(102, 126, 234, 0.6);
}
.stat-card:hover::before {
opacity: 1;
}
.stat-card h3 {
font-size: 3rem;
margin: 0;
font-weight: 800;
line-height: 1;
}
.stat-card p {
margin: 0.75rem 0 0 0;
opacity: 0.95;
font-size: 0.95rem;
text-transform: uppercase;
letter-spacing: 2px;
font-weight: 600;
}
/* ========== MODERN BUTTONS ========== */
.stButton>button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 1rem 2.5rem;
font-size: 1.05rem;
font-weight: 700;
border-radius: 16px;
cursor: pointer;
transition: all 0.3s ease;
width: 100%;
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
letter-spacing: 0.5px;
text-transform: uppercase;
position: relative;
overflow: hidden;
}
.stButton>button::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 0;
height: 0;
border-radius: 50%;
background: rgba(255, 255, 255, 0.3);
transform: translate(-50%, -50%);
transition: width 0.6s, height 0.6s;
}
.stButton>button:hover::before {
width: 300px;
height: 300px;
}
.stButton>button:hover {
transform: translateY(-3px);
box-shadow: 0 12px 35px rgba(102, 126, 234, 0.7);
}
.stButton>button:active {
transform: translateY(-1px);
}
/* ========== RESULT BOX (UNIFORM STYLE) ========== */
/* ========== JUSTIFIED TEXT FOR SUMMARIES ========== */
.justified-text {
text-align: justify;
line-height: 1.8;
color: #333;
font-size: 1.05rem;
}
/* ========== INFO BLOCKS (COMPACT VERSION) ========== */
.info-block {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.06) 0%, rgba(118, 75, 162, 0.06) 100%);
backdrop-filter: blur(10px);
padding: 1.25rem;
border-radius: 16px;
border: 1px solid rgba(102, 126, 234, 0.15);
margin: 0.75rem 0;
box-shadow: 0 4px 12px rgba(0,0,0,0.04);
transition: all 0.3s ease;
}
.info-block:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.12);
border-color: rgba(102, 126, 234, 0.25);
}
.info-block h4 {
color: #667eea;
margin-top: 0;
margin-bottom: 1rem;
font-size: 1.2rem;
font-weight: 700;
text-align: center;
}
/* ========== FEATURE ITEM ========== */
.feature-item {
padding: 0.75rem 0;
border-bottom: 1px solid rgba(102, 126, 234, 0.1);
}
.feature-item:last-child {
border-bottom: none;
}
.feature-item strong {
color: #667eea;
font-size: 1.05rem;
}
.feature-item p {
color: #666;
margin: 0.25rem 0 0 0;
font-size: 0.95rem;
line-height: 1.6;
}
/* ========== MODERN BADGES ========== */
.badge {
display: inline-block;
padding: 0.5rem 1rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 25px;
font-size: 0.9rem;
font-weight: 600;
margin: 0.35rem;
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
transition: all 0.3s ease;
}
.badge:hover {
transform: scale(1.05);
box-shadow: 0 6px 18px rgba(102, 126, 234, 0.5);
}
/* ========== MODERN TABS (CENTERED) ========== */
.stTabs [data-baseweb="tab-list"] {
gap: 1rem;
background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
border-bottom: none;
padding: 1.5rem 2rem;
display: flex;
justify-content: center;
align-items: center;
}
.stTabs [data-baseweb="tab"] {
background: rgba(255, 255, 255, 0.8);
backdrop-filter: blur(5px);
border-radius: 16px;
padding: 1rem 2rem;
font-weight: 700;
font-size: 1.05rem;
border: 2px solid rgba(102, 126, 234, 0.2);
color: #667eea;
transition: all 0.3s ease;
min-width: 180px;
text-align: center;
}
.stTabs [data-baseweb="tab"]:hover {
background: rgba(255, 255, 255, 1);
transform: translateY(-3px);
box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
border-color: #667eea;
}
.stTabs [aria-selected="true"] {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.5);
border-color: transparent;
transform: translateY(-3px);
}
.stTabs [data-baseweb="tab-panel"] {
padding: 2.5rem;
text-align: center;
max-width: 1200px;
margin: 0 auto;
}
/* Center all tab content */
.stTabs h3, .stTabs h4 {
text-align: center !important;
}
.stTabs .stButton {
display: flex;
justify-content: center;
}
/* ========== UPLOAD AREA ========== */
.uploadedFile {
background: rgba(102, 126, 234, 0.05);
border-radius: 16px;
padding: 1.5rem;
border: 3px dashed #667eea;
transition: all 0.3s ease;
}
.uploadedFile:hover {
background: rgba(102, 126, 234, 0.1);
border-color: #764ba2;
}
/* ========== INFO BOXES ========== */
.stInfo, .stSuccess, .stWarning, .stError {
border-radius: 16px;
padding: 1.25rem;
margin: 1rem 0;
font-weight: 500;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
/* ========== TEXT AREA ========== */
.stTextArea textarea {
border-radius: 16px;
border: 2px solid rgba(102, 126, 234, 0.3);
font-family: 'Inter', monospace;
transition: all 0.3s ease;
}
.stTextArea textarea:focus {
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
}
/* ========== LOADING ANIMATION ========== */
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.6; }
}
.loading {
animation: pulse 2s ease-in-out infinite;
}
/* ========== FILE UPLOADER ========== */
[data-testid="stFileUploader"] {
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(5px);
border-radius: 16px;
padding: 1.5rem;
border: 2px dashed rgba(102, 126, 234, 0.4);
transition: all 0.3s ease;
}
[data-testid="stFileUploader"]:hover {
border-color: #667eea;
background: rgba(255, 255, 255, 0.9);
}
/* ========== RESPONSIVE DESIGN ========== */
@media (max-width: 768px) {
.glass-header h1 {
font-size: 2.5rem;
}
.glass-header p {
font-size: 1rem;
}
.stat-card h3 {
font-size: 2.5rem;
}
.bento-container {
padding: 1.5rem;
}
}
</style>
""", unsafe_allow_html=True)
# ============================================================================
# SESSION STATE
# ============================================================================
if 'pdf_data' not in st.session_state:
st.session_state.pdf_data = None
if 'summary' not in st.session_state:
st.session_state.summary = None
if 'key_info' not in st.session_state:
st.session_state.key_info = None
if 'processing_time' not in st.session_state:
st.session_state.processing_time = 0
# ============================================================================
# CORE FUNCTIONS
# ============================================================================
def extract_pdf_text(pdf_path: Path):
"""Extract text from PDF with metadata."""
try:
with open(pdf_path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
text_data = {
'full_text': '',
'total_pages': len(reader.pages),
'metadata': {}
}
# Extract metadata
if reader.metadata:
text_data['metadata'] = {
'title': reader.metadata.get('/Title', 'N/A'),
'author': reader.metadata.get('/Author', 'N/A'),
'creator': reader.metadata.get('/Creator', 'N/A')
}
# Extract text from all pages
for page in reader.pages:
try:
text = page.extract_text()
if text.strip():
text_data['full_text'] += text + "\n\n"
except:
continue
text_data['word_count'] = len(text_data['full_text'].split())
text_data['char_count'] = len(text_data['full_text'])
return text_data
except Exception as e:
raise Exception(f"PDF extraction failed: {str(e)}")
def generate_ai_summary(text: str):
"""Generate AI summary using Gemini."""
try:
model = genai.GenerativeModel(Config.MODEL_NAME)
prompt = f"""Analyze this document and provide a concise, well-structured summary in approximately 150-200 words.
Focus on key points, main themes, and actionable insights.
DOCUMENT:
{text[:15000]}
Provide a clear, professional summary:"""
response = model.generate_content(prompt)
return response.text.strip()
except Exception as e:
raise Exception(f"AI summarization failed: {str(e)}")
def extract_key_information(text: str):
"""Extract structured information using Gemini."""
try:
model = genai.GenerativeModel(Config.MODEL_NAME)
prompt = f"""Analyze this document and extract key information in a structured format:
DOCUMENT:
{text[:15000]}
Provide the following information:
1. MAIN TOPICS: (List 3-5 key topics, comma-separated)
2. KEY ENTITIES: (People, organizations, locations - comma-separated)
3. IMPORTANT DATES/NUMBERS: (Any significant data points - comma-separated)
4. DOCUMENT TYPE: (Single category/type)
5. KEY TAKEAWAYS: (3-5 bullet points starting with -)
Format your response exactly as shown above."""
response = model.generate_content(prompt)
return parse_response(response.text)
except Exception as e:
raise Exception(f"Information extraction failed: {str(e)}")
def parse_response(text: str):
"""Parse AI response into structured data."""
result = {
'topics': [],
'entities': [],
'dates_numbers': [],
'doc_type': 'Unknown',
'takeaways': []
}
lines = text.split('\n')
current_section = None
for line in lines:
line = line.strip()
if 'MAIN TOPICS:' in line.upper() or line.startswith('1.'):
current_section = 'topics'
if ':' in line:
content = line.split(':', 1)[1].strip()
if content:
result['topics'] = [t.strip() for t in content.split(',') if t.strip()]
elif 'KEY ENTITIES:' in line.upper() or line.startswith('2.'):
current_section = 'entities'
if ':' in line:
content = line.split(':', 1)[1].strip()
if content:
result['entities'] = [e.strip() for e in content.split(',') if e.strip()]
elif 'IMPORTANT DATES' in line.upper() or 'NUMBERS:' in line.upper() or line.startswith('3.'):
current_section = 'dates'
if ':' in line:
content = line.split(':', 1)[1].strip()
if content:
result['dates_numbers'] = [d.strip() for d in content.split(',') if d.strip()]
elif 'DOCUMENT TYPE:' in line.upper() or line.startswith('4.'):
current_section = 'type'
if ':' in line:
result['doc_type'] = line.split(':', 1)[1].strip()
elif 'KEY TAKEAWAYS:' in line.upper() or 'TAKEAWAYS:' in line.upper() or line.startswith('5.'):
current_section = 'takeaways'
elif line.startswith(('- ', '• ', '* ', '·')) and current_section == 'takeaways':
takeaway = line.lstrip('- •*· ').strip()
if takeaway:
result['takeaways'].append(takeaway)
return result
# ============================================================================
# UI - HEADER
# ============================================================================
st.markdown("""
<div class="glass-header">
<h1 style="color: #ffffff !important; text-shadow: 3px 3px 10px rgba(0,0,0,0.7), 0 0 30px rgba(255,255,255,0.3) !important;">🤖 AI PDF EXTRACTOR</h1>
<p style="color: #ffffff !important; text-shadow: 2px 2px 8px rgba(0,0,0,0.6) !important;">Powered by Google Gemini 2.5 • Extract • Analyze • Summarize</p>
</div>
""", unsafe_allow_html=True)
# ============================================================================
# UI - MAIN CONTAINER
# ============================================================================
st.markdown('<div class="bento-container">', unsafe_allow_html=True)
# Create tabs with modern icons
tab1, tab2, tab3, tab4 = st.tabs([
"📤 Upload & Extract",
"🤖 AI Analysis",
"📊 Complete Results",
"ℹ️ About"
])
# ============================================================================
# TAB 1: UPLOAD & EXTRACT
# ============================================================================
with tab1:
st.markdown("<h3 style='text-align: center;'>📄 Upload Your PDF Document</h3>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; color: #666; margin-bottom: 2rem;'>Drag and drop or browse to upload your PDF file (max 10MB)</p>", unsafe_allow_html=True)
# Center the upload area
col_left, col_center, col_right = st.columns([1, 2, 1])
with col_center:
uploaded_file = st.file_uploader(
"Choose PDF",
type=['pdf'],
help="Maximum file size: 10MB",
label_visibility="collapsed"
)
if uploaded_file:
col1, col2 = st.columns(2)
with col1:
st.info(f"**📁 {uploaded_file.name}**")
with col2:
file_size = len(uploaded_file.getvalue()) / (1024 * 1024)
st.success(f"**📊 {file_size:.2f} MB**")
st.markdown("---")
# Center the button
col_left, col_center, col_right = st.columns([1, 2, 1])
with col_center:
extract_btn = st.button("🚀 EXTRACT TEXT", use_container_width=True)
if extract_btn:
start_time = time.time()
with st.spinner("🔄 Processing PDF..."):
try:
# Save temp file
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp:
tmp.write(uploaded_file.getvalue())
tmp_path = Path(tmp.name)
# Extract
pdf_data = extract_pdf_text(tmp_path)
st.session_state.pdf_data = pdf_data
st.session_state.processing_time = time.time() - start_time
# Cleanup
tmp_path.unlink()
st.success("✅ Text extracted successfully!")
# Display stats in Bento grid
st.markdown('<div class="stat-grid">', unsafe_allow_html=True)
col1, col2, col3, col4 = st.columns(4)
with col1:
st.markdown(f"""
<div class="stat-card">
<h3>{pdf_data['total_pages']}</h3>
<p>Pages</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown(f"""
<div class="stat-card">
<h3>{pdf_data['word_count']:,}</h3>
<p>Words</p>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown(f"""
<div class="stat-card">
<h3>{pdf_data['char_count']:,}</h3>
<p>Characters</p>
</div>
""", unsafe_allow_html=True)
with col4:
st.markdown(f"""
<div class="stat-card">
<h3>{st.session_state.processing_time:.2f}s</h3>
<p>Time</p>
</div>
""", unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
except Exception as e:
st.error(f"❌ Error: {str(e)}")
# Preview extracted text
if st.session_state.pdf_data:
st.markdown("---")
with st.expander("👁️ Preview Extracted Text", expanded=False):
preview_text = st.session_state.pdf_data['full_text'][:3000]
st.text_area(
"Document Content",
preview_text + "..." if len(st.session_state.pdf_data['full_text']) > 3000 else preview_text,
height=300,
disabled=True,
label_visibility="collapsed"
)
else:
st.markdown("<br><br>", unsafe_allow_html=True)
st.info("👆 Please upload a PDF file to get started")
# ============================================================================
# TAB 2: AI ANALYSIS
# ============================================================================
with tab2:
st.markdown("<h3 style='text-align: center;'>🤖 AI-Powered Document Analysis</h3>", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
if not st.session_state.pdf_data:
st.warning("⚠️ Please upload and extract a PDF first in the Upload tab.")
else:
st.info(f"🎯 Analyzing document: **{uploaded_file.name if uploaded_file else 'Document'}**")
st.markdown("<br>", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
if st.button("📝 GENERATE AI SUMMARY", use_container_width=True):
with st.spinner("🤖 Generating intelligent summary..."):
try:
summary = generate_ai_summary(st.session_state.pdf_data['full_text'])
st.session_state.summary = summary
st.success("✅ Summary generated successfully!")
st.balloons()
except Exception as e:
st.error(f"❌ Error: {str(e)}")
with col2:
if st.button("🔍 EXTRACT KEY INFORMATION", use_container_width=True):
with st.spinner("🤖 Extracting key insights..."):
try:
key_info = extract_key_information(st.session_state.pdf_data['full_text'])
st.session_state.key_info = key_info
st.success("✅ Information extracted successfully!")
st.balloons()
except Exception as e:
st.error(f"❌ Error: {str(e)}")
# Display Summary
if st.session_state.summary:
st.markdown("---")
st.markdown('<div class="result-box">', unsafe_allow_html=True)
st.markdown("#### 📝 AI-Generated Summary")
st.markdown(f'<div class="justified-text">{st.session_state.summary}</div>', unsafe_allow_html=True)
st.caption(f"✨ Generated by {Config.MODEL_NAME} • {len(st.session_state.summary.split())} words")
st.markdown('</div>', unsafe_allow_html=True)
# Display Key Information
if st.session_state.key_info:
st.markdown("---")
st.markdown('<div class="result-box">', unsafe_allow_html=True)
st.markdown("#### 🔍 Key Information Extracted")
st.markdown("<br>", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
st.markdown("**📌 Main Topics**")
if st.session_state.key_info['topics']:
for topic in st.session_state.key_info['topics']:
st.markdown(f'<span class="badge">{topic}</span>', unsafe_allow_html=True)
else:
st.caption("No topics identified")
st.markdown("<br>**👥 Key Entities**", unsafe_allow_html=True)
if st.session_state.key_info['entities']:
entities_text = "<div style='text-align: left;'>"
for entity in st.session_state.key_info['entities'][:6]:
entities_text += f"<p style='margin: 0.5rem 0; color: #555;'>• {entity}</p>"
entities_text += "</div>"
st.markdown(entities_text, unsafe_allow_html=True)
else:
st.caption("No entities identified")
with col2:
st.markdown(f"**📄 Document Type**")
st.code(st.session_state.key_info['doc_type'], language=None)
st.markdown("**📅 Important Data**")
if st.session_state.key_info['dates_numbers']:
dates_text = "<div style='text-align: left;'>"
for data in st.session_state.key_info['dates_numbers'][:6]:
dates_text += f"<p style='margin: 0.5rem 0; color: #555;'>• {data}</p>"
dates_text += "</div>"
st.markdown(dates_text, unsafe_allow_html=True)
else:
st.caption("No significant dates/numbers found")
if st.session_state.key_info['takeaways']:
st.markdown("<br>**💡 Key Takeaways**", unsafe_allow_html=True)
takeaways_text = "<div class='justified-text'>"
for i, takeaway in enumerate(st.session_state.key_info['takeaways'], 1):
takeaways_text += f"<p><strong>{i}.</strong> {takeaway}</p>"
takeaways_text += "</div>"
st.markdown(takeaways_text, unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
# ============================================================================
# TAB 3: COMPLETE RESULTS
# ============================================================================
with tab3:
st.markdown("<h3 style='text-align: center;'>📊 Complete Analysis Results</h3>", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
if not st.session_state.pdf_data:
st.warning("⚠️ No results available. Please extract a PDF first.")
else:
# Document Information Block
st.markdown('<div class="result-box">', unsafe_allow_html=True)
st.markdown("#### 📄 Document Information")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("📄 Filename", uploaded_file.name if uploaded_file else "N/A")
with col2:
st.metric("📊 Total Pages", st.session_state.pdf_data['total_pages'])
with col3:
st.metric("📝 Word Count", f"{st.session_state.pdf_data['word_count']:,}")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("🔤 Characters", f"{st.session_state.pdf_data['char_count']:,}")
with col2:
st.metric("⏱️ Processing Time", f"{st.session_state.processing_time:.2f}s")
with col3:
st.metric("🤖 AI Model", Config.MODEL_NAME.split('-')[1].upper())
st.markdown('</div>', unsafe_allow_html=True)
# AI Analysis Block
if st.session_state.summary or st.session_state.key_info:
st.markdown('<div class="result-box">', unsafe_allow_html=True)
st.markdown("#### 🤖 AI Analysis Summary")
if st.session_state.summary:
st.markdown("**📝 Document Summary:**")
st.markdown(f'<div class="justified-text">{st.session_state.summary}</div>', unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
if st.session_state.key_info:
col1, col2 = st.columns(2)
with col1:
st.markdown("**📄 Document Type:**")
st.info(st.session_state.key_info['doc_type'])
if st.session_state.key_info['topics']:
st.markdown("**📌 Topics:**")
for topic in st.session_state.key_info['topics']:
st.markdown(f"- {topic}")
with col2:
if st.session_state.key_info['entities']:
st.markdown("**👥 Entities:**")
for entity in st.session_state.key_info['entities'][:5]:
st.markdown(f"- {entity}")
if st.session_state.key_info['dates_numbers']:
st.markdown("**📅 Key Data:**")
for data in st.session_state.key_info['dates_numbers'][:5]:
st.markdown(f"- {data}")
st.markdown('</div>', unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# Download Options
st.markdown('<div class="result-box">', unsafe_allow_html=True)
st.markdown("#### ⬇️ Download Options")
# Compile results
results = {
'document_info': {
'filename': uploaded_file.name if uploaded_file else 'N/A',
'total_pages': st.session_state.pdf_data['total_pages'],
'word_count': st.session_state.pdf_data['word_count'],
'character_count': st.session_state.pdf_data['char_count'],
'processing_time_seconds': round(st.session_state.processing_time, 2),
'metadata': st.session_state.pdf_data['metadata']
},
'ai_analysis': {
'summary': st.session_state.summary,
'key_information': st.session_state.key_info,
'model_used': Config.MODEL_NAME
},
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S IST")
}
col1, col2 = st.columns(2)
with col1:
json_data = json.dumps(results, indent=2)
st.download_button(
label="📥 DOWNLOAD JSON",
data=json_data,
file_name=f"analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
mime="application/json",
use_container_width=True
)
with col2:
# Create text report
text_report = f"""
AI PDF EXTRACTION REPORT
========================
Document: {results['document_info']['filename']}
Processed: {results['timestamp']}
Model: {Config.MODEL_NAME}
STATISTICS:
- Pages: {results['document_info']['total_pages']}
- Words: {results['document_info']['word_count']}
- Characters: {results['document_info']['character_count']}
- Processing Time: {results['document_info']['processing_time_seconds']}s
AI SUMMARY:
{st.session_state.summary if st.session_state.summary else 'Not generated'}
KEY INFORMATION:
- Document Type: {st.session_state.key_info['doc_type'] if st.session_state.key_info else 'N/A'}
- Topics: {', '.join(st.session_state.key_info['topics']) if st.session_state.key_info and st.session_state.key_info['topics'] else 'N/A'}
Generated by AI PDF Extractor
"""
st.download_button(
label="📥 DOWNLOAD TXT",
data=text_report,
file_name=f"report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
mime="text/plain",
use_container_width=True
)
st.markdown('</div>', unsafe_allow_html=True)
# ============================================================================
# TAB 4: ABOUT & INFO
# ============================================================================
with tab4:
st.markdown("<h3 style='text-align: center; margin-bottom: 0.5rem;'>📖 About AI PDF Extractor</h3>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; color: #666; margin-bottom: 2rem;'>Intelligent document processing powered by Google Gemini AI</p>", unsafe_allow_html=True)
# Row 1: Key Features and How to Use
col1, col2 = st.columns(2, gap="large")
with col1:
with st.container():
st.markdown("#### ✨ Key Features")
st.markdown("")
st.markdown("**📄 PDF Text Extraction**")
st.caption("Extract text from any PDF document with complete metadata and structural information")
st.markdown("")
st.markdown("**🤖 AI Summarization**")
st.caption("Generate intelligent, context-aware summaries using Google Gemini 2.5 Flash model")
st.markdown("")