Spooke commited on
Commit
233be72
Β·
verified Β·
1 Parent(s): 7207c11

Upload 3 files

Browse files
Files changed (2) hide show
  1. app.py +78 -75
  2. requirements.txt +5 -11
app.py CHANGED
@@ -1,64 +1,51 @@
1
  """
2
  FitView Virtual Try-On β€” HuggingFace Space
3
- Uses CatVTON (MIT license) with ZeroGPU (free A100).
 
4
 
5
- API endpoint: POST /run/predict
6
- inputs: [person_image_b64, cloth_image_b64, garment_type]
7
- outputs: [result_image_b64]
8
  """
9
 
10
  import base64
11
  import io
12
  import os
13
- import subprocess
14
- import sys
15
 
16
  import gradio as gr
17
  import numpy as np
18
  import spaces
19
  import torch
20
- from PIL import Image, ImageOps
21
 
22
- # ── Install CatVTON from GitHub (runs once at Space startup) ──────────────────
23
- _CATVTON_DIR = "/home/user/CatVTON"
24
 
25
- def _install_catvton():
26
- if os.path.isdir(_CATVTON_DIR):
27
- return
28
- print("Cloning CatVTON…")
29
- subprocess.check_call([
30
- "git", "clone", "--depth", "1",
31
- "https://github.com/Zheng-Chong/CatVTON.git",
32
- _CATVTON_DIR,
33
- ])
34
- subprocess.check_call([sys.executable, "-m", "pip", "install", "-e", _CATVTON_DIR, "-q"])
35
 
36
- _install_catvton()
37
- sys.path.insert(0, _CATVTON_DIR)
38
-
39
-
40
- # ── Model loading (lazy β€” loaded once per ZeroGPU GPU lease) ──────────────────
41
-
42
- _pipeline = None
43
 
44
  def _load_pipeline():
45
- global _pipeline
46
- if _pipeline is not None:
47
- return _pipeline
48
-
49
- from model.pipeline import CatVTONPipeline # noqa: E402 (installed above)
50
-
51
- print("Loading CatVTON weights…")
52
- _pipeline = CatVTONPipeline(
53
- attn_ckpt_version="mix",
54
- attn_ckpt="zhengchong/CatVTON",
55
- base_ckpt="booksforcharlie/stable-diffusion-inpainting",
56
- motion_ckpt=None,
57
- weight_dtype=torch.float16,
58
- device="cuda",
59
- skip_safety_check=True,
60
  )
61
- return _pipeline
 
 
 
 
 
 
 
 
62
 
63
 
64
  # ── Helpers ───────────────────────────────────────────────────────────────────
@@ -74,77 +61,93 @@ def _pil_to_b64(img: Image.Image) -> str:
74
  return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
75
 
76
 
77
- def _make_cloth_mask(cloth: Image.Image) -> Image.Image:
78
- """White mask that covers the entire cloth image (CatVTON agnostic mask)."""
79
- return Image.new("L", cloth.size, 255)
 
 
 
 
 
 
 
 
 
 
80
 
81
 
82
- def _resize_pair(person: Image.Image, cloth: Image.Image):
83
- """Resize both images to 768Γ—1024 as CatVTON expects."""
84
- target = (768, 1024)
85
- person = ImageOps.fit(person, target, Image.LANCZOS)
86
- cloth = ImageOps.fit(cloth, target, Image.LANCZOS)
87
- return person, cloth
88
 
89
 
90
  # ── Inference ─────────────────────────────────────────────────────────────────
91
 
92
  @spaces.GPU(duration=60)
93
- def _run_inference(person: Image.Image, cloth: Image.Image) -> Image.Image:
94
  pipe = _load_pipeline()
95
- person, cloth = _resize_pair(person, cloth)
96
- mask = _make_cloth_mask(cloth)
 
 
 
 
 
 
 
 
 
97
 
98
  result = pipe(
 
 
99
  image=person,
100
- condition_image=cloth,
101
- mask=mask,
102
- num_inference_steps=50,
103
- guidance_scale=2.5,
104
- generator=torch.Generator(device="cuda").manual_seed(42),
105
- )[0]
 
 
106
  return result
107
 
108
 
109
- # ── Gradio API ────────────────────────────────────────────────────────────────
110
 
111
  def predict(person_b64: str, cloth_b64: str, garment_type: str = "top") -> str:
112
  person = _b64_to_pil(person_b64)
113
  cloth = _b64_to_pil(cloth_b64)
114
- result = _run_inference(person, cloth)
115
  return _pil_to_b64(result)
116
 
117
 
118
- # ── UI (for manual testing in the Space) ──────────────────────────────────────
119
 
120
- def ui_predict(person_img, cloth_img, garment_type):
121
- if person_img is None or cloth_img is None:
122
  return None
123
- person_pil = Image.fromarray(person_img)
124
- cloth_pil = Image.fromarray(cloth_img)
125
- result = _run_inference(person_pil, cloth_pil)
126
  return np.array(result)
127
 
128
 
129
  with gr.Blocks(title="FitView Virtual Try-On") as demo:
130
- gr.Markdown("## FitView Virtual Try-On\nPowered by [CatVTON](https://github.com/Zheng-Chong/CatVTON) Β· ZeroGPU")
131
 
132
  with gr.Row():
133
- inp_person = gr.Image(label="Your photo", type="numpy")
134
- inp_cloth = gr.Image(label="Garment image", type="numpy")
135
- out_result = gr.Image(label="Try-on result", type="numpy")
136
 
137
  inp_type = gr.Radio(["top", "bottom", "full"], value="top", label="Garment type")
138
  btn = gr.Button("Try On", variant="primary")
139
-
140
  btn.click(ui_predict, inputs=[inp_person, inp_cloth, inp_type], outputs=out_result)
141
 
142
  # Named API for gradio_client calls from vton.py
143
  gr.Interface(
144
  fn=predict,
145
  inputs=[
146
- gr.Textbox(label="person_b64", visible=False),
147
- gr.Textbox(label="cloth_b64", visible=False),
148
  gr.Textbox(label="garment_type", visible=False),
149
  ],
150
  outputs=gr.Textbox(label="result_b64", visible=False),
 
1
  """
2
  FitView Virtual Try-On β€” HuggingFace Space
3
+ Uses Stable Diffusion Inpainting + IP-Adapter for garment conditioning.
4
+ No repo cloning needed β€” everything loads from HuggingFace Hub.
5
 
6
+ API: POST /run/predict
7
+ inputs: [person_b64 (str), cloth_b64 (str), garment_type (str)]
8
+ outputs: [result_b64 (str)]
9
  """
10
 
11
  import base64
12
  import io
13
  import os
 
 
14
 
15
  import gradio as gr
16
  import numpy as np
17
  import spaces
18
  import torch
19
+ from PIL import Image, ImageDraw, ImageFilter, ImageOps
20
 
21
+ # ── Model loading ─────────────────────────────────────────────────────────────
 
22
 
23
+ _pipe = None
 
 
 
 
 
 
 
 
 
24
 
 
 
 
 
 
 
 
25
 
26
  def _load_pipeline():
27
+ global _pipe
28
+ if _pipe is not None:
29
+ return _pipe
30
+
31
+ from diffusers import StableDiffusionInpaintPipeline
32
+
33
+ print("[VTON] Loading SD-Inpainting + IP-Adapter…")
34
+ pipe = StableDiffusionInpaintPipeline.from_pretrained(
35
+ "botp/stable-diffusion-v1-5-inpainting",
36
+ torch_dtype=torch.float16,
37
+ safety_checker=None,
38
+ requires_safety_checker=False,
 
 
 
39
  )
40
+ pipe.load_ip_adapter(
41
+ "h94/IP-Adapter",
42
+ subfolder="models",
43
+ weight_name="ip-adapter_sd15.bin",
44
+ )
45
+ pipe.set_ip_adapter_scale(0.85)
46
+ _pipe = pipe.to("cuda")
47
+ print("[VTON] Pipeline ready.")
48
+ return _pipe
49
 
50
 
51
  # ── Helpers ───────────────────────────────────────────────────────────────────
 
61
  return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
62
 
63
 
64
+ def _make_mask(size: tuple, garment_type: str) -> Image.Image:
65
+ W, H = size
66
+ mask = Image.new("L", (W, H), 0)
67
+ draw = ImageDraw.Draw(mask)
68
+
69
+ if garment_type == "bottom":
70
+ draw.rectangle([int(W * 0.08), int(H * 0.48), int(W * 0.92), int(H * 0.98)], fill=255)
71
+ elif garment_type == "full":
72
+ draw.rectangle([int(W * 0.08), int(H * 0.15), int(W * 0.92), int(H * 0.98)], fill=255)
73
+ else: # top (default)
74
+ draw.rectangle([int(W * 0.08), int(H * 0.15), int(W * 0.92), int(H * 0.65)], fill=255)
75
+
76
+ return mask.filter(ImageFilter.GaussianBlur(18))
77
 
78
 
79
+ def _resize(img: Image.Image, target=(512, 768)) -> Image.Image:
80
+ return ImageOps.fit(img, target, Image.LANCZOS)
 
 
 
 
81
 
82
 
83
  # ── Inference ─────────────────────────────────────────────────────────────────
84
 
85
  @spaces.GPU(duration=60)
86
+ def _run_inference(person: Image.Image, cloth: Image.Image, garment_type: str) -> Image.Image:
87
  pipe = _load_pipeline()
88
+
89
+ person = _resize(person)
90
+ cloth = _resize(cloth)
91
+ mask = _make_mask(person.size, garment_type)
92
+
93
+ label = {"top": "shirt", "bottom": "pants", "full": "dress"}.get(garment_type, "clothing")
94
+ prompt = (
95
+ f"photorealistic fashion photo, person wearing a {label}, "
96
+ "garment fits naturally, high quality, detailed fabric texture"
97
+ )
98
+ neg_prompt = "distorted, deformed, blurry, artifacts, low quality, duplicate"
99
 
100
  result = pipe(
101
+ prompt=prompt,
102
+ negative_prompt=neg_prompt,
103
  image=person,
104
+ mask_image=mask,
105
+ ip_adapter_image=cloth,
106
+ num_inference_steps=35,
107
+ guidance_scale=7.5,
108
+ strength=0.99,
109
+ generator=torch.Generator("cuda").manual_seed(42),
110
+ ).images[0]
111
+
112
  return result
113
 
114
 
115
+ # ── Gradio API ───────────────────────────────────────────────────────────────
116
 
117
  def predict(person_b64: str, cloth_b64: str, garment_type: str = "top") -> str:
118
  person = _b64_to_pil(person_b64)
119
  cloth = _b64_to_pil(cloth_b64)
120
+ result = _run_inference(person, cloth, garment_type)
121
  return _pil_to_b64(result)
122
 
123
 
124
+ # ── UI ────────────────────────────────────────────────────────────────────────
125
 
126
+ def ui_predict(person_arr, cloth_arr, garment_type):
127
+ if person_arr is None or cloth_arr is None:
128
  return None
129
+ result = _run_inference(Image.fromarray(person_arr), Image.fromarray(cloth_arr), garment_type)
 
 
130
  return np.array(result)
131
 
132
 
133
  with gr.Blocks(title="FitView Virtual Try-On") as demo:
134
+ gr.Markdown("## FitView Virtual Try-On\nSD-Inpainting + IP-Adapter Β· ZeroGPU (free)")
135
 
136
  with gr.Row():
137
+ inp_person = gr.Image(label="Your photo", type="numpy")
138
+ inp_cloth = gr.Image(label="Garment image", type="numpy")
139
+ out_result = gr.Image(label="Try-on result", type="numpy")
140
 
141
  inp_type = gr.Radio(["top", "bottom", "full"], value="top", label="Garment type")
142
  btn = gr.Button("Try On", variant="primary")
 
143
  btn.click(ui_predict, inputs=[inp_person, inp_cloth, inp_type], outputs=out_result)
144
 
145
  # Named API for gradio_client calls from vton.py
146
  gr.Interface(
147
  fn=predict,
148
  inputs=[
149
+ gr.Textbox(label="person_b64", visible=False),
150
+ gr.Textbox(label="cloth_b64", visible=False),
151
  gr.Textbox(label="garment_type", visible=False),
152
  ],
153
  outputs=gr.Textbox(label="result_b64", visible=False),
requirements.txt CHANGED
@@ -1,11 +1,5 @@
1
- gradio==4.44.0
2
- spaces
3
- diffusers==0.29.2
4
- transformers==4.44.2
5
- accelerate==0.33.0
6
- torch==2.3.1
7
- torchvision==0.18.1
8
- Pillow==10.4.0
9
- numpy==1.26.4
10
- omegaconf==2.3.0
11
- einops==0.8.0
 
1
+ diffusers>=0.29.2
2
+ transformers>=4.36.0
3
+ accelerate>=0.26.0
4
+ Pillow>=10.0.0
5
+ numpy>=1.24.0