vikashmakeit commited on
Commit
a956c3b
·
verified ·
1 Parent(s): 00c5d0f

Add Agentic Refinement tab: iterative image→pattern→3D→projection→compare→refine loop

Browse files
Files changed (1) hide show
  1. app.py +189 -156
app.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- Garment Image -> 2D Sewing Pattern + Chat Editing + 3D Preview
3
  """
4
  import json, os, re, traceback, copy
5
  from typing import Dict, Optional, Tuple, List
@@ -7,6 +7,7 @@ import gradio as gr
7
  from PIL import Image
8
  from pattern_generator import generate_pattern_from_analysis, get_pattern_pieces
9
  from garment_3d import create_3d_figure
 
10
 
11
  GARMENT_ANALYSIS_PROMPT = """You are a professional fashion pattern maker. Analyze this garment image and extract precise sewing pattern parameters.
12
 
@@ -69,32 +70,23 @@ VISION_MODELS = [
69
  ("google/gemma-4-31B-it", "together", "Gemma 4 31B"),
70
  ("moonshotai/Kimi-K2.5", "together", "Kimi K2.5"),
71
  ]
72
- TEXT_MODELS = VISION_MODELS
73
 
74
  def _extract_response_text(message):
75
  content = message.get('content', '') or ''
76
  reasoning = message.get('reasoning', '') or ''
77
- if content.strip():
78
- return content.strip()
79
- if reasoning.strip():
80
- return reasoning.strip()
81
- return ''
82
 
83
  def _extract_json_from_text(text):
84
  json_match = re.search(r'```(?:json)?\s*([\s\S]*?)\s*```', text)
85
- if json_match:
86
- return json_match.group(1)
87
  json_match = re.search(r'\{[\s\S]*\}', text)
88
- if json_match:
89
- return json_match.group()
90
  return None
91
 
92
  def _call_vlm(messages, timeout=180):
93
- import requests, base64
94
- from io import BytesIO
95
  hf_token = os.environ.get("HF_TOKEN", "")
96
- if not hf_token:
97
- return None
98
  for model_id, provider, display_name in VISION_MODELS:
99
  try:
100
  url = f"https://router.huggingface.co/{provider}/v1/chat/completions"
@@ -105,28 +97,23 @@ def _call_vlm(messages, timeout=180):
105
  if response.status_code == 200:
106
  result = response.json()
107
  text = _extract_response_text(result['choices'][0]['message'])
108
- if not text:
109
- continue
110
  json_str = _extract_json_from_text(text)
111
- if not json_str:
112
- continue
113
  analysis = json.loads(json_str)
114
- analysis['_model_used'] = f"{display_name}"
115
  print(f"[VLM] OK: {display_name} detected {analysis.get('garment_type','?')}")
116
  return analysis
117
- else:
118
- print(f"[VLM] {display_name}: HTTP {response.status_code}")
119
  except Exception as e:
120
- print(f"[VLM] {display_name} failed: {e}")
121
- continue
122
  return None
123
 
124
  def analyze_with_vlm(image):
125
  import base64
126
  from io import BytesIO
127
  hf_token = os.environ.get("HF_TOKEN", "")
128
- if not hf_token:
129
- return None
130
  max_dim = 1024
131
  if max(image.size) > max_dim:
132
  ratio = max_dim / max(image.size)
@@ -155,21 +142,13 @@ def get_default_analysis(garment_type="shirt"):
155
  _current_analysis = {"data": None}
156
 
157
  def _generate_all_outputs(analysis):
158
- """Generate 2D pattern, 3D figure (from pattern pieces), and summary."""
159
  garment_type = analysis.get('garment_type', 'shirt')
160
  measurements = analysis.get('measurements', {})
161
  features = analysis.get('features', {})
162
  params = {**measurements, **features}
163
-
164
- # Generate 2D pattern pieces
165
  pattern_pieces = get_pattern_pieces(garment_type, params)
166
-
167
- # Generate 2D pattern image and summary
168
  pattern_image, summary = generate_pattern_from_analysis(analysis)
169
-
170
- # Generate 3D figure FROM the actual pattern pieces
171
  fig_3d = create_3d_figure(analysis, pattern_pieces=pattern_pieces)
172
-
173
  display = {k: v for k, v in analysis.items() if k != '_model_used'}
174
  model_info = f"\n\n*AI: {analysis.get('_model_used', 'Default')}*" if analysis.get('_model_used') else ""
175
  desc = analysis.get('description', 'No description')
@@ -181,10 +160,8 @@ def process_image(image, garment_type_override="Auto-detect"):
181
  return None, None, "Please upload a garment image or select a type.", "{}", []
182
  analysis = None
183
  if image is not None:
184
- try:
185
- analysis = analyze_with_vlm(image)
186
- except Exception as e:
187
- print(f"VLM failed: {e}")
188
  if analysis is None:
189
  gt = garment_type_override.lower() if garment_type_override != "Auto-detect" else "shirt"
190
  analysis = get_default_analysis(gt)
@@ -201,33 +178,23 @@ def process_image(image, garment_type_override="Auto-detect"):
201
  return None, None, f"Error: {e}", "{}", []
202
 
203
  def process_text(description):
204
- if not description.strip():
205
- return None, None, "Enter a description.", "{}", []
206
  analysis = None
207
  hf_token = os.environ.get("HF_TOKEN", "")
208
  if hf_token:
209
- messages = [{"role": "user", "content": f"""Based on this garment description, extract sewing pattern parameters.
210
-
211
- Description: {description}
212
-
213
- Return ONLY JSON with: garment_type, description, measurements (bust, waist, hip, shoulder_width, bodice_length, sleeve_length, skirt_length, pant_length, neckline_depth, neckline_width, bicep, wrist, cap_height, collar_height, flare), features (has_collar, collar_type, has_cuffs, has_pockets, pocket_type, has_hood, fit)."""}]
214
  analysis = _call_vlm(messages, timeout=90)
215
  if analysis is None:
216
  desc_lower = description.lower()
217
  for gt in ['hoodie','jacket','coat','blazer','dress','skirt','pants','trousers','jeans','vest','shirt','blouse','top']:
218
  if gt in desc_lower:
219
- analysis = get_default_analysis(gt)
220
- analysis['description'] = description
221
- break
222
- if analysis is None:
223
- analysis = get_default_analysis("shirt")
224
- analysis['description'] = description
225
  _current_analysis["data"] = copy.deepcopy(analysis)
226
  try:
227
  p2d, p3d, summary, j = _generate_all_outputs(analysis)
228
  return p2d, p3d, summary, j, []
229
- except Exception as e:
230
- return None, None, f"Error: {e}", "{}", []
231
 
232
  def process_manual(gt,bust,waist,hip,shoulder,bodice,sleeve,skirt,pant,neck,flare_c,collar,ctype,cuffs,pockets,hood,fit):
233
  analysis = {"garment_type":gt.lower(),"description":f"Custom {gt.lower()}","measurements":{"bust":bust,"waist":waist,"hip":hip,"shoulder_width":shoulder,"bodice_length":bodice,"sleeve_length":sleeve,"skirt_length":skirt,"pant_length":pant,"neckline_depth":neck,"neckline_width":7,"bicep":30,"wrist":18,"cap_height":14,"collar_height":5,"flare":flare_c},"features":{"has_collar":collar,"collar_type":ctype.lower(),"has_cuffs":cuffs,"has_pockets":pockets,"pocket_type":"patch","has_hood":hood,"fit":fit.lower()}}
@@ -235,79 +202,133 @@ def process_manual(gt,bust,waist,hip,shoulder,bodice,sleeve,skirt,pant,neck,flar
235
  try:
236
  p2d, p3d, summary, j = _generate_all_outputs(analysis)
237
  return p2d, p3d, summary, j, []
238
- except Exception as e:
239
- return None, None, f"Error: {e}", "{}", []
240
 
241
  def chat_edit(message, history):
242
- if not message.strip():
243
- return history, None, None, "Please enter an edit request.", "{}"
244
- current = _current_analysis.get("data")
245
- if current is None:
246
- current = get_default_analysis("shirt")
247
- _current_analysis["data"] = current
248
  current_clean = {k: v for k, v in current.items() if k != '_model_used'}
249
- edit_prompt = EDIT_PROMPT_TEMPLATE.format(
250
- current_json=json.dumps(current_clean, indent=2), user_message=message)
251
  updated = None
252
- hf_token = os.environ.get("HF_TOKEN", "")
253
- if hf_token:
254
- messages = [{"role": "user", "content": edit_prompt}]
255
- try:
256
- updated = _call_vlm(messages, timeout=90)
257
- except Exception as e:
258
- print(f"Edit VLM failed: {e}")
259
  if updated is None:
260
  updated = copy.deepcopy(current)
261
  msg_lower = message.lower()
262
- if "long sleeve" in msg_lower or "longer sleeve" in msg_lower:
263
- updated['measurements']['sleeve_length'] = 65
264
- elif "short sleeve" in msg_lower or "shorter sleeve" in msg_lower:
265
- updated['measurements']['sleeve_length'] = 25
266
- if "no collar" in msg_lower or "remove collar" in msg_lower:
267
- updated['features']['has_collar'] = False; updated['features']['collar_type'] = 'none'
268
- if "add collar" in msg_lower:
269
- updated['features']['has_collar'] = True; updated['features']['collar_type'] = 'standard'
270
- if "add hood" in msg_lower or "hoodie" in msg_lower:
271
- updated['features']['has_hood'] = True
272
- if "no hood" in msg_lower or "remove hood" in msg_lower:
273
- updated['features']['has_hood'] = False
274
- if "add pocket" in msg_lower:
275
- updated['features']['has_pockets'] = True; updated['features']['pocket_type'] = 'patch'
276
- if "no pocket" in msg_lower or "remove pocket" in msg_lower:
277
- updated['features']['has_pockets'] = False
278
- if "oversized" in msg_lower or "loose" in msg_lower:
279
- updated['features']['fit'] = 'oversized'
280
- updated['measurements']['bust'] = updated['measurements'].get('bust', 96) + 10
281
- if "fitted" in msg_lower or "slim" in msg_lower:
282
- updated['features']['fit'] = 'fitted'
283
- if "flare" in msg_lower or "a-line" in msg_lower:
284
- updated['measurements']['flare'] = max(updated['measurements'].get('flare', 0), 8)
285
- if "straight" in msg_lower: updated['measurements']['flare'] = 0
286
- if "mini" in msg_lower: updated['measurements']['skirt_length'] = 30
287
- if "midi" in msg_lower: updated['measurements']['skirt_length'] = 80
288
- if "maxi" in msg_lower: updated['measurements']['skirt_length'] = 110
289
  updated['_model_used'] = 'Rule-based edit'
290
- if 'garment_type' not in updated:
291
- updated['garment_type'] = current.get('garment_type', 'shirt')
292
  _current_analysis["data"] = copy.deepcopy(updated)
293
- try:
294
- p2d, p3d, summary, j = _generate_all_outputs(updated)
295
- except Exception as e:
296
- p2d, p3d, summary, j = None, None, f"Error: {e}", "{}"
297
- ai_msg = f"Applied edit: {message}\n\n"
298
  changes = []
299
  for k in set(list(current.get('measurements',{}).keys()) + list(updated.get('measurements',{}).keys())):
300
  ov, nv = current.get('measurements',{}).get(k), updated.get('measurements',{}).get(k)
301
- if ov != nv and ov is not None and nv is not None:
302
- changes.append(f" {k}: {ov} -> {nv}")
303
  for k in set(list(current.get('features',{}).keys()) + list(updated.get('features',{}).keys())):
304
  ov, nv = current.get('features',{}).get(k), updated.get('features',{}).get(k)
305
- if ov != nv: changes.append(f" {k}: {ov} -> {nv}")
306
- ai_msg += ("Changes:\n" + "\n".join(changes)) if changes else "No changes detected."
307
- history = history or []
308
- history.append((message, ai_msg))
309
  return history, p2d, p3d, summary, j
310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  CSS = """
312
  .main-header { text-align: center; margin-bottom: 20px; }
313
  .info-box { padding: 15px; border-radius: 10px; background: #f0f7ff; border: 1px solid #cce0ff; margin: 10px 0; }
@@ -315,18 +336,17 @@ CSS = """
315
  """
316
 
317
  with gr.Blocks(title="Garment Pattern Studio") as demo:
318
- gr.HTML("""
319
- <div class="main-header">
320
  <h1>🧵 Garment Pattern Studio</h1>
321
- <p style="font-size: 1.1em; color: #555;">Analyze garments, edit with chat, preview in 3D</p>
322
  </div>
323
  <div class="info-box">
324
- <b>Powered by:</b> Qwen 3.5 &middot; Gemma 4 &middot; Kimi K2.5 via
325
  <a href="https://huggingface.co/docs/inference-providers">HF Inference Providers</a>
326
- &nbsp;|&nbsp; <b>3D view is built from the actual 2D pattern pieces</b>
327
  </div>""")
328
 
329
- with gr.Tab("From Image"):
330
  with gr.Row():
331
  with gr.Column(scale=1):
332
  input_image = gr.Image(type="pil", label="Upload Garment Image", height=350)
@@ -337,10 +357,10 @@ with gr.Blocks(title="Garment Pattern Studio") as demo:
337
  with gr.Column(): out_pattern_2d = gr.Image(label="2D Sewing Pattern", height=400)
338
  with gr.Column(): out_3d = gr.Plot(label="3D Garment Preview")
339
  out_summary = gr.Markdown(label="Pattern Summary")
340
- with gr.Accordion("Raw JSON", open=False): out_json = gr.Code(language="json", label="Analysis")
341
  analyze_btn.click(process_image, inputs=[input_image, garment_override], outputs=[out_pattern_2d, out_3d, out_summary, out_json])
342
 
343
- with gr.Tab("From Text"):
344
  with gr.Row():
345
  with gr.Column(scale=1):
346
  text_input = gr.Textbox(label="Describe the garment", placeholder="e.g., A fitted A-line dress with cap sleeves", lines=3)
@@ -361,36 +381,20 @@ with gr.Blocks(title="Garment Pattern Studio") as demo:
361
  with gr.Accordion("Raw JSON", open=False): txt_json = gr.Code(language="json")
362
  text_btn.click(process_text, inputs=[text_input], outputs=[txt_pattern_2d, txt_3d, txt_summary, txt_json])
363
 
364
- with gr.Tab("Manual Parameters"):
365
  with gr.Row():
366
  with gr.Column(scale=1):
367
  m_type = gr.Dropdown(choices=["Shirt","Dress","Skirt","Pants","Jacket","Hoodie","Vest"], value="Shirt", label="Garment Type")
368
  gr.Markdown("### Measurements (cm)")
369
- with gr.Row():
370
- m_bust = gr.Slider(70,130,value=92,step=1,label="Bust")
371
- m_waist = gr.Slider(55,110,value=74,step=1,label="Waist")
372
- with gr.Row():
373
- m_hip = gr.Slider(75,130,value=96,step=1,label="Hip")
374
- m_shoulder = gr.Slider(35,55,value=42,step=1,label="Shoulder")
375
- with gr.Row():
376
- m_bodice = gr.Slider(30,80,value=42,step=1,label="Bodice Length")
377
- m_sleeve = gr.Slider(10,75,value=60,step=1,label="Sleeve Length")
378
- with gr.Row():
379
- m_skirt = gr.Slider(25,120,value=55,step=1,label="Skirt Length")
380
- m_pant = gr.Slider(25,115,value=100,step=1,label="Pant Length")
381
- with gr.Row():
382
- m_neck = gr.Slider(3,25,value=8,step=1,label="Neckline Depth")
383
- m_flare = gr.Slider(0,20,value=0,step=1,label="Hem Flare")
384
  gr.Markdown("### Features")
385
- with gr.Row():
386
- m_collar = gr.Checkbox(value=True,label="Collar")
387
- m_ctype = gr.Dropdown(["Standard","Mandarin","Peter_pan"],value="Standard",label="Collar Type")
388
- with gr.Row():
389
- m_cuffs = gr.Checkbox(value=True,label="Cuffs")
390
- m_pockets = gr.Checkbox(value=False,label="Pockets")
391
- with gr.Row():
392
- m_hood = gr.Checkbox(value=False,label="Hood")
393
- m_fit = gr.Dropdown(["Fitted","Regular","Oversized","Loose"],value="Regular",label="Fit")
394
  manual_btn = gr.Button("Generate Pattern", variant="primary", size="lg")
395
  with gr.Column(scale=2):
396
  with gr.Row():
@@ -400,31 +404,60 @@ with gr.Blocks(title="Garment Pattern Studio") as demo:
400
  with gr.Accordion("Raw JSON", open=False): man_json = gr.Code(language="json")
401
  manual_btn.click(process_manual, inputs=[m_type,m_bust,m_waist,m_hip,m_shoulder,m_bodice,m_sleeve,m_skirt,m_pant,m_neck,m_flare,m_collar,m_ctype,m_cuffs,m_pockets,m_hood,m_fit], outputs=[man_pattern_2d, man_3d, man_summary, man_json])
402
 
403
- with gr.Tab("Chat & Edit"):
404
- gr.Markdown("### Edit your pattern with natural language\nFirst generate a pattern, then edit here. Both 2D and 3D update together.")
405
  with gr.Row():
406
  with gr.Column(scale=1):
407
  chatbot = gr.Chatbot(label="Pattern Editor", height=400)
408
- chat_input = gr.Textbox(label="Edit instruction", placeholder="e.g., Make the sleeves longer, Add a hood, Change to A-line skirt", lines=2)
409
- with gr.Row():
410
- chat_send = gr.Button("Apply Edit", variant="primary")
411
- chat_clear = gr.Button("Clear Chat")
412
  with gr.Column(scale=2):
413
  with gr.Row():
414
- with gr.Column(): chat_pattern_2d = gr.Image(label="Updated 2D Pattern", height=400)
415
- with gr.Column(): chat_3d = gr.Plot(label="Updated 3D Preview")
416
  chat_summary = gr.Markdown()
417
- with gr.Accordion("Updated JSON", open=False): chat_json = gr.Code(language="json")
418
  def clear_chat(): return [], None, None, "", "{}"
419
  chat_send.click(chat_edit, inputs=[chat_input, chatbot], outputs=[chatbot, chat_pattern_2d, chat_3d, chat_summary, chat_json])
420
  chat_input.submit(chat_edit, inputs=[chat_input, chatbot], outputs=[chatbot, chat_pattern_2d, chat_3d, chat_summary, chat_json])
421
  chat_clear.click(clear_chat, outputs=[chatbot, chat_pattern_2d, chat_3d, chat_summary, chat_json])
422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  gr.HTML("""<div class="ref-box" style="margin-top: 20px;"><h4>Research References</h4><ul>
424
- <li><b>ChatGarment</b> (2024) [<a href="https://arxiv.org/abs/2412.17811">Paper</a>] [<a href="https://huggingface.co/datasets/sy000/ChatGarmentDataset">Dataset</a>]</li>
425
- <li><b>NGL-Prompter</b> (2025) [<a href="https://arxiv.org/abs/2602.20700">Paper</a>]</li>
426
- <li><b>SewFormer</b> (2023) [<a href="https://arxiv.org/abs/2311.04218">Paper</a>]</li>
427
- <li><b>GarmentDiffusion</b> (2025) [<a href="https://arxiv.org/abs/2504.21476">Paper</a>]</li>
428
  </ul></div>""")
429
 
430
  if __name__ == "__main__":
 
1
  """
2
+ Garment Image -> 2D Sewing Pattern + Chat Editing + 3D Preview + Agentic Refinement
3
  """
4
  import json, os, re, traceback, copy
5
  from typing import Dict, Optional, Tuple, List
 
7
  from PIL import Image
8
  from pattern_generator import generate_pattern_from_analysis, get_pattern_pieces
9
  from garment_3d import create_3d_figure
10
+ from refinement_loop import refinement_loop, render_3d_to_image
11
 
12
  GARMENT_ANALYSIS_PROMPT = """You are a professional fashion pattern maker. Analyze this garment image and extract precise sewing pattern parameters.
13
 
 
70
  ("google/gemma-4-31B-it", "together", "Gemma 4 31B"),
71
  ("moonshotai/Kimi-K2.5", "together", "Kimi K2.5"),
72
  ]
 
73
 
74
  def _extract_response_text(message):
75
  content = message.get('content', '') or ''
76
  reasoning = message.get('reasoning', '') or ''
77
+ return content.strip() or reasoning.strip() or ''
 
 
 
 
78
 
79
  def _extract_json_from_text(text):
80
  json_match = re.search(r'```(?:json)?\s*([\s\S]*?)\s*```', text)
81
+ if json_match: return json_match.group(1)
 
82
  json_match = re.search(r'\{[\s\S]*\}', text)
83
+ if json_match: return json_match.group()
 
84
  return None
85
 
86
  def _call_vlm(messages, timeout=180):
87
+ import requests
 
88
  hf_token = os.environ.get("HF_TOKEN", "")
89
+ if not hf_token: return None
 
90
  for model_id, provider, display_name in VISION_MODELS:
91
  try:
92
  url = f"https://router.huggingface.co/{provider}/v1/chat/completions"
 
97
  if response.status_code == 200:
98
  result = response.json()
99
  text = _extract_response_text(result['choices'][0]['message'])
100
+ if not text: continue
 
101
  json_str = _extract_json_from_text(text)
102
+ if not json_str: continue
 
103
  analysis = json.loads(json_str)
104
+ analysis['_model_used'] = display_name
105
  print(f"[VLM] OK: {display_name} detected {analysis.get('garment_type','?')}")
106
  return analysis
107
+ else: print(f"[VLM] {display_name}: HTTP {response.status_code}")
 
108
  except Exception as e:
109
+ print(f"[VLM] {display_name} failed: {e}"); continue
 
110
  return None
111
 
112
  def analyze_with_vlm(image):
113
  import base64
114
  from io import BytesIO
115
  hf_token = os.environ.get("HF_TOKEN", "")
116
+ if not hf_token: return None
 
117
  max_dim = 1024
118
  if max(image.size) > max_dim:
119
  ratio = max_dim / max(image.size)
 
142
  _current_analysis = {"data": None}
143
 
144
  def _generate_all_outputs(analysis):
 
145
  garment_type = analysis.get('garment_type', 'shirt')
146
  measurements = analysis.get('measurements', {})
147
  features = analysis.get('features', {})
148
  params = {**measurements, **features}
 
 
149
  pattern_pieces = get_pattern_pieces(garment_type, params)
 
 
150
  pattern_image, summary = generate_pattern_from_analysis(analysis)
 
 
151
  fig_3d = create_3d_figure(analysis, pattern_pieces=pattern_pieces)
 
152
  display = {k: v for k, v in analysis.items() if k != '_model_used'}
153
  model_info = f"\n\n*AI: {analysis.get('_model_used', 'Default')}*" if analysis.get('_model_used') else ""
154
  desc = analysis.get('description', 'No description')
 
160
  return None, None, "Please upload a garment image or select a type.", "{}", []
161
  analysis = None
162
  if image is not None:
163
+ try: analysis = analyze_with_vlm(image)
164
+ except Exception as e: print(f"VLM failed: {e}")
 
 
165
  if analysis is None:
166
  gt = garment_type_override.lower() if garment_type_override != "Auto-detect" else "shirt"
167
  analysis = get_default_analysis(gt)
 
178
  return None, None, f"Error: {e}", "{}", []
179
 
180
  def process_text(description):
181
+ if not description.strip(): return None, None, "Enter a description.", "{}", []
 
182
  analysis = None
183
  hf_token = os.environ.get("HF_TOKEN", "")
184
  if hf_token:
185
+ messages = [{"role": "user", "content": f"Based on this garment description, extract sewing pattern parameters.\n\nDescription: {description}\n\nReturn ONLY JSON with: garment_type, description, measurements (bust, waist, hip, shoulder_width, bodice_length, sleeve_length, skirt_length, pant_length, neckline_depth, neckline_width, bicep, wrist, cap_height, collar_height, flare), features (has_collar, collar_type, has_cuffs, has_pockets, pocket_type, has_hood, fit)."}]
 
 
 
 
186
  analysis = _call_vlm(messages, timeout=90)
187
  if analysis is None:
188
  desc_lower = description.lower()
189
  for gt in ['hoodie','jacket','coat','blazer','dress','skirt','pants','trousers','jeans','vest','shirt','blouse','top']:
190
  if gt in desc_lower:
191
+ analysis = get_default_analysis(gt); analysis['description'] = description; break
192
+ if analysis is None: analysis = get_default_analysis("shirt"); analysis['description'] = description
 
 
 
 
193
  _current_analysis["data"] = copy.deepcopy(analysis)
194
  try:
195
  p2d, p3d, summary, j = _generate_all_outputs(analysis)
196
  return p2d, p3d, summary, j, []
197
+ except Exception as e: return None, None, f"Error: {e}", "{}", []
 
198
 
199
  def process_manual(gt,bust,waist,hip,shoulder,bodice,sleeve,skirt,pant,neck,flare_c,collar,ctype,cuffs,pockets,hood,fit):
200
  analysis = {"garment_type":gt.lower(),"description":f"Custom {gt.lower()}","measurements":{"bust":bust,"waist":waist,"hip":hip,"shoulder_width":shoulder,"bodice_length":bodice,"sleeve_length":sleeve,"skirt_length":skirt,"pant_length":pant,"neckline_depth":neck,"neckline_width":7,"bicep":30,"wrist":18,"cap_height":14,"collar_height":5,"flare":flare_c},"features":{"has_collar":collar,"collar_type":ctype.lower(),"has_cuffs":cuffs,"has_pockets":pockets,"pocket_type":"patch","has_hood":hood,"fit":fit.lower()}}
 
202
  try:
203
  p2d, p3d, summary, j = _generate_all_outputs(analysis)
204
  return p2d, p3d, summary, j, []
205
+ except Exception as e: return None, None, f"Error: {e}", "{}", []
 
206
 
207
  def chat_edit(message, history):
208
+ if not message.strip(): return history, None, None, "Please enter an edit request.", "{}"
209
+ current = _current_analysis.get("data") or get_default_analysis("shirt")
210
+ _current_analysis["data"] = current
 
 
 
211
  current_clean = {k: v for k, v in current.items() if k != '_model_used'}
212
+ edit_prompt = EDIT_PROMPT_TEMPLATE.format(current_json=json.dumps(current_clean, indent=2), user_message=message)
 
213
  updated = None
214
+ if os.environ.get("HF_TOKEN", ""):
215
+ try: updated = _call_vlm([{"role": "user", "content": edit_prompt}], timeout=90)
216
+ except: pass
 
 
 
 
217
  if updated is None:
218
  updated = copy.deepcopy(current)
219
  msg_lower = message.lower()
220
+ if "long sleeve" in msg_lower: updated['measurements']['sleeve_length'] = 65
221
+ elif "short sleeve" in msg_lower: updated['measurements']['sleeve_length'] = 25
222
+ if "no collar" in msg_lower: updated['features']['has_collar'] = False; updated['features']['collar_type'] = 'none'
223
+ if "add collar" in msg_lower: updated['features']['has_collar'] = True; updated['features']['collar_type'] = 'standard'
224
+ if "add hood" in msg_lower: updated['features']['has_hood'] = True
225
+ if "no hood" in msg_lower: updated['features']['has_hood'] = False
226
+ if "oversized" in msg_lower: updated['features']['fit'] = 'oversized'; updated['measurements']['bust'] = updated['measurements'].get('bust', 96) + 10
227
+ if "fitted" in msg_lower: updated['features']['fit'] = 'fitted'
228
+ if "flare" in msg_lower: updated['measurements']['flare'] = max(updated['measurements'].get('flare', 0), 8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  updated['_model_used'] = 'Rule-based edit'
230
+ if 'garment_type' not in updated: updated['garment_type'] = current.get('garment_type', 'shirt')
 
231
  _current_analysis["data"] = copy.deepcopy(updated)
232
+ try: p2d, p3d, summary, j = _generate_all_outputs(updated)
233
+ except Exception as e: p2d, p3d, summary, j = None, None, f"Error: {e}", "{}"
234
+ ai_msg = f"Applied: {message}\n"
 
 
235
  changes = []
236
  for k in set(list(current.get('measurements',{}).keys()) + list(updated.get('measurements',{}).keys())):
237
  ov, nv = current.get('measurements',{}).get(k), updated.get('measurements',{}).get(k)
238
+ if ov != nv and ov is not None and nv is not None: changes.append(f" {k}: {ov} → {nv}")
 
239
  for k in set(list(current.get('features',{}).keys()) + list(updated.get('features',{}).keys())):
240
  ov, nv = current.get('features',{}).get(k), updated.get('features',{}).get(k)
241
+ if ov != nv: changes.append(f" {k}: {ov} {nv}")
242
+ ai_msg += ("\n".join(changes)) if changes else "No changes."
243
+ history = history or []; history.append((message, ai_msg))
 
244
  return history, p2d, p3d, summary, j
245
 
246
+ # ── Agentic Refinement ──────────────────────────────────────────────────────
247
+ def run_refinement(image, garment_type_override, max_iters):
248
+ """Run the agentic refinement loop."""
249
+ if image is None:
250
+ yield None, None, None, "Please upload a garment image.", "{}", None
251
+ return
252
+
253
+ # Step 1: Initial VLM analysis
254
+ analysis = None
255
+ try:
256
+ analysis = analyze_with_vlm(image)
257
+ except Exception as e:
258
+ print(f"VLM failed: {e}")
259
+
260
+ if analysis is None:
261
+ gt = garment_type_override.lower() if garment_type_override != "Auto-detect" else "shirt"
262
+ analysis = get_default_analysis(gt)
263
+
264
+ if garment_type_override != "Auto-detect":
265
+ analysis['garment_type'] = garment_type_override.lower()
266
+
267
+ # Generate function for the loop
268
+ def gen_fn(a):
269
+ return _generate_all_outputs(a)
270
+
271
+ # Run refinement loop
272
+ max_iters = int(max_iters)
273
+ result = refinement_loop(
274
+ original_image=image,
275
+ initial_analysis=analysis,
276
+ generate_fn=gen_fn,
277
+ max_iterations=max_iters,
278
+ target_composite=0.82,
279
+ plateau_patience=3,
280
+ lr=0.7,
281
+ )
282
+
283
+ # Build log markdown
284
+ log_lines = [f"## Refinement Results\n"]
285
+ log_lines.append(f"**Converged:** {'✅ Yes' if result['converged'] else '❌ No'}")
286
+ log_lines.append(f"**Iterations:** {result['total_iterations']}")
287
+ log_lines.append(f"**Best Score:** {result['best_score']:.4f}")
288
+ if result['scores']:
289
+ log_lines.append(f"**Score progression:** {' → '.join(f'{s:.3f}' for s in result['scores'])}")
290
+ log_lines.append("")
291
+
292
+ for step in result['history']:
293
+ it = step['iteration']
294
+ status = step.get('status', '?')
295
+ metrics = step.get('metrics', {})
296
+ log_lines.append(f"### Iteration {it} — {status}")
297
+ if metrics:
298
+ log_lines.append(f"SSIM={metrics.get('ssim',0):.3f} | Edge={metrics.get('edge_ssim',0):.3f} | Composite={metrics.get('composite',0):.3f}")
299
+ if step.get('new_best'):
300
+ log_lines.append("⭐ **New best!**")
301
+ diffs = step.get('vlm_differences', [])
302
+ if diffs:
303
+ log_lines.append("**Differences:** " + "; ".join(diffs[:3]))
304
+ adj = step.get('adjustments', {})
305
+ if adj:
306
+ log_lines.append("**Adjustments:** " + ", ".join(f"{k}={v}" for k, v in adj.items()))
307
+ reason = step.get('reason', '')
308
+ if reason:
309
+ log_lines.append(f"*{reason}*")
310
+ log_lines.append("")
311
+
312
+ log_md = "\n".join(log_lines)
313
+
314
+ # Get best outputs
315
+ best = result['best_analysis']
316
+ _current_analysis["data"] = copy.deepcopy(best)
317
+ try:
318
+ p2d, p3d, summary, j = _generate_all_outputs(best)
319
+ except:
320
+ p2d, p3d, summary, j = None, None, "Error generating final outputs", "{}"
321
+
322
+ # Get last projection
323
+ last_proj = None
324
+ for step in reversed(result['history']):
325
+ if 'projection' in step:
326
+ last_proj = step['projection']
327
+ break
328
+
329
+ yield p2d, p3d, last_proj, log_md, j, summary
330
+
331
+ # ── UI ──────────────────────────────────────────────────────────────────────
332
  CSS = """
333
  .main-header { text-align: center; margin-bottom: 20px; }
334
  .info-box { padding: 15px; border-radius: 10px; background: #f0f7ff; border: 1px solid #cce0ff; margin: 10px 0; }
 
336
  """
337
 
338
  with gr.Blocks(title="Garment Pattern Studio") as demo:
339
+ gr.HTML("""<div class="main-header">
 
340
  <h1>🧵 Garment Pattern Studio</h1>
341
+ <p style="font-size: 1.1em; color: #555;">Analyze garments, edit with chat, preview in 3D, refine with AI agent</p>
342
  </div>
343
  <div class="info-box">
344
+ <b>Powered by:</b> Qwen 3.5 · Gemma 4 · Kimi K2.5 via
345
  <a href="https://huggingface.co/docs/inference-providers">HF Inference Providers</a>
346
+ &nbsp;|&nbsp; <b>3D view built from actual 2D pattern pieces</b>
347
  </div>""")
348
 
349
+ with gr.Tab("📸 From Image"):
350
  with gr.Row():
351
  with gr.Column(scale=1):
352
  input_image = gr.Image(type="pil", label="Upload Garment Image", height=350)
 
357
  with gr.Column(): out_pattern_2d = gr.Image(label="2D Sewing Pattern", height=400)
358
  with gr.Column(): out_3d = gr.Plot(label="3D Garment Preview")
359
  out_summary = gr.Markdown(label="Pattern Summary")
360
+ with gr.Accordion("Raw JSON", open=False): out_json = gr.Code(language="json")
361
  analyze_btn.click(process_image, inputs=[input_image, garment_override], outputs=[out_pattern_2d, out_3d, out_summary, out_json])
362
 
363
+ with gr.Tab("✍️ From Text"):
364
  with gr.Row():
365
  with gr.Column(scale=1):
366
  text_input = gr.Textbox(label="Describe the garment", placeholder="e.g., A fitted A-line dress with cap sleeves", lines=3)
 
381
  with gr.Accordion("Raw JSON", open=False): txt_json = gr.Code(language="json")
382
  text_btn.click(process_text, inputs=[text_input], outputs=[txt_pattern_2d, txt_3d, txt_summary, txt_json])
383
 
384
+ with gr.Tab("📐 Manual"):
385
  with gr.Row():
386
  with gr.Column(scale=1):
387
  m_type = gr.Dropdown(choices=["Shirt","Dress","Skirt","Pants","Jacket","Hoodie","Vest"], value="Shirt", label="Garment Type")
388
  gr.Markdown("### Measurements (cm)")
389
+ with gr.Row(): m_bust = gr.Slider(70,130,value=92,step=1,label="Bust"); m_waist = gr.Slider(55,110,value=74,step=1,label="Waist")
390
+ with gr.Row(): m_hip = gr.Slider(75,130,value=96,step=1,label="Hip"); m_shoulder = gr.Slider(35,55,value=42,step=1,label="Shoulder")
391
+ with gr.Row(): m_bodice = gr.Slider(30,80,value=42,step=1,label="Bodice Length"); m_sleeve = gr.Slider(10,75,value=60,step=1,label="Sleeve Length")
392
+ with gr.Row(): m_skirt = gr.Slider(25,120,value=55,step=1,label="Skirt Length"); m_pant = gr.Slider(25,115,value=100,step=1,label="Pant Length")
393
+ with gr.Row(): m_neck = gr.Slider(3,25,value=8,step=1,label="Neckline Depth"); m_flare = gr.Slider(0,20,value=0,step=1,label="Hem Flare")
 
 
 
 
 
 
 
 
 
 
394
  gr.Markdown("### Features")
395
+ with gr.Row(): m_collar = gr.Checkbox(value=True,label="Collar"); m_ctype = gr.Dropdown(["Standard","Mandarin","Peter_pan"],value="Standard",label="Collar Type")
396
+ with gr.Row(): m_cuffs = gr.Checkbox(value=True,label="Cuffs"); m_pockets = gr.Checkbox(value=False,label="Pockets")
397
+ with gr.Row(): m_hood = gr.Checkbox(value=False,label="Hood"); m_fit = gr.Dropdown(["Fitted","Regular","Oversized","Loose"],value="Regular",label="Fit")
 
 
 
 
 
 
398
  manual_btn = gr.Button("Generate Pattern", variant="primary", size="lg")
399
  with gr.Column(scale=2):
400
  with gr.Row():
 
404
  with gr.Accordion("Raw JSON", open=False): man_json = gr.Code(language="json")
405
  manual_btn.click(process_manual, inputs=[m_type,m_bust,m_waist,m_hip,m_shoulder,m_bodice,m_sleeve,m_skirt,m_pant,m_neck,m_flare,m_collar,m_ctype,m_cuffs,m_pockets,m_hood,m_fit], outputs=[man_pattern_2d, man_3d, man_summary, man_json])
406
 
407
+ with gr.Tab("💬 Chat & Edit"):
408
+ gr.Markdown("### Edit pattern with natural language\nGenerate a pattern first, then refine here.")
409
  with gr.Row():
410
  with gr.Column(scale=1):
411
  chatbot = gr.Chatbot(label="Pattern Editor", height=400)
412
+ chat_input = gr.Textbox(label="Edit instruction", placeholder="e.g., Make sleeves longer, Add a hood", lines=2)
413
+ with gr.Row(): chat_send = gr.Button("Apply Edit", variant="primary"); chat_clear = gr.Button("Clear")
 
 
414
  with gr.Column(scale=2):
415
  with gr.Row():
416
+ with gr.Column(): chat_pattern_2d = gr.Image(label="Updated 2D", height=400)
417
+ with gr.Column(): chat_3d = gr.Plot(label="Updated 3D")
418
  chat_summary = gr.Markdown()
419
+ with gr.Accordion("JSON", open=False): chat_json = gr.Code(language="json")
420
  def clear_chat(): return [], None, None, "", "{}"
421
  chat_send.click(chat_edit, inputs=[chat_input, chatbot], outputs=[chatbot, chat_pattern_2d, chat_3d, chat_summary, chat_json])
422
  chat_input.submit(chat_edit, inputs=[chat_input, chatbot], outputs=[chatbot, chat_pattern_2d, chat_3d, chat_summary, chat_json])
423
  chat_clear.click(clear_chat, outputs=[chatbot, chat_pattern_2d, chat_3d, chat_summary, chat_json])
424
 
425
+ with gr.Tab("🔄 Agentic Refinement"):
426
+ gr.Markdown("""### Iterative Refinement Loop
427
+ Upload a garment image. The AI agent will:
428
+ 1. **Analyze** → extract initial pattern parameters
429
+ 2. **Generate** → create 2D pattern + 3D garment
430
+ 3. **Project** → render 3D to 2D front view
431
+ 4. **Compare** → measure similarity (SSIM + VLM visual comparison)
432
+ 5. **Refine** → VLM suggests parameter adjustments
433
+ 6. **Repeat** until convergence or max iterations
434
+
435
+ *Requires HF_TOKEN for VLM-powered refinement.*""")
436
+ with gr.Row():
437
+ with gr.Column(scale=1):
438
+ refine_image = gr.Image(type="pil", label="Upload Garment Image", height=300)
439
+ refine_type = gr.Dropdown(choices=["Auto-detect","Shirt","Dress","Skirt","Pants","Jacket","Hoodie","Vest"], value="Auto-detect", label="Garment Type")
440
+ refine_iters = gr.Slider(1, 15, value=5, step=1, label="Max Iterations")
441
+ refine_btn = gr.Button("🚀 Start Refinement", variant="primary", size="lg")
442
+ with gr.Column(scale=2):
443
+ with gr.Row():
444
+ with gr.Column(): refine_2d = gr.Image(label="Best 2D Pattern", height=350)
445
+ with gr.Column(): refine_proj = gr.Image(label="3D→2D Projection", height=350)
446
+ with gr.Row():
447
+ with gr.Column(): refine_3d = gr.Plot(label="Best 3D Preview")
448
+ with gr.Column(): refine_log = gr.Markdown(label="Refinement Log")
449
+ refine_summary = gr.Markdown()
450
+ with gr.Accordion("Best Parameters JSON", open=False): refine_json = gr.Code(language="json")
451
+
452
+ refine_btn.click(run_refinement,
453
+ inputs=[refine_image, refine_type, refine_iters],
454
+ outputs=[refine_2d, refine_3d, refine_proj, refine_log, refine_json, refine_summary])
455
+
456
  gr.HTML("""<div class="ref-box" style="margin-top: 20px;"><h4>Research References</h4><ul>
457
+ <li><b>ChatGarment</b> (2024) — VLM + dialogue for garment editing [<a href="https://arxiv.org/abs/2412.17811">Paper</a>]</li>
458
+ <li><b>NGL-Prompter</b> (2025) — Training-free VLM pattern estimation [<a href="https://arxiv.org/abs/2602.20700">Paper</a>]</li>
459
+ <li><b>RRVF</b> (2025) — Render-compare visual feedback loops [<a href="https://arxiv.org/abs/2507.20766">Paper</a>]</li>
460
+ <li><b>SceneAssistant</b> (2026) — Agentic VLM scene refinement [<a href="https://arxiv.org/abs/2603.12238">Paper</a>]</li>
461
  </ul></div>""")
462
 
463
  if __name__ == "__main__":