Update app.py
Browse files123456232 unmodified lines23924024124224324424514 unmodified lines26026126226326426525 unmodified lines2912922932942952967 unmodified lines304305306307308309310311312313import spacesimport gradio as grfrom PIL import Imagefrom src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipelinefrom src.unet_hacked_garmnet import UNet2DConditionModel as UNet2DConditionModel_reffrom src.unet_hacked_tryon import UNet2DConditionModel232 unmodified linesreturn human_img_orig, mask_grayelse:return images[0], mask_gray# return images[0], mask_graygarm_list = os.listdir(os.path.join(example_path,"cloth"))garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list]14 unmodified linesimage_blocks = gr.Blocks().queue()with image_blocks as demo:gr.Markdown("## IDM-VTON πππ")gr.Markdown("Virtual Try-on with your image and garment image. Check out the [source codes](https://github.com/yisol/IDM-VTON) and the [model](https://huggingface.co/yisol/IDM-VTON)")with gr.Row():25 unmodified lineswith gr.Column():# image_out = gr.Image(label="Output", elem_id="output-img", height=400)image_out = gr.Image(label="Output", elem_id="output-img",show_share_button=False)7 unmodified linestry_button.click(fn=start_tryon, inputs=[imgs, garm_img, prompt, is_checked,is_checked_crop, denoise_steps, seed], outputs=[image_out,masked_img], api_name='tryon')image_blocks.launch()123456789101112131415232 unmodified lines24824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229314 unmodified lines30830931031131231331425 unmodified lines3403413423433443453467 unmodified lines354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454import spacesimport gradio as grfrom PIL import Imageimport osimport uuidimport timeimport base64from io import BytesIOfrom fastapi import FastAPI, Request, BackgroundTasks, Formfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import JSONResponseimport uvicornfrom src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipelinefrom src.unet_hacked_garmnet import UNet2DConditionModel as UNet2DConditionModel_reffrom src.unet_hacked_tryon import UNet2DConditionModel232 unmodified linesreturn human_img_orig, mask_grayelse:return images[0], mask_graydef start_tryon_wrapper(dict, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed, state=None, request: gr.Request = None, view_name="front", filename_holder=None):# Call the GPU functionresult_img, mask_img = start_tryon(dict, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed)# Save the output images to static directory (on the CPU web server/host)os.makedirs("./static/outputs", exist_ok=True)unique_id = f"{uuid.uuid4().hex[:8]}_{int(time.time())}"output_filename = f"{view_name}_{unique_id}.jpg"mask_filename = f"{view_name}_{unique_id}_mask.jpg"output_path = os.path.join("./static/outputs", output_filename)mask_path = os.path.join("./static/outputs", mask_filename)result_img.save(output_path, "JPEG")mask_img.save(mask_path, "JPEG")if isinstance(filename_holder, dict):filename_holder["output_filename"] = output_filenamefilename_holder["mask_filename"] = mask_filenamereturn result_img, mask_img# If called from Gradio, construct the markdown link with all images generated in this sessionhost = request.headers.get("host", "localhost:7860") if request else "localhost:7860"proto = "https" if "hf.space" in host else "http"base_url = f"{proto}://{host}"url = f"{base_url}/static/outputs/{output_filename}"if not isinstance(state, list):state = []state.append(url)# Limit to maximum of 10 images for Instagram carousel rulesstate = state[-10:]images_query = ",".join(state)markdown_link = f"### [π Post all generated images ({len(state)}) to Instagram (via local service)](http://localhost:3000/?images={images_query})"return result_img, mask_img, gr.update(value=markdown_link, visible=True), stategarm_list = os.listdir(os.path.join(example_path,"cloth"))garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list]14 unmodified linesimage_blocks = gr.Blocks().queue()with image_blocks as demo:generated_images_state = gr.State(value=[])gr.Markdown("## IDM-VTON πππ")gr.Markdown("Virtual Try-on with your image and garment image. Check out the [source codes](https://github.com/yisol/IDM-VTON) and the [model](https://huggingface.co/yisol/IDM-VTON)")with gr.Row():25 unmodified lineswith gr.Column():# image_out = gr.Image(label="Output", elem_id="output-img", height=400)image_out = gr.Image(label="Output", elem_id="output-img",show_share_button=False)instagram_link = gr.Markdown(value="", visible=False)7 unmodified linestry_button.click(fn=start_tryon_wrapper, inputs=[imgs, garm_img, prompt, is_checked,is_checked_crop, denoise_steps, seed, generated_images_state], outputs=[image_out,masked_img,instagram_link,generated_images_state], api_name='tryon')# Create static directoryos.makedirs("./static/outputs", exist_ok=True)# Define FastAPI applicationapp = FastAPI()# Mount the static files directoryapp.mount("/static", StaticFiles(directory="static"), name="static")# Helper task to clean up old files (>1 hour old) to prevent disk fill-updef cleanup_old_files():now = time.time()outputs_dir = "./static/outputs"if os.path.exists(outputs_dir):for filename in os.listdir(outputs_dir):file_path = os.path.join(outputs_dir, filename)if os.path.isfile(file_path):if os.stat(file_path).st_mtime < now - 3600:try:os.remove(file_path)except Exception as e:print(f"Error removing {file_path}: {e}")# Expose REST API endpoint for automated backend workflows (e.g. posting to Instagram)@app.post("/api/tryon")async def api_tryon(request: Request,background_tasks: BackgroundTasks,human_image: str = Form(..., description="Base64 encoded human image"),garment_image: str = Form(..., description="Base64 encoded garment image"),garment_description: str = Form(..., description="Text description of the garment"),view: str = Form("front", description="View name: front, back, left, right"),is_checked: bool = Form(True, description="Use auto-generated mask"),is_checked_crop: bool = Form(False, description="Use auto-crop & resizing"),denoise_steps: int = Form(30, description="Denoising steps (20-40)"),seed: int = Form(42, description="Seed value")):# Queue cleanup task in backgroundbackground_tasks.add_task(cleanup_old_files)try:# Decode base64 human imageif "," in human_image:human_image = human_image.split(",")[1]human_pil = Image.open(BytesIO(base64.b64decode(human_image))).convert("RGB")# Decode base64 garment imageif "," in garment_image:garment_image = garment_image.split(",")[1]garm_pil = Image.open(BytesIO(base64.b64decode(garment_image))).convert("RGB")# Create input dictionary for start_tryon formatinput_dict = {"background": human_pil,"layers": [None],"composite": None}# Call try_on with filename holder to capture output filenamesfilename_holder = {}start_tryon_wrapper(input_dict, garm_pil, garment_description, is_checked,is_checked_crop, denoise_steps, seed, view_name=view,filename_holder=filename_holder)# Get base URL of the request dynamically, respecting HF reverse proxy headersproto = request.headers.get("x-forwarded-proto", "http")host = request.headers.get("x-forwarded-host", request.headers.get("host", "localhost:7860"))base_url = f"{proto}://{host}"output_filename = filename_holder.get("output_filename")mask_filename = filename_holder.get("mask_filename")return JSONResponse({"status": "success","view": view,"image_url": f"{base_url}/static/outputs/{output_filename}","mask_url": f"{base_url}/static/outputs/{mask_filename}","output_filename": output_filename,"mask_filename": mask_filename})except Exception as e:import tracebacktraceback.print_exc()return JSONResponse({"status": "error", "message": str(e)}, status_code=500)# Mount Gradio interface inside FastAPI under the root pathapp = gr.mount_gradio_app(app, image_blocks, path="/")if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+145-4