nftblackmagic commited on
Commit
ddc1268
1 Parent(s): ea205f0

Create app_lora.py

Browse files
Files changed (1) hide show
  1. app_lora.py +202 -0
app_lora.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+
3
+ import gradio as gr
4
+ from tryon_inference import run_inference
5
+ import os
6
+ import numpy as np
7
+ from PIL import Image
8
+ import tempfile
9
+ import torch
10
+ from diffusers import FluxTransformer2DModel, FluxFillPipeline
11
+ import subprocess
12
+
13
+ subprocess.run("rm -rf /data-nvme/zerogpu-offload/*", env={}, shell=True)
14
+ dtype = torch.bfloat16
15
+ device = "cuda" if torch.cuda.is_available() else "cpu"
16
+
17
+ print("Start loading LoRA weights")
18
+ state_dict, network_alphas = FluxFillPipeline.lora_state_dict(
19
+ pretrained_model_name_or_path_or_dict="xiaozaa/catvton-flux-lora-alpha", ## The tryon Lora weights
20
+ weight_name="pytorch_lora_weights.safetensors",
21
+ return_alphas=True
22
+ )
23
+ is_correct_format = all("lora" in key or "dora_scale" in key for key in state_dict.keys())
24
+ if not is_correct_format:
25
+ raise ValueError("Invalid LoRA checkpoint.")
26
+ print('Loading diffusion model ...')
27
+ pipe = FluxFillPipeline.from_pretrained(
28
+ "black-forest-labs/FLUX.1-Fill-dev",
29
+ torch_dtype=torch.bfloat16
30
+ ).to(device)
31
+ FluxFillPipeline.load_lora_into_transformer(
32
+ state_dict=state_dict,
33
+ network_alphas=network_alphas,
34
+ transformer=pipe.transformer,
35
+ )
36
+
37
+ print('Loading Finished!')
38
+
39
+ @spaces.GPU
40
+ def gradio_inference(
41
+ image_data,
42
+ garment,
43
+ num_steps=50,
44
+ guidance_scale=30.0,
45
+ seed=-1,
46
+ width=768,
47
+ height=1024
48
+ ):
49
+ """Wrapper function for Gradio interface"""
50
+ # Use temporary directory
51
+ with tempfile.TemporaryDirectory() as tmp_dir:
52
+ # Save inputs to temp directory
53
+ temp_image = os.path.join(tmp_dir, "image.png")
54
+ temp_mask = os.path.join(tmp_dir, "mask.png")
55
+ temp_garment = os.path.join(tmp_dir, "garment.png")
56
+
57
+ # Extract image and mask from ImageEditor data
58
+ image = image_data["background"]
59
+ mask = image_data["layers"][0] # First layer contains the mask
60
+
61
+ # Convert to numpy array and process mask
62
+ mask_array = np.array(mask)
63
+ is_black = np.all(mask_array < 10, axis=2)
64
+ mask = Image.fromarray(((~is_black) * 255).astype(np.uint8))
65
+
66
+ # Save files to temp directory
67
+ image.save(temp_image)
68
+ mask.save(temp_mask)
69
+ garment.save(temp_garment)
70
+
71
+ try:
72
+ # Run inference
73
+ _, tryon_result = run_inference(
74
+ pipe=pipe,
75
+ image_path=temp_image,
76
+ mask_path=temp_mask,
77
+ garment_path=temp_garment,
78
+ num_steps=num_steps,
79
+ guidance_scale=guidance_scale,
80
+ seed=seed,
81
+ size=(width, height)
82
+ )
83
+ return tryon_result
84
+ except Exception as e:
85
+ raise gr.Error(f"Error during inference: {str(e)}")
86
+
87
+ with gr.Blocks() as demo:
88
+ gr.Markdown("""
89
+ # CATVTON FLUX Virtual Try-On Demo (by using LoRA weights)
90
+ Upload a model image, draw a mask, and a garment image to generate virtual try-on results.
91
+
92
+ [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/xiaozaa/catvton-flux-alpha)
93
+ [![GitHub](https://img.shields.io/badge/github-%23121011.svg?style=for-the-badge&logo=github&logoColor=white)](https://github.com/nftblackmagic/catvton-flux)
94
+ """)
95
+
96
+ # gr.Video("example/github.mp4", label="Demo Video: How to use the tool")
97
+
98
+ with gr.Column():
99
+ with gr.Row():
100
+ with gr.Column():
101
+ image_input = gr.ImageMask(
102
+ label="Model Image (Click 'Edit' and draw mask over the clothing area)",
103
+ type="pil",
104
+ height=600,
105
+ width=300
106
+ )
107
+ gr.Examples(
108
+ examples=[
109
+ ["./example/person/00008_00.jpg"],
110
+ ["./example/person/00055_00.jpg"],
111
+ ["./example/person/00057_00.jpg"],
112
+ ["./example/person/00067_00.jpg"],
113
+ ["./example/person/00069_00.jpg"],
114
+ ],
115
+ inputs=[image_input],
116
+ label="Person Images",
117
+ )
118
+ with gr.Column():
119
+ garment_input = gr.Image(label="Garment Image", type="pil", height=600, width=300)
120
+ gr.Examples(
121
+ examples=[
122
+ ["./example/garment/04564_00.jpg"],
123
+ ["./example/garment/00055_00.jpg"],
124
+ ["./example/garment/00396_00.jpg"],
125
+ ["./example/garment/00067_00.jpg"],
126
+ ["./example/garment/00069_00.jpg"],
127
+ ],
128
+ inputs=[garment_input],
129
+ label="Garment Images",
130
+ )
131
+ with gr.Column():
132
+ tryon_output = gr.Image(label="Try-On Result", height=600, width=300)
133
+
134
+ with gr.Row():
135
+ num_steps = gr.Slider(
136
+ minimum=1,
137
+ maximum=100,
138
+ value=30,
139
+ step=1,
140
+ label="Number of Steps"
141
+ )
142
+ guidance_scale = gr.Slider(
143
+ minimum=1.0,
144
+ maximum=50.0,
145
+ value=30.0,
146
+ step=0.5,
147
+ label="Guidance Scale"
148
+ )
149
+ seed = gr.Slider(
150
+ minimum=-1,
151
+ maximum=2147483647,
152
+ step=1,
153
+ value=-1,
154
+ label="Seed (-1 for random)"
155
+ )
156
+ width = gr.Slider(
157
+ minimum=256,
158
+ maximum=1024,
159
+ step=64,
160
+ value=768,
161
+ label="Width"
162
+ )
163
+ height = gr.Slider(
164
+ minimum=256,
165
+ maximum=1024,
166
+ step=64,
167
+ value=1024,
168
+ label="Height"
169
+ )
170
+
171
+
172
+ submit_btn = gr.Button("Generate Try-On", variant="primary")
173
+
174
+
175
+ with gr.Row():
176
+ gr.Markdown("""
177
+ ### Notes:
178
+ - The model is trained on VITON-HD dataset. It focuses on the woman upper body try-on generation.
179
+ - The mask should indicate the region where the garment will be placed.
180
+ - The garment image should be on a clean background.
181
+ - The model is not perfect. It may generate some artifacts.
182
+ - The model is slow. Please be patient.
183
+ - The model is just for research purpose.
184
+ """)
185
+
186
+ submit_btn.click(
187
+ fn=gradio_inference,
188
+ inputs=[
189
+ image_input,
190
+ garment_input,
191
+ num_steps,
192
+ guidance_scale,
193
+ seed,
194
+ width,
195
+ height
196
+ ],
197
+ outputs=[tryon_output],
198
+ api_name="try-on"
199
+ )
200
+
201
+
202
+ demo.launch()