3rdaiOhpinFully commited on
Commit
ae62fae
·
1 Parent(s): 03a7340

Deploy v12 Primeo-fused single-space mapper

Browse files
README.md CHANGED
@@ -1,14 +1,63 @@
1
  ---
2
- title: Soul Threading
3
- emoji: 🔥
4
  colorFrom: purple
5
  colorTo: blue
6
  sdk: gradio
7
- sdk_version: 6.19.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
11
- short_description: 'AOP Image2Garment Design Get Production LVL AOP Prototypes '
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Soul Threading v12 Primeo-Fused
3
+ emoji: 🧵
4
  colorFrom: purple
5
  colorTo: blue
6
  sdk: gradio
 
 
7
  app_file: app.py
8
  pinned: false
9
+ license: mit
10
  ---
11
 
12
+ # Soul Threading v12 Primeo-Fused
13
+
14
+ One-platform Hugging Face / ZeroGPU-ready AOP garment mapper.
15
+
16
+ This version fuses the best parts of Primeo's pipeline design into the v11 production mapper.
17
+
18
+ ## What it does
19
+
20
+ 1. Upload artwork.
21
+ 2. Upload AOP template ZIP.
22
+ 3. Scan only white printable areas from template PNGs.
23
+ 4. Build multiple divergent layout candidates.
24
+ 5. Score them through a Quality Tribunal.
25
+ 6. Render clean transparent print PNGs.
26
+ 7. Enforce pocket/flap/overlay continuity.
27
+ 8. Export a production ZIP.
28
+
29
+ ## Locked rules
30
+
31
+ ```txt
32
+ Only white printable template areas become pieces.
33
+ Colored seam / bleed / blur / safe lines are restrictions, never pieces.
34
+ Front body receives the hero by default.
35
+ Back, hood, sleeves, trim, labels receive support crops.
36
+ Pocket/flap/overlay inherits rendered front underlay.
37
+ No production guide lines appear in exported PNGs.
38
+ ```
39
+
40
+ ## Files
41
+
42
+ ```txt
43
+ app.py
44
+ requirements.txt
45
+ README.md
46
+ memory/
47
+ docs/
48
+ tests/
49
+ deploy_to_hf.ps1
50
+ ```
51
+
52
+ ## ZeroGPU
53
+
54
+ The pipeline is decorated with `@spaces.GPU`, which keeps it ready for ZeroGPU model upgrades. The current v12 core remains CPU-safe and deterministic for production export.
55
+
56
+ Future model slots can be added inside this same Space:
57
+
58
+ ```txt
59
+ Grounding DINO
60
+ SAM/SAM2
61
+ Florence OCR
62
+ VLM art director
63
+ ```
app.py CHANGED
@@ -1,60 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import json
2
- from typing import Dict, Any, List, Tuple
 
 
 
 
 
3
 
4
  import cv2
5
- import numpy as np
6
- from PIL import Image
7
  import gradio as gr
 
 
 
 
 
 
 
8
 
9
  try:
10
  import spaces
11
  except Exception:
12
- class spaces:
13
  @staticmethod
14
  def GPU(*args, **kwargs):
15
  def deco(fn):
16
  return fn
17
  return deco
18
 
19
- try:
20
- import torch
21
- from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection, pipeline
22
- except Exception:
23
- torch = None
24
- AutoProcessor = None
25
- AutoModelForZeroShotObjectDetection = None
26
- pipeline = None
27
-
28
 
29
- APP_VERSION = "soul-threading-hf-worker-v7-dino-cv-pillow"
30
- GROUNDING_DINO_MODEL_ID = "IDEA-Research/grounding-dino-tiny"
31
- OWLV2_MODEL_ID = "google/owlv2-base-patch16-ensemble"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- _gd_processor = None
34
- _gd_model = None
35
- _owl_pipe = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- DEFAULT_PROMPTS = [
38
- "person", "human", "face", "head", "body", "torso",
39
- "animal", "main character", "primary subject", "object",
40
- "logo", "text", "fire", "smoke", "vehicle", "building",
41
- "abstract shape", "background"
42
- ]
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- def clamp(v, lo, hi):
46
- return max(lo, min(hi, v))
 
 
 
 
 
 
47
 
 
 
 
 
 
48
 
49
- def pil_from_input(image):
50
- if image is None:
51
- raise ValueError("No image received.")
52
- if isinstance(image, Image.Image):
53
- return image.convert("RGB")
54
- return Image.fromarray(image).convert("RGB")
55
 
 
 
 
56
 
57
- def cv_focal_scan(img: Image.Image) -> Dict[str, Any]:
58
  arr = np.array(img.convert("RGB"))
59
  h, w = arr.shape[:2]
60
  gray = cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY)
@@ -63,332 +246,553 @@ def cv_focal_scan(img: Image.Image) -> Dict[str, Any]:
63
  sat = hsv[:, :, 1]
64
  val = hsv[:, :, 2]
65
 
66
- heat = (edges.astype(np.float32) / 255.0) * 0.65
67
- heat += (sat.astype(np.float32) / 255.0) * 0.25
68
  heat += ((255 - val).astype(np.float32) / 255.0) * 0.10
69
  heat = cv2.GaussianBlur(heat, (31, 31), 0)
70
 
71
  ys, xs = np.where(heat > np.percentile(heat, 86))
72
- if len(xs) < 25:
73
- return {
74
- "label": "cv_center_fallback",
75
- "confidence": 0.15,
76
- "bbox_xyxy": [int(w * 0.20), int(h * 0.15), int(w * 0.80), int(h * 0.90)],
77
- "center_xy_norm": [0.5, 0.5],
78
- "method": "opencv_center_fallback"
79
- }
80
-
81
- x1 = int(np.percentile(xs, 4))
82
- y1 = int(np.percentile(ys, 4))
83
- x2 = int(np.percentile(xs, 96))
84
- y2 = int(np.percentile(ys, 96))
85
-
86
- if (x2 - x1) < w * 0.10 or (y2 - y1) < h * 0.10:
87
- x1, y1, x2, y2 = int(w * 0.20), int(h * 0.15), int(w * 0.80), int(h * 0.90)
88
 
89
  return {
90
- "label": "cv_saliency",
91
- "confidence": 0.35,
92
- "bbox_xyxy": [x1, y1, x2, y2],
93
- "center_xy_norm": [round(((x1 + x2) / 2) / max(w, 1), 4), round(((y1 + y2) / 2) / max(h, 1), 4)],
94
- "method": "opencv_edges_saturation_heatmap"
95
  }
96
 
97
 
98
- def normalize_labels(query_text: str) -> List[str]:
99
- if not query_text or not query_text.strip():
100
- return DEFAULT_PROMPTS
101
- raw = query_text.replace("\n", ",").replace(".", ",").split(",")
102
- labels = [x.strip() for x in raw if x.strip()]
103
- return labels or DEFAULT_PROMPTS
104
-
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
- def labels_to_grounding_text(labels: List[str]) -> str:
107
- return ". ".join(labels) + "."
108
 
 
 
 
 
109
 
110
- def box_area(box):
111
- x1, y1, x2, y2 = box
112
- return max(0, x2 - x1) * max(0, y2 - y1)
113
-
114
-
115
- def clean_detections(dets: List[Dict[str, Any]], img_size: Tuple[int, int]) -> List[Dict[str, Any]]:
116
- w, h = img_size
117
- clean = []
118
- for d in dets:
119
- box = [int(round(v)) for v in d.get("bbox_xyxy", [0, 0, 0, 0])]
120
- x1, y1, x2, y2 = box
121
- x1 = clamp(x1, 0, max(w - 1, 0))
122
- y1 = clamp(y1, 0, max(h - 1, 0))
123
- x2 = clamp(x2, x1 + 1, w)
124
- y2 = clamp(y2, y1 + 1, h)
125
- area_ratio = box_area([x1, y1, x2, y2]) / max(w * h, 1)
126
- if area_ratio < 0.002 or area_ratio > 0.96:
127
- continue
128
- clean.append({
129
- "label": str(d.get("label", "object")),
130
- "confidence": float(d.get("confidence", 0.0)),
131
- "bbox_xyxy": [x1, y1, x2, y2],
132
- "center_xy_norm": [
133
- round(((x1 + x2) / 2) / max(w, 1), 4),
134
- round(((y1 + y2) / 2) / max(h, 1), 4)
135
- ],
136
- "area_ratio": round(area_ratio, 5),
137
- "method": d.get("method", "unknown")
138
- })
139
- clean.sort(key=lambda x: (x["confidence"], x["area_ratio"]), reverse=True)
140
- return clean[:12]
141
-
142
-
143
- def load_grounding_dino():
144
- global _gd_processor, _gd_model
145
- if AutoProcessor is None or AutoModelForZeroShotObjectDetection is None or torch is None:
146
- raise RuntimeError("transformers/torch not available")
147
- if _gd_processor is None or _gd_model is None:
148
- _gd_processor = AutoProcessor.from_pretrained(GROUNDING_DINO_MODEL_ID)
149
- _gd_model = AutoModelForZeroShotObjectDetection.from_pretrained(GROUNDING_DINO_MODEL_ID)
150
- device = "cuda" if torch.cuda.is_available() else "cpu"
151
- _gd_model.to(device)
152
- _gd_model.eval()
153
- return _gd_processor, _gd_model
154
-
155
-
156
- def run_grounding_dino(img: Image.Image, labels: List[str], box_threshold=0.25, text_threshold=0.20) -> List[Dict[str, Any]]:
157
- processor, model = load_grounding_dino()
158
- device = next(model.parameters()).device
159
- text = labels_to_grounding_text(labels)
160
-
161
- inputs = processor(images=img, text=text, return_tensors="pt")
162
- inputs = {k: v.to(device) if hasattr(v, "to") else v for k, v in inputs.items()}
163
-
164
- with torch.no_grad():
165
- outputs = model(**inputs)
166
-
167
- target_sizes = torch.tensor([img.size[::-1]], device=device)
168
-
169
- if hasattr(processor, "post_process_grounded_object_detection"):
170
- results = processor.post_process_grounded_object_detection(
171
- outputs,
172
- inputs.get("input_ids"),
173
- box_threshold=box_threshold,
174
- text_threshold=text_threshold,
175
- target_sizes=target_sizes
176
- )[0]
177
- else:
178
- results = processor.post_process_object_detection(
179
- outputs,
180
- threshold=box_threshold,
181
- target_sizes=target_sizes
182
- )[0]
183
-
184
- dets = []
185
- boxes = results.get("boxes", [])
186
- scores = results.get("scores", [])
187
- result_labels = results.get("labels", [])
188
-
189
- for i in range(len(boxes)):
190
- label = result_labels[i]
191
- if not isinstance(label, str):
192
- try:
193
- label = labels[int(label)]
194
- except Exception:
195
- label = str(label)
196
- score = scores[i].detach().cpu().item() if hasattr(scores[i], "detach") else scores[i]
197
- box = boxes[i].detach().cpu().tolist() if hasattr(boxes[i], "detach") else boxes[i]
198
- dets.append({
199
- "label": label,
200
- "confidence": float(score),
201
- "bbox_xyxy": box,
202
- "method": "grounding_dino_tiny_transformers"
203
- })
204
- return dets
205
-
206
-
207
- def load_owlv2():
208
- global _owl_pipe
209
- if pipeline is None or torch is None:
210
- raise RuntimeError("transformers pipeline/torch not available")
211
- if _owl_pipe is None:
212
- device = 0 if torch.cuda.is_available() else -1
213
- _owl_pipe = pipeline(
214
- task="zero-shot-object-detection",
215
- model=OWLV2_MODEL_ID,
216
- device=device
217
- )
218
- return _owl_pipe
219
-
220
-
221
- def run_owlv2(img: Image.Image, labels: List[str], threshold=0.08) -> List[Dict[str, Any]]:
222
- pipe = load_owlv2()
223
- preds = pipe(img, candidate_labels=labels, threshold=threshold)
224
- dets = []
225
- for p in preds[:12]:
226
- b = p.get("box", {})
227
- dets.append({
228
- "label": p.get("label", "object"),
229
- "confidence": float(p.get("score", 0.0)),
230
- "bbox_xyxy": [
231
- int(b.get("xmin", 0)),
232
- int(b.get("ymin", 0)),
233
- int(b.get("xmax", 0)),
234
- int(b.get("ymax", 0))
235
- ],
236
- "method": "owlv2_transformers_pipeline"
237
- })
238
- return dets
239
 
240
 
241
- def choose_primary(detections: List[Dict[str, Any]], cv_subject: Dict[str, Any]) -> Dict[str, Any]:
242
- priority_words = ["person", "human", "face", "head", "body", "torso", "main character", "primary subject"]
243
- if detections:
244
- def score(d):
245
- label = d["label"].lower()
246
- priority = 0.25 if any(w in label for w in priority_words) else 0
247
- text_penalty = -0.25 if "text" in label or "logo" in label else 0
248
- return d["confidence"] + priority + text_penalty + min(d.get("area_ratio", 0), 0.25)
249
- return max(detections, key=score)
250
- return cv_subject
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
252
 
253
- def make_layout_plan(primary: Dict[str, Any]) -> Dict[str, Any]:
254
- cx, cy = primary.get("center_xy_norm", [0.5, 0.5])
255
- cx = float(cx)
256
- cy = float(cy)
257
- front_cx = clamp(cx, 0.38, 0.58)
258
- front_cy = clamp(cy, 0.38, 0.62)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
 
260
- return {
261
- "front_body": {
262
- "center": [round(front_cx, 4), round(front_cy, 4)],
263
- "zoom": 1.00,
264
- "intent": "hold primary subject cleanly inside body panel"
265
- },
266
- "back_body": {
267
- "center": [0.72, 0.50],
268
- "zoom": 1.12,
269
- "intent": "supporting environment, not random duplicate face"
270
- },
271
- "hood": {
272
- "center": [0.50, 0.22],
273
- "zoom": 1.18,
274
- "intent": "upper atmosphere / background detail"
275
- },
276
- "left_sleeve": {
277
- "center": [0.28, 0.52],
278
- "zoom": 1.16,
279
- "intent": "left-side color motion"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  },
281
- "right_sleeve": {
282
- "center": [0.76, 0.52],
283
- "zoom": 1.16,
284
- "intent": "right-side color motion"
285
- },
286
- "kangaroo_pocket": {
287
- "center": [round(front_cx, 4), 0.72],
288
- "zoom": 1.06,
289
- "intent": "front-lower underlay crop until exact assembly coordinates exist"
290
- },
291
- "trim": {
292
- "center": [0.50, 0.85],
293
- "zoom": 1.30,
294
- "intent": "texture strip only"
295
- }
296
- }
297
 
 
 
 
 
 
 
298
 
299
- def draw_debug(img: Image.Image, detections: List[Dict[str, Any]], primary: Dict[str, Any]) -> Image.Image:
300
- arr = np.array(img.copy().convert("RGB"))
301
- for d in detections[:8]:
302
- x1, y1, x2, y2 = d["bbox_xyxy"]
303
- cv2.rectangle(arr, (x1, y1), (x2, y2), (255, 255, 255), 3)
304
- cv2.putText(arr, d["label"][:22], (x1, max(22, y1 - 6)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
305
- if primary:
306
- x1, y1, x2, y2 = primary["bbox_xyxy"]
307
- cv2.rectangle(arr, (x1, y1), (x2, y2), (0, 255, 0), 5)
308
- return Image.fromarray(arr)
309
-
310
-
311
- @spaces.GPU(duration=90)
312
- def analyze(image, query_text="", prefer_model="GroundingDINO first"):
313
- img = pil_from_input(image)
314
- labels = normalize_labels(query_text)
315
- cv_subject = cv_focal_scan(img)
316
-
317
- model_status = []
318
- detections = []
319
-
320
- if prefer_model in ["GroundingDINO first", "GroundingDINO only"]:
321
- try:
322
- detections = clean_detections(run_grounding_dino(img, labels), img.size)
323
- model_status.append(f"GroundingDINO ok: {len(detections)} detections")
324
- except Exception as e:
325
- model_status.append("GroundingDINO failed: " + str(e))
326
- if prefer_model == "GroundingDINO only":
327
- detections = []
328
-
329
- if not detections and prefer_model in ["GroundingDINO first", "OWLv2 fallback", "OWLv2 only"]:
330
- try:
331
- detections = clean_detections(run_owlv2(img, labels), img.size)
332
- model_status.append(f"OWLv2 ok: {len(detections)} detections")
333
- except Exception as e:
334
- model_status.append("OWLv2 failed: " + str(e))
335
-
336
- primary = choose_primary(detections, cv_subject)
337
- layout_plan = make_layout_plan(primary)
338
-
339
- result = {
340
- "version": APP_VERSION,
341
- "models": {
342
- "grounding_dino": GROUNDING_DINO_MODEL_ID,
343
- "owlv2_fallback": OWLV2_MODEL_ID,
344
- "opencv_fallback": "edges + saturation heatmap",
345
- "pillow": "image loading/cropping"
346
- },
347
- "model_status": model_status,
348
- "source_size": list(img.size),
349
- "query_labels": labels,
350
- "primary_subject": primary,
351
- "objects": detections,
352
- "cv_fallback_subject": cv_subject,
353
- "layout_plan": layout_plan,
354
- "mapper_contract": {
355
- "use_this_for": "focal detection and crop planning only",
356
- "do_not_use_this_for": "final print pixels or garment shape extraction",
357
- "final_print_rule": "local mapper clips selected artwork section to clean garment-piece mask with transparent outside"
358
- }
359
- }
360
 
361
- debug = draw_debug(img, detections, primary)
362
- return json.dumps(result, indent=2), debug
363
 
 
 
 
364
 
365
- with gr.Blocks(title="Soul Threading AI Layout Worker v7") as demo:
366
  gr.Markdown(
367
  """
368
- # Soul Threading AI Layout Worker v7
369
 
370
- GroundingDINO → OWLv2 fallback → OpenCV/Pillow fallback.
371
 
372
- This Space analyzes the uploaded artwork and returns layout JSON for the garment mapper.
373
- It does **not** export final print pieces. The main mapper does that with deterministic template masks.
374
- """
 
 
 
 
 
 
375
  )
376
- with gr.Row():
377
- image = gr.Image(type="numpy", label="Artwork")
378
- with gr.Column():
379
- query = gr.Textbox(
380
- label="Detection prompts",
381
- value=", ".join(DEFAULT_PROMPTS),
382
- lines=5
383
- )
384
- prefer = gr.Dropdown(
385
- choices=["GroundingDINO first", "GroundingDINO only", "OWLv2 fallback", "OWLv2 only"],
386
- value="GroundingDINO first",
387
- label="Model route"
388
- )
389
- btn = gr.Button("Analyze artwork")
390
- json_out = gr.Textbox(label="Layout JSON", lines=28)
391
- debug_img = gr.Image(label="Detection debug preview")
392
- btn.click(analyze, inputs=[image, query, prefer], outputs=[json_out, debug_img], api_name="analyze")
393
-
394
- demo.queue(max_size=16).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Soul Threading HF Space v12 Primeo-Fused
3
+
4
+ Single-platform Hugging Face / ZeroGPU-ready Gradio app.
5
+
6
+ Fuses:
7
+ - v11 white-only real-template scanner
8
+ - v11 no-hero-spam role-safe composition
9
+ - v11 pocket/flap/overlay underlay continuity
10
+ - Primeo-style pipeline objects, warnings, quality score, productionReady flag
11
+ - Divergent layout brancher + Quality Tribunal
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
  import json
17
+ import math
18
+ import tempfile
19
+ import zipfile
20
+ from dataclasses import asdict, dataclass, field
21
+ from pathlib import Path
22
+ from typing import Any, Dict, List, Optional, Tuple
23
 
24
  import cv2
 
 
25
  import gradio as gr
26
+ import numpy as np
27
+ from PIL import Image, ImageDraw
28
+
29
+
30
+ APP_VERSION = "soul-threading-hf-space-v12-primeo-fused"
31
+ DEFAULT_BRANCH_COUNT = 4
32
+
33
 
34
  try:
35
  import spaces
36
  except Exception:
37
+ class spaces: # type: ignore
38
  @staticmethod
39
  def GPU(*args, **kwargs):
40
  def deco(fn):
41
  return fn
42
  return deco
43
 
 
 
 
 
 
 
 
 
 
44
 
45
+ # =============================================================================
46
+ # Primeo-inspired pipeline data shapes
47
+ # =============================================================================
48
+
49
+ @dataclass
50
+ class BoundingBox:
51
+ x1: float
52
+ y1: float
53
+ x2: float
54
+ y2: float
55
+
56
+ @property
57
+ def width(self) -> float:
58
+ return self.x2 - self.x1
59
+
60
+ @property
61
+ def height(self) -> float:
62
+ return self.y2 - self.y1
63
+
64
+ def to_xyxy(self) -> List[float]:
65
+ return [self.x1, self.y1, self.x2, self.y2]
66
+
67
+
68
+ @dataclass
69
+ class PiecePlan:
70
+ piece_id: str
71
+ role: str
72
+ crop_center: List[float]
73
+ zoom: float
74
+ protected_regions: List[str] = field(default_factory=list)
75
+ avoid_regions: List[str] = field(default_factory=list)
76
+ reason: str = ""
77
+ continuity_parent: Optional[str] = None
78
+ composition_mode: str = "role_safe_crop"
79
+
80
+
81
+ @dataclass
82
+ class LayoutCandidate:
83
+ candidate_id: str
84
+ description: str
85
+ piece_plans: List[PiecePlan]
86
+ score: float = 0.0
87
+ warnings: List[str] = field(default_factory=list)
88
+ production_ready: bool = False
89
+
90
+
91
+ @dataclass
92
+ class PipelineOutput:
93
+ version: str
94
+ selected_candidate_id: str
95
+ production_ready: bool
96
+ quality_score: float
97
+ status_message: str
98
+ warnings: List[str]
99
+ files: Dict[str, Any]
100
+ analysis: Dict[str, Any]
101
+ selected_plan: Dict[str, Any]
102
+ all_candidates: List[Dict[str, Any]]
103
+ scan_reports: List[Dict[str, Any]]
104
+ piece_reports: List[Dict[str, Any]]
105
+
106
+
107
+ # =============================================================================
108
+ # Utility
109
+ # =============================================================================
110
+
111
+ def safe_name(name: str) -> str:
112
+ return "".join(c if c.isalnum() or c in "._-" else "_" for c in name).strip("_") or "piece"
113
+
114
+
115
+ def odd(n: int) -> int:
116
+ return n if n % 2 else n + 1
117
+
118
+
119
+ def close_kernel(width: int, height: int) -> int:
120
+ longest = max(width, height)
121
+ if longest >= 7000:
122
+ return 41
123
+ if longest >= 5000:
124
+ return 35
125
+ if longest >= 3000:
126
+ return 25
127
+ if longest >= 1500:
128
+ return 15
129
+ return 7
130
+
131
+
132
+ def image_to_rgb_white_bg(path_or_img: Any) -> Image.Image:
133
+ img = Image.open(path_or_img).convert("RGBA") if not isinstance(path_or_img, Image.Image) else path_or_img.convert("RGBA")
134
+ bg = Image.new("RGBA", img.size, (255, 255, 255, 255))
135
+ bg.alpha_composite(img)
136
+ return bg.convert("RGB")
137
+
138
+
139
+ # =============================================================================
140
+ # White-only template scanner
141
+ # =============================================================================
142
+
143
+ def get_white_only_mask(template_path: Path) -> Tuple[np.ndarray, Dict[str, Any]]:
144
+ """
145
+ The user rule:
146
+ only the white printable area marked off by colored seam/bleed/blur/safe lines is usable.
147
+ Colored lines are restrictions, never pieces.
148
+ """
149
+ img = Image.open(template_path).convert("RGBA")
150
+ arr = np.array(img)
151
+ rgb = arr[:, :, :3]
152
+ h, w = rgb.shape[:2]
153
+
154
+ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
155
+ hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
156
+ sat = hsv[:, :, 1]
157
+ val = hsv[:, :, 2]
158
 
159
+ white = (r >= 238) & (g >= 238) & (b >= 238) & (sat <= 35) & (val >= 238)
160
+ mask = white.astype(np.uint8) * 255
161
+ raw_ratio = float(white.mean())
162
+
163
+ # If full background is white, drop edge-connected background.
164
+ if raw_ratio > 0.70:
165
+ flood = mask.copy()
166
+ flood_mask = np.zeros((h + 2, w + 2), np.uint8)
167
+ cv2.floodFill(flood, flood_mask, (0, 0), 0)
168
+ mask = flood
169
+
170
+ # Close tiny guide/text holes inside the white printable region.
171
+ # This does NOT admit colored guide lines because the seed mask is white-only.
172
+ k = odd(close_kernel(w, h))
173
+ mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((k, k), np.uint8), iterations=1)
174
+ mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8), iterations=1)
175
+
176
+ return mask, {
177
+ "template": template_path.name,
178
+ "canvas_size": [int(w), int(h)],
179
+ "white_ratio_before_repair": round(raw_ratio, 6),
180
+ "white_ratio_after_repair": round(float((mask > 0).mean()), 6),
181
+ "scanner_rule": "white_printable_area_only",
182
+ "colored_lines_are_pieces": False,
183
+ "guide_lines_exported": False,
184
+ "close_kernel_px": int(k),
185
+ }
186
 
 
 
 
 
 
 
187
 
188
+ def extract_components(template_path: Path) -> Tuple[int, int, List[Dict[str, Any]], Dict[str, Any]]:
189
+ mask, report = get_white_only_mask(template_path)
190
+ h, w = mask.shape
191
+ n, labels, stats, _ = cv2.connectedComponentsWithStats(mask, 8)
192
+
193
+ comps: List[Dict[str, Any]] = []
194
+ rejected: List[Dict[str, Any]] = []
195
+
196
+ for i in range(1, n):
197
+ x, y, cw, ch, area = [int(v) for v in stats[i]]
198
+ area_ratio = area / max(w * h, 1)
199
+ density = area / max(cw * ch, 1)
200
+ reason: Optional[str] = None
201
+
202
+ if area_ratio < 0.0015:
203
+ reason = "too_small"
204
+ elif cw < 80 or ch < 80:
205
+ reason = "too_thin"
206
+ elif density < 0.18:
207
+ reason = "too_sparse"
208
+ elif area_ratio > 0.92:
209
+ reason = "likely_background"
210
+
211
+ if reason:
212
+ rejected.append({
213
+ "bbox": [x, y, cw, ch],
214
+ "area_ratio": round(area_ratio, 6),
215
+ "density": round(density, 4),
216
+ "reason": reason,
217
+ })
218
+ continue
219
 
220
+ comps.append({
221
+ "component_id": f"shape_{i:02d}",
222
+ "bbox": [x, y, cw, ch],
223
+ "mask": (labels == i).astype(np.uint8) * 255,
224
+ "area": int(area),
225
+ "area_ratio": round(area_ratio, 6),
226
+ "density": round(density, 4),
227
+ })
228
 
229
+ comps.sort(key=lambda c: (c["bbox"][1], c["bbox"][0]))
230
+ report["component_count"] = len(comps)
231
+ report["rejected_count"] = len(rejected)
232
+ report["rejected_examples"] = rejected[:20]
233
+ return w, h, comps, report
234
 
 
 
 
 
 
 
235
 
236
+ # =============================================================================
237
+ # Artwork analysis
238
+ # =============================================================================
239
 
240
+ def cv_subject_box(img: Image.Image) -> Dict[str, Any]:
241
  arr = np.array(img.convert("RGB"))
242
  h, w = arr.shape[:2]
243
  gray = cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY)
 
246
  sat = hsv[:, :, 1]
247
  val = hsv[:, :, 2]
248
 
249
+ heat = (edges.astype(np.float32) / 255.0) * 0.60
250
+ heat += (sat.astype(np.float32) / 255.0) * 0.30
251
  heat += ((255 - val).astype(np.float32) / 255.0) * 0.10
252
  heat = cv2.GaussianBlur(heat, (31, 31), 0)
253
 
254
  ys, xs = np.where(heat > np.percentile(heat, 86))
255
+ if len(xs) < 30:
256
+ box = [int(w * 0.25), int(h * 0.15), int(w * 0.75), int(h * 0.85)]
257
+ else:
258
+ box = [
259
+ int(np.percentile(xs, 4)),
260
+ int(np.percentile(ys, 4)),
261
+ int(np.percentile(xs, 96)),
262
+ int(np.percentile(ys, 96)),
263
+ ]
264
+
265
+ x1, y1, x2, y2 = box
266
+ cx = ((x1 + x2) / 2) / max(w, 1)
267
+ cy = ((y1 + y2) / 2) / max(h, 1)
268
+
269
+ # Rough text map from long horizontal high-contrast components.
270
+ text_risk = detect_text_like_regions(arr)
271
 
272
  return {
273
+ "bbox_xyxy": box,
274
+ "center_xy_norm": [round(cx, 4), round(cy, 4)],
275
+ "method": "opencv_saliency",
276
+ "text_like_regions": text_risk,
 
277
  }
278
 
279
 
280
+ def detect_text_like_regions(rgb: np.ndarray) -> List[Dict[str, Any]]:
281
+ gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
282
+ edges = cv2.Canny(gray, 80, 180)
283
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 5))
284
+ joined = cv2.dilate(edges, kernel, iterations=1)
285
+ n, labels, stats, _ = cv2.connectedComponentsWithStats(joined, 8)
286
+ h, w = gray.shape[:2]
287
+ regs = []
288
+ for i in range(1, n):
289
+ x, y, cw, ch, area = [int(v) for v in stats[i]]
290
+ if area < 300:
291
+ continue
292
+ aspect = cw / max(ch, 1)
293
+ if aspect >= 3.0 and cw > w * 0.08 and ch < h * 0.18:
294
+ regs.append({
295
+ "bbox_xyxy_norm": [round(x/w, 4), round(y/h, 4), round((x+cw)/w, 4), round((y+ch)/h, 4)],
296
+ "aspect": round(aspect, 2),
297
+ "reason": "text_like_horizontal_component",
298
+ })
299
+ return regs[:12]
300
 
 
 
301
 
302
+ def analyze_artwork(img: Image.Image, focal_hint: str = "") -> Dict[str, Any]:
303
+ subject = cv_subject_box(img)
304
+ cx, cy = subject["center_xy_norm"]
305
+ front_center = [float(np.clip(cx, 0.40, 0.56)), float(np.clip(cy, 0.34, 0.58))]
306
 
307
+ return {
308
+ "version": APP_VERSION,
309
+ "source_size": list(img.size),
310
+ "focal_hint": focal_hint,
311
+ "primary_subject": subject,
312
+ "composition_law": "hero_front_only; abstract_support_elsewhere; pocket_inherits_front_underlay",
313
+ "zones": {
314
+ "front_hero": {"center": front_center, "zoom": 1.05},
315
+ "front_hero_tight": {"center": front_center, "zoom": 1.22},
316
+ "back_atmosphere": {"center": [0.72, 0.48], "zoom": 1.28},
317
+ "back_wide": {"center": [0.52, 0.50], "zoom": 1.02},
318
+ "hood_atmosphere_left": {"center": [0.25, 0.20], "zoom": 1.38},
319
+ "hood_atmosphere_right": {"center": [0.78, 0.22], "zoom": 1.38},
320
+ "sleeve_left_motion": {"center": [0.22, 0.55], "zoom": 1.40},
321
+ "sleeve_right_motion": {"center": [0.82, 0.56], "zoom": 1.40},
322
+ "trim_texture": {"center": [0.50, 0.88], "zoom": 1.75},
323
+ "label_texture": {"center": [0.50, 0.18], "zoom": 2.20},
324
+ },
325
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
 
328
+ # =============================================================================
329
+ # Template and role handling
330
+ # =============================================================================
331
+
332
+ def classify_piece(template_name: str, component_index: int, bbox: List[int], canvas_size: Tuple[int, int]) -> str:
333
+ n = template_name.lower()
334
+ if "front" in n:
335
+ return "front_body" if component_index == 0 else "trim"
336
+ if "back" in n:
337
+ return "back_body" if component_index == 0 else "trim"
338
+ if "hood" in n:
339
+ return "hood"
340
+ if "sleeve" in n:
341
+ return "sleeve" if component_index < 2 else "trim"
342
+ if "pocket" in n or "kangaroo" in n:
343
+ return "overlay_pocket"
344
+ if any(word in n for word in ["flap", "placket", "overlay", "guard", "welt"]):
345
+ return "overlay"
346
+ if "label" in n:
347
+ return "inside_label"
348
+
349
+ # Fallback geometry hints.
350
+ _, _, pw, ph = bbox
351
+ ratio = pw / max(ph, 1)
352
+ if ratio > 1.5 and ph < canvas_size[1] * 0.25:
353
+ return "trim"
354
+ return "garment_piece"
355
+
356
+
357
+ def template_files_from_zip(template_zip: str, work: Path) -> List[Path]:
358
+ tdir = work / "template"
359
+ tdir.mkdir(parents=True, exist_ok=True)
360
+ with zipfile.ZipFile(template_zip, "r") as z:
361
+ z.extractall(tdir)
362
+
363
+ files = [
364
+ p for p in tdir.rglob("*")
365
+ if p.suffix.lower() in [".png", ".jpg", ".jpeg", ".webp"]
366
+ and "__macosx" not in str(p).lower()
367
+ ]
368
+
369
+ def sort_key(p: Path):
370
+ n = p.name.lower()
371
+ if "front" in n: return (0, n)
372
+ if "back" in n: return (1, n)
373
+ if "hood" in n: return (2, n)
374
+ if "sleeve" in n: return (3, n)
375
+ if "pocket" in n or "kangaroo" in n: return (4, n)
376
+ if "label" in n: return (5, n)
377
+ return (9, n)
378
+
379
+ return sorted(files, key=sort_key)
380
+
381
+
382
+ # =============================================================================
383
+ # Divergent brancher and quality tribunal
384
+ # =============================================================================
385
+
386
+ def build_candidate(candidate_id: str, description: str, roles: List[Tuple[str, str]], analysis: Dict[str, Any]) -> LayoutCandidate:
387
+ z = analysis["zones"]
388
+ piece_plans: List[PiecePlan] = []
389
+
390
+ for piece_key, role in roles:
391
+ if role == "front_body":
392
+ zone = "front_hero_tight" if candidate_id == "hero_tight" else "front_hero"
393
+ plan = PiecePlan(piece_key, role, z[zone]["center"], z[zone]["zoom"], ["face", "main_subject"], ["seams"], "hero anchor on front only", composition_mode=zone)
394
+ elif role == "back_body":
395
+ zone = "back_wide" if candidate_id == "gallery_wrap" else "back_atmosphere"
396
+ plan = PiecePlan(piece_key, role, z[zone]["center"], z[zone]["zoom"], [], ["face", "primary_text"], "supporting back crop avoids front hero repeat", composition_mode=zone)
397
+ elif role == "hood":
398
+ zone = "hood_atmosphere_left" if len(piece_plans) % 2 == 0 else "hood_atmosphere_right"
399
+ plan = PiecePlan(piece_key, role, z[zone]["center"], z[zone]["zoom"], [], ["face", "eyes", "text"], "hood receives abstract atmosphere only", composition_mode=zone)
400
+ elif role == "sleeve":
401
+ zone = "sleeve_left_motion" if len(piece_plans) % 2 == 0 else "sleeve_right_motion"
402
+ plan = PiecePlan(piece_key, role, z[zone]["center"], z[zone]["zoom"], [], ["face", "text"], "sleeve receives motion/texture flow", composition_mode=zone)
403
+ elif role in ["overlay_pocket", "overlay"]:
404
+ plan = PiecePlan(piece_key, role, [0.5, 0.7], 1.0, ["parent_underlay"], ["fresh_crop"], "overlay inherits rendered parent underlay", continuity_parent="front_body", composition_mode="exact_parent_underlay")
405
+ elif role == "inside_label":
406
+ zone = "label_texture"
407
+ plan = PiecePlan(piece_key, role, z[zone]["center"], z[zone]["zoom"], [], ["face", "text"], "label receives simple hidden detail", composition_mode=zone)
408
+ else:
409
+ zone = "trim_texture"
410
+ plan = PiecePlan(piece_key, role, z[zone]["center"], z[zone]["zoom"], [], ["face", "text"], "trim receives low-detail texture", composition_mode=zone)
411
+
412
+ piece_plans.append(plan)
413
+
414
+ return LayoutCandidate(candidate_id=candidate_id, description=description, piece_plans=piece_plans)
415
+
416
+
417
+ def branch_layouts(piece_roles: List[Tuple[str, str]], analysis: Dict[str, Any], branch_count: int = DEFAULT_BRANCH_COUNT) -> List[LayoutCandidate]:
418
+ candidates = [
419
+ build_candidate("balanced_safe", "Default safe AOP: hero front, support crops everywhere else.", piece_roles, analysis),
420
+ build_candidate("hero_tight", "Tighter front hero with stricter support crops.", piece_roles, analysis),
421
+ build_candidate("gallery_wrap", "Wider atmospheric back crop while preserving no-hero-spam.", piece_roles, analysis),
422
+ build_candidate("abstract_safe", "Maximum seam safety: abstract/motion crops dominate all non-front pieces.", piece_roles, analysis),
423
+ ]
424
+ return candidates[:max(1, min(branch_count, len(candidates)))]
425
+
426
+
427
+ def quality_tribunal(candidate: LayoutCandidate, piece_roles: List[Tuple[str, str]], analysis: Dict[str, Any], require_pocket_continuity: bool = True) -> LayoutCandidate:
428
+ score = 100.0
429
+ warnings: List[str] = []
430
+
431
+ front_hero_count = 0
432
+ nonfront_hero_count = 0
433
+ overlay_count = 0
434
+
435
+ for plan in candidate.piece_plans:
436
+ if plan.role == "front_body" and "hero" in plan.composition_mode:
437
+ front_hero_count += 1
438
+ if plan.role != "front_body" and "hero" in plan.composition_mode:
439
+ nonfront_hero_count += 1
440
+ if plan.role in ["overlay_pocket", "overlay"]:
441
+ overlay_count += 1
442
+ if require_pocket_continuity and plan.composition_mode != "exact_parent_underlay":
443
+ score -= 30
444
+ warnings.append(f"{plan.piece_id}: overlay did not inherit front underlay.")
445
+
446
+ if plan.role in ["hood", "sleeve", "trim"] and ("face" not in plan.avoid_regions and "eyes" not in plan.avoid_regions):
447
+ score -= 10
448
+ warnings.append(f"{plan.piece_id}: risky non-front piece did not avoid face/eyes.")
449
+
450
+ if plan.zoom < 0.85:
451
+ score -= 5
452
+ warnings.append(f"{plan.piece_id}: low zoom could expose weak crop edges.")
453
+
454
+ if front_hero_count == 0:
455
+ score -= 20
456
+ warnings.append("No clear front hero assignment.")
457
+ if nonfront_hero_count > 0:
458
+ score -= 35 * nonfront_hero_count
459
+ warnings.append("Hero spam detected on non-front piece.")
460
+
461
+ text_regions = analysis.get("primary_subject", {}).get("text_like_regions", [])
462
+ if text_regions:
463
+ score -= min(8, len(text_regions) * 2)
464
+ warnings.append(f"Text-like regions detected: {len(text_regions)}. Avoid seam-heavy pieces.")
465
+
466
+ score = max(0.0, min(100.0, score))
467
+ candidate.score = round(score, 2)
468
+ candidate.warnings = warnings
469
+ candidate.production_ready = score >= 75 and nonfront_hero_count == 0
470
+ return candidate
471
+
472
+
473
+ def choose_best_candidate(candidates: List[LayoutCandidate]) -> LayoutCandidate:
474
+ return sorted(candidates, key=lambda c: (c.production_ready, c.score), reverse=True)[0]
475
+
476
+
477
+ # =============================================================================
478
+ # Rendering
479
+ # =============================================================================
480
+
481
+ def crop_cover(img: Image.Image, target_w: int, target_h: int, center: List[float], zoom: float) -> Tuple[Image.Image, Dict[str, Any]]:
482
+ sw, sh = img.size
483
+ tr = target_w / max(target_h, 1)
484
+ sr = sw / max(sh, 1)
485
+
486
+ if sr > tr:
487
+ crop_h = sh / zoom
488
+ crop_w = crop_h * tr
489
+ else:
490
+ crop_w = sw / zoom
491
+ crop_h = crop_w / max(tr, 0.0001)
492
+
493
+ cw, ch = max(2, int(round(crop_w))), max(2, int(round(crop_h)))
494
+ cx, cy = center[0] * sw, center[1] * sh
495
+ x1 = max(0, min(int(round(cx - cw / 2)), sw - cw))
496
+ y1 = max(0, min(int(round(cy - ch / 2)), sh - ch))
497
+ rect = [x1, y1, x1 + cw, y1 + ch]
498
+ crop = img.crop(tuple(rect)).resize((target_w, target_h), Image.Resampling.LANCZOS)
499
+ return crop, {"source_crop_xyxy": rect, "center": center, "zoom": zoom}
500
+
501
+
502
+ def apply_mask(img: Image.Image, mask: Image.Image) -> Image.Image:
503
+ out = img.convert("RGBA")
504
+ out.putalpha(mask.convert("L"))
505
+ return out
506
+
507
+
508
+ def overlay_from_front_underlay(front_img: Image.Image, target_w: int, target_h: int) -> Tuple[Image.Image, Dict[str, Any]]:
509
+ fw, fh = front_img.size
510
+ ratio = target_w / max(target_h, 1)
511
+ cover_w = int(fw * 0.64)
512
+ cover_h = int(cover_w / max(ratio, 0.001))
513
+ if cover_h > int(fh * 0.34):
514
+ cover_h = int(fh * 0.30)
515
+ cover_w = int(cover_h * ratio)
516
+
517
+ x1 = max(0, int((fw - cover_w) / 2))
518
+ y1 = min(max(0, int(fh * 0.58)), max(0, fh - cover_h))
519
+ x2, y2 = min(fw, x1 + cover_w), min(fh, y1 + cover_h)
520
+
521
+ crop = front_img.crop((x1, y1, x2, y2)).resize((target_w, target_h), Image.Resampling.LANCZOS)
522
+ return crop, {
523
+ "method": "sample_rendered_front_underlay",
524
+ "front_coverage_xyxy": [x1, y1, x2, y2],
525
+ "rule": "pocket/flap/overlay inherits front render, not a fresh crop",
526
+ }
527
 
528
 
529
+ def make_contact_sheet(paths: List[str], out_path: Path) -> None:
530
+ thumbs = []
531
+ for p in paths:
532
+ im = Image.open(p).convert("RGBA")
533
+ bg = Image.new("RGBA", im.size, (255, 255, 255, 255))
534
+ bg.alpha_composite(im)
535
+ bg = bg.convert("RGB")
536
+ bg.thumbnail((260, 260))
537
+ tile = Image.new("RGB", (290, 330), "white")
538
+ tile.paste(bg, ((290 - bg.width) // 2, 10))
539
+ d = ImageDraw.Draw(tile)
540
+ d.text((10, 292), Path(p).name[:36], fill=(0, 0, 0))
541
+ thumbs.append(tile)
542
+
543
+ cols = 3
544
+ rows = max(1, math.ceil(len(thumbs) / cols))
545
+ sheet = Image.new("RGB", (cols * 290, rows * 330), "white")
546
+ for i, im in enumerate(thumbs):
547
+ sheet.paste(im, ((i % cols) * 290, (i // cols) * 330))
548
+ sheet.save(out_path, quality=92)
549
+
550
+
551
+ def find_plan(selected: LayoutCandidate, piece_key: str, role: str) -> PiecePlan:
552
+ for plan in selected.piece_plans:
553
+ if plan.piece_id == piece_key:
554
+ return plan
555
+ for plan in selected.piece_plans:
556
+ if plan.role == role:
557
+ return plan
558
+ return PiecePlan(piece_key, role, [0.5, 0.5], 1.2, [], ["face", "text"], "fallback role-safe plan")
559
+
560
+
561
+ # =============================================================================
562
+ # Main pipeline
563
+ # =============================================================================
564
+
565
+ @spaces.GPU(duration=180)
566
+ def run_pipeline(
567
+ artwork_file,
568
+ template_zip_file,
569
+ focal_hint: str,
570
+ branch_count: int,
571
+ require_pocket_continuity: bool,
572
+ export_full_canvases: bool,
573
+ ):
574
+ if artwork_file is None:
575
+ raise gr.Error("Upload artwork first.")
576
+ if template_zip_file is None:
577
+ raise gr.Error("Upload an AOP template ZIP first.")
578
+
579
+ work = Path(tempfile.mkdtemp(prefix="soul_threading_v12_"))
580
+ out_dir = work / "outputs"
581
+ print_dir = out_dir / "print"
582
+ manifest_dir = out_dir / "manifest"
583
+ preview_dir = out_dir / "preview"
584
+ for d in [print_dir, manifest_dir, preview_dir]:
585
+ d.mkdir(parents=True, exist_ok=True)
586
+
587
+ artwork = Image.open(artwork_file).convert("RGBA")
588
+ analysis = analyze_artwork(artwork, focal_hint=focal_hint or "")
589
+ template_files = template_files_from_zip(template_zip_file, work)
590
+
591
+ scan_reports: List[Dict[str, Any]] = []
592
+ piece_meta: List[Dict[str, Any]] = []
593
+ roles_for_brancher: List[Tuple[str, str]] = []
594
+
595
+ # Pre-scan so brancher sees the whole garment.
596
+ scanned_templates = []
597
+ for template_path in template_files:
598
+ width, height, comps, scan_report = extract_components(template_path)
599
+ scan_reports.append(scan_report)
600
+ scanned_templates.append((template_path, width, height, comps))
601
+ for idx, comp in enumerate(comps):
602
+ role = classify_piece(template_path.name, idx, comp["bbox"], (width, height))
603
+ piece_key = f"{safe_name(template_path.stem)}__piece_{idx + 1:02d}_{role}"
604
+ roles_for_brancher.append((piece_key, role))
605
+
606
+ if not roles_for_brancher:
607
+ raise gr.Error("No printable white areas found in the template ZIP.")
608
+
609
+ candidates = branch_layouts(roles_for_brancher, analysis, int(branch_count))
610
+ candidates = [quality_tribunal(c, roles_for_brancher, analysis, require_pocket_continuity) for c in candidates]
611
+ selected = choose_best_candidate(candidates)
612
+
613
+ gallery: List[str] = []
614
+ front_underlay: Optional[Image.Image] = None
615
+ piece_reports: List[Dict[str, Any]] = []
616
+
617
+ for template_path, width, height, comps in scanned_templates:
618
+ if not comps:
619
+ piece_reports.append({"template": template_path.name, "status": "no white printable pieces found"})
620
+ continue
621
 
622
+ full_canvas = Image.new("RGBA", (width, height), (0, 0, 0, 0))
623
+
624
+ for idx, comp in enumerate(comps):
625
+ x, y, pw, ph = comp["bbox"]
626
+ role = classify_piece(template_path.name, idx, comp["bbox"], (width, height))
627
+ piece_key = f"{safe_name(template_path.stem)}__piece_{idx + 1:02d}_{role}"
628
+ plan = find_plan(selected, piece_key, role)
629
+ mask = Image.fromarray(comp["mask"], "L").crop((x, y, x + pw, y + ph))
630
+
631
+ if role in ["overlay_pocket", "overlay"] and front_underlay is not None and require_pocket_continuity:
632
+ crop, crop_report = overlay_from_front_underlay(front_underlay, pw, ph)
633
+ reason = "overlay continuity: sampled from rendered front underlay"
634
+ else:
635
+ crop, crop_report = crop_cover(artwork, pw, ph, plan.crop_center, plan.zoom)
636
+ crop_report["composition_mode"] = plan.composition_mode
637
+ reason = plan.reason
638
+
639
+ piece = apply_mask(crop, mask)
640
+ piece_name = f"{piece_key}.png"
641
+ piece_path = print_dir / piece_name
642
+ piece.save(piece_path)
643
+ gallery.append(str(piece_path))
644
+ full_canvas.alpha_composite(piece, (x, y))
645
+
646
+ if role == "front_body" and front_underlay is None:
647
+ front_underlay = piece.copy()
648
+
649
+ piece_reports.append({
650
+ "template": template_path.name,
651
+ "piece": piece_name,
652
+ "role": role,
653
+ "bbox": comp["bbox"],
654
+ "assignment_reason": reason,
655
+ "crop_report": crop_report,
656
+ "white_only_scanner": True,
657
+ "colored_lines_used_as_pieces": False,
658
+ "status": "mapped",
659
+ })
660
+
661
+ if export_full_canvases:
662
+ full_canvas.save(print_dir / f"{safe_name(template_path.stem)}__full_canvas.png")
663
+
664
+ sheet_path = preview_dir / "contact_sheet.jpg"
665
+ make_contact_sheet(gallery, sheet_path)
666
+
667
+ status_msg = "Production ready." if selected.production_ready else "Needs review: Quality Tribunal found risks."
668
+ pipeline_output = PipelineOutput(
669
+ version=APP_VERSION,
670
+ selected_candidate_id=selected.candidate_id,
671
+ production_ready=selected.production_ready,
672
+ quality_score=selected.score,
673
+ status_message=status_msg,
674
+ warnings=selected.warnings,
675
+ files={
676
+ "piece_png_count": len(gallery),
677
+ "contact_sheet": "preview/contact_sheet.jpg",
678
+ "zip_name": "soul_threading_v12_primeo_fused_outputs.zip",
679
  },
680
+ analysis=analysis,
681
+ selected_plan=asdict(selected),
682
+ all_candidates=[asdict(c) for c in candidates],
683
+ scan_reports=scan_reports,
684
+ piece_reports=piece_reports,
685
+ )
 
 
 
 
 
 
 
 
 
 
686
 
687
+ manifest = asdict(pipeline_output)
688
+ (manifest_dir / "mapping_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
689
+ (manifest_dir / "mapping_process_log.txt").write_text(
690
+ "v12 Primeo-fused pipeline: one HF Space, white-only scanner, divergent layout brancher, Quality Tribunal, pocket continuity.\n",
691
+ encoding="utf-8",
692
+ )
693
 
694
+ zip_path = work / "soul_threading_v12_primeo_fused_outputs.zip"
695
+ with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as z:
696
+ for p in out_dir.rglob("*"):
697
+ z.write(p, p.relative_to(out_dir))
698
+
699
+ return str(zip_path), gallery[:60], str(sheet_path), json.dumps(manifest, indent=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
700
 
 
 
701
 
702
+ # =============================================================================
703
+ # Gradio UI
704
+ # =============================================================================
705
 
706
+ with gr.Blocks(title="Soul Threading v12 Primeo-Fused") as demo:
707
  gr.Markdown(
708
  """
709
+ # Soul Threading v12 Primeo-Fused 🧵
710
 
711
+ **One-platform Hugging Face / ZeroGPU-ready mapper.**
712
 
713
+ This folds Primeo's pipeline thinking into the v11 production core:
714
+
715
+ - white-only real-template scanner
716
+ - no hero spam
717
+ - pocket/flap/overlay continuity
718
+ - divergent layout brancher
719
+ - Quality Tribunal
720
+ - production ZIP export
721
+ """
722
  )
723
+
724
+ with gr.Tab("Map Garment"):
725
+ with gr.Row():
726
+ artwork = gr.Image(type="filepath", label="Artwork")
727
+ template_zip = gr.File(file_types=[".zip"], label="AOP template ZIP")
728
+
729
+ with gr.Row():
730
+ focal_hint = gr.Textbox(label="Focal hint", value="main character / face / hero subject", lines=1)
731
+ branch_count = gr.Slider(1, 4, value=4, step=1, label="Divergent layout branches")
732
+ require_pocket = gr.Checkbox(value=True, label="Require pocket/flap continuity")
733
+ export_full = gr.Checkbox(value=True, label="Export full template canvases too")
734
+
735
+ btn = gr.Button("Run Soul Threading v12 Mapper", variant="primary")
736
+ out_zip = gr.File(label="Download production ZIP")
737
+ gallery = gr.Gallery(label="Mapped print pieces", columns=3, height=720)
738
+ sheet = gr.Image(label="Contact sheet")
739
+ manifest = gr.Textbox(label="Manifest / Quality Tribunal", lines=28)
740
+
741
+ btn.click(
742
+ run_pipeline,
743
+ inputs=[artwork, template_zip, focal_hint, branch_count, require_pocket, export_full],
744
+ outputs=[out_zip, gallery, sheet, manifest],
745
+ api_name="map_aop_v12",
746
+ )
747
+
748
+ with gr.Tab("Rules"):
749
+ gr.Markdown(
750
+ """
751
+ ## Locked production rules
752
+
753
+ ```txt
754
+ Only white printable template areas become garment pieces.
755
+ Colored seam / bleed / blur / safe lines are restrictions, never pieces.
756
+ The front body gets the hero by default.
757
+ Back, hood, sleeves, trim and label get support crops.
758
+ Pocket/flap/overlay inherits the rendered parent underlay.
759
+ Exported print PNGs are transparent outside the piece shape.
760
+ ```
761
+
762
+ ## Primeo ideas fused in
763
+
764
+ ```txt
765
+ PipelineOutput
766
+ PiecePlan
767
+ qualityScore
768
+ warnings
769
+ productionReady
770
+ divergent branch candidates
771
+ Quality Tribunal
772
+ ```
773
+ """
774
+ )
775
+
776
+ with gr.Tab("Next Upgrade Slots"):
777
+ gr.Markdown(
778
+ """
779
+ ## ZeroGPU model slots
780
+
781
+ This app is ZeroGPU-ready and uses `@spaces.GPU` on the pipeline call.
782
+
783
+ Next optional upgrades can happen inside this same Space:
784
+
785
+ ```txt
786
+ Grounding DINO detector
787
+ SAM/SAM2 segmentation assist
788
+ Florence OCR/text-region assist
789
+ VLM art director
790
+ template memory database
791
+ ```
792
+
793
+ The deterministic export engine stays in charge of final production math.
794
+ """
795
+ )
796
+
797
+
798
+ demo.queue(max_size=8).launch()
docs/PRIMEO_FUSION_NOTES.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Primeo Fusion Notes
2
+
3
+ Primeo had strong pipeline concepts but was split across Flutter, HF Inference API, device temp storage, and hardcoded garment polygons.
4
+
5
+ v12 ports the useful concepts into one Hugging Face Gradio Space:
6
+
7
+ - PipelineOutput
8
+ - PiecePlan
9
+ - qualityScore
10
+ - warnings
11
+ - productionReady
12
+ - staged pipeline logic
13
+
14
+ v12 rejects the split architecture:
15
+
16
+ - no user API key box
17
+ - no Flutter runtime
18
+ - no hardcoded final garment polygons as the only source of truth
19
+ - no separate Supabase/job layer for v1
20
+
21
+ The real production core remains:
22
+
23
+ - uploaded template ZIP
24
+ - white-only printable region scanner
25
+ - role-safe mapping
26
+ - pocket continuity
27
+ - transparent PNG export
memory/model_stack.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "current": "deterministic_cv_core",
3
+ "zerogpu_slots": {
4
+ "vlm_art_director": "future optional",
5
+ "object_detector": "Grounding DINO future optional",
6
+ "segmentation": "SAM/SAM2 future optional",
7
+ "ocr_text_regions": "Florence future optional"
8
+ },
9
+ "rule": "AI may suggest layout, deterministic renderer owns final production math."
10
+ }
memory/pipeline_schema.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "ported_from_primeo": [
3
+ "PiecePlan",
4
+ "BoundingBox",
5
+ "PipelineOutput",
6
+ "qualityScore",
7
+ "warnings",
8
+ "productionReady",
9
+ "progressive pipeline stages"
10
+ ],
11
+ "kept_from_v11": [
12
+ "white-only scanner",
13
+ "real template ZIP parsing",
14
+ "no hero spam",
15
+ "pocket continuity from front underlay",
16
+ "transparent print PNG export",
17
+ "manifest JSON"
18
+ ],
19
+ "runtime_target": "single Hugging Face Gradio Space"
20
+ }
memory/production_rules.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "v12-primeo-fused",
3
+ "rules": [
4
+ "Only white printable areas are pieces.",
5
+ "Colored seam, bleed, blur, safe-zone, label, and guide marks are restrictions only.",
6
+ "Front body gets hero by default.",
7
+ "No hero spam on hood, sleeves, trim, pocket, or label.",
8
+ "Pocket/flap/overlay must inherit rendered parent underlay.",
9
+ "Export transparent PNGs only, no template board or guide lines.",
10
+ "Quality Tribunal must mark non-ready if hero repeats on non-front pieces."
11
+ ],
12
+ "piece_roles": {
13
+ "front_body": "hero_subject",
14
+ "back_body": "secondary_scene_or_atmosphere",
15
+ "hood": "abstract_atmosphere_only",
16
+ "sleeve": "motion_texture_background",
17
+ "trim": "low_detail_texture",
18
+ "inside_label": "small_hidden_detail",
19
+ "overlay_pocket": "exact_parent_underlay"
20
+ }
21
+ }
requirements.txt CHANGED
@@ -2,9 +2,3 @@ gradio>=4.44.1
2
  pillow>=10.4.0
3
  numpy>=1.26.0
4
  opencv-python-headless>=4.10.0.84
5
- torch
6
- torchvision
7
- transformers>=4.53.0
8
- accelerate>=0.33.0
9
- safetensors>=0.4.5
10
- huggingface_hub>=0.24.0
 
2
  pillow>=10.4.0
3
  numpy>=1.26.0
4
  opencv-python-headless>=4.10.0.84