server OCR: accept any file extension, detect format from bytes

- Removed extension whitelist — no more 'unsupported format' errors
- Falls back to .jpg temp file for unknown/no extension
- PIL detects actual image format from file bytes (handles DNG as TIFF)
- Android browsers often strip DNG extensions when picking from gallery
- Tested: works with .dng, .jpg, no extension, and .bogus
This commit is contained in:
2026-05-21 15:05:39 -04:00
parent 28f1a33a2d
commit 09d83da4e2
+5 -6
View File
@@ -2627,16 +2627,15 @@ async def ocr_sticker(file: UploadFile = File(...)):
Accepts an image upload, runs Tesseract OCR, and looks for a pattern like
'12345-678901'. Returns the extracted machine_id or an error.
"""
# Validate file extension
ext = file.filename.rsplit(".", 1)[-1].lower() if "." in (file.filename or "") else ""
if ext not in {"png", "jpg", "jpeg", "webp", "bmp", "dng"}:
raise HTTPException(status_code=400, detail=f"Unsupported image format: .{ext}")
# Read file contents first (validate size before saving)
contents = await file.read()
if len(contents) > 20 * 1024 * 1024: # 20MB max
raise HTTPException(status_code=400, detail="Image too large (max 20MB)")
# Save temp file for OCR
# Save temp file for OCR — try original extension, fallback to jpg
ext = file.filename.rsplit(".", 1)[-1].lower() if "." in (file.filename or "") else "jpg"
if ext not in {"png", "jpg", "jpeg", "webp", "bmp", "dng", "tiff", "tif"}:
ext = "jpg" # PIL detects format from bytes regardless of extension
temp_dir = Path(UPLOADS_DIR / "ocr")
temp_dir.mkdir(parents=True, exist_ok=True)
temp_path = temp_dir / f"{uuid.uuid4().hex}.{ext or 'jpg'}"