File size: 5,911 Bytes
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
"""Find every repo that might be downstream of a model family, on purpose too wide.

Classification decides later what really belongs to the family; this step only makes
sure nothing is missed, because a day without a download snapshot cannot be recovered.
"""
import datetime as dt
from concurrent.futures import ThreadPoolExecutor

from . import hub


def _iso(x):
    return x.isoformat() if isinstance(x, (dt.date, dt.datetime)) else x


def _card(o):
    cd = getattr(o, "card_data", None) or getattr(o, "cardData", None)
    return cd.to_dict() if hasattr(cd, "to_dict") else (cd or {})


def _as_list(x):
    if x is None:
        return []
    return [x] if isinstance(x, str) else [str(i) for i in x]


def record(kind, o, now):
    tags = list(o.tags or [])
    card = _card(o)
    parents = []                            # direct parents as HF parsed them: (relation, parent)
    for t in tags:
        if t.startswith("base_model:"):
            p = t.split(":")
            if len(p) == 3:
                parents.append(f"{p[1]}:{p[2]}")
    return {
        "kind": kind,
        "repo_id": o.id,
        "author": o.id.split("/")[0],
        "fetched_at": now,
        "downloads_30d": getattr(o, "downloads", None),
        "downloads_all_time": getattr(o, "downloads_all_time", None),
        "likes": getattr(o, "likes", None),
        "created_at": _iso(getattr(o, "created_at", None)),
        "last_modified": _iso(getattr(o, "last_modified", None)),
        "sha": getattr(o, "sha", None),
        "pipeline_tag": getattr(o, "pipeline_tag", None),
        "library_name": getattr(o, "library_name", None),
        "tags": tags,
        "gated": str(getattr(o, "gated", None)),
        "card_base_model": _as_list(card.get("base_model")),
        "card_base_model_relation": card.get("base_model_relation"),
        "license": card.get("license_name") or card.get("license"),
        "hf_parents": parents,
        "space_sdk": getattr(o, "sdk", None),
        "space_models": list(getattr(o, "models", None) or []),
        "space_stage": (getattr(o, "runtime", None).stage if getattr(o, "runtime", None) else None),
    }


def discover(fam, log=print, recurse_workers=8):
    BASES = fam.bases
    now = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
    found = {}                               # (kind, id) -> record
    sources = {}                             # (kind, id) -> set of discovery channels

    def add(kind, objs, src):
        for o in objs:
            k = (kind, o.id)
            if k not in found:
                found[k] = record(kind, o, now)
            sources.setdefault(k, set()).add(src)

    # 1. Declared model trees, followed downwards until nothing new appears.
    frontier = list(BASES)
    seen_parent = set()
    depth = 0
    while frontier:
        depth += 1
        todo = [p for p in frontier if p not in seen_parent]
        seen_parent.update(todo)
        with ThreadPoolExecutor(recurse_workers) as ex:
            res = list(ex.map(lambda p: (p, hub.listing("model", filter=f"base_model:{p}")), todo))
        frontier = []
        for p, kids in res:
            add("model", kids, f"tree:{p}" if p in BASES else "tree:descendant")
            frontier += [k.id for k in kids]
        log(f"tree depth {depth}: {len(todo)} parents, {sum(len(k) for _, k in res)} children")

    # 2. Name, tag and README full-text search.
    for q in fam.name_queries:     # Hub name search is a substring match on the repo id
        add("model", hub.listing("model", search=q), f"name:{q}")
        add("dataset", hub.listing("dataset", search=q), f"name:{q}")
        add("space", hub.listing("space", search=q), f"name:{q}")
    for t in fam.tag_filters:
        add("model", hub.listing("model", filter=t), f"tag:{t}")
    log(f"after name/tag search: {len(found)}")

    missing = []
    for q in fam.fulltext_queries:
        for kind in ("model", "dataset", "space"):
            for rid in hub.full_text(q, kind):
                k = (kind, rid)
                sources.setdefault(k, set()).add(f"fulltext:{q}")
                if k not in found:
                    missing.append(k)
    # 3. Spaces that load a family model.
    for b in BASES:
        add("space", hub.listing("space", models=b), f"space-uses:{b}")
    log(f"after full-text + spaces: {len(found)} listed, {len(set(missing))} need a per-repo fetch")

    # 4. Children of any candidate that names the family explicitly (catches repos that only
    #    declare a community repo, e.g. Comfy-Org/MiniMax-H3, as their base).
    extra_parents = [rid for (kind, rid) in found if kind == "model" and rid not in seen_parent
                     and _looks_family(rid, found[(kind, rid)], fam)]
    with ThreadPoolExecutor(recurse_workers) as ex:
        res = list(ex.map(lambda p: (p, hub.listing("model", filter=f"base_model:{p}")), extra_parents))
    for p, kids in res:
        add("model", kids, "tree:descendant")
    log(f"children of {len(extra_parents)} name hits: {sum(len(k) for _, k in res)}")

    # Per-repo fetch for full-text-only hits.
    def fetch(k):
        try:
            return k, hub.info(k[0], k[1])
        except Exception:
            return k, None
    with ThreadPoolExecutor(recurse_workers) as ex:
        for k, o in ex.map(fetch, sorted(set(m for m in missing if m not in found))):
            if o is not None:
                found[k] = record(k[0], o, now)

    rows = []
    for k, r in found.items():
        r["sources"] = sorted(sources.get(k, []))
        rows.append(r)
    log(f"total candidates: {len(rows)}")
    return rows


def _looks_family(rid, rec, fam):
    tags = rec.get("tags") or []
    return bool(fam.family_text.search(rid)
                or any(m.text_hint and m.text_hint.search(rid) for m in fam.members)
                or any(t in tags or rec.get("library_name") == t for t in fam.tag_filters))