chore: auto-commit (14 archivos)

- docs/capabilities/comfyui.md
- python/functions/ml/comfyui_build_image_to_3d_workflow.md
- python/functions/ml/comfyui_build_image_to_3d_workflow.py
- python/functions/ml/tests/test_comfyui_build_image_to_3d_workflow.py
- python/functions/ml/comfyui_build_facedetailer_workflow.md
- python/functions/ml/comfyui_build_facedetailer_workflow.py
- python/functions/ml/comfyui_build_hires_fix_workflow.md
- python/functions/ml/comfyui_build_hires_fix_workflow.py
- python/functions/ml/tests/test_comfyui_build_facedetailer_workflow.py
- python/functions/ml/tests/test_comfyui_build_hires_fix_workflow.py
- ...

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-24 02:34:10 +02:00
parent 3823a28d1c
commit f686b338d6
14 changed files with 1265 additions and 28 deletions
@@ -0,0 +1,86 @@
---
name: comfyui_mesh_cleanup_oneshot
kind: pipeline
lang: py
domain: pipelines
version: "1.0.0"
purity: impure
signature: "def comfyui_mesh_cleanup_oneshot(in_path: str, *, target_faces: int = 80000, watertight: bool = True, method: str = \"repair\", out_path: str | None = None) -> dict"
description: "Pipeline de limpieza de mallas 3D en una sola llamada: decima a un presupuesto de caras (comfyui_simplify_mesh) y, opcionalmente, la hace estanca (comfyui_make_watertight). Capitaliza el 'Golden 3' del report 0088 (80k caras + estanca a la vez) para las mallas densas no estancas que produce el pipeline Hunyuan3D de ComfyUI. Promocion de secuencia (issue 0087). Impuro: lee y escribe archivos en disco; requiere trimesh + pymeshlab + scipy."
tags: [comfyui, pipelines, mesh, cleanup, watertight, launcher]
uses_functions: [comfyui_simplify_mesh_py_ml, comfyui_make_watertight_py_ml]
uses_types: []
returns: []
returns_optional: false
error_type: error_py_core
imports: [comfyui_simplify_mesh_py_ml, comfyui_make_watertight_py_ml]
params:
- name: in_path
desc: "Ruta de la malla de entrada (.glb/.obj/.ply/.gltf/.stl/.off)."
- name: target_faces
desc: "Caras objetivo del paso de decimacion (comfyui_simplify_mesh). keyword-only."
- name: watertight
desc: "Si True (default) aplica comfyui_make_watertight tras decimar; si False solo decima. keyword-only."
- name: method
desc: "Metodo de make_watertight cuando watertight=True. 'repair' (default) conserva las caras decimadas pero no garantiza estanqueidad en mallas muy rotas; 'voxel' garantiza is_watertight=True via voxeliza+fill+marching cubes, a costa de re-mallar (cambia el conteo de caras y descarta apariencia). keyword-only."
- name: out_path
desc: "Ruta de salida final. Si None, se deriva de in_path ('<in>_cleaned.glb'). keyword-only."
output: "dict {ok, in_path, out_path, in_faces, simplified_faces, final_faces, watertight_requested, is_watertight, method, steps, error}. steps = resultados crudos de cada funcion compuesta. Si algun paso falla, ok=False y error explica en cual."
tested: false
tests: []
test_file_path: ""
file_path: "python/functions/pipelines/comfyui_mesh_cleanup_oneshot.py"
---
## Ejemplo
```bash
# Limpia la malla densa de ComfyUI: decima a 80k caras y la hace estanca.
./fn run comfyui_mesh_cleanup_oneshot ~/ComfyUI/output/3d_mesh_00002_.glb
```
```python
import sys, os
sys.path.insert(0, os.path.join(os.environ["HOME"], "fn_registry", "python", "functions"))
from pipelines.comfyui_mesh_cleanup_oneshot import comfyui_mesh_cleanup_oneshot
res = comfyui_mesh_cleanup_oneshot(
os.path.expanduser("~/ComfyUI/output/3d_mesh_00002_.glb"),
target_faces=80000,
watertight=True,
)
# res["ok"] == True
# res["in_faces"] >> res["final_faces"] # decimada
# res["is_watertight"] # True/False segun method y la malla
print(res["in_faces"], "->", res["final_faces"], "watertight:", res["is_watertight"])
```
## Cuando usarla
Justo después de generar una malla 3D con ComfyUI/Hunyuan3D
(`comfyui_image_to_3d_oneshot`, `comfyui_text_to_3d_oneshot`), cuando el GLB sale
denso (decenas de MB, >1M caras) y/o no estanco. En una llamada la dejas lista
para web (ligera) o impresión 3D (cerrada). Es la promoción del patrón
"simplify → make_watertight" que se repetía a mano (reports 0088/0091).
## Gotchas
- Impuro: lee y **escribe** archivos en disco. Con `watertight=True` deja también
un intermedio `<out>_simplified.glb` junto al final.
- Necesita `trimesh` + `pymeshlab` + `scipy` (decimación). Con `method="voxel"`
además `scikit-image` (marching cubes). Si falta una, el paso correspondiente
devuelve `ok=False` con el comando `uv add` a ejecutar.
- **`method="repair"` (default) NO garantiza estanqueidad** en mallas muy rotas:
cierra huecos pequeños y conserva las caras decimadas. El output reporta
`is_watertight` real — compruébalo. Si necesitas estanqueidad GARANTIZADA usa
`method="voxel"` (re-malla: cambia el conteo de caras y descarta UV/colores).
- El `target_faces` aplica al paso de decimación. Con `method="voxel"` el conteo
final lo fija el voxel-remesh (mira `final_faces`), no `target_faces`.
- El pipeline NO falla si la malla no queda estanca con `repair`: devuelve `ok=True`
con `is_watertight=False`. Decide en el caller si reintentar con `method="voxel"`.
- No toca el servidor ComfyUI: opera sobre archivos GLB ya en disco.
## Capability growth log
- v1.0.0 (2026-06-24) — pipeline inicial. Compone `comfyui_simplify_mesh` +
`comfyui_make_watertight` (issue 0087, capitaliza report 0088).
@@ -0,0 +1,119 @@
"""comfyui_mesh_cleanup_oneshot — limpia una malla 3D en una sola llamada.
Promocion de la secuencia repetida (issue 0087) del post-proceso de mallas
Hunyuan3D: decimar a un presupuesto de caras razonable y, opcionalmente, hacerla
estanca. Capitaliza el "Golden 3" del report 0088 (80k caras + estanca a la vez).
Compone funciones del registry del grupo `comfyui`:
comfyui_simplify_mesh_py_ml (decima conservando apariencia)
comfyui_make_watertight_py_ml (cierra la malla; solo si watertight=True)
Las mallas nativas de ComfyUI/Hunyuan3D salen densas (decenas de MB, >1M caras) y
NO estancas (VoxelToMeshBasic produce "cube-soup"). Este pipeline las deja listas
para web/impresion: ligeras y, si se pide, cerradas.
Pipeline impuro: lee y escribe archivos en disco. Requiere trimesh + pymeshlab +
scipy (simplify) y, para method="voxel", scikit-image (make_watertight).
"""
from __future__ import annotations
import os
import sys
# Importa las funciones del registry (mismo arbol python/functions).
_FUNCTIONS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _FUNCTIONS_ROOT not in sys.path:
sys.path.insert(0, _FUNCTIONS_ROOT)
from ml.comfyui_make_watertight import comfyui_make_watertight
from ml.comfyui_simplify_mesh import comfyui_simplify_mesh
def comfyui_mesh_cleanup_oneshot(
in_path: str,
*,
target_faces: int = 80000,
watertight: bool = True,
method: str = "repair",
out_path: str | None = None,
) -> dict:
"""Decima una malla y, opcionalmente, la hace estanca, en una sola llamada.
Args:
in_path: ruta de la malla de entrada (.glb/.obj/.ply/.gltf/.stl/.off).
target_faces: caras objetivo del paso de decimacion (comfyui_simplify_mesh).
keyword-only.
watertight: si True (default) aplica comfyui_make_watertight tras decimar;
si False solo decima. keyword-only.
method: metodo de make_watertight cuando watertight=True. "repair" (default)
conserva las caras decimadas (fill_holes + fix_normals) pero NO garantiza
estanqueidad en mallas muy rotas; "voxel" GARANTIZA is_watertight=True via
voxeliza+fill+marching cubes, a costa de re-mallar (cambia el conteo de
caras y descarta apariencia). keyword-only.
out_path: ruta de salida final. Si None, se deriva de in_path
("<in>_cleaned.glb"). keyword-only.
Returns:
dict {ok, in_path, out_path, in_faces, simplified_faces, final_faces,
watertight_requested, is_watertight, method, steps, error}. `steps` es la
lista de resultados crudos de cada funcion compuesta (para auditar). Si algun
paso falla, ok=False y error explica en cual.
"""
base = {
"ok": False, "in_path": in_path, "out_path": "",
"in_faces": 0, "simplified_faces": 0, "final_faces": 0,
"watertight_requested": watertight, "is_watertight": None,
"method": method, "steps": [], "error": "",
}
if watertight and method not in ("repair", "voxel"):
return {**base, "error": f"method '{method}' invalido (usa 'repair' o 'voxel')"}
if out_path is None:
out_path = os.path.splitext(in_path)[0] + "_cleaned.glb"
# Paso 1: decimar. Si no se pide watertight, este es el output final directo.
simplify_out = out_path if not watertight else (
os.path.splitext(out_path)[0] + "_simplified.glb"
)
s = comfyui_simplify_mesh(in_path, target_faces=target_faces, out_path=simplify_out)
steps = [{"step": "simplify_mesh", **s}]
if not s.get("ok"):
return {**base, "steps": steps, "error": f"simplify_mesh fallo: {s.get('error')}"}
in_faces = s["in_faces"]
simplified_faces = s["out_faces"]
if not watertight:
return {
**base, "ok": True, "out_path": s["out_path"],
"in_faces": in_faces, "simplified_faces": simplified_faces,
"final_faces": simplified_faces, "is_watertight": None,
"steps": steps,
}
# Paso 2: hacer estanca la malla decimada.
w = comfyui_make_watertight(s["out_path"], method=method, out_path=out_path)
steps.append({"step": "make_watertight", **w})
if not w.get("ok"):
return {
**base, "out_path": s["out_path"],
"in_faces": in_faces, "simplified_faces": simplified_faces,
"final_faces": simplified_faces, "steps": steps,
"error": f"make_watertight fallo: {w.get('error')}",
}
return {
**base, "ok": True, "out_path": w["out_path"],
"in_faces": in_faces, "simplified_faces": simplified_faces,
"final_faces": w["out_faces"], "is_watertight": w["is_watertight"],
"steps": steps,
}
if __name__ == "__main__":
import json
src = sys.argv[1] if len(sys.argv) > 1 else (
os.path.expanduser("~/ComfyUI/output/3d_mesh_00002_.glb"))
res = comfyui_mesh_cleanup_oneshot(src)
print(json.dumps({k: v for k, v in res.items() if k != "steps"}, indent=2))
@@ -0,0 +1,89 @@
---
name: comfyui_txt2img_oneshot
kind: pipeline
lang: py
domain: pipelines
version: "1.0.0"
purity: impure
signature: "def comfyui_txt2img_oneshot(prompt: str, *, ckpt: str = \"dreamshaper_8.safetensors\", negative: str = \"\", server: str = \"127.0.0.1:8188\", dest: str | None = None, wait_timeout: float = 300.0, **gen) -> dict"
description: "Pipeline prompt de texto -> PNG en disco en una sola llamada. Construye el workflow txt2img de Stable Diffusion, lo encola en ComfyUI, espera y descarga la imagen. Compone comfyui_build_txt2img_workflow + comfyui_submit_workflow + comfyui_wait_result + comfyui_fetch_output_image. Promocion de secuencia (issue 0087). Impuro: HTTP + disco."
tags: [comfyui, pipelines, txt2img, stable-diffusion, launcher]
uses_functions: [comfyui_build_txt2img_workflow_py_ml, comfyui_submit_workflow_py_ml, comfyui_wait_result_py_ml, comfyui_fetch_output_image_py_ml]
uses_types: []
returns: []
returns_optional: false
error_type: error_py_core
imports: [comfyui_build_txt2img_workflow_py_ml, comfyui_submit_workflow_py_ml, comfyui_wait_result_py_ml, comfyui_fetch_output_image_py_ml]
params:
- name: prompt
desc: "Prompt positivo (lo que se quiere ver en la imagen)."
- name: ckpt
desc: "Checkpoint Stable Diffusion tal como lo ve el servidor (CheckpointLoaderSimple). Por defecto 'dreamshaper_8.safetensors'. keyword-only."
- name: negative
desc: "Prompt negativo. Por defecto ''. keyword-only."
- name: server
desc: "host:port del servidor ComfyUI (sin esquema). keyword-only."
- name: dest
desc: "Directorio local donde guardar el PNG (None = cwd). keyword-only."
- name: wait_timeout
desc: "Segundos maximos esperando a que el server termine. keyword-only."
- name: gen
desc: "Parametros de generacion pasados a comfyui_build_txt2img_workflow (steps, cfg, width, height, seed, sampler_name, scheduler, filename_prefix). keyword-only (**gen)."
output: "dict {ok, image_path, prompt_id, error}. image_path = ruta local del PNG descargado; prompt_id = id del trabajo en ComfyUI. Si falla, ok=False y error explica en que paso."
tested: false
tests: []
test_file_path: ""
file_path: "python/functions/pipelines/comfyui_txt2img_oneshot.py"
---
## Ejemplo
```bash
# Genera una imagen desde texto y la baja a /tmp.
./fn run comfyui_txt2img_oneshot "a red apple on a wooden table, sharp focus"
```
```python
import sys, os
sys.path.insert(0, os.path.join(os.environ["HOME"], "fn_registry", "python", "functions"))
from pipelines.comfyui_txt2img_oneshot import comfyui_txt2img_oneshot
res = comfyui_txt2img_oneshot(
"a red apple on a wooden table, sharp focus",
negative="blurry, low quality",
dest="/tmp/comfy_txt2img",
steps=20,
seed=42,
)
# res["ok"] == True
# res["image_path"] # ruta local del PNG
print(res["image_path"], res["prompt_id"])
```
## Cuando usarla
Cuando solo quieres "texto → imagen" sin montar el grafo a mano ni encadenar
submit/wait/fetch tú mismo. Es la forma de una sola llamada del flujo txt2img más
común. Para añadir detalle de caras encadénala con `comfyui_build_facedetailer_workflow`,
o para nitidez en alta con `comfyui_build_hires_fix_workflow` (esos son builders;
este pipeline ejecuta el camino básico end-to-end).
## Gotchas
- Impuro: requiere el **servidor ComfyUI vivo** en `server` (default
`127.0.0.1:8188`). Si está caído, falla en el paso submit con el error de conexión.
- `ckpt` debe existir en el servidor (CheckpointLoaderSimple). Default
`dreamshaper_8.safetensors`; cámbialo si usas SDXL u otro.
- `dest` es un **directorio** (se crea si no existe), no un nombre de archivo: el
PNG conserva el nombre que le da ComfyUI (`<filename_prefix>_NNNNN_.png`).
- `wait_timeout` por defecto 300 s. Subir resolución/steps puede requerir más; si
el server está cargando el modelo por primera vez, la primera generación tarda más.
- Devuelve el **primer** PNG de los outputs. Para batches de varias imágenes usa
`comfyui_batch_generate` o itera con distintos `seed`.
- No reintenta: si el server está ocupado con otra cola, encola igualmente y espera
su turno hasta `wait_timeout`.
## Capability growth log
- v1.0.0 (2026-06-24) — pipeline inicial. Compone build_txt2img + submit + wait +
fetch_output_image (issue 0087, roadmap del report 0092).
@@ -0,0 +1,117 @@
"""comfyui_txt2img_oneshot — prompt de texto -> PNG en disco en una sola llamada.
Promocion de la secuencia repetida (issue 0087): construir el workflow txt2img ->
encolar -> esperar -> descargar la imagen. Compone funciones del registry del
grupo `comfyui`:
comfyui_build_txt2img_workflow_py_ml (workflow de nodos en API format)
comfyui_submit_workflow_py_ml (POST /prompt)
comfyui_wait_result_py_ml (poll /history)
comfyui_fetch_output_image_py_ml (GET /view -> disco)
Pipeline impuro: red (HTTP) + escritura en disco.
"""
from __future__ import annotations
import os
import sys
# Importa las funciones del registry (mismo arbol python/functions).
_FUNCTIONS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _FUNCTIONS_ROOT not in sys.path:
sys.path.insert(0, _FUNCTIONS_ROOT)
from ml.comfyui_build_txt2img_workflow import comfyui_build_txt2img_workflow
from ml.comfyui_fetch_output_image import comfyui_fetch_output_image
from ml.comfyui_submit_workflow import comfyui_submit_workflow
from ml.comfyui_wait_result import comfyui_wait_result
def comfyui_txt2img_oneshot(
prompt: str,
*,
ckpt: str = "dreamshaper_8.safetensors",
negative: str = "",
server: str = "127.0.0.1:8188",
dest: str | None = None,
wait_timeout: float = 300.0,
**gen,
) -> dict:
"""Genera una imagen desde un prompt de texto, end-to-end.
Args:
prompt: prompt positivo (lo que se quiere ver en la imagen).
ckpt: checkpoint Stable Diffusion tal como lo ve el servidor
(CheckpointLoaderSimple). Por defecto "dreamshaper_8.safetensors".
keyword-only.
negative: prompt negativo. Por defecto "". keyword-only.
server: host:port del servidor ComfyUI (sin esquema). keyword-only.
dest: directorio local donde guardar el PNG (None = cwd). keyword-only.
wait_timeout: segundos maximos esperando a que el server termine.
keyword-only.
**gen: parametros de generacion pasados a comfyui_build_txt2img_workflow
(steps, cfg, width, height, seed, sampler_name, scheduler,
filename_prefix).
Returns:
dict {ok, image_path, prompt_id, error}. image_path = ruta local del PNG
descargado; prompt_id = id del trabajo en ComfyUI. Si falla, ok=False y
error explica en que paso.
"""
# 1. Construir el workflow (funcion pura del registry).
workflow = comfyui_build_txt2img_workflow(ckpt, prompt, negative, **gen)
# 2. Encolar.
try:
sub = comfyui_submit_workflow(workflow, server=server)
prompt_id = sub["prompt_id"]
except (RuntimeError, KeyError) as exc:
return {"ok": False, "image_path": "", "prompt_id": "",
"error": f"submit fallo: {exc}"}
# 3. Esperar a que termine.
try:
outputs = comfyui_wait_result(prompt_id, server=server, timeout=wait_timeout)
except (TimeoutError, RuntimeError) as exc:
return {"ok": False, "image_path": "", "prompt_id": prompt_id,
"error": f"wait fallo: {exc}"}
# 4. Localizar el primer PNG en los outputs (nodo SaveImage -> images).
img = None
for node_out in outputs.values():
images = node_out.get("images") if isinstance(node_out, dict) else None
if images:
img = images[0]
break
if img is None:
return {"ok": False, "image_path": "", "prompt_id": prompt_id,
"error": f"el workflow no produjo imagenes (outputs={list(outputs)})"}
# 5. Descargar la imagen a disco.
fetched = comfyui_fetch_output_image(
img["filename"],
subfolder=img.get("subfolder", ""),
type_=img.get("type", "output"),
server=server,
dest_dir=dest or ".",
)
if not fetched.get("ok"):
return {"ok": False, "image_path": "", "prompt_id": prompt_id,
"error": f"fetch de imagen fallo: {fetched.get('error')}"}
return {"ok": True, "image_path": fetched["path"], "prompt_id": prompt_id,
"error": ""}
if __name__ == "__main__":
import json
res = comfyui_txt2img_oneshot(
"a red apple on a wooden table, sharp focus",
negative="blurry, low quality",
dest="/tmp/comfy_txt2img",
steps=20,
seed=42,
)
print(json.dumps(res, indent=2))