MCPcopy Create free account
hub / github.com/TextGeneratorio/text-generator.io / upload_image

Function upload_image

main.py:1310–1366  ·  view source on GitHub ↗

Upload image with WebP conversion and upload to S3

(request: Request, file: UploadFile = File(...))

Source from the content-addressed store, hash-verified

1308
1309@app.post("/api/upload-image")
1310async def upload_image(request: Request, file: UploadFile = File(...)):
1311 """Upload image with WebP conversion and upload to S3"""
1312 try:
1313 # Check if user is authenticated
1314 if USE_POSTGRES:
1315 from questions.auth import get_current_user
1316
1317 current_user = get_current_user(request, next(get_db()))
1318 if not current_user:
1319 raise HTTPException(status_code=401, detail="Authentication required")
1320
1321 # Validate file type
1322 if not file.content_type or not file.content_type.startswith("image/"):
1323 raise HTTPException(status_code=400, detail="File must be an image")
1324
1325 # Read image data
1326 image_data = await file.read()
1327
1328 # Convert to WebP with quality 85
1329 image = Image.open(io.BytesIO(image_data))
1330
1331 # Convert to RGB if necessary (for WebP compatibility)
1332 if image.mode in ("RGBA", "LA", "P"):
1333 image = image.convert("RGB")
1334
1335 # Create WebP image
1336 webp_buffer = io.BytesIO()
1337 image.save(webp_buffer, format="WEBP", quality=85, optimize=True)
1338 webp_data = webp_buffer.getvalue()
1339
1340 # Generate filename
1341 import uuid
1342
1343 filename = f"uploaded_{uuid.uuid4().hex}.webp"
1344
1345 # Upload to S3 (assuming AWS credentials are configured)
1346 s3_client = boto3.client("s3")
1347 bucket_name = "textgeneratorstatic.netwrck.com"
1348
1349 try:
1350 s3_client.put_object(
1351 Bucket=bucket_name, Key=filename, Body=webp_data, ContentType="image/webp", ACL="public-read"
1352 )
1353
1354 # Return the URL
1355 image_url = f"https://{bucket_name}/{filename}"
1356 return JSONResponse({"success": True, "url": image_url, "filename": filename})
1357
1358 except Exception as e:
1359 logger.error(f"Error uploading to S3: {e}")
1360 raise HTTPException(status_code=500, detail="Failed to upload image")
1361
1362 except HTTPException:
1363 raise
1364 except Exception as e:
1365 logger.error(f"Error processing image upload: {e}")
1366 raise HTTPException(status_code=500, detail="Failed to process image")
1367

Callers

nothing calls this directly

Calls 5

get_current_userFunction · 0.90
get_dbFunction · 0.90
nextFunction · 0.50
convertMethod · 0.45
saveMethod · 0.45

Tested by

no test coverage detected