Spaces:
Sleeping
Sleeping
| """ | |
| 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() | |
| 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)}") | |
| 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' | |
| } | |
| ) | |