File size: 11,946 Bytes
09281fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
PDF Document Processor Test
Allows you to choose any PDF file and process it with the document processor
"""

import os
import sys
import tkinter as tk
from tkinter import filedialog, messagebox
from pathlib import Path
import tempfile
import shutil

def select_pdf_file():
    """Open file dialog to select a PDF file"""
    root = tk.Tk()
    root.withdraw()  # Hide the main window
    
    file_path = filedialog.askopenfilename(
        title="Select a PDF file to process",
        filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")]
    )
    
    root.destroy()
    return file_path

def process_pdf_with_ocr(pdf_path, use_ocr=False):
    """Process a PDF file with optional OCR"""
    try:
        from document_processer import AdvancedDocumentProcessor
        
        print(f"πŸ”„ Processing PDF: {pdf_path}")
        print(f"πŸ“„ File size: {os.path.getsize(pdf_path) / 1024:.1f} KB")
        
        # Initialize processor
        processor = AdvancedDocumentProcessor()
        
        # Process the document
        chunks = processor.process_document(pdf_path, use_ocr=use_ocr)
        
        return chunks, None
        
    except Exception as e:
        return None, str(e)

def display_results(chunks, pdf_path):
    """Display processing results"""
    print(f"\n{'='*60}")
    print("πŸ“Š PROCESSING RESULTS")
    print(f"{'='*60}")
    
    print(f"πŸ“„ PDF File: {pdf_path}")
    print(f"πŸ“Š Total Chunks: {len(chunks)}")
    
    # Analyze chunks
    text_chunks = [c for c in chunks if c.section_type == 'main_text']
    table_chunks = [c for c in chunks if c.section_type == 'table']
    metadata_chunks = [c for c in chunks if c.section_type == 'metadata']
    
    print(f"πŸ“ Text Chunks: {len(text_chunks)}")
    print(f"πŸ“Š Table Chunks: {len(table_chunks)}")
    print(f"🏷️  Metadata Chunks: {len(metadata_chunks)}")
    
    # Show sample chunks
    print(f"\nπŸ“‹ SAMPLE CHUNKS:")
    for i, chunk in enumerate(chunks[:5]):  # Show first 5 chunks
        print(f"\nChunk {i+1}:")
        print(f"  ID: {chunk.chunk_id}")
        print(f"  Type: {chunk.section_type}")
        print(f"  Content Preview: {chunk.content[:150]}...")
        
        if chunk.table_data:
            print(f"  Table Data: {len(chunk.table_data.get('data', []))} rows")
    
    if len(chunks) > 5:
        print(f"\n... and {len(chunks) - 5} more chunks")
    
    # Save results to file
    save_results_to_file(chunks, pdf_path)

def save_results_to_file(chunks, pdf_path):
    """Save processing results to a text file"""
    try:
        # Create output filename
        pdf_name = Path(pdf_path).stem
        output_file = f"{pdf_name}_processed_results.txt"
        
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(f"PDF Processing Results\n")
            f.write(f"="*50 + "\n")
            f.write(f"Source PDF: {pdf_path}\n")
            f.write(f"Total Chunks: {len(chunks)}\n\n")
            
            for i, chunk in enumerate(chunks):
                f.write(f"Chunk {i+1}:\n")
                f.write(f"  ID: {chunk.chunk_id}\n")
                f.write(f"  Type: {chunk.section_type}\n")
                f.write(f"  Source: {chunk.source_file}\n")
                f.write(f"  File Type: {chunk.file_type}\n")
                f.write(f"  Content:\n{chunk.content}\n")
                f.write(f"  {'-'*40}\n\n")
        
        print(f"\nπŸ’Ύ Results saved to: {output_file}")
        
    except Exception as e:
        print(f"⚠️  Could not save results to file: {e}")

def analyze_pdf_content(chunks):
    """Analyze the content of processed chunks"""
    print(f"\nπŸ” CONTENT ANALYSIS")
    print(f"{'='*40}")
    
    total_text_length = sum(len(chunk.content) for chunk in chunks)
    avg_chunk_size = total_text_length / len(chunks) if chunks else 0
    
    print(f"πŸ“ Total Text Length: {total_text_length:,} characters")
    print(f"πŸ“Š Average Chunk Size: {avg_chunk_size:.0f} characters")
    
    # Find longest and shortest chunks
    if chunks:
        longest_chunk = max(chunks, key=lambda x: len(x.content))
        shortest_chunk = min(chunks, key=lambda x: len(x.content))
        
        print(f"πŸ“ Longest Chunk: {len(longest_chunk.content)} characters")
        print(f"πŸ“ Shortest Chunk: {len(shortest_chunk.content)} characters")
    
    # Count unique words
    all_text = " ".join(chunk.content for chunk in chunks)
    unique_words = len(set(all_text.lower().split()))
    total_words = len(all_text.split())
    
    print(f"πŸ“ Total Words: {total_words:,}")
    print(f"πŸ“ Unique Words: {unique_words:,}")

def main():
    """Main function to run the PDF processor test"""
    print("πŸš€ PDF Document Processor Test")
    print("="*50)
    print("This tool allows you to process any PDF file by specifying its path.")
    print("You can choose whether to use OCR for better text extraction.")
    print()
    
    # Check if document processor is available
    try:
        from document_processer import AdvancedDocumentProcessor
        print("βœ… Document processor loaded successfully")
    except ImportError as e:
        print(f"❌ Error loading document processor: {e}")
        print("πŸ’‘ Make sure document_processer.py is in the same directory")
        return
    
    # Get PDF file path
    print("\nπŸ“ Enter the path to your PDF file:")
    print("   Examples:")
    print("   - C:\\Users\\YourName\\Documents\\document.pdf")
    print("   - /home/username/documents/document.pdf")
    print("   - ./local_file.pdf")
    print("   - Or press Enter to use file dialog")
    
    pdf_path = input("PDF file path: ").strip()
    
    # If no path provided, use file dialog
    if not pdf_path:
        print("\nπŸ“ Opening file dialog...")
        pdf_path = select_pdf_file()
    
    if not pdf_path:
        print("❌ No file selected. Exiting.")
        return
    
    # Expand relative paths and resolve to absolute path
    pdf_path = os.path.abspath(os.path.expanduser(pdf_path))
    
    if not os.path.exists(pdf_path):
        print(f"❌ File not found: {pdf_path}")
        print("πŸ’‘ Please check the file path and try again.")
        return
    
    # Check if it's actually a PDF file
    if not pdf_path.lower().endswith('.pdf'):
        print(f"⚠️  Warning: File doesn't have .pdf extension: {pdf_path}")
        proceed = input("Continue anyway? (y/n): ").lower().strip()
        if proceed not in ['y', 'yes']:
            print("❌ Exiting.")
            return
    
    print(f"βœ… Found file: {pdf_path}")
    print(f"πŸ“„ File size: {os.path.getsize(pdf_path) / 1024:.1f} KB")
    
    # Ask about OCR
    print("\nπŸ€” Do you want to use OCR for better text extraction?")
    print("   OCR is useful for scanned PDFs or PDFs with images")
    print("   OCR takes longer but provides better results for image-based PDFs")
    
    use_ocr = input("Use OCR? (y/n): ").lower().strip() in ['y', 'yes']
    
    if use_ocr:
        print("πŸ” Will use OCR for text extraction")
    else:
        print("πŸ“ Will use standard text extraction")
    
    # Process the PDF
    print(f"\nπŸ”„ Processing PDF...")
    chunks, error = process_pdf_with_ocr(pdf_path, use_ocr)
    
    if error:
        print(f"❌ Error processing PDF: {error}")
        print("\nπŸ’‘ Troubleshooting tips:")
        print("1. Make sure the PDF file is not corrupted")
        print("2. Try without OCR if the PDF has text")
        print("3. Check if all dependencies are installed")
        print("4. Verify the file path is correct")
        return
    
    if not chunks:
        print("❌ No chunks were extracted from the PDF")
        print("πŸ’‘ This might be because:")
        print("   - The PDF is password protected")
        print("   - The PDF contains only images")
        print("   - The PDF is corrupted")
        return
    
    # Display results
    display_results(chunks, pdf_path)
    
    # Analyze content
    analyze_pdf_content(chunks)
    
    print(f"\nπŸŽ‰ PDF processing completed successfully!")
    print(f"πŸ“„ Processed: {pdf_path}")
    print(f"πŸ“Š Extracted: {len(chunks)} chunks")

def batch_process_pdfs():
    """Process multiple PDF files in a directory"""
    print("πŸ”„ Batch PDF Processing")
    print("="*40)
    
    # Select directory
    root = tk.Tk()
    root.withdraw()
    directory = filedialog.askdirectory(title="Select directory containing PDF files")
    root.destroy()
    
    if not directory:
        print("❌ No directory selected")
        return
    
    # Find PDF files
    pdf_files = list(Path(directory).glob("*.pdf"))
    
    if not pdf_files:
        print("❌ No PDF files found in the selected directory")
        return
    
    print(f"πŸ“ Found {len(pdf_files)} PDF files in {directory}")
    
    # Process each PDF
    results = {}
    for pdf_file in pdf_files:
        print(f"\nπŸ”„ Processing: {pdf_file.name}")
        chunks, error = process_pdf_with_ocr(str(pdf_file), use_ocr=False)
        
        if error:
            print(f"❌ Error: {error}")
            results[pdf_file.name] = "ERROR"
        else:
            print(f"βœ… Processed: {len(chunks)} chunks")
            results[pdf_file.name] = len(chunks)
    
    # Summary
    print(f"\nπŸ“Š BATCH PROCESSING SUMMARY")
    print(f"{'='*40}")
    successful = sum(1 for result in results.values() if isinstance(result, int))
    total = len(results)
    
    for filename, result in results.items():
        status = f"{result} chunks" if isinstance(result, int) else result
        print(f"{filename}: {status}")
    
    print(f"\nβœ… Successfully processed: {successful}/{total} files")

def process_from_command_line():
    """Process PDF from command line arguments"""
    import sys
    
    if len(sys.argv) < 2:
        print("❌ Usage: python test_pdf_processor.py <pdf_file_path> [--ocr]")
        print("   Example: python test_pdf_processor.py C:\\path\\to\\document.pdf --ocr")
        return
    
    pdf_path = sys.argv[1]
    use_ocr = "--ocr" in sys.argv
    
    # Expand relative paths and resolve to absolute path
    pdf_path = os.path.abspath(os.path.expanduser(pdf_path))
    
    if not os.path.exists(pdf_path):
        print(f"❌ File not found: {pdf_path}")
        return
    
    print(f"πŸš€ Processing PDF from command line: {pdf_path}")
    print(f"πŸ” OCR enabled: {use_ocr}")
    
    # Process the PDF
    chunks, error = process_pdf_with_ocr(pdf_path, use_ocr)
    
    if error:
        print(f"❌ Error processing PDF: {error}")
        return
    
    if not chunks:
        print("❌ No chunks were extracted from the PDF")
        return
    
    # Display results
    display_results(chunks, pdf_path)
    analyze_pdf_content(chunks)
    
    print(f"\nπŸŽ‰ PDF processing completed successfully!")

if __name__ == "__main__":
    # Check if command line arguments are provided
    if len(sys.argv) > 1 and not sys.argv[1].startswith("--"):
        process_from_command_line()
    else:
        print("Choose an option:")
        print("1. Process a single PDF file")
        print("2. Batch process all PDFs in a directory")
        print("3. Process from command line (usage: python test_pdf_processor.py <pdf_path> [--ocr])")
        
        choice = input("Enter choice (1, 2, or 3): ").strip()
        
        if choice == "1":
            main()
        elif choice == "2":
            batch_process_pdfs()
        elif choice == "3":
            print("\nCommand line usage:")
            print("python test_pdf_processor.py <pdf_file_path> [--ocr]")
            print("\nExamples:")
            print("python test_pdf_processor.py C:\\path\\to\\document.pdf")
            print("python test_pdf_processor.py /home/user/document.pdf --ocr")
            print("python test_pdf_processor.py ./local_file.pdf")
        else:
            print("❌ Invalid choice. Exiting.")