Update api/src/main.py
Browse files- api/src/main.py +58 -59
api/src/main.py
CHANGED
|
@@ -10,19 +10,23 @@ import sys
|
|
| 10 |
from pathlib import Path
|
| 11 |
import requests as http_requests
|
| 12 |
|
| 13 |
-
# Path Setup
|
| 14 |
root_dir = Path(__file__).resolve().parent.parent.parent
|
| 15 |
sys.path.append(str(root_dir))
|
| 16 |
|
| 17 |
# Import your core engine
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
app = FastAPI()
|
| 21 |
|
| 22 |
-
# CORS Fix
|
| 23 |
app.add_middleware(
|
| 24 |
CORSMiddleware,
|
| 25 |
allow_origins=["*"],
|
|
|
|
| 26 |
allow_methods=["*"],
|
| 27 |
allow_headers=["*"],
|
| 28 |
)
|
|
@@ -37,103 +41,86 @@ def get_dirs():
|
|
| 37 |
|
| 38 |
@app.get("/")
|
| 39 |
def health_check():
|
| 40 |
-
return {"status": "active", "service": "CarVite AI"}
|
| 41 |
|
|
|
|
|
|
|
| 42 |
@app.post("/process")
|
| 43 |
@app.post("/upload-image")
|
| 44 |
async def process_car_image(
|
| 45 |
image: UploadFile = File(...),
|
| 46 |
-
action: str = Form("remove"), #
|
| 47 |
bg_color: str = Form(None),
|
| 48 |
bg_url: str = Form(None),
|
| 49 |
):
|
| 50 |
input_dir, output_dir = get_dirs()
|
| 51 |
-
|
| 52 |
-
# Save original image with unique ID
|
| 53 |
file_id = int(time.time() * 1000)
|
| 54 |
-
file_extension = Path(image.filename).suffix or ".jpg"
|
| 55 |
-
input_filename = f"in_{file_id}{file_extension}"
|
| 56 |
-
input_path = input_dir / input_filename
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
| 63 |
|
| 64 |
try:
|
| 65 |
-
# 1.
|
| 66 |
-
# Isnet model use ho raha hai car cutout nikalne k liye
|
| 67 |
processed_img, _ = processor.process_image(str(input_path), model_name="isnet-general-use")
|
| 68 |
processed_img = processed_img.convert("RGBA")
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
# 2. Case: JUST REMOVE BACKGROUND (Transparent PNG)
|
| 74 |
-
if action == "remove":
|
| 75 |
processed_img.save(output_path, "PNG")
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
try:
|
| 84 |
bg_res = http_requests.get(bg_url, timeout=10)
|
| 85 |
-
bg_res.raise_for_status()
|
| 86 |
bg_img = Image.open(io.BytesIO(bg_res.content)).convert("RGBA")
|
| 87 |
bg_img = bg_img.resize(processed_img.size, Image.LANCZOS)
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
combined.paste(processed_img, (0, 0), processed_img)
|
| 93 |
-
final_img = combined
|
| 94 |
-
except Exception as e:
|
| 95 |
-
print(f"BG URL Error: {e}")
|
| 96 |
-
# Agar background fail ho jaye toh sirf cutout bhej do bajaye crash hone k
|
| 97 |
-
final_img = processed_img
|
| 98 |
-
|
| 99 |
-
elif bg_color:
|
| 100 |
-
try:
|
| 101 |
-
# Color code like '#FFFFFF' or 'red'
|
| 102 |
bg_img = Image.new("RGBA", processed_img.size, bg_color)
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
print(f"BG Color Error: {e}")
|
| 107 |
-
final_img = processed_img
|
| 108 |
|
| 109 |
-
# Save and Send
|
| 110 |
-
final_img.save(output_path, "PNG")
|
| 111 |
return FileResponse(str(output_path), media_type="image/png")
|
| 112 |
|
| 113 |
except Exception as e:
|
| 114 |
-
print(f"AI
|
| 115 |
raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
|
| 116 |
finally:
|
| 117 |
image.file.close()
|
| 118 |
|
| 119 |
-
#
|
| 120 |
@app.post("/replace-background")
|
| 121 |
async def replace_custom_bg(
|
| 122 |
-
image: UploadFile = File(...),
|
| 123 |
-
background: UploadFile = File(...),
|
| 124 |
car_size: float = Form(0.65),
|
| 125 |
smart_placement: bool = Form(True)
|
| 126 |
):
|
| 127 |
input_dir, output_dir = get_dirs()
|
| 128 |
-
file_id = int(time.time())
|
| 129 |
|
| 130 |
fg_path = input_dir / f"fg_{file_id}_{image.filename}"
|
| 131 |
bg_path = input_dir / f"bg_{file_id}_{background.filename}"
|
|
|
|
| 132 |
|
| 133 |
with fg_path.open("wb") as f: shutil.copyfileobj(image.file, f)
|
| 134 |
with bg_path.open("wb") as b: shutil.copyfileobj(background.file, b)
|
| 135 |
|
| 136 |
try:
|
|
|
|
| 137 |
result_img = processor.replace_background(
|
| 138 |
foreground_input=str(fg_path),
|
| 139 |
background_input=str(bg_path),
|
|
@@ -141,8 +128,20 @@ async def replace_custom_bg(
|
|
| 141 |
smart_placement=smart_placement
|
| 142 |
)
|
| 143 |
|
| 144 |
-
output_path = output_dir / f"custom_{file_id}.png"
|
| 145 |
result_img.save(output_path, "PNG")
|
| 146 |
return FileResponse(str(output_path), media_type="image/png")
|
|
|
|
| 147 |
except Exception as e:
|
| 148 |
-
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
from pathlib import Path
|
| 11 |
import requests as http_requests
|
| 12 |
|
| 13 |
+
# --- Path Setup ---
|
| 14 |
root_dir = Path(__file__).resolve().parent.parent.parent
|
| 15 |
sys.path.append(str(root_dir))
|
| 16 |
|
| 17 |
# Import your core engine
|
| 18 |
+
try:
|
| 19 |
+
from core import processor
|
| 20 |
+
except ImportError:
|
| 21 |
+
print("Error: 'core.processor' nahi mila. Check karein ke 'core' folder sahi jagah hai.")
|
| 22 |
|
| 23 |
app = FastAPI()
|
| 24 |
|
| 25 |
+
# --- CORS Fix (Sirf ek baar clean code) ---
|
| 26 |
app.add_middleware(
|
| 27 |
CORSMiddleware,
|
| 28 |
allow_origins=["*"],
|
| 29 |
+
allow_credentials=True,
|
| 30 |
allow_methods=["*"],
|
| 31 |
allow_headers=["*"],
|
| 32 |
)
|
|
|
|
| 41 |
|
| 42 |
@app.get("/")
|
| 43 |
def health_check():
|
| 44 |
+
return {"status": "active", "service": "CarVite AI Backend"}
|
| 45 |
|
| 46 |
+
# --- Main Processing Endpoint ---
|
| 47 |
+
# Dono routes add kar diye hain taake frontend jo bhi call kare chal jaye
|
| 48 |
@app.post("/process")
|
| 49 |
@app.post("/upload-image")
|
| 50 |
async def process_car_image(
|
| 51 |
image: UploadFile = File(...),
|
| 52 |
+
action: str = Form("remove"), # Default: remove background
|
| 53 |
bg_color: str = Form(None),
|
| 54 |
bg_url: str = Form(None),
|
| 55 |
):
|
| 56 |
input_dir, output_dir = get_dirs()
|
|
|
|
|
|
|
| 57 |
file_id = int(time.time() * 1000)
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
# Save Input Image
|
| 60 |
+
ext = Path(image.filename).suffix or ".jpg"
|
| 61 |
+
input_path = input_dir / f"in_{file_id}{ext}"
|
| 62 |
+
|
| 63 |
+
with input_path.open("wb") as buffer:
|
| 64 |
+
shutil.copyfileobj(image.file, buffer)
|
| 65 |
|
| 66 |
try:
|
| 67 |
+
# 1. Background Remove (Hamesha pehle cutout nikalte hain)
|
|
|
|
| 68 |
processed_img, _ = processor.process_image(str(input_path), model_name="isnet-general-use")
|
| 69 |
processed_img = processed_img.convert("RGBA")
|
| 70 |
+
|
| 71 |
+
output_path = output_dir / f"out_{file_id}.png"
|
| 72 |
|
| 73 |
+
# 2. Logic: Sirf Remove karna hai ya Replace?
|
| 74 |
+
if action == "remove" and not bg_url and not bg_color:
|
| 75 |
+
# Sirf Transparent PNG save karo
|
|
|
|
|
|
|
| 76 |
processed_img.save(output_path, "PNG")
|
| 77 |
+
|
| 78 |
+
else:
|
| 79 |
+
# Background Replacement Logic
|
| 80 |
+
final_img = processed_img
|
| 81 |
+
|
| 82 |
+
if bg_url:
|
| 83 |
+
# Agar URL se background lagana hai
|
|
|
|
| 84 |
bg_res = http_requests.get(bg_url, timeout=10)
|
|
|
|
| 85 |
bg_img = Image.open(io.BytesIO(bg_res.content)).convert("RGBA")
|
| 86 |
bg_img = bg_img.resize(processed_img.size, Image.LANCZOS)
|
| 87 |
+
final_img = Image.alpha_composite(bg_img, processed_img)
|
| 88 |
+
|
| 89 |
+
elif bg_color:
|
| 90 |
+
# Agar solid color lagana hai
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
bg_img = Image.new("RGBA", processed_img.size, bg_color)
|
| 92 |
+
final_img = Image.alpha_composite(bg_img, processed_img)
|
| 93 |
+
|
| 94 |
+
final_img.save(output_path, "PNG")
|
|
|
|
|
|
|
| 95 |
|
|
|
|
|
|
|
| 96 |
return FileResponse(str(output_path), media_type="image/png")
|
| 97 |
|
| 98 |
except Exception as e:
|
| 99 |
+
print(f"AI Error: {str(e)}")
|
| 100 |
raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
|
| 101 |
finally:
|
| 102 |
image.file.close()
|
| 103 |
|
| 104 |
+
# --- Custom Background Upload Endpoint ---
|
| 105 |
@app.post("/replace-background")
|
| 106 |
async def replace_custom_bg(
|
| 107 |
+
image: UploadFile = File(..., description="Car Image"),
|
| 108 |
+
background: UploadFile = File(..., description="Custom BG Image"),
|
| 109 |
car_size: float = Form(0.65),
|
| 110 |
smart_placement: bool = Form(True)
|
| 111 |
):
|
| 112 |
input_dir, output_dir = get_dirs()
|
| 113 |
+
file_id = int(time.time() * 1000)
|
| 114 |
|
| 115 |
fg_path = input_dir / f"fg_{file_id}_{image.filename}"
|
| 116 |
bg_path = input_dir / f"bg_{file_id}_{background.filename}"
|
| 117 |
+
output_path = output_dir / f"final_{file_id}.png"
|
| 118 |
|
| 119 |
with fg_path.open("wb") as f: shutil.copyfileobj(image.file, f)
|
| 120 |
with bg_path.open("wb") as b: shutil.copyfileobj(background.file, b)
|
| 121 |
|
| 122 |
try:
|
| 123 |
+
# Core replacement function call
|
| 124 |
result_img = processor.replace_background(
|
| 125 |
foreground_input=str(fg_path),
|
| 126 |
background_input=str(bg_path),
|
|
|
|
| 128 |
smart_placement=smart_placement
|
| 129 |
)
|
| 130 |
|
|
|
|
| 131 |
result_img.save(output_path, "PNG")
|
| 132 |
return FileResponse(str(output_path), media_type="image/png")
|
| 133 |
+
|
| 134 |
except Exception as e:
|
| 135 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 136 |
+
finally:
|
| 137 |
+
image.file.close()
|
| 138 |
+
background.file.close()
|
| 139 |
+
|
| 140 |
+
# --- Serve Processed Images (Just in case) ---
|
| 141 |
+
@app.get("/output/{filename}")
|
| 142 |
+
def get_output(filename: str):
|
| 143 |
+
_, output_dir = get_dirs()
|
| 144 |
+
file_path = output_dir / filename
|
| 145 |
+
if not file_path.exists():
|
| 146 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 147 |
+
return FileResponse(file_path)
|