mbuckle commited on
Commit
78b142a
·
1 Parent(s): ce717af

Enhanced paddle test

Browse files
archive/app -og.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py - Correct structure with monkey patch BEFORE any fitz imports
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+ import time
8
+ import base64
9
+ import json
10
+
11
+ # SSL fix function (keep as is)
12
+ def fix_ssl_library():
13
+ """Download and install libssl1.1 if not present"""
14
+ try:
15
+ if os.path.exists('/usr/lib/x86_64-linux-gnu/libssl.so.1.1'):
16
+ print("libssl.so.1.1 already exists")
17
+ return True
18
+
19
+ print("Attempting to install libssl1.1...")
20
+
21
+ subprocess.run([
22
+ 'wget', '-q',
23
+ 'http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb',
24
+ '-O', '/tmp/libssl1.1.deb'
25
+ ], check=True)
26
+
27
+ result = subprocess.run([
28
+ 'dpkg', '-i', '/tmp/libssl1.1.deb'
29
+ ], capture_output=True, text=True)
30
+
31
+ if result.returncode != 0:
32
+ print("dpkg install failed, trying manual extraction...")
33
+ subprocess.run([
34
+ 'dpkg', '-x', '/tmp/libssl1.1.deb', '/tmp/ssl_extract'
35
+ ], check=True)
36
+
37
+ lib_path = '/tmp/ssl_extract/usr/lib/x86_64-linux-gnu'
38
+ current_ld_path = os.environ.get('LD_LIBRARY_PATH', '')
39
+ if current_ld_path:
40
+ os.environ['LD_LIBRARY_PATH'] = f"{lib_path}:{current_ld_path}"
41
+ else:
42
+ os.environ['LD_LIBRARY_PATH'] = lib_path
43
+ print(f"Set LD_LIBRARY_PATH to: {os.environ['LD_LIBRARY_PATH']}")
44
+
45
+ return True
46
+
47
+ except Exception as e:
48
+ print(f"Failed to install libssl1.1: {e}")
49
+ return False
50
+
51
+ # CRITICAL: Apply monkey patch BEFORE importing fitz/PyMuPDF
52
+ def monkey_patch_pymupdf():
53
+ """Fix PaddleOCR compatibility with newer PyMuPDF versions"""
54
+ print("Applying PyMuPDF compatibility patches...")
55
+
56
+ # Import fitz here to apply patches
57
+ import fitz
58
+
59
+ # Add pageCount property to Document class if it doesn't exist
60
+ if not hasattr(fitz.Document, 'pageCount'):
61
+ def pageCount_property(self):
62
+ return self.page_count
63
+
64
+ fitz.Document.pageCount = property(pageCount_property)
65
+ print("✓ Added pageCount compatibility property to PyMuPDF Document class")
66
+ else:
67
+ print("✓ pageCount already exists")
68
+
69
+ # Add getPixmap method to Page class if it doesn't exist
70
+ if not hasattr(fitz.Page, 'getPixmap'):
71
+ def getPixmap(self, matrix=None, alpha=True):
72
+ return self.get_pixmap(matrix=matrix, alpha=alpha)
73
+
74
+ fitz.Page.getPixmap = getPixmap
75
+ print("✓ Added getPixmap compatibility method to PyMuPDF Page class")
76
+ else:
77
+ print("✓ getPixmap already exists")
78
+
79
+ # Add getText method if it doesn't exist
80
+ if not hasattr(fitz.Page, 'getText'):
81
+ def getText(self, option="text"):
82
+ return self.get_text(option)
83
+
84
+ fitz.Page.getText = getText
85
+ print("✓ Added getText compatibility method to PyMuPDF Page class")
86
+ else:
87
+ print("✓ getText already exists")
88
+
89
+ print("✓ PyMuPDF compatibility patches applied successfully")
90
+
91
+ def try_paddle_import():
92
+ """Try different approaches to import PaddleOCR"""
93
+
94
+ # First try the SSL fix
95
+ fix_ssl_library()
96
+
97
+ # CRITICAL: Apply PyMuPDF compatibility patches BEFORE importing PaddleOCR
98
+ monkey_patch_pymupdf()
99
+
100
+ # Try importing with different environment variables
101
+ os.environ['PADDLE_GIT_DISABLE'] = '1'
102
+
103
+ try:
104
+ from paddleocr import PaddleOCR
105
+ return PaddleOCR
106
+ except ImportError as e:
107
+ if 'libssl.so.1.1' in str(e):
108
+ print("Still having SSL issues, trying alternative PaddlePaddle version...")
109
+
110
+ try:
111
+ subprocess.run([sys.executable, '-m', 'pip', 'uninstall', 'paddlepaddle', '-y'],
112
+ capture_output=True)
113
+ subprocess.run([sys.executable, '-m', 'pip', 'install', 'paddlepaddle==2.4.2'],
114
+ check=True)
115
+ from paddleocr import PaddleOCR
116
+ return PaddleOCR
117
+ except Exception as inner_e:
118
+ print(f"Failed to install alternative version: {inner_e}")
119
+
120
+ print(f"PaddleOCR import failed: {e}")
121
+ raise e
122
+
123
+ # Import Gradio
124
+ import gradio as gr
125
+
126
+ # Import PyMuPDF AFTER monkey patch is defined but BEFORE PaddleOCR
127
+ import fitz # This import will use the patched version
128
+
129
+ # Try to import PaddleOCR with fixes
130
+ print("Attempting to import PaddleOCR...")
131
+ try:
132
+ PaddleOCR = try_paddle_import()
133
+ print("Loading PaddleOCR models...")
134
+ ocr = PaddleOCR(use_angle_cls=True, lang='en', show_log=False)
135
+ print("PaddleOCR models loaded successfully!")
136
+ except Exception as e:
137
+ print(f"Failed to load PaddleOCR: {e}")
138
+ print("Application will exit - compatibility issue not resolved")
139
+ sys.exit(1)
140
+
141
+ # Test the monkey patch
142
+ print("Testing monkey patch...")
143
+ test_doc = None
144
+ try:
145
+ # Create a simple test to verify pageCount exists
146
+ import io
147
+ pdf_content = b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\nxref\n0 4\n0000000000 65535 f \n0000000010 00000 n \n0000000053 00000 n \n0000000100 00000 n \ntrailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n179\n%%EOF"
148
+ test_doc = fitz.open(stream=pdf_content, filetype="pdf")
149
+
150
+ if hasattr(test_doc, 'pageCount'):
151
+ print(f"✓ Monkey patch successful! pageCount = {test_doc.pageCount}")
152
+ else:
153
+ print("✗ Monkey patch failed - pageCount not found")
154
+ print(f"Available attributes: {[attr for attr in dir(test_doc) if 'count' in attr.lower()]}")
155
+
156
+ test_doc.close()
157
+ except Exception as e:
158
+ print(f"Monkey patch test failed: {e}")
159
+ if test_doc:
160
+ test_doc.close()
161
+
162
+ # Rest of your app code (process_document, API functions, Gradio interface, etc.)
163
+ def process_document(file):
164
+ """Process uploaded document with PaddleOCR"""
165
+ if file is None:
166
+ return "No file uploaded", "", ""
167
+
168
+ start_time = time.time()
169
+
170
+ try:
171
+ filename = os.path.basename(file.name)
172
+ print(f"Processing: {filename}")
173
+
174
+ file_path = file.name
175
+ print(f"File path: {file_path}")
176
+
177
+ # Count pages if PDF
178
+ total_pages = 1
179
+ if filename.lower().endswith('.pdf'):
180
+ try:
181
+ print(f"Opening PDF: {file_path}")
182
+ doc = fitz.open(file_path)
183
+
184
+ # Test pageCount attribute
185
+ print(f"Document has pageCount attribute: {hasattr(doc, 'pageCount')}")
186
+ print(f"Document has page_count attribute: {hasattr(doc, 'page_count')}")
187
+
188
+ if hasattr(doc, 'pageCount'):
189
+ total_pages = doc.pageCount
190
+ print(f"Used pageCount: {total_pages}")
191
+ elif hasattr(doc, 'page_count'):
192
+ total_pages = doc.page_count
193
+ print(f"Used page_count: {total_pages}")
194
+ else:
195
+ total_pages = len(doc)
196
+ print(f"Used len(): {total_pages}")
197
+
198
+ doc.close()
199
+ except Exception as e:
200
+ print(f"PDF page counting error: {e}")
201
+ total_pages = 1
202
+
203
+ # Run OCR
204
+ print(f"Running OCR on: {file_path}")
205
+ result = ocr.ocr(file_path, cls=True)
206
+
207
+ # Extract text
208
+ extracted_text = ""
209
+ pages_processed = 0
210
+
211
+ if result:
212
+ for page_idx, page_result in enumerate(result):
213
+ if page_result:
214
+ pages_processed += 1
215
+ for line in page_result:
216
+ if len(line) >= 2 and line[1][1] > 0.5:
217
+ extracted_text += line[1][0] + "\n"
218
+
219
+ processing_time = time.time() - start_time
220
+
221
+ summary = f"""
222
+ 📄 **File**: {filename}
223
+ 📊 **Pages Processed**: {pages_processed}/{total_pages}
224
+ ⏱️ **Processing Time**: {processing_time:.2f} seconds
225
+ 📝 **Text Length**: {len(extracted_text)} characters
226
+ 🔧 **OCR Engine**: PaddleOCR
227
+ """
228
+
229
+ api_response = json.dumps({
230
+ "success": True,
231
+ "text": extracted_text,
232
+ "filename": filename,
233
+ "pages_processed": pages_processed,
234
+ "total_pages": total_pages,
235
+ "processing_time": processing_time,
236
+ "ocr_engine": "PaddleOCR"
237
+ }, indent=2)
238
+
239
+ return summary, extracted_text, api_response
240
+
241
+ except Exception as e:
242
+ error_msg = f"Error processing file: {str(e)}"
243
+ print(f"Full error: {e}")
244
+ import traceback
245
+ traceback.print_exc()
246
+ return error_msg, "", json.dumps({"success": False, "error": str(e)})
247
+
248
+ def process_api_request(api_data):
249
+ """Process API-style requests (for integration with your Vercel app)"""
250
+ try:
251
+ data = json.loads(api_data)
252
+
253
+ if 'file' not in data:
254
+ return json.dumps({"success": False, "error": "No file data provided"})
255
+
256
+ # Decode base64 file
257
+ file_data = base64.b64decode(data['file'])
258
+ filename = data.get('filename', 'unknown.pdf')
259
+
260
+ # Save to temp file
261
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(filename)[1]) as tmp_file:
262
+ tmp_file.write(file_data)
263
+ tmp_file_path = tmp_file.name
264
+
265
+ try:
266
+ # Run OCR
267
+ result = ocr.ocr(tmp_file_path, cls=True)
268
+
269
+ # Extract text
270
+ text = ""
271
+ for page_result in result:
272
+ if page_result:
273
+ for line in page_result:
274
+ if len(line) >= 2:
275
+ text += line[1][0] + "\n"
276
+
277
+ return json.dumps({
278
+ "success": True,
279
+ "text": text,
280
+ "filename": filename,
281
+ "ocr_engine": "PaddleOCR"
282
+ })
283
+
284
+ finally:
285
+ os.unlink(tmp_file_path)
286
+
287
+ except Exception as e:
288
+ return json.dumps({"success": False, "error": str(e)})
289
+
290
+ # Create Gradio interface with multiple tabs
291
+ with gr.Blocks(title="PaddleOCR Medical Document Processor") as demo:
292
+ gr.Markdown("# 🏥 PaddleOCR Medical Document Processor")
293
+ gr.Markdown("Upload medical documents (PDF/images) to extract text using PaddleOCR")
294
+
295
+ with gr.Tab("📄 File Upload"):
296
+ with gr.Row():
297
+ with gr.Column():
298
+ file_input = gr.File(
299
+ label="Upload Document (PDF, JPG, PNG)",
300
+ file_types=[".pdf", ".jpg", ".jpeg", ".png"]
301
+ )
302
+ process_btn = gr.Button("🔍 Process Document", variant="primary")
303
+
304
+ with gr.Column():
305
+ summary_output = gr.Markdown(label="📊 Processing Summary")
306
+
307
+ with gr.Row():
308
+ text_output = gr.Textbox(
309
+ label="📝 Extracted Text",
310
+ lines=15,
311
+ max_lines=20
312
+ )
313
+
314
+ process_btn.click(
315
+ fn=process_document,
316
+ inputs=[file_input],
317
+ outputs=[summary_output, text_output, gr.Textbox(visible=False)]
318
+ )
319
+
320
+ with gr.Tab("🔌 API Integration"):
321
+ gr.Markdown("### For integration with your Vercel app:")
322
+ gr.Markdown("**Endpoint**: `https://mbuck17-paddleocr-processor.hf.space/api/predict`")
323
+ gr.Markdown("**Method**: POST")
324
+ gr.Markdown("**Headers**: `Content-Type: application/json`")
325
+
326
+ with gr.Row():
327
+ with gr.Column():
328
+ gr.Markdown("**Sample Request:**")
329
+ gr.Code('''
330
+ {
331
+ "data": [
332
+ {
333
+ "file": "base64_encoded_file_data_here",
334
+ "filename": "lab_report.pdf"
335
+ }
336
+ ]
337
+ }
338
+ ''', language="json")
339
+
340
+ with gr.Column():
341
+ gr.Markdown("**Sample Response:**")
342
+ gr.Code('''
343
+ {
344
+ "data": [
345
+ {
346
+ "success": true,
347
+ "text": "Extracted text content...",
348
+ "filename": "lab_report.pdf",
349
+ "ocr_engine": "PaddleOCR"
350
+ }
351
+ ]
352
+ }
353
+ ''', language="json")
354
+
355
+ gr.Markdown("### Test API Request:")
356
+ api_input = gr.Textbox(
357
+ label="API Request (JSON)",
358
+ placeholder='{"file": "base64_encoded_file_data", "filename": "document.pdf"}',
359
+ lines=5
360
+ )
361
+ api_btn = gr.Button("🧪 Test API Request")
362
+ api_output = gr.Textbox(
363
+ label="API Response (JSON)",
364
+ lines=10
365
+ )
366
+
367
+ api_btn.click(
368
+ fn=process_api_request,
369
+ inputs=[api_input],
370
+ outputs=[api_output]
371
+ )
372
+
373
+ with gr.Tab("ℹ️ About"):
374
+ gr.Markdown("""
375
+ ### 🎯 Purpose
376
+ This service extracts text from medical documents using PaddleOCR, specifically designed for lab reports and medical forms.
377
+
378
+ ### 🔧 Integration
379
+ This Hugging Face Space can be integrated with your Vercel app as an external OCR service.
380
+
381
+ ### 📚 Supported Formats
382
+ - PDF documents (multi-page)
383
+ - JPEG/JPG images
384
+ - PNG images
385
+
386
+ ### 🚀 Features
387
+ - High accuracy OCR with PaddleOCR
388
+ - Medical document optimization
389
+ - Multi-page PDF support
390
+ - RESTful API integration
391
+ - Free hosting on Hugging Face
392
+ - SSL compatibility fixes included
393
+
394
+ ### 🔗 Integration URL
395
+ `https://mbuck17-paddleocr-processor.hf.space/api/predict`
396
+ """)
397
+
398
+ # Launch the app
399
+ if __name__ == "__main__":
400
+ demo.launch(server_name="0.0.0.0", server_port=7860)
minimal_test_paddle.py → archive/minimal_test_paddle.py RENAMED
File without changes
archive/paddle_ocr_standalone.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # paddle_ocr_standalone.py - Robust version with comprehensive error handling
3
+
4
+ import sys
5
+ import os
6
+ import json
7
+ import tempfile
8
+ import traceback
9
+
10
+ def safe_print_stderr(message):
11
+ """Safely print to stderr"""
12
+ try:
13
+ print(message, file=sys.stderr, flush=True)
14
+ except:
15
+ pass
16
+
17
+ def safe_print_json(data):
18
+ """Safely print JSON to stdout"""
19
+ try:
20
+ print(json.dumps(data), flush=True)
21
+ except Exception as e:
22
+ safe_print_stderr(f"Error printing JSON: {e}")
23
+ print('{"success": false, "error": "JSON serialization failed"}')
24
+
25
+ # Check if file path was provided
26
+ if len(sys.argv) < 2:
27
+ safe_print_json({"success": False, "error": "Usage: python paddle_ocr_standalone.py <file_path>"})
28
+ sys.exit(1)
29
+
30
+ file_path = sys.argv[1]
31
+ temp_files = []
32
+
33
+ try:
34
+ safe_print_stderr(f"=== Starting OCR processing for: {os.path.basename(file_path)} ===")
35
+
36
+ # Check if file exists and is readable
37
+ if not os.path.exists(file_path):
38
+ raise Exception(f"File does not exist: {file_path}")
39
+
40
+ if not os.access(file_path, os.R_OK):
41
+ raise Exception(f"File is not readable: {file_path}")
42
+
43
+ file_size = os.path.getsize(file_path)
44
+ safe_print_stderr(f"File size: {file_size} bytes")
45
+
46
+ # Import dependencies one by one with error handling
47
+ safe_print_stderr("Importing PyMuPDF...")
48
+ try:
49
+ import fitz
50
+ safe_print_stderr("✓ PyMuPDF imported successfully")
51
+ except Exception as e:
52
+ raise Exception(f"Failed to import PyMuPDF: {e}")
53
+
54
+ # Apply monkey patch for PyMuPDF compatibility
55
+ safe_print_stderr("Applying PyMuPDF compatibility patches...")
56
+ try:
57
+ if not hasattr(fitz.Document, 'pageCount'):
58
+ def pageCount_property(self):
59
+ return self.page_count
60
+ fitz.Document.pageCount = property(pageCount_property)
61
+ safe_print_stderr("✓ Added pageCount property")
62
+
63
+ if not hasattr(fitz.Page, 'getPixmap'):
64
+ def getPixmap(self, matrix=None, alpha=True):
65
+ return self.get_pixmap(matrix=matrix, alpha=alpha)
66
+ fitz.Page.getPixmap = getPixmap
67
+ safe_print_stderr("✓ Added getPixmap method")
68
+
69
+ if not hasattr(fitz.Page, 'getText'):
70
+ def getText(self, option="text"):
71
+ return self.get_text(option)
72
+ fitz.Page.getText = getText
73
+ safe_print_stderr("✓ Added getText method")
74
+
75
+ except Exception as e:
76
+ safe_print_stderr(f"Warning: Monkey patch failed: {e}")
77
+
78
+ # Test PDF opening
79
+ safe_print_stderr("Testing PDF opening...")
80
+ try:
81
+ test_doc = fitz.open(file_path)
82
+ page_count = len(test_doc)
83
+ safe_print_stderr(f"✓ PDF opened successfully, {page_count} pages detected")
84
+ test_doc.close()
85
+ except Exception as e:
86
+ raise Exception(f"Failed to open PDF: {e}")
87
+
88
+ # Import PaddleOCR
89
+ safe_print_stderr("Importing PaddleOCR...")
90
+ try:
91
+ from paddleocr import PaddleOCR
92
+ safe_print_stderr("✓ PaddleOCR imported successfully")
93
+ except Exception as e:
94
+ raise Exception(f"Failed to import PaddleOCR: {e}")
95
+
96
+ # Initialize PaddleOCR
97
+ safe_print_stderr("Initializing PaddleOCR...")
98
+ try:
99
+ ocr = PaddleOCR(
100
+ use_angle_cls=True,
101
+ lang='en',
102
+ show_log=False,
103
+ use_gpu=False
104
+ )
105
+ safe_print_stderr("✓ PaddleOCR initialized successfully")
106
+ except Exception as e:
107
+ raise Exception(f"Failed to initialize PaddleOCR: {e}")
108
+
109
+ def pdf_to_images(pdf_path, dpi=150):
110
+ """Convert PDF pages to images"""
111
+ try:
112
+ safe_print_stderr(f"Converting PDF to images (DPI: {dpi})...")
113
+ doc = fitz.open(pdf_path)
114
+ image_paths = []
115
+
116
+ total_pages = len(doc) # Store this before we close the document
117
+ safe_print_stderr(f"PDF has {total_pages} pages")
118
+
119
+ for page_num in range(total_pages):
120
+ try:
121
+ safe_print_stderr(f"Converting page {page_num + 1}...")
122
+ page = doc[page_num]
123
+
124
+ # Create transformation matrix
125
+ mat = fitz.Matrix(dpi/72, dpi/72)
126
+
127
+ # Render page to pixmap
128
+ if hasattr(page, 'getPixmap'):
129
+ pix = page.getPixmap(matrix=mat)
130
+ else:
131
+ pix = page.get_pixmap(matrix=mat)
132
+
133
+ # Save to temporary file
134
+ temp_img_path = f"/tmp/ocr_page_{page_num}_{os.getpid()}.png"
135
+ pix.save(temp_img_path)
136
+
137
+ # Verify file creation
138
+ if os.path.exists(temp_img_path):
139
+ file_size = os.path.getsize(temp_img_path)
140
+ safe_print_stderr(f"✓ Page {page_num + 1} converted: {temp_img_path} (size: {file_size} bytes, {pix.width}x{pix.height})")
141
+ image_paths.append(temp_img_path)
142
+ else:
143
+ safe_print_stderr(f"✗ Failed to create image: {temp_img_path}")
144
+
145
+ except Exception as page_error:
146
+ safe_print_stderr(f"✗ Error converting page {page_num + 1}: {page_error}")
147
+ continue
148
+
149
+ doc.close()
150
+ safe_print_stderr(f"✓ Successfully converted {len(image_paths)}/{total_pages} pages")
151
+ return image_paths
152
+
153
+ except Exception as e:
154
+ safe_print_stderr(f"✗ PDF conversion failed: {e}")
155
+ traceback.print_exc(file=sys.stderr)
156
+ return []
157
+
158
+ def cleanup_temp_files(file_paths):
159
+ """Clean up temporary files"""
160
+ for file_path in file_paths:
161
+ try:
162
+ if os.path.exists(file_path):
163
+ os.unlink(file_path)
164
+ safe_print_stderr(f"✓ Cleaned up: {file_path}")
165
+ except Exception as e:
166
+ safe_print_stderr(f"Warning: Could not clean up {file_path}: {e}")
167
+
168
+ # Determine file type and convert if needed
169
+ is_pdf = file_path.lower().endswith('.pdf')
170
+
171
+ if is_pdf:
172
+ safe_print_stderr("Processing PDF file...")
173
+ image_paths = pdf_to_images(file_path)
174
+ temp_files = image_paths
175
+
176
+ if not image_paths:
177
+ raise Exception("PDF conversion produced no images")
178
+
179
+ total_pages = len(image_paths)
180
+ safe_print_stderr(f"Will process {total_pages} images")
181
+ else:
182
+ safe_print_stderr("Processing image file...")
183
+ image_paths = [file_path]
184
+ total_pages = 1
185
+
186
+ safe_print_stderr(f"TOTAL_PAGES:{total_pages}")
187
+
188
+ # Process each image with OCR
189
+ safe_print_stderr("Starting OCR processing...")
190
+ extracted_text = ""
191
+ pages_processed = 0
192
+
193
+ for i, img_path in enumerate(image_paths):
194
+ try:
195
+ current_page = i + 1
196
+ safe_print_stderr(f"CURRENT_PAGE:{current_page}")
197
+ safe_print_stderr(f"Processing image: {img_path}")
198
+
199
+ # Verify image exists and is readable
200
+ if not os.path.exists(img_path):
201
+ safe_print_stderr(f"✗ Image file does not exist: {img_path}")
202
+ continue
203
+
204
+ img_size = os.path.getsize(img_path)
205
+ safe_print_stderr(f"Image size: {img_size} bytes")
206
+
207
+ # Run OCR on the image
208
+ safe_print_stderr(f"Running OCR on page {current_page}...")
209
+ result = ocr.ocr(img_path, cls=True)
210
+
211
+ safe_print_stderr(f"OCR result type: {type(result)}")
212
+ if result:
213
+ safe_print_stderr(f"OCR result length: {len(result)}")
214
+ if result[0]:
215
+ safe_print_stderr(f"Page {current_page} has {len(result[0])} text regions detected")
216
+ else:
217
+ safe_print_stderr(f"Page {current_page}: OCR returned empty result")
218
+ else:
219
+ safe_print_stderr(f"Page {current_page}: OCR returned None")
220
+ continue
221
+
222
+ if result and result[0]:
223
+ pages_processed += 1
224
+ page_text = ""
225
+
226
+ for line_idx, line in enumerate(result[0]):
227
+ try:
228
+ if len(line) >= 2:
229
+ text_content = line[1][0] if isinstance(line[1], (list, tuple)) else str(line[1])
230
+ confidence = line[1][1] if isinstance(line[1], (list, tuple)) and len(line[1]) > 1 else 1.0
231
+
232
+ safe_print_stderr(f"Line {line_idx}: '{text_content}' (confidence: {confidence:.2f})")
233
+
234
+ if confidence > 0.3:
235
+ page_text += text_content + "\n"
236
+ except Exception as line_error:
237
+ safe_print_stderr(f"Error processing line {line_idx}: {line_error}")
238
+ continue
239
+
240
+ if page_text.strip():
241
+ extracted_text += f"\n--- Page {current_page} ---\n"
242
+ extracted_text += page_text
243
+ safe_print_stderr(f"✓ Page {current_page}: Added {len(page_text)} characters of text")
244
+ else:
245
+ safe_print_stderr(f"Page {current_page}: No text above confidence threshold")
246
+
247
+ else:
248
+ safe_print_stderr(f"Page {current_page}: No OCR results")
249
+
250
+ except Exception as page_error:
251
+ safe_print_stderr(f"✗ Error processing page {current_page}: {page_error}")
252
+ traceback.print_exc(file=sys.stderr)
253
+ continue
254
+
255
+ # Clean up temporary files
256
+ if temp_files:
257
+ safe_print_stderr("Cleaning up temporary files...")
258
+ cleanup_temp_files(temp_files)
259
+
260
+ # Prepare final result
261
+ result_data = {
262
+ "success": True,
263
+ "text": extracted_text,
264
+ "total_pages": total_pages,
265
+ "pages_processed": pages_processed,
266
+ "method": "pdf_to_images" if is_pdf else "direct_image"
267
+ }
268
+
269
+ safe_print_stderr(f"=== OCR Complete: {pages_processed}/{total_pages} pages processed ===")
270
+ safe_print_stderr(f"Total text length: {len(extracted_text)} characters")
271
+
272
+ # Output final JSON result
273
+ safe_print_json(result_data)
274
+
275
+ except Exception as e:
276
+ # Clean up on error
277
+ if temp_files:
278
+ try:
279
+ cleanup_temp_files(temp_files)
280
+ except:
281
+ pass
282
+
283
+ safe_print_stderr(f"=== FATAL ERROR ===")
284
+ safe_print_stderr(f"Error: {e}")
285
+ traceback.print_exc(file=sys.stderr)
286
+
287
+ error_data = {
288
+ "success": False,
289
+ "error": str(e)
290
+ }
291
+ safe_print_json(error_data)
292
+ sys.exit(1)
enhanced_paddle_test.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # enhanced_paddle_test.py - Trying to match your local implementation quality
3
+
4
+ import sys
5
+ import os
6
+ import json
7
+ import fitz
8
+ from paddleocr import PaddleOCR
9
+
10
+ def test_multiple_approaches():
11
+ if len(sys.argv) < 2:
12
+ print(json.dumps({"error": "No file path provided"}))
13
+ return
14
+
15
+ file_path = sys.argv[1]
16
+
17
+ try:
18
+ print(f"Testing multiple OCR approaches on: {file_path}", file=sys.stderr)
19
+
20
+ # Test different DPI settings and OCR configurations
21
+ approaches = [
22
+ {"name": "High DPI (300)", "dpi": 300, "det_limit_side_len": 1960},
23
+ {"name": "Medium DPI (200)", "dpi": 200, "det_limit_side_len": 1280},
24
+ {"name": "Low DPI (150)", "dpi": 150, "det_limit_side_len": 960},
25
+ {"name": "Your Local Settings", "dpi": 200, "det_limit_side_len": None}
26
+ ]
27
+
28
+ doc = fitz.open(file_path)
29
+ print(f"PDF has {len(doc)} pages", file=sys.stderr)
30
+
31
+ all_results = {}
32
+
33
+ for approach in approaches:
34
+ print(f"\n=== Testing {approach['name']} ===", file=sys.stderr)
35
+
36
+ # Convert first page with specific DPI
37
+ page = doc[0]
38
+ mat = fitz.Matrix(approach['dpi']/72, approach['dpi']/72)
39
+ pix = page.get_pixmap(matrix=mat)
40
+
41
+ temp_img = f"/tmp/test_{approach['dpi']}.png"
42
+ pix.save(temp_img)
43
+
44
+ if os.path.exists(temp_img):
45
+ img_size = os.path.getsize(temp_img)
46
+ print(f"Image: {temp_img} (size: {img_size} bytes, {pix.width}x{pix.height})", file=sys.stderr)
47
+
48
+ # Initialize OCR with specific settings
49
+ ocr_kwargs = {
50
+ 'use_angle_cls': True,
51
+ 'lang': 'en',
52
+ 'show_log': False,
53
+ 'use_gpu': False
54
+ }
55
+
56
+ if approach['det_limit_side_len']:
57
+ ocr_kwargs['det_limit_side_len'] = approach['det_limit_side_len']
58
+
59
+ print(f"OCR settings: {ocr_kwargs}", file=sys.stderr)
60
+ ocr = PaddleOCR(**ocr_kwargs)
61
+
62
+ # Run OCR
63
+ result = ocr.ocr(temp_img, cls=True)
64
+
65
+ if result and result[0]:
66
+ detections = len(result[0])
67
+ print(f"Detections: {detections}", file=sys.stderr)
68
+
69
+ # Extract all text
70
+ text_parts = []
71
+ for i, detection in enumerate(result[0]):
72
+ if len(detection) >= 2:
73
+ text = str(detection[1][0]) if isinstance(detection[1], (list, tuple)) else str(detection[1])
74
+ conf = float(detection[1][1]) if isinstance(detection[1], (list, tuple)) and len(detection[1]) > 1 else 1.0
75
+
76
+ if conf > 0.3: # Lower threshold for testing
77
+ text_parts.append(text)
78
+ if i < 10: # Show first 10 detections
79
+ print(f" {i}: '{text}' ({conf:.2f})", file=sys.stderr)
80
+
81
+ all_results[approach['name']] = {
82
+ 'detections': detections,
83
+ 'text': '\n'.join(text_parts),
84
+ 'settings': ocr_kwargs
85
+ }
86
+ else:
87
+ print("No detections", file=sys.stderr)
88
+ all_results[approach['name']] = {'detections': 0, 'text': '', 'settings': ocr_kwargs}
89
+
90
+ # Clean up
91
+ if os.path.exists(temp_img):
92
+ os.unlink(temp_img)
93
+ else:
94
+ print(f"Failed to create image: {temp_img}", file=sys.stderr)
95
+
96
+ doc.close()
97
+
98
+ # Find best result
99
+ best_approach = max(all_results.keys(), key=lambda k: all_results[k]['detections'])
100
+
101
+ print(f"\nBest approach: {best_approach} with {all_results[best_approach]['detections']} detections", file=sys.stderr)
102
+
103
+ # Return the best result
104
+ print(json.dumps({
105
+ "success": True,
106
+ "best_approach": best_approach,
107
+ "all_results": all_results,
108
+ "text": all_results[best_approach]['text'],
109
+ "detections": all_results[best_approach]['detections']
110
+ }))
111
+
112
+ except Exception as e:
113
+ print(f"Error: {e}", file=sys.stderr)
114
+ import traceback
115
+ traceback.print_exc(file=sys.stderr)
116
+ print(json.dumps({"success": False, "error": str(e)}))
117
+
118
+ if __name__ == "__main__":
119
+ test_multiple_approaches()