Spaces:
Paused
Paused
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,35 +1,46 @@
|
|
|
|
|
| 1 |
from fastapi import FastAPI, Query
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
import cloudinary
|
| 4 |
import cloudinary.uploader
|
| 5 |
from cloudinary.utils import cloudinary_url
|
| 6 |
-
from cloudinary import CloudinaryImage
|
| 7 |
-
import uvicorn
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
-
# Cloudinary configuration
|
| 12 |
cloudinary.config(
|
| 13 |
cloud_name="dob6buqxd",
|
| 14 |
api_key="397945971979515",
|
| 15 |
-
api_secret="nRMIOSr10xiLo443LLMNDxJBB-Q"
|
|
|
|
| 16 |
)
|
| 17 |
|
| 18 |
-
#
|
| 19 |
@app.get("/compress_image")
|
| 20 |
-
async def compress_image(image_url: str):
|
| 21 |
try:
|
| 22 |
-
# Upload
|
| 23 |
-
upload_result = cloudinary.uploader.upload(image_url
|
| 24 |
-
# Apply Cloudinary transformations to compress the image
|
| 25 |
-
optimize_url = cloudinary_url("compress", fetch_format="auto", quality="auto")
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
except Exception as e:
|
| 31 |
-
|
|
|
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
if __name__ == "__main__":
|
| 35 |
-
uvicorn
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
from fastapi import FastAPI, Query
|
| 3 |
from fastapi.responses import JSONResponse
|
| 4 |
import cloudinary
|
| 5 |
import cloudinary.uploader
|
| 6 |
from cloudinary.utils import cloudinary_url
|
|
|
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
+
# Cloudinary configuration
|
| 11 |
cloudinary.config(
|
| 12 |
cloud_name="dob6buqxd",
|
| 13 |
api_key="397945971979515",
|
| 14 |
+
api_secret="nRMIOSr10xiLo443LLMNDxJBB-Q",
|
| 15 |
+
secure=True
|
| 16 |
)
|
| 17 |
|
| 18 |
+
# Image compression endpoint
|
| 19 |
@app.get("/compress_image")
|
| 20 |
+
async def compress_image(image_url: str = Query(..., description="URL of the image to compress")):
|
| 21 |
try:
|
| 22 |
+
# Step 1: Upload the image from the provided URL to Cloudinary
|
| 23 |
+
upload_result = cloudinary.uploader.upload(image_url)
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
# Step 2: Apply transformation to optimize the image
|
| 26 |
+
compressed_url, options = cloudinary_url(
|
| 27 |
+
upload_result["public_id"],
|
| 28 |
+
fetch_format="auto",
|
| 29 |
+
quality="auto"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Return the compressed image URL
|
| 33 |
+
return JSONResponse(content={"compressed_image_url": compressed_url})
|
| 34 |
|
| 35 |
except Exception as e:
|
| 36 |
+
# Handle any error and return a response
|
| 37 |
+
return JSONResponse(content={"error": str(e)}, status_code=500)
|
| 38 |
|
| 39 |
+
# Root endpoint
|
| 40 |
+
@app.get("/")
|
| 41 |
+
def root():
|
| 42 |
+
return "Welcome to the Image Compression API"
|
| 43 |
|
| 44 |
if __name__ == "__main__":
|
| 45 |
+
import uvicorn
|
| 46 |
+
uvicorn.run("main:app", host="0.0.0.0", port=7861)
|