"""Freeze different-source sampling before fetching annotations or images."""
import hashlib,json,random,re
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r115';INV=R/'results/r46/inventory.json';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 assert not (O/'protocol.json').exists();inventory=json.loads(INV.read_text());sets={kind:{Path(x['name']).stem for x in inventory['files'] if x['name'].startswith(kind+'/')} for kind in ('images','annotations','xmls')};ex=set();evidence={}
 for root in (R/'datasets',Path('/tmp/diatom-r46-public')):
  paths=[]
  if root.exists():
   for p in root.rglob('*'):
    if p.is_file() and p.suffix.lower() in ('.png','.jpg','.jpeg','.xml') and p.stem.isdecimal() and 1<=int(p.stem)<=3000:ex.add(p.stem);paths.append(str(p))
  evidence[str(root)]={'numeric_file_paths':sorted(paths)}
 for f in ('results/r46/metadata-selection.json','results/r91/protocol.json'):
  d=json.loads((R/f).read_text());vals=d.get('selection',[])+d.get('preselection',[]);ex.update(x for x in vals if isinstance(x,str) and x.isdecimal());evidence[f]={'sha256':sha(R/f),'selection_ids':vals}
 scanned={}
 for path in sorted((R/'results').rglob('*.json')):
  if path.name in ('inventory.json','archive-index.json') or path.stat().st_size>25000000:continue
  try:s=path.read_text()
  except (UnicodeError,OSError):continue
  if not any(v in s.lower() for v in ('gunduz','gündüz','huseyingunduz','r91-gunduz','r80-gunduz','diatom-r46-public')):continue
  found=set(re.findall(r'(?:images|annotations|masks|xmls?)/([0-9]{1,4})\.(?:png|xml|jpg)',s,re.I));found.update(re.findall(r'"(?:id|image_id|source_id)"\s*:\s*"([0-9]{1,4})"',s));ex.update(found);scanned[str(path.relative_to(R))]={'sha256':sha(path),'detected_ids':sorted(found,key=int)}
 evidence['marked_result_json']=scanned;eligible=sorted((sets['images']&sets['annotations']&sets['xmls'])-ex,key=int);assert len(eligible)>=48;rng=random.Random(20261203);picked=rng.sample(eligible,48);e={'format':'r115-prior-id-screen-v1','warning':'Literal numeric IDs found in named local paths, two metadata selections and result JSON mentioning this source. This search can miss undocumented accesses and related specimens; common filenames, file IDs, sites and model-training independence remain unproven.','excluded_ids':sorted(ex,key=int),'evidence':evidence,'eligible_count':len(eligible)};(O/'prior-id-screen.json').write_text(json.dumps(e,indent=2)+'\n')
 p={'format':'r115-gunduz-protocol-v1','source':'Hüseyin Gündüz Diatom Dataset, CC BY-NC-SA 4.0; binary foreground components matched structurally to XML boxes are only proxies, not expert-confirmed instance masks.','inventory_sha256':sha(INV),'id_screen_sha256':sha(O/'prior-id-screen.json'),'prior_polygon_results_sha256':sha(R/'results/r112/source-mask-polygon-proxy/results.json'),'prior_medoid_results_sha256':sha(R/'results/r112/source-mask-polygon-proxy/medoid-exploration.json'),'model_sha256':sha(Path('/tmp/mobile_sam.pt')),'seed':20261203,'preselection':picked,'annotation_selection':'Before any selected source image pixels are fetched, audit 48 preselected XML files and binary annotation masks. Require existing connected-component/box rule: non-intersecting boxes, 8-connected binary components area >=20, one-to-one mapping and >=98% within exactly one box. Pick first 24 passing file IDs in fixed sampled order. For each selected image pick the largest matched component; tie by box index. Do not replace after image download.','duplicate_screen':'Before inference, compare each selected whole image and chosen component crop to all 29 prior R112 polygon-proxy source crops using exact whole-image SHA256 and 63-bit masked DCT hash over eight orientations. Quarantine if whole-image SHA matches or any crop DCT distance <=8; report all comparisons, no replacement. This coarse screen can miss related images or flag similar distinct specimens; it cannot establish independence.','crop_prompt':'Take the chosen matched XML box with 15% longer-side padding, clipped to native image; convert to grayscale. Use its binary component as reference. Derive contour from largest 8-connected component external boundary via OpenCV CHAIN_APPROX_SIMPLE; use its vertex mean and ±20% principal-axis span with the same UDE helper. Resize/pad grayscale to 512 as in prior study. Crops and prompts derive from reference and are oracle-assisted.','methods':'Compare same fixed center, 3-mask medoid (maximum sum of pairwise IoUs; ties center, minus, plus), and prior predeclared gated rule (center if existing geometric consistency triage passes, medoid otherwise). Triage requires minimum pair IoU >=0.75 and 3–75% center crop coverage. No reference-dependent candidate selection.','outcomes':'For every non-quarantined field and selected component report source-relative IoU for each rule, >=0.5 and >=0.75 counts, mean/median IoU, wins/losses, triage, ambiguity and all prompt positions/masks. Do not pool correlated cases as independent samples or treat source masks as expert-verified ground truth.','limits':'Different source dataset but already examined in project, unknown image/sample/site or base-model training independence. Structural mapping excludes intersecting boxes and cannot test real overlap recovery or false positives. Source annotation author expertise and completeness are unknown. Whole image and crop fingerprint screening is not proof of independent biology. No Academy, species or production accuracy claim.'};(O/'protocol.json').write_text(json.dumps(p,indent=2)+'\n');print('preselected',len(picked),'of',len(eligible),'eligible IDs; excluded',len(ex))
if __name__=='__main__':main()
