Datasets:
Download tools/audit_semantics.py from brianhu25/flickr5k: direct link, hf CLI and curl.
- Browser
- Download file 7.73 kB
-
https://huggingface.co/datasets/brianhu25/flickr5k/resolve/main/tools/audit_semantics.py
- Command line
-
hf download hf://datasets/brianhu25/flickr5k/tools/audit_semantics.py
-
curl -L -o audit_semantics.py https://huggingface.co/datasets/brianhu25/flickr5k/resolve/main/tools/audit_semantics.py
7.73 kB
| """Optional local CLIP evidence for audit_dataset.py. No remote image inference.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import tempfile | |
| import uuid | |
| from pathlib import Path | |
| import numpy as np | |
| from PIL import Image, ImageOps | |
| from tqdm import tqdm | |
| PROMPTS = { | |
| "photograph": ["a camera photograph of a real world scene", "an ordinary real photograph", "a natural photo of an indoor or outdoor scene"], | |
| "map": ["a geographic map", "a street map or satellite map screenshot", "a diagram showing a map"], | |
| "screenshot": ["a screenshot of a website or computer application", "a screenshot of a phone screen", "a computer user interface screenshot"], | |
| "document": ["a scanned document with text", "a page of printed text", "a presentation slide or infographic"], | |
| "illustration": ["a drawing or digital illustration", "a cartoon illustration", "a sketch rather than a photograph"], | |
| "painting": ["a painting or artwork", "a watercolor or oil painting", "a painted illustration"], | |
| "render": ["a computer generated 3D rendering", "a scene from a video game", "a synthetic CGI scene"], | |
| "collage": ["a collage of multiple separate photographs", "a grid of photos arranged as a montage", "a photo collage with panels and borders"], | |
| } | |
| def classify_scores(scores, margin): | |
| """Cosine evidence is prompt-relative, deliberately not presented as probability.""" | |
| top=max(scores,key=scores.get) | |
| nonphoto=max((label for label in scores if label!="photograph"),key=scores.get) | |
| delta=float(scores[nonphoto]-scores["photograph"]) | |
| flag="likely_nonphoto_"+nonphoto if delta>=margin else "ambiguous_photo_eligibility" if delta>=0 else None | |
| return dict(status="checked",top_label=top,nonphoto_margin=round(delta,6), | |
| cosine_scores={k:round(float(v),6) for k,v in scores.items()}),flag | |
| def atomic_embeddings(path, vectors, fingerprints, signature): | |
| ids=sorted(vectors) | |
| if not ids: | |
| return | |
| fd,tmp=tempfile.mkstemp(dir=path.parent,suffix=".npz") | |
| try: | |
| with os.fdopen(fd,"wb") as file: | |
| np.savez_compressed(file,ids=np.array(ids), | |
| fingerprints=np.array([fingerprints[pid] for pid in ids]), | |
| embeddings=np.stack([vectors[pid] for pid in ids]), | |
| signature=np.array(signature)) | |
| os.replace(tmp,path) | |
| finally: | |
| Path(tmp).unlink(missing_ok=True) | |
| def load_embeddings(path, rows, signature): | |
| wanted={r["photo_id"]:r["fingerprint"] for r in rows} | |
| vectors={} | |
| if path.exists(): | |
| with np.load(path,allow_pickle=False) as cache: | |
| if str(cache["signature"].item())==signature: | |
| for pid,fingerprint,vector in zip(cache["ids"],cache["fingerprints"],cache["embeddings"]): | |
| if wanted.get(str(pid))==str(fingerprint) and np.isfinite(vector).all() and np.linalg.norm(vector)>0: | |
| vector=vector.astype(np.float32) | |
| vectors[str(pid)]=vector/np.linalg.norm(vector) | |
| return vectors | |
| def semantic_audit(rows,args): | |
| # Import lazily: --skip-semantic and all lightweight tests need no ML dependencies. | |
| os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY","1") | |
| try: | |
| import torch | |
| import transformers | |
| from transformers import CLIPModel,CLIPProcessor | |
| except ImportError as exc: | |
| raise RuntimeError("Install torch and transformers, or use --skip-semantic") from exc | |
| device=args.device | |
| if device=="auto": | |
| device="cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" | |
| if device=="mps" and not torch.backends.mps.is_available(): | |
| raise RuntimeError("MPS unavailable; use --device cpu") | |
| if device=="cuda" and not torch.cuda.is_available(): | |
| raise RuntimeError("CUDA unavailable; use --device cpu") | |
| print(f"Loading local CLIP ({args.model}, {device}); first use may download model weights.",flush=True) | |
| processor=CLIPProcessor.from_pretrained(args.model,revision=args.model_revision,cache_dir=args.model_cache,use_fast=False) | |
| model=CLIPModel.from_pretrained(args.model,revision=args.model_revision,cache_dir=args.model_cache).eval().to(device) | |
| commit=getattr(model.config,"_commit_hash",None) | |
| if commit is None and re.fullmatch(r"[0-9a-f]{40}",args.model_revision): | |
| commit=args.model_revision | |
| # Without a resolved revision, cross-run embedding reuse could mix different weights. | |
| signature=json.dumps(dict(model=args.model,requested_revision=args.model_revision,commit=commit, | |
| unresolved_session=uuid.uuid4().hex if commit is None else None),sort_keys=True) | |
| readable=[r for r in rows if not r["metrics"].get("decode_error")] | |
| fingerprints={r["photo_id"]:r["fingerprint"] for r in readable} | |
| cache_path=args.out/"clip_embeddings.npz" | |
| vectors=load_embeddings(cache_path,readable,signature) | |
| texts=[prompt for group in PROMPTS.values() for prompt in group] | |
| # Forward outputs expose normalized projected embeddings in both Transformers 4/5. | |
| tokenized=processor(text=texts,return_tensors="pt",padding=True) | |
| tokenized={key:value.to(device) for key,value in tokenized.items()} | |
| text_features=None | |
| pending=[r for r in readable if r["photo_id"] not in vectors] | |
| # One cached image is forwarded if all embeddings are cached, to obtain text features. | |
| work=pending if pending else readable[:1] | |
| try: | |
| with torch.inference_mode(): | |
| for start in tqdm(range(0,len(work),args.batch_size),desc="Local CLIP",unit="batch"): | |
| batch=work[start:start+args.batch_size] | |
| images=[] | |
| for row in batch: | |
| with Image.open(args.data/"images"/f"{row['photo_id']}.jpg") as image: | |
| images.append(ImageOps.exif_transpose(image).convert("RGB")) | |
| processed=processor(images=images,return_tensors="pt") | |
| output=model(**tokenized,pixel_values=processed["pixel_values"].to(device)) | |
| if text_features is None: | |
| text_features=output.text_embeds.float().cpu().numpy() | |
| encoded=output.image_embeds.float().cpu().numpy() | |
| for row,vector in zip(batch,encoded): | |
| vectors[row["photo_id"]]=vector/np.maximum(np.linalg.norm(vector),1e-12) | |
| if start%(args.batch_size*10)==0: | |
| atomic_embeddings(cache_path,vectors,fingerprints,signature) | |
| finally: | |
| # Preserve completed batches even if interrupted. Other audit results regenerate on rerun. | |
| atomic_embeddings(cache_path,vectors,fingerprints,signature) | |
| if text_features is not None: | |
| classes=[] | |
| begin=0 | |
| for prompts in PROMPTS.values(): | |
| mean=text_features[begin:begin+len(prompts)].mean(axis=0) | |
| classes.append(mean/np.maximum(np.linalg.norm(mean),1e-12)) | |
| begin+=len(prompts) | |
| matrix=np.stack(classes) | |
| for row in readable: | |
| values=matrix @ vectors[row["photo_id"]] | |
| row["semantic"],flag=classify_scores(dict(zip(PROMPTS,values)),args.semantic_margin) | |
| if flag: | |
| row["eligibility_flags"].append(flag) | |
| return vectors,dict(status="completed",model=args.model,requested_revision=args.model_revision, | |
| resolved_commit=commit,device=device,prompts=PROMPTS, | |
| prompt_sha256=hashlib.sha256(json.dumps(PROMPTS,sort_keys=True).encode()).hexdigest(), | |
| torch_version=torch.__version__,transformers_version=transformers.__version__) | |