File size: 9,571 Bytes
6b95c6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a3215f
 
 
 
 
 
 
 
 
 
 
6b95c6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a3215f
6b95c6c
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""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 value<limit:reasons.append('insufficient_'+name)
    return reasons


def consensus(rows,capture,options):
    settings=options.up_estimation;out=reference(options,'insufficient_reliable_frames')
    out.update(settings=settings.model_dump(),sampled_frame_count=len(rows),accepted_frame_count=0,
               sampled_frame_ids=[r['source_frame_index'] for r in rows],frames=rows)
    credible=[];seen=set()
    for row in rows:
        row['reasons']=frame_reasons(row,settings)
        image_hash=row.get('image_sha256')
        if not image_hash or image_hash in seen:row['reasons'].append('duplicate_or_missing_image_evidence')
        seen.add(image_hash)
        if not row['reasons']:credible.append(row)
    if len(credible)<settings.minimum_frames:return out
    vectors=np.array([r['up_vector'] for r in credible],float)
    vectors/=np.linalg.norm(vectors,axis=1,keepdims=True)
    angles=np.degrees(np.arccos(np.clip(vectors@vectors.T,-1,1)))
    members=angles<=settings.maximum_frame_deviation_deg
    # A spherical medoid preserves sign; opposite directions never cancel into
    # a plausible average. Do not flip predictions to force agreement.
    best=int(np.argmax(members.sum(1)));take=members[best]
    if take.sum()<max(settings.minimum_frames,math.ceil(settings.minimum_consensus_fraction*len(credible))):
        out['reason_code']='inconsistent_camera_up_across_frames';return out
    vector=np.mean(vectors[take],axis=0);vector/=np.linalg.norm(vector)
    deviation=np.degrees(np.arccos(np.clip(vectors@vector,-1,1)))
    if np.max(deviation[take])>settings.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 coverage<settings.minimum_temporal_coverage:
        out['reason_code']='insufficient_camera_up_temporal_coverage';return out
    source='GeoCalib pinhole image calibration; multi-frame camera-up consensus (estimated)'
    out.update(status='estimated',up_vector=vector.tolist(),up_source=source,applied=True,reliable=True,reason_code=None)
    # Lens estimates support automatic scene geometry only. They do not replace
    # the reconstruction model's intrinsics or become user-verified calibration.
    cameras=np.asarray([r['estimated_intrinsics'] for r in accepted if 'estimated_intrinsics' in r],float)
    if cameras.shape==(len(accepted),3,3) and np.isfinite(cameras).all():
        focal=cameras[:,[0,1],[0,1]]
        centre=np.median(cameras,axis=0)
        if np.all(focal>0) 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)<options.up_estimation.minimum_frames:return reference(options,'insufficient_source_frames_for_camera_up')
    request={'video':str(Path(video).resolve()),'rotation':capture['rotation_degrees'],
        'frames':[{'source_frame_index':i,'video_time_s':capture['frames'][i]['playback_s']-capture['frames'][0]['playback_s'],
                   'box':track.get('boxes',[None]*capture['frame_count'])[i],
                   'tracking_reason':track['reasons'][i]} for i in indices],
        'camera':options.camera.model_dump() if options.camera else None,
        'weights':provider['weights'],'output':str((job/'camera-up-predictions-private.json').resolve())}
    path=job/'camera-up-request-private.json';atomic_json(path,request)
    env=dict(os.environ,MPLBACKEND='Agg',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1')
    for key in ('BASEBALL_API_KEY','GOOGLE_API_KEY','HF_TOKEN','HUGGING_FACE_HUB_TOKEN'):env.pop(key,None)
    progress('camera_up_estimation',0,len(indices))
    try:
        with (job/'camera-up-worker-private.log').open('wb') as log:
            subprocess.run([provider['worker_python'],'-m','baseball_batting.camera_up_worker','--request',str(path.resolve())],
                           env=env,stdout=log,stderr=subprocess.STDOUT,check=True,timeout=180)
        rows=read_json(request['output'])['frames']
        # Provider provenance is verified locally, never taken from video metadata.
        out=consensus(rows,capture,options)
        out.update(provider_revision=REVISION,weights_sha256=provider['weights_sha256'],
            implementation_sha256=implementation_hash(),inference_seed=0,
            camera_intrinsics_policy='estimated scene geometry only; body-model intrinsics unchanged')
    except (OSError,ValueError,KeyError,subprocess.SubprocessError) as error:
        out=reference(options,'camera_up_estimation_failed');out['error_type']=type(error).__name__
    atomic_json(job/'camera-up-private.json',out)
    progress('camera_up_estimation',len(indices),len(indices))
    return out