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:
@@ -2627,16 +2627,15 @@ async def ocr_sticker(file: UploadFile = File(...)):
|
|||||||
Accepts an image upload, runs Tesseract OCR, and looks for a pattern like
|
Accepts an image upload, runs Tesseract OCR, and looks for a pattern like
|
||||||
'12345-678901'. Returns the extracted machine_id or an error.
|
'12345-678901'. Returns the extracted machine_id or an error.
|
||||||
"""
|
"""
|
||||||
# Validate file extension
|
# Read file contents first (validate size before saving)
|
||||||
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}")
|
|
||||||
|
|
||||||
contents = await file.read()
|
contents = await file.read()
|
||||||
if len(contents) > 20 * 1024 * 1024: # 20MB max
|
if len(contents) > 20 * 1024 * 1024: # 20MB max
|
||||||
raise HTTPException(status_code=400, detail="Image too large (max 20MB)")
|
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 = Path(UPLOADS_DIR / "ocr")
|
||||||
temp_dir.mkdir(parents=True, exist_ok=True)
|
temp_dir.mkdir(parents=True, exist_ok=True)
|
||||||
temp_path = temp_dir / f"{uuid.uuid4().hex}.{ext or 'jpg'}"
|
temp_path = temp_dir / f"{uuid.uuid4().hex}.{ext or 'jpg'}"
|
||||||
|
|||||||
Reference in New Issue
Block a user