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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VAMP Vision Dataset Booster — Free Playground
|
| 3 |
+
|
| 4 |
+
Gradio entrypoint for Hugging Face Spaces. This application accepts one target
|
| 5 |
+
object image plus an environmental context prompt, delegates dataset generation
|
| 6 |
+
to the verified pipeline.py engine, packages the generated YOLO dataset into a
|
| 7 |
+
single ZIP archive, and returns a visual bounding-box preview.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import inspect
|
| 13 |
+
import logging
|
| 14 |
+
import os
|
| 15 |
+
import shutil
|
| 16 |
+
import tempfile
|
| 17 |
+
import time
|
| 18 |
+
import traceback
|
| 19 |
+
import zipfile
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any, Dict, Iterable, Optional, Tuple
|
| 22 |
+
|
| 23 |
+
import gradio as gr
|
| 24 |
+
from PIL import Image, ImageDraw
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
import torch
|
| 28 |
+
except Exception: # pragma: no cover - torch availability depends on Space image
|
| 29 |
+
torch = None
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
import cv2 # noqa: F401 # Imported to ensure OpenCV is available for pipeline.py
|
| 33 |
+
except Exception: # pragma: no cover - pipeline may not require direct app-level cv2 use
|
| 34 |
+
cv2 = None
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
import pipeline
|
| 38 |
+
except Exception as import_error: # pragma: no cover - surfaced cleanly at runtime
|
| 39 |
+
pipeline = None
|
| 40 |
+
PIPELINE_IMPORT_ERROR = import_error
|
| 41 |
+
else:
|
| 42 |
+
PIPELINE_IMPORT_ERROR = None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
APP_TITLE = "VAMP Vision Dataset Booster — Free Playground"
|
| 46 |
+
APP_DESCRIPTION = (
|
| 47 |
+
"Upload 1 target object photo, input a context prompt, and download a "
|
| 48 |
+
"50-image model-ready training batch with precise YOLO bounding boxes."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
TMP_ROOT = Path(os.getenv("VAMP_PLAYGROUND_TMP", "/tmp/vamp_playground"))
|
| 52 |
+
INPUT_ROOT = Path("/tmp/inputs")
|
| 53 |
+
OUTPUT_ROOT = TMP_ROOT / "outputs"
|
| 54 |
+
ZIP_FILENAME = "vamp_playground_dataset.zip"
|
| 55 |
+
EXPECTED_IMAGE_COUNT = 50
|
| 56 |
+
PREVIEW_FILENAME = "debug_preview_0.jpg"
|
| 57 |
+
|
| 58 |
+
logging.basicConfig(
|
| 59 |
+
level=os.getenv("VAMP_LOG_LEVEL", "INFO").upper(),
|
| 60 |
+
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
| 61 |
+
)
|
| 62 |
+
logger = logging.getLogger("vamp_playground")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class PlaygroundGenerationError(RuntimeError):
|
| 66 |
+
"""Raised when the playground cannot complete dataset generation."""
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _reset_directory(path: Path) -> None:
|
| 70 |
+
"""Create an empty directory, removing stale files from previous runs."""
|
| 71 |
+
if path.exists():
|
| 72 |
+
shutil.rmtree(path, ignore_errors=True)
|
| 73 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _safe_prompt(context_prompt: Optional[str]) -> str:
|
| 77 |
+
"""Normalize a user context prompt without introducing placeholders."""
|
| 78 |
+
prompt = (context_prompt or "").strip()
|
| 79 |
+
return prompt if prompt else "neutral studio environment with natural lighting"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _save_uploaded_image(input_image: Image.Image, request_dir: Path) -> Path:
|
| 83 |
+
"""Validate and save the uploaded PIL image as an RGB PNG for pipeline use."""
|
| 84 |
+
if input_image is None:
|
| 85 |
+
raise PlaygroundGenerationError("Please upload a target object photo before generating a dataset.")
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
image = input_image.convert("RGB")
|
| 89 |
+
except Exception as exc:
|
| 90 |
+
raise PlaygroundGenerationError(
|
| 91 |
+
"The uploaded file could not be decoded as a valid image. Please try a PNG or JPEG file."
|
| 92 |
+
) from exc
|
| 93 |
+
|
| 94 |
+
if image.width < 8 or image.height < 8:
|
| 95 |
+
raise PlaygroundGenerationError("The uploaded image is too small. Please upload an image at least 8×8 pixels.")
|
| 96 |
+
|
| 97 |
+
INPUT_ROOT.mkdir(parents=True, exist_ok=True)
|
| 98 |
+
request_input_dir = request_dir / "inputs"
|
| 99 |
+
request_input_dir.mkdir(parents=True, exist_ok=True)
|
| 100 |
+
|
| 101 |
+
canonical_input = INPUT_ROOT / "target_object.png"
|
| 102 |
+
request_input = request_input_dir / "target_object.png"
|
| 103 |
+
image.save(canonical_input, format="PNG")
|
| 104 |
+
image.save(request_input, format="PNG")
|
| 105 |
+
|
| 106 |
+
logger.info("Saved uploaded image to %s and %s", canonical_input, request_input)
|
| 107 |
+
return request_input
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _pipeline_function() -> Any:
|
| 111 |
+
"""Return the verified pipeline execution callable or raise a helpful error."""
|
| 112 |
+
if pipeline is None:
|
| 113 |
+
raise PlaygroundGenerationError(
|
| 114 |
+
"pipeline.py could not be imported. Ensure pipeline.py is committed beside app.py in the Hugging Face Space. "
|
| 115 |
+
f"Import error: {PIPELINE_IMPORT_ERROR}"
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
runner = getattr(pipeline, "run_pipeline", None)
|
| 119 |
+
if runner is None or not callable(runner):
|
| 120 |
+
raise PlaygroundGenerationError("pipeline.py must expose a callable function named run_pipeline.")
|
| 121 |
+
return runner
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _accepted_kwargs(callable_obj: Any, candidate_kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
| 125 |
+
"""
|
| 126 |
+
Filter candidate keyword arguments to match the pipeline signature.
|
| 127 |
+
|
| 128 |
+
If pipeline.run_pipeline accepts **kwargs, pass the full production config.
|
| 129 |
+
Otherwise, only pass recognized parameters so this app remains compatible
|
| 130 |
+
with stricter verified pipeline signatures.
|
| 131 |
+
"""
|
| 132 |
+
try:
|
| 133 |
+
signature = inspect.signature(callable_obj)
|
| 134 |
+
except (TypeError, ValueError):
|
| 135 |
+
return candidate_kwargs
|
| 136 |
+
|
| 137 |
+
parameters = signature.parameters
|
| 138 |
+
accepts_kwargs = any(param.kind == inspect.Parameter.VAR_KEYWORD for param in parameters.values())
|
| 139 |
+
if accepts_kwargs:
|
| 140 |
+
return candidate_kwargs
|
| 141 |
+
|
| 142 |
+
return {key: value for key, value in candidate_kwargs.items() if key in parameters}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _run_core_pipeline(input_path: Path, context_prompt: str, output_dir: Path) -> Optional[Path]:
|
| 146 |
+
"""Run pipeline.py with conservative CPU-safe playground parameters."""
|
| 147 |
+
runner = _pipeline_function()
|
| 148 |
+
|
| 149 |
+
cpu_device = "cpu"
|
| 150 |
+
if torch is not None:
|
| 151 |
+
try:
|
| 152 |
+
torch.set_grad_enabled(False)
|
| 153 |
+
torch.set_num_threads(max(1, min(4, os.cpu_count() or 1)))
|
| 154 |
+
except Exception:
|
| 155 |
+
logger.warning("Unable to apply torch CPU thread controls; continuing with default torch settings.")
|
| 156 |
+
|
| 157 |
+
candidate_kwargs: Dict[str, Any] = {
|
| 158 |
+
"input_image_path": str(input_path),
|
| 159 |
+
"image_path": str(input_path),
|
| 160 |
+
"target_image": str(input_path),
|
| 161 |
+
"target_object_path": str(input_path),
|
| 162 |
+
"context_prompt": context_prompt,
|
| 163 |
+
"prompt": context_prompt,
|
| 164 |
+
"environment_prompt": context_prompt,
|
| 165 |
+
"output_dir": str(output_dir),
|
| 166 |
+
"dataset_dir": str(output_dir),
|
| 167 |
+
"num_images": EXPECTED_IMAGE_COUNT,
|
| 168 |
+
"image_count": EXPECTED_IMAGE_COUNT,
|
| 169 |
+
"target_count": EXPECTED_IMAGE_COUNT,
|
| 170 |
+
"device": cpu_device,
|
| 171 |
+
"use_cpu": True,
|
| 172 |
+
"skip_lora_training": True,
|
| 173 |
+
"skip_lora": True,
|
| 174 |
+
"disable_training": True,
|
| 175 |
+
"train_lora": False,
|
| 176 |
+
"fast_mode": True,
|
| 177 |
+
"playground_mode": True,
|
| 178 |
+
"inference_steps": 8,
|
| 179 |
+
"num_inference_steps": 8,
|
| 180 |
+
"guidance_scale": 3.5,
|
| 181 |
+
"seed": 42,
|
| 182 |
+
}
|
| 183 |
+
kwargs = _accepted_kwargs(runner, candidate_kwargs)
|
| 184 |
+
|
| 185 |
+
logger.info("Starting pipeline.run_pipeline with CPU-safe playground configuration.")
|
| 186 |
+
logger.info("Pipeline output directory: %s", output_dir)
|
| 187 |
+
logger.debug("Pipeline accepted kwargs: %s", sorted(kwargs.keys()))
|
| 188 |
+
|
| 189 |
+
try:
|
| 190 |
+
result = runner(**kwargs)
|
| 191 |
+
except TypeError as first_exc:
|
| 192 |
+
logger.warning("Keyword pipeline call failed; attempting compatibility positional call: %s", first_exc)
|
| 193 |
+
try:
|
| 194 |
+
result = runner(str(input_path), context_prompt, str(output_dir))
|
| 195 |
+
except Exception as second_exc:
|
| 196 |
+
raise PlaygroundGenerationError(
|
| 197 |
+
"pipeline.run_pipeline failed with both keyword and compatibility positional calls. "
|
| 198 |
+
f"Last error: {second_exc}"
|
| 199 |
+
) from second_exc
|
| 200 |
+
except RuntimeError as exc:
|
| 201 |
+
message = str(exc).lower()
|
| 202 |
+
if "cuda" in message or "tensor" in message or "out of memory" in message:
|
| 203 |
+
raise PlaygroundGenerationError(
|
| 204 |
+
"The generation engine reported a tensor/device configuration issue on the CPU Space. "
|
| 205 |
+
"Please verify that pipeline.py honors device='cpu' and skip_lora_training=True."
|
| 206 |
+
) from exc
|
| 207 |
+
raise
|
| 208 |
+
|
| 209 |
+
resolved = _resolve_pipeline_output(result, output_dir)
|
| 210 |
+
logger.info("Pipeline completed. Resolved dataset directory: %s", resolved or output_dir)
|
| 211 |
+
return resolved
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _resolve_pipeline_output(result: Any, fallback_output_dir: Path) -> Optional[Path]:
|
| 215 |
+
"""Resolve the dataset directory from common pipeline return shapes."""
|
| 216 |
+
if result is None:
|
| 217 |
+
return fallback_output_dir
|
| 218 |
+
|
| 219 |
+
if isinstance(result, (str, os.PathLike)):
|
| 220 |
+
path = Path(result)
|
| 221 |
+
return path if path.exists() else fallback_output_dir
|
| 222 |
+
|
| 223 |
+
if isinstance(result, dict):
|
| 224 |
+
for key in ("dataset_dir", "output_dir", "path", "dataset_path", "root"):
|
| 225 |
+
value = result.get(key)
|
| 226 |
+
if value:
|
| 227 |
+
path = Path(value)
|
| 228 |
+
if path.exists():
|
| 229 |
+
return path
|
| 230 |
+
|
| 231 |
+
if isinstance(result, (tuple, list)):
|
| 232 |
+
for value in result:
|
| 233 |
+
if isinstance(value, (str, os.PathLike)):
|
| 234 |
+
path = Path(value)
|
| 235 |
+
if path.exists():
|
| 236 |
+
return path
|
| 237 |
+
|
| 238 |
+
return fallback_output_dir
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _iter_dataset_files(dataset_dir: Path) -> Iterable[Path]:
|
| 242 |
+
"""Yield generated image and YOLO label files from the dataset structure."""
|
| 243 |
+
valid_suffixes = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".txt", ".yaml", ".yml", ".json"}
|
| 244 |
+
for file_path in sorted(dataset_dir.rglob("*")):
|
| 245 |
+
if file_path.is_file() and file_path.suffix.lower() in valid_suffixes:
|
| 246 |
+
if file_path.name == ZIP_FILENAME:
|
| 247 |
+
continue
|
| 248 |
+
yield file_path
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _find_subdir(dataset_dir: Path, name: str) -> Optional[Path]:
|
| 252 |
+
"""Find a dataset subdirectory named images or labels, preferring direct children."""
|
| 253 |
+
direct = dataset_dir / name
|
| 254 |
+
if direct.is_dir():
|
| 255 |
+
return direct
|
| 256 |
+
matches = [path for path in dataset_dir.rglob(name) if path.is_dir()]
|
| 257 |
+
return matches[0] if matches else None
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _validate_dataset_layout(dataset_dir: Path) -> None:
|
| 261 |
+
"""Check that the generated dataset contains images and matching YOLO labels."""
|
| 262 |
+
images_dir = _find_subdir(dataset_dir, "images")
|
| 263 |
+
labels_dir = _find_subdir(dataset_dir, "labels")
|
| 264 |
+
|
| 265 |
+
if images_dir is None or labels_dir is None:
|
| 266 |
+
logger.warning("Expected /images and /labels folders were not both found under %s", dataset_dir)
|
| 267 |
+
return
|
| 268 |
+
|
| 269 |
+
image_files = [p for p in images_dir.rglob("*") if p.suffix.lower() in {".jpg", ".jpeg", ".png", ".webp", ".bmp"}]
|
| 270 |
+
label_files = [p for p in labels_dir.rglob("*") if p.suffix.lower() == ".txt"]
|
| 271 |
+
|
| 272 |
+
if len(image_files) < EXPECTED_IMAGE_COUNT:
|
| 273 |
+
logger.warning("Expected 50 generated images, found %d in %s", len(image_files), images_dir)
|
| 274 |
+
if len(label_files) < min(len(image_files), EXPECTED_IMAGE_COUNT):
|
| 275 |
+
logger.warning("Found %d labels for %d generated images.", len(label_files), len(image_files))
|
| 276 |
+
|
| 277 |
+
logger.info("Dataset validation heartbeat: %d images, %d labels", len(image_files), len(label_files))
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _compile_dataset_zip(dataset_dir: Path, request_dir: Path) -> Path:
|
| 281 |
+
"""Package the generated dataset into vamp_playground_dataset.zip."""
|
| 282 |
+
zip_path = request_dir / ZIP_FILENAME
|
| 283 |
+
dataset_files = list(_iter_dataset_files(dataset_dir))
|
| 284 |
+
|
| 285 |
+
if not dataset_files:
|
| 286 |
+
raise PlaygroundGenerationError(
|
| 287 |
+
"The pipeline completed but no dataset files were found. Expected generated files under /images and /labels."
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
logger.info("Compiling %d dataset files into %s", len(dataset_files), zip_path)
|
| 291 |
+
with zipfile.ZipFile(zip_path, mode="w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
| 292 |
+
for file_path in dataset_files:
|
| 293 |
+
arcname = file_path.relative_to(dataset_dir)
|
| 294 |
+
archive.write(file_path, arcname=str(arcname))
|
| 295 |
+
|
| 296 |
+
logger.info("ZIP archive ready: %s", zip_path)
|
| 297 |
+
return zip_path
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _parse_yolo_label(label_path: Path) -> Optional[Tuple[float, float, float, float]]:
|
| 301 |
+
"""Read the first YOLO box from a label file as normalized xywh values."""
|
| 302 |
+
try:
|
| 303 |
+
first_line = label_path.read_text(encoding="utf-8").strip().splitlines()[0]
|
| 304 |
+
parts = first_line.split()
|
| 305 |
+
if len(parts) < 5:
|
| 306 |
+
return None
|
| 307 |
+
_, x_center, y_center, width, height = parts[:5]
|
| 308 |
+
return float(x_center), float(y_center), float(width), float(height)
|
| 309 |
+
except Exception:
|
| 310 |
+
return None
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _draw_preview_from_dataset(dataset_dir: Path, request_dir: Path) -> Optional[Path]:
|
| 314 |
+
"""Create debug_preview_0.jpg when the pipeline did not already provide one."""
|
| 315 |
+
images_dir = _find_subdir(dataset_dir, "images")
|
| 316 |
+
labels_dir = _find_subdir(dataset_dir, "labels")
|
| 317 |
+
if images_dir is None or labels_dir is None:
|
| 318 |
+
return None
|
| 319 |
+
|
| 320 |
+
image_files = sorted(
|
| 321 |
+
p for p in images_dir.rglob("*") if p.suffix.lower() in {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
|
| 322 |
+
)
|
| 323 |
+
if not image_files:
|
| 324 |
+
return None
|
| 325 |
+
|
| 326 |
+
image_path = image_files[0]
|
| 327 |
+
label_path = labels_dir / f"{image_path.stem}.txt"
|
| 328 |
+
if not label_path.exists():
|
| 329 |
+
matching_labels = sorted(labels_dir.rglob("*.txt"))
|
| 330 |
+
label_path = matching_labels[0] if matching_labels else label_path
|
| 331 |
+
|
| 332 |
+
preview_path = request_dir / PREVIEW_FILENAME
|
| 333 |
+
with Image.open(image_path).convert("RGB") as image:
|
| 334 |
+
draw = ImageDraw.Draw(image)
|
| 335 |
+
box = _parse_yolo_label(label_path) if label_path.exists() else None
|
| 336 |
+
if box is not None:
|
| 337 |
+
x_center, y_center, box_width, box_height = box
|
| 338 |
+
img_w, img_h = image.size
|
| 339 |
+
x1 = max(0, int((x_center - box_width / 2) * img_w))
|
| 340 |
+
y1 = max(0, int((y_center - box_height / 2) * img_h))
|
| 341 |
+
x2 = min(img_w - 1, int((x_center + box_width / 2) * img_w))
|
| 342 |
+
y2 = min(img_h - 1, int((y_center + box_height / 2) * img_h))
|
| 343 |
+
line_width = max(2, img_w // 160)
|
| 344 |
+
draw.rectangle((x1, y1, x2, y2), outline=(255, 36, 36), width=line_width)
|
| 345 |
+
draw.text((x1 + 4, max(0, y1 - 18)), "YOLO box", fill=(255, 36, 36))
|
| 346 |
+
else:
|
| 347 |
+
logger.warning("No readable YOLO label found for preview image %s", image_path)
|
| 348 |
+
image.save(preview_path, format="JPEG", quality=92)
|
| 349 |
+
|
| 350 |
+
logger.info("Generated fallback preview at %s", preview_path)
|
| 351 |
+
return preview_path
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _find_preview(dataset_dir: Path, request_dir: Path) -> Path:
|
| 355 |
+
"""Return pipeline-generated debug preview or synthesize one from image/label files."""
|
| 356 |
+
candidates = [
|
| 357 |
+
dataset_dir / PREVIEW_FILENAME,
|
| 358 |
+
dataset_dir / "debug" / PREVIEW_FILENAME,
|
| 359 |
+
dataset_dir / "previews" / PREVIEW_FILENAME,
|
| 360 |
+
request_dir / PREVIEW_FILENAME,
|
| 361 |
+
]
|
| 362 |
+
candidates.extend(dataset_dir.rglob(PREVIEW_FILENAME))
|
| 363 |
+
|
| 364 |
+
for candidate in candidates:
|
| 365 |
+
if candidate.exists() and candidate.is_file():
|
| 366 |
+
logger.info("Using bounding-box preview: %s", candidate)
|
| 367 |
+
return candidate
|
| 368 |
+
|
| 369 |
+
generated = _draw_preview_from_dataset(dataset_dir, request_dir)
|
| 370 |
+
if generated and generated.exists():
|
| 371 |
+
return generated
|
| 372 |
+
|
| 373 |
+
raise PlaygroundGenerationError(
|
| 374 |
+
"The dataset was generated, but no debug_preview_0.jpg or drawable image/label pair could be found."
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def run_playground_generation(input_image: Image.Image, context_prompt: str) -> Tuple[str, str]:
|
| 379 |
+
"""
|
| 380 |
+
Gradio execution handler.
|
| 381 |
+
|
| 382 |
+
Saves the uploaded image, calls pipeline.run_pipeline with CPU-friendly
|
| 383 |
+
generation parameters, compiles generated /images and /labels into the exact
|
| 384 |
+
archive name vamp_playground_dataset.zip, and returns the preview plus ZIP.
|
| 385 |
+
"""
|
| 386 |
+
started_at = time.time()
|
| 387 |
+
request_id = f"run_{int(started_at)}_{os.getpid()}"
|
| 388 |
+
request_dir = TMP_ROOT / request_id
|
| 389 |
+
output_dir = OUTPUT_ROOT / request_id
|
| 390 |
+
|
| 391 |
+
try:
|
| 392 |
+
logger.info("Generation request received: %s", request_id)
|
| 393 |
+
_reset_directory(request_dir)
|
| 394 |
+
_reset_directory(output_dir)
|
| 395 |
+
|
| 396 |
+
prompt = _safe_prompt(context_prompt)
|
| 397 |
+
input_path = _save_uploaded_image(input_image, request_dir)
|
| 398 |
+
dataset_dir = _run_core_pipeline(input_path=input_path, context_prompt=prompt, output_dir=output_dir)
|
| 399 |
+
dataset_dir = dataset_dir or output_dir
|
| 400 |
+
|
| 401 |
+
_validate_dataset_layout(dataset_dir)
|
| 402 |
+
zip_path = _compile_dataset_zip(dataset_dir=dataset_dir, request_dir=request_dir)
|
| 403 |
+
preview_path = _find_preview(dataset_dir=dataset_dir, request_dir=request_dir)
|
| 404 |
+
|
| 405 |
+
elapsed = time.time() - started_at
|
| 406 |
+
logger.info("Generation request %s completed successfully in %.2f seconds", request_id, elapsed)
|
| 407 |
+
return str(preview_path), str(zip_path)
|
| 408 |
+
|
| 409 |
+
except PlaygroundGenerationError as exc:
|
| 410 |
+
logger.error("Generation request %s failed: %s", request_id, exc)
|
| 411 |
+
raise gr.Error(str(exc)) from exc
|
| 412 |
+
except Exception as exc:
|
| 413 |
+
logger.error("Unexpected generation failure for %s: %s", request_id, exc)
|
| 414 |
+
logger.debug("Unexpected failure traceback:\n%s", traceback.format_exc())
|
| 415 |
+
raise gr.Error(
|
| 416 |
+
"Dataset generation failed due to an unexpected runtime error. "
|
| 417 |
+
"Please check the Space logs for the full traceback and verify pipeline.py output paths."
|
| 418 |
+
) from exc
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def build_interface() -> gr.Blocks:
|
| 422 |
+
"""Construct the Gradio Blocks interface for Hugging Face Spaces."""
|
| 423 |
+
with gr.Blocks(title=APP_TITLE, theme=gr.themes.Soft()) as demo:
|
| 424 |
+
gr.Markdown(f"# {APP_TITLE}")
|
| 425 |
+
gr.Markdown(APP_DESCRIPTION)
|
| 426 |
+
|
| 427 |
+
with gr.Row():
|
| 428 |
+
with gr.Column(scale=1):
|
| 429 |
+
input_image = gr.Image(type="pil", label="Upload Target Object Photo")
|
| 430 |
+
context_prompt = gr.Textbox(
|
| 431 |
+
label="Environmental Context Prompt",
|
| 432 |
+
placeholder="e.g., conveyor belt with reflections",
|
| 433 |
+
lines=2,
|
| 434 |
+
max_lines=4,
|
| 435 |
+
)
|
| 436 |
+
generate_button = gr.Button("Generate 50-Image Dataset", variant="primary")
|
| 437 |
+
|
| 438 |
+
with gr.Column(scale=1):
|
| 439 |
+
preview_output = gr.Image(label="Visual Smoke Test Bounding-Box Preview")
|
| 440 |
+
zip_output = gr.File(label="Download Complete 50-Image YOLO Dataset (.zip)")
|
| 441 |
+
|
| 442 |
+
generate_button.click(
|
| 443 |
+
fn=run_playground_generation,
|
| 444 |
+
inputs=[input_image, context_prompt],
|
| 445 |
+
outputs=[preview_output, zip_output],
|
| 446 |
+
api_name="generate_dataset",
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
return demo
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
demo = build_interface()
|
| 453 |
+
|
| 454 |
+
if __name__ == "__main__":
|
| 455 |
+
demo.queue(default_concurrency_limit=1).launch()
|
| 456 |
+
else:
|
| 457 |
+
demo.queue(default_concurrency_limit=1)
|
| 458 |
+
|