Datasets:
Download code/robohome/src/engine/source/packages/asset_registry/certification.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/asset_registry/certification.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/engine/source/packages/asset_registry/certification.py
-
curl -L -o certification.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/asset_registry/certification.py
15.1 kB
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| from collections import Counter, defaultdict | |
| from collections.abc import Iterable | |
| from pathlib import Path | |
| from typing import Any | |
| from packages.asset_registry.certification_models import ( | |
| AssetCertification, | |
| CertificationCheck, | |
| CertificationProfile, | |
| FidelityScores, | |
| FrontConfidenceGrade, | |
| QualityTier, | |
| ) | |
| from packages.asset_registry.descriptors import AssetDescriptor | |
| from packages.asset_registry.front_certification import ( | |
| definition_for_category, | |
| load_descriptor_index, | |
| ) | |
| from packages.asset_registry.ingestion import SourceRegistry | |
| from packages.core.files import atomic_write_text | |
| def _clamp(value: float) -> float: | |
| return round(max(0.0, min(100.0, value)), 3) | |
| def _dependency_fraction(descriptor: AssetDescriptor) -> float: | |
| total = len(descriptor.texture_dependencies) + len(descriptor.missing_dependencies) | |
| if total == 0: | |
| return 1.0 if descriptor.material_count == 0 else 0.5 | |
| return len(descriptor.texture_dependencies) / total | |
| def score_fidelity(descriptor: AssetDescriptor) -> FidelityScores: | |
| pbr = descriptor.pbr_channels | |
| pbr_fraction = sum( | |
| (pbr.base_color, pbr.normal, pbr.roughness, pbr.metallic, pbr.occlusion) | |
| ) / 5.0 | |
| dependency_fraction = _dependency_fraction(descriptor) | |
| measured_scale = ( | |
| descriptor.height_m > 0 | |
| and all(value > 0 for value in descriptor.native_bbox_m) | |
| and descriptor.obb_m is not None | |
| ) | |
| scale_confidence = float( | |
| descriptor.confidence.get( | |
| "dimensions", descriptor.confidence.get("scale", 0.75 if measured_scale else 0.0) | |
| ) | |
| ) | |
| collision = { | |
| "explicit": 92.0, | |
| "visual_conservative": 68.0, | |
| "none": 10.0, | |
| }[descriptor.collision_source] | |
| physics = 15.0 | |
| if descriptor.collision_source != "none" and measured_scale: | |
| physics = 68.0 | |
| if any(token in descriptor.affordances for token in ("mass", "inertia", "friction")): | |
| physics += 18.0 | |
| if "stable" in descriptor.affordances or "static_physics" in descriptor.affordances: | |
| physics += 10.0 | |
| articulation = 50.0 if not descriptor.articulated else 20.0 | |
| if descriptor.articulated: | |
| articulation += min(40.0, 8.0 * len(descriptor.movable_parts)) | |
| articulation += min(25.0, 8.0 * len(descriptor.operational_clearance)) | |
| if any("joint" in item for item in descriptor.affordances): | |
| articulation += 15.0 | |
| semantic = 25.0 if descriptor.category.casefold() in {"", "unknown"} else 72.0 | |
| semantic += 15.0 * float(descriptor.confidence.get("semantic", 0.5)) | |
| semantic += min(13.0, 2.0 * len(descriptor.semantic_tags)) | |
| front_confidence = descriptor.front_confidence or float( | |
| descriptor.confidence.get("front_axis", 0.0) | |
| ) | |
| grade_bonus = { | |
| FrontConfidenceGrade.VERIFIED: 10.0, | |
| FrontConfidenceGrade.HIGH: 5.0, | |
| FrontConfidenceGrade.MEDIUM: 0.0, | |
| FrontConfidenceGrade.LOW: -10.0, | |
| FrontConfidenceGrade.UNKNOWN: -25.0, | |
| FrontConfidenceGrade.AMBIGUOUS: -30.0, | |
| }[descriptor.front_confidence_grade] | |
| front = 100.0 * front_confidence + grade_bonus | |
| definition = definition_for_category(descriptor.category) | |
| if definition.functional_semantics == "none" and descriptor.functional_front_axis == "NONE": | |
| front = max(front, 90.0) | |
| task = 25.0 + min(35.0, 7.0 * len(descriptor.affordances)) | |
| task += min(20.0, 10.0 * len(descriptor.operational_clearance)) | |
| if descriptor.support_type in {"floor", "surface"}: | |
| task += 10.0 | |
| if descriptor.collision_source != "none": | |
| task += 10.0 | |
| return FidelityScores( | |
| geometry_fidelity=_clamp(float(descriptor.quality.geometry)), | |
| material_fidelity=_clamp(0.65 * descriptor.quality.materials + 35.0 * pbr_fraction), | |
| texture_fidelity=_clamp(100.0 * dependency_fraction * (0.55 + 0.45 * pbr_fraction)), | |
| scale_fidelity=_clamp(100.0 * scale_confidence), | |
| render_fidelity=_clamp( | |
| 0.75 * descriptor.quality.realism | |
| + 25.0 * min(1.0, len(descriptor.multiview_images) / 4.0) | |
| ), | |
| collision_fidelity=_clamp(collision), | |
| physics_fidelity=_clamp(physics), | |
| articulation_fidelity=_clamp(articulation), | |
| semantic_fidelity=_clamp(semantic), | |
| front_fidelity=_clamp(front), | |
| task_fidelity=_clamp(task), | |
| ) | |
| def derive_quality_tier( | |
| descriptor: AssetDescriptor, fidelity: FidelityScores | |
| ) -> QualityTier: | |
| if descriptor.status == "QUARANTINED": | |
| return QualityTier.QUARANTINED | |
| visual = min( | |
| fidelity.geometry_fidelity, | |
| fidelity.material_fidelity, | |
| fidelity.texture_fidelity, | |
| fidelity.render_fidelity, | |
| ) | |
| simulation = min( | |
| fidelity.scale_fidelity, | |
| fidelity.collision_fidelity, | |
| fidelity.physics_fidelity, | |
| fidelity.semantic_fidelity, | |
| ) | |
| definition = definition_for_category(descriptor.category) | |
| front_required = definition.functional_semantics not in {"none", "unknown"} | |
| front_ok = not front_required or fidelity.front_fidelity >= 80.0 | |
| articulation_ok = not descriptor.articulated or fidelity.articulation_fidelity >= 80.0 | |
| if visual >= 80.0 and simulation >= 82.0 and front_ok and articulation_ok: | |
| return QualityTier.HQ_A | |
| if visual >= 65.0 and simulation >= 68.0: | |
| return QualityTier.HQ_B | |
| if simulation >= 72.0 and fidelity.task_fidelity >= 65.0: | |
| return QualityTier.SIM_A | |
| if visual >= 65.0: | |
| return QualityTier.VISUAL_ONLY | |
| return QualityTier.PROXY | |
| def derive_capability_profiles( | |
| descriptor: AssetDescriptor, fidelity: FidelityScores | |
| ) -> set[CertificationProfile]: | |
| output: set[CertificationProfile] = set() | |
| affordances = {item.casefold() for item in descriptor.affordances} | |
| parts = json.dumps(descriptor.movable_parts, ensure_ascii=False).casefold() | |
| if min( | |
| fidelity.scale_fidelity, | |
| fidelity.collision_fidelity, | |
| fidelity.physics_fidelity, | |
| ) >= 70.0: | |
| output.add(CertificationProfile.STATIC_PHYSICS_V1) | |
| if ( | |
| affordances & {"grasp", "grasp_frame", "grasp_frames", "graspable"} | |
| and min(fidelity.collision_fidelity, fidelity.task_fidelity) >= 65.0 | |
| ): | |
| output.add(CertificationProfile.GRASP_V1) | |
| if descriptor.articulated and ("revolute" in parts or "hinge" in parts): | |
| if min(fidelity.articulation_fidelity, fidelity.front_fidelity) >= 65.0: | |
| output.add(CertificationProfile.HINGE_DOOR_V1) | |
| if descriptor.articulated and ("prismatic" in parts or "drawer" in parts): | |
| if fidelity.articulation_fidelity >= 65.0: | |
| output.add(CertificationProfile.DRAWER_V1) | |
| if affordances & {"bimanual", "two_hand_grasp", "paired_grasp_frames"}: | |
| if fidelity.task_fidelity >= 70.0: | |
| output.add(CertificationProfile.BIMANUAL_V1) | |
| if affordances & {"low_pick", "floor_grasp", "low_reach"}: | |
| if fidelity.task_fidelity >= 65.0: | |
| output.add(CertificationProfile.LOW_PICK_V1) | |
| if descriptor.articulated and affordances & {"pedal", "foot_pedal"}: | |
| if fidelity.articulation_fidelity >= 70.0: | |
| output.add(CertificationProfile.FOOT_PEDAL_V1) | |
| return output | |
| def certify_quality( | |
| descriptor: AssetDescriptor, | |
| *, | |
| source_version: str | None = None, | |
| ) -> AssetCertification: | |
| selected_source_version = source_version or descriptor.source_version | |
| fidelity = score_fidelity(descriptor) | |
| tier = derive_quality_tier(descriptor, fidelity) | |
| profiles = derive_capability_profiles(descriptor, fidelity) | |
| checks = [ | |
| CertificationCheck( | |
| check_id="identity.sha256", | |
| passed=len(descriptor.sha256) == 64, | |
| method="descriptor_validation", | |
| ), | |
| CertificationCheck( | |
| check_id="license.declared", | |
| passed=bool(descriptor.source_license.strip()), | |
| method="source_manifest", | |
| ), | |
| CertificationCheck( | |
| check_id="source.version_declared", | |
| passed=selected_source_version.casefold() not in {"", "unknown", "latest"}, | |
| method="source_manifest", | |
| details=selected_source_version, | |
| ), | |
| CertificationCheck( | |
| check_id="geometry.loadable", | |
| passed=descriptor.status == "ACTIVE" and descriptor.triangle_count > 0, | |
| method="asset_release_v2", | |
| details=descriptor.status_reason, | |
| ), | |
| CertificationCheck( | |
| check_id="dependencies.resolved", | |
| passed=not descriptor.missing_dependencies, | |
| method="dependency_scan", | |
| details="|".join(descriptor.missing_dependencies), | |
| ), | |
| ] | |
| blocking = [] | |
| if descriptor.status == "QUARANTINED": | |
| blocking.append(descriptor.status_reason) | |
| blocking.extend(check.check_id for check in checks if not check.passed) | |
| production = tier in {QualityTier.HQ_A, QualityTier.HQ_B, QualityTier.SIM_A} and not blocking | |
| return AssetCertification( | |
| asset_id=descriptor.asset_id, | |
| asset_sha256=descriptor.sha256, | |
| source=descriptor.source, | |
| source_version=selected_source_version, | |
| source_license=descriptor.source_license, | |
| quality_tier=tier, | |
| fidelity=fidelity, | |
| capability_profiles=profiles, | |
| checks=checks, | |
| certifier="robothousegen-automated-policy", | |
| policy_version="asset-certification-v1-heuristic", | |
| production_eligible=production, | |
| blocking_reasons=blocking, | |
| ) | |
| def role_coverage_report( | |
| descriptors: Iterable[AssetDescriptor], | |
| certifications: dict[str, AssetCertification], | |
| ) -> dict[str, Any]: | |
| roles: dict[str, dict[str, Counter[str]]] = defaultdict( | |
| lambda: {"quality_tiers": Counter(), "capability_profiles": Counter(), "sources": Counter()} | |
| ) | |
| for descriptor in descriptors: | |
| certification = certifications[descriptor.asset_id] | |
| if not certification.production_eligible: | |
| continue | |
| role = descriptor.category.casefold().strip() or "unknown" | |
| roles[role]["quality_tiers"][certification.quality_tier.value] += 1 | |
| roles[role]["sources"][descriptor.source] += 1 | |
| for profile in certification.capability_profiles: | |
| roles[role]["capability_profiles"][profile.value] += 1 | |
| return { | |
| "schema_version": "1.0", | |
| "truth_policy": "counts include production_eligible certifications only", | |
| "roles": { | |
| role: {name: dict(sorted(counter.items())) for name, counter in values.items()} | |
| for role, values in sorted(roles.items()) | |
| }, | |
| } | |
| def _sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def batch_certify_quality( | |
| *, | |
| source_index: Path, | |
| output_dir: Path, | |
| source_version: str | None = None, | |
| source_versions: dict[str, str] | None = None, | |
| active_only: bool = False, | |
| limit: int | None = None, | |
| ) -> dict[str, Any]: | |
| if output_dir.exists(): | |
| raise FileExistsError(f"refusing to overwrite quality certification output: {output_dir}") | |
| descriptors = load_descriptor_index(source_index, active_only=active_only) | |
| if limit is not None: | |
| descriptors = descriptors[:limit] | |
| normalized_versions = { | |
| key.casefold(): value for key, value in (source_versions or {}).items() | |
| } | |
| certifications = { | |
| item.asset_id: certify_quality( | |
| item, | |
| source_version=( | |
| source_version | |
| or normalized_versions.get(item.source.casefold()) | |
| or item.source_version | |
| ), | |
| ) | |
| for item in descriptors | |
| } | |
| output_dir.mkdir(parents=True, exist_ok=False) | |
| certification_jsonl = output_dir / "asset_certifications.jsonl" | |
| descriptor_jsonl = output_dir / "asset_descriptors.certified.jsonl" | |
| coverage_path = output_dir / "asset_role_coverage.json" | |
| atomic_write_text( | |
| certification_jsonl, | |
| "".join(certifications[key].model_dump_json() + "\n" for key in sorted(certifications)), | |
| ) | |
| atomic_write_text( | |
| descriptor_jsonl, | |
| "".join( | |
| AssetDescriptor.model_validate( | |
| { | |
| **descriptor.model_dump(mode="python"), | |
| "schema_version": "2.1", | |
| "source_version": certifications[descriptor.asset_id].source_version, | |
| "certification": certifications[descriptor.asset_id], | |
| } | |
| ).model_dump_json() | |
| + "\n" | |
| for descriptor in descriptors | |
| ), | |
| ) | |
| coverage = role_coverage_report(descriptors, certifications) | |
| atomic_write_text( | |
| coverage_path, json.dumps(coverage, ensure_ascii=False, indent=2, sort_keys=True) + "\n" | |
| ) | |
| report: dict[str, Any] = { | |
| "schema_version": "1.0", | |
| "source_index": str(source_index.resolve()), | |
| "source_index_sha256": _sha256(source_index), | |
| "source_index_preserved": True, | |
| "processed": len(descriptors), | |
| "quality_tiers": dict( | |
| sorted(Counter(item.quality_tier.value for item in certifications.values()).items()) | |
| ), | |
| "capability_profiles": dict( | |
| sorted( | |
| Counter( | |
| profile.value | |
| for item in certifications.values() | |
| for profile in item.capability_profiles | |
| ).items() | |
| ) | |
| ), | |
| "production_eligible": sum(item.production_eligible for item in certifications.values()), | |
| "unknown_source_versions": dict( | |
| sorted( | |
| Counter( | |
| descriptor.source | |
| for descriptor in descriptors | |
| if certifications[descriptor.asset_id].source_version.casefold() | |
| in {"", "unknown", "latest"} | |
| ).items() | |
| ) | |
| ), | |
| "files": {}, | |
| } | |
| for path in (certification_jsonl, descriptor_jsonl, coverage_path): | |
| report["files"][path.name] = {"path": str(path), "sha256": _sha256(path)} | |
| atomic_write_text( | |
| output_dir / "quality_certification_report.json", | |
| json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", | |
| ) | |
| return report | |
| def source_versions_from_registry(path: Path) -> dict[str, str]: | |
| registry = SourceRegistry.from_yaml(path) | |
| output: dict[str, str] = {} | |
| for source in registry.sources: | |
| aliases = {source.source_id, source.display_name, *source.descriptor_source_aliases} | |
| for alias in aliases: | |
| key = alias.casefold() | |
| previous = output.get(key) | |
| if previous is not None and previous != source.version: | |
| raise ValueError(f"source alias has conflicting versions: {alias}") | |
| output[key] = source.version | |
| return output | |