Spaces:
Sleeping
Sleeping
Upload 9 files
Browse files- agents/discovery.py +94 -22
- agents/discovery_api.py +3 -1
- agents/discovery_capabilities.py +162 -0
- docs/DISCOVERY.md +21 -6
- docs/VALIDATION_DISCOVERY_4.12.1.json +47 -0
- mouh/learning/manifest.json +5 -4
- tests/test_discovery.py +3 -3
- tests/test_discovery_capabilities.py +185 -0
- unique_ext/__init__.py +1 -1
agents/discovery.py
CHANGED
|
@@ -22,6 +22,8 @@ from urllib.error import HTTPError
|
|
| 22 |
from urllib.parse import urlencode, urlsplit
|
| 23 |
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
| 24 |
|
|
|
|
|
|
|
| 25 |
HUB = "https://huggingface.co"
|
| 26 |
DOMAIN_WORDS = {
|
| 27 |
"code": ("code", "coder", "coding", "python", "programming", "developer"),
|
|
@@ -35,8 +37,7 @@ _ACTIVE = None
|
|
| 35 |
|
| 36 |
|
| 37 |
def infer_domains(text: str) -> list[str]:
|
| 38 |
-
|
| 39 |
-
return [domain for domain, words in DOMAIN_WORDS.items() if any(word in text for word in words)] or ["general"]
|
| 40 |
|
| 41 |
|
| 42 |
def safe_host(value: str) -> str:
|
|
@@ -66,8 +67,8 @@ def timestamp(value) -> float:
|
|
| 66 |
class Settings:
|
| 67 |
enabled: bool = True
|
| 68 |
limit: int = 24
|
| 69 |
-
budget_s: float =
|
| 70 |
-
timeout_s: float =
|
| 71 |
refresh_s: float = 21600.0
|
| 72 |
ttl_s: float = 86400.0
|
| 73 |
workers: int = 4
|
|
@@ -84,8 +85,8 @@ class Settings:
|
|
| 84 |
return default
|
| 85 |
return cls(enabled=os.environ.get("UNIQUE_DISCOVERY_ENABLED", "1") == "1",
|
| 86 |
limit=int(number("UNIQUE_DISCOVERY_LIMIT", 24, 2, 64)),
|
| 87 |
-
budget_s=number("UNIQUE_DISCOVERY_BUDGET_S",
|
| 88 |
-
timeout_s=number("UNIQUE_DISCOVERY_TIMEOUT_S",
|
| 89 |
refresh_s=number("UNIQUE_DISCOVERY_REFRESH_S", 21600, 900, 604800),
|
| 90 |
ttl_s=number("UNIQUE_DISCOVERY_TTL_S", 86400, 900, 604800))
|
| 91 |
|
|
@@ -128,12 +129,23 @@ class HubClient:
|
|
| 128 |
raise ValueError("liste de Spaces attendue")
|
| 129 |
return result[:self.settings.limit]
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
def inspect(self, repo: str, deadline: float) -> dict:
|
| 132 |
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}/[A-Za-z0-9][A-Za-z0-9_.-]{0,95}", repo):
|
| 133 |
raise ValueError("identifiant de Space invalide")
|
| 134 |
row = {"id": repo, "url": "", "domains": ["general"], "kind": "unknown", "stage": "UNKNOWN",
|
| 135 |
"available": False, "schema_verified": False, "modified": 0.0, "likes": 0,
|
| 136 |
-
"endpoints": [], "error": ""
|
|
|
|
| 137 |
try:
|
| 138 |
info = self.get_json(HUB + "/api/spaces/" + repo, deadline)
|
| 139 |
except HTTPError as exc:
|
|
@@ -147,6 +159,7 @@ class HubClient:
|
|
| 147 |
return row
|
| 148 |
card = info.get("cardData") if isinstance(info.get("cardData"), dict) else {}
|
| 149 |
row["domains"] = infer_domains(" ".join([repo, str(card.get("title", "")), str(info.get("tags", []))]))
|
|
|
|
| 150 |
row["kind"] = info.get("sdk") if info.get("sdk") in KINDS else "unknown"
|
| 151 |
row["modified"] = timestamp(info.get("lastModified"))
|
| 152 |
row["likes"] = max(0, int(info.get("likes") or 0))
|
|
@@ -163,16 +176,22 @@ class HubClient:
|
|
| 163 |
paths = ["/gradio_api/info", "/info"] if row["kind"] == "gradio" else ["/openapi.json"]
|
| 164 |
for path in paths:
|
| 165 |
try:
|
| 166 |
-
schema = self.get_json(row["url"] + path, deadline)
|
| 167 |
if not isinstance(schema, dict):
|
| 168 |
continue
|
| 169 |
endpoints = schema.get("named_endpoints")
|
| 170 |
if row["kind"] == "gradio" and isinstance(endpoints, dict) and endpoints:
|
| 171 |
row.update(available=True, schema_verified=True, endpoints=[n[:160] for n in sorted(endpoints)[:40]])
|
|
|
|
|
|
|
|
|
|
| 172 |
return row
|
| 173 |
if isinstance(schema.get("openapi"), str) and isinstance(schema.get("paths"), dict) and schema["paths"]:
|
| 174 |
row.update(kind="openapi", available=True, schema_verified=True,
|
| 175 |
endpoints=[n[:160] for n in sorted(schema["paths"])[:40]])
|
|
|
|
|
|
|
|
|
|
| 176 |
return row
|
| 177 |
except Exception as exc:
|
| 178 |
row["error"] = type(exc).__name__
|
|
@@ -281,7 +300,8 @@ class Registry:
|
|
| 281 |
stale = now-saved["checked"] > self.ttl_s
|
| 282 |
if domain != "general" and domain not in row["domains"] or kind and row["kind"] != kind:
|
| 283 |
continue
|
| 284 |
-
|
|
|
|
| 285 |
continue
|
| 286 |
count = saved["successes"] + saved["failures"]
|
| 287 |
availability = (saved["successes"]+1)/(count+2)
|
|
@@ -289,18 +309,28 @@ class Registry:
|
|
| 289 |
score = 0.60*availability + 0.25*freshness + 0.15*min(count/10, 1)
|
| 290 |
output.append({**row, "score": round(score, 4), "availability": round(availability, 4),
|
| 291 |
"observations": count, "freshness": round(freshness, 4),
|
| 292 |
-
"last_checked": saved["checked"], "stale": stale,
|
|
|
|
| 293 |
"score_basis": "disponibilité et métadonnées ; qualité des réponses non mesurée"})
|
| 294 |
return sorted(output, key=lambda r: (-r["score"], r["id"]))[:limit]
|
| 295 |
|
| 296 |
def status(self):
|
| 297 |
if not self.path.exists():
|
| 298 |
-
return {"spaces": 0, "last_scan": None, "last_success": None}
|
| 299 |
with self.connection() as db:
|
| 300 |
count = db.execute("SELECT COUNT(*) FROM spaces").fetchone()[0]
|
| 301 |
last = db.execute("SELECT at,ok,detail FROM scans ORDER BY id DESC LIMIT 1").fetchone()
|
| 302 |
success = db.execute("SELECT MAX(at) FROM scans WHERE ok=1").fetchone()[0]
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
|
| 306 |
class DiscoveryWorker:
|
|
@@ -317,6 +347,8 @@ class DiscoveryWorker:
|
|
| 317 |
self._wake = threading.Event()
|
| 318 |
self._thread = None
|
| 319 |
self.last_error = ""
|
|
|
|
|
|
|
| 320 |
|
| 321 |
def scan_once(self):
|
| 322 |
if not self.settings.enabled:
|
|
@@ -326,16 +358,55 @@ class DiscoveryWorker:
|
|
| 326 |
try:
|
| 327 |
self.registry.initialize()
|
| 328 |
deadline = time.monotonic() + self.settings.budget_s
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
repo = batch[index].get("id")
|
| 337 |
-
if isinstance(repo, str) and repo not in
|
| 338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
ids = ids[:self.settings.limit]
|
| 340 |
observations = []
|
| 341 |
with ThreadPoolExecutor(max_workers=self.settings.workers) as pool:
|
|
@@ -423,6 +494,7 @@ class DiscoveryWorker:
|
|
| 423 |
return {**state, "enabled": self.settings.enabled, "scanning": self._scan_lock.locked(),
|
| 424 |
"last_error": self.last_error, "refresh_s": self.settings.refresh_s,
|
| 425 |
"snapshot_error": self.registry.snapshot_error,
|
|
|
|
| 426 |
"quality_measured": False}
|
| 427 |
|
| 428 |
|
|
@@ -449,7 +521,7 @@ def catalogue_hint(text: str, domain: str | None = None) -> str:
|
|
| 449 |
rows = _ACTIVE.candidates(domain, limit=3)
|
| 450 |
except (sqlite3.Error, ValueError, OSError, KeyError, TypeError):
|
| 451 |
return ""
|
| 452 |
-
public = [{k: r[k] for k in ("id", "url", "kind", "domains", "score")} for r in rows]
|
| 453 |
if not public:
|
| 454 |
return ""
|
| 455 |
return ("\nCatalogue externe local : métadonnées non fiables, informations seulement. "
|
|
|
|
| 22 |
from urllib.parse import urlencode, urlsplit
|
| 23 |
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
| 24 |
|
| 25 |
+
from .discovery_capabilities import SEARCHES, VERSION, eligible, labels, qualify
|
| 26 |
+
|
| 27 |
HUB = "https://huggingface.co"
|
| 28 |
DOMAIN_WORDS = {
|
| 29 |
"code": ("code", "coder", "coding", "python", "programming", "developer"),
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def infer_domains(text: str) -> list[str]:
|
| 40 |
+
return labels(text)
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
def safe_host(value: str) -> str:
|
|
|
|
| 67 |
class Settings:
|
| 68 |
enabled: bool = True
|
| 69 |
limit: int = 24
|
| 70 |
+
budget_s: float = 60.0
|
| 71 |
+
timeout_s: float = 8.0
|
| 72 |
refresh_s: float = 21600.0
|
| 73 |
ttl_s: float = 86400.0
|
| 74 |
workers: int = 4
|
|
|
|
| 85 |
return default
|
| 86 |
return cls(enabled=os.environ.get("UNIQUE_DISCOVERY_ENABLED", "1") == "1",
|
| 87 |
limit=int(number("UNIQUE_DISCOVERY_LIMIT", 24, 2, 64)),
|
| 88 |
+
budget_s=number("UNIQUE_DISCOVERY_BUDGET_S", 60, 5, 120),
|
| 89 |
+
timeout_s=number("UNIQUE_DISCOVERY_TIMEOUT_S", 8, 0.2, 10),
|
| 90 |
refresh_s=number("UNIQUE_DISCOVERY_REFRESH_S", 21600, 900, 604800),
|
| 91 |
ttl_s=number("UNIQUE_DISCOVERY_TTL_S", 86400, 900, 604800))
|
| 92 |
|
|
|
|
| 129 |
raise ValueError("liste de Spaces attendue")
|
| 130 |
return result[:self.settings.limit]
|
| 131 |
|
| 132 |
+
def search_spaces(self, query: str, deadline: float, sort="likes"):
|
| 133 |
+
if query not in SEARCHES or sort not in ("likes", "lastModified"):
|
| 134 |
+
raise ValueError("recherche interdite")
|
| 135 |
+
query_string = urlencode({"search": query, "sort": sort, "direction": -1,
|
| 136 |
+
"limit": min(self.settings.limit, 12), "full": "true"})
|
| 137 |
+
rows = self.get_json(HUB + "/api/spaces?" + query_string, deadline, 2000000)
|
| 138 |
+
if not isinstance(rows, list):
|
| 139 |
+
raise ValueError("liste de Spaces attendue")
|
| 140 |
+
return rows[:min(self.settings.limit, 12)]
|
| 141 |
+
|
| 142 |
def inspect(self, repo: str, deadline: float) -> dict:
|
| 143 |
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}/[A-Za-z0-9][A-Za-z0-9_.-]{0,95}", repo):
|
| 144 |
raise ValueError("identifiant de Space invalide")
|
| 145 |
row = {"id": repo, "url": "", "domains": ["general"], "kind": "unknown", "stage": "UNKNOWN",
|
| 146 |
"available": False, "schema_verified": False, "modified": 0.0, "likes": 0,
|
| 147 |
+
"endpoints": [], "error": "", "capability_version": VERSION, "capabilities": [],
|
| 148 |
+
"qualification": "non_qualifie", "rejection_reasons": ["schema_non_verifie"]}
|
| 149 |
try:
|
| 150 |
info = self.get_json(HUB + "/api/spaces/" + repo, deadline)
|
| 151 |
except HTTPError as exc:
|
|
|
|
| 159 |
return row
|
| 160 |
card = info.get("cardData") if isinstance(info.get("cardData"), dict) else {}
|
| 161 |
row["domains"] = infer_domains(" ".join([repo, str(card.get("title", "")), str(info.get("tags", []))]))
|
| 162 |
+
row["metadata_domains"] = list(row["domains"])
|
| 163 |
row["kind"] = info.get("sdk") if info.get("sdk") in KINDS else "unknown"
|
| 164 |
row["modified"] = timestamp(info.get("lastModified"))
|
| 165 |
row["likes"] = max(0, int(info.get("likes") or 0))
|
|
|
|
| 176 |
paths = ["/gradio_api/info", "/info"] if row["kind"] == "gradio" else ["/openapi.json"]
|
| 177 |
for path in paths:
|
| 178 |
try:
|
| 179 |
+
schema = self.get_json(row["url"] + path, deadline, 2000000)
|
| 180 |
if not isinstance(schema, dict):
|
| 181 |
continue
|
| 182 |
endpoints = schema.get("named_endpoints")
|
| 183 |
if row["kind"] == "gradio" and isinstance(endpoints, dict) and endpoints:
|
| 184 |
row.update(available=True, schema_verified=True, endpoints=[n[:160] for n in sorted(endpoints)[:40]])
|
| 185 |
+
row.update(qualify(schema, "gradio", row["metadata_domains"]))
|
| 186 |
+
row["domains"] = sorted(set(row["domains"]) | {d for c in row["capabilities"] for d in c["domains"]})
|
| 187 |
+
row["error"] = ""
|
| 188 |
return row
|
| 189 |
if isinstance(schema.get("openapi"), str) and isinstance(schema.get("paths"), dict) and schema["paths"]:
|
| 190 |
row.update(kind="openapi", available=True, schema_verified=True,
|
| 191 |
endpoints=[n[:160] for n in sorted(schema["paths"])[:40]])
|
| 192 |
+
row.update(qualify(schema, "openapi", row["metadata_domains"]))
|
| 193 |
+
row["domains"] = sorted(set(row["domains"]) | {d for c in row["capabilities"] for d in c["domains"]})
|
| 194 |
+
row["error"] = ""
|
| 195 |
return row
|
| 196 |
except Exception as exc:
|
| 197 |
row["error"] = type(exc).__name__
|
|
|
|
| 300 |
stale = now-saved["checked"] > self.ttl_s
|
| 301 |
if domain != "general" and domain not in row["domains"] or kind and row["kind"] != kind:
|
| 302 |
continue
|
| 303 |
+
routable = not stale and row["available"] and row["schema_verified"] and eligible(row, domain)
|
| 304 |
+
if ready_only and not routable:
|
| 305 |
continue
|
| 306 |
count = saved["successes"] + saved["failures"]
|
| 307 |
availability = (saved["successes"]+1)/(count+2)
|
|
|
|
| 309 |
score = 0.60*availability + 0.25*freshness + 0.15*min(count/10, 1)
|
| 310 |
output.append({**row, "score": round(score, 4), "availability": round(availability, 4),
|
| 311 |
"observations": count, "freshness": round(freshness, 4),
|
| 312 |
+
"last_checked": saved["checked"], "stale": stale, "routable": bool(routable),
|
| 313 |
+
"needs_requalification": row.get("capability_version") != VERSION,
|
| 314 |
"score_basis": "disponibilité et métadonnées ; qualité des réponses non mesurée"})
|
| 315 |
return sorted(output, key=lambda r: (-r["score"], r["id"]))[:limit]
|
| 316 |
|
| 317 |
def status(self):
|
| 318 |
if not self.path.exists():
|
| 319 |
+
return {"spaces": 0, "qualified_spaces": 0, "qualified_by_domain": {d: 0 for d in DOMAIN_WORDS}, "last_scan": None, "last_success": None}
|
| 320 |
with self.connection() as db:
|
| 321 |
count = db.execute("SELECT COUNT(*) FROM spaces").fetchone()[0]
|
| 322 |
last = db.execute("SELECT at,ok,detail FROM scans ORDER BY id DESC LIMIT 1").fetchone()
|
| 323 |
success = db.execute("SELECT MAX(at) FROM scans WHERE ok=1").fetchone()[0]
|
| 324 |
+
saved_rows = db.execute("SELECT payload,checked FROM spaces LIMIT 1000").fetchall()
|
| 325 |
+
qualified = []
|
| 326 |
+
for saved in saved_rows:
|
| 327 |
+
row = json.loads(saved["payload"])
|
| 328 |
+
if (time.time()-saved["checked"] <= self.ttl_s and row.get("available")
|
| 329 |
+
and row.get("schema_verified") and eligible(row)):
|
| 330 |
+
qualified.append(row)
|
| 331 |
+
return {"spaces": count, "qualified_spaces": len(qualified),
|
| 332 |
+
"qualified_by_domain": {d: sum(eligible(row, d) for row in qualified) for d in DOMAIN_WORDS},
|
| 333 |
+
"last_scan": dict(last) if last else None, "last_success": success}
|
| 334 |
|
| 335 |
|
| 336 |
class DiscoveryWorker:
|
|
|
|
| 347 |
self._wake = threading.Event()
|
| 348 |
self._thread = None
|
| 349 |
self.last_error = ""
|
| 350 |
+
self.discovery_warnings = []
|
| 351 |
+
self._round = 0
|
| 352 |
|
| 353 |
def scan_once(self):
|
| 354 |
if not self.settings.enabled:
|
|
|
|
| 358 |
try:
|
| 359 |
self.registry.initialize()
|
| 360 |
deadline = time.monotonic() + self.settings.budget_s
|
| 361 |
+
# Les recherches ciblées ont priorité. Une panne d'une source n'annule
|
| 362 |
+
# pas les autres sources ; toute panne globale conserve le cache.
|
| 363 |
+
batches = []
|
| 364 |
+
self.discovery_warnings = []
|
| 365 |
+
cycle = self._round
|
| 366 |
+
self._round += 1
|
| 367 |
+
requests = []
|
| 368 |
+
search = getattr(self.client, "search_spaces", None)
|
| 369 |
+
if search:
|
| 370 |
+
queries = SEARCHES[cycle % len(SEARCHES):] + SEARCHES[:cycle % len(SEARCHES)]
|
| 371 |
+
requests.extend(("search:" + q, search, (q, deadline, "likes" if cycle % 2 == 0 else "lastModified")) for q in queries)
|
| 372 |
+
requests.extend((sort, self.client.list_spaces, (sort, deadline)) for sort in ("lastModified", "likes"))
|
| 373 |
+
# La collecte ne consomme pas tout le budget réservé aux schémas.
|
| 374 |
+
listing_deadline = min(deadline, time.monotonic() + self.settings.budget_s * 0.35)
|
| 375 |
+
with ThreadPoolExecutor(max_workers=self.settings.workers) as pool:
|
| 376 |
+
jobs = []
|
| 377 |
+
for name, fn, args in requests:
|
| 378 |
+
call_args = (args[0], listing_deadline, args[2]) if name.startswith("search:") else (args[0], listing_deadline)
|
| 379 |
+
jobs.append((name, pool.submit(fn, *call_args)))
|
| 380 |
+
for name, job in jobs:
|
| 381 |
+
try:
|
| 382 |
+
batch = job.result()
|
| 383 |
+
if not isinstance(batch, list):
|
| 384 |
+
raise ValueError("liste attendue")
|
| 385 |
+
if batch:
|
| 386 |
+
offset = cycle % len(batch)
|
| 387 |
+
batch = batch[offset:] + batch[:offset]
|
| 388 |
+
batches.append(batch)
|
| 389 |
+
except Exception as exc:
|
| 390 |
+
self.discovery_warnings.append(name + ":" + type(exc).__name__)
|
| 391 |
+
if not batches:
|
| 392 |
+
raise OSError("toutes les sources de découverte sont indisponibles")
|
| 393 |
+
fresh = []
|
| 394 |
+
for index in range(max((len(batch) for batch in batches), default=0)):
|
| 395 |
+
for batch in batches:
|
| 396 |
+
if index < len(batch) and isinstance(batch[index], dict) and not batch[index].get("private") and not batch[index].get("gated"):
|
| 397 |
repo = batch[index].get("id")
|
| 398 |
+
if isinstance(repo, str) and repo not in fresh:
|
| 399 |
+
fresh.append(repo)
|
| 400 |
+
prior = self.registry.oldest_ids(self.settings.limit)
|
| 401 |
+
# 3/4 de nouveaux candidats, 1/4 de recontrôles ; le cache ne doit pas
|
| 402 |
+
# monopoliser le prochain scan et empêcher les découvertes ciblées.
|
| 403 |
+
quota = max(1, self.settings.limit // 4)
|
| 404 |
+
ids = fresh[:max(1, self.settings.limit - quota)]
|
| 405 |
+
for repo in prior + fresh:
|
| 406 |
+
if repo not in ids:
|
| 407 |
+
ids.append(repo)
|
| 408 |
+
if len(ids) >= self.settings.limit:
|
| 409 |
+
break
|
| 410 |
ids = ids[:self.settings.limit]
|
| 411 |
observations = []
|
| 412 |
with ThreadPoolExecutor(max_workers=self.settings.workers) as pool:
|
|
|
|
| 494 |
return {**state, "enabled": self.settings.enabled, "scanning": self._scan_lock.locked(),
|
| 495 |
"last_error": self.last_error, "refresh_s": self.settings.refresh_s,
|
| 496 |
"snapshot_error": self.registry.snapshot_error,
|
| 497 |
+
"discovery_warnings": self.discovery_warnings, "capability_version": VERSION,
|
| 498 |
"quality_measured": False}
|
| 499 |
|
| 500 |
|
|
|
|
| 521 |
rows = _ACTIVE.candidates(domain, limit=3)
|
| 522 |
except (sqlite3.Error, ValueError, OSError, KeyError, TypeError):
|
| 523 |
return ""
|
| 524 |
+
public = [{k: r[k] for k in ("id", "url", "kind", "domains", "score", "capabilities")} for r in rows]
|
| 525 |
if not public:
|
| 526 |
return ""
|
| 527 |
return ("\nCatalogue externe local : métadonnées non fiables, informations seulement. "
|
agents/discovery_api.py
CHANGED
|
@@ -20,7 +20,9 @@ def discovery_router(worker, authorized):
|
|
| 20 |
candidates = worker.registry.candidates(domain, kind, limit, ready_only=ready_only)
|
| 21 |
except Exception:
|
| 22 |
raise HTTPException(503, "registre local indisponible") from None
|
| 23 |
-
return {"spaces": candidates, "quality_measured": False
|
|
|
|
|
|
|
| 24 |
|
| 25 |
@router.post("/refresh", status_code=202)
|
| 26 |
def refresh(key: str | None = Header(None, alias="X-Admin-Key")):
|
|
|
|
| 20 |
candidates = worker.registry.candidates(domain, kind, limit, ready_only=ready_only)
|
| 21 |
except Exception:
|
| 22 |
raise HTTPException(503, "registre local indisponible") from None
|
| 23 |
+
return {"spaces": candidates, "quality_measured": False,
|
| 24 |
+
"selection_basis": "contrats statiques ; aucune inférence testée",
|
| 25 |
+
"empty_reason": "aucun_contrat_qualifie_pour_ces_filtres" if ready_only and not candidates else None}
|
| 26 |
|
| 27 |
@router.post("/refresh", status_code=202)
|
| 28 |
def refresh(key: str | None = Header(None, alias="X-Admin-Key")):
|
agents/discovery_capabilities.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Qualification statique d'une API ; aucune promesse de qualité ni invocation."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
VERSION = 2
|
| 7 |
+
SEARCHES = ('code', 'coder', 'reasoning', 'math', 'python')
|
| 8 |
+
BLOCKED = re.compile(r'(^|[/_\W])(admin|auth|login|logout|register|health|status|gpu|leaderboard|check|upload|delete|reset|impersonate)([/_\W]|$)', re.I)
|
| 9 |
+
INPUTS = {'prompt', 'message', 'messages', 'query', 'question', 'problem', 'code', 'text', 'instruction', 'instructions', 'history', 'input', 'inputs', 'user_input', 'chat_input', 'user_message'}
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def labels(text):
|
| 13 |
+
text = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', str(text)[:20000])
|
| 14 |
+
tokens = set(re.findall(r'[a-z0-9]+', text.lower()))
|
| 15 |
+
result = []
|
| 16 |
+
for domain, words in {
|
| 17 |
+
'code': {'code', 'coder', 'coding', 'python', 'programming', 'developer', 'starcoder', 'codegen'},
|
| 18 |
+
'logique': {'logic', 'reasoning', 'math', 'mathematics', 'theorem', 'formal', 'proof', 'solver'},
|
| 19 |
+
'texte': {'chat', 'chatbot', 'llm', 'nlp', 'translation', 'summarization', 'text'},
|
| 20 |
+
'image': {'image', 'vision', 'diffusion', 'flux', 'photo'},
|
| 21 |
+
'audio': {'audio', 'speech', 'voice', 'music', 'whisper'},
|
| 22 |
+
}.items():
|
| 23 |
+
if tokens & words:
|
| 24 |
+
result.append(domain)
|
| 25 |
+
# QR codes et restauration CodeFormer ne sont pas de la programmation.
|
| 26 |
+
if ('qr' in tokens or {'code', 'former'} <= tokens) and not tokens & {'coder', 'python', 'programming', 'developer'}:
|
| 27 |
+
result = [d for d in result if d != 'code']
|
| 28 |
+
return result or ['general']
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def resolve(value, schema, depth=0):
|
| 32 |
+
"""Références locales seulement, profondeur bornée ; aucun téléchargement $ref."""
|
| 33 |
+
if not isinstance(value, dict) or depth >= 8:
|
| 34 |
+
return {}
|
| 35 |
+
ref = value.get('$ref')
|
| 36 |
+
if ref:
|
| 37 |
+
if not isinstance(ref, str) or not ref.startswith('#/'):
|
| 38 |
+
return {}
|
| 39 |
+
target = schema
|
| 40 |
+
for part in ref[2:].split('/'):
|
| 41 |
+
target = target.get(part.replace('~1', '/').replace('~0', '~'), {}) if isinstance(target, dict) else {}
|
| 42 |
+
return resolve(target, schema, depth+1)
|
| 43 |
+
for union in ('anyOf', 'oneOf', 'allOf'):
|
| 44 |
+
if union in value:
|
| 45 |
+
# Une variante nulle est admise ; les contrats ambigus restent exclus.
|
| 46 |
+
options = value[union]
|
| 47 |
+
if not isinstance(options, list):
|
| 48 |
+
return {}
|
| 49 |
+
options = [resolve(v, schema, depth+1) for v in options[:8]]
|
| 50 |
+
options = [v for v in options if v.get('type') != 'null']
|
| 51 |
+
return options[0] if len(options) == 1 else {}
|
| 52 |
+
return value
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def type_name(value):
|
| 56 |
+
if not isinstance(value, dict):
|
| 57 |
+
return ''
|
| 58 |
+
py = value.get('python_type', {})
|
| 59 |
+
name = py.get('type', '') if isinstance(py, dict) else ''
|
| 60 |
+
return str(name or value.get('type', ''))[:80].lower()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def qualify(schema, kind, metadata_domains):
|
| 64 |
+
capabilities = []
|
| 65 |
+
rejected = []
|
| 66 |
+
|
| 67 |
+
def add(path, method, parameters, outputs, evidence='', authenticated=False):
|
| 68 |
+
if BLOCKED.search(path):
|
| 69 |
+
rejected.append('route_utilitaire_ou_administration')
|
| 70 |
+
return
|
| 71 |
+
if authenticated:
|
| 72 |
+
rejected.append('authentification_requise')
|
| 73 |
+
return
|
| 74 |
+
supported = [p for p in parameters if p['name'].lower() in INPUTS and p['type'] in ('str', 'string', 'array', 'list', 'list[dict]', 'list[list[str]]', 'list[dict[str, str]]')]
|
| 75 |
+
if not supported or not outputs:
|
| 76 |
+
rejected.append('contrat_entree_sortie_insuffisant')
|
| 77 |
+
return
|
| 78 |
+
# Un paramètre obligatoire inconnu empêche de préparer un appel sûr.
|
| 79 |
+
if any(p['required'] and p not in supported and not p.get('has_default') for p in parameters):
|
| 80 |
+
rejected.append('parametre_obligatoire_non_pris_en_charge')
|
| 81 |
+
return
|
| 82 |
+
domains = set(metadata_domains) | set(labels(path + ' ' + evidence))
|
| 83 |
+
domains.discard('general')
|
| 84 |
+
if not domains:
|
| 85 |
+
rejected.append('specialite_non_etablie')
|
| 86 |
+
return
|
| 87 |
+
capabilities.append({'endpoint': path[:160], 'method': method, 'domains': sorted(domains),
|
| 88 |
+
'inputs': parameters[:12], 'outputs': outputs[:12],
|
| 89 |
+
'verification': 'contrat_statique', 'invocation_tested': False})
|
| 90 |
+
|
| 91 |
+
if kind == 'gradio':
|
| 92 |
+
endpoints = schema.get('named_endpoints', {})
|
| 93 |
+
for path, endpoint in list(endpoints.items())[:200]:
|
| 94 |
+
if not isinstance(path, str) or not isinstance(endpoint, dict):
|
| 95 |
+
continue
|
| 96 |
+
params, returns = endpoint.get('parameters'), endpoint.get('returns')
|
| 97 |
+
if not isinstance(params, list) or not isinstance(returns, list):
|
| 98 |
+
rejected.append('contrat_entree_sortie_insuffisant')
|
| 99 |
+
continue
|
| 100 |
+
parameters = [{'name': str(p.get('parameter_name', ''))[:80], 'type': type_name(p),
|
| 101 |
+
'required': not bool(p.get('parameter_has_default', False)),
|
| 102 |
+
'has_default': bool(p.get('parameter_has_default', False))}
|
| 103 |
+
for p in params[:40] if isinstance(p, dict)]
|
| 104 |
+
outputs = [type_name(r) for r in returns[:12] if isinstance(r, dict) and type_name(r) in ('str', 'string', 'dict', 'object', 'array', 'list', 'list[dict]', 'list[list[str]]', 'list[dict[str, str]]')]
|
| 105 |
+
if len(params) > 40:
|
| 106 |
+
continue
|
| 107 |
+
add(path, 'GRADIO', parameters, outputs, str(endpoint.get('description', ''))[:1000])
|
| 108 |
+
elif kind == 'openapi':
|
| 109 |
+
for path, item in list(schema.get('paths', {}).items())[:200]:
|
| 110 |
+
if not isinstance(path, str) or not isinstance(item, dict):
|
| 111 |
+
continue
|
| 112 |
+
operation = item.get('post')
|
| 113 |
+
if not isinstance(operation, dict):
|
| 114 |
+
continue
|
| 115 |
+
body = resolve(operation.get('requestBody', {}), schema)
|
| 116 |
+
media = body.get('content', {}).get('application/json', {})
|
| 117 |
+
shape = resolve(media.get('schema', {}), schema)
|
| 118 |
+
props = shape.get('properties', {})
|
| 119 |
+
if not isinstance(props, dict) or len(props) > 40:
|
| 120 |
+
continue
|
| 121 |
+
parameters = []
|
| 122 |
+
for name, p in props.items():
|
| 123 |
+
p = resolve(p, schema)
|
| 124 |
+
input_type = str(p.get('type', ''))[:80]
|
| 125 |
+
if input_type == 'array':
|
| 126 |
+
items = resolve(p.get('items', {}), schema)
|
| 127 |
+
props = items.get('properties', {})
|
| 128 |
+
messages = (isinstance(props, dict) and
|
| 129 |
+
resolve(props.get('content', {}), schema).get('type') == 'string' and
|
| 130 |
+
resolve(props.get('role', {}), schema).get('type') == 'string')
|
| 131 |
+
if items.get('type') != 'string' and not messages:
|
| 132 |
+
input_type = 'unsupported_array'
|
| 133 |
+
parameters.append({'name': str(name)[:80], 'type': input_type,
|
| 134 |
+
'required': name in shape.get('required', []), 'has_default': 'default' in p})
|
| 135 |
+
# Chemins et paramètres HTTP obligatoires doivent également être connus.
|
| 136 |
+
http_params = item.get('parameters', []) + operation.get('parameters', [])
|
| 137 |
+
for p in http_params[:40]:
|
| 138 |
+
p = resolve(p, schema)
|
| 139 |
+
if p.get('required'):
|
| 140 |
+
parameters.append({'name': str(p.get('name', ''))[:80], 'type': 'unsupported_http_parameter', 'required': True, 'has_default': False})
|
| 141 |
+
outputs = []
|
| 142 |
+
responses = operation.get('responses', {})
|
| 143 |
+
for status, response in list(responses.items())[:20]:
|
| 144 |
+
if str(status).startswith('2'):
|
| 145 |
+
response = resolve(response, schema)
|
| 146 |
+
out = resolve(response.get('content', {}).get('application/json', {}).get('schema', {}), schema)
|
| 147 |
+
if out.get('type') in ('string', 'object', 'array'):
|
| 148 |
+
outputs.append(out['type'])
|
| 149 |
+
add(path, 'POST', parameters, outputs,
|
| 150 |
+
str(operation.get('summary', ''))[:500] + ' ' + str(operation.get('description', ''))[:500],
|
| 151 |
+
bool(operation.get('security', schema.get('security', []))))
|
| 152 |
+
return {'capability_version': VERSION, 'capabilities': capabilities[:40],
|
| 153 |
+
'qualification': 'contrat_statique' if capabilities else 'non_qualifie',
|
| 154 |
+
'rejection_reasons': sorted(set(rejected))[:12] or ([] if capabilities else ['aucune_route_inference_qualifiee'])}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def eligible(row, domain='general'):
|
| 158 |
+
if row.get('capability_version') != VERSION:
|
| 159 |
+
return False
|
| 160 |
+
return any(isinstance(c, dict) and c.get('inputs') and c.get('outputs') and
|
| 161 |
+
(domain == 'general' or domain in c.get('domains', []))
|
| 162 |
+
for c in row.get('capabilities', []))
|
docs/DISCOVERY.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# UNIQUE 4.12.
|
| 2 |
|
| 3 |
## Ce qui est installé
|
| 4 |
|
|
@@ -10,7 +10,7 @@ Le catalogue est exploitable par les agents via une requête SQLite, la fonction
|
|
| 10 |
|
| 11 |
## Installation
|
| 12 |
|
| 13 |
-
Ce
|
| 14 |
|
| 15 |
Conserver le secret `UNIQUE_ADMIN_KEY`. Retirer `UNIQUE_EXT_INSTALL` et `UNIQUE_EXT_ROLLBACK` s'ils réinstallent une ancienne archive. Après la reconstruction, ouvrir `/api/discovery/status` pour suivre le premier scan.
|
| 16 |
|
|
@@ -20,7 +20,7 @@ Les domaines sont `code`, `logique`, `texte`, `image`, `audio`, `general`. L'ét
|
|
| 20 |
|
| 21 |
Un Space Gradio n'est éligible au routage qu'après lecture d'un schéma `/gradio_api/info` ou `/info` contenant des endpoints nommés. Un Space Docker n'est classé `openapi` qu'après lecture d'un schéma OpenAPI valide avec des routes. Le label Docker seul ne permet pas d'affirmer qu'il s'agit de FastAPI. Les autres catégories servent au diagnostic et ne sont pas éligibles par défaut.
|
| 22 |
|
| 23 |
-
Les Spaces privés, à accès contrôlé, supprimés, non exécutés, indisponibles ou dont le
|
| 24 |
|
| 25 |
## Score et fraîcheur
|
| 26 |
|
|
@@ -49,8 +49,8 @@ Une panne du Hub ne vide pas l'ancien registre. Les lignes périmées sont exclu
|
|
| 49 |
| `UNIQUE_DISCOVERY_ENABLED` | `1` | `0` désactive les scans réseau ; les lectures du cache restent possibles |
|
| 50 |
| `UNIQUE_DISCOVERY_CONTEXT` | `1` | `0` désactive l'ajout de candidats au contexte des tâches |
|
| 51 |
| `UNIQUE_DISCOVERY_LIMIT` | `24` | Nombre de Spaces observés par scan, borné entre 2 et 64 |
|
| 52 |
-
| `UNIQUE_DISCOVERY_BUDGET_S` | `
|
| 53 |
-
| `UNIQUE_DISCOVERY_TIMEOUT_S` | `
|
| 54 |
| `UNIQUE_DISCOVERY_REFRESH_S` | `21600` | Rafraîchissement toutes les six heures, borné entre 15 minutes et sept jours |
|
| 55 |
| `UNIQUE_DISCOVERY_TTL_S` | `86400` | Exclusion des entrées non vérifiées depuis 24 heures par défaut |
|
| 56 |
| `UNIQUE_DISCOVERY_DIR` | `~/.cache/unique` | Racine locale du registre SQLite |
|
|
@@ -72,6 +72,21 @@ Pour un contrôle manuel du worker uniquement : `python -m agents.discovery --ro
|
|
| 72 |
|
| 73 |
Ce registre prépare la découverte et la sélection ; il ne remplace pas les générateurs d'UNIQUE par des modèles publics. L'invocation distante demanderait une intégration séparée : sélection d'une route précise, validation de ses paramètres et politique d'envoi de données.
|
| 74 |
|
| 75 |
-
Les tests couvrent le démarrage non bloquant, la persistance, la restauration, les pannes réseau, les entrées périmées, les schémas, l'absence d'envoi de jeton, la validation des hôtes, les lecteurs SQLite simultanés et l'authentification du rafraîchissement. La macro-boucle est rejouée avec le catalogue présent. Les résultats exacts sont dans `VALIDATION_DISCOVERY_4.12.json` ; le démarrage complet de l'image avec le modèle A10G n'est pas présenté comme validé ici.
|
| 76 |
|
| 77 |
Références des interfaces publiques : [Hub API](https://huggingface.co/docs/hub/api), [list_spaces et SpaceInfo](https://huggingface.co/docs/huggingface_hub/package_reference/hf_api#huggingface_hub.HfApi.list_spaces).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# UNIQUE 4.12.1 — registre local de Spaces publics
|
| 2 |
|
| 3 |
## Ce qui est installé
|
| 4 |
|
|
|
|
| 10 |
|
| 11 |
## Installation
|
| 12 |
|
| 13 |
+
Ce correctif complète la découverte 4.12.0 déjà installée et conserve son registre SQLite et sa sauvegarde. Décompresser puis uploader tous les fichiers de l'archive à la racine de TARGET_SPACE, en conservant leurs chemins, dans un seul commit. Le démarrage est intégré au lifespan de `app.py` ; il n'y a pas de commande Docker supplémentaire à lancer.
|
| 14 |
|
| 15 |
Conserver le secret `UNIQUE_ADMIN_KEY`. Retirer `UNIQUE_EXT_INSTALL` et `UNIQUE_EXT_ROLLBACK` s'ils réinstallent une ancienne archive. Après la reconstruction, ouvrir `/api/discovery/status` pour suivre le premier scan.
|
| 16 |
|
|
|
|
| 20 |
|
| 21 |
Un Space Gradio n'est éligible au routage qu'après lecture d'un schéma `/gradio_api/info` ou `/info` contenant des endpoints nommés. Un Space Docker n'est classé `openapi` qu'après lecture d'un schéma OpenAPI valide avec des routes. Le label Docker seul ne permet pas d'affirmer qu'il s'agit de FastAPI. Les autres catégories servent au diagnostic et ne sont pas éligibles par défaut.
|
| 22 |
|
| 23 |
+
Les Spaces privés, à accès contrôlé, supprimés, non exécutés, indisponibles ou dont le contrat n'est pas qualifié sont écartés de la sélection. Les Spaces endormis ne sont pas réveillés par le worker. Les hôtes d'application sont limités à HTTPS sur un sous-domaine direct `*.hf.space`, sans port personnalisé, identifiants ni redirections. Les domaines personnalisés ne sont pas pris en charge dans cette version.
|
| 24 |
|
| 25 |
## Score et fraîcheur
|
| 26 |
|
|
|
|
| 49 |
| `UNIQUE_DISCOVERY_ENABLED` | `1` | `0` désactive les scans réseau ; les lectures du cache restent possibles |
|
| 50 |
| `UNIQUE_DISCOVERY_CONTEXT` | `1` | `0` désactive l'ajout de candidats au contexte des tâches |
|
| 51 |
| `UNIQUE_DISCOVERY_LIMIT` | `24` | Nombre de Spaces observés par scan, borné entre 2 et 64 |
|
| 52 |
+
| `UNIQUE_DISCOVERY_BUDGET_S` | `60` | Budget de scan, borné entre 5 et 120 secondes |
|
| 53 |
+
| `UNIQUE_DISCOVERY_TIMEOUT_S` | `8` | Timeout réseau par requête, borné entre 0,2 et 10 secondes |
|
| 54 |
| `UNIQUE_DISCOVERY_REFRESH_S` | `21600` | Rafraîchissement toutes les six heures, borné entre 15 minutes et sept jours |
|
| 55 |
| `UNIQUE_DISCOVERY_TTL_S` | `86400` | Exclusion des entrées non vérifiées depuis 24 heures par défaut |
|
| 56 |
| `UNIQUE_DISCOVERY_DIR` | `~/.cache/unique` | Racine locale du registre SQLite |
|
|
|
|
| 72 |
|
| 73 |
Ce registre prépare la découverte et la sélection ; il ne remplace pas les générateurs d'UNIQUE par des modèles publics. L'invocation distante demanderait une intégration séparée : sélection d'une route précise, validation de ses paramètres et politique d'envoi de données.
|
| 74 |
|
| 75 |
+
Les tests couvrent le démarrage non bloquant, la persistance, la restauration, les pannes réseau, les entrées périmées, les schémas, l'absence d'envoi de jeton, la validation des hôtes, les lecteurs SQLite simultanés et l'authentification du rafraîchissement. La macro-boucle est rejouée avec le catalogue présent. Les résultats exacts sont dans `VALIDATION_DISCOVERY_4.12.1.json` ; le démarrage complet de l'image avec le modèle A10G n'est pas présenté comme validé ici.
|
| 76 |
|
| 77 |
Références des interfaces publiques : [Hub API](https://huggingface.co/docs/hub/api), [list_spaces et SpaceInfo](https://huggingface.co/docs/huggingface_hub/package_reference/hf_api#huggingface_hub.HfApi.list_spaces).
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
## Correctif 4.12.1 : pertinence et contrats
|
| 81 |
+
|
| 82 |
+
La liste vide observée dans le domaine code venait d'un scan généraliste : des APIs utilitaires et des tableaux de classement occupaient le catalogue. Désormais, cinq recherches Hub ciblées (`code`, `coder`, `reasoning`, `math`, `python`) passent avant les sources récentes et populaires. Les sources sont interrogées indépendamment : une panne partielle ne supprime pas les résultats des autres. Le tri et les premiers résultats tournent entre les scans. Les trois quarts du quota vont aux candidats découverts et le quart restant aux recontrôles de l'ancien catalogue, avec redistribution des places inutilisées. Le budget global reste borné.
|
| 83 |
+
|
| 84 |
+
Une API accessible ne suffit plus. Chaque fonction candidate doit exposer un paramètre textuel ou de conversation reconnu, une sortie déclarée et une spécialité identifiable. Une entrée obligatoire inconnue, une route d'administration, d'authentification, d'état ou de contrôle GPU empêchent sa qualification. Pour OpenAPI, seules les routes POST avec corps JSON et réponse JSON sont actuellement prises en charge. Les routes déclarant une authentification sont exclues. Les références de schémas restent locales et bornées ; aucune référence distante n'est téléchargée.
|
| 85 |
+
|
| 86 |
+
Le statut distingue `spaces` (observations stockées), `qualified_spaces` et `qualified_by_domain` (contrats sélectionnables et non périmés). Une sélection vide donne `empty_reason` au lieu de laisser supposer une panne.
|
| 87 |
+
|
| 88 |
+
Les champs `capabilities`, `qualification`, `rejection_reasons`, `routable` et `needs_requalification` expliquent la sélection. `capabilities` contient l'endpoint, la méthode, les noms et types des entrées et les sorties déclarées. Les anciens enregistrements 4.12.0 restent consultables avec `ready_only=false`, mais sont exclus des candidats tant que le worker ne les a pas requalifiés. Le score historique mesure toujours l'accessibilité API, séparément de la qualification.
|
| 89 |
+
|
| 90 |
+
La qualification est **statique** : elle ne prouve ni que l'API est réellement anonyme, ni que le modèle sait résoudre la mission. `invocation_tested=false` et `quality_measured=false` restent explicites. Les schémas insuffisamment documentés ou non pris en charge sont exclus, même si l'application pourrait fonctionner manuellement. Aucun candidat n'est garanti à chaque scan : un domaine peut rester vide si aucun contrat adéquat n'est accessible. UNIQUE continue alors avec son modèle local.
|
| 91 |
+
|
| 92 |
+
Après upload de tous les fichiers du correctif dans un seul commit et redémarrage, attendre la fin du premier scan. Vérifier `/api/discovery/status`, puis `/api/discovery/spaces?domain=code&limit=5`. Pour comprendre une exclusion, utiliser `/api/discovery/spaces?domain=code&ready_only=false&limit=50`. Il n'est pas nécessaire de supprimer le cache ni de modifier des secrets.
|
docs/VALIDATION_DISCOVERY_4.12.1.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": "4.12.1",
|
| 3 |
+
"date": "2026-11-12",
|
| 4 |
+
"tests": {
|
| 5 |
+
"discovery": {
|
| 6 |
+
"tests": 52,
|
| 7 |
+
"failures": 0,
|
| 8 |
+
"errors": 0,
|
| 9 |
+
"skipped": 0
|
| 10 |
+
},
|
| 11 |
+
"macro_compatibility": {
|
| 12 |
+
"tests": 20,
|
| 13 |
+
"failures": 0,
|
| 14 |
+
"errors": 0,
|
| 15 |
+
"skipped": 0
|
| 16 |
+
}
|
| 17 |
+
},
|
| 18 |
+
"syntax": "Python AST valid for all changed runtime modules",
|
| 19 |
+
"live_scan": {
|
| 20 |
+
"status": {
|
| 21 |
+
"spaces": 11,
|
| 22 |
+
"qualified_spaces": 1,
|
| 23 |
+
"qualified_by_domain": {
|
| 24 |
+
"code": 1,
|
| 25 |
+
"logique": 0,
|
| 26 |
+
"texte": 0,
|
| 27 |
+
"image": 0,
|
| 28 |
+
"audio": 0
|
| 29 |
+
},
|
| 30 |
+
"last_scan": {
|
| 31 |
+
"at": 1794501105.406573,
|
| 32 |
+
"ok": 1,
|
| 33 |
+
"detail": "11 observations publiques"
|
| 34 |
+
},
|
| 35 |
+
"last_success": 1794501105.406573
|
| 36 |
+
},
|
| 37 |
+
"generation_calls": 0,
|
| 38 |
+
"limits": "Static qualification only; no inference executed"
|
| 39 |
+
},
|
| 40 |
+
"limits": [
|
| 41 |
+
"Full Docker/A10G model startup not tested locally",
|
| 42 |
+
"Availability scores are not model quality scores",
|
| 43 |
+
"Domains use lexical metadata rules",
|
| 44 |
+
"Catalogue selection does not invoke external models",
|
| 45 |
+
"Initial cache may be empty; stale entries excluded by default"
|
| 46 |
+
]
|
| 47 |
+
}
|
mouh/learning/manifest.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
{
|
| 2 |
-
"version": "v4.12.
|
| 3 |
"files": {
|
| 4 |
"Dockerfile": "b3f4ddb914b0198d",
|
| 5 |
"README.md": "ed433a59c0e4fb6d",
|
|
@@ -86,7 +86,7 @@
|
|
| 86 |
"requirements-dev.txt": "9a03d0d2ca94a0d2",
|
| 87 |
"requirements.txt": "8877a189d3a2a02c",
|
| 88 |
"unique_ext/README.md": "0f0be41551e6bacb",
|
| 89 |
-
"unique_ext/__init__.py": "
|
| 90 |
"unique_ext/backends/__init__.py": "e3b0c44298fc1c14",
|
| 91 |
"unique_ext/backends/hf.py": "506d29e81c127e1e",
|
| 92 |
"unique_ext/contracts.py": "4ce5632e921dfcdc",
|
|
@@ -135,8 +135,9 @@
|
|
| 135 |
"web/symbioza/static/vendor/three/build/three.module.js": "9052042d676cb0fd",
|
| 136 |
"agents/projects.py": "d9a96dcaaea98e6f",
|
| 137 |
"agents/service.py": "df33c1a2540b3680",
|
| 138 |
-
"agents/discovery.py": "
|
| 139 |
-
"agents/discovery_api.py": "
|
|
|
|
| 140 |
},
|
| 141 |
"removed": [
|
| 142 |
"mouh/learning/autopilot.py",
|
|
|
|
| 1 |
{
|
| 2 |
+
"version": "v4.12.1",
|
| 3 |
"files": {
|
| 4 |
"Dockerfile": "b3f4ddb914b0198d",
|
| 5 |
"README.md": "ed433a59c0e4fb6d",
|
|
|
|
| 86 |
"requirements-dev.txt": "9a03d0d2ca94a0d2",
|
| 87 |
"requirements.txt": "8877a189d3a2a02c",
|
| 88 |
"unique_ext/README.md": "0f0be41551e6bacb",
|
| 89 |
+
"unique_ext/__init__.py": "fc746537d5a3f858",
|
| 90 |
"unique_ext/backends/__init__.py": "e3b0c44298fc1c14",
|
| 91 |
"unique_ext/backends/hf.py": "506d29e81c127e1e",
|
| 92 |
"unique_ext/contracts.py": "4ce5632e921dfcdc",
|
|
|
|
| 135 |
"web/symbioza/static/vendor/three/build/three.module.js": "9052042d676cb0fd",
|
| 136 |
"agents/projects.py": "d9a96dcaaea98e6f",
|
| 137 |
"agents/service.py": "df33c1a2540b3680",
|
| 138 |
+
"agents/discovery.py": "659a585656d0c0b0",
|
| 139 |
+
"agents/discovery_api.py": "ea8ba886909ef1ea",
|
| 140 |
+
"agents/discovery_capabilities.py": "e20540fa1d32fdd6"
|
| 141 |
},
|
| 142 |
"removed": [
|
| 143 |
"mouh/learning/autopilot.py",
|
tests/test_discovery.py
CHANGED
|
@@ -16,7 +16,8 @@ from agents.discovery_api import discovery_router
|
|
| 16 |
def row(repo="org/coder", **kw):
|
| 17 |
return {"id": repo, "url": "https://org-coder.hf.space", "domains": ["code"], "kind": "gradio",
|
| 18 |
"stage": "RUNNING", "available": True, "schema_verified": True, "modified": time.time(),
|
| 19 |
-
"likes": 10, "endpoints": ["/predict"], "error": "",
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
class Client:
|
|
@@ -34,7 +35,7 @@ def test_scans_recent_and_popular_without_private_spaces(tmp_path):
|
|
| 34 |
client = Client()
|
| 35 |
worker = DiscoveryWorker(tmp_path, client=client)
|
| 36 |
assert worker.scan_once()
|
| 37 |
-
assert client.calls == ["lastModified", "likes", "org/coder"]
|
| 38 |
assert worker.registry.candidates("code")[0]["schema_verified"]
|
| 39 |
|
| 40 |
|
|
@@ -214,7 +215,6 @@ def test_bootstrap_serves_api_while_scan_is_pending(tmp_path):
|
|
| 214 |
return original(*a)
|
| 215 |
source.list_spaces = blocked
|
| 216 |
worker = DiscoveryWorker(tmp_path, client=source)
|
| 217 |
-
app = FastAPI(lifespan=worker.serving)
|
| 218 |
# FastAPI fournit app au lifespan ; garder un adaptateur de signature explicite.
|
| 219 |
from contextlib import asynccontextmanager
|
| 220 |
@asynccontextmanager
|
|
|
|
| 16 |
def row(repo="org/coder", **kw):
|
| 17 |
return {"id": repo, "url": "https://org-coder.hf.space", "domains": ["code"], "kind": "gradio",
|
| 18 |
"stage": "RUNNING", "available": True, "schema_verified": True, "modified": time.time(),
|
| 19 |
+
"likes": 10, "endpoints": ["/predict"], "error": "", "capability_version": 2,
|
| 20 |
+
"capabilities": [{"endpoint": "/predict", "domains": ["code"], "inputs": [{"name": "prompt", "type": "str"}], "outputs": ["str"]}], **kw}
|
| 21 |
|
| 22 |
|
| 23 |
class Client:
|
|
|
|
| 35 |
client = Client()
|
| 36 |
worker = DiscoveryWorker(tmp_path, client=client)
|
| 37 |
assert worker.scan_once()
|
| 38 |
+
assert sorted(client.calls) == sorted(["lastModified", "likes", "org/coder"])
|
| 39 |
assert worker.registry.candidates("code")[0]["schema_verified"]
|
| 40 |
|
| 41 |
|
|
|
|
| 215 |
return original(*a)
|
| 216 |
source.list_spaces = blocked
|
| 217 |
worker = DiscoveryWorker(tmp_path, client=source)
|
|
|
|
| 218 |
# FastAPI fournit app au lifespan ; garder un adaptateur de signature explicite.
|
| 219 |
from contextlib import asynccontextmanager
|
| 220 |
@asynccontextmanager
|
tests/test_discovery_capabilities.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import time
|
| 3 |
+
from urllib.parse import parse_qs, urlsplit
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from agents.discovery import DiscoveryWorker, HubClient, Registry, Settings
|
| 8 |
+
from agents.discovery_capabilities import eligible, qualify
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def gradio(path='/predict', name='prompt', output=True):
|
| 12 |
+
return {'named_endpoints': {path: {'parameters': [
|
| 13 |
+
{'parameter_name': name, 'python_type': {'type': 'str'}, 'parameter_has_default': False}],
|
| 14 |
+
'returns': [{'python_type': {'type': 'str'}}] if output else []}}}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def openapi(path='/generate', security=None):
|
| 18 |
+
return {'openapi': '3.1.0', 'security': security or [], 'paths': {path: {'post': {
|
| 19 |
+
'requestBody': {'content': {'application/json': {'schema': {'$ref': '#/components/schemas/Input'}}}},
|
| 20 |
+
'responses': {'200': {'content': {'application/json': {'schema': {'type': 'object'}}}}}}}},
|
| 21 |
+
'components': {'schemas': {'Input': {'type': 'object', 'required': ['prompt'],
|
| 22 |
+
'properties': {'prompt': {'type': 'string'}}}}}}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.mark.parametrize('path', ['/check_gpu_status', '/_check_login_status', '/v1/admin/runs', '/api/auth/login', '/leaderboard', '/upload'])
|
| 26 |
+
def test_utility_routes_cannot_be_selected_even_with_code_metadata(path):
|
| 27 |
+
result = qualify(gradio(path), 'gradio', ['code'])
|
| 28 |
+
assert result['capabilities'] == []
|
| 29 |
+
assert 'route_utilitaire_ou_administration' in result['rejection_reasons']
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_code_contract_requires_inputs_and_outputs():
|
| 33 |
+
assert qualify(gradio(), 'gradio', ['code'])['capabilities'][0]['domains'] == ['code']
|
| 34 |
+
assert not qualify(gradio(output=False), 'gradio', ['code'])['capabilities']
|
| 35 |
+
assert not qualify(gradio(name='device_code'), 'gradio', ['code'])['capabilities']
|
| 36 |
+
assert not qualify(gradio(), 'gradio', ['general'])['capabilities']
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_required_unsupported_inputs_are_rejected():
|
| 40 |
+
schema = gradio()
|
| 41 |
+
schema['named_endpoints']['/predict']['parameters'].append(
|
| 42 |
+
{'parameter_name': 'private_api_key', 'python_type': {'type': 'str'}, 'parameter_has_default': False})
|
| 43 |
+
assert not qualify(schema, 'gradio', ['code'])['capabilities']
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_openapi_local_refs_work_and_authentication_excludes_routes():
|
| 47 |
+
assert qualify(openapi(), 'openapi', ['logique'])['capabilities'][0]['inputs'][0]['name'] == 'prompt'
|
| 48 |
+
assert not qualify(openapi(security=[{'BearerAuth': []}]), 'openapi', ['code'])['capabilities']
|
| 49 |
+
assert not qualify(openapi('/v1/admin/runs'), 'openapi', ['code'])['capabilities']
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_openapi_external_and_cyclic_refs_are_not_followed():
|
| 53 |
+
schema = openapi()
|
| 54 |
+
target = schema['paths']['/generate']['post']['requestBody']['content']['application/json']
|
| 55 |
+
target['schema'] = {'$ref': 'https://foreign.example/secret.json'}
|
| 56 |
+
assert not qualify(schema, 'openapi', ['code'])['capabilities']
|
| 57 |
+
target['schema'] = {'$ref': '#/components/schemas/Input'}
|
| 58 |
+
schema['components']['schemas']['Input'] = {'$ref': '#/components/schemas/Input'}
|
| 59 |
+
assert not qualify(schema, 'openapi', ['code'])['capabilities']
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_path_parameters_and_empty_response_contract_are_excluded():
|
| 63 |
+
schema = openapi('/generate/{user}')
|
| 64 |
+
item = schema['paths']['/generate/{user}']
|
| 65 |
+
item['parameters'] = [{'in': 'path', 'name': 'user', 'required': True, 'schema': {'type': 'string'}}]
|
| 66 |
+
assert not qualify(schema, 'openapi', ['code'])['capabilities']
|
| 67 |
+
schema = openapi()
|
| 68 |
+
schema['paths']['/generate']['post']['responses'] = {}
|
| 69 |
+
assert not qualify(schema, 'openapi', ['code'])['capabilities']
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_old_v412_registry_is_readable_but_requires_requalification(tmp_path):
|
| 73 |
+
from test_discovery import row
|
| 74 |
+
registry = Registry(tmp_path)
|
| 75 |
+
registry.initialize()
|
| 76 |
+
saved = row()
|
| 77 |
+
saved.pop('capability_version'); saved.pop('capabilities')
|
| 78 |
+
registry.publish([saved])
|
| 79 |
+
assert registry.candidates('code') == []
|
| 80 |
+
assert registry.candidates('code', ready_only=False)[0]['needs_requalification']
|
| 81 |
+
qualified = row(**qualify(gradio(), 'gradio', ['code']))
|
| 82 |
+
registry.publish([qualified])
|
| 83 |
+
assert registry.candidates('code')[0]['routable']
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_targeted_search_uses_hub_search_with_bounded_results():
|
| 87 |
+
client = HubClient(Settings(limit=24))
|
| 88 |
+
calls = []
|
| 89 |
+
def get(url, *args):
|
| 90 |
+
calls.append(url)
|
| 91 |
+
return [{'id': f'org/code{i}'} for i in range(30)]
|
| 92 |
+
client.get_json = get
|
| 93 |
+
assert len(client.search_spaces('coder', time.monotonic()+1)) == 12
|
| 94 |
+
query = parse_qs(urlsplit(calls[0]).query)
|
| 95 |
+
assert query['search'] == ['coder'] and query['sort'] == ['likes']
|
| 96 |
+
with pytest.raises(ValueError): client.search_spaces('../private', time.monotonic()+1)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_targeted_results_take_priority_and_survive_unrelated_source_failure(tmp_path):
|
| 100 |
+
from test_discovery import row
|
| 101 |
+
class Source:
|
| 102 |
+
def search_spaces(self, term, deadline, sort):
|
| 103 |
+
return [{'id': 'org/coder'}] if term in ('code', 'coder') else [{'id': 'org/reasoning'}]
|
| 104 |
+
def list_spaces(self, sort, deadline):
|
| 105 |
+
raise OSError('generic list unavailable')
|
| 106 |
+
def inspect(self, repo, deadline):
|
| 107 |
+
return row(repo)
|
| 108 |
+
worker = DiscoveryWorker(tmp_path, Settings(limit=4), Source())
|
| 109 |
+
assert worker.scan_once()
|
| 110 |
+
assert {r['id'] for r in worker.registry.candidates('code')} == {'org/coder', 'org/reasoning'}
|
| 111 |
+
assert len(worker.status()['discovery_warnings']) == 2
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_stale_catalogue_does_not_monopolize_new_targeted_scan(tmp_path):
|
| 115 |
+
from test_discovery import row
|
| 116 |
+
class Source:
|
| 117 |
+
def search_spaces(self, term, deadline, sort):
|
| 118 |
+
return [{'id': f'org/new{i}'} for i in range(4)]
|
| 119 |
+
def list_spaces(self, *args): return []
|
| 120 |
+
def inspect(self, repo, deadline): return row(repo)
|
| 121 |
+
worker = DiscoveryWorker(tmp_path, Settings(limit=4), Source())
|
| 122 |
+
worker.registry.initialize()
|
| 123 |
+
worker.registry.publish([row(f'org/old{i}') for i in range(4)])
|
| 124 |
+
assert worker.scan_once()
|
| 125 |
+
ids = {r['id'] for r in worker.registry.candidates('code', limit=50)}
|
| 126 |
+
assert {'org/new0', 'org/new1', 'org/new2'} <= ids
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_capabilities_are_domain_specific():
|
| 130 |
+
row = {'capability_version': 2, **qualify(gradio(), 'gradio', ['image'])}
|
| 131 |
+
assert eligible(row, 'image') and not eligible(row, 'code')
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def test_inspection_qualifies_contract_without_invoking_generation():
|
| 135 |
+
client = HubClient(Settings())
|
| 136 |
+
calls = []
|
| 137 |
+
def get(url, *args):
|
| 138 |
+
calls.append(url)
|
| 139 |
+
if '/api/spaces/' in url:
|
| 140 |
+
return {'id': 'org/code', 'sdk': 'gradio', 'host': 'https://org-code.hf.space',
|
| 141 |
+
'runtime': {'stage': 'RUNNING'}}
|
| 142 |
+
return gradio()
|
| 143 |
+
client.get_json = get
|
| 144 |
+
result = client.inspect('org/code', time.monotonic()+3)
|
| 145 |
+
assert eligible(result, 'code')
|
| 146 |
+
assert result['capabilities'][0]['invocation_tested'] is False
|
| 147 |
+
assert len(calls) == 2 and calls[-1].endswith('/gradio_api/info')
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_status_distinguishes_observations_from_qualified_tools(tmp_path):
|
| 151 |
+
from test_discovery import row
|
| 152 |
+
registry = Registry(tmp_path)
|
| 153 |
+
registry.initialize()
|
| 154 |
+
registry.publish([row('org/tool'), row('org/utility', capabilities=[])])
|
| 155 |
+
status = registry.status()
|
| 156 |
+
assert status['spaces'] == 2 and status['qualified_spaces'] == 1
|
| 157 |
+
assert status['qualified_by_domain']['code'] == 1
|
| 158 |
+
assert status['qualified_by_domain']['logique'] == 0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_openapi_numeric_arrays_are_not_textual_contracts():
|
| 162 |
+
schema = openapi()
|
| 163 |
+
schema['components']['schemas']['Input']['properties']['prompt'] = {'type': 'array', 'items': {'type': 'number'}}
|
| 164 |
+
assert not qualify(schema, 'openapi', ['code'])['capabilities']
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_empty_api_selection_explains_contract_filtering(tmp_path):
|
| 168 |
+
from fastapi import FastAPI
|
| 169 |
+
from fastapi.testclient import TestClient
|
| 170 |
+
from agents.discovery_api import discovery_router
|
| 171 |
+
worker = DiscoveryWorker(tmp_path, Settings(enabled=False))
|
| 172 |
+
worker.registry.initialize()
|
| 173 |
+
app = FastAPI()
|
| 174 |
+
app.include_router(discovery_router(worker, lambda key: False))
|
| 175 |
+
with TestClient(app) as client:
|
| 176 |
+
result = client.get('/api/discovery/spaces?domain=code').json()
|
| 177 |
+
assert result['spaces'] == []
|
| 178 |
+
assert result['empty_reason'] == 'aucun_contrat_qualifie_pour_ces_filtres'
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_qr_codes_and_codeformer_are_not_programming_domains():
|
| 182 |
+
from agents.discovery_capabilities import labels
|
| 183 |
+
assert 'code' not in labels('QR-code image generator')
|
| 184 |
+
assert 'code' not in labels('sczhou/CodeFormer image restoration')
|
| 185 |
+
assert 'code' in labels('vmohan-sn/PythonCodeExec')
|
unique_ext/__init__.py
CHANGED
|
@@ -13,7 +13,7 @@ from __future__ import annotations
|
|
| 13 |
import os
|
| 14 |
|
| 15 |
API_VERSION = 1 # contrat entre le job d'entraînement et ce paquet : le job refuse une autre valeur
|
| 16 |
-
__version__ = "4.12.
|
| 17 |
|
| 18 |
|
| 19 |
def enabled(name: str) -> bool:
|
|
|
|
| 13 |
import os
|
| 14 |
|
| 15 |
API_VERSION = 1 # contrat entre le job d'entraînement et ce paquet : le job refuse une autre valeur
|
| 16 |
+
__version__ = "4.12.1"
|
| 17 |
|
| 18 |
|
| 19 |
def enabled(name: str) -> bool:
|