TEST-FRANKO / api /product_routes.py
Franko Fišter
Small fixes
56cdc39
from fastapi import APIRouter, File, UploadFile, HTTPException, Form
from utils.image_processing import read_image_file, process_product_image
from product_detector.detector import ObjectDetector
from config.settings import MODEL_ONNX_PATH, CLASS_NAMES, INPUT_SIZE
from utils.image_processing import process_and_store_product_image
# Initialize the detector
detector = ObjectDetector(
model_path=MODEL_ONNX_PATH,
class_names=CLASS_NAMES,
input_size=INPUT_SIZE
)
router = APIRouter(prefix="/products", tags=["Product Processing"])
@router.options("/detect-product")
async def detect_options():
return {"Allow": "POST"}
@router.post("/detect-product")
async def detect_objects(file: UploadFile = File(...)):
try:
image = await read_image_file(file)
detections = detector.predict(image)
return {
"status": "success",
"detections": detections,
"count": len(detections)
}
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, f"Processing error: {str(e)}")
@router.post("/process-image")
async def process_image(
file: UploadFile = File(...),
remove_bg: bool = Form(True),
upscale: bool = Form(True),
scale_factor: int = Form(2),
process_order: str = Form("remove_first")
):
"""
Process product images by removing background and/or upscaling
"""
try:
# Validate inputs
if scale_factor not in [2, 3, 4]:
raise HTTPException(400, "Scale factor must be 2, 3, or 4")
if process_order not in ["remove_first", "upscale_first"]:
raise HTTPException(400, "Process order must be 'remove_first' or 'upscale_first'")
if not file.content_type.startswith("image/"):
raise HTTPException(400, "File must be an image")
# Use the combined processing and storage function
result = await process_and_store_product_image(
file,
remove_bg=remove_bg,
upscale=upscale,
scale_factor=scale_factor,
process_order=process_order
)
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, f"Image processing error: {str(e)}")
@router.post("/process-product-image")
async def process_product_image_endpoint(
file: UploadFile = File(...),
remove_bg: bool = Form(True),
upscale: bool = Form(True),
scale_factor: int = Form(2),
process_order: str = Form("remove_first"),
product_id: str = Form(None)
):
"""
Process a product image and update the product record
"""
try:
# Use the combined processing, storage and database function
result = await process_and_store_product_image(
file,
remove_bg=remove_bg,
upscale=upscale,
scale_factor=scale_factor,
process_order=process_order,
product_id=product_id
)
return result
except Exception as e:
raise HTTPException(500, f"Image processing error: {str(e)}")