File size: 26,898 Bytes
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226b7bf
fb6b9a8
 
 
 
 
 
 
 
6e42356
fb6b9a8
 
 
 
226b7bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e42356
 
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f66d08
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226b7bf
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f66d08
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f66d08
 
 
fb6b9a8
9f66d08
 
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f66d08
 
 
 
 
 
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f66d08
 
 
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e42356
9f66d08
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f66d08
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226b7bf
fb6b9a8
 
 
 
 
 
 
 
 
 
 
226b7bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
"""Decide, for each candidate, which official model of a family it belongs to and how.

lineage   a member lineage of the family (e.g. H3 | H3-Image | H3-Image-PE), or
          unrelated | unknown
relation  official | adapter | finetune | merge | quantized | repackage | mirror |
          component | tool | no-weights | app (Space) | dataset
family    True when the repo is about the family at all (even if the member is unknown)

Evidence is tiered. Tier 1 is structural and decides on its own; tier 2 (declared base,
repo content, dates) decides only when tier 1 is silent; names alone (tier 3) give at
most low confidence. Every decision keeps its reasons in `evidence`. All family-specific
facts come from the Family object (hfeco/families/*.py).
"""
import json
import re

import numpy as np

VERSION = "2026-11-17.9"
DERIVED = {"adapter", "finetune", "merge", "quantized", "repackage", "mirror", "component"}
HF_RELATIONS = {"adapter", "finetune", "merge", "quantized"}
SAME = 1e-3        # probe distance below this = same weights (bf16 -> fp16 copies land at ~0)

LORA_KEY = re.compile(r"lora_[ABab]\b|lora_down|lora_up|lora\.(down|up)|\.lokr_|\.hada_|\.alpha$|\.diff(_b)?$",
                      re.I)
QUANT_NAME = re.compile(r"fp8|int8|int4|int6|nf4|nvfp4|mxfp|fp4|w4a\d|w6a8|w8a8|gptq|awq|svdq|nunchaku|"
                        r"q[2-8]_[0k]|q[2-8]_k|iq[1-4]|bnb|sdnq|convrot|[2-8]-?bit\b|gguf|exl2|hqq|quant", re.I)
MERGE_NAME = re.compile(r"merge|merged|mix\b|fused|\bfuse\b|blend|hybrid|graft", re.I)   # not "mixed": mixed precision
REPACK_NAME = re.compile(r"comfy|diffusers|single[-_ ]?file|repack|split|bf16|fp16|fp32|pruned|mlx", re.I)
TUNED_NAME = re.compile(r"finetun|fine-tun|\bft\b|turbo|lightning|distill|\d+[-_ ]?steps?|\bacc\b|fast|"
                        r"lcm|dmd|pdmd|singularity|eros|nsfw|uncensor|heretic|abliterat", re.I)
DISTILL_NAME = re.compile(r"turbo|lightning|distill|\d+[-_ ]?steps?|\bacc\b|lcm|dmd|pdmd|fast", re.I)
# Adult content is counted like anything else but never named on the (public) dashboard, so
# these lean towards hiding. Names: explicit words, also inside compounds ("epiccum", "Tit_Fuck").
NSFW = re.compile(r"nsfw|porn|hentai|nude|nudity|naked|sex|dildo|cum(?![a-z])|cumshot|blowj|blow[-_ ]?job|"
                  r"deep[-_ ]?throat|pussy|vagina|penis|dick(?![a-z])|cock(?![a-z])|tits?(?![a-z])|titty|"
                  r"titties|tiddies|boob|breast|nipple|anal(?![a-z])|orgasm|squirt|creampie|bukkake|milf|"
                  r"futa|bdsm|bondage|fetish|lewd|ecchi|ahegao|fuck|erotic|xxx|uncensor|strip(?:tease|per)|"
                  r"onlyfans|topless|undress|lingerie|bikini|r18|moan|pleasure|writh|cowgirl|doggy|missionary|"
                  r"panties|underwear|masturbat|handjob|footjob|grop(?:e|ing)|jiggl|booty|twerk|thicc|seduc|"
                  r"sensual|horny|slut|whore|bimbo|busty|cleavage|upskirt|voyeur|"
                  r"(?:(?<=\d)|(?<=ten))eros|(?:\b|(?<=_))eros(?![a-z])", re.I)   # "10ErosMax", "TenEros"
# Cards only count when they describe the model itself as adult: derivatives copy the official
# license ("unlawful, pornographic, or ...") and many cards say "does not contain NSFW content".
NSFW_CARD = re.compile(r"\bnsfw[- ](?:lora|model|version|finetune|fine-tune|merge|capable|focused|checkpoint)s?\b|"
                       r"trained on .{0,30}\bporn|\bhentai\b|\bnudity\b|explicit sexual|not-for-all-audiences",
                       re.I)
# Training/merge tools describe merges in prose; quantizers have a bare "merge" field for a compute step.
META_MERGE = re.compile(r"lora[ _-]?merg|merged|graft|merge[ _](of|from|method|ratio|weights)|linear merge|"
                        r"consensus merge|baked", re.I)
LORA_NAME = re.compile(r"lora|lycoris|locon|loha|lokr|adapter", re.I)
AUTHORS = {}      # family key -> authors who publish family repos (filled by classify_all)
COMMUNITY = {}    # family key -> weight-file index over all probed repos (for whole-repo copies)
TEXT_LLM_TYPES = re.compile(r"^(qwen|llama|mistral|gemma|phi|glm|deepseek|minimax_m)", re.I)


def declared_graph(raw):
    """child -> list of (relation, parent) as parsed by HF from each card."""
    return {r.repo_id: [tuple(p.split(":", 1)) for p in r.hf_parents] for r in raw.itertuples()}


def declared_member(rid, g, fam, seen=None):
    """Nearest family base reached by following declared parents."""
    lob = fam.lineage_of_base()
    if rid in lob:
        return lob[rid]
    seen = seen or set()
    if rid in seen:
        return None
    seen.add(rid)
    best = None
    for _, p in g.get(rid, []):
        if p in lob:
            return lob[p]
        best = best or declared_member(p, g, fam, seen)
    return best


def probe_match(probe, fam):
    """Compare a probed tensor slice with the official ones -> (lineage, rel_distance, source)."""
    if not probe or not probe.get("values"):
        return None
    v = np.array(probe["values"], dtype=np.float64)
    best = None
    for ref in fam.ref["probes"]:
        r = np.array(ref["values"][:len(v)], dtype=np.float64)
        if len(r) != len(v):
            continue
        d = float(np.linalg.norm(v - r) / (np.linalg.norm(r) + 1e-12))
        if best is None or d < best[1]:
            best = (ref["lineage"], d, ref["source"])
    return best


def sha_mirror(files, fam):
    wb = [f for f in files or [] if f.get("sha256") and f.get("size", 0) > 1_000_000
          and f["name"].lower().endswith(WEIGHT_EXT)]          # tokenizers etc. are shared widely
    if not wb:
        return None
    total = sum(f["size"] for f in wb)
    hit, any_b = {}, 0
    for f in wb:
        ref = fam.ref["sha256"].get(f["sha256"])
        if ref:
            any_b += f["size"]
            for lin in ref.get("lineages") or [ref.get("lineage")]:
                hit[lin] = hit.get(lin, 0) + f["size"]
    if not hit:
        return None
    lin = max(hit.items(), key=lambda x: x[1])[0]
    return lin, any_b / total


def _res(lineage, relation, family, confidence, evidence, flags):
    return dict(lineage=lineage, relation=relation, family=family, confidence=confidence,
                evidence=evidence, flags=flags, copy_of=None)


def classify_model(r, ev, g, cutoff, fam):
    rid = r["repo_id"]
    E, tier1 = [], {}
    score = {k: 0.0 for k in fam.lineages}
    name = rid.split("/")[1]
    readme = (ev or {}).get("readme") or ""
    text = " ".join([name, " ".join(r["tags"]), readme])
    flags = ["nsfw"] if ("not-for-all-audiences" in r["tags"] or NSFW.search(rid) or NSFW_CARD.search(readme)) else []
    lob = fam.lineage_of_base()

    if rid in lob:
        return _res(lob[rid], "official", True, "high", ["官方仓库"], flags)
    if rid.startswith("MiniMaxAI/"):
        return _res("unrelated", None, False, "high", ["MiniMax 其他模型的官方仓库"], flags)
    decl = declared_member(rid, g, fam)
    if ev is None:
        return _res("unrelated", None, False, "medium",
                    ["名字里的关键词是别的词的一部分,且没有任何相关信号"], flags)
    if any(e.startswith("fatal") for e in ev.get("errors", [])):
        return _res(decl or "unknown", None, bool(decl), "low",
                    ["仓库读不到(可能已删除或设了访问限制)"] + ([f"声明底模属于 {decl}"] if decl else []), flags)

    weight_ev = []                           # tier-1 hits that come from the weights themselves

    def t1(lin, why, from_weights=False):
        tier1[lin] = tier1.get(lin, 0) + 1
        E.append(why)
        if from_weights:
            weight_ev.append(lin)

    files = ev.get("files", [])
    keys = ev.get("st_keys") or (ev.get("gguf") or {}).get("tensor_names") or {}
    markers = " ".join(keys.get("markers", []))
    sig = ev.get("dit_sig") or {}
    hits = sig.get("sig_hits", sig.get("h3_dim_hits", 0))
    is_dit = hits >= 8
    other_dit = sig.get("block_tensors", 0) >= 20 and hits == 0
    is_lora = bool(LORA_KEY.search(markers)) or bool(ev.get("has_adapter_config"))
    meta = json.dumps(ev.get("st_meta") or {}).lower()
    cfg = ev.get("config") or {}
    cfg_s = f'{cfg.get("model_type") or ""} {" ".join(cfg.get("architectures") or [])}'
    gguf_arch = str(((ev.get("gguf") or {}).get("kv") or {}).get("general.architecture") or "")
    patterns = " ".join(keys.get("patterns", []))
    is_text_llm = (bool(TEXT_LLM_TYPES.search(str(cfg.get("model_type") or ""))) or "ForCausalLM" in cfg_s
                   or bool(TEXT_LLM_TYPES.search(gguf_arch))
                   or (not is_dit and bool(re.search(r"layers\.N\.(self_attn|mlp|linear_attn)", patterns))))
    readable = bool(keys.get("n")) or bool(ev.get("gguf"))
    mi = json.dumps(ev.get("model_index") or {})
    ctx = {"markers": markers, "sig": sig, "is_dit": is_dit, "is_lora": is_lora}

    # ---- Tier 1: structural evidence --------------------------------------------------
    mirror = sha_mirror(files, fam)
    if mirror and mirror[1] >= 0.5:
        t1(mirror[0], f"{mirror[1]:.0%} 的权重文件与官方 {mirror[0]} 逐字节相同", True)
    for rx, lin, why, full_only in fam.marker_rules:
        if rx.search(markers) and not (full_only and is_lora):
            t1(lin, why, not is_lora)
    if fam.extra_structural:
        for lin, why in fam.extra_structural(ev, ctx):
            t1(lin, why, True)
    pm = probe_match(ev.get("probe"), fam)
    if pm:
        lin, d, src = pm
        if d < SAME:
            t1(lin, f"抽查的权重数值与官方 {src} 完全相同", True)
        elif d < 0.6:
            t1(lin, f"抽查的权重数值最接近官方 {lin}(相对差异 {d:.1%}),是在它上面改过的", True)
    for sub, lin in fam.index_rules:
        if sub in mi:
            t1(lin, f"model_index.json 是 {lin} 的管线")
            break
    for rx, lin in fam.config_rules:
        if rx.search(cfg_s):
            t1(lin, f"config 的模型结构是 {lin}")
            break
    created = str(r.get("created_at") or "")
    if meta not in ("{}", ""):
        for rx, lin, why in fam.meta_rules:
            m = rx.search(meta)
            # Metadata strings can echo a repo name; a member released after the repo was
            # created cannot be its training base, so skip such a match.
            if m and not (created and cutoff.get(lin) and created < cutoff[lin]):
                t1(lin, f"{why}({m.group(0)})")
                break
    # A text model belongs to the text member only on weight evidence, a declaration, or the
    # member's own name; "does prompt expansion" alone describes a tool, not a derivative.
    name_tags = name + " " + " ".join(r["tags"])
    pe_like = bool(fam.text_member and is_text_llm and (
        (fam.text_member_name and fam.text_member_name.search(name_tags))
        or (mirror and mirror[0] == fam.text_member and mirror[1] >= 0.5) or decl == fam.text_member)
        and not (created and cutoff.get(fam.text_member) and created < cutoff[fam.text_member]))
    if pe_like:
        t1(fam.text_member, f"是文本大模型,且标明是 {fam.text_member}")

    # ---- Tier 2: declared base, repo content, dates ------------------------------------
    if decl:
        score[decl] += 5
        E.append(f"声明的 base_model 指向 {decl}")
    video_member = next((m.lineage for m in fam.members if m.modality == "video"), None)
    if video_member and ev.get("has_video_media") and not is_text_llm:
        score[video_member] += 3
        E.append("仓库里有视频样例")
    member_hit = False
    for rx, lin, w, why, skip_text in fam.card_rules:
        if rx.search(readme) and not (skip_text and is_text_llm):
            score[lin] += w
            E.append(why)
            member_hit = member_hit or lin != fam.default_member
    if fam.family_text and fam.family_text.search(readme) and not member_hit:
        score[fam.default_member] += 2
    pt = r.get("pipeline_tag") or ""
    for m in fam.members:
        if m.modality in ("video", "audio") and m.modality in pt:
            score[m.lineage] += 2
    if is_dit:
        for m in fam.members:
            if m.modality != "text":
                score[m.lineage] += 2
    for lin, day in cutoff.items():
        if created and day and created < day:
            score[lin] -= 20
            if lin != fam.text_member:
                E.append(f"创建于 {created[:10]},早于 {lin} 发布,不可能基于 {lin}")

    # ---- Tier 3: names -----------------------------------------------------------------
    for m in fam.members:
        if m.text_hint and m.text_hint.search(name):
            score[m.lineage] += 1.5
    if fam.family_text and fam.family_text.search(name):
        score[fam.default_member] += 1

    # ---- Family gate -------------------------------------------------------------------
    fam_text = bool(fam.family_text and fam.family_text.search(text)) or any(
        m.text_hint and m.text_hint.search(text) for m in fam.members if m.modality != "text")
    name_fam = bool(fam.family_text and fam.family_text.search(name)) or any(
        m.text_hint and m.text_hint.search(name) for m in fam.members)
    if other_dit and is_lora and not tier1 and not decl:
        return _res("unrelated", None, False, "high", ["是别的 DiT 模型的 LoRA(层的尺寸不对)"], flags)
    component_for_family = bool(fam_text and fam.component_names and fam.component_names.search(name))
    if other_dit and not tier1 and not decl and not name_fam and not component_for_family:
        return _res("unrelated", None, False, "high", ["是别的模型的权重(层的尺寸不对),名字也没提到这个家族"], flags)
    author_hint = bool(fam.name_hint and fam.name_hint.search(name) and r["author"] in AUTHORS.get(fam.key, ()))
    if not (decl or tier1 or is_dit or fam_text or author_hint):
        return _res("unrelated", None, False, "medium", ["没有任何相关信号"], flags)
    if author_hint and not (decl or tier1 or is_dit or fam_text):
        E.append("作者发布过这个家族的衍生模型,名字里也有家族关键词")
        score[fam.default_member] += 1

    # ---- Decide lineage ----------------------------------------------------------------
    possible = [m.lineage for m in fam.members if m.modality != "text" and score[m.lineage] > -10]
    if tier1:
        if len(tier1) == 1:
            lineage, conf = next(iter(tier1)), "high"
        else:
            # Collections hold files of several members; let the repo's own framing choose.
            ranked = sorted(tier1, key=lambda k: -score[k])
            if score[ranked[0]] - score[ranked[1]] >= 2:
                lineage, conf = ranked[0], "medium"
                E.append("仓库里同时有 " + "、".join(tier1) + " 的权重,按仓库名和声明归到 " + ranked[0])
            else:
                lineage, conf = "unknown", "low"
                E.append("结构证据互相矛盾:" + " / ".join(tier1))
    elif is_dit and len(possible) == 1:
        lineage, conf = possible[0], "medium"
        E.append(f"结构是这个家族的 DiT,且创建时只有 {possible[0]} 已发布")
    else:
        ranked = sorted(score.items(), key=lambda x: -x[1])
        (l1, s1), (_, s2) = ranked[0], ranked[1]
        if s1 >= 4 and s1 - s2 >= 3:
            lineage, conf = l1, "medium"
        elif s1 > 0 and s1 - s2 >= 1:
            lineage, conf = l1, "low"
        else:
            lineage, conf = "unknown", "low"
            E.append("看得出属于这个家族,但分不清是哪个模型")

    pe_like = pe_like or (lineage == fam.text_member and is_text_llm)
    copy_of = community_mirror(r, ev, fam)
    if copy_of:
        flags.append("copy")
        E.append(f"整仓权重与更早的 {copy_of} 逐字节相同,是重新上传")
    rel = relation(r, ev, is_lora, is_dit or bool(weight_ev), is_text_llm, mirror, pm, name, E, pe_like, fam,
                   readable, other_dit, lineage)
    if rel == "tool" and not (decl or name_fam or component_for_family):
        # Weights from another model and only the card mentions the family: an ad, a comparison,
        # or training data made with it. Not part of the ecosystem count.
        return _res("unrelated", None, False, "medium", ["权重来自别的模型,只在模型卡里提到这个家族"], flags)
    if rel == "tool":
        E.append("权重不是来自这个家族,是给它用的周边工具")
    if DISTILL_NAME.search(name) and rel in ("finetune", "adapter", "merge", "quantized"):
        flags.append("distilled")
    out = _res(lineage, rel, True, conf, E, flags)
    out["copy_of"] = copy_of
    return out


def relation(r, ev, is_lora, is_family_weights, is_text_llm, mirror, pm, name, E, pe_like, fam,
             readable, other_dit, lineage):
    wbytes = ev.get("weight_bytes", 0)
    card = ev.get("card") or {}
    main = ev.get("main_weight") or ""
    if ev.get("n_weight_files", 0) == 0 or wbytes < 1_000_000:
        return "no-weights"
    if mirror and mirror[1] >= 0.9:
        return "mirror"
    if is_text_llm and not pe_like:
        if fam.text_component and fam.text_component.search(name + " " + json.dumps(ev.get("config"))):
            E.append("是这个家族自带的文本编码器")
            return "component"
        return "tool"
    if not is_family_weights and not pe_like:
        if fam.component_names and (fam.component_names.search(name) or fam.component_names.search(main)):
            return "component"
        # "tool" needs positive evidence that the weights come from another model;
        # unreadable weights (gated, .bin, unparsed) fall through to the name rules below.
        if (other_dit or (readable and not is_lora)) and not is_lora:
            return "tool"
    if is_lora or (not readable and LORA_NAME.search(name + " " + main)):
        return "adapter"
    bm = card.get("base_model")
    multi = [b for b in bm if isinstance(b, str)] if isinstance(bm, list) else []
    same = pm and pm[1] < SAME
    meta_merge = bool(META_MERGE.search(json.dumps(ev.get("st_meta") or {})))
    if (card.get("base_model_relation") == "merge" or len(multi) >= 2 or meta_merge or MERGE_NAME.search(name)
            or any(p.startswith("merge:") for p in r["hf_parents"])) and not (same and not MERGE_NAME.search(name)):
        return "merge"
    if same:
        return "repackage"
    st_d = ev.get("st_dtypes") or {}
    low = sum(v for k, v in st_d.items() if k in ("F8_E4M3", "F8_E5M2", "I8", "U8", "I4", "U4"))
    quant = (ev.get("has_gguf") or (st_d and low / max(1, sum(st_d.values())) >= 0.25)
             or QUANT_NAME.search(name) or QUANT_NAME.search(main)
             or "quantization_config" in json.dumps(ev.get("config") or {}))
    if quant:
        native = fam.native_quant.get(lineage) if fam.native_quant else None
        if native and not ev.get("has_gguf") and native.search(name + " " + main) \
                and not re.search(r"gguf|mlx|[2-8]-?bit|int[48]|awq|gptq", name, re.I):
            E.append(f"官方 {lineage} 本身就是这种量化格式,这里只是换了打包方式")
            return "repackage"
        return "quantized"
    if MERGE_NAME.search(name):
        return "merge"
    if pm:
        return "finetune"
    if REPACK_NAME.search(name) and not TUNED_NAME.search(name):
        return "repackage"
    return "finetune"


WEIGHT_EXT = (".safetensors", ".gguf", ".bin", ".pt", ".pth", ".ckpt", ".onnx", ".npz", ".sft", ".tflite",
              ".mlmodel", ".engine", ".pte")


def _weights(ev):
    return {f["sha256"]: f["size"] for f in (ev or {}).get("files", [])
            if f.get("sha256") and f.get("size", 0) > 1_000_000 and f["name"].lower().endswith(WEIGHT_EXT)}


def community_mirror(r, ev, fam):
    """Whole-repo copy of an earlier community repo: each covers >= 90% of the other's
    weight bytes. Being collected into a bigger repo, or copying part of one, does not count."""
    c = COMMUNITY.get(fam.key)
    if not c:
        return None
    mine = _weights(ev)
    total = sum(mine.values())
    if not total:
        return None
    me = str(r.get("created_at") or "")
    shared = {}
    for sha, size in mine.items():
        for other in c["by_sha"].get(sha, ()):
            if other != r["repo_id"]:
                shared[other] = shared.get(other, 0) + size
    for other, b in sorted(shared.items(), key=lambda x: -x[1]):
        if b / total < 0.9:
            break
        o_total = c["total"][other]
        if o_total and b / o_total >= 0.9 and c["created"].get(other, "9999") < me:
            return other
    return None


def classify_space(r, model_labels, fam):
    lins, E = set(), []
    for m in r["space_models"]:
        lab = model_labels.get(m)
        if lab and lab["family"] and lab["lineage"] in fam.lineages:
            lins.add(lab["lineage"])
    if lins:
        E.append("调用的模型:" + "、".join(sorted(lins)))
    text = r["repo_id"] + " " + " ".join(r["tags"])
    if not lins:
        lins = _text_members(text, r, fam)
        if lins:
            E.append("名字或说明里提到这个家族")
    if not lins:
        return _res("unrelated", "app", False, "medium", ["没有调用这个家族的模型,名字里的关键词另有所指"], [])
    lineage = fam.default_member if fam.default_member in lins else sorted(lins)[0]
    return _res(lineage, "app", True, "high" if r["space_models"] else "low", E, [])


def classify_dataset(r, fam):
    lins = _text_members(r["repo_id"] + " " + " ".join(r["tags"]), r, fam)
    if not lins:
        return _res("unrelated", "dataset", False, "medium", ["名字里的关键词另有所指"], [])
    lin = sorted(lins)[0]
    return _res(lin, "dataset", True, "low", ["名字或数据卡提到 " + lin], [])


def _text_members(text, r, fam):
    for m in fam.members:
        if m.text_hint and m.modality != "text" and m.text_hint.search(text):
            return {m.lineage}
    if (fam.family_text and fam.family_text.search(text)) or any(s.startswith("fulltext") for s in r["sources"]):
        return {fam.default_member}
    # The author publishes family models and the name carries the family keyword as a token.
    if fam.name_hint and fam.name_hint.search(r["repo_id"].split("/")[1]) and r["author"] in AUTHORS.get(fam.key, ()):
        return {fam.default_member}
    return set()


def classify_all(raw_today, cache, fam):
    """raw_today: one day's raw frame for this family. Returns a list of label dicts."""
    g = declared_graph(raw_today)
    created = dict(zip(raw_today.repo_id, raw_today.created_at))
    AUTHORS[fam.key] = {r.author for r in raw_today.itertuples() if r.kind == "model" and not
                        r.repo_id.startswith("MiniMaxAI/") and (declared_member(r.repo_id, g, fam)
                                                                 or fam.family_text.search(r.repo_id))}
    by_sha, total = {}, {}
    for rid, ev in cache.items():
        w = _weights(ev)
        total[rid] = sum(w.values())
        for sha in w:
            by_sha.setdefault(sha, []).append(rid)
    COMMUNITY[fam.key] = {"by_sha": by_sha, "total": total,
                          "created": {k: str(v or "9999") for k, v in created.items()}}
    # A derivative cannot predate its base repo; the default member never needs the check.
    cutoff = {m.lineage: str(created.get(m.base) or "") for m in fam.members if m.lineage != fam.default_member}
    out, mlabels = [], {}
    rows = raw_today.to_dict("records")
    for r in rows:
        if r["kind"] != "model":
            continue
        lab = classify_model(r, cache.get(r["repo_id"]), g, cutoff, fam)
        lab.update(declared_status(r, lab, g, fam))
        mlabels[r["repo_id"]] = lab
        out.append({"kind": "model", "repo_id": r["repo_id"], **lab})
    _nsfw_spread(mlabels, g, fam)
    for r in rows:
        if r["kind"] == "space":
            out.append({"kind": "space", "repo_id": r["repo_id"], **classify_space(r, mlabels, fam)})
        elif r["kind"] == "dataset":
            out.append({"kind": "dataset", "repo_id": r["repo_id"], **classify_dataset(r, fam)})
    for o in out:
        o["classifier_version"] = VERSION
        o["family_key"] = fam.key
    return out


def _nsfw_spread(mlabels, g, fam):
    """Adult flags beyond a repo's own name/tags/card. These only decide what the public page
    names; every repo is still counted.

    - Whole-repo copies and declared children of an adult repo (a GGUF of an adult finetune
      rarely says so in its name).
    - Every repo of an author with several adult repos ("nsfw_author"), except publishers in
      fam.nsfw_author_exempt whose adult repos are a small part of their work.
    """
    hidden = lambda rid: bool({"nsfw", "nsfw_author"} & set(mlabels.get(rid, {}).get("flags", [])))

    def spread():
        for _ in range(4):
            for rid, lab in mlabels.items():
                if hidden(rid):
                    continue
                ups = ([lab["copy_of"]] if lab.get("copy_of") else []) + [p for _, p in g.get(rid, [])]
                if any(hidden(u) for u in ups):
                    lab["flags"].append("nsfw")

    spread()
    by_author = {}
    for rid, lab in mlabels.items():
        if lab["family"]:
            by_author.setdefault(rid.split("/")[0], []).append(lab)
    for author, labs in by_author.items():
        n = sum("nsfw" in x["flags"] for x in labs)
        if author in fam.nsfw_author_exempt:
            continue
        if n >= 3 or (n >= 2 and n / len(labs) >= 0.25) or (n and n / len(labs) >= 0.5):
            for x in labs:
                if "nsfw" not in x["flags"]:
                    x["flags"].append("nsfw_author")
    spread()


def declared_status(r, lab, g, fam):
    decl = declared_member(r["repo_id"], g, fam)
    hf_rel = r["hf_parents"][0].split(":")[0] if r["hf_parents"] else None
    out = {"declared_lineage": decl, "declared_relation": hf_rel, "declared_status": None,
           "proposed_base_model": None, "proposed_relation": None}
    if not lab["family"] or lab["relation"] not in DERIVED or lab["lineage"] not in fam.lineages:
        return out
    base = fam.base_of(lab["lineage"])
    if decl is None:
        out["declared_status"] = "missing"
    elif decl != lab["lineage"]:
        out["declared_status"] = "wrong_base"
    elif lab["relation"] in HF_RELATIONS and hf_rel and hf_rel != lab["relation"] \
            and any(p.split(":", 1)[1] == base for p in r["hf_parents"]):
        out["declared_status"] = "wrong_relation"
    else:
        out["declared_status"] = "ok"
    if out["declared_status"] != "ok":
        out["proposed_base_model"] = base
        # HF only knows four relations; for the rest we set base_model and let HF infer.
        out["proposed_relation"] = lab["relation"] if lab["relation"] in HF_RELATIONS else None
    return out