"""Research-only anchor classification ignore for fixed, identity-transformed images.

This masks direct classification BCE only; it does not mask instance-mask pixels,
regression losses, or effects through shared network weights.
"""
from pathlib import Path
import numpy as np,torch
from PIL import Image
from ultralytics.utils.loss import v8SegmentationLoss
from ultralytics.utils.tal import make_anchors
class RegionBCE(torch.nn.Module):
 def __init__(self,ignore,stats):super().__init__();self.ignore=ignore;self.stats=stats
 def forward(self,logits,target):
  assert logits.shape==target.shape and self.ignore.shape==(*target.shape[:2],1)
  positive=(target>0).any(dim=-1,keepdim=True);excluded=self.ignore&~positive;self.stats['bce_calls']+=1;self.stats['ignored_negative_anchors']+=int(excluded.sum());self.stats['preserved_positive_anchors_in_ignore']+=int((self.ignore&positive).sum());return torch.nn.functional.binary_cross_entropy_with_logits(logits,target,reduction='none')*((~self.ignore)|positive).to(logits.dtype)
class OracleIgnoreLoss(v8SegmentationLoss):
 def __init__(self,model,records,root,stats):
  super().__init__(model);self.stats=stats;self.table={}
  for r in records:
   img=Path(root)/r['image'];ign=Path(root)/r['ignore_mask'];im=np.asarray(Image.open(img).convert('RGB')).copy();mask=np.asarray(Image.open(ign).convert('L'))>0;assert im.shape==(512,512,3) and mask.shape==(512,512);self.table[str(img.resolve())]=(torch.from_numpy(im).permute(2,0,1),torch.from_numpy(mask))
 def loss(self,preds,batch):
  im=batch['img'];paths=batch['im_file'];assert im.ndim==4 and tuple(im.shape[1:])==(3,512,512) and len(paths)==im.shape[0];anchors,stride=make_anchors(preds['feats'],self.stride,.5);points=anchors*stride;assert (points>=0).all() and (points<512).all();xy=points.floor().long();ignore=[]
  for i,path in enumerate(paths):
   key=str(Path(path).resolve());assert key in self.table,'Training path is missing from immutable ignore manifest';expected,mask=self.table[key];observed=torch.round(im[i].detach().cpu()*255).to(torch.uint8);assert torch.equal(observed,expected),'Training transformed pixels; ignore masks no longer align';ignore.append(mask[xy[:,1].cpu(),xy[:,0].cpu()]);self.stats['validated_images']+=1
  ignore=torch.stack(ignore,dim=0).to(im.device)[...,None];self.bce=RegionBCE(ignore,self.stats);return super().loss(preds,batch)
