<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8">
  <title>Sharp / Noise / Blur-Loss Maps + Time</title>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    canvas { border: 1px solid #ccc; margin: 10px; }
    .row { margin: 10px 0; }
    label { display: inline-block; width: 200px; }
    input[type="number"] { width: 60px; }
    .canvases { display: flex; flex-wrap: wrap; }
    .canvases > div { text-align: center; margin-right: 20px; }
    #timeVal { font-weight: bold; margin-left: 5px; }
  </style>
</head>
<body>
TODO
сделай на основе этого comfyui node
с вариантом из гаусового размытия
входные параметры - рисунок и Квантиль Blur-Loss %
выход - рисунок чернобелый rgb или как там принято в comfyui

  <h2>1. Загрузите изображение</h2>
  <input type="file" id="fileInput" accept="image/*">

  <div class="row">
    <canvas id="inputCanvas" width="300" height="200"></canvas>
  </div>

  <h2>2. Параметры</h2>
  <div class="row">
    <label for="qSharp">Квантиль Sharp (Laplace) %</label>
    <input type="number" id="qSharp" value="80" min="50" max="100">  
  </div>
  <div class="row">
    <label for="qNoise">Квантиль Noise (σ 5×5) %</label>
    <input type="number" id="qNoise" value="95" min="50" max="100">  
  </div>
  <div class="row">
    <label for="qBlur">Квантиль Blur-Loss %</label>
    <input type="number" id="qBlur" value="90" min="50" max="100">  
  </div>
  <button id="btnCompute">Compute</button>

  <div class="row">
    <label>Время расчёта:</label>
    <span id="timeVal">—</span> ms
  </div>

  <h2>3. Результаты</h2>
  <div class="canvases">
    <div>
      <div>Sharpness Map</div>
      <canvas id="sharpMap" width="300" height="200"></canvas>
    </div>
    <div>
      <div>Noise Map</div>
      <canvas id="noiseMap" width="300" height="200"></canvas>
    </div>
    <div>
      <div>Blur-Loss Map применять гауссово размытие и смотреть, где потери детализации максимальны.</div>
      <canvas id="blurMap" width="300" height="200"></canvas>
    </div>
  </div>

<script>
(function(){
  const fileInput   = document.getElementById('fileInput');
  const inputCanvas = document.getElementById('inputCanvas');
  const ctxIn       = inputCanvas.getContext('2d');
  const sharpMap    = document.getElementById('sharpMap');
  const noiseMap    = document.getElementById('noiseMap');
  const blurMap     = document.getElementById('blurMap');
  const ctxSharp    = sharpMap.getContext('2d');
  const ctxNoise    = noiseMap.getContext('2d');
  const ctxBlur     = blurMap.getContext('2d');
  const timeVal     = document.getElementById('timeVal');

  // Загрузка изображения
  fileInput.addEventListener('change', e => {
    const file = e.target.files[0];
    if(!file) return;
    const img = new Image();
    img.onload = () => {
      [inputCanvas, sharpMap, noiseMap, blurMap].forEach(c => {
        c.width  = img.width;
        c.height = img.height;
      });
      ctxIn.drawImage(img, 0,0);
    };
    img.src = URL.createObjectURL(file);
  });

  document.getElementById('btnCompute')
          .addEventListener('click', computeMaps);

  function computeMaps(){
    const w = inputCanvas.width, h = inputCanvas.height;
    if(w===0||h===0){
      alert('Сначала загрузите изображение');
      return;
    }

    const t0 = performance.now();  // старт таймера

    // 1) читаем и переводим в серый
    const imgData = ctxIn.getImageData(0,0,w,h);
    const gray    = new Float32Array(w*h);
    for(let i=0,p=0; i<w*h; i++,p+=4){
      gray[i] = 0.299*imgData.data[p]
              + 0.587*imgData.data[p+1]
              + 0.114*imgData.data[p+2];
    }

    // 2) Sharpness: Variance of Laplacian
    const laplace = [0,1,0, 1,-4,1, 0,1,0];
    const lapVar  = new Float32Array(w*h);
    for(let y=1; y<h-1; y++){
      for(let x=1; x<w-1; x++){
        let sum=0, idx=0;
        for(let dy=-1; dy<=1; dy++){
          for(let dx=-1; dx<=1; dx++, idx++){
            sum += laplace[idx] * gray[(y+dy)*w + (x+dx)];
          }
        }
        lapVar[y*w + x] = Math.abs(sum);
      }
    }

    // 3) Noise: σ в окне 5×5
    const sigma   = new Float32Array(w*h);
    for(let y=2; y<h-2; y++){
      for(let x=2; x<w-2; x++){
        let sum=0, sum2=0, cnt=0;
        for(let dy=-2; dy<=2; dy++){
          for(let dx=-2; dx<=2; dx++){
            const v = gray[(y+dy)*w + (x+dx)];
            sum  += v; sum2 += v*v; cnt++;
          }
        }
        const m = sum/cnt;
        sigma[y*w + x] = Math.sqrt(sum2/cnt - m*m);
      }
    }

    // 4) Blur-Loss: Гауссово размытие 5×5 σ=1
    const gk      = makeGaussianKernel(5,1.0);
    const blurred = convolution(gray, gk, w, h);
    const blurLoss= new Float32Array(w*h);
    for(let i=0; i<w*h; i++){
      blurLoss[i] = Math.abs(gray[i] - blurred[i]);
    }

    // 5) Пороги по квантилям
    const tSharp = quantile(lapVar, parseFloat(qSharp.value)/100);
    const tNoise = quantile(sigma,  parseFloat(qNoise.value)/100);
    const tBlur  = quantile(blurLoss,parseFloat(qBlur.value)/100);

    // 6) Рисуем оверлеи
    drawOverlay(ctxSharp, imgData, lapVar,   tSharp, [0,255,0,180]);
    drawOverlay(ctxNoise, imgData, sigma,    tNoise, [0,0,255,180]);
    drawOverlay(ctxBlur,  imgData, blurLoss, tBlur,  [255,255,0,180]);

    const t1 = performance.now();  // конец таймера
    timeVal.textContent = (t1 - t0).toFixed(1);
  }

  // Вспомог: квантиль массива
  function quantile(arr, q){
    const tmp = Array.from(arr).filter(v=>v>0).sort((a,b)=>a-b);
    const idx = Math.floor(tmp.length * q);
    return tmp[idx]||0;
  }

  // Вспомог: рисует oверлей
  function drawOverlay(ctx, imgData, metric, thresh, color){
    const w = imgData.width, h = imgData.height;
    // исходный фон
    ctx.clearRect(0,0,w,h);
    ctx.putImageData(imgData, 0,0);
    // маска
    const mask = new Uint8ClampedArray(imgData.data);
    for(let i=0,p=0; i<w*h; i++,p+=4){
      if(metric[i] >= thresh){
        mask[p]   = color[0];
        mask[p+1] = color[1];
        mask[p+2] = color[2];
        mask[p+3] = color[3];
      } else {
        mask[p+3] = 0;
      }
    }
    ctx.putImageData(new ImageData(mask,w,h), 0,0);
  }

  // Вспомог: Gaussian kernel
  function makeGaussianKernel(size, sigma){
    const k = [], half = Math.floor(size/2), s2=2*sigma*sigma;
    let sum=0;
    for(let y=-half; y<=half; y++){
      for(let x=-half; x<=half; x++){
        const v = Math.exp(-(x*x+y*y)/s2) / (Math.PI*s2);
        k.push(v); sum+=v;
      }
    }
    return k.map(v=>v/sum);
  }

  // Вспомог: свёртка
  function convolution(gray, kernel, w, h){
    const size = Math.sqrt(kernel.length)|0, half = Math.floor(size/2);
    const out = new Float32Array(w*h);
    for(let y=0; y<h; y++){
      for(let x=0; x<w; x++){
        let sum=0, idx=0;
        for(let dy=-half; dy<=half; dy++){
          for(let dx=-half; dx<=half; dx++,idx++){
            const yy = Math.min(h-1, Math.max(0, y+dy));
            const xx = Math.min(w-1, Math.max(0, x+dx));
            sum += kernel[idx] * gray[yy*w + xx];
          }
        }
        out[y*w + x] = sum;
      }
    }
    return out;
  }

  // короткие ссылки на элементы
  const qSharp = document.getElementById('qSharp');
  const qNoise = document.getElementById('qNoise');
  const qBlur  = document.getElementById('qBlur');

})();
</script>

</body>
</html>
class Example:
    """
    A example node

    Class methods
    -------------
    INPUT_TYPES (dict):
        Tell the main program input parameters of nodes.
    IS_CHANGED:
        optional method to control when the node is re executed.

    Attributes
    ----------
    RETURN_TYPES (`tuple`):
        The type of each element in the output tuple.
    RETURN_NAMES (`tuple`):
        Optional: The name of each output in the output tuple.
    FUNCTION (`str`):
        The name of the entry-point method. For example, if `FUNCTION = "execute"` then it will run Example().execute()
    OUTPUT_NODE ([`bool`]):
        If this node is an output node that outputs a result/image from the graph. The SaveImage node is an example.
        The backend iterates on these output nodes and tries to execute all their parents if their parent graph is properly connected.
        Assumed to be False if not present.
    CATEGORY (`str`):
        The category the node should appear in the UI.
    DEPRECATED (`bool`):
        Indicates whether the node is deprecated. Deprecated nodes are hidden by default in the UI, but remain
        functional in existing workflows that use them.
    EXPERIMENTAL (`bool`):
        Indicates whether the node is experimental. Experimental nodes are marked as such in the UI and may be subject to
        significant changes or removal in future versions. Use with caution in production workflows.
    execute(s) -> tuple || None:
        The entry point method. The name of this method must be the same as the value of property `FUNCTION`.
        For example, if `FUNCTION = "execute"` then this method's name must be `execute`, if `FUNCTION = "foo"` then it must be `foo`.
    """
    def __init__(self):
        pass

    @classmethod
    def INPUT_TYPES(s):
        """
            Return a dictionary which contains config for all input fields.
            Some types (string): "MODEL", "VAE", "CLIP", "CONDITIONING", "LATENT", "IMAGE", "INT", "STRING", "FLOAT".
            Input types "INT", "STRING" or "FLOAT" are special values for fields on the node.
            The type can be a list for selection.

            Returns: `dict`:
                - Key input_fields_group (`string`): Can be either required, hidden or optional. A node class must have property `required`
                - Value input_fields (`dict`): Contains input fields config:
                    * Key field_name (`string`): Name of a entry-point method's argument
                    * Value field_config (`tuple`):
                        + First value is a string indicate the type of field or a list for selection.
                        + Second value is a config for type "INT", "STRING" or "FLOAT".
        """
        return {
            "required": {
                "image": ("IMAGE",),
                "int_field": ("INT", {
                    "default": 0, 
                    "min": 0, #Minimum value
                    "max": 4096, #Maximum value
                    "step": 64, #Slider's step
                    "display": "number", # Cosmetic only: display as "number" or "slider"
                    "lazy": True # Will only be evaluated if check_lazy_status requires it
                }),
                "float_field": ("FLOAT", {
                    "default": 1.0,
                    "min": 0.0,
                    "max": 10.0,
                    "step": 0.01,
                    "round": 0.001, #The value representing the precision to round to, will be set to the step value by default. Can be set to False to disable rounding.
                    "display": "number",
                    "lazy": True
                }),
                "print_to_screen": (["enable", "disable"],),
                "string_field": ("STRING", {
                    "multiline": False, #True if you want the field to look like the one on the ClipTextEncode node
                    "default": "Hello World!",
                    "lazy": True
                }),
            },
        }

    RETURN_TYPES = ("IMAGE",)
    #RETURN_NAMES = ("image_output_name",)

    FUNCTION = "test"

    #OUTPUT_NODE = False

    CATEGORY = "Example"

    def check_lazy_status(self, image, string_field, int_field, float_field, print_to_screen):
        """
            Return a list of input names that need to be evaluated.

            This function will be called if there are any lazy inputs which have not yet been
            evaluated. As long as you return at least one field which has not yet been evaluated
            (and more exist), this function will be called again once the value of the requested
            field is available.

            Any evaluated inputs will be passed as arguments to this function. Any unevaluated
            inputs will have the value None.
        """
        if print_to_screen == "enable":
            return ["int_field", "float_field", "string_field"]
        else:
            return []

    def test(self, image, string_field, int_field, float_field, print_to_screen):
        if print_to_screen == "enable":
            print(f"""Your input contains:
                string_field aka input text: {string_field}
                int_field: {int_field}
                float_field: {float_field}
            """)
        #do some processing on the image, in this example I just invert it
        image = 1.0 - image
        return (image,)

    """
        The node will always be re executed if any of the inputs change but
        this method can be used to force the node to execute again even when the inputs don't change.
        You can make this node return a number or a string. This value will be compared to the one returned the last time the node was
        executed, if it is different the node will be executed again.
        This method is used in the core repo for the LoadImage node where they return the image hash as a string, if the image hash
        changes between executions the LoadImage node is executed again.
    """
    #@classmethod
    #def IS_CHANGED(s, image, string_field, int_field, float_field, print_to_screen):
    #    return ""

# Set the web directory, any .js file in that directory will be loaded by the frontend as a frontend extension
# WEB_DIRECTORY = "./somejs"


# Add custom API routes, using router
from aiohttp import web
from server import PromptServer

@PromptServer.instance.routes.get("/hello")
async def get_hello(request):
    return web.json_response("hello")


# A dictionary that contains all nodes you want to export with their names
# NOTE: names should be globally unique
NODE_CLASS_MAPPINGS = {
    "Example": Example
}

# A dictionary that contains the friendly/humanly readable titles for the nodes
NODE_DISPLAY_NAME_MAPPINGS = {
    "Example": "Example Node"
}