Spaces:
Running
Running
Deploy eval-entity-registry service
Browse files
src/eval_entity_registry/cli.py
CHANGED
|
@@ -3,6 +3,7 @@ import json
|
|
| 3 |
import math
|
| 4 |
import re
|
| 5 |
import unicodedata
|
|
|
|
| 6 |
from numbers import Real
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Optional
|
|
@@ -17,6 +18,15 @@ import yaml
|
|
| 17 |
# instead of scoping an alias to a config that never calls.
|
| 18 |
_SOURCE_SCOPE_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def seed_collision_key(s: str) -> str:
|
| 22 |
"""Key under which two seed surface forms count as one entity: NFKD +
|
|
@@ -45,7 +55,7 @@ def _legacy_parent_model_id_to_parents(entry: dict) -> None:
|
|
| 45 |
if legacy:
|
| 46 |
entry["parents"] = [{"id": legacy, "relationship": "variant", "axis": "size"}]
|
| 47 |
|
| 48 |
-
from eval_entity_registry.store.hf_store import get_store
|
| 49 |
from eval_entity_registry.store import queries, schemas
|
| 50 |
from eval_entity_registry.lib import collision_fold, org_attribution
|
| 51 |
from eval_entity_registry.lib.seed_io import WEAK_SCALAR_FIELDS, build_hf_to_dev_from_orgs_yaml
|
|
@@ -94,16 +104,20 @@ def _load_store():
|
|
| 94 |
def seed(
|
| 95 |
local: bool = typer.Option(False, "--local", help="Write to fixtures/ instead of HF Hub"),
|
| 96 |
seed_dir: str = typer.Option("./seed", "--seed-dir"),
|
| 97 |
-
prune_stale: bool = typer.Option(
|
| 98 |
-
|
| 99 |
"--prune-stale/--no-prune-stale",
|
| 100 |
-
help="Remove
|
|
|
|
|
|
|
| 101 |
),
|
| 102 |
):
|
| 103 |
"""Load known canonical entities from seed YAML files."""
|
| 104 |
import os
|
| 105 |
if local:
|
| 106 |
os.environ["LOCAL_MODE"] = "true"
|
|
|
|
|
|
|
| 107 |
|
| 108 |
store = _load_store()
|
| 109 |
seed_path = Path(seed_dir)
|
|
@@ -740,6 +754,10 @@ def seed(
|
|
| 740 |
# O(N²) concat-per-row.
|
| 741 |
queries._rebuild_alias_index(store)
|
| 742 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 743 |
for table, yaml_file, label, entity_type in seed_specs:
|
| 744 |
table_columns = set(schemas.empty(table).columns)
|
| 745 |
if yaml_file == "__merged_models__":
|
|
@@ -864,6 +882,15 @@ def seed(
|
|
| 864 |
if len(cids) == 1
|
| 865 |
}
|
| 866 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 867 |
for original_item in items:
|
| 868 |
item = dict(original_item)
|
| 869 |
extra_aliases = item.pop("aliases", []) or []
|
|
@@ -916,7 +943,7 @@ def seed(
|
|
| 916 |
global_aliases.discard(display_name)
|
| 917 |
|
| 918 |
alias_specs: list[tuple[str, Optional[str]]] = [
|
| 919 |
-
(raw, None) for raw in global_aliases if
|
| 920 |
]
|
| 921 |
for source_cfg, raw_values in scoped_aliases.items():
|
| 922 |
if not isinstance(source_cfg, str) or not _SOURCE_SCOPE_KEY_RE.match(source_cfg):
|
|
@@ -957,8 +984,12 @@ def seed(
|
|
| 957 |
(raw_value, entity_type, _claim_key[2],
|
| 958 |
_prev[0], target_cid, _prev[1], canonical_id)
|
| 959 |
)
|
|
|
|
|
|
|
|
|
|
| 960 |
try:
|
| 961 |
queries.add_alias(store, {
|
|
|
|
| 962 |
"raw_value": raw_value,
|
| 963 |
"entity_type": entity_type,
|
| 964 |
"canonical_id": target_cid,
|
|
@@ -969,6 +1000,7 @@ def seed(
|
|
| 969 |
"confidence": 1.0,
|
| 970 |
"notes": None,
|
| 971 |
}, buffered=True)
|
|
|
|
| 972 |
alias_count += 1
|
| 973 |
except ValueError:
|
| 974 |
# An existing row pointing at a different canonical is a YAML
|
|
@@ -1236,10 +1268,15 @@ def seed(
|
|
| 1236 |
|
| 1237 |
removed_entities = 0
|
| 1238 |
removed_aliases = 0
|
|
|
|
| 1239 |
if prune_stale:
|
| 1240 |
-
#
|
| 1241 |
-
#
|
| 1242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1243 |
aliases_df = store.table("aliases")
|
| 1244 |
seed_mask = (aliases_df["strategy"] == "seed") & (aliases_df["entity_type"] == entity_type)
|
| 1245 |
if seed_mask.any():
|
|
@@ -1261,7 +1298,16 @@ def seed(
|
|
| 1261 |
entity_df = store.table(table)
|
| 1262 |
if len(entity_df) > 0:
|
| 1263 |
stale = entity_df["id"].isin(yaml_ids)
|
| 1264 |
-
stale_entities = entity_df[~stale
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1265 |
# FK guard: an org auto-created from a model's id prefix is not
|
| 1266 |
# in the orgs YAML, and pruning it would dangle the model's
|
| 1267 |
# org_id; parent_org_id references are kept for the same reason.
|
|
@@ -1305,6 +1351,8 @@ def seed(
|
|
| 1305 |
)
|
| 1306 |
if removed_entities:
|
| 1307 |
typer.echo(f" stale entities removed: {removed_entities}")
|
|
|
|
|
|
|
| 1308 |
|
| 1309 |
store.push_to_hub()
|
| 1310 |
typer.echo("Seed complete.")
|
|
|
|
| 3 |
import math
|
| 4 |
import re
|
| 5 |
import unicodedata
|
| 6 |
+
import uuid
|
| 7 |
from numbers import Real
|
| 8 |
from pathlib import Path
|
| 9 |
from typing import Optional
|
|
|
|
| 18 |
# instead of scoping an alias to a config that never calls.
|
| 19 |
_SOURCE_SCOPE_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
|
| 20 |
|
| 21 |
+
# eval_results columns that hold a canonical id of each entity type; a stale
|
| 22 |
+
# entity they still point at is kept by --prune-stale.
|
| 23 |
+
_EVAL_RESULTS_FK = {
|
| 24 |
+
"model": ("model_id",),
|
| 25 |
+
"benchmark": ("benchmark_id", "parent_benchmark_id"),
|
| 26 |
+
"metric": ("metric_id",),
|
| 27 |
+
"harness": ("harness_id",),
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
|
| 31 |
def seed_collision_key(s: str) -> str:
|
| 32 |
"""Key under which two seed surface forms count as one entity: NFKD +
|
|
|
|
| 55 |
if legacy:
|
| 56 |
entry["parents"] = [{"id": legacy, "relationship": "variant", "axis": "size"}]
|
| 57 |
|
| 58 |
+
from eval_entity_registry.store.hf_store import _local_mode, get_store
|
| 59 |
from eval_entity_registry.store import queries, schemas
|
| 60 |
from eval_entity_registry.lib import collision_fold, org_attribution
|
| 61 |
from eval_entity_registry.lib.seed_io import WEAK_SCALAR_FIELDS, build_hf_to_dev_from_orgs_yaml
|
|
|
|
| 104 |
def seed(
|
| 105 |
local: bool = typer.Option(False, "--local", help="Write to fixtures/ instead of HF Hub"),
|
| 106 |
seed_dir: str = typer.Option("./seed", "--seed-dir"),
|
| 107 |
+
prune_stale: Optional[bool] = typer.Option(
|
| 108 |
+
None,
|
| 109 |
"--prune-stale/--no-prune-stale",
|
| 110 |
+
help="Remove entities and seed aliases absent from the current YAML snapshot "
|
| 111 |
+
"unless a non-seed alias or an eval_results row still references them. "
|
| 112 |
+
"Default on in local mode, off otherwise.",
|
| 113 |
),
|
| 114 |
):
|
| 115 |
"""Load known canonical entities from seed YAML files."""
|
| 116 |
import os
|
| 117 |
if local:
|
| 118 |
os.environ["LOCAL_MODE"] = "true"
|
| 119 |
+
if prune_stale is None:
|
| 120 |
+
prune_stale = _local_mode()
|
| 121 |
|
| 122 |
store = _load_store()
|
| 123 |
seed_path = Path(seed_dir)
|
|
|
|
| 754 |
# O(N²) concat-per-row.
|
| 755 |
queries._rebuild_alias_index(store)
|
| 756 |
|
| 757 |
+
# Derived alias ids must not collide with persisted rows (a rejected row
|
| 758 |
+
# may hold the same key) nor repeat within the run.
|
| 759 |
+
taken_alias_ids: set[str] = set(store.table("aliases")["id"].dropna().astype(str))
|
| 760 |
+
|
| 761 |
for table, yaml_file, label, entity_type in seed_specs:
|
| 762 |
table_columns = set(schemas.empty(table).columns)
|
| 763 |
if yaml_file == "__merged_models__":
|
|
|
|
| 882 |
if len(cids) == 1
|
| 883 |
}
|
| 884 |
|
| 885 |
+
# A seed row is a function of its YAML entry alone: rows for YAML ids are
|
| 886 |
+
# dropped and re-inserted whole, so a field removed from YAML cannot linger.
|
| 887 |
+
yaml_item_ids = {it["id"] for it in items if isinstance(it, dict) and it.get("id")}
|
| 888 |
+
existing_df = store.table(table)
|
| 889 |
+
if len(existing_df) > 0:
|
| 890 |
+
reseeded = existing_df["id"].isin(yaml_item_ids)
|
| 891 |
+
if reseeded.any():
|
| 892 |
+
store.set_table(table, existing_df[~reseeded].reset_index(drop=True))
|
| 893 |
+
|
| 894 |
for original_item in items:
|
| 895 |
item = dict(original_item)
|
| 896 |
extra_aliases = item.pop("aliases", []) or []
|
|
|
|
| 943 |
global_aliases.discard(display_name)
|
| 944 |
|
| 945 |
alias_specs: list[tuple[str, Optional[str]]] = [
|
| 946 |
+
(raw, None) for raw in sorted(a for a in global_aliases if isinstance(a, str) and a)
|
| 947 |
]
|
| 948 |
for source_cfg, raw_values in scoped_aliases.items():
|
| 949 |
if not isinstance(source_cfg, str) or not _SOURCE_SCOPE_KEY_RE.match(source_cfg):
|
|
|
|
| 984 |
(raw_value, entity_type, _claim_key[2],
|
| 985 |
_prev[0], target_cid, _prev[1], canonical_id)
|
| 986 |
)
|
| 987 |
+
alias_id = queries.seed_alias_id(entity_type, raw_value, source_cfg)
|
| 988 |
+
if alias_id in taken_alias_ids:
|
| 989 |
+
alias_id = str(uuid.uuid4())
|
| 990 |
try:
|
| 991 |
queries.add_alias(store, {
|
| 992 |
+
"id": alias_id,
|
| 993 |
"raw_value": raw_value,
|
| 994 |
"entity_type": entity_type,
|
| 995 |
"canonical_id": target_cid,
|
|
|
|
| 1000 |
"confidence": 1.0,
|
| 1001 |
"notes": None,
|
| 1002 |
}, buffered=True)
|
| 1003 |
+
taken_alias_ids.add(alias_id)
|
| 1004 |
alias_count += 1
|
| 1005 |
except ValueError:
|
| 1006 |
# An existing row pointing at a different canonical is a YAML
|
|
|
|
| 1268 |
|
| 1269 |
removed_entities = 0
|
| 1270 |
removed_aliases = 0
|
| 1271 |
+
kept_for_results = 0
|
| 1272 |
if prune_stale:
|
| 1273 |
+
# An entity absent from YAML survives only while another writer still
|
| 1274 |
+
# claims it: a non-seed alias, an eval_results row, or (orgs) an FK
|
| 1275 |
+
# from a surviving row. Orgs go last so the FK guard sees pruned models.
|
| 1276 |
+
results_df = store.table("eval_results")
|
| 1277 |
+
for table, entity_type, yaml_ids, yaml_alias_keys in sorted(
|
| 1278 |
+
seed_snapshot, key=lambda t: t[0] == "canonical_orgs"
|
| 1279 |
+
):
|
| 1280 |
aliases_df = store.table("aliases")
|
| 1281 |
seed_mask = (aliases_df["strategy"] == "seed") & (aliases_df["entity_type"] == entity_type)
|
| 1282 |
if seed_mask.any():
|
|
|
|
| 1298 |
entity_df = store.table(table)
|
| 1299 |
if len(entity_df) > 0:
|
| 1300 |
stale = entity_df["id"].isin(yaml_ids)
|
| 1301 |
+
stale_entities = entity_df[~stale]
|
| 1302 |
+
referenced_by_results: set[str] = set()
|
| 1303 |
+
if results_df is not None and len(results_df) > 0:
|
| 1304 |
+
for col in _EVAL_RESULTS_FK.get(entity_type, ()):
|
| 1305 |
+
if col in results_df.columns:
|
| 1306 |
+
referenced_by_results |= set(results_df[col].dropna().astype(str))
|
| 1307 |
+
if referenced_by_results:
|
| 1308 |
+
in_results = stale_entities["id"].astype(str).isin(referenced_by_results)
|
| 1309 |
+
kept_for_results += int(in_results.sum())
|
| 1310 |
+
stale_entities = stale_entities[~in_results]
|
| 1311 |
# FK guard: an org auto-created from a model's id prefix is not
|
| 1312 |
# in the orgs YAML, and pruning it would dangle the model's
|
| 1313 |
# org_id; parent_org_id references are kept for the same reason.
|
|
|
|
| 1351 |
)
|
| 1352 |
if removed_entities:
|
| 1353 |
typer.echo(f" stale entities removed: {removed_entities}")
|
| 1354 |
+
if kept_for_results:
|
| 1355 |
+
typer.echo(f" stale entities kept (referenced by eval_results): {kept_for_results}")
|
| 1356 |
|
| 1357 |
store.push_to_hub()
|
| 1358 |
typer.echo("Seed complete.")
|
src/eval_entity_registry/store/queries.py
CHANGED
|
@@ -544,10 +544,17 @@ def get_alias(
|
|
| 544 |
return None
|
| 545 |
|
| 546 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 547 |
def add_alias(store: RegistryStore, data: dict, buffered: bool = False) -> dict:
|
| 548 |
"""Insert an alias row. Raises ValueError when a non-rejected alias already
|
| 549 |
exists for (entity_type, raw_value, source_config). buffered=True defers
|
| 550 |
-
the write to flush_pending."""
|
| 551 |
raw_value = data["raw_value"]
|
| 552 |
entity_type = data["entity_type"]
|
| 553 |
source_config = _source_config_key(data.get("source_config"))
|
|
@@ -588,7 +595,7 @@ def add_alias(store: RegistryStore, data: dict, buffered: bool = False) -> dict:
|
|
| 588 |
row = {
|
| 589 |
**data,
|
| 590 |
"source_config": source_config,
|
| 591 |
-
"id": str(uuid.uuid4()),
|
| 592 |
"created_at": now,
|
| 593 |
"updated_at": now,
|
| 594 |
}
|
|
|
|
| 544 |
return None
|
| 545 |
|
| 546 |
|
| 547 |
+
def seed_alias_id(entity_type: str, raw_value: str, source_config) -> str:
|
| 548 |
+
"""Content-derived alias id over the uniqueness key, so a from-scratch seed
|
| 549 |
+
is reproducible; the caller must fall back to a random id when it is taken."""
|
| 550 |
+
key = f"{entity_type}\0{raw_value}\0{_source_config_key(source_config) or ''}"
|
| 551 |
+
return hashlib.sha256(key.encode("utf-8")).hexdigest()[:32]
|
| 552 |
+
|
| 553 |
+
|
| 554 |
def add_alias(store: RegistryStore, data: dict, buffered: bool = False) -> dict:
|
| 555 |
"""Insert an alias row. Raises ValueError when a non-rejected alias already
|
| 556 |
exists for (entity_type, raw_value, source_config). buffered=True defers
|
| 557 |
+
the write to flush_pending. A caller-supplied `id` is used as-is."""
|
| 558 |
raw_value = data["raw_value"]
|
| 559 |
entity_type = data["entity_type"]
|
| 560 |
source_config = _source_config_key(data.get("source_config"))
|
|
|
|
| 595 |
row = {
|
| 596 |
**data,
|
| 597 |
"source_config": source_config,
|
| 598 |
+
"id": data.get("id") or str(uuid.uuid4()),
|
| 599 |
"created_at": now,
|
| 600 |
"updated_at": now,
|
| 601 |
}
|