Datasets:
Download code/robohome/src/engine/measurement_refresh.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 20.6 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/measurement_refresh.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/engine/measurement_refresh.py
-
curl -L -o measurement_refresh.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/measurement_refresh.py
20.6 kB
| """Authenticate opt-in measurements of an unchanged, saved generated scene. | |
| refresh_measurements(config, generated_manifest_path, output_dir, *, source_root, | |
| timeout_s) returns a retained result.json receipt. A runner | |
| is an argv list in config.measurement_refresh.command; the literal tokens | |
| {manifest}, {scene}, {output}, {source_root}, {requirements} are substituted | |
| without a shell. The latter names the retained original task/priors JSON. | |
| Its JSON output must use rhg.measured-refresh.v1 and bind exact manifest and | |
| saved-scene bytes with manifest_sha256 and scene_sha256. Evidence can contain | |
| sparse task/priors patches or repeat unchanged requirement fields. | |
| Only measured_supports surface region/height/source pins and approach width/pins, | |
| and priors surface/footprint bounds/source pins can change. Placement anchors, | |
| candidate IDs, dimensions, limits, reservations and motifs remain requirements. | |
| source_sha256 pins the entity asset_sha256 when available, otherwise the scene; | |
| the envelope ALWAYS pins the scene. Old measurement fields are removed before | |
| merging, so partial evidence cannot inherit a previous pose's measurements. | |
| passed certifies fresh, complete measurement evidence, including evidence of | |
| infeasible geometry. It never certifies task feasibility or native physics. | |
| Absent runners and incomplete measurements return pending with passed=False. | |
| """ | |
| from __future__ import annotations | |
| import copy | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| import time | |
| if __package__: | |
| from . import process_control | |
| from .spatial_priors import evaluate_priors | |
| from .task_precheck import evaluate_task | |
| else: | |
| import process_control | |
| from spatial_priors import evaluate_priors | |
| from task_precheck import evaluate_task | |
| __all__ = ['refresh_measurements'] | |
| _SURFACE = {'region', 'height_m', 'source_sha256', 'source_scene_sha256'} | |
| _APPROACH = {'approach_clearance_width_m', 'approach_source_sha256', | |
| 'approach_scene_sha256', 'source_sha256', 'source_scene_sha256'} | |
| _BOUNDS = {'bounds_xy_m', 'source_sha256', 'source_scene_sha256'} | |
| def file_sha256(path): | |
| digest = hashlib.sha256() | |
| with Path(path).open('rb') as stream: | |
| for chunk in iter(lambda: stream.read(1024 * 1024), b''): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def _canonical(value): | |
| return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) | |
| def _pairs(items): | |
| result = {} | |
| for key, value in items: | |
| if key in result: | |
| raise ValueError('Duplicate JSON field: ' + key) | |
| result[key] = value | |
| return result | |
| def load_json(path): | |
| def invalid(value): | |
| raise ValueError('Nonfinite JSON number: ' + value) | |
| value = json.loads(Path(path).read_bytes(), object_pairs_hook=_pairs, parse_constant=invalid) | |
| _canonical(value) # Includes numeric overflow such as 1e999. | |
| return value | |
| def _save(path, value): | |
| with Path(path).open('x', encoding='utf-8') as stream: | |
| stream.write(json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + '\n') | |
| def _positive(value, label): | |
| if type(value) not in (int, float) or not math.isfinite(value) or value <= 0: | |
| raise ValueError(label + ' must be finite and positive') | |
| return float(value) | |
| def _index(rows, label): | |
| if not isinstance(rows, list): | |
| raise ValueError(label + ' must be a list') | |
| indexed = {} | |
| for row in rows: | |
| if not isinstance(row, dict): | |
| raise ValueError(label + ' must contain objects') | |
| identifier = row.get('entity_id') | |
| if not isinstance(identifier, str) or not identifier.strip() or identifier in indexed: | |
| raise ValueError(label + ' requires unique, nonempty entity_id values') | |
| indexed[identifier] = row | |
| return indexed | |
| def _protected(original, patch, mutable, label): | |
| if not isinstance(original, dict) or not isinstance(patch, dict): | |
| raise ValueError(label + ' must be an object') | |
| for key, value in patch.items(): | |
| if key not in mutable and (key not in original or | |
| _canonical(value) != _canonical(original[key])): | |
| raise ValueError('Protected requirement changed: ' + label + '.' + key) | |
| def _without_evidence(config): | |
| result = {key: copy.deepcopy(config[key]) for key in ('task', 'priors') if key in config} | |
| task = result.get('task') | |
| if isinstance(task, dict): | |
| for row in task.get('measured_supports', []): | |
| if isinstance(row, dict): | |
| for key in _APPROACH: | |
| row.pop(key, None) | |
| if isinstance(row.get('surface'), dict): | |
| for key in _SURFACE: | |
| row['surface'].pop(key, None) | |
| priors = result.get('priors') | |
| if isinstance(priors, dict): | |
| for field in ('surfaces', 'footprints'): | |
| for row in priors.get(field, []): | |
| if isinstance(row, dict): | |
| for key in _BOUNDS: | |
| row.pop(key, None) | |
| return result | |
| def _source(record, entity, scene_sha, label): | |
| if 'source_scene_sha256' in record and record['source_scene_sha256'] != scene_sha: | |
| raise ValueError('Stale scene source pin: ' + label) | |
| if 'source_sha256' not in record: | |
| return False | |
| expected = entity.get('asset_sha256') or scene_sha | |
| value = record['source_sha256'] | |
| if (not isinstance(expected, str) or len(expected) != 64 or | |
| any(c not in '0123456789abcdefABCDEF' for c in expected) or | |
| not isinstance(value, str) or value.lower() != expected.lower()): | |
| raise ValueError('Stale or invalid source_sha256: ' + label) | |
| return True | |
| def _rectangle(value): | |
| if (not isinstance(value, list) or len(value) != 4 or | |
| any(type(v) not in (int, float) or not math.isfinite(v) for v in value) or | |
| not value[0] < value[2] or not value[1] < value[3]): | |
| raise ValueError('Measured bounds require a positive finite XY rectangle') | |
| def _merge(config, evidence, manifest, scene_sha): | |
| result = _without_evidence(config) | |
| missing = [] | |
| entities = _index(manifest.get('entities'), 'manifest.entities') | |
| for section in ('task', 'priors'): | |
| if section not in config or config[section] is None: | |
| if section in evidence and evidence[section] not in (None, {}): | |
| raise ValueError('Unrequested evidence section: ' + section) | |
| continue | |
| original, patch = config[section], evidence.get(section, {}) | |
| mutable = {'measured_supports'} if section == 'task' else {'surfaces', 'footprints'} | |
| _protected(original, patch, mutable, section) | |
| if section == 'task': | |
| old = _index(original.get('measured_supports', []), 'task.measured_supports') | |
| rows = _index(patch.get('measured_supports', []), 'evidence.measured_supports') | |
| wanted = list(dict.fromkeys(original.get('support_entity_ids', []) + list(old))) | |
| if set(rows) - set(wanted) or set(wanted) - set(entities): | |
| raise ValueError('Measurement changed task support candidates') | |
| merged_rows = [] | |
| for identifier in wanted: | |
| previous = old.get(identifier, {'entity_id': identifier}) | |
| update = rows.get(identifier, {}) | |
| _protected(previous, update, _APPROACH | {'surface'}, 'measured_supports') | |
| row = next((r for r in result[section].get('measured_supports', []) | |
| if r['entity_id'] == identifier), {'entity_id': identifier}) | |
| surface_patch = update.get('surface', {}) | |
| _protected(previous.get('surface', {}), surface_patch, _SURFACE, 'surface') | |
| row.setdefault('surface', {}).update(copy.deepcopy(surface_patch)) | |
| row.update({key: copy.deepcopy(value) for key, value in update.items() | |
| if key in _APPROACH}) | |
| surface = row['surface'] | |
| source_ok = _source(surface_patch, entities[identifier], scene_sha, identifier) | |
| if not source_ok or not {'region', 'height_m', 'xy_m'} <= surface.keys(): | |
| missing.append('task.surface:' + identifier) | |
| for key in ('source_scene_sha256', 'approach_scene_sha256'): | |
| if key in update and update[key] != scene_sha: | |
| raise ValueError('Stale approach/scene source pin') | |
| if 'source_sha256' in update: | |
| _source(update, entities[identifier], scene_sha, identifier) | |
| if 'approach_clearance_width_m' in update: | |
| pin = update.get('approach_source_sha256', update.get('source_sha256')) | |
| if pin is not None: | |
| _source({'source_sha256': pin}, entities[identifier], scene_sha, identifier) | |
| if pin is None: | |
| missing.append('task.approach_source:' + identifier) | |
| elif 'minimum_approach_width_m' in original: | |
| missing.append('task.approach:' + identifier) | |
| merged_rows.append(row) | |
| result[section]['measured_supports'] = merged_rows | |
| audit = evaluate_task(manifest, result[section]) | |
| if audit['status'] == 'insufficient_evidence': | |
| missing.append('task.required_measurements') | |
| else: | |
| reserved = {r['support_entity_id'] for r in original.get('reservations', [])} | |
| for field in ('surfaces', 'footprints'): | |
| old = _index(original.get(field, []), 'priors.' + field) | |
| expected = dict(old) | |
| if field == 'surfaces': | |
| for identifier in reserved: | |
| expected.setdefault(identifier, {'entity_id': identifier}) | |
| else: | |
| for identifier, entity in entities.items(): | |
| parents = {entity[k] for k in ('supported_by_entity_id', | |
| 'support_entity_id', 'parent_entity_id') if entity.get(k) is not None} | |
| if len(parents) == 1 and next(iter(parents)) in reserved: | |
| expected.setdefault(identifier, dict(entity_id=identifier, | |
| support_entity_id=next(iter(parents)))) | |
| rows = _index(patch.get(field, []), 'evidence.' + field) | |
| if set(rows) - set(expected) or set(expected) - set(entities): | |
| raise ValueError('Measurement changed prior entity domain') | |
| merged_rows = [] | |
| for identifier, previous in expected.items(): | |
| update = rows.get(identifier, {}) | |
| _protected(previous, update, _BOUNDS, 'priors.' + field) | |
| row = {k: copy.deepcopy(v) for k, v in previous.items() if k not in _BOUNDS} | |
| row.update({k: copy.deepcopy(v) for k, v in update.items() if k in _BOUNDS}) | |
| if 'bounds_xy_m' in update: | |
| _rectangle(update['bounds_xy_m']) | |
| source_ok = _source(update, entities[identifier], scene_sha, identifier) | |
| if not source_ok or 'bounds_xy_m' not in update: | |
| missing.append('priors.' + field + ':' + identifier) | |
| merged_rows.append(row) | |
| if field in original or merged_rows: | |
| result[section][field] = merged_rows | |
| audit = evaluate_priors(manifest, result[section]) | |
| if audit['status'] == 'insufficient_evidence': | |
| missing.append('priors.required_measurements') | |
| return result, missing | |
| def refresh_measurements(config, generated_manifest_path, output_dir, *, source_root, | |
| timeout_s) -> dict: | |
| """Run a configured measurement command within the caller's remaining budget.""" | |
| started = time.monotonic() | |
| output = Path(output_dir).resolve() | |
| result = dict(schema='rhg.measurement-refresh-result.v1', status='pending', passed=False, | |
| evidence_manifest_sha256=None, input_sha256={}, artifact_sha256={}, | |
| command=None, receipt_path=None, inputs_unchanged=True, | |
| physical_qualified=False, native_preflight_queried=False, | |
| whole_task_acceptance=False) | |
| writable = False | |
| try: | |
| if not isinstance(config, dict): | |
| raise ValueError('config must be an object') | |
| _canonical(config) | |
| result.update(_without_evidence(config)) | |
| output.mkdir(parents=True, exist_ok=True) | |
| if any(output.iterdir()): | |
| raise ValueError('Measurement output directory must be new or empty') | |
| writable = True | |
| budget = _positive(timeout_s, 'timeout_s') | |
| runner = config.get('measurement_refresh') | |
| if runner is None or runner == {}: | |
| result['pending_fields'] = ['measurement_refresh.command'] | |
| else: | |
| if not isinstance(runner, dict): | |
| raise ValueError('measurement_refresh must be an object') | |
| command = runner.get('command') | |
| if command is None: | |
| result['pending_fields'] = ['measurement_refresh.command'] | |
| else: | |
| if (not isinstance(command, list) or not command or | |
| any(not isinstance(arg, str) or not arg for arg in command)): | |
| raise ValueError('measurement_refresh.command must be nonempty argv tokens') | |
| if 'timeout_s' in runner: | |
| budget = min(budget, _positive(runner['timeout_s'], 'measurement_refresh.timeout_s')) | |
| deadline = started + budget | |
| manifest_path = Path(generated_manifest_path).resolve(strict=True) | |
| manifest_sha = file_sha256(manifest_path) | |
| result['input_sha256'][str(manifest_path)] = manifest_sha | |
| manifest = load_json(manifest_path) | |
| generation = config.get('generation', {}) | |
| scene_name = generation.get('scene_output') | |
| if scene_name is None: | |
| identifier = manifest.get('scene_id') | |
| if (not isinstance(identifier, str) or not identifier or | |
| Path(identifier).name != identifier or identifier in ('.', '..')): | |
| raise ValueError('Manifest needs scene_id or generation.scene_output') | |
| scene_name = identifier + '.blend' | |
| if not isinstance(scene_name, str) or not scene_name: | |
| raise ValueError('generation.scene_output must be a saved file path') | |
| scene = (manifest_path.parent / scene_name).resolve(strict=True) | |
| if scene == manifest_path or not scene.is_file(): | |
| raise ValueError('Saved scene is missing or aliases the manifest') | |
| scene_sha = file_sha256(scene) | |
| result['input_sha256'][str(scene)] = scene_sha | |
| source = Path(source_root).resolve(strict=True) | |
| request = output / 'measurement_request.json' | |
| _save(request, {key: config[key] for key in ('task', 'priors') if key in config}) | |
| result['input_sha256'][str(request)] = file_sha256(request) | |
| target = output / 'evidence.json' | |
| tokens = {'{manifest}': str(manifest_path), '{scene}': str(scene), | |
| '{output}': str(target), '{source_root}': str(source), | |
| '{requirements}': str(request)} | |
| expanded = [] | |
| for argument in command: | |
| for token, value in tokens.items(): | |
| argument = argument.replace(token, value) | |
| expanded.append(argument) | |
| for index, argument in enumerate(expanded): | |
| path = Path(argument) | |
| if path.is_absolute() and path.is_file() and (index == 0 or path.suffix == '.py'): | |
| sha = file_sha256(path) | |
| # Keep the invoked path too: a symlink can be retargeted. | |
| result['input_sha256'][str(path)] = sha | |
| result['input_sha256'][str(path.resolve())] = sha | |
| remaining = deadline - time.monotonic() | |
| if remaining <= 0: | |
| raise TimeoutError('Measurement deadline exhausted before command launch') | |
| result['command'] = expanded | |
| receipt = process_control.execute_command(expanded, source, output / 'measurement.log', remaining) | |
| receipt_path = output / 'command_receipt.json' | |
| _save(receipt_path, receipt) | |
| result['receipt_path'] = str(receipt_path) | |
| if (receipt.get('exit_code') != 0 or receipt.get('timed_out') is not False or | |
| receipt.get('cleanup_passed') is not True): | |
| raise ValueError('Measurement command failed, timed out, or cleanup failed') | |
| if time.monotonic() > deadline: | |
| raise TimeoutError('Measurement command exceeded remaining deadline') | |
| evidence = load_json(target) | |
| if (not isinstance(evidence, dict) or evidence.get('schema') != 'rhg.measured-refresh.v1' or | |
| evidence.get('manifest_sha256') != manifest_sha or | |
| evidence.get('scene_sha256') != scene_sha): | |
| raise ValueError('Stale or malformed measurement evidence binding') | |
| if any(evidence.get(k) is True for k in ('physical_qualified', 'whole_task_acceptance')): | |
| raise ValueError('Measurement evidence cannot certify native acceptance') | |
| extra_pins = evidence.get('input_sha256', {}) | |
| if not isinstance(extra_pins, dict): | |
| raise ValueError('Evidence input_sha256 must be a path/hash mapping') | |
| for name, expected in extra_pins.items(): | |
| path = Path(name) | |
| if (not path.is_absolute() or not path.is_file() or | |
| not isinstance(expected, str) or file_sha256(path) != expected or | |
| (str(path.resolve()) in result['input_sha256'] and | |
| result['input_sha256'][str(path.resolve())] != expected)): | |
| raise ValueError('Stale or conflicting measurement input pin: ' + name) | |
| result['input_sha256'][str(path.resolve())] = expected | |
| merged, missing = _merge(config, evidence, manifest, scene_sha) | |
| if time.monotonic() > deadline: | |
| raise TimeoutError('Measurement validation exceeded remaining deadline') | |
| result.update(merged) | |
| result['evidence_path'] = str(target) | |
| result['evidence_manifest_sha256'] = manifest_sha | |
| if missing or evidence.get('status') == 'pending' or evidence.get('passed') is False: | |
| result['pending_fields'] = missing or evidence.get('pending_fields', ['runner.pending']) | |
| else: | |
| if evidence.get('status', 'measured') not in ('measured', 'refreshed', 'complete'): | |
| raise ValueError('Unsupported measurement evidence status') | |
| result.update(status='refreshed', passed=True) | |
| except Exception as error: | |
| result.update(status='failed', passed=False, evidence_manifest_sha256=None, | |
| error_type=type(error).__name__, error=str(error)) | |
| finally: | |
| try: | |
| result['inputs_unchanged'] = all(Path(path).is_file() and file_sha256(path) == sha | |
| for path, sha in result['input_sha256'].items()) | |
| except OSError: | |
| result['inputs_unchanged'] = False | |
| if not result['inputs_unchanged']: | |
| result.update(status='failed', passed=False, evidence_manifest_sha256=None, | |
| error='Measurement input changed during command or validation') | |
| result['elapsed_s'] = round(time.monotonic() - started, 3) | |
| if writable: | |
| result['artifact_sha256'] = {str(path): file_sha256(path) | |
| for path in sorted(output.rglob('*')) if path.is_file() and not path.is_symlink()} | |
| result['result_path'] = str(output / 'result.json') | |
| _save(output / 'result.json', result) | |
| return result | |