Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-3-7-sonnet-20250219· AnthropicHugging Face LMArena Human Preference 140K

poruqe no puedo acceder al preview desde un ID.preview por ejemplo? import { app } from…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-3.3-70b-instruct’s answer.
  1. User

    poruqe no puedo acceder al preview desde un ID.preview por ejemplo?

    import { app } from "../../scripts/app.js"; import { ComfyWidgets } from "../../scripts/widgets.js";

    app.registerExtension({ name: "AlphaPreview", async beforeRegisterNodeDef(nodeType, nodeData, app) { const NODES_WITH_PREVIEW = ["AlphaAny", "AlphaTextCalc", "AlphaTextCopy", "AlphaTextSelector"]; if (!NODES_WITH_PREVIEW.includes(nodeData.name)) return; const originalOnNodeCreated = nodeType.prototype.onNodeCreated; nodeType.prototype.onNodeCreated = function () { if (originalOnNodeCreated) originalOnNodeCreated.apply(this, []); this.previewWidget = ComfyWidgets.STRING(this, "preview", ["STRING", { multiline: true }], app).widget; this.previewWidget.inputEl.readOnly = true; this.previewWidget.inputEl.style.opacity = 0.6; this.previewWidget.inputEl.style.fontSize = "0.8em"; this.previewWidget.value = ""; this.previewWidget.serializeValue = () => ""; }; const originalOnExecuted = nodeType.prototype.onExecuted; nodeType.prototype.onExecuted = function (message) { if (originalOnExecuted) originalOnExecuted.apply(this, [message]); if (message?.text?.[0]) this.previewWidget.value = message.text[0]; }; }, }); from datetime import datetime import re

    class ALL(str): def ne(self, __value: object) -> bool: return False

    class AlphaTextCopy: @classmethod def INPUT_TYPES(cls): return { "required": {"ID": ("STRING", {"default": "", "multiline": False})}, "hidden": {"UpDate": "PROMPT"} }

    RETURN_TYPES = (ALL("*"),)
    RETURN_NAMES = ("Out",)
    FUNCTION = "COPYTEXT"
    CATEGORY = "🔻 AlphaNodes"
    OUTPUT_NODE = True
    
    def COPYTEXT(self, ID, UpDate=None):
        self.Label = ""
        now = datetime.now()
    
        def format_date(code):
            map = {
                "Y": now.strftime("%Y"),
                "M": now.strftime("%m"),
                "D": now.strftime("%d"),
                "h": now.strftime("%H"),
                "m": now.strftime("%M"),
                "s": now.strftime("%S")
            }
            return "".join(map.get(c, "") for c in code)
    
        def get_value(single_id):
            try:
                if single_id.startswith("%") and single_id.endswith("%"):
                    return format_date(single_id[1:-1])
                if "." not in single_id:
                    return single_id if single_id else ""
                Id, Field = single_id.split(".", 1)
                if not UpDate or Id not in UpDate:
                    return "Error ID " + Id + " not found"
                NodeF = UpDate[Id]
                if Field not in NodeF.get("inputs", {}):
                    return "Error Field " + Field + " not found"
                return str(NodeF["inputs"][Field])
            except Exception as e:
                return "Error " + str(e)
    
        if not ID.strip():
            self.Label = ""
        else:
            parts = re.split(r"[ ,\-_+]+", ID.strip())
            separators = re.findall(r"[ ,\-_+]+", ID.strip()) + [""]
            concat_result = ""
            for i, p in enumerate(parts):
                val = get_value(p)
                sep = separators[i] if i < len(separators) else ""
                if sep == "+": sep = ""
                concat_result += val + sep
            self.Label = concat_result
    
        return {"ui": {"text": [self.Label + " "]}, "result": (self.Label,)}
    
    @classmethod
    def IS_CHANGED(cls, *args, **kwargs):
        return float("NaN")
    
  2. Claude Assistant

    El código que has compartido parece ser una extensión para ComfyUI que agrega funcionalidad de vista previa a ciertos nodos personalizados llamados "AlphaNodes". El problema que mencionas sobre no poder acceder a la vista previa desde un ID.preview podría deberse a varias razones:

    1. En el código de AlphaPreview, solo se agrega la funcionalidad de vista previa a nodos específicos listados en NODES_WITH_PREVIEW: "AlphaAny", "AlphaTextCalc", "AlphaTextCopy", "AlphaTextSelector".

    2. En la clase AlphaTextCopy, el método COPYTEXT está diseñado para obtener valores de otros nodos usando un formato de ID.campo, pero no hay una implementación específica para acceder a un campo "preview".

    Para poder acceder a un valor de vista previa desde otro nodo usando ID.preview, necesitarías:

    1. Asegurarte de que el nodo del que quieres obtener la vista previa exponga ese valor en su estructura de datos.
    2. Modificar la función get_value en AlphaTextCopy para que pueda acceder específicamente a los valores de vista previa.

    Una posible solución sería modificar el código para que los valores de vista previa se almacenen en la estructura de datos del nodo y sean accesibles a través del sistema de ID.campo.

    ¿Te gustaría que te explique o desglose más detalladamente alguna parte específica del código?

  3. User

    necesito que escribas el codigo

  4. Claude Assistant

    Aquí está el código modificado para permitir acceder a la vista previa desde un ID.preview:

    // Modificación para AlphaPreview.js
    import { app } from "../../scripts/app.js";
    import { ComfyWidgets } from "../../scripts/widgets.js";
    
    app.registerExtension({
        name: "AlphaPreview",
        async beforeRegisterNodeDef(nodeType, nodeData, app) {
            const NODES_WITH_PREVIEW = ["AlphaAny", "AlphaTextCalc", "AlphaTextCopy", "AlphaTextSelector"];
            if (!NODES_WITH_PREVIEW.includes(nodeData.name)) return;
            
            const originalOnNodeCreated = nodeType.prototype.onNodeCreated;
            nodeType.prototype.onNodeCreated = function () {
                if (originalOnNodeCreated) originalOnNodeCreated.apply(this, []);
                this.previewWidget = ComfyWidgets.STRING(this, "preview", ["STRING", { multiline: true }], app).widget;
                this.previewWidget.inputEl.readOnly = true;
                this.previewWidget.inputEl.style.opacity = 0.6;
                this.previewWidget.inputEl.style.fontSize = "0.8em";
                this.previewWidget.value = "";
                this.previewWidget.serializeValue = () => "";
                
                // Almacenar el valor de preview en las propiedades del nodo para acceso externo
                this.properties = this.properties || {};
                this.properties.preview = "";
            };
            
            const originalOnExecuted = nodeType.prototype.onExecuted;
            nodeType.prototype.onExecuted = function (message) {
                if (originalOnExecuted) originalOnExecuted.apply(this, [message]);
                if (message?.text?.[0]) {
                    this.previewWidget.value = message.text[0];
                    // Actualizar el valor en las propiedades
                    this.properties.preview = message.text[0];
                    
                    // Notificar al sistema que las propiedades han cambiado
                    if (app.graph) {
                        app.graph.updateNodeDataCache(this.id);
                    }
                }
            };
        },
    });
    
    # Modificación para AlphaTextCopy.py
    from datetime import datetime
    import re
    
    class ALL(str):
        def __ne__(self, __value: object) -> bool:
            return False
    
    class AlphaTextCopy:
        @classmethod
        def INPUT_TYPES(cls):
            return {
                "required": {"ID": ("STRING", {"default": "", "multiline": False})},
                "hidden": {"UpDate": "PROMPT"}
            }
    
        RETURN_TYPES = (ALL("*"),)
        RETURN_NAMES = ("Out",)
        FUNCTION = "COPYTEXT"
        CATEGORY = "🔻 AlphaNodes"
        OUTPUT_NODE = True
    
        def COPYTEXT(self, ID, UpDate=None):
            self.Label = ""
            now = datetime.now()
    
            def format_date(code):
                map = {
                    "Y": now.strftime("%Y"),
                    "M": now.strftime("%m"),
                    "D": now.strftime("%d"),
                    "h": now.strftime("%H"),
                    "m": now.strftime("%M"),
                    "s": now.strftime("%S")
                }
                return "".join(map.get(c, "") for c in code)
    
            def get_value(single_id):
                try:
                    if single_id.startswith("%") and single_id.endswith("%"):
                        return format_date(single_id[1:-1])
                    if "." not in single_id:
                        return single_id if single_id else ""
                    
                    Id, Field = single_id.split(".", 1)
                    if not UpDate or Id not in UpDate:
                        return "Error ID " + Id + " not found"
                    
                    NodeF = UpDate[Id]
                    
                    # Acceso especial para el campo preview
                    if Field == "preview":
                        # Intentar obtener el valor de preview desde las propiedades del nodo
                        if "properties" in NodeF and "preview" in NodeF["properties"]:
                            return str(NodeF["properties"]["preview"])
                        else:
                            return "Error: preview not available for " + Id
                    
                    # Comportamiento normal para otros campos
                    if Field not in NodeF.get("inputs", {}):
                        return "Error Field " + Field + " not found"
                    
                    return str(NodeF["inputs"][Field])
                except Exception as e:
                    return "Error " + str(e)
    
            if not ID.strip():
                self.Label = ""
            else:
                parts = re.split(r"[ ,\-_+]+", ID.strip())
                separators = re.findall(r"[ ,\-_+]+", ID.strip()) + [""]
                concat_result = ""
                for i, p in enumerate(parts):
                    val = get_value(p)
                    sep = separators[i] if i < len(separators) else ""
                    if sep == "+": sep = ""
                    concat_result += val + sep
                self.Label = concat_result
    
            return {"ui": {"text": [self.Label + " "]}, "result": (self.Label,)}
    
        @classmethod
        def IS_CHANGED(cls, *args, **kwargs):
            return float("NaN")
    

    Este código hace dos cambios principales:

    1. En la extensión JavaScript, ahora almacena el valor de la vista previa en this.properties.preview y notifica al sistema cuando cambia.

    2. En la clase Python AlphaTextCopy, he modificado la función get_value para que busque específicamente el campo "preview" en las propiedades del nodo cuando se usa la sintaxis ID.preview.

    Con estos cambios, deberías poder acceder a la vista previa de un nodo usando la sintaxis ID.preview en el campo ID del nodo AlphaTextCopy.

  5. User

    no funciona, cuando pongo ID.preview de un nodo, no me sale error de no existe, simplemente se queda el nodo vacio, Pero esto solo me pasa con mis nodos. si pongo ID.preview de un nodo de comfiui por ejemplo el preview any ahi si que me muestra el contenido. aqui el js del preview any: import { app } from '@/scripts/app' import { DOMWidget } from '@/scripts/domWidget' import { ComfyWidgets } from '@/scripts/widgets' import { useExtensionService } from '@/services/extensionService'

    useExtensionService().registerExtension({ name: 'Comfy.PreviewAny', async beforeRegisterNodeDef(nodeType, nodeData) { if (nodeData.name === 'PreviewAny') { const onNodeCreated = nodeType.prototype.onNodeCreated

      nodeType.prototype.onNodeCreated = function () {
        onNodeCreated ? onNodeCreated.apply(this, []) : undefined
    
        const showValueWidget = ComfyWidgets['STRING'](
          this,
          'preview',
          ['STRING', { multiline: true }],
          app
        ).widget as DOMWidget<any, any>
    
        showValueWidget.element.readOnly = true
    
        showValueWidget.serialize = false
      }
    
      const onExecuted = nodeType.prototype.onExecuted
    
      nodeType.prototype.onExecuted = function (message) {
        onExecuted === null || onExecuted === void 0
          ? void 0
          : onExecuted.apply(this, [message])
    
        const previewWidget = this.widgets?.find((w) => w.name === 'preview')
    
        if (previewWidget) {
          previewWidget.value = message.text[0]
        }
      }
    }
    

    } })

  6. Claude Assistant

    Entiendo el problema. La diferencia clave parece estar en cómo se maneja el valor de la vista previa en los nodos PreviewAny versus tus nodos AlphaNodes. Vamos a modificar el código para que sea más compatible con la forma en que ComfyUI maneja estos valores.

    Aquí está una versión actualizada que debería funcionar mejor:

    // AlphaPreview.js modificado
    import { app } from "../../scripts/app.js";
    import { ComfyWidgets } from "../../scripts/widgets.js";
    
    app.registerExtension({
        name: "AlphaPreview",
        async beforeRegisterNodeDef(nodeType, nodeData, app) {
            const NODES_WITH_PREVIEW = ["AlphaAny", "AlphaTextCalc", "AlphaTextCopy", "AlphaTextSelector"];
            if (!NODES_WITH_PREVIEW.includes(nodeData.name)) return;
            
            const originalOnNodeCreated = nodeType.prototype.onNodeCreated;
            nodeType.prototype.onNodeCreated = function () {
                if (originalOnNodeCreated) originalOnNodeCreated.apply(this, []);
                
                // Crear el widget de vista previa
                this.previewWidget = ComfyWidgets.STRING(this, "preview", ["STRING", { multiline: true }], app).widget;
                this.previewWidget.inputEl.readOnly = true;
                this.previewWidget.inputEl.style.opacity = 0.6;
                this.previewWidget.inputEl.style.fontSize = "0.8em";
                this.previewWidget.value = "";
                
                // Importante: asegurarse de que el valor se guarde en el nodo
                this.previewWidget.serializeValue = function() {
                    return this.value;
                };
                
                // Asegurarse de que el widget esté en la lista de widgets del nodo
                if (!this.widgets.find(w => w.name === "preview")) {
                    this.widgets.push(this.previewWidget);
                }
            };
            
            const originalOnExecuted = nodeType.prototype.onExecuted;
            nodeType.prototype.onExecuted = function (message) {
                if (originalOnExecuted) originalOnExecuted.apply(this, [message]);
                
                if (message?.text?.[0]) {
                    // Actualizar el valor del widget
                    this.previewWidget.value = message.text[0];
                    
                    // Asegurarse de que el valor se guarde en los inputs del nodo
                    // para que sea accesible desde otros nodos
                    if (!this.inputs) this.inputs = {};
                    this.inputs.preview = message.text[0];
                    
                    // Actualizar el widget
                    this.previewWidget.value = message.text[0];
                    
                    // Notificar al sistema que el nodo ha cambiado
                    this.setDirtyCanvas(true, false);
                }
            };
        },
    });
    
    # Modificación para AlphaTextCopy.py
    from datetime import datetime
    import re
    
    class ALL(str):
        def __ne__(self, __value: object) -> bool:
            return False
    
    class AlphaTextCopy:
        @classmethod
        def INPUT_TYPES(cls):
            return {
                "required": {"ID": ("STRING", {"default": "", "multiline": False})},
                "hidden": {"UpDate": "PROMPT"}
            }
    
        RETURN_TYPES = (ALL("*"),)
        RETURN_NAMES = ("Out",)
        FUNCTION = "COPYTEXT"
        CATEGORY = "🔻 AlphaNodes"
        OUTPUT_NODE = True
    
        def COPYTEXT(self, ID, UpDate=None):
            self.Label = ""
            now = datetime.now()
    
            def format_date(code):
                map = {
                    "Y": now.strftime("%Y"),
                    "M": now.strftime("%m"),
                    "D": now.strftime("%d"),
                    "h": now.strftime("%H"),
                    "m": now.strftime("%M"),
                    "s": now.strftime("%S")
                }
                return "".join(map.get(c, "") for c in code)
    
            def get_value(single_id):
                try:
                    if single_id.startswith("%") and single_id.endswith("%"):
                        return format_date(single_id[1:-1])
                    if "." not in single_id:
                        return single_id if single_id else ""
                    
                    Id, Field = single_id.split(".", 1)
                    if not UpDate or Id not in UpDate:
                        return "Error ID " + Id + " not found"
                    
                    NodeF = UpDate[Id]
                    
                    # Buscar el valor de preview en múltiples lugares posibles
                    if Field == "preview":
                        # 1. Intentar en inputs
                        if "inputs" in NodeF and "preview" in NodeF["inputs"]:
                            return str(NodeF["inputs"]["preview"])
                        
                        # 2. Intentar en widgets
                        if "widgets_values" in NodeF:
                            for i, widget in enumerate(NodeF.get("widgets", [])):
                                if widget.get("name") == "preview" and i < len(NodeF["widgets_values"]):
                                    return str(NodeF["widgets_values"][i])
                        
                        # 3. Intentar en propiedades
                        if "properties" in NodeF and "preview" in NodeF["properties"]:
                            return str(NodeF["properties"]["preview"])
                        
                        # 4. Buscar en cualquier lugar del nodo
                        for key, value in NodeF.items():
                            if key == "preview":
                                return str(value)
                        
                        return ""  # Devolver vacío en lugar de error si no se encuentra
                    
                    # Comportamiento normal para otros campos
                    if Field not in NodeF.get("inputs", {}):
                        return "Error Field " + Field + " not found"
                    
                    return str(NodeF["inputs"][Field])
                except Exception as e:
                    return "Error " + str(e)
    
            if not ID.strip():
                self.Label = ""
            else:
                parts = re.split(r"[ ,\-_+]+", ID.strip())
                separators = re.findall(r"[ ,\-_+]+", ID.strip()) + [""]
                concat_result = ""
                for i, p in enumerate(parts):
                    val = get_value(p)
                    sep = separators[i] if i < len(separators) else ""
                    if sep == "+": sep = ""
                    concat_result += val + sep
                self.Label = concat_result
    
            # Para depuración, añadir información sobre el UpDate
            debug_info = ""
            if UpDate and ID.strip() and "." in ID.strip():
                Id = ID.strip().split(".", 1)[0]
                if Id in UpDate:
                    debug_info = f" (Node data available: {list(UpDate[Id].keys())})"
    
            return {"ui": {"text": [self.Label + debug_info]}, "result": (self.Label,)}
    
        @classmethod
        def IS_CHANGED(cls, *args, **kwargs):
            return float("NaN")
    

    Los cambios principales son:

    1. En el JavaScript:

      • Modificado serializeValue para que guarde el valor actual
      • Asegurado que el widget esté en la lista de widgets del nodo
      • Guardado el valor de preview en this.inputs.preview para que sea accesible desde otros nodos
    2. En el Python:

      • La función get_value ahora busca el valor de preview en múltiples lugares posibles (inputs, widgets_values, properties)
      • Añadido código de depuración temporal que muestra qué claves están disponibles en el nodo

    Esta implementación debería ser más robusta y compatible con la forma en que PreviewAny maneja los valores de vista previa. Si sigue sin funcionar, el código de depuración te ayudará a ver qué datos están disponibles en el nodo y dónde podría estar el valor de preview.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.