File size: 1,806 Bytes
8403882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from fastapi import FastAPI, UploadFile, File,BackgroundTasks
from rembg import remove

from fastapi.responses import FileResponse
import os
from starlette.middleware.cors import CORSMiddleware
# from fastapi.staticfiles import StaticFiles


app = FastAPI()




origins = [
    "http://localhost:3000",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Directory to store processed images
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
# app.mount("/processed_images", StaticFiles(directory=output_dir), name="processed_images")

@app.post("/remove-background/")
async def remove_background(file: UploadFile):
    # Ensure the uploaded file is an image (you can add more validation)
    if not file.content_type.startswith("image/"):
        return {"error": "Invalid file format"}

    # Read the uploaded image file
    image_bytes = await file.read()

    # Process the image to remove the background using Rembg
    output_image_bytes = remove(image_bytes)

    # Save the processed image to a file
    output_filename = f"{output_dir}/{file.filename}"

    # output_filename  = f"processed_images/{file.filename.split('/')[-1]}"
    with open(output_filename, "wb") as output_file:
        output_file.write(output_image_bytes)

    return {"result": "Background removed successfully", "output_filename": output_filename}

    

@app.get("/download/{filename}")
async def download_processed_image(filename: str):
    file_path = os.path.join(output_dir, filename)
    # file_path = f"/output/{filename}"
    if not os.path.exists(file_path):
        return {"error": "File not found"}

    return FileResponse(file_path)


@app.get("/delete")
def deleteAll():
    os.rmdir("output")