test handler
Browse files- handler.py +49 -0
- requirements.txt +2 -0
handler.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List
|
| 2 |
+
import base64
|
| 3 |
+
import io
|
| 4 |
+
import tempfile
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from pdf2image import convert_from_path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def process_image(pdfdata):
|
| 10 |
+
prompt = "detect the accident diagram"
|
| 11 |
+
# PDF input -> convert to images -> find crash diagram
|
| 12 |
+
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
| 13 |
+
temp_file.write(pdfdata)
|
| 14 |
+
temp_file.flush()
|
| 15 |
+
print("temporary name:", temp_file.name)
|
| 16 |
+
images = convert_from_path(temp_file.name)
|
| 17 |
+
|
| 18 |
+
crash_img = None
|
| 19 |
+
for img in images:
|
| 20 |
+
crash_img = img.crop((0,0, 200, 200))
|
| 21 |
+
break
|
| 22 |
+
|
| 23 |
+
if crash_img:
|
| 24 |
+
img_io = io.BytesIO()
|
| 25 |
+
crash_img.save(img_io, "PNG")
|
| 26 |
+
img_io.seek(0)
|
| 27 |
+
# Return the cropped image as base64
|
| 28 |
+
return {"data": base64.b64encode(img_io.read()).decode("utf-8"), "mime_type": "image/png"}
|
| 29 |
+
else:
|
| 30 |
+
return {"error": "No crash diagram detected"}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class EndpointHandler:
|
| 34 |
+
def __init__(self, path: str = ""):
|
| 35 |
+
"""Initialize the endpoint handler.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
path: Path to the model artifacts
|
| 39 |
+
"""
|
| 40 |
+
print("initialized")
|
| 41 |
+
pass
|
| 42 |
+
|
| 43 |
+
def __call__(self, data: Any) -> List[List[Dict[str, str]]]:
|
| 44 |
+
pdfdata = data.pop("filedata", data)
|
| 45 |
+
if isinstance(pdfdata, str):
|
| 46 |
+
print("decoding pdfdata")
|
| 47 |
+
pdfdata = base64.b64decode(pdfdata)
|
| 48 |
+
|
| 49 |
+
return process_image(pdfdata)
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pdf2image==1.17.0
|
| 2 |
+
pillow==10.4.0
|