JerryCoder commited on
Commit
8254d65
·
verified ·
1 Parent(s): 086e553

© 2025 by JerryCoder

Browse files
Files changed (1) hide show
  1. app.py +54 -46
app.py CHANGED
@@ -1,80 +1,95 @@
1
  import requests
2
  import json
 
3
  from fastapi import FastAPI, UploadFile, File, Query
4
- from fastapi.responses import JSONResponse
5
  from fastapi.middleware.cors import CORSMiddleware
6
  from rembg import remove
7
  import uvicorn
8
 
9
  # --------------------------
10
- # Custom Pretty JSON Response
 
 
 
 
 
11
  # --------------------------
12
  class PrettyJSONResponse(JSONResponse):
13
  def render(self, content) -> bytes:
14
  return json.dumps(content, indent=4, ensure_ascii=False).encode("utf-8")
15
 
16
- app = FastAPI(title="AI ClearCut - Background Remover | JerryCoder", default_response_class=PrettyJSONResponse)
 
 
 
17
 
18
  # --------------------------
19
- # Enable CORS
20
  # --------------------------
21
  app.add_middleware(
22
  CORSMiddleware,
23
- allow_origins=["*"], # Allow all origins
24
  allow_credentials=True,
25
- allow_methods=["*"], # Allow all HTTP methods
26
- allow_headers=["*"], # Allow all headers
27
  )
28
 
29
  # --------------------------
30
- # Root endpoint
31
  # --------------------------
32
  @app.get("/")
33
  async def root():
34
  return {
35
- "message": "AI ClearCut Background Remover API is running! © 2025 by JerryCoder",
36
  "endpoints": {
37
- "POST /upload": "Upload an image file for background removal",
38
- "GET /json?url=": "Provide an image URL for background removal"
 
39
  },
40
- "creator": "Jerrycoder",
41
- "telegram": "Oggy_workshop"
42
  }
43
 
44
  # --------------------------
45
- # Helper: process image bytes
 
 
 
 
 
 
 
 
 
 
 
46
  # --------------------------
47
  def process_image(img_bytes: bytes):
48
  try:
49
- # Fast background removal
50
  output_bytes = remove(img_bytes)
51
 
52
- # Upload to Uguu
53
- files = {
54
- "files[]": ("output.png", output_bytes, "image/png")
55
- }
56
 
57
- r = requests.post("https://uguu.se/upload", files=files, timeout=20)
58
- r.raise_for_status()
59
- data = r.json()
60
 
61
- # Uguu returns a list
62
- if isinstance(data, list) and len(data) > 0:
63
- return {
64
- "status": "success",
65
- "url": data[0].get("url"),
66
- "name": data[0].get("name"),
67
- "size": data[0].get("size"),
68
- "creator": "Jerrycoder",
69
- "telegram": "Oggy_workshop"
70
- }
71
 
72
- return {"status": "error", "message": "Upload failed"}
 
 
 
 
 
73
 
74
  except Exception as e:
75
  return {"status": "error", "message": str(e)}
 
76
  # --------------------------
77
- # POST: Upload file
78
  # --------------------------
79
  @app.post("/upload")
80
  async def upload_file(file: UploadFile = File(...)):
@@ -82,26 +97,19 @@ async def upload_file(file: UploadFile = File(...)):
82
  return process_image(img_bytes)
83
 
84
  # --------------------------
85
- # GET: From image URL
86
  # --------------------------
87
  @app.get("/json")
88
- async def from_url(url: str = Query(..., description="Image URL")):
89
  try:
90
- headers = {
91
- "User-Agent": (
92
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
93
- "AppleWebKit/537.36 (KHTML, like Gecko) "
94
- "Chrome/115.0 Safari/537.36"
95
- )
96
- }
97
- resp = requests.get(url, headers=headers, timeout=15)
98
  resp.raise_for_status()
99
  return process_image(resp.content)
100
  except Exception as e:
101
  return {"status": "error", "message": str(e)}
102
 
103
  # --------------------------
104
- # HF Entry point
105
  # --------------------------
106
  if __name__ == "__main__":
107
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
  import requests
2
  import json
3
+ import uuid
4
  from fastapi import FastAPI, UploadFile, File, Query
5
+ from fastapi.responses import JSONResponse, Response
6
  from fastapi.middleware.cors import CORSMiddleware
7
  from rembg import remove
8
  import uvicorn
9
 
10
  # --------------------------
11
+ # Temp Memory Storage
12
+ # --------------------------
13
+ TEMP_FILES = {}
14
+
15
+ # --------------------------
16
+ # Pretty JSON Response
17
  # --------------------------
18
  class PrettyJSONResponse(JSONResponse):
19
  def render(self, content) -> bytes:
20
  return json.dumps(content, indent=4, ensure_ascii=False).encode("utf-8")
21
 
22
+ app = FastAPI(
23
+ title="AI ClearCut - HF UltraFast BG Remover",
24
+ default_response_class=PrettyJSONResponse
25
+ )
26
 
27
  # --------------------------
28
+ # CORS
29
  # --------------------------
30
  app.add_middleware(
31
  CORSMiddleware,
32
+ allow_origins=["*"],
33
  allow_credentials=True,
34
+ allow_methods=["*"],
35
+ allow_headers=["*"],
36
  )
37
 
38
  # --------------------------
39
+ # Root
40
  # --------------------------
41
  @app.get("/")
42
  async def root():
43
  return {
44
+ "message": "HF UltraFast Background Remover Running 🚀",
45
  "endpoints": {
46
+ "POST /upload": "Upload image",
47
+ "GET /json?url=": "Image from URL",
48
+ "GET /file/{id}": "Get processed image"
49
  },
50
+ "creator": "Jerrycoder"
 
51
  }
52
 
53
  # --------------------------
54
+ # Serve temp file
55
+ # --------------------------
56
+ @app.get("/file/{file_id}")
57
+ async def get_file(file_id: str):
58
+ file_data = TEMP_FILES.get(file_id)
59
+ if not file_data:
60
+ return {"status": "error", "message": "File expired"}
61
+
62
+ return Response(content=file_data, media_type="image/png")
63
+
64
+ # --------------------------
65
+ # Process image
66
  # --------------------------
67
  def process_image(img_bytes: bytes):
68
  try:
69
+ # Remove background
70
  output_bytes = remove(img_bytes)
71
 
72
+ # Generate unique ID
73
+ file_id = str(uuid.uuid4())
 
 
74
 
75
+ # Store temporarily
76
+ TEMP_FILES[file_id] = output_bytes
 
77
 
78
+ # Build URL
79
+ file_url = f"/file/{file_id}"
 
 
 
 
 
 
 
 
80
 
81
+ return {
82
+ "status": "success",
83
+ "url": file_url,
84
+ "full_url": file_url,
85
+ "creator": "Jerrycoder"
86
+ }
87
 
88
  except Exception as e:
89
  return {"status": "error", "message": str(e)}
90
+
91
  # --------------------------
92
+ # POST upload
93
  # --------------------------
94
  @app.post("/upload")
95
  async def upload_file(file: UploadFile = File(...)):
 
97
  return process_image(img_bytes)
98
 
99
  # --------------------------
100
+ # GET from URL
101
  # --------------------------
102
  @app.get("/json")
103
+ async def from_url(url: str = Query(...)):
104
  try:
105
+ resp = requests.get(url, timeout=10)
 
 
 
 
 
 
 
106
  resp.raise_for_status()
107
  return process_image(resp.content)
108
  except Exception as e:
109
  return {"status": "error", "message": str(e)}
110
 
111
  # --------------------------
112
+ # Run
113
  # --------------------------
114
  if __name__ == "__main__":
115
+ uvicorn.run(app, host="0.0.0.0", port=7860)