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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#  streamlit run extraction_ui.py
import streamlit as st
import requests
import fitz  # PyMuPDF
import docx
from io import BytesIO
import re
from datetime import datetime
from typing import Dict, List, Tuple

# Set page configuration
st.set_page_config(
    page_title="PDF Entity Extractor",
    page_icon="📄",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# Custom CSS for professional styling
st.markdown("""
<style>
    .main-header {
        font-size: 2.5rem;
        color: #1E3A8A;
        text-align: center;
        margin-bottom: 1rem;
        font-weight: 600;
    }
    .section-header {
        font-size: 1.5rem;
        color: #374151;
        margin-bottom: 1rem;
        font-weight: 600;
        border-bottom: 2px solid #E5E7EB;
        padding-bottom: 0.5rem;
    }
    .info-box {
        background-color: #F3F4F6;
        padding: 1.5rem;
        border-radius: 8px;
        border-left: 4px solid #3B82F6;
        margin-bottom: 1.5rem;
    }
    .success-box {
        background-color: #D1FAE5;
        padding: 1rem;
        border-radius: 6px;
        border-left: 4px solid #10B981;
        margin: 1rem 0;
    }
    .entity-card {
        background-color: white;
        border: 1px solid #E5E7EB;
        border-radius: 8px;
        padding: 1rem;
        margin-bottom: 1rem;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }
    .stButton button {
        background-color: #2563EB;
        color: white;
        border: none;
        padding: 0.5rem 1rem;
        border-radius: 6px;
        font-weight: 500;
        transition: background-color 0.3s;
        height: 44px;
        margin-top: 1.6rem;
    }
    .stButton button:hover {
        background-color: #1D4ED8;
    }
    .clear-btn button {
        background-color: #EF4444 !important;
        height: 44px;
        margin-top: 1.6rem;
    }
    .clear-btn button:hover {
        background-color: #DC2626 !important;
    }
    .download-btn {
        background-color: #10B981 !important;
    }
    .download-btn:hover {
        background-color: #0DA271 !important;
    }
    .stDownloadButton button {
        width: 100%;
    }
    .stExpander {
        border: 1px solid #E5E7EB;
        border-radius: 8px;
        margin-bottom: 0.5rem;
    }
    .entity-item {
        padding: 0.5rem 0;
        border-bottom: 1px solid #F3F4F6;
    }
    .entity-item:last-child {
        border-bottom: none;
    }
    .url-input-container {
        margin-bottom: 1rem;
    }
</style>
""", unsafe_allow_html=True)

# Initialize session state
if 'extracted_text' not in st.session_state:
    st.session_state.extracted_text = ""
if 'entities' not in st.session_state:
    st.session_state.entities = {}
if 'docx_buffer' not in st.session_state:
    st.session_state.docx_buffer = None
if 'pdf_bytes' not in st.session_state:
    st.session_state.pdf_bytes = None
if 'filename' not in st.session_state:
    st.session_state.filename = ""
if 'show_entities' not in st.session_state:
    st.session_state.show_entities = False
if 'pdf_preview_buffer' not in st.session_state:
    st.session_state.pdf_preview_buffer = None

def extract_text_from_pdf(pdf_bytes: bytes) -> str:
    """Extract text from PDF bytes."""
    text = ""
    try:
        with fitz.open(stream=pdf_bytes, filetype="pdf") as doc:
            for page in doc:
                text += page.get_text()
    except Exception as e:
        st.error(f"Error extracting text from PDF: {str(e)}")
    return text

def extract_entities(text: str) -> Dict[str, List[str]]:
    """Extract entities from text using regex patterns."""
    entities = {
        "Dates": [],
        "Email Addresses": [],
        "Phone Numbers": [],
        "URLs": [],
        "Monetary Values": [],
        "Names": [],
        "Organizations": []
    }
    
    # Date patterns
    date_patterns = [
        r'\b\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b',
        r'\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{1,2},? \d{4}\b',
        r'\b\d{4}[/-]\d{1,2}[/-]\d{1,2}\b'
    ]
    
    # Email pattern
    email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    
    # Phone number patterns
    phone_patterns = [
        r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b',
        r'\b\(\d{3}\)\s*\d{3}[-.]?\d{4}\b',
    ]
    
    # URL pattern
    url_pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+[/\w\.-]*'
    
    # Monetary values pattern
    money_pattern = r'\$\d{1,3}(?:,\d{3})*(?:\.\d{2})?|\b\d+\s*(?:dollars|USD)\b'
    
    # Name pattern (simplified)
    name_pattern = r'\b(?:Mr\.|Ms\.|Mrs\.|Dr\.)\s+[A-Z][a-z]+\s+[A-Z][a-z]+\b'
    
    # Organization patterns
    org_patterns = [
        r'\b(?:Inc\.|LLC|Ltd\.|Corp\.|Company|Co\.|Corporation|Incorporated)\b',
        r'\b[A-Z][a-z]+\s+(?:Inc|LLC|Ltd|Corp|Co)\b'
    ]
    
    # Extract dates
    for pattern in date_patterns:
        entities["Dates"].extend(re.findall(pattern, text, re.IGNORECASE))
    
    # Extract emails
    entities["Email Addresses"].extend(re.findall(email_pattern, text, re.IGNORECASE))
    
    # Extract phone numbers
    for pattern in phone_patterns:
        entities["Phone Numbers"].extend(re.findall(pattern, text))
    
    # Extract URLs
    entities["URLs"].extend(re.findall(url_pattern, text, re.IGNORECASE))
    
    # Extract monetary values
    entities["Monetary Values"].extend(re.findall(money_pattern, text, re.IGNORECASE))
    
    # Extract names
    entities["Names"].extend(re.findall(name_pattern, text))
    
    # Extract organizations
    for pattern in org_patterns:
        entities["Organizations"].extend(re.findall(pattern, text, re.IGNORECASE))
    
    # Remove duplicates and sort each entity list
    for key in entities:
        entities[key] = sorted(list(set(entities[key])))
    
    return entities

def create_word_document(entities: Dict[str, List[str]], filename: str) -> BytesIO:
    """Create a Word document from extracted entities."""
    doc = docx.Document()
    
    # Add title
    title = doc.add_heading('Extracted Entities Report', 0)
    title.alignment = 1  # Center alignment
    
    # Add metadata
    doc.add_paragraph(f"Source Document: {filename}")
    doc.add_paragraph(f"Extraction Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    doc.add_paragraph("")
    
    # Add summary
    doc.add_heading('Summary', level=1)
    summary_table = doc.add_table(rows=1, cols=2)
    summary_table.style = 'LightShading-Accent1'
    hdr_cells = summary_table.rows[0].cells
    hdr_cells[0].text = 'Entity Type'
    hdr_cells[1].text = 'Count'
    
    total_entities = 0
    for entity_type, values in entities.items():
        if values:
            row_cells = summary_table.add_row().cells
            row_cells[0].text = entity_type
            row_cells[1].text = str(len(values))
            total_entities += len(values)
    
    doc.add_paragraph(f"\nTotal Entities Extracted: {total_entities}")
    doc.add_paragraph("")
    
    # Add detailed entities
    doc.add_heading('Detailed Entities', level=1)
    
    for entity_type, values in entities.items():
        if values:
            doc.add_heading(entity_type, level=2)
            for value in values:
                doc.add_paragraph(f"• {value}", style='ListBullet')
            doc.add_paragraph()
    
    # Save to bytes buffer
    buffer = BytesIO()
    doc.save(buffer)
    buffer.seek(0)
    return buffer

def create_pdf_preview(entities: Dict[str, List[str]], filename: str) -> BytesIO:
    """Create a simple PDF preview using PyMuPDF."""
    buffer = BytesIO()
    
    # Create a new PDF document
    doc = fitz.open()
    
    # Add a page
    page = doc.new_page()
    
    # Define margins and starting position
    margin = 50
    x = margin
    y = margin
    line_height = 14
    page_height = 800
    
    # Title
    title = "Extracted Entities Preview"
    page.insert_text((x, y), title, fontsize=16, color=(0.12, 0.23, 0.54))  # #1E3A8A
    y += 40
    
    # Metadata
    page.insert_text((x, y), f"Source: {filename}", fontsize=10)
    y += line_height * 1.5
    
    page.insert_text((x, y), f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", fontsize=10)
    y += 30
    
    # Summary section
    page.insert_text((x, y), "Summary", fontsize=12, color=(0.22, 0.26, 0.32))  # #374151
    y += 25
    
    # Draw summary table header
    page.draw_rect((x, y, x + 300, y + 25), fill=(0.23, 0.51, 0.96))  # #3B82F6
    page.insert_text((x + 10, y + 18), "Entity Type", fontsize=10, color=(1, 1, 1))
    page.insert_text((x + 210, y + 18), "Count", fontsize=10, color=(1, 1, 1))
    y += 25
    
    total_entities = 0
    row_index = 0
    
    # Add entity rows
    for entity_type, values in entities.items():
        if values:
            # Alternate row colors
            if row_index % 2 == 0:
                fill_color = (0.95, 0.96, 0.97)  # Light gray
            else:
                fill_color = (1, 1, 1)  # White
            
            page.draw_rect((x, y, x + 300, y + 20), fill=fill_color)
            page.insert_text((x + 10, y + 13), entity_type, fontsize=10)
            page.insert_text((x + 210, y + 13), str(len(values)), fontsize=10)
            y += 20
            total_entities += len(values)
            row_index += 1
    
    # Add total row
    y += 5
    page.draw_rect((x, y, x + 300, y + 25), fill=(0.95, 0.96, 0.97))
    page.insert_text((x + 10, y + 18), "Total", fontsize=10, fontname="helv", color=(0, 0, 0))
    page.insert_text((x + 210, y + 18), str(total_entities), fontsize=10, fontname="helv", color=(0, 0, 0))
    y += 40
    
    # Detailed entities section
    if y > page_height - 100:
        page = doc.new_page()
        x = margin
        y = margin
    
    page.insert_text((x, y), "Detailed Entities", fontsize=12, color=(0.22, 0.26, 0.32))
    y += 30
    
    # Add each entity type with values
    for entity_type, values in entities.items():
        if values:
            if y > page_height - 50:
                page = doc.new_page()
                x = margin
                y = margin
            
            page.insert_text((x, y), f"{entity_type}:", fontsize=11, color=(0.12, 0.23, 0.54))
            y += 20
            
            for value in values:
                if y > page_height - 30:
                    page = doc.new_page()
                    x = margin
                    y = margin
                
                page.insert_text((x + 20, y), f"• {value}", fontsize=10)
                y += line_height
            
            y += 10
    
    # Save to buffer
    doc.save(buffer)
    doc.close()
    buffer.seek(0)
    return buffer

def display_pdf_viewer(pdf_bytes: bytes, filename: str, preview: bool = False):
    """Display PDF in the viewer."""
    try:
        # Convert PDF to images for display
        pdf_document = fitz.open(stream=pdf_bytes, filetype="pdf")
        
        # Display first page as preview
        page = pdf_document[0]
        pix = page.get_pixmap(dpi=150)
        
        # Convert to bytes for display
        img_bytes = pix.tobytes("png")
        
        # Display the PDF page as image
        st.image(img_bytes, use_container_width=True)
        
        # Show document info
        col1, col2 = st.columns(2)
        with col1:
            display_name = "Entities Preview.pdf" if preview else filename
            st.caption(f"**File:** {display_name}")
        with col2:
            st.caption(f"**Pages:** {len(pdf_document)}")
        
        pdf_document.close()
        
    except Exception as e:
        st.error(f"Error displaying PDF: {str(e)}")

def fetch_pdf_from_url(url: str) -> Tuple[bool, bytes]:
    """Fetch PDF from URL."""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        
        # Check if it's a PDF
        content_type = response.headers.get('content-type', '').lower()
        if 'pdf' in content_type or url.lower().endswith('.pdf'):
            return True, response.content
        else:
            st.warning("The URL does not appear to point to a PDF file.")
            return False, b""
    except requests.exceptions.RequestException as e:
        st.error(f"Error fetching PDF: {str(e)}")
        return False, b""

def clear_session():
    """Clear session state."""
    st.session_state.extracted_text = ""
    st.session_state.entities = {}
    st.session_state.docx_buffer = None
    st.session_state.pdf_bytes = None
    st.session_state.filename = ""
    st.session_state.show_entities = False
    st.session_state.pdf_preview_buffer = None

# Main application
def main():
    # Header
    st.markdown('<div class="main-header">PDF Entity Extractor</div>', unsafe_allow_html=True)
    
    # Top section for URL input with aligned buttons
    st.markdown("### Fetch PDF from URL")
    
    # Create columns for aligned layout
    url_col1, url_col2, url_col3 = st.columns([4, 1, 1])
    
    with url_col1:
        url_input = st.text_input(
            "Enter PDF URL",
            placeholder="https://example.com/document.pdf",
            label_visibility="collapsed",
            key="url_input"
        )
    
    with url_col2:
        fetch_btn = st.button("Fetch", use_container_width=True, type="primary")
    
    with url_col3:
        if st.button("Clear All", use_container_width=True, type="secondary"):
            clear_session()
            st.rerun()
    
    # File upload section
    st.markdown("---")
    uploaded_file = st.file_uploader(
        "Upload PDF File",
        type=["pdf"],
        help="Select a PDF file from your device",
        label_visibility="collapsed"
    )
    
    # Handle URL fetch
    if fetch_btn and url_input:
        with st.spinner("Fetching PDF document..."):
            success, pdf_bytes = fetch_pdf_from_url(url_input)
            if success:
                st.session_state.pdf_bytes = pdf_bytes
                st.session_state.filename = url_input.split("/")[-1] or "document.pdf"
                st.success("PDF document fetched successfully")
                st.session_state.show_entities = False
    
    # Handle file upload
    elif uploaded_file is not None:
        st.session_state.pdf_bytes = uploaded_file.getvalue()
        st.session_state.filename = uploaded_file.name
        st.session_state.show_entities = False
    
    # Process PDF if available
    if st.session_state.pdf_bytes:
        # Create two columns
        col1, col2 = st.columns([1, 1], gap="large")
        
        with col1:
            st.markdown('<div class="section-header">PDF Document</div>', unsafe_allow_html=True)
            display_pdf_viewer(st.session_state.pdf_bytes, st.session_state.filename)
            
            # Download button for PDF
            st.download_button(
                label="Download PDF",
                data=st.session_state.pdf_bytes,
                file_name=st.session_state.filename,
                mime="application/pdf",
                use_container_width=True,
                key="pdf_download"
            )
        
        with col2:
            st.markdown('<div class="section-header">Entity Extraction</div>', unsafe_allow_html=True)
            
            # Extract entities button
            if st.button("Extract Entities", use_container_width=True, type="primary"):
                with st.spinner("Processing document..."):
                    text = extract_text_from_pdf(st.session_state.pdf_bytes)
                    if text.strip():
                        entities = extract_entities(text)
                        st.session_state.extracted_text = text
                        st.session_state.entities = entities
                        
                        # Create Word document
                        docx_buffer = create_word_document(entities, st.session_state.filename)
                        st.session_state.docx_buffer = docx_buffer
                        
                        # Create PDF preview
                        pdf_preview_buffer = create_pdf_preview(entities, st.session_state.filename)
                        st.session_state.pdf_preview_buffer = pdf_preview_buffer
                        
                        st.session_state.show_entities = True
                        st.success(f"Extracted {sum(len(v) for v in entities.values())} entities")
                    else:
                        st.error("Could not extract text from PDF. The document may be scanned or contain only images.")
            
            # Display entities if available
            if st.session_state.show_entities and st.session_state.entities:
                if any(st.session_state.entities.values()):
                    st.markdown("### Extracted Entities Preview")
                    
                    # Display PDF preview
                    if st.session_state.pdf_preview_buffer:
                        display_pdf_viewer(st.session_state.pdf_preview_buffer, "", preview=True)
                    
                    # Download Word document button
                    if st.session_state.docx_buffer:
                        st.markdown("### Download Report")
                        doc_name = f"{st.session_state.filename.rsplit('.', 1)[0]}_entities_report.docx"
                        
                        st.download_button(
                            label="Download Word Report",
                            data=st.session_state.docx_buffer,
                            file_name=doc_name,
                            mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                            use_container_width=True,
                            key="docx_download"
                        )
                        
                        st.caption("Note: The preview above is a PDF. The download will be a Word document containing the complete report.")
                
                else:
                    st.info("No entities found in the document.")
            else:
                st.info("Click 'Extract Entities' to begin entity extraction.")
    
    else:
        # Show instructions when no PDF is loaded
        st.markdown('<div class="info-box">', unsafe_allow_html=True)
        st.markdown("""
        ### Welcome to PDF Entity Extractor
        
        **To get started, you can either:**
        1. **Enter a URL** - Provide a direct link to a PDF file above
        2. **Upload a PDF** - Use the upload area below to select a file from your device
        
        **What this tool does:**
        - Extracts entities like dates, email addresses, phone numbers, URLs, monetary values, names, and organizations
        - Generates a comprehensive Word document report
        - Provides a PDF preview of extracted entities
        
        **Supported formats:** PDF files with extractable text
        """)
        st.markdown('</div>', unsafe_allow_html=True)

if __name__ == "__main__":
    main()