"""Smaug AI Image Detector demo: upload an image or paste a link, get the probability it is AI-generated.""" import io import ipaddress import socket import sys from urllib.parse import urljoin, urlparse import gradio as gr import requests import spaces from huggingface_hub import snapshot_download from PIL import Image MODEL = 'abacusai/Smaug-AI-Image-Detector' MAX_BYTES = 20 * 1024 * 1024 UA = 'AbacusAI-SmaugAIImageDetector/1.0 (https://huggingface.co/spaces/abacusai/Smaug-AI-Image-Detector)' FAQ = '''## Frequently asked questions **How accurate is this AI image detector?** On real-world images posted to Reddit, it catches 86.7% of AI-generated images while flagging only 5% of real photos, ahead of every other open-source detector we tested (next best: 77.4%). At its default threshold it flags 0.4–3% of real photos as AI. [Full benchmark](https://huggingface.co/abacusai/Smaug-AI-Image-Detector). **Which AI image generators does it detect?** The ones people use today, including GPT-Image 2, Nano Banana Pro, Midjourney 7, Seedream 5, FLUX.2, Z-Image, Recraft, Ideogram, ERNIE-Image, and frames from Sora 2 and Veo 3. **Is it free? Do I need an account?** Yes, it is free, with no signup. The model is open source under Apache 2.0. **What happens to my images?** They are only used to compute the score; we do not collect them or train on them. To keep images entirely on your own device, run the [open-source model](https://huggingface.co/abacusai/Smaug-AI-Image-Detector) locally: it runs on a laptop CPU, Apple Silicon, or a GPU, and there is a [GGUF build for llama.cpp](https://huggingface.co/abacusai/Smaug-AI-Image-Detector-GGUF). **Can it detect AI edits to a real photo?** Partly. Fully generated images are its strength; a real photo with a small AI-edited region may score as real. Built by [Abacus.AI](https://abacus.ai). Read the [launch post](https://blog.abacus.ai/blog/2026/10/17/smaug-ai-image-detector/). ''' path = snapshot_download(MODEL) sys.path.insert(0, path) from smaug_image_detect import SmaugImageDetect # noqa: E402 - ships with the model repo det = SmaugImageDetect.from_pretrained(path, device="cuda") # ZeroGPU: place on cuda at startup, real GPU inside @spaces.GPU @spaces.GPU(duration=10) # scoring takes ~1-2 s; a short reservation leaves more of each visitor's GPU quota def score(img): return det(img) def check_public(url): """Only fetch from public internet addresses: no localhost, private networks or cloud metadata endpoints.""" u = urlparse(url) if u.scheme not in ('http', 'https') or not u.hostname: raise gr.Error('The link must start with http:// or https://') try: addrs = {a[4][0] for a in socket.getaddrinfo(u.hostname, u.port or (443 if u.scheme == 'https' else 80))} except socket.gaierror: raise gr.Error('Could not find that website.') if not all(ipaddress.ip_address(a.split('%')[0]).is_global for a in addrs): raise gr.Error('That link does not point to a public website.') def fetch(url): try: for _ in range(4): # the link plus up to 3 redirects, each checked before it is followed check_public(url) r = requests.get(url, timeout=15, stream=True, allow_redirects=False, headers={'User-Agent': UA}) if r.is_redirect: url = urljoin(url, r.headers['Location']) continue r.raise_for_status() data = r.raw.read(MAX_BYTES + 1, decode_content=True) break else: raise gr.Error('That link redirects too many times.') except requests.RequestException as e: raise gr.Error(f'Could not download the image: {e}') if len(data) > MAX_BYTES: raise gr.Error('That image is larger than 20 MB.') try: return Image.open(io.BytesIO(data)) except Exception: raise gr.Error('That link did not return an image.') def predict(image, url): if image is None and url and url.strip(): image = fetch(url.strip()) if image is None: raise gr.Error('Upload an image or paste an image link.') if min(image.size) < 256: gr.Warning('Images smaller than 256 px are less reliable.') p = score(image) verdict = 'Likely AI-generated' if p >= 0.5 else 'Likely a real photo' return {'AI-generated': p, 'Real': 1 - p}, f'### {verdict}\nProbability AI-generated: **{p:.1%}** (threshold 50%)' with gr.Blocks(title='Smaug AI Image Detector: is this image AI-generated?') as demo: gr.Markdown('# Smaug AI Image Detector\nIs this image AI-generated? Upload one or paste a link. Free and open source: ' f'[{MODEL}](https://huggingface.co/{MODEL}) by [Abacus.AI](https://abacus.ai).') with gr.Row(): with gr.Column(): image = gr.Image(type='pil', label='Image', sources=['upload', 'clipboard']) url = gr.Textbox(label='…or an image link', placeholder='https://...') btn = gr.Button('Check', variant='primary') with gr.Column(): label = gr.Label(label='Result', num_top_classes=2) text = gr.Markdown() gr.Examples(examples=[['examples/real_photo.jpg', None], ['examples/ai_image.jpg', None]], inputs=[image, url]) gr.Markdown('A score is evidence, not proof. It can miss images from brand-new generators and may score a real photo ' 'with a small AI-edited region as real. Do not use it as the only basis for decisions about people or their work.') gr.Markdown(FAQ) btn.click(predict, [image, url], [label, text]) demo.queue(max_size=40).launch(max_file_size='20mb')