"""Conservative camera-up consensus and isolated image-provider invocation.""" import math import os from pathlib import Path import subprocess import numpy as np from .camera_up_provider import REVISION, WEIGHTS_SHA256, METHOD, CAMERA_FRAME from .storage import atomic_json, read_json, sha256_file, digest def implementation_hash(): return digest({n:sha256_file(Path(__file__).with_name(n)) for n in ('camera_up.py','camera_up_worker.py','camera_up_provider.py')}) def configured_record(models=None): path=Path(os.environ.get('BASEBALL_CAMERA_UP_RECORD',str(Path(models or '/opt/models')/'camera_up/provider.json'))) try: data=read_json(path) if (data['source_revision']==REVISION and data['weights_sha256']==WEIGHTS_SHA256 and Path(data['worker_python']).is_file() and Path(data['weights']).is_file()):return data except (OSError,ValueError,KeyError,TypeError):pass return None def public_status(models=None): return {'configured':configured_record(models) is not None,'method':METHOD, 'automatic_when_missing':True,'coordinate_frame':CAMERA_FRAME,'accuracy_validated':False} def reference(options,reason='not_estimated'): supplied=options.up_vector is not None return {'status':'provided' if supplied else 'unknown','up_vector':list(options.up_vector) if supplied else None, 'up_source':options.up_source if supplied else None,'coordinate_frame':CAMERA_FRAME, 'method':'caller_supplied' if supplied else METHOD,'applied':supplied, 'reliable':None if supplied else False,'confidence':None,'accuracy_validated':False, 'reason_code':'caller_input_not_independently_verified' if supplied else reason, 'reliability_kind':'engineering_image_and_temporal_checks; not calibrated accuracy or probability'} def sample_indices(capture,count): times=np.array([f['playback_s'] for f in capture['frames']],float) if not len(times) or not np.isfinite(times).all() or np.any(np.diff(times)<=0):return [] targets=np.linspace(times[0],times[-1],min(count,len(times))) return sorted({int(np.argmin(np.abs(times-t))) for t in targets}) def frame_reasons(row,settings): if row.get('reason_code'):return [row['reason_code']] reasons=[] v=np.asarray(row.get('up_vector',[]),float) if v.shape!=(3,) or not np.isfinite(v).all() or np.linalg.norm(v)<1e-8:reasons.append('invalid_camera_up_vector') checks=(('gravity_uncertainty_deg',settings.maximum_gravity_uncertainty_deg,'high_gravity_uncertainty'), ('up_residual_deg',settings.maximum_up_residual_deg,'up_field_disagreement'), ('latitude_residual_deg',settings.maximum_latitude_residual_deg,'latitude_field_disagreement')) for name,limit,reason in checks: value=row.get(name) if value is None or not math.isfinite(value) or value<0 or value>limit:reasons.append(reason) if row.get('covariance_valid') is not True:reasons.append('invalid_gravity_covariance') if not row.get('gravity_uncertainty_deg',0)>0:reasons.append('zero_gravity_uncertainty') minimums=(('background_fraction',settings.minimum_background_fraction), ('up_effective_pixels',settings.minimum_effective_pixels), ('latitude_effective_pixels',settings.minimum_effective_pixels), ('up_spatial_cells',settings.minimum_spatial_cells), ('latitude_spatial_cells',settings.minimum_spatial_cells), ('texture_fraction',settings.minimum_texture_fraction)) for name,limit in minimums: value=row.get(name) if value is None or not math.isfinite(value) or valuesettings.maximum_frame_deviation_deg: out['reason_code']='inconsistent_camera_up_across_frames';return out accepted=[r for r,good in zip(credible,take) if good] times=[r['playback_s'] for r in capture['frames']];duration=times[-1]-times[0] coverage=(max(r['video_time_s'] for r in accepted)-min(r['video_time_s'] for r in accepted))/duration if duration>0 else 0 out.update(temporal_coverage_fraction=float(coverage),maximum_deviation_deg=float(np.max(deviation[take])), accepted_frame_count=len(accepted),accepted_frame_ids=[r['source_frame_index'] for r in accepted], maximum_model_uncertainty_deg=max(r['gravity_uncertainty_deg'] for r in accepted)) if coverage0) and np.max(np.abs(focal/centre[[0,1],[0,1]]-1))<=.15: out['estimated_camera']={'fx':float(centre[0,0]),'fy':float(centre[1,1]), 'cx':float(centre[0,2]),'cy':float(centre[1,2]), 'source':'GeoCalib accepted scene frames; median estimated intrinsics', 'calibration_status':'estimated'} return out def estimate(job,video,capture,models,options,track,progress): if options.up_vector is not None:return reference(options) if not options.up_estimation.enabled:return reference(options,'automatic_up_estimation_disabled') provider=configured_record(models) if provider is None:return reference(options,'camera_up_provider_unavailable') job=Path(job);indices=sample_indices(capture,options.up_estimation.sample_count) if len(indices)