"""Original GenImage validation examples and dataset-label presentation.""" from pathlib import Path import hashlib import json ROOT = Path(__file__).absolute().parent SAMPLES = json.loads((ROOT / "examples/manifest.json").read_text()) GENERATOR_NAMES = { "stable_diffusion_v_1_4": "Stable Diffusion 1.4", "Midjourney": "Midjourney", "ADM": "ADM", "BigGAN": "BigGAN", } def sample_at(index): if isinstance(index, (list, tuple)): index = index[0] if ( isinstance(index, bool) or not isinstance(index, int) or not 0 <= index < len(SAMPLES) ): raise ValueError("Unknown example selection.") sample = SAMPLES[index] return sample, ROOT / "examples" / sample["file"] def gallery_items(): return [ ( str(ROOT / "examples" / sample["file"]), f"{'Real' if sample['label'] == 0 else 'Generated'} {index % 4 + 1:02d} · " + ( "ImageNet" if sample["label"] == 0 else GENERATOR_NAMES[sample["generator"]] ), ) for index, sample in enumerate(SAMPLES) ] def annotate_example(outputs, sample): metadata = { key: sample[key] for key in ( "id", "dataset", "split", "label", "label_name", "generator", "sha256", ) } outputs[4]["example"] = metadata outputs[13]["result"]["example"] = metadata label = "Real" if sample["label"] == 0 else "Generated" generator = ( "ImageNet" if sample["label"] == 0 else GENERATOR_NAMES[sample["generator"]] ) return ( f"Selected **{sample['id']}** · Dataset label: **{label}** · {generator} · " f"{sample['width']} × {sample['height']}. Model prediction scores are shown above." ) def same_image_as_state(path, state): """An example response already contains its analysis; do not clear it on File.change. Gradio copies the returned example into its file cache, so the paths can differ even though the original bytes are identical. """ if not path or not state or not state.get("path"): return False first, second = Path(path), Path(state["path"]) try: if first == second: return first.is_file() if first.stat().st_size != second.stat().st_size: return False return ( hashlib.sha256(first.read_bytes()).digest() == hashlib.sha256(second.read_bytes()).digest() ) except OSError: return False