Spaces:
Sleeping
Sleeping
File size: 1,791 Bytes
91d209c 66e744c 91d209c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
"""
Image Service API endpoints
Handles image compression, storage, and serving
"""
from fastapi import APIRouter, HTTPException, Response, UploadFile, File
from fastapi.responses import JSONResponse
from utils.storage import temp_images
from utils.image_processor import compress_and_store_image
import os
router = APIRouter()
@router.post("/upload-image")
async def upload_image(file: UploadFile = File(...)):
"""
Upload and host an image, returns public URL
"""
try:
# Read image bytes
image_bytes = await file.read()
# Convert to data URL for processing
import base64
encoded = base64.b64encode(image_bytes).decode('utf-8')
data_url = f"data:{file.content_type};base64,{encoded}"
# Get public URL from env or use default
public_url = os.getenv('VITE_API_BASE_URL', 'http://localhost:4000')
# Compress and store, get hosted URL
hosted_url = await compress_and_store_image(data_url, public_url)
return JSONResponse(content={
"url": hosted_url,
"filename": file.filename
})
except Exception as e:
raise HTTPException(status_code=500, detail=f"Image upload failed: {str(e)}")
@router.get("/images/{image_id}")
async def serve_image(image_id: str):
"""
Serve temporarily stored images
Images are compressed and cached for 1 hour
"""
if image_id not in temp_images:
raise HTTPException(status_code=404, detail="Image not found")
image_data = temp_images[image_id]
return Response(
content=image_data['buffer'],
media_type=image_data['content_type'],
headers={
'Cache-Control': 'public, max-age=3600'
}
)
|