---
name: sdcpp_python_generate
kind: function
lang: py
domain: ml
version: "1.0.0"
purity: impure
signature: "def sdcpp_python_generate(sd: Any, cfg: GenerationConfig) -> ImageGenResult"
description: "Genera una imagen con un StableDiffusion (stable-diffusion-cpp-python) usando GenerationConfig como contrato. Mapea sampler, mide duracion y retorna ImageGenResult con meta del backend."
tags: [ml, stable-diffusion, sdcpp, inference, backend, generate, txt2img, pendiente-usar]
uses_functions: [sdcpp_python_load_py_ml]
uses_types: [generation_config_py_ml, image_gen_result_py_ml]
returns: [image_gen_result_py_ml]
returns_optional: false
error_type: "error_go_core"
imports: [stable_diffusion_cpp, PIL]
params:
  - name: sd
    desc: "Instancia StableDiffusion cargada via sdcpp_python_load. Debe tener metodo generate_image()."
  - name: cfg
    desc: "Contrato de parametros de generacion. cfg.sampler debe ser uno de: euler | euler_a | dpm++2m | dpm++2m_v2 | heun | dpm2 | lcm."
output: "ImageGenResult con image=PIL.Image (primera del batch), meta con backend/model/sampler/seed/wtype, duration_ms medido, vram_peak_mb=None."
tested: true
tests:
  - "generate retorna ImageGenResult valido"
  - "duration_ms mayor que cero"
  - "meta backend es sdcpp_python"
test_file_path: "python/functions/ml/tests/test_sdcpp_python_backend.py"
file_path: "python/functions/ml/sdcpp_python_generate.py"
---

## Ejemplo

```python
import sys
sys.path.insert(0, "python/functions/ml")
from model_ref import ModelRef
from generation_config import GenerationConfig
from sdcpp_python_load import sdcpp_python_load
from sdcpp_python_generate import sdcpp_python_generate

model = ModelRef(
    name="sd-turbo",
    model_type="sd15",
    quantization="fp16",
    path="/home/lucas/vaults/imagegen_models/diffusers/sd-turbo/sd_turbo.safetensors",
)
sd = sdcpp_python_load(model)

cfg = GenerationConfig(
    prompt="a red cat sitting on a wooden table",
    seed=42,
    steps=4,
    cfg_scale=1.0,
    sampler="euler_a",
    width=512,
    height=512,
    model=model,
)
result = sdcpp_python_generate(sd, cfg)
result.image.save("/tmp/output.png")
print(f"Generado en {result.duration_ms}ms, meta={result.meta}")
```

## Notas

- El sampler mapping canonico: euler->euler, euler_a->euler_a, dpm++2m->dpmpp2m,
  dpm++2m_v2->dpmpp2mv2, heun->heun, dpm2->dpm2, lcm->lcm.
- API usada: `StableDiffusion.generate_image()` (binding 0.4.7+). Versiones anteriores
  exponían `txt_to_img()` — actualizar el package si se encuentra ese error.
- `vram_peak_mb` siempre None: stable-diffusion-cpp-python no expone medicion de VRAM.
- `clip_skip`: -1 le dice al backend que use el valor por defecto del modelo (equivale a
  no especificarlo). Si cfg.clip_skip es None, se pasa -1.
- El campo `wtype` en meta se extrae via `getattr(sd, 'wtype', 'unknown')` ya que el
  binding no garantiza el atributo en todas las versiones.
---
