#!/usr/bin/env python3
"""Inventario de .safetensors em Python PURO - nao precisa de torch.

Aceita arquivo local OU URL https. Em URL usa HTTP Range, entao da para
inspecionar um arquivo de 7.8 GB lendo uns 2 MB (so o header + os tensores
que interessam).

uso:
  python safetensors_probe.py ALVO [ALVO ...]        inventario + checagem de valores
  python safetensors_probe.py --chaves ALVO          so a lista de chaves
  python safetensors_probe.py --linhas 64 ALVO       limita quantas linhas sao lidas
  python safetensors_probe.py --colunas "ALVO::tens" quantas colunas tem valor (pega
                                                     CURVE disfarcado de FULL)
  python safetensors_probe.py --compara "A::tens_a[@linha]" "B::tens_b[@linha]"

Em --compara e --colunas, ALVO::tensor aceita um sufixo: o script acha a chave
pelo fim dela, entao nao precisa acertar o prefixo (model.diffusion_model. etc).

ALVO pode ser:
  I:\\...\\modelo.safetensors
  https://huggingface.co/ORG/REPO/resolve/main/pasta/modelo.safetensors

Confere tambem os VALORES (NaN, inf, |max|) e nao so o nome das chaves.
"""

import json
import os
import re
import struct
import sys
import urllib.request

PADRAO = re.compile(r"adaln|t_table|t_emb|basis|time_embed|norm|mean", re.I)
MAXLIN = 512
LIMITE = 1000.0

ITENS = {"F64": 8, "F32": 4, "F16": 2, "BF16": 2, "I64": 8, "I32": 4, "I16": 2,
         "I8": 1, "U8": 1, "BOOL": 1, "F8_E4M3": 1, "F8_E5M2": 1}


def decodifica(dtype, bruto, quantos):
    """bytes -> lista de float, suficiente para estatistica."""
    if dtype == "F32":
        return list(struct.unpack("<%df" % quantos, bruto))
    if dtype == "F16":
        return list(struct.unpack("<%de" % quantos, bruto))
    if dtype == "BF16":
        # bf16 == os 16 bits superiores de um fp32
        v = struct.unpack("<%dH" % quantos, bruto)
        return list(struct.unpack("<%df" % quantos,
                                  struct.pack("<%dI" % quantos, *[x << 16 for x in v])))
    if dtype == "F64":
        return list(struct.unpack("<%dd" % quantos, bruto))
    if dtype == "I8":
        return list(struct.unpack("<%db" % quantos, bruto))
    if dtype == "U8" or dtype == "BOOL":
        return list(struct.unpack("<%dB" % quantos, bruto))
    if dtype == "I16":
        return list(struct.unpack("<%dh" % quantos, bruto))
    if dtype == "I32":
        return list(struct.unpack("<%di" % quantos, bruto))
    if dtype == "I64":
        return list(struct.unpack("<%dq" % quantos, bruto))
    if dtype in ("F8_E4M3", "F8_E5M2"):
        eb, mb = (4, 3) if dtype == "F8_E4M3" else (5, 2)
        vies, maxe = (1 << (eb - 1)), (1 << eb) - 1
        saida = []
        for b in bruto:
            s = -1.0 if b >> 7 else 1.0
            e = (b >> mb) & maxe
            m = b & ((1 << mb) - 1)
            if e == maxe:
                saida.append(float("nan") if m else s * float("inf"))
            elif e == 0:
                saida.append(s * (m / (1 << mb)) * 2.0 ** (1 - vies))
            else:
                saida.append(s * (1 + m / (1 << mb)) * 2.0 ** (e - vies))
        return saida
    raise ValueError("dtype nao suportado: %s" % dtype)


class Alvo(object):
    """Le um safetensors local ou remoto."""

    def __init__(self, alvo):
        self.alvo = alvo
        self.nome = alvo
        self.remoto = alvo.lower().startswith(("http://", "https://"))
        self.f = None
        if self.remoto:
            cab = self._range(0, 7)
            self.tam = self._tamanho()
        else:
            if not os.path.exists(alvo):
                raise IOError("nao existe: %s" % alvo)
            self.f = open(alvo, "rb")
            cab = self.f.read(8)
            self.tam = os.path.getsize(alvo)
        self.n, = struct.unpack("<Q", cab)
        hj = self._range(8, 8 + self.n - 1) if self.remoto else self.f.read(self.n)
        self.header = json.loads(hj.decode("utf-8"))
        self.base = 8 + self.n
        self.meta = self.header.get("__metadata__", {})
        self.chaves = [k for k in self.header if k != "__metadata__"]

    def _range(self, ini, fim):
        pedido = urllib.request.Request(self.alvo, headers={"Range": "bytes=%d-%d" % (ini, fim)})
        with urllib.request.urlopen(pedido, timeout=180) as r:
            return r.read()

    def _tamanho(self):
        pedido = urllib.request.Request(self.alvo, method="HEAD")
        with urllib.request.urlopen(pedido, timeout=180) as r:
            return int(r.headers.get("Content-Length", 0))

    def le(self, chave, linhas=None, desloc=0):
        """Le o tensor inteiro ou `linhas` linhas a partir da linha `desloc`."""
        d = self.header[chave]
        ini, fim = d["data_offsets"]
        it = ITENS.get(d["dtype"])
        if it is None:
            raise ValueError("dtype nao suportado: %s" % d["dtype"])
        forma = d.get("shape") or []
        if linhas and len(forma) > 1:
            col = 1
            for s in forma[1:]:
                col *= s
            quantos = max(0, min(linhas, forma[0] - desloc)) * col
            ini = ini + desloc * col * it
            fim = ini + quantos * it
        else:
            quantos = (fim - ini) // it
        if self.remoto:
            bruto = self._range(self.base + ini, self.base + fim - 1)
        else:
            self.f.seek(self.base + ini)
            bruto = self.f.read(fim - ini)
        return decodifica(d["dtype"], bruto, quantos), d, quantos


def estat(valores):
    n = len(valores)
    nan = sum(1 for v in valores if v != v)
    inf = sum(1 for v in valores if v == float("inf") or v == float("-inf"))
    fin = [v for v in valores if v == v and v not in (float("inf"), float("-inf"))]
    if not fin:
        return n, nan, inf, None, None, None, None, 0
    mn, mx = min(fin), max(fin)
    media = sum(fin) / len(fin)
    var = sum((v - media) ** 2 for v in fin) / len(fin)
    return n, nan, inf, mn, mx, media, var ** 0.5, len(fin)


def inspeciona(alvo, maxlin):
    print("=" * 78)
    print("ALVO:", alvo.nome)
    print("   bytes: %d  (%.2f GB)  %s" % (alvo.tam, alvo.tam / 1024.0 ** 3,
                                          "REMOTO (HTTP Range)" if alvo.remoto else "local"))
    print("   metadata: %s" % (alvo.meta if alvo.meta else "{}"))
    print("   tensores: %d" % len(alvo.chaves))
    if alvo.meta.get("minimax_h3_fun_controlnet"):
        print("   >>> forma adaln: %s" % alvo.meta["minimax_h3_fun_controlnet"].upper())

    grupos = {}
    for k in alvo.chaves:
        if PADRAO.search(k):
            grupos.setdefault(re.sub(r"\d+", "#", k), []).append(k)

    print("   --- chaves de interesse ---")
    if not grupos:
        print("      (nenhuma)")
    for g in sorted(grupos):
        d = alvo.header[grupos[g][0]]
        print("      %4dx %-46s %-13s %s" % (len(grupos[g]), g[:46],
                                             str(d.get("shape")), d["dtype"]))

    print("   --- valores (ate %d linhas por chave) ---" % maxlin)
    problemas = 0
    for g in sorted(grupos):
        chave = grupos[g][0]
        try:
            valores, d, quantos = alvo.le(chave, maxlin)
        except Exception as e:
            print("      %-46s ERRO: %s" % (g[:46], e))
            problemas += 1
            continue
        n, nan, inf, mn, mx, media, desvio, fin = estat(valores)
        if fin == 0:
            print("      %-46s *** TODOS NAO-FINITOS ***" % g[:46])
            problemas += 1
            continue
        marca = ""
        if nan:
            marca += "  NaN=%d" % nan
        if inf:
            marca += "  inf=%d" % inf
        if max(abs(mn), abs(mx)) > LIMITE:
            marca += "  *** |max|>%.0f ***" % LIMITE
        if marca:
            problemas += 1
        print("      %-46s n=%-8d min=%+.5f max=%+.5f mean=%+.5f std=%.6f%s"
              % (g[:46], n, mn, mx, media, desvio, marca))

    print("   >>> PROBLEMAS: %d" % problemas)
    return problemas


def lista_chaves(alvo):
    print("=" * 78)
    print("ALVO:", alvo.nome)
    print("   tensores: %d" % len(alvo.chaves))
    for k in sorted(alvo.chaves):
        d = alvo.header[k]
        print("   %-56s %-14s %s" % (k[:56], str(d.get("shape")), d["dtype"]))
    return 0


def separa(texto):
    """'ALVO::TENSOR@DESLOC' -> (alvo, tensor, desloc)."""
    if "::" not in texto:
        raise ValueError("formato esperado ALVO::TENSOR (opcional @linha_inicial): %s" % texto)
    alvo, resto = texto.split("::", 1)
    desloc = 0
    if "@" in resto:
        resto, pos = resto.rsplit("@", 1)
        desloc = int(pos)
    return alvo, resto, desloc


def compara(esq, dir_, maxlin):
    alvo_a, tens_a, off_a = separa(esq)
    alvo_b, tens_b, off_b = separa(dir_)
    a, b = Alvo(alvo_a), Alvo(alvo_b)
    print("=" * 78)
    print("ESQ: %s  @linha %d" % (tens_a, off_a))
    print("     %s" % alvo_a)
    print("DIR: %s  @linha %d" % (tens_b, off_b))
    print("     %s" % alvo_b)
    da_, db_ = a.header[tens_a], b.header[tens_b]
    print("   shapes: %s %s   vs   %s %s"
          % (da_.get("shape"), da_["dtype"], db_.get("shape"), db_["dtype"]))
    va, _, _ = a.le(tens_a, maxlin, off_a)
    vb, _, _ = b.le(tens_b, maxlin, off_b)
    n = min(len(va), len(vb))
    if n == 0:
        print("   ### nada para comparar (0 valores)")
        return 1
    iguais, maxdif, primeira, soma = 0, 0.0, None, 0.0
    for i in range(n):
        d = abs(va[i] - vb[i])
        soma += d
        if d == 0.0:
            iguais += 1
        else:
            if primeira is None:
                primeira = i
            if d > maxdif:
                maxdif = d
    print("   comparados : %d valores" % n)
    print("   identicos  : %d  (%.4f%%)" % (iguais, 100.0 * iguais / n))
    print("   max|diff|  : %.8f" % maxdif)
    print("   diff media : %.8f" % (soma / n))
    if primeira is not None:
        print("   1a divergencia no indice %d: %.8f vs %.8f"
              % (primeira, va[primeira], vb[primeira]))
    veredito = "IGUAIS" if iguais == n else ("QUASE (so quantizacao)" if maxdif < 0.01 else "DIFERENTES")
    print("   >>> VEREDITO: %s" % veredito)
    return 0 if veredito != "DIFERENTES" else 1


def acha_tensor(alvo, sufixo):
    """Acha uma chave pelo sufixo (ignora prefixos tipo model.diffusion_model.)."""
    exatos = [k for k in alvo.chaves if k == sufixo]
    if exatos:
        return exatos[0]
    casam = [k for k in alvo.chaves if k.endswith(sufixo)]
    if casam:
        return sorted(casam, key=len)[0]
    casam = [k for k in alvo.chaves if sufixo in k]
    return sorted(casam, key=len)[0] if casam else None


def perfil_colunas(alvo_s, maxlin):
    alvo_nome, sufixo, desloc = separa(alvo_s)
    a = Alvo(alvo_nome)
    if not sufixo:
        sufixo = "adaln_proj.linear.weight"
    chave = acha_tensor(a, sufixo)
    if chave is None:
        print("=" * 78)
        print("ALVO:", a.nome)
        print("   ### nenhuma chave contendo %r" % sufixo)
        return 1
    d = a.header[chave]
    forma = d.get("shape") or []
    print("=" * 78)
    print("ALVO:", a.nome)
    print("   metadata: %s" % (a.meta if a.meta else "{}"))
    print("   tensores: %d" % len(a.chaves))
    print("   chave: %s   %s   %s" % (chave, forma, d["dtype"]))
    if len(forma) < 2:
        print("   ### tensor 1-D, sem colunas")
        return 1
    linhas = min(forma[0], maxlin)
    col = forma[1]
    valores, _, _ = a.le(chave, linhas, desloc)
    nao_zero, primeira_zero = 0, None
    perfis = []
    for c in range(col):
        mx = 0.0
        base = c
        for r in range(linhas):
            v = valores[r * col + base]
            if v < 0.0:
                v = -v
            if v > mx:
                mx = v
        perfis.append(mx)
        if mx > 0.0:
            nao_zero += 1
        elif primeira_zero is None:
            primeira_zero = c
    print("   lidas %d de %d linhas" % (linhas, forma[0]))
    print("   colunas com algum valor != 0: %d de %d" % (nao_zero, col))
    if nao_zero == col:
        print("   max|v| global: %.8f" % max(perfis))
    else:
        print("   >>> %.1f%% DAS COLUNAS ESTAO ZERADAS (1a zerada: col %s)"
              % (100.0 * (col - nao_zero) / col, primeira_zero))
    if nao_zero < col and nao_zero <= 64:
        vivas = [c for c in range(col) if perfis[c] > 0.0]
        print("   colunas vivas: %s" % vivas)
        for c in vivas:
            print("      col %5d : %.8f" % (c, perfis[c]))
    else:
        print("   amostra de max|v| por coluna:")
        for c in list(range(min(12, col))) + list(range(max(0, col - 4), col)):
            print("      col %5d : %.8f" % (c, perfis[c]))
    return 0


def principal(argv):
    maxlin = MAXLIN
    so_chaves = False
    modo = "inspeciona"
    while argv and argv[0].startswith("--"):
        op = argv[0]
        argv = argv[1:]
        if op == "--linhas":
            maxlin = int(argv[0])
            argv = argv[1:]
        elif op == "--chaves":
            so_chaves = True
        elif op == "--compara":
            modo = "compara"
        elif op == "--colunas":
            modo = "colunas"
    if not argv:
        print(__doc__)
        return 1
    if modo == "compara":
        if len(argv) < 2:
            print('uso: --compara "ARQ_A::tensor_a[@linha]" "ARQ_B::tensor_b[@linha]"')
            return 1
        return compara(argv[0], argv[1], maxlin)
    if modo == "colunas":
        alvo_s = argv[0] if "::" in argv[0] else argv[0] + "::"
        return perfil_colunas(alvo_s, maxlin)
    total = 0
    for a in argv:
        try:
            alvo = Alvo(a)
            total += lista_chaves(alvo) if so_chaves else inspeciona(alvo, maxlin)
        except Exception as e:
            print("=" * 78)
            print("ALVO:", a)
            print("   ### FALHOU: %s: %s" % (type(e).__name__, e))
            total += 1
    print()
    print("########## TOTAL DE PROBLEMAS: %d ##########" % total)
    return 0


if __name__ == "__main__":
    sys.exit(principal(sys.argv[1:]))
