File size: 14,802 Bytes
f44aac9
 
 
 
9219266
 
f44aac9
 
 
 
 
 
 
490a71e
 
 
 
 
 
 
 
 
 
f44aac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490a71e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f44aac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
902a11f
f44aac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490a71e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f44aac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9219266
 
 
f44aac9
9219266
 
 
 
 
 
 
f44aac9
 
 
 
 
9219266
 
 
 
 
 
 
 
 
 
 
 
f44aac9
 
 
 
 
 
 
 
 
 
 
9219266
 
 
 
 
 
 
 
 
 
 
 
f44aac9
 
 
 
 
 
 
 
 
 
 
 
 
 
902a11f
 
 
 
f44aac9
 
 
 
 
 
 
9219266
f44aac9
 
 
 
 
 
902a11f
 
 
 
 
 
 
 
f44aac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9219266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490a71e
9219266
 
 
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
from __future__ import annotations

from collections import Counter
from dataclasses import dataclass
from datetime import datetime, timezone
from hashlib import sha256
import json
import math
from pathlib import Path
import re


TOKEN_RE = re.compile(r"[a-z0-9][a-z0-9.+_-]*", re.IGNORECASE)
GENERIC_PUBLIC_TITLE_RE = re.compile(
    r"^(?:my\s+)?build\s+small\s+hackathon$",
    re.IGNORECASE,
)
GENERIC_PUBLIC_SUMMARY_RE = re.compile(
    r"(?:\bthis\s+(?:is\s+)?(?:space\s+is\s+for|my\s+submission)\b.*\b(?:build[-\s]*small|hackathon)\b)"
    r"|(?:\bhacka?ton\s+project\b)"
    r"|(?:^\s*todo\s*$)",
    re.IGNORECASE,
)


@dataclass(frozen=True)
class Project:
    id: str
    title: str
    summary: str
    tags: tuple[str, ...]
    models: tuple[str, ...]
    datasets: tuple[str, ...]
    likes: int
    sdk: str
    license: str
    created_at: str
    last_modified: str
    host: str
    url: str

    @classmethod
    def from_dict(cls, data: dict) -> "Project":
        return cls(
            id=str(data["id"]),
            title=str(data.get("title") or data["id"].rsplit("/", 1)[-1]),
            summary=str(data.get("summary") or ""),
            tags=tuple(data.get("tags") or ()),
            models=tuple(data.get("models") or ()),
            datasets=tuple(data.get("datasets") or ()),
            likes=int(data.get("likes") or 0),
            sdk=str(data.get("sdk") or ""),
            license=str(data.get("license") or ""),
            created_at=str(data.get("created_at") or ""),
            last_modified=str(data.get("last_modified") or ""),
            host=str(data.get("host") or ""),
            url=str(data.get("url") or f"https://huggingface.co/spaces/{data['id']}"),
        )

    @property
    def slug(self) -> str:
        return self.id.rsplit("/", 1)[-1]

    @property
    def searchable_text(self) -> str:
        return " ".join(
            [
                self.title,
                self.slug.replace("-", " ").replace("_", " "),
                self.summary,
                " ".join(self.tags),
                " ".join(self.models),
                " ".join(self.datasets),
            ]
        )

    def to_public_dict(self) -> dict:
        return {
            "id": self.id,
            "title": public_project_title(self.title),
            "summary": public_project_summary(self.summary),
            "tags": list(self.tags),
            "models": list(self.models),
            "datasets": list(self.datasets),
            "likes": self.likes,
            "sdk": self.sdk,
            "license": self.license,
            "created_at": self.created_at,
            "last_modified": self.last_modified,
            "host": self.host,
            "url": self.url,
        }

    def to_snapshot_dict(self) -> dict:
        return {
            "id": self.id,
            "title": self.title,
            "summary": self.summary,
            "tags": list(self.tags),
            "models": list(self.models),
            "datasets": list(self.datasets),
            "likes": self.likes,
            "sdk": self.sdk,
            "license": self.license,
            "created_at": self.created_at,
            "last_modified": self.last_modified,
            "host": self.host,
            "url": self.url,
        }


@dataclass(frozen=True)
class SearchHit:
    project: Project
    score: float
    matched_terms: tuple[str, ...]
    page_number: int


@dataclass(frozen=True)
class WhitespaceItem:
    label: str
    pitch: str
    evidence: str
    score: float
    nearby_projects: tuple[Project, ...]

    def to_dict(self) -> dict:
        return {
            "label": self.label,
            "pitch": self.pitch,
            "evidence": self.evidence,
            "score": round(self.score, 3),
            "nearby_projects": [project.to_public_dict() for project in self.nearby_projects],
        }


def public_project_title(title: str) -> str:
    cleaned = " ".join(str(title).split())
    if not cleaned:
        return "Untitled project"
    if GENERIC_PUBLIC_TITLE_RE.search(cleaned):
        return "Untitled project"
    return cleaned


def public_project_summary(summary: str) -> str:
    cleaned = " ".join(str(summary).split())
    if not cleaned:
        return ""
    if GENERIC_PUBLIC_SUMMARY_RE.search(cleaned):
        return ""
    return cleaned


@dataclass(frozen=True)
class WhitespaceSeed:
    label: str
    query: str
    pitch: str


WHITESPACE_SEEDS: tuple[WhitespaceSeed, ...] = (
    WhitespaceSeed(
        "Tiny civic repair desk",
        "local government forms benefits tenant aid accessibility paperwork",
        "A small agent that turns intimidating public-service forms into one-page action plans.",
    ),
    WhitespaceSeed(
        "Hands-on science coach",
        "kitchen science experiment kids sensor notebook classroom",
        "A lab-notebook companion that designs safe experiments from household materials.",
    ),
    WhitespaceSeed(
        "Offline field translator",
        "offline translation field guide travel emergency low connectivity",
        "A local-first phrase and intent helper for stressful travel or field-work moments.",
    ),
    WhitespaceSeed(
        "Personal archive cartographer",
        "photos notes memories archive timeline family history scrapbook",
        "A tiny model that maps a private archive into stories without sending it to cloud APIs.",
    ),
    WhitespaceSeed(
        "Small-team incident scribe",
        "incident retrospective logs on call debugging timeline root cause",
        "A local incident historian that turns messy notes into a calm timeline and next actions.",
    ),
    WhitespaceSeed(
        "Accessibility rehearsal room",
        "accessibility captions alt text screen reader rehearsal inclusive design",
        "A practice space that lets makers rehearse their demo for captions, contrast, and clarity.",
    ),
    WhitespaceSeed(
        "Neighborhood seed library",
        "garden plants seed library neighborhood seasons climate local exchange",
        "An advisor for hyperlocal seed swaps, planting plans, and community garden knowledge.",
    ),
)


INDEX_ALGORITHM = "tfidf-sparse-v1"


class ProjectIndex:
    def __init__(
        self,
        projects: list[Project],
        generated_at: str,
        source: str,
        index_payload: dict | None = None,
    ) -> None:
        if not projects:
            raise ValueError("project index requires at least one project")
        self.projects = projects
        self.generated_at = generated_at
        self.source = source
        if index_payload is None:
            index_payload = build_index_payload(projects, generated_at, source)
        validate_index_payload(index_payload, projects, generated_at, source)
        self.index_generated_at = str(index_payload["generated_at"])
        self.index_algorithm = str(index_payload["algorithm"])
        self.snapshot_digest = str(index_payload["snapshot_digest"])
        self._idf = {str(term): float(value) for term, value in index_payload["idf"].items()}
        self._documents = [
            Counter({str(term): float(value) for term, value in document["weights"].items()})
            for document in index_payload["documents"]
        ]
        self._norms = [float(document["norm"]) for document in index_payload["documents"]]

    @classmethod
    def from_file(cls, path: Path) -> "ProjectIndex":
        data = json.loads(path.read_text(encoding="utf-8"))
        projects = [Project.from_dict(item) for item in data["projects"]]
        return cls(
            projects=projects,
            generated_at=str(data.get("generated_at") or ""),
            source=str(data.get("source") or ""),
        )

    @classmethod
    def from_files(cls, project_path: Path, index_path: Path) -> "ProjectIndex":
        data = json.loads(project_path.read_text(encoding="utf-8"))
        index_payload = json.loads(index_path.read_text(encoding="utf-8"))
        projects = [Project.from_dict(item) for item in data["projects"]]
        return cls(
            projects=projects,
            generated_at=str(data.get("generated_at") or ""),
            source=str(data.get("source") or ""),
            index_payload=index_payload,
        )

    def top_projects(self, limit: int = 8) -> list[Project]:
        return sorted(
            self.projects,
            key=lambda project: (project.likes, project.last_modified, project.title.lower()),
            reverse=True,
        )[:limit]

    def search(self, query: str, limit: int = 5) -> list[SearchHit]:
        query_terms = tokenize(query)
        if not query_terms:
            return []
        query_doc = Counter(query_terms)
        query_norm = self._norm(query_doc)
        hits: list[SearchHit] = []
        for page_number, (project, doc, doc_norm) in enumerate(
            zip(self.projects, self._documents, self._norms, strict=True),
            start=1,
        ):
            if doc_norm == 0.0 or query_norm == 0.0:
                continue
            raw = 0.0
            matched: list[str] = []
            for term, count in query_doc.items():
                if term not in doc:
                    continue
                raw += (count * self._idf.get(term, 1.0)) * doc[term]
                matched.append(term)
            if not matched:
                continue
            title_bonus = sum(0.08 for term in matched if term in tokenize(project.title))
            tag_bonus = sum(0.05 for term in matched if term in tokenize(" ".join(project.tags)))
            score = raw / (query_norm * doc_norm) + title_bonus + tag_bonus
            hits.append(
                SearchHit(
                    project=project,
                    score=score,
                    matched_terms=tuple(sorted(matched)),
                    page_number=page_number,
                )
            )
        hits.sort(key=lambda hit: (hit.score, hit.project.likes), reverse=True)
        return hits[:limit]

    def get(self, project_id: str) -> Project | None:
        for project in self.projects:
            if project.id == project_id or project.slug == project_id:
                return project
        return None

    def find_whitespace(self, limit: int = 5) -> list[WhitespaceItem]:
        items: list[WhitespaceItem] = []
        for seed in WHITESPACE_SEEDS:
            hits = self.search(seed.query, limit=3)
            saturation = sum(hit.score for hit in hits) / max(len(hits), 1)
            score = max(0.0, 1.0 - min(saturation, 0.95))
            if hits:
                evidence = f"Nearest echoes are weak: {', '.join(hit.project.title for hit in hits[:2])}."
            else:
                evidence = "No close project echoes in the current snapshot."
            items.append(
                WhitespaceItem(
                    label=seed.label,
                    pitch=seed.pitch,
                    evidence=evidence,
                    score=score,
                    nearby_projects=tuple(hit.project for hit in hits),
                )
            )
        items.sort(key=lambda item: item.score, reverse=True)
        return items[:limit]

    def _norm(self, doc: Counter[str]) -> float:
        return math.sqrt(sum((count * self._idf.get(term, 1.0)) ** 2 for term, count in doc.items()))


def tokenize(text: str) -> list[str]:
    return [token.lower().strip("._-+") for token in TOKEN_RE.findall(text) if len(token.strip("._-+")) > 1]


def build_index_payload(projects: list[Project], snapshot_generated_at: str, source: str) -> dict:
    documents = [Counter(tokenize(project.searchable_text)) for project in projects]
    df = Counter(term for document in documents for term in document)
    idf = {
        term: math.log((1 + len(documents)) / (1 + freq)) + 1.0
        for term, freq in sorted(df.items())
    }
    indexed_documents = []
    for project, document in zip(projects, documents, strict=True):
        weights = {
            term: round(count * idf.get(term, 1.0), 8)
            for term, count in sorted(document.items())
        }
        norm = math.sqrt(sum(value * value for value in weights.values()))
        indexed_documents.append(
            {
                "project_id": project.id,
                "tokens": sum(document.values()),
                "unique_terms": len(document),
                "norm": round(norm, 8),
                "weights": weights,
            }
        )
    return {
        "schema_version": 1,
        "algorithm": INDEX_ALGORITHM,
        "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "snapshot_generated_at": snapshot_generated_at,
        "snapshot_source": source,
        "snapshot_digest": project_snapshot_digest(projects, snapshot_generated_at, source),
        "document_count": len(projects),
        "vocabulary_size": len(idf),
        "idf": {term: round(value, 8) for term, value in idf.items()},
        "documents": indexed_documents,
    }


def validate_index_payload(
    payload: dict,
    projects: list[Project],
    snapshot_generated_at: str,
    snapshot_source: str,
) -> None:
    if payload.get("schema_version") != 1:
        raise ValueError("unsupported project index schema version")
    if payload.get("algorithm") != INDEX_ALGORITHM:
        raise ValueError(f"unsupported project index algorithm: {payload.get('algorithm')}")
    if payload.get("snapshot_generated_at") != snapshot_generated_at:
        raise ValueError("project index was built from a different snapshot timestamp")
    if payload.get("snapshot_source") != snapshot_source:
        raise ValueError("project index was built from a different snapshot source")
    if payload.get("snapshot_digest") != project_snapshot_digest(
        projects,
        snapshot_generated_at,
        snapshot_source,
    ):
        raise ValueError("project index digest does not match projects snapshot")
    documents = payload.get("documents")
    if not isinstance(documents, list) or len(documents) != len(projects):
        raise ValueError("project index document count does not match projects snapshot")
    project_ids = [project.id for project in projects]
    indexed_ids = [document.get("project_id") for document in documents]
    if indexed_ids != project_ids:
        raise ValueError("project index project order does not match projects snapshot")


def project_snapshot_digest(projects: list[Project], generated_at: str, source: str) -> str:
    payload = {
        "generated_at": generated_at,
        "source": source,
        "projects": [project.to_snapshot_dict() for project in projects],
    }
    encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    return sha256(encoded).hexdigest()