Update handler.py
Browse files- handler.py +27 -15
handler.py
CHANGED
|
@@ -6,6 +6,9 @@ from io import BytesIO
|
|
| 6 |
from PIL import Image
|
| 7 |
import os
|
| 8 |
import tempfile
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
class EndpointHandler:
|
| 11 |
def __init__(self, model_dir = 'deepseek-ai/DeepSeek-OCR'):
|
|
@@ -79,6 +82,7 @@ class EndpointHandler:
|
|
| 79 |
print(f"Image saved to: {image_path}")
|
| 80 |
|
| 81 |
# Verify the image can be opened
|
|
|
|
| 82 |
try:
|
| 83 |
test_image = Image.open(image_path)
|
| 84 |
if test_image.mode != 'RGB':
|
|
@@ -87,21 +91,29 @@ class EndpointHandler:
|
|
| 87 |
print(f"Image verified: {test_image.size}, mode: {test_image.mode}")
|
| 88 |
except Exception as img_error:
|
| 89 |
return {"error": f"Invalid image: {str(img_error)}"}
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
except Exception as e:
|
| 107 |
print(f"Error processing image: {e}")
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
import os
|
| 8 |
import tempfile
|
| 9 |
+
import sys
|
| 10 |
+
from io import StringIO
|
| 11 |
+
from contextlib import redirect_stdout
|
| 12 |
|
| 13 |
class EndpointHandler:
|
| 14 |
def __init__(self, model_dir = 'deepseek-ai/DeepSeek-OCR'):
|
|
|
|
| 82 |
print(f"Image saved to: {image_path}")
|
| 83 |
|
| 84 |
# Verify the image can be opened
|
| 85 |
+
output_file = os.path.join(temp_dir, "output.md")
|
| 86 |
try:
|
| 87 |
test_image = Image.open(image_path)
|
| 88 |
if test_image.mode != 'RGB':
|
|
|
|
| 91 |
print(f"Image verified: {test_image.size}, mode: {test_image.mode}")
|
| 92 |
except Exception as img_error:
|
| 93 |
return {"error": f"Invalid image: {str(img_error)}"}
|
| 94 |
+
|
| 95 |
+
output_buffer = StringIO()
|
| 96 |
+
|
| 97 |
+
with redirect_stdout(output_buffer):
|
| 98 |
+
|
| 99 |
+
# Run OCR inference
|
| 100 |
+
result = self.model.infer(
|
| 101 |
+
self.tokenizer,
|
| 102 |
+
prompt=prompt,
|
| 103 |
+
image_file=image_path, # Pass the PIL Image object directly
|
| 104 |
+
output_path=output_file,
|
| 105 |
+
base_size=1024,
|
| 106 |
+
image_size=640,
|
| 107 |
+
crop_mode=True,
|
| 108 |
+
save_results=True
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
captured_output = output_buffer.getvalue()
|
| 112 |
+
|
| 113 |
+
print(f"Captured output length: {len(captured_output)}")
|
| 114 |
+
print(f"First 500 chars of captured output: {captured_output[:500]}")
|
| 115 |
+
|
| 116 |
+
return captured_output
|
| 117 |
|
| 118 |
except Exception as e:
|
| 119 |
print(f"Error processing image: {e}")
|