Akane710 commited on
Commit
5b4e72b
·
verified ·
1 Parent(s): 584639f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +25 -14
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 (already set in your existing code)
12
  cloudinary.config(
13
  cloud_name="dob6buqxd",
14
  api_key="397945971979515",
15
- api_secret="nRMIOSr10xiLo443LLMNDxJBB-Q"
 
16
  )
17
 
18
- # New route for image compression
19
  @app.get("/compress_image")
20
- async def compress_image(image_url: str):
21
  try:
22
- # Upload an image
23
- upload_result = cloudinary.uploader.upload(image_url,public_id="compress")
24
- # Apply Cloudinary transformations to compress the image
25
- optimize_url = cloudinary_url("compress", fetch_format="auto", quality="auto")
26
 
27
- # Return the secure Cloudinary URL of the compressed image
28
- return JSONResponse(content={'compressed_image_url': optimize_url})
 
 
 
 
 
 
 
29
 
30
  except Exception as e:
31
- return JSONResponse(content={'error': 'Error compressing image: ' + str(e)}, status_code=500)
 
32
 
 
 
 
 
33
 
34
  if __name__ == "__main__":
35
- uvicorn.run("main:app", host="0.0.0.0", port=7860, workers=8, timeout_keep_alive=60000)
 
 
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)