"""Explicit150-target quality override; no deleted/isolated/human target resurrection."""
from collections import Counter,defaultdict
from contextlib import closing
import hashlib
import json
import math
from pathlib import Path
import shutil
import time

import cv2
import numpy as np
from PIL import Image,ImageDraw

from .cluster_targets import digest,protected_snapshot
from .mask_model_training_data import PROJECT,read,jsonl,write,sha,require,letterbox,gpu_receipt
from .mask_quota_saved_extension import load_formal_evidence,file_inventory
from .mask_quality_recovery import POSE,GALLERY,fingerprint
from .mask_template_refined import QUARANTINE,readonly,snapshot_database
from .mask_remaining_classes import confirmed,original_rectangle
from .mask_model_worklist import FLAGS,polygonize
from .mask_class_keypoints import convert,clockwise_top_left
from .mask_annotation_full_data import context
from .pose_review_geometry import raster_mask

ROOT=PROJECT/'outputs/pallet_mask_quality_override_requests_v1'
MODEL=PROJECT/'outputs/pallet_mask_annotation_update_v2'
BASE=MODEL/'private/training_records.jsonl'
LAST_TASKS=PROJECT/'outputs/pallet_mask_annotation_update_requests_v2'
LAST_DB=PROJECT/'outputs/pallet_mask_model_reviews_v5/mask_reviews.sqlite3'
STANDARD=LAST_TASKS/'class_keypoint_standard.json'
NAMESPACE='quality-override-manual-correction-v1'
SCHEMA='explicit_quality_override_model_or_template_initialization_v1'
DRAFT_PREFIX='mask-quality-override-manual-correction-v1:'
CHECKPOINT='879b1a30590e0782e01023dadcf079ab81e8a8f3ba11c0fd95f3c3a726d3275a'
GAPS={9:32,12:24,14:7,15:5,16:23,17:9,19:50}
POLICY=dict(user_request='本次无论标注质量，提供剩余的标注供人工修正',
    image_reuse_authorization='允许复用未标目标（Recommended）',fallback_authorization='标准点数模板（Recommended）',
    bypass_native_image_quality_screen=True,bypass_prediction_quality_screen=True,bypass_AI_coarse_corner_screen=True,
    allow_prior_machine_only_quality_withheld_and_shortlisted_targets=True,allow_seen_or_duplicate_images_for_unedited_targets=True,
    protect_completed_deleted_deferred_confirmed_isolated_and_all_human_contour_targets=True,
    template_fallback_not_this_image_model_geometry=True,initial_class_standard_K_preserved=True,
    duplicated_images_never_counted_as_new_distinct_images=True,no_automatic_training_GT_robot_or_propagation_promotion=True)


def raw_sha(raw):return hashlib.sha256(raw.encode('utf-8')).hexdigest() if raw is not None else None


def latest_basis():
    from scripts.audit_mask_model_reviews import audit
    result=audit(LAST_TASKS,LAST_DB);require(result['new_distinct_saved_images']==9 and result['events']==12,'All previous9 genuine saves required')
    records=jsonl(BASE);props={p['target_key']:p for p in jsonl(LAST_TASKS/'proposals.jsonl')}
    with closing(readonly(LAST_DB)) as db:current=dict(db.execute('SELECT target_key,payload FROM reviews'))
    counted=[dict(target_key=r['target_key'],class_id=r['class_id'],frame_id=r['frame_id'],image=r['native_image']) for r in records]
    counted.extend(dict(target_key=k,class_id=props[k]['class_id'],frame_id=props[k]['source']['frame_id'],image=props[k]['source']['image']) for k in current)
    require(len(counted)==len({r['target_key'] for r in counted})==2050,'Actual2050 distinct saved target basis required')
    return counted,result


def human_protection(rows,counted):
    protected=set(QUARANTINE)|{r['target_key'] for r in counted};reasons=defaultdict(set)
    for key in protected:reasons[key].add('already_saved_or_special_quarantine')
    with closing(readonly(POSE)) as db:
        current=dict(db.execute('SELECT target_key,payload FROM annotations'));history=defaultdict(list)
        for key,raw in db.execute('SELECT target_key,payload FROM events ORDER BY id'):history[key].append(json.loads(raw))
    for key in set(current)|set(history):
        values=history[key]+([json.loads(current[key])] if key in current else [])
        if key not in current or any(v.get('state') in ('deleted','deferred','confirmed') or confirmed(v) or not original_rectangle(v.get('polygon'),rows[key]) for v in values):
            protected.add(key);reasons[key].add('human_pose_mask_state_or_history_protected')
    stores={}
    for path in sorted((PROJECT/'outputs').glob('pallet_mask*_reviews_v*/mask_reviews.sqlite3')):
        with closing(readonly(path)) as db:
            for table in ('reviews','events'):
                for key, in db.execute(f'SELECT DISTINCT target_key FROM {table}'):
                    if key in rows:protected.add(key);reasons[key].add('existing_human_review_or_history')
        stores[str(path.relative_to(PROJECT))]=fingerprint(path)
    # Protect the entire isolated request inventory, not just saved isolated rows.
    isolated=PROJECT/'outputs/pallet_mask_nonconforming_requests_v1'
    for filename in ('requests.jsonl','proposals.jsonl','inspection_targets.jsonl'):
        path=isolated/filename
        if path.is_file():
            for r in jsonl(path):
                if r.get('target_key') in rows:protected.add(r['target_key']);reasons[r['target_key']].add('isolated_request_inventory')
    return protected,current,stores,{k:sorted(v) for k,v in reasons.items()}


def prior_inventory():
    inventories={};membership=defaultdict(set)
    for pattern in ('requests.jsonl','shortlist.jsonl','inspection_targets.jsonl'):
        for path in sorted((PROJECT/'outputs').rglob(pattern)):
            if path.is_relative_to(ROOT):continue
            name=str(path.relative_to(PROJECT));inventories[name]=digest(path)
            for r in jsonl(path):
                if r.get('target_key'):membership[r['target_key']].add(name)
    return inventories,{k:sorted(v) for k,v in membership.items()}


def old_versions():
    old=read(MODEL/'private/old_versions_inventory.json')
    for name in ('pallet_mask_annotation_update_v2','pallet_mask_annotation_update_requests_v2','pallet_mask_annotation_update_checks_v2'):
        old['outputs/'+name]=file_inventory(PROJECT/'outputs'/name)
    return old


def stage():
    require(not ROOT.exists(),'New isolated quality-override version required')
    formal,rows,evidence=load_formal_evidence(read(PROJECT/'outputs/pallet_mask_remaining_round5_v1/manifest.json'))
    counted,last=latest_basis();counts=Counter(r['class_id'] for r in counted);gaps={c:100-counts[c] for c in counts if counts[c]<100}
    require(gaps==GAPS,'Current150-target gaps differ; do not silently reassign completed targets')
    protected,current,stores,reasons=human_protection(rows,counted);inventories,membership=prior_inventory()
    counted_keys={r['target_key'] for r in counted};saved_frames={r['frame_id'] for r in counted};saved_hashes={digest(formal/r['image']) for r in counted}
    old_frames={rows[k]['frame_id'] for k in protected};old_hashes={digest(formal/rows[k]['image']) for k in protected};cache={}
    available={c:[] for c in GAPS}
    for key,row in sorted(rows.items()):
        if row['final_class_id'] not in GAPS or key in protected:continue
        image=evidence.image(row['frame_id']);require(list(image.shape[::-1])==row['size'],'Original image must load; no synthetic image replacement')
        box=row['bbox'];values=[box[n] for n in ('x','y','width','height')]
        if not all(math.isfinite(v) for v in values) or box['width']<=0 or box['height']<=0:continue
        if min(row['size'][0]-1,box['x']+box['width'])<=max(0,box['x']) or min(row['size'][1]-1,box['y']+box['height'])<=max(0,box['y']):continue
        if row['image'] not in cache:cache[row['image']]=digest(formal/row['image'])
        h=cache[row['image']];available[row['final_class_id']].append((key,h))
    selected=[];selected_frames=set();selected_hashes=set();class_frames=defaultdict(set);class_hashes=defaultdict(set);groups=Counter()
    for cls in sorted(GAPS,key=lambda c:(len(available[c]),c)):
        pending=list(available[cls]);require(len(pending)>=GAPS[cls],f'Not enough unedited Class{cls} targets; never resurrect human holds')
        for _ in range(GAPS[cls]):
            key,h=min(pending,key=lambda item:(
                rows[item[0]]['frame_id'] in class_frames[cls] or item[1] in class_hashes[cls],
                rows[item[0]]['frame_id'] in old_frames or item[1] in old_hashes,
                rows[item[0]]['frame_id'] in selected_frames or item[1] in selected_hashes,
                bool(membership.get(item[0])),groups[cls,rows[item[0]]['group_id']],
                -rows[item[0]]['bbox']['height'],-rows[item[0]]['bbox']['width'],item[0]))
            pending.remove((key,h));row=rows[key]
            reuse=dict(image_seen_in_prior_human_saved_target=row['frame_id'] in saved_frames or h in saved_hashes,
                image_seen_in_prior_protected_target=row['frame_id'] in old_frames or h in old_hashes,
                image_repeated_within_new_batch=row['frame_id'] in selected_frames or h in selected_hashes,
                image_repeated_within_class_in_new_batch=row['frame_id'] in class_frames[cls] or h in class_hashes[cls],
                previously_shortlisted_or_requested=bool(membership.get(key)),original_target_has_no_human_contour_history=True,
                counts_as_new_distinct_image=not (h in saved_hashes or h in selected_hashes or row['frame_id'] in saved_frames or row['frame_id'] in selected_frames))
            selected.append(dict(target_key=key,class_id=cls,source=row,request_order=len(selected)+1,image_sha256=h,
                pose_payload_raw_sha256=raw_sha(current.get(key)),gallery_payload_raw_sha256=None,image_reuse=reuse,prior_request_membership=membership.get(key,[])))
            selected_frames.add(row['frame_id']);selected_hashes.add(h);class_frames[cls].add(row['frame_id']);class_hashes[cls].add(h);groups[cls,row['group_id']]+=1
    require(len(selected)==150 and len({r['target_key'] for r in selected})==150,'Exactly150 unique unedited targets required')
    ROOT.mkdir(mode=0o700);(ROOT/'private').mkdir(mode=0o700)
    write(ROOT/'policy.json',POLICY);write(ROOT/'private/shortlist.jsonl',selected,lines=True);write(ROOT/'private/counted2050.jsonl',counted,lines=True)
    write(ROOT/'private/completed9_audit.json',last);snapshot_database(LAST_DB,ROOT/'private/completed9_snapshot.sqlite3')
    write(ROOT/'private/human_protection_reasons.json',reasons);write(ROOT/'private/old_versions_inventory.json',old_versions())
    shutil.copyfile(STANDARD,ROOT/'class_keypoint_standard.json')
    write(ROOT/'input_manifest.json',dict(schema='explicit150_quality_override_with_seen_image_permission_v1',policy_sha256=digest(ROOT/'policy.json'),
        actual_human_saved_targets=2050,actual_human_saved_before=dict(counts),remaining_target_gaps=GAPS,shortlist_sha256=digest(ROOT/'private/shortlist.jsonl'),
        counted2050_sha256=digest(ROOT/'private/counted2050.jsonl'),protected_target_count=len(protected),source_fingerprints=stores,
        pose_fingerprint=fingerprint(POSE),gallery_fingerprint=fingerprint(GALLERY),prior_worklist_inventories=inventories,
        configuration_sha256=file_inventory(PROJECT/'configs'),formal_protected=protected_snapshot(formal),
        formal_manifest_sha256=read(PROJECT/'outputs/pallet_mask_remaining_round5_v1/manifest.json')['formal_manifest_sha256'],
        class_standard_sha256=digest(STANDARD),checkpoint_sha256=CHECKPOINT,model_training_manifest_sha256=digest(MODEL/'dataset_manifest.json'),
        old_versions_inventory_sha256=digest(ROOT/'private/old_versions_inventory.json'),
        template_catalog_sha256=digest(MODEL/'private/training_records.jsonl'),old_image_reuse_authorized=True,quality_not_certified=True,
        selected_class_counts=dict(Counter(r['class_id'] for r in selected)),selected_native_image_hashes=len(selected_hashes),
        distinct_new_image_contribution=sum(r['image_reuse']['counts_as_new_distinct_image'] for r in selected)))
    print(dict(state='all150_unedited_targets_staged_without_quality_gate',classes=dict(Counter(r['class_id'] for r in selected)),
        native_unique_images=len(selected_hashes),new_distinct_images=sum(r['image_reuse']['counts_as_new_distinct_image'] for r in selected)),flush=True)


def template_for(row,count,catalog):
    candidates=[r for r in catalog if r['class_id']==row['final_class_id'] and len(r['polygon'])==count]
    require(candidates,'A genuine same-class standard-K template is required')
    ref=min(candidates,key=lambda r:r['target_key']);points=np.asarray(ref['polygon'],float);low=points.min(axis=0);span=np.ptp(points,axis=0)
    require((span>0).all(),'Template has degenerate extent')
    box=row['bbox'];width,height=row['size'];left=max(0.,box['x']);top=max(0.,box['y']);right=min(float(width-1),box['x']+box['width']);bottom=min(float(height-1),box['y']+box['height'])
    transformed=clockwise_top_left(np.round((points-low)/span*np.array([right-left,bottom-top])+[left,top],6)).tolist()
    from .pose_review_geometry import polygon_value
    polygon_value(transformed,width,height)
    return transformed,dict(kind='same_class_template',not_this_image_model_geometry=True,template_target_key=ref['target_key'],
        template_class_id=ref['class_id'],template_saved_polygon_sha256=sha(ref['polygon']),template_source_payload_sha256=ref['source_payload_sha256'],
        template_source_event_raw_sha256=ref['source_event_raw_sha256'],transform='affine_polygon_extent_to_clipped_original_target_box',
        physical_semantic_slots_confirmed=False,quality_certified=False)


def infer():
    import torch
    from rfdetr import RFDETRSegSmall
    from .mask_annotation_full_train import normalize
    from .mask_model_improvement import predicted_rle
    from .mask_model_improvement_adapter import mask_logits,native_logits,highest_class_query
    require(not (ROOT/'private/predictions.jsonl').exists(),'Preserve prediction evidence')
    require(digest(MODEL/'m2/final_ema.pt')==CHECKPOINT,'Use latest frozen trained M2, not retrain or relabel old predictions')
    gpu=gpu_receipt('m2');torch.set_num_threads(4);cv2.setNumThreads(1);weights=torch.load(MODEL/'m2/final_ema.pt',map_location='cpu',weights_only=True)
    wrapper=RFDETRSegSmall(num_classes=1,resolution=576,device='cuda:0',pretrain_weights=str(PROJECT/'outputs/pallet_mask_model_training_v1/generic_pretraining/rf-detr-seg-small.pt'),gradient_checkpointing=True,compile=False)
    network=wrapper.model.model;network.load_state_dict(weights['model'],strict=True);network.cuda().eval();del weights
    _,_,evidence=load_formal_evidence(read(PROJECT/'outputs/pallet_mask_remaining_round5_v1/manifest.json'))
    standard=read(STANDARD);catalog=jsonl(BASE);predictions=[];started=time.monotonic()
    write(ROOT/'private/inference_start.json',dict(checkpoint_sha256=CHECKPOINT,gpu=gpu,threshold=.5,network_input='image_pixels_only_fixed_original_bbox_context',
        target_manual_polygon_used=False,template_only_after_failed_model_K_conversion=True,all150_targets_inferred_no_quality_rejection=True))
    with torch.inference_mode():
        for r in jsonl(ROOT/'private/shortlist.jsonl'):
            row=r['source'];roi=context(row['bbox'],row['size']);x1,y1,x2,y2=roi;grey=evidence.image(row['frame_id'])[y1:y2,x1:x2]
            canvas,_,_,transform=letterbox(grey,None,(576,576));output=network(normalize(canvas)[None].cuda());query,score=highest_class_query(output)
            mask=native_logits(mask_logits(output)[0,query],transform).sigmoid().cpu().numpy()>=.5;dense,dense_info=polygonize(mask)
            k=standard['classes'][str(r['class_id'])]['standard_count']
            if dense:polygon,conversion=convert(mask,dense,k,row['bbox']['height'],origin=(x1,y1),native_size=row['size'])
            else:polygon,conversion=None,dict(reason=dense_info['reason'])
            if polygon:initialization=dict(kind='model_class_K',not_this_image_model_geometry=False,quality_certified=False)
            else:polygon,initialization=template_for(row,k,catalog)
            predictions.append(dict(target_key=r['target_key'],class_id=r['class_id'],roi=roi,raw_native_prediction_rle=predicted_rle(mask),selected_query=query,
                class_confidence_not_quality_probability=score,raw_polygonization=dense_info,model_corner_conversion=conversion,
                polygon=polygon,initialization=initialization,standard_count=k,checkpoint_sha256=CHECKPOINT,threshold=.5))
    write(ROOT/'private/predictions.jsonl',predictions,lines=True)
    result=dict(state='actual150_M2_inferences_model_or_explicit_template_drafts_not_quality_approved',targets=len(predictions),
        initialization_counts=dict(Counter(p['initialization']['kind'] for p in predictions)),checkpoint_sha256=CHECKPOINT,gpu=gpu,elapsed_seconds=time.monotonic()-started)
    write(ROOT/'private/inference_complete.json',result);print(result,flush=True)


def build():
    from .mask_quality_override_review import validate,editor_js
    from .mask_gallery import ASSETS
    from scripts.build_mask_remaining_direct_requests import build_font
    require(not (ROOT/'manifest.json').exists(),'Do not overwrite frozen override worklist')
    inputs=read(ROOT/'input_manifest.json');standard=read(ROOT/'class_keypoint_standard.json');standard_sha=digest(ROOT/'class_keypoint_standard.json')
    records={r['target_key']:r for r in jsonl(ROOT/'private/shortlist.jsonl')};predictions=jsonl(ROOT/'private/predictions.jsonl');proposals=[]
    for pred in predictions:
        r=records[pred['target_key']];cls=r['class_id'];init=pred['initialization'];proof=dict(model_family='RF-DETR-Seg Small',checkpoint_sha256=CHECKPOINT,
            training_version=str(MODEL.relative_to(PROJECT)),predictions_sha256=digest(ROOT/'private/predictions.jsonl'),native_mask_rle_sha256=sha(pred['raw_native_prediction_rle']),
            initialization=init,model_corner_conversion=pred['model_corner_conversion'],initial_polygon_is_this_image_model_geometry=init['kind']=='model_class_K',
            quality_gate_passed=False,human_saved=False,assistant_redrawn=False,template_used_only_if_model_cannot_supply_valid_class_K=True)
        p=dict(schema=SCHEMA,origin='same_class_template_initialization' if init['kind']=='same_class_template' else 'unfiltered_M2_model_initialization',
            status='unfiltered_initialization_pending_manual_correction',target_key=r['target_key'],class_id=cls,source=r['source'],polygon=pred['polygon'],vertex_count=len(pred['polygon']),
            formal_manifest_sha256=inputs['formal_manifest_sha256'],model_source_image_sha256=r['image_sha256'],pose_payload_raw_sha256=r['pose_payload_raw_sha256'],gallery_payload_raw_sha256=None,
            class_keypoint_constraint=dict(class_id=cls,standard_count=standard['classes'][str(cls)]['standard_count'],standard_sha256=standard_sha,
                method='unique_class_saved_polygon_vertex_count_mode',physical_semantic_slots_confirmed=False),
            initialization=init,image_reuse=r['image_reuse'],model_provenance=proof,quality_override_authorized=True,quality_certified=False,
            mask_semantics='unfiltered_model_or_template_initialization_requires_manual_correction_not_GT',**dict.fromkeys(FLAGS,False))
        validate(p,standard,standard_sha);proposals.append(p)
    require(len(proposals)==150,'No quality rejection allowed this authorized150 batch')
    formal=Path(read(PROJECT/'configs/active_formal_dataset.json')['dataset'])
    for folder in ('images','cases','masks','labelme'):(ROOT/folder).mkdir()
    for p in proposals:
        key=p['target_key'];row=p['source'];points=p['polygon'];k=len(points);shutil.copyfile(formal/row['image'],ROOT/'images'/f'{key}.png')
        image=Image.open(ROOT/'images'/f'{key}.png').convert('RGB');draw=ImageDraw.Draw(image);vertices=[tuple(v) for v in points]
        draw.line(vertices+[vertices[0]],fill='#55d5ff',width=1);box=row['bbox']
        left=max(0,math.floor(box['x']-12));top=max(0,math.floor(box['y']-16));right=min(row['size'][0],math.ceil(box['x']+box['width']+12));bottom=min(row['size'][1],math.ceil(box['y']+box['height']+16))
        crop=image.crop((left,top,right,bottom)).resize(((right-left)*3,(bottom-top)*3),Image.Resampling.NEAREST);draw=ImageDraw.Draw(crop)
        for i,(x,y) in enumerate(points,1):
            xx=(x-left)*3;yy=(y-top)*3;draw.ellipse((xx-2,yy-2,xx+2,yy+2),fill='#ffbe43');draw.text((xx+3,yy-9),str(i),fill='white',stroke_width=1,stroke_fill='black')
        crop.save(ROOT/'cases'/f'{key}.png')
        Image.fromarray(raster_mask(points,*row['size']).astype(np.uint8)*255).save(ROOT/'masks'/f'{key}.png')
        flags=dict(unfiltered_initialization=True,template_placeholder=p['initialization']['kind']=='same_class_template',human_confirmed=False,ground_truth_eligible=False,quality_certified=False)
        shapes=[dict(label='pallet',shape_type='polygon',points=points,group_id=row['box_index'],flags=flags)]
        shapes.extend(dict(label=f'kp_{i:02d}',shape_type='point',points=[point],group_id=row['box_index'],flags=flags) for i,point in enumerate(points,1))
        write(ROOT/'labelme'/f'{key}.json',dict(version='5.0.0',imagePath=f'../images/{key}.png',imageData=None,imageWidth=row['size'][0],imageHeight=row['size'][1],
            flags=flags,shapes=shapes,keypoints_xy=points,num_keypoints=k,class_id=p['class_id'],class_keypoint_constraint=p['class_keypoint_constraint'],
            initialization=p['initialization'],image_reuse=p['image_reuse'],model_checkpoint_sha256=CHECKPOINT,annotation_scope='single_unfiltered_target_initialization_not_GT'))
    write(ROOT/'proposals.jsonl',proposals,lines=True);write(ROOT/'requests.jsonl',[dict(target_key=p['target_key'],class_id=p['class_id'],keypoint_count=p['vertex_count'],
        initialization_kind=p['initialization']['kind'],counts_as_new_distinct_image=p['image_reuse']['counts_as_new_distinct_image']) for p in proposals],lines=True)
    counts=Counter(p['class_id'] for p in proposals);kinds=Counter(p['initialization']['kind'] for p in proposals)
    per_class_images=defaultdict(set)
    for r in jsonl(ROOT/'private/counted2050.jsonl'):per_class_images[r['class_id']].add(digest(formal/r['image']))
    for p in proposals:per_class_images[p['class_id']].add(p['model_source_image_sha256'])
    conditional_distinct_image_gaps={str(c):max(0,100-len(per_class_images[c])) for c in range(1,23)}
    page='<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>全部剩余150目标 · 不限质量供人工修正</title><style>@font-face{font-family:Review;src:url("report-font.otf")}*{box-sizing:border-box}body{font:16px/1.6 Review,sans-serif;background:#101720;color:#e7edf5;max-width:1100px;margin:auto;padding:12px}article{border:1px solid #536479;padding:12px;margin:18px 0}p,h2,td{overflow-wrap:anywhere}.warn{color:#ffd182}img{display:block;max-width:100%;height:auto}a{color:#80ceff}table{width:100%;border-collapse:collapse}td,th{padding:5px;border:1px solid #536479}@media(max-width:480px){h1{font-size:23px}body{padding:8px}}</style>'
    page+=f'<h1>剩余150个未标目标 · 全部供人工修正</h1><p class="warn">本轮按授权取消图像、预测及角点质量筛选，不做质量放行。共{len(proposals)}个不同目标：模型草稿{kinds["model_class_K"]}份，同类模板占位{kinds["same_class_template"]}份。模板占位不是本图模型检测轮廓，可能需要全部重画。</p><p>前9张均已真实保存，共12条修订，当前已保存2050个目标。沿用原访问码。初始点数仍按类别标准；可拖点、点击边增点、删点、撤销、重做和恢复历史；保存失败不跳转、不清本机草稿。</p>'
    page+=f'<p class="warn">您已允许已见/重复图片中的未标目标：本批150目标仅有{inputs["selected_native_image_hashes"]}份不同原生图像，其中只有{inputs["distinct_new_image_contribution"]}份可新增不同图像。重复图像不计作新增不同图像；完成150目标不等于每类100张不同图像。若全部保存，按每类不同图像计仍差{sum(conditional_distinct_image_gaps.values())}张。已完成、删除、暂缓、确认、隔离及有人工轮廓历史的目标仍保护。</p><p>机器草稿未保存不计完成，不自动成为GT、训练样本、传播种子或机器人指令。本轮没有重训，沿用2041张训练的最新M2；最新9份人工保存没有动态追加冻结训练集。旧入口与全部人工历史保留。</p><p>筛选 <select id="request-filter"><option value="">全部</option>'+''.join(f'<option value="{c}">Class {c}</option>' for c in range(1,23))+'</select></p><table><tr><th>类别</th><th>标准点数</th><th>已保存目标</th><th>本批待修正目标</th></tr>'
    for cls in range(1,23):page+=f'<tr><td>Class {cls}</td><td>{standard["classes"][str(cls)]["standard_count"]}</td><td>{inputs["actual_human_saved_before"][str(cls)]}</td><td>{counts[cls]}</td></tr>'
    page+='</table>'
    for p in proposals:
        key=p['target_key'];template=p['initialization']['kind']=='same_class_template';mode='模板占位（不是本图模型轮廓）' if template else '模型草稿（质量未验收）'
        duplicate='新图像' if p['image_reuse']['counts_as_new_distinct_image'] else '已见/重复图片，不计新增不同图像'
        page+=f'<article id="target-{key}" data-class="{p["class_id"]}"><h2>Class {p["class_id"]} · 标准{p["vertex_count"]}点 · 待人工修正</h2><p class="warn">{mode}；{duplicate}。请核对完整观察面和边界，可全部重画。</p><img loading="lazy" src="cases/{key}.png" alt="未验收模型或模板初始草稿"><a href="images/{key}.png">原图</a> · <a href="labelme/{key}.json">初始关键点LabelMe</a> · <a href="masks/{key}.png">初始掩膜</a></article>'
    page+='<script>const f=document.getElementById("request-filter");f.onchange=()=>document.querySelectorAll("article").forEach(a=>a.hidden=!!f.value&&a.dataset.class!==f.value);</script></html>'
    js=editor_js();(ROOT/'report_zh.html').write_text(page);(ROOT/'model-editor.js').write_text(js);build_font(ROOT,page+js+(ASSETS/'editor.html').read_text())
    assets={name:digest(ROOT/name) for name in ('report_zh.html','report-font.otf','FONT_LICENSE.txt','model-editor.js')}
    for p in proposals:
        for folder,ext in [('images','png'),('cases','png'),('masks','png'),('labelme','json')]:
            name=f'{folder}/{p["target_key"]}.{ext}';assets[name]=digest(ROOT/name)
    write(ROOT/'manifest.json',dict(schema=SCHEMA,source_namespace=NAMESPACE,request_count=150,class_counts=dict(counts),standard_counts={c:s['standard_count'] for c,s in standard['classes'].items()},
        actual_human_saved_before=inputs['actual_human_saved_before'],base_manual_count=2050,count_unit='distinct_targets_not_necessarily_distinct_images',
        initial_class_K_only=True,allow_template_initialization=True,initialization_counts=dict(kinds),quality_override_authorized=True,quality_certified=False,
        selected_native_image_hashes=inputs['selected_native_image_hashes'],distinct_new_image_contribution=inputs['distinct_new_image_contribution'],
        checkpoint_sha256=CHECKPOINT,class_standard_sha256=standard_sha,policy_sha256=digest(ROOT/'policy.json'),input_manifest_sha256=digest(ROOT/'input_manifest.json'),
        proposals_sha256=digest(ROOT/'proposals.jsonl'),requests_sha256=digest(ROOT/'requests.jsonl'),predictions_sha256=digest(ROOT/'private/predictions.jsonl'),
        public_assets=assets,automatic_GT_or_training_promotion=False,new_human_events_created=0,new_training_started=False,
        conditional_remaining_distinct_target_gap_after_all_saves={str(c):0 for c in range(1,23)},
        conditional_remaining_per_class_distinct_image_gaps=conditional_distinct_image_gaps,
        conditional_per_class_distinct_images_after_all_saves={str(c):len(per_class_images[c]) for c in range(1,23)},distinct_image_quota_completed=False))
    print(dict(state='built_all150_unfiltered_model_or_template_drafts_not_quality_pass',classes=dict(counts),initialization=dict(kinds)),flush=True)
