"""Versioned 180-degree correction of the user-identified 240x96 capture domain."""
from __future__ import annotations
from collections import Counter
from copy import deepcopy
from dataclasses import replace
from datetime import datetime
import hashlib
import json
from pathlib import Path
import zipfile
from zoneinfo import ZoneInfo

import numpy as np
from PIL import Image
import torch
from torch.utils.data import DataLoader

from pallet.annotation import load_jsonl, annotation_digest
from pallet.clean_intensity_review import safe_bytes, safe_copy, safe_json, jsonl, reserve
from pallet.data.loader import load_frame, decoder_digest, policy_digest, NormalizationStats
from pallet.data.orientation import orient_grid, rotate_document
from pallet.data.pcd import read_pcd
from pallet.data.protocol import load_protocol, file_digest, write_json
from pallet.devices import resolve_device, device_metadata
from pallet.export import load_detector_checkpoint
from pallet.experiments.evaluate import predict_batch_boxes
from pallet.human_labeling import _InferenceDataset, _collate_inference, _validated_manual_partition, _load_frame_index
from pallet.review_batches import display

ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT/'outputs/orientation_240x96_v1'
OLD_PROTOCOL=ROOT/'outputs/protocol_v6_clean'
PROTOCOL=ROOT/'outputs/protocol_v7_oriented'
OLD_CACHE=ROOT/'outputs/cache_v6_clean'
CACHE=ROOT/'outputs/cache_v7_oriented'
OLD=ROOT/'outputs/human_correction_manual_6552_v1'
SOURCE=OLD/'anylabeling'
ACTIVE=ROOT/'outputs/pallet_clean_intensity_v1/active_anylabeling'
EXAMPLE='0b7fb57b1bad05d0c9fe3fef'
UUID='GPU-3ce8e1e7-efb2-80a6-de52-75da2f9fa259'


def read(path):return json.loads(Path(path).read_text())
def rows(path):return [json.loads(line) for line in Path(path).read_text().splitlines() if line]
def key(fid):return hashlib.sha256(fid.encode()).hexdigest()[:24]

def status(stage,**kw):
    write_json(OUT/'workflow_status.json',{'stage':stage,'updated_at':datetime.now(ZoneInfo('Asia/Shanghai')).isoformat(),**kw})
    print(stage,kw,flush=True)


def prepare():
    OUT.mkdir(exist_ok=True);reserve()
    binding={str(p.relative_to(ROOT)):file_digest(p) for p in [OLD_PROTOCOL/'protocol.json',
        OLD_CACHE/'sealed_index.json',OLD_CACHE/'seal.json',SOURCE/'frames.jsonl',SOURCE/'package_manifest.json',
        ACTIVE/'frames.jsonl',OLD/'inputs/all_checked_annotations.jsonl',OLD/'training/best.pt',OLD/'confidence_threshold.json']}
    safe_json(OUT/'input_binding.json',binding)
    old_rows=rows(OLD_PROTOCOL/'manifest.jsonl'); original={r['frame_id']:r for r in old_rows}
    records,assignments,_=load_protocol(OLD_PROTOCOL)
    affected=[r for r in records if r.sensor_config['grid']==[96,240]]
    affected_ids={r.frame_id for r in affected};by_id={r.frame_id:r for r in records}
    assert len(affected)==300 and {r.frame_id.split('/')[0] for r in affected}=={'2024_11_27'}
    assert {assignments[r.group_id] for r in affected}=={'test'}
    source_index={r['frame_id']:r for r in rows(SOURCE/'frames.jsonl')}
    assert len(affected_ids & set(source_index))==300
    human=load_jsonl(OLD/'inputs/all_checked_annotations.jsonl')
    assert not affected_ids & set(human.frames)
    baseline=read(OUT/'inputs/parent_decoder_proof.json')
    assert baseline['parent_decoder_sha256']==read(OLD_CACHE/'seal.json')['decoder_sha256']
    assert baseline['cache_seal_sha256']==file_digest(OLD_CACHE/'seal.json')
    index=read(OLD_CACHE/'sealed_index.json')
    assert file_digest(OLD_CACHE/'sealed_index.json')==read(OLD_CACHE/'seal.json')['index_sha256']
    tensor_dir=CACHE/'frames';tensor_dir.mkdir(parents=True,exist_ok=True)
    new_rows=[];trace=[];new_records=[]
    for r in records:
        row=deepcopy(original[r.frame_id])
        if r.frame_id in affected_ids:
            policy={**r.sensor_config,'pixel_rotation_degrees':180,
                'orientation_evidence':'User identified all 240x96 images as upside down on 2026-10-09; upright pallet body verified in native before/after view.',
                'coordinate_frame':'pixel grid rotated 180 degrees; XYZ values remain in original sensor axes'}
            row['sensor_config']=policy
            # Explicit cache and policy checks reproduce the sealed original tensor.
            entry=index[r.frame_id]
            old_record=replace(r,cache_path=entry['path'],cache_sha256=entry['sha256'])
            old_tensor=load_frame(old_record)
            if file_digest(r.pcd)!=r.source_sha256:raise ValueError('Source PCD hash changed')
            _,points=read_pcd(r.pcd)
            raw_i=points[:,3].reshape(96,240)
            np.testing.assert_array_equal(old_tensor[...,1],np.where(old_tensor[...,3]>0,raw_i,0))
            corrected=replace(r,sensor_config=policy,cache_path=None,cache_sha256=None)
            tensor,metadata=load_frame(corrected,return_metadata=True)
            np.testing.assert_array_equal(tensor,orient_grid(old_tensor,policy))
            path=tensor_dir/f'{r.source_sha256}-{policy_digest(policy)[:12]}.npz'
            if not path.exists():
                reserve();np.savez_compressed(path,frame=tensor,metadata=json.dumps(metadata))
            new_entry={'path':str(path),'sha256':file_digest(path),'size':path.stat().st_size}
            index[r.frame_id]=new_entry
            cached=replace(corrected,cache_path=str(path),cache_sha256=new_entry['sha256'])
            np.testing.assert_array_equal(load_frame(cached),tensor)
            # Floating input, display PNG, all masks and ordered point indices share this mapping.
            original_view=np.asarray(Image.open(SOURCE/source_index[r.frame_id]['image']))
            np.testing.assert_array_equal(display(old_tensor[...,1],old_tensor[...,3],log=True),original_view)
            np.testing.assert_array_equal(display(tensor[...,1],tensor[...,3],log=True),np.rot90(original_view,2))
            raw_depth=np.asarray(Image.open(r.paths['depth']))
            depth_dst=OUT/'derived_native_depth'/f'{key(r.frame_id)}.depth.png';depth_dst.parent.mkdir(exist_ok=True)
            if not depth_dst.exists():Image.fromarray(np.ascontiguousarray(np.rot90(raw_depth,2))).save(depth_dst)
            np.testing.assert_array_equal(np.asarray(Image.open(depth_dst)),np.rot90(raw_depth,2))
            trace.append({'frame_id':r.frame_id,'group_id':r.group_id,'domain':r.domain,'split':'test',
                'pcd':str(r.pcd),'pcd_sha256':r.source_sha256,'native_size':[240,96],
                'original_image':str(SOURCE/source_index[r.frame_id]['image']),
                'original_image_sha256':source_index[r.frame_id]['view_sha256']['image'],
                'source_grid_header':[23040,1],'rotation_degrees':180,
                'old_tensor_sha256':entry['sha256'],'corrected_tensor_sha256':new_entry['sha256'],
                'raw_depth_display':str(depth_dst),'raw_depth_sha256':file_digest(r.paths['depth']),
                'corrected_raw_depth_sha256':file_digest(depth_dst),
                'raw_depth_units_and_registration_verified':False})
            new_records.append(cached)
            if len(trace)%100==0:status('preparing',corrected_frames=len(trace),expected=300)
        new_rows.append(row)
    # Verify all 600 raw PCD copies of the 300 unique frames, including all/ duplicates.
    hashes={r.source_sha256:r.frame_id for r in affected};copies=[]
    for path in sorted((Path('/root/private/data/pallet')/'2024_11_27').rglob('*.pcd')):
        sha=file_digest(path)
        if sha not in hashes:raise ValueError('Unexpected 240x96 source copy identity')
        copies.append({'path':str(path),'frame_id':hashes[sha],'source_sha256':sha})
    assert len(copies)==600 and set(Counter(c['frame_id'] for c in copies).values())=={2}
    safe_json(OUT/'source_copy_index.json',copies);safe_json(OUT/'orientation_manifest.json',trace)
    PROTOCOL.mkdir(exist_ok=True);jsonl(PROTOCOL/'manifest.jsonl',new_rows)
    prior=read(OLD_PROTOCOL/'protocol.json')
    for name in prior['files']:
        if name=='manifest.jsonl':continue
        if name=='sensors.json':
            sensors=read(OLD_PROTOCOL/name)
            for r in new_records:sensors[r.sensor_config['policy_id']]=r.sensor_config
            safe_json(PROTOCOL/name,sensors)
        else:safe_copy(OLD_PROTOCOL/name,PROTOCOL/name)
    protocol={**prior,'version':7,'parent_protocol_sha256':file_digest(OLD_PROTOCOL/'protocol.json'),
        'files':{n:file_digest(PROTOCOL/n) for n in prior['files']},
        'orientation_corrected_frames':300,'orientation_manifest_sha256':file_digest(OUT/'orientation_manifest.json'),
        'orientation_note':'User-authorized rotation of all native 240x96 frames; train/val/test membership preserved.'}
    safe_json(PROTOCOL/'protocol.json',protocol)
    safe_json(CACHE/'sealed_index.json',index)
    safe_json(CACHE/'seal.json',{'protocol_sha256':file_digest(PROTOCOL/'protocol.json'),'frames':10374,
        'index_sha256':file_digest(CACHE/'sealed_index.json'),'decoder_sha256':decoder_digest(),
        'rotated_tensors':300,'unchanged_cached_tensors':10074,'parent_seal_sha256':file_digest(OLD_CACHE/'seal.json'),
        'validation':'All 300 rotated tensors bit-exactly equal native PCD/cached input rotated over both spatial axes; cached and uncached routes match. Remaining entries and policies unchanged.'})
    fresh,assignment,_=load_protocol(PROTOCOL)
    assert assignment==assignments and len(fresh)==10374
    migrate_manual()
    return new_records,affected_ids,source_index


def migrate_manual():
    target=OUT/'human_training';inputs=target/'inputs';inputs.mkdir(parents=True,exist_ok=True)
    for name in ['annotations.jsonl','selection.json','all_checked_annotations.jsonl','checked_external_annotations.jsonl']:
        safe_copy(OLD/'inputs'/name,inputs/name)
    for name in ['human_training_manifest.json','human_validation_manifest.json']:
        manifest=read(OLD/'inputs'/name);manifest['protocol_sha256']=file_digest(PROTOCOL/'protocol.json')
        manifest['parent_manifest_sha256']=file_digest(OLD/'inputs'/name)
        safe_json(inputs/name,manifest)
    partition=read(OLD/'manual_partition.json');partition['protocol_sha256']=file_digest(PROTOCOL/'protocol.json')
    partition['parent_partition_sha256']=file_digest(OLD/'manual_partition.json')
    partition['orientation_changes_affect_manual_labels']=False
    partition['artifact_sha256']={str(p.relative_to(target)):file_digest(p) for p in inputs.iterdir() if p.is_file()}
    safe_json(target/'manual_partition.json',partition)
    # External review receipts keep the original split, now bound to the new protocol.
    receipt=read(OLD/'inputs/external_review_receipt.json');receipt['protocol_sha256']=file_digest(PROTOCOL/'protocol.json')
    safe_json(inputs/'external_review_receipt.json',receipt)
    exclude=read(OLD/'inputs/reviewed_external_exclusion.json');exclude['protocol_sha256']=file_digest(PROTOCOL/'protocol.json')
    exclude['receipt_sha256']=file_digest(inputs/'external_review_receipt.json');safe_json(inputs/'reviewed_external_exclusion.json',exclude)
    _validated_manual_partition(target,PROTOCOL)


def predict(records):
    checkpoint=OLD/'training/best.pt';threshold=read(OLD/'confidence_threshold.json')
    assert file_digest(checkpoint)==read(OLD/'training/completed.json')['best_checkpoint_sha256']==threshold['checkpoint_sha256']
    binding={'protocol_sha256':file_digest(PROTOCOL/'protocol.json'),'checkpoint_sha256':file_digest(checkpoint),
        'threshold_sha256':file_digest(OLD/'confidence_threshold.json'), 'selected_confidence':threshold['selected_confidence'],
        'orientation_manifest_sha256':file_digest(OUT/'orientation_manifest.json'),'batch_size':16,
        'device_uuid':device_metadata(UUID)['uuid'],'model_retrained':False,'threshold_recalibrated':False}
    safe_json(OUT/'prediction_binding.json',binding);directory=OUT/'predictions';directory.mkdir(exist_ok=True)
    predictions={};pending=[]
    for r in records:
        path=directory/f'{key(r.frame_id)}.json'
        if path.exists():
            p=read(path)
            if p['binding']!=binding or p['frame_id']!=r.frame_id or p['source_anchor_hash']!=r.source_sha256:
                raise ValueError('Resumed prediction identity/binding changed')
            predictions[r.frame_id]=p
        else:pending.append(r)
    if pending:
        torch.set_num_threads(4);device=resolve_device(UUID)
        model,config=load_detector_checkpoint(checkpoint);model.to(device).eval()
        state=torch.load(checkpoint,map_location='cpu',weights_only=False);stats=NormalizationStats(**state['normalization'])
        dataset=_InferenceDataset(pending,stats,640)
        loader=DataLoader(dataset,batch_size=16,num_workers=2,pin_memory=True,collate_fn=_collate_inference)
        for images,metas in loader:
            detections=predict_batch_boxes(model,images.to(device,non_blocking=True),metas,conf=binding['selected_confidence'],size=640)
            for meta,boxes in zip(metas,detections):
                h,w=meta.original_size;result=[]
                for coords,score in boxes:
                    xyxy=np.clip(coords,[0,0,0,0],[w,h,w,h]).tolist()
                    if xyxy[2]>xyxy[0] and xyxy[3]>xyxy[1]:result.append({'xyxy':xyxy,'score':score})
                r=next(r for r in records if r.frame_id==meta.frame_id)
                p={'frame_id':r.frame_id,'source_anchor_hash':r.source_sha256,'width':w,'height':h,
                    'boxes_xyxy_score':result,'binding':binding,'coordinate_frame':'upright_rotated180',
                    'status':'proposal' if result else 'zero_detection_unreviewed'}
                safe_json(directory/f'{key(r.frame_id)}.json',p);predictions[r.frame_id]=p
            status('predicting_corrected',completed=len(predictions),expected=300)
    assert len(predictions)==300
    safe_json(OUT/'prediction_manifest.json',{'state':'complete','completed_frames':300,'errors':0,'binding':binding,
        'proposal_frames':sum(bool(p['boxes_xyxy_score']) for p in predictions.values()),
        'proposal_boxes':sum(len(p['boxes_xyxy_score']) for p in predictions.values()),
        'zero_detection_unreviewed':sum(not p['boxes_xyxy_score'] for p in predictions.values())})
    return predictions


def rotated_file(source,target):
    with Image.open(source) as image:
        corrected=image.transpose(Image.Transpose.ROTATE_180)
        from io import BytesIO
        b=BytesIO();corrected.save(b,format='PNG');safe_bytes(target,b.getvalue())
        with Image.open(target) as saved:np.testing.assert_array_equal(np.asarray(saved),np.rot90(np.asarray(image),2))


def build_workspace(source,target,affected,predictions):
    index=[]
    for original in rows(source/'frames.jsonl'):
        row=deepcopy(original);fid=row['frame_id'];doc=read(source/row['annotation'])
        is_rotated=fid in affected
        for role in ['image','depth','validity','intensity_validity']:
            if not row.get(role):continue
            if is_rotated:rotated_file(source/row[role],target/row[role])
            else:safe_copy(source/row[role],target/row[role])
        if is_rotated:
            old=deepcopy(doc);doc=rotate_document(doc)
            # Native box transform is applied to all existing rectangle/ignore shapes first;
            # fresh proposals use the corrected input and explicitly supersede old suggestions.
            p=predictions[fid];boxes=p['boxes_xyxy_score']
            doc['shapes']=[{'label':'pallet','shape_type':'rectangle','points':[b['xyxy'][:2],b['xyxy'][2:]],
                'flags':{'proposal_only':True},'group_id':None,'text':''} for b in boxes]
            doc['flags']={'human_reviewed':False,'unreviewed':True,'proposal_only':True,
                'confirmed_negative':False,'ignore':False,'machine_resolved':False,'label_conflict':False}
            metadata=doc.pop('pallet_export',None) or doc.get('pallet_prediction',{})
            metadata.update(frame_id=fid,group_id=row['group_id'],domain=row['domain'],source_anchor_hash=row['source_anchor_hash'],
                confidence=[b['score'] for b in boxes],status=p['status'],prediction_only=True,
                checkpoint_sha256=p['binding']['checkpoint_sha256'],threshold_sha256=p['binding']['threshold_sha256'],
                threshold=p['binding']['selected_confidence'],pixel_rotation_degrees=180,
                coordinate_frame='upright_rotated180',orientation_manifest_sha256=file_digest(OUT/'orientation_manifest.json'),
                original_annotation_sha256=file_digest(source/row['annotation']),
                old_shape_count=len(old.get('shapes',[])),fresh_prediction=True)
            doc['pallet_prediction']=metadata
            row.pop('baseline_json_sha256',None);row['status']=p['status'];row['proposal_count']=len(boxes)
            row['confidences']=[b['score'] for b in boxes]
            row['checkpoint_sha256']=p['binding']['checkpoint_sha256'];row['prediction_sha256']=file_digest(OUT/'predictions'/f'{key(fid)}.json')
            row['pixel_rotation_degrees']=180;row['coordinate_frame']='upright_rotated180';row['orientation_corrected']=True
            row['independent_reference']=False
            row.pop('machine_resolved',None);row.pop('state',None);row.pop('source_annotation_digest',None)
            safe_json(target/row['annotation'],doc)
        else:safe_copy(source/row['annotation'],target/row['annotation'])
        if 'size' not in row:row['size']=[doc['imageWidth'],doc['imageHeight']]
        row.pop('files',None);row.pop('baseline_json_sha256',None)
        row['baseline_annotation_sha256']=file_digest(target/row['annotation'])
        row['view_sha256']={role:file_digest(target/row[role]) for role in ['image','depth','validity']}
        index.append(row)
    jsonl(target/'frames.jsonl',index)
    safe_copy(source/'anylabeling_config.yaml',target/'anylabeling_config.yaml')
    safe_copy(source/'labels.txt',target/'labels.txt')
    # New labels contain corrected coordinates and exact parent/model provenance.
    parent=read(source/'package_manifest.json')
    manifest={**parent,'frames':len(index),'frames_index_sha256':file_digest(target/'frames.jsonl'),
        'prediction_binding':{**parent.get('prediction_binding',{}),'protocol_sha256':file_digest(PROTOCOL/'protocol.json'),
            'orientation_manifest_sha256':file_digest(OUT/'orientation_manifest.json')},
        'orientation_correction':{'degrees':180,'frames':300,'native_size':[240,96],
            'all_aligned_views_rotated':True,'fresh_proposals_for_corrected_frames':True},
        'parent_manifest_sha256':file_digest(source/'package_manifest.json')}
    count=Counter((r['split'],r.get('status','unknown')) for r in index)
    manifest['status_counts']={s:{state:n for (split,state),n in count.items() if split==s} for s in ['train','val','test']}
    safe_json(target/'package_manifest.json',manifest)
    _load_frame_index(target)
    return index


def audit_workspace(source,target,index,affected):
    for row in index:
        fid=row['frame_id'];doc=read(target/row['annotation']);w,h=row['size']
        if (doc['imageWidth'],doc['imageHeight'])!=(w,h) or doc['imagePath']!=Path(row['image']).name:
            raise ValueError('Native JSON coordinate mismatch')
        for role in ['image','depth','validity','intensity_validity']:
            if not row.get(role):continue
            with Image.open(source/row[role]) as old,Image.open(target/row[role]) as new:
                old.load();new.load()
                if old.size!=new.size or new.size!=(w,h):raise ValueError('Native view dimensions differ')
                np.testing.assert_array_equal(np.asarray(new),np.rot90(np.asarray(old),2) if fid in affected else np.asarray(old))
                if role=='image' and np.asarray(new).max()==0:raise ValueError('Black primary image present')
        if fid not in affected and file_digest(source/row['annotation'])!=file_digest(target/row['annotation']):
            raise ValueError('Unselected frame label changed')
        for shape in doc['shapes']:
            from pallet.data.orientation import rotate_rectangle
            rotate_rectangle(shape['points'],w,h)  # Bounds check, no mutation.
        if fid in affected:
            if not doc['flags']['unreviewed'] or doc['flags']['human_reviewed'] or not doc['flags']['proposal_only']:
                raise ValueError('Corrected proposal falsely accepted')
    return {'state':'passed','frames':len(index),'orientation_corrected':300,'failed':0,'pixel_exact_transforms':True}


def main():
    records,affected,source_index=prepare();predictions=predict(records)
    status('packaging',remaining_frames=3788,orientation_corrected=300)
    remaining=OUT/'anylabeling';index=build_workspace(SOURCE,remaining,affected,predictions)
    audit=audit_workspace(SOURCE,remaining,index,affected)
    active=OUT/'active_anylabeling';allindex=build_workspace(ACTIVE,active,affected,predictions)
    audit_workspace(ACTIVE,active,allindex,affected)
    assert len(index)==3788 and len(allindex)==10374
    checked={r['frame_id'] for r in rows(OLD/'inputs/all_checked_annotations.jsonl')}
    assert not {r['frame_id'] for r in index}&checked
    safe_json(remaining/'orientation_manifest.json',read(OUT/'orientation_manifest.json'))
    safe_bytes(remaining/'README_人工修正.md',(
        '本包含3,788帧未人工检查图像，val1,439/test2,349。所有240×96图像共300帧已纠正180度倒置。\n'
        '强度主图、同坐标深度显示和有效掩码同步旋转；其余3,488帧图像和JSON保持原样。\n'
        '300帧已用原最佳YOLO26s在校正后输入上重新预测，阈值0.70不变。所有框仍是待审建议，空框不是负例。\n'
        '打开images/val或images/test修改PNG旁的同名JSON。保留源身份元数据，不要更改文件名或尺寸。\n'
        '未确认的深度仍置零，原始深度PNG仅另存方向校正显示，未经单位/配准确认不进入模型。\n'
        '排除全部6,586帧已人工检查图像及148张不可恢复黑图；不作为独立测试参考。\n').encode())
    archive=OUT/'human_correction_remaining_3788_rotated180_v2.zip'
    if not archive.exists():
        reserve();temp=archive.with_suffix('.zip.tmp')
        with zipfile.ZipFile(temp,'w',zipfile.ZIP_DEFLATED,compresslevel=4) as z:
            for path in sorted(remaining.rglob('*')):
                if path.is_file():z.write(path,str(path.relative_to(remaining)))
        temp.replace(archive)
    files={str(p.relative_to(remaining)):p for p in remaining.rglob('*') if p.is_file()}
    with zipfile.ZipFile(archive) as z:
        if z.testzip() is not None:raise ValueError('ZIP CRC failed')
        if set(z.namelist())!=set(files):raise ValueError('ZIP member set differs from workspace')
        for name,path in files.items():
            if hashlib.sha256(z.read(name)).hexdigest()!=file_digest(path):raise ValueError('ZIP payload mismatch')
    if file_digest(OLD/'training/best.pt')!=read(OUT/'prediction_binding.json')['checkpoint_sha256']:raise ValueError('Model changed')
    payload={'state':'complete','archive':str(archive),'archive_sha256':file_digest(archive),'archive_bytes':archive.stat().st_size,
        'remaining_frames':3788,'split_counts':dict(Counter(r['split'] for r in index)),'corrected_unique_frames':300,
        'raw_pcd_copies_traced':600,'changed_annotation_frames':300,'unchanged_frames':3488,
        'manual_overlap':0,'zero_black_primary':True,'model_retrained':False,'test_labels_scored':False,
        'corrected_frame_prediction':read(OUT/'prediction_manifest.json'),'workspace_audit':audit,
        'zip_crc':'passed','zip_member_payload_hashes':'passed','parent_archive_sha256':file_digest(OLD/'human_correction_remaining_3788_v1.zip')}
    safe_json(OUT/'delivery_manifest.json',payload)
    control=read(OUT/'inputs/configs__active_dataset.json')
    control.update(protocol=str(PROTOCOL),source_export=str(active),cache_index=str(CACHE/'sealed_index.json'),
        human_training=str(OUT/'human_training'),remaining_review_package=str(archive),
        orientation_manifest=str(OUT/'orientation_manifest.json'),latest_orientation_delivery=str(OUT/'delivery_manifest.json'))
    write_json(ROOT/'configs/active_dataset.json',control)
    write_json(ROOT/'outputs/anylabeling_latest.json',{'kind':'orientation_corrected_model_assisted_delivery',
        'delivery':str(OUT/'delivery_manifest.json'),'protocol':str(PROTOCOL),'remaining_review_package':str(archive)})
    status('complete',remaining_frames=3788,corrected_frames=300)

if __name__=='__main__':main()
