<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by AIEngine on Medium]]></title>
        <description><![CDATA[Stories by AIEngine on Medium]]></description>
        <link>https://medium.com/@ai-engine?source=rss-075c3c29f0bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dz7IGWz4L_fKXOX8dn1FRQ.png</url>
            <title>Stories by AIEngine on Medium</title>
            <link>https://medium.com/@ai-engine?source=rss-075c3c29f0bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:14:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ai-engine/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Remove Video Background in Python with an API]]></title>
            <link>https://medium.com/@ai-engine/remove-video-background-in-python-with-an-api-aad856b6aa41?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/aad856b6aa41</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[video-editing]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 13:59:33 GMT</pubDate>
            <atom:updated>2026-11-13T13:59:33.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TjazOw6_aRsTlZ5T.jpg" /></figure><p>To remove a video background in Python, split the video into frames, send each frame to a background removal API, and rebuild the video from the cutouts. There is no green screen and no model to host. We ran the script below exactly as shown on a real stock clip.</p><blockquote><em>Want to try it on your own clip? </em><a href="https://ai-engine.net/apis/background-removal?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Get a key for the Background Removal API</em></a><em>.</em></blockquote><h3>How it works</h3><ol><li>ffmpeg extracts the frames as JPG files.</li><li>The API returns a transparent PNG for each frame.</li><li>ffmpeg rebuilds the PNG sequence into a transparent WebM and an MP4 on a solid color.</li></ol><p>You need Python with requests, ffmpeg, and a RapidAPI key saved in the RAPIDAPI_KEY environment variable.</p><h3>The complete script</h3><pre>import os<br>import subprocess<br>from concurrent.futures import ThreadPoolExecutor<br>from pathlib import Path<br>import requests<br>API_URL = &quot;https://background-removal-ai.p.rapidapi.com/remove-background&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-host&quot;: &quot;background-removal-ai.p.rapidapi.com&quot;,<br>    &quot;x-rapidapi-key&quot;: os.environ[&quot;RAPIDAPI_KEY&quot;],<br>}<br>INPUT_VIDEO = &quot;input.mp4&quot;<br>FPS = 8<br>SECONDS = 5<br>FRAMES = Path(&quot;frames&quot;)<br>CUTOUTS = Path(&quot;cutouts&quot;)<br>def extract_frames():<br>    FRAMES.mkdir(exist_ok=True)<br>    subprocess.run(<br>        [&quot;ffmpeg&quot;, &quot;-y&quot;, &quot;-v&quot;, &quot;error&quot;, &quot;-i&quot;, INPUT_VIDEO, &quot;-t&quot;, str(SECONDS),<br>         &quot;-vf&quot;, f&quot;fps={FPS}&quot;, str(FRAMES / &quot;%04d.jpg&quot;)],<br>        check=True,<br>    )<br>def remove_background(frame):<br>    with open(frame, &quot;rb&quot;) as f:<br>        response = requests.post(API_URL, headers=HEADERS, files={&quot;image&quot;: f}, timeout=120)<br>    response.raise_for_status()<br>    png = requests.get(response.json()[&quot;image_url&quot;], timeout=120)<br>    png.raise_for_status()<br>    (CUTOUTS / f&quot;{frame.stem}.png&quot;).write_bytes(png.content)<br>def process_frames():<br>    CUTOUTS.mkdir(exist_ok=True)<br>    frames = sorted(FRAMES.glob(&quot;*.jpg&quot;))<br>    with ThreadPoolExecutor(max_workers=4) as pool:<br>        list(pool.map(remove_background, frames))<br>    return len(frames)<br>def build_transparent_webm():<br>    subprocess.run(<br>        [&quot;ffmpeg&quot;, &quot;-y&quot;, &quot;-v&quot;, &quot;error&quot;, &quot;-framerate&quot;, str(FPS),<br>         &quot;-i&quot;, str(CUTOUTS / &quot;%04d.png&quot;),<br>         &quot;-c:v&quot;, &quot;libvpx-vp9&quot;, &quot;-pix_fmt&quot;, &quot;yuva420p&quot;, &quot;output_transparent.webm&quot;],<br>        check=True,<br>    )<br>def build_mp4_on_color(color=&quot;0x1E3A8A&quot;):<br>    subprocess.run(<br>        [&quot;ffmpeg&quot;, &quot;-y&quot;, &quot;-v&quot;, &quot;error&quot;, &quot;-framerate&quot;, str(FPS),<br>         &quot;-i&quot;, str(CUTOUTS / &quot;%04d.png&quot;),<br>         &quot;-filter_complex&quot;,<br>         f&quot;color=c={color}:s=960x540:r={FPS}[bg];[bg][0:v]overlay=shortest=1,format=yuv420p&quot;,<br>         &quot;output_on_color.mp4&quot;],<br>        check=True,<br>    )<br>extract_frames()<br>print(f&quot;Frames processed: {process_frames()}&quot;)<br>build_transparent_webm()<br>build_mp4_on_color()<br>print(&quot;Saved output_transparent.webm and output_on_color.mp4&quot;)</pre><p>Output on our test clip, in about 70 seconds with four parallel workers:</p><pre>Frames processed: 39<br>Saved output_transparent.webm and output_on_color.mp4</pre><h3>The result</h3><p>These are real output frames, shown on a checkerboard so you can see the transparency. The raised hand, the fingers, the hair, and the sleeves stay clean as the person moves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SPsHsdsWyrDcBFFp.jpg" /></figure><p>We also sent the same frame twice and got identical transparency masks.</p><h3>Choosing the right settings</h3><p>Each frame is one request, so requests equal FPS multiplied by SECONDS. Our clip lasts 4.84 seconds, so 8 frames per second gave 39 frames. Start with a low frame rate while you test.</p><ul><li><strong>Transparent WebM</strong>: for web overlays and editors that read VP9 alpha.</li><li><strong>MP4 on a color</strong>: for when you know the final background. Change the color argument, and the 960x540 size if your video has another resolution.</li></ul><h3>Production tips</h3><ul><li><strong>Best for</strong>: one clear subject in front of a simple backdrop, such as talking-head clips, presenters, and studio footage. Run a few seconds of your own footage first to confirm the result.</li><li><strong>Run it in a background job</strong>: use a queue and notify the user when the file is ready.</li><li><strong>Reuse the pattern</strong>: the same approach powers our <a href="https://ai-engine.net/blog/nsfw-video-moderation-python?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost">NSFW video moderation guide</a>.</li></ul><h3>Sources</h3><ul><li><a href="https://www.pexels.com/video/8627747/">Test clip on Pexels</a></li><li><a href="https://ffmpeg.org/ffmpeg-codecs.html">ffmpeg VP9 encoder documentation</a></li></ul><blockquote><em>Add it to your pipeline: grab a key from the </em><a href="https://ai-engine.net/apis/background-removal?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Background Removal API page</em></a><em> and run the script on a short clip.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/remove-video-background-python?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aad856b6aa41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Swap in Python: Batch Swap One Face onto Templates]]></title>
            <link>https://medium.com/@ai-engine/face-swap-in-python-batch-swap-one-face-onto-templates-c523e0c94ff2?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c523e0c94ff2</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 19:16:32 GMT</pubDate>
            <atom:updated>2026-11-12T19:16:32.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bRVjWPLj-JSXcxPP.jpg" /></figure><p>Personalized avatar packs and themed profile pictures need the same thing: one user’s face placed on many template images. This tutorial builds that in Python. You give the script a selfie and a folder of templates, and it saves one swapped image per template, with no GPU and no model to install.</p><p>All the code was run against the live <a href="https://ai-engine.net/apis/face-swap?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost">Face Swap API</a>, and the results shown are its real output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-XPFuNURgUkWFkQu.jpg" /></figure><h3>The batch script</h3><p>You need pip install requests, a RapidAPI key, a selfie.jpg and a templates/ folder of JPG images.</p><pre>from concurrent.futures import ThreadPoolExecutor<br>from pathlib import Path<br>import requests<br>BASE = &quot;https://deepfake-face-swap-ai.p.rapidapi.com&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-host&quot;: &quot;deepfake-face-swap-ai.p.rapidapi.com&quot;,<br>    &quot;x-rapidapi-key&quot;: &quot;YOUR_API_KEY&quot;,<br>}<br>WORKERS = 4<br>def swap_face(source_path, target_path):<br>    &quot;&quot;&quot;Swap the face from source_path onto target_path, return the result URL.&quot;&quot;&quot;<br>    with open(source_path, &quot;rb&quot;) as source, open(target_path, &quot;rb&quot;) as target:<br>        response = requests.post(<br>            f&quot;{BASE}/swap-face&quot;,<br>            headers=HEADERS,<br>            files={<br>                &quot;source_image&quot;: (&quot;source.jpg&quot;, source, &quot;image/jpeg&quot;),<br>                &quot;target_image&quot;: (&quot;target.jpg&quot;, target, &quot;image/jpeg&quot;),<br>            },<br>            timeout=120,<br>        )<br>    response.raise_for_status()<br>    return response.json()[&quot;image_url&quot;]<br>def has_face(image_path):<br>    &quot;&quot;&quot;Return True if the image contains at least one face.&quot;&quot;&quot;<br>    with open(image_path, &quot;rb&quot;) as image:<br>        response = requests.post(<br>            f&quot;{BASE}/detect-faces&quot;,<br>            headers=HEADERS,<br>            files={&quot;image&quot;: (&quot;image.jpg&quot;, image, &quot;image/jpeg&quot;)},<br>            timeout=60,<br>        )<br>    return response.ok and response.json().get(&quot;total_faces&quot;, 0) &gt; 0<br>def process_template(selfie, template, output_dir):<br>    if not has_face(template):<br>        return template.name, &quot;skipped: no face&quot;<br>    url = swap_face(selfie, template)<br>    output = output_dir / template.name<br>    output.write_bytes(requests.get(url, timeout=60).content)<br>    return template.name, f&quot;saved {output}&quot;<br>def swap_onto_templates(selfie, template_dir, output_dir):<br>    output_dir = Path(output_dir)<br>    output_dir.mkdir(exist_ok=True)<br>    templates = sorted(Path(template_dir).glob(&quot;*.jpg&quot;))<br>    with ThreadPoolExecutor(max_workers=WORKERS) as pool:<br>        jobs = [<br>            pool.submit(process_template, selfie, template, output_dir)<br>            for template in templates<br>        ]<br>        return [job.result() for job in jobs]<br>if __name__ == &quot;__main__&quot;:<br>    for name, status in swap_onto_templates(&quot;selfie.jpg&quot;, &quot;templates&quot;, &quot;output&quot;):<br>        print(f&quot;{name}: {status}&quot;)</pre><p>has_face skips any template with no face, so the batch carries on, and four worker threads run the swaps side by side.</p><h3>Real results</h3><p>One selfie and six templates: five portraits and one photo with no face, to test the skip.</p><pre>casual.jpg: saved output/casual.jpg<br>no_face.jpg: skipped: no face<br>office.jpg: saved output/office.jpg<br>outdoor.jpg: saved output/outdoor.jpg<br>sofa.jpg: saved output/sofa.jpg<br>suit.jpg: saved output/suit.jpg</pre><p>Each result keeps the template’s pose, clothes, glasses and lighting, and takes the face from the selfie.</p><h3>Using image URLs</h3><p>If your images are already hosted, send the URLs as form fields:</p><pre>import requests<br>response = requests.post(<br>    &quot;https://deepfake-face-swap-ai.p.rapidapi.com/swap-face&quot;,<br>    headers={<br>        &quot;x-rapidapi-host&quot;: &quot;deepfake-face-swap-ai.p.rapidapi.com&quot;,<br>        &quot;x-rapidapi-key&quot;: &quot;YOUR_API_KEY&quot;,<br>    },<br>    data={<br>        &quot;source_url&quot;: &quot;https://images.pexels.com/photos/614810/pexels-photo-614810.jpeg?w=800&quot;,<br>        &quot;target_url&quot;: &quot;https://images.pexels.com/photos/2182970/pexels-photo-2182970.jpeg?w=800&quot;,<br>    },<br>    timeout=120,<br>)<br>print(response.json())</pre><pre>{&#39;image_url&#39;: &#39;https://images.ai-engine.net/face-swap-ai/6ae31bb6-6517-4f79-a481-47982e2afdd5.jpg&#39;, &#39;width&#39;: 800, &#39;height&#39;: 1200, &#39;size_bytes&#39;: 131991}</pre><h3>Production tips</h3><ul><li>Copy each result to your own storage, as the script does.</li><li>Handle HTTP 422: a template with no face returns No face detected in target image.</li><li>Use front-facing or three-quarter portraits as templates for a natural result.</li></ul><h3>Use it with consent</h3><p>Only swap the face of someone who has agreed to it, which is the natural flow when users upload their own selfie. Use templates you have the rights to, tell people when an image has been generated, and never use face swap to impersonate anyone.</p><p>Test photos come from Pexels. Full tutorial with before and after images: <a href="https://ai-engine.net/blog/face-swap-python-batch-templates?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost">Face swap in Python on ai-engine.net</a>.</p><blockquote><em>Grab a key from the </em><a href="https://ai-engine.net/apis/face-swap?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Face Swap API page</em></a><em> and point the script at your own templates.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/face-swap-python-batch-templates?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c523e0c94ff2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Discord NSFW Bots to Block Explicit Images (2026)]]></title>
            <link>https://medium.com/@ai-engine/best-discord-nsfw-bots-to-block-explicit-images-2026-c58cbf9667db?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c58cbf9667db</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[content-moderation]]></category>
            <category><![CDATA[discord-bot]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 19:24:18 GMT</pubDate>
            <atom:updated>2026-11-10T19:24:18.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OMB22artAogrLkoL.jpg" /></figure><p>A single explicit image in a public channel can drive members away and put your server at risk under Discord’s rules. A Discord NSFW bot for moderation scans what people post and removes explicit images before most members see them.</p><p>We only list bots that block NSFW content, not bots that serve it. Features come from each bot’s own website, documentation or listing, checked on October 31, 2026. We did not run them side by side, so test your choice on a private server first.</p><h3>1. Moderator Bot</h3><p><a href="https://modbot.neomechanical.com/">Moderator Bot</a> says it “checks images, GIFs, stickers and video frames” and deletes NSFW media from day one. Strikes, timeouts and bans only start if you enable them. Best for servers that want broad media coverage and a quick setup.</p><h3>2. SfwBot</h3><p><a href="https://sfw.bot/features">SfwBot</a> combines image detection with hash-based blacklists, and you adjust sensitivity, whitelists and actions in a dashboard. Best for communities that want NSFW filtering and general moderation in one bot.</p><h3>3. DeGore</h3><p><a href="https://unitedweco.de/degore/">DeGore</a> scans images sent in non-NSFW channels, and its <a href="https://discordbotlist.com/bots/degore">bot listing</a> says it deletes explicit images and GIFs automatically. Best for admins who want a focused image filter. Its invite link requests Administrator permission, so review that first.</p><h3>4. Beholder</h3><p><a href="https://github.com/brainboxdotcc/beholder">Beholder</a> is open source under Apache-2.0. It reads text inside images, blocks known images by hash, detects NSFW imagery, and scans GIFs and videos. Best for technical teams that want to host the code themselves.</p><h3>5. Build Your Own with an NSFW Detection API</h3><p>A custom bot lets you decide what is removed in each server. The <a href="https://ai-engine.net/apis/nsfw-detect?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost">NSFW Detect API</a> returns top-level categories with a confidence score, so your rules fit in a small dictionary:</p><pre>import os<br>import requests<br>API_URL = &quot;https://nsfw-detect3.p.rapidapi.com/nsfw-detect&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-host&quot;: &quot;nsfw-detect3.p.rapidapi.com&quot;,<br>    &quot;x-rapidapi-key&quot;: os.environ[&quot;RAPIDAPI_KEY&quot;],<br>}<br># Your server rules: top-level category -&gt; minimum confidence to delete<br>DELETE_RULES = {<br>    &quot;Explicit&quot;: 50,<br>    &quot;Non-Explicit Nudity of Intimate parts and Kissing&quot;: 70,<br>    &quot;Violence&quot;: 70,<br>    &quot;Visually Disturbing&quot;: 70,<br>    &quot;Hate Symbols&quot;: 70,<br>    &quot;Drugs &amp; Tobacco&quot;: 80,<br>    &quot;Gambling&quot;: 80,<br>    &quot;Alcohol&quot;: 80,<br>}<br>def check_attachment(image_url):<br>    &quot;&quot;&quot;Return (&quot;delete&quot;, category, score) or (&quot;allow&quot;, None, None).&quot;&quot;&quot;<br>    response = requests.post(API_URL, headers=HEADERS, data={&quot;url&quot;: image_url})<br>    for label in response.json()[&quot;body&quot;][&quot;ModerationLabels&quot;]:<br>        minimum = DELETE_RULES.get(label[&quot;Name&quot;])<br>        if label[&quot;ParentName&quot;] == &quot;&quot; and minimum and label[&quot;Confidence&quot;] &gt;= minimum:<br>            return &quot;delete&quot;, label[&quot;Name&quot;], round(label[&quot;Confidence&quot;], 1)<br>    return &quot;allow&quot;, None, None</pre><p>We ran this function on real images through the live API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D08RLyOz92ix6cbi.jpg" /></figure><p>For the full bot with discord.py, warnings and a mod log channel, follow the <a href="https://ai-engine.net/blog/discord-nsfw-moderation-bot?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost">Discord NSFW moderation bot tutorial</a>.</p><blockquote><em>Need your own rules per category? </em><a href="https://ai-engine.net/apis/nsfw-detect?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Try the NSFW Detect API</em></a><em> on your server’s images.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/best-discord-nsfw-filter-bots?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c58cbf9667db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blur Faces in Photos Automatically with Python (GDPR)]]></title>
            <link>https://medium.com/@ai-engine/blur-faces-in-photos-automatically-with-python-gdpr-891569ec0906?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/891569ec0906</guid>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[gdpr]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 18:26:17 GMT</pubDate>
            <atom:updated>2026-11-04T18:37:57.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lAKqr9pAmFBWaPWL.jpg" /></figure><p>Street shots for a city guide, user uploads on a marketplace, a dataset for model training, a CCTV clip someone asked for under GDPR: every one of them is full of faces of people who never agreed to be published. Blurring them by hand does not scale past a few photos.</p><p>Below: how to blur faces automatically in Python. One API call finds every face, Pillow pixelates them, and the saved file drops the GPS metadata too. Every number comes from live calls on six crowded street photos and one party photo.</p><blockquote><em>Want to run it on your own photos? </em><a href="https://ai-engine.net/apis/face-analyzer?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Get a key for the Face Analyzer API</em></a><em> and point the script at a folder.</em></blockquote><h3>Why Blur Faces: What GDPR Says</h3><ul><li><strong>Anonymous data is out of scope:</strong> GDPR Recital 26 says data protection does not apply to anonymous information, judged by “all the means reasonably likely to be used” to identify someone</li><li><strong>Access requests:</strong> the EDPB video guidelines say that when someone asks for a copy of footage, other people who can be identified in it should be anonymised, for example by blurring</li><li><strong>Erasure:</strong> the same guidelines state that blurring a picture with no retroactive ability to recover the data means the personal data are considered erased</li></ul><h3>Step 1: Detect Every Face with One API Call</h3><pre>import os<br>import requests<br>from concurrent.futures import ThreadPoolExecutor<br>from PIL import Image, ImageFilter, ImageOps<br>BASE = &quot;https://faceanalyzer-ai.p.rapidapi.com&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-host&quot;: &quot;faceanalyzer-ai.p.rapidapi.com&quot;,<br>    &quot;x-rapidapi-key&quot;: &quot;YOUR_API_KEY&quot;,<br>}<br>def detect_faces(path):<br>    &quot;&quot;&quot;Return the bounding box of every face in the image (0 to 1 coordinates).&quot;&quot;&quot;<br>    with open(path, &quot;rb&quot;) as f:<br>        r = requests.post(f&quot;{BASE}/faceanalysis&quot;, headers=HEADERS, files={&quot;image&quot;: f})<br>    return [face[&quot;boundingBox&quot;] for face in r.json()[&quot;body&quot;][&quot;faces&quot;]]<br>boxes = detect_faces(&quot;photos/covered_market.jpg&quot;)<br>print(len(boxes), &quot;faces&quot;)<br># 21 faces</pre><p>A photo without anyone in it returns an empty faces list, so the rest of the script needs no special case.</p><h3>Step 2: Pixelate and Blur Each Face</h3><p>A light Gaussian blur can leave a face recognizable. Shrinking each face to an 8x8 grid first removes the detail for good, and a 25% margin covers hair, ears and chin:</p><pre>def blur_boxes(path, boxes, out_path, pad=0.25):<br>    &quot;&quot;&quot;Pixelate and blur each face box, then save without the original metadata.&quot;&quot;&quot;<br>    im = ImageOps.exif_transpose(Image.open(path)).convert(&quot;RGB&quot;)<br>    w, h = im.size<br>    for b in boxes:<br>        x1, y1 = b[&quot;topLeft&quot;][&quot;x&quot;] * w, b[&quot;topLeft&quot;][&quot;y&quot;] * h<br>        x2, y2 = b[&quot;bottomRight&quot;][&quot;x&quot;] * w, b[&quot;bottomRight&quot;][&quot;y&quot;] * h<br>        px, py = max((x2 - x1) * pad, 4), max((y2 - y1) * pad, 4)<br>        box = (<br>            int(max(0, x1 - px)), int(max(0, y1 - py)),<br>            int(min(w, x2 + px)), int(min(h, y2 + py)),<br>        )<br>        face = im.crop(box)<br>        tiny = face.resize((8, 8))  # 8x8 blocks: the facial detail is gone<br>        im.paste(tiny.resize(face.size, Image.NEAREST).filter(ImageFilter.GaussianBlur(4)), box)<br>    im.save(out_path, quality=90)  # no exif= argument: GPS and camera data are dropped</pre><ul><li><strong>Metadata is dropped:</strong> a test photo with GPS coordinates came out with an empty EXIF block</li><li><strong>Phone photos stay upright:</strong> the API reads the orientation tag, and exif_transpose rotates the pixels the same way before the blur</li><li><strong>Tiny faces stay covered:</strong> the 4-pixel minimum margin handles faces a few pixels wide</li></ul><h3>Step 3: Blur a Whole Folder in Parallel</h3><pre>def anonymize(path, out_dir=&quot;blurred&quot;):<br>    &quot;&quot;&quot;Detect and blur every face in one photo.&quot;&quot;&quot;<br>    boxes = detect_faces(path)<br>    blur_boxes(path, boxes, os.path.join(out_dir, os.path.basename(path)))<br>    return os.path.basename(path), len(boxes)<br>os.makedirs(&quot;blurred&quot;, exist_ok=True)<br>photos = sorted(os.path.join(&quot;photos&quot;, n) for n in os.listdir(&quot;photos&quot;))<br>with ThreadPoolExecutor(max_workers=4) as pool:<br>    for name, count in pool.map(anonymize, photos):<br>        print(name, count, &quot;faces blurred&quot;)<br># city_market.jpg 17 faces blurred<br># covered_market.jpg 21 faces blurred<br># crowded_street.jpg 22 faces blurred<br># london_street.jpg 19 faces blurred<br># road_crossing.jpg 24 faces blurred<br># zurich_crossing.jpg 20 faces blurred</pre><p>123 faces in about 3.5 seconds, including faces in profile, under a cap and a few pixels wide at the back of the crowd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bDoGPgn5Q2yCmFH4.jpg" /></figure><h3>Why Not OpenCV Haar Cascades?</h3><p>We ran the usual haarcascade_frontalface_default.xml setup (scaleFactor=1.1, minNeighbors=5) on the same seven photos. Haar boxes vs API faces:</p><ul><li><strong>city_market.jpg:</strong> 0 vs 17</li><li><strong>covered_market.jpg:</strong> 8 boxes (3 not faces) vs 21</li><li><strong>crowded_street.jpg:</strong> 4 vs 22</li><li><strong>london_street.jpg:</strong> 1 vs 19</li><li><strong>road_crossing.jpg:</strong> 3 vs 24</li><li><strong>zurich_crossing.jpg:</strong> 3 vs 20</li><li><strong>party.jpg (5 people):</strong> 7 boxes (2 not faces) vs 5</li></ul><p>The cascade boxed a shop sign, a pair of shorts, a snack packet, a coat and a shoe. For anonymization, a missed face is the failure that matters: it gets published as is.</p><h3>Blur Everyone Except One Person</h3><p>For access requests, the person who asked gets a copy where everyone else is blurred. /compare-faces takes a reference photo and the scene, and splits the faces of the scene into matchedFaces and unmatchedFaces:</p><pre>def blur_all_except(reference_path, photo_path, out_path):<br>    &quot;&quot;&quot;Blur every face in the photo except the person in the reference photo.&quot;&quot;&quot;<br>    with open(reference_path, &quot;rb&quot;) as ref, open(photo_path, &quot;rb&quot;) as photo:<br>        r = requests.post(<br>            f&quot;{BASE}/compare-faces&quot;,<br>            headers=HEADERS,<br>            files={&quot;source_image&quot;: ref, &quot;target_image&quot;: photo},<br>        )<br>    body = r.json()[&quot;body&quot;]<br>    others = [face[&quot;boundingBox&quot;] for face in body[&quot;unmatchedFaces&quot;]]<br>    blur_boxes(photo_path, others, out_path)<br>    # The margin around a neighbour can spill onto the kept face: paste it back<br>    original = ImageOps.exif_transpose(Image.open(photo_path)).convert(&quot;RGB&quot;)<br>    out = Image.open(out_path)<br>    w, h = out.size<br>    for face in body[&quot;matchedFaces&quot;]:<br>        b = face[&quot;boundingBox&quot;]<br>        box = (<br>            int(b[&quot;topLeft&quot;][&quot;x&quot;] * w), int(b[&quot;topLeft&quot;][&quot;y&quot;] * h),<br>            int(b[&quot;bottomRight&quot;][&quot;x&quot;] * w), int(b[&quot;bottomRight&quot;][&quot;y&quot;] * h),<br>        )<br>        out.paste(original.crop(box), box)<br>    out.save(out_path, quality=90)<br>    return len(body[&quot;matchedFaces&quot;]), len(others)<br>kept, blurred = blur_all_except(&quot;requester.jpg&quot;, &quot;party.jpg&quot;, &quot;party_for_requester.jpg&quot;)<br>print(kept, &quot;kept,&quot;, blurred, &quot;blurred&quot;)<br># 1 kept, 4 blurred</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/0*bAwmBu3qSiU3xnOz.jpg" /></figure><p>Blur matchedFaces instead and you get the reverse: hide one person who withdrew consent and leave the rest untouched.</p><blockquote><em>The </em><a href="https://ai-engine.net/blog/blur-faces-in-images-python?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>full guide on ai-engine.net</em></a><em> covers use cases, video and more production details.</em></blockquote><h3>Production Tips</h3><ul><li><strong>Blur before storage:</strong> a CSS blur leaves the original on your server and in the browser cache</li><li><strong>Check the other clues:</strong> name badges, license plates and screens can identify someone as surely as a face</li><li><strong>Keep the margin:</strong> raise it for close-up portraits where the hairstyle alone is recognizable</li><li><strong>Video:</strong> extract frames, run the same function and reassemble</li></ul><h3>Sources</h3><ul><li><a href="https://gdpr-info.eu/recitals/no-26/">GDPR Recital 26</a>: anonymous information and identifiability</li><li><a href="https://www.edpb.europa.eu/our-work-tools/our-documents/guidelines/guidelines-32019-processing-personal-data-through-video_en">EDPB Guidelines 3/2019 on video devices</a>: version 2.0, paragraphs 96 and 103</li><li>Test photos on Pexels by Th2city Santana, BabijaPhoto JB, Christopher Ugale, Ivan Aguilar, Mâide Arslan, Gije Cho and Polina Tankilevitch</li></ul><blockquote><em>Blur the faces in your own photos tonight: grab a key from the </em><a href="https://ai-engine.net/apis/face-analyzer?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Face Analyzer API page</em></a><em> and run the script on a folder.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/blur-faces-in-images-python?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=891569ec0906" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[face-api.js Alternative: Face Recognition in Node.js]]></title>
            <link>https://medium.com/@ai-engine/face-api-js-alternative-face-recognition-in-node-js-35b6ec4551e3?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/35b6ec4551e3</guid>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 09:09:11 GMT</pubDate>
            <atom:updated>2026-11-03T09:09:11.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iEWsyGdF7O6XL1Rd.jpg" /></figure><p>If you are looking for a face-api.js alternative, you are probably maintaining a project built on it. face-api.js made face recognition in JavaScript easy in 2019, but its last release (0.22.2) shipped in March 2020 and still pins TensorFlow.js core 1.7.0. The best-known fork, @vladmandic/face-api, is now archived too.</p><p>Below: how to replace it with a face recognition API in Node.js 20 (built-in fetch and FormData, no SDK, no model weights), with code we ran against the live API.</p><blockquote><em>Want to run it on your own photos? </em><a href="https://ai-engine.net/apis/face-analyzer?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Get a key for the Face Analyzer API</em></a><em> and copy the helper below.</em></blockquote><h3>Where face-api.js Stands in 2026</h3><ul><li><strong>face-api.js:</strong> last release 0.22.2 on 22 March 2020, on @tensorflow/tfjs-core 1.7.0</li><li><strong>@vladmandic/face-api:</strong> archived on GitHub, last updated in February 2025</li><li><strong>Usage:</strong> still about 465,000 and 518,000 npm downloads a month</li></ul><p>In Node.js, face-api.js also needs canvas (native), @tensorflow/tfjs-node, a monkeyPatch call and model weights loaded from disk. Every Node.js upgrade can break one of those pieces.</p><h3>face-api.js Calls Mapped to API Endpoints</h3><ul><li>nets.*.loadFromDisk(&quot;./models&quot;) → nothing to load</li><li>detectAllFaces().withFaceLandmarks() → /faceanalysis (boundingBox, landmarks)</li><li>.withAgeAndGender(), .withFaceExpressions() → /faceanalysis (AgeRange, Gender, Emotions, Smile, Eyeglasses)</li><li>euclideanDistance(d1, d2) &lt; 0.6 → /compare-faces (matchedFaces, unmatchedFaces)</li><li>new FaceMatcher(labeledDescriptors) → /save-face-in-repository with an external_id label</li><li>faceMatcher.findBestMatch() → /search-face-in-repository (label + Similarity 0 to 100)</li></ul><h3>Step 1: One Helper for Every Endpoint</h3><pre>// face.mjs<br>import { openAsBlob } from &quot;node:fs&quot;;<br>const BASE = &quot;https://faceanalyzer-ai.p.rapidapi.com&quot;;<br>const HEADERS = {<br>  &quot;x-rapidapi-host&quot;: &quot;faceanalyzer-ai.p.rapidapi.com&quot;,<br>  &quot;x-rapidapi-key&quot;: process.env.RAPIDAPI_KEY,<br>};<br>export async function callApi(endpoint, files = {}, fields = {}) {<br>  const form = new FormData();<br>  for (const [name, path] of Object.entries(files)) {<br>    form.append(name, await openAsBlob(path), path);<br>  }<br>  for (const [name, value] of Object.entries(fields)) {<br>    form.append(name, value);<br>  }<br>  const res = await fetch(`${BASE}${endpoint}`, {<br>    method: &quot;POST&quot;,<br>    headers: HEADERS,<br>    body: form,<br>  });<br>  return (await res.json()).body;<br>}</pre><h3>Step 2: Face Detection and Attributes</h3><pre>import { callApi } from &quot;./face.mjs&quot;;<br>const { faces } = await callApi(&quot;/faceanalysis&quot;, { image: &quot;team.jpg&quot; });<br>console.log(faces.length, &quot;faces&quot;);<br>for (const face of faces) {<br>  const { Gender, Eyeglasses, Emotions } = face.facialFeatures;<br>  console.log(Gender, Eyeglasses ? &quot;glasses&quot; : &quot;no glasses&quot;, Emotions.join(&quot;, &quot;));<br>}<br>// 5 faces<br>// Female glasses HAPPY<br>// Male no glasses HAPPY<br>// Male glasses HAPPY<br>// Male glasses CALM<br>// Female no glasses HAPPY</pre><p>Each face also has a boundingBox (0 to 1), AgeRange, Smile, Sunglasses and landmarks. No face means an empty faces list.</p><h3>Step 3: Compare Two Faces</h3><pre>import { callApi } from &quot;./face.mjs&quot;;<br>async function samePerson(sourcePath, targetPath) {<br>  const body = await callApi(&quot;/compare-faces&quot;, {<br>    source_image: sourcePath,<br>    target_image: targetPath,<br>  });<br>  return body.matchedFaces.length &gt; 0;<br>}<br>console.log(await samePerson(&quot;alex_badge.jpg&quot;, &quot;alex_today.jpg&quot;)); // true<br>console.log(await samePerson(&quot;alex_badge.jpg&quot;, &quot;maya.jpg&quot;));       // false</pre><p>No threshold to tune. One result surprised us: on a photo of a colleague, the API found Alex again, out of focus in the background and half hidden behind the colleague’s arm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QUYSwc8NOM_3zhIY.jpg" /></figure><h3>Step 4: Replace FaceMatcher with a Face Repository</h3><pre>import { callApi } from &quot;./face.mjs&quot;;<br>const REPO = &quot;team-faces&quot;;<br>await callApi(&quot;/create-facial-repository&quot;, {}, { repository_id: REPO });<br>const team = { alex: &quot;alex_badge.jpg&quot;, maya: &quot;maya.jpg&quot;, sam: &quot;sam.jpg&quot; };<br>for (const [label, path] of Object.entries(team)) {<br>  await callApi(&quot;/save-face-in-repository&quot;, { image: path }, {<br>    repository_id: REPO,<br>    external_id: label,<br>    max_faces: &quot;1&quot;,<br>  });<br>}<br>async function whoIs(path) {<br>  const { FaceMatches = [] } = await callApi(<br>    &quot;/search-face-in-repository&quot;,<br>    { image: path },<br>    { repository_id: REPO },<br>  );<br>  const best = FaceMatches.reduce(<br>    (a, b) =&gt; (!a || b.Similarity &gt; a.Similarity ? b : a),<br>    null,<br>  );<br>  return best &amp;&amp; best.Similarity &gt;= 90<br>    ? `${best.ExternalImageId} (${best.Similarity.toFixed(2)})`<br>    : &quot;unknown&quot;;<br>}<br>console.log(await whoIs(&quot;alex_office.jpg&quot;)); // alex (100.00)<br>console.log(await whoIs(&quot;visitor.jpg&quot;));     // unknown</pre><p>The whole script, including enrolling three people, ran in about 3.4 seconds.</p><blockquote><em>The </em><a href="https://ai-engine.net/blog/face-api-js-alternative?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>full guide on ai-engine.net</em></a><em> adds an Express route so browser uploads keep working without exposing your API key.</em></blockquote><h3>Migration Tips</h3><ul><li><strong>Remove the native dependencies:</strong> drop face-api.js, canvas, @tensorflow/tfjs-node and the models folder</li><li><strong>Re-enroll, do not convert:</strong> run your reference photos through /save-face-in-repository with your existing labels</li><li><strong>Scale boxes by image size:</strong> coordinates come back from 0 to 1</li><li><strong>Keep the key server side:</strong> read it from process.env</li><li><strong>Handle empty results:</strong> show “no face found” instead of an error</li></ul><h3>Sources</h3><ul><li><a href="https://github.com/justadudewhohacks/face-api.js">face-api.js on GitHub</a> and <a href="https://www.npmjs.com/package/face-api.js">on npm</a></li><li><a href="https://github.com/vladmandic/face-api">@vladmandic/face-api on GitHub</a>: archived fork</li><li><a href="https://nodejs.org/api/fs.html#fsopenasblobpath-options">Node.js fs.openAsBlob</a></li></ul><blockquote><em>Move off face-api.js this week: grab a key from the </em><a href="https://ai-engine.net/apis/face-analyzer?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Face Analyzer API page</em></a><em> and run the scripts on your own photos.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/face-api-js-alternative?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35b6ec4551e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detect Duplicate Accounts with a Face Search API]]></title>
            <link>https://medium.com/@ai-engine/detect-duplicate-accounts-with-a-face-search-api-29bfb877d85d?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/29bfb877d85d</guid>
            <category><![CDATA[fraud-prevention]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[face-recognition]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 20:08:15 GMT</pubDate>
            <atom:updated>2026-10-31T20:08:15.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tHTqk4wDwIAJIMaD.jpg" /></figure><p>Your referral bonus is being farmed. One person opens ten accounts with ten email addresses, ten prepaid SIMs and a VPN, collects the signup credit on each, and your fraud rules see ten different users. Email, phone and device checks all fail for the same reason: those signals are cheap to rotate. A face is not.</p><p>The fix is a face search at signup: index every verified user’s selfie once, then search each new selfie against that index before the account is created. Below is the full check in Python, with real similarity scores from live calls and the threshold we picked from them.</p><blockquote><em>Want to see the scores on your own photos? </em><a href="https://ai-engine.net/apis/face-analyzer?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Try the Face Analyzer API</em></a><em> with two photos of the same person.</em></blockquote><h3>Where Multi-Accounting Costs You Money</h3><ul><li><strong>Referral and signup bonuses</strong>: fintech apps, wallets and delivery platforms paying credit per new user</li><li><strong>Free-trial abuse</strong>: SaaS and AI tools where a new account resets the free quota</li><li><strong>Banned users coming back</strong>: marketplaces, dating apps and gig platforms where a removed seller or scammer registers again</li><li><strong>Betting and gaming</strong>: bonus hunting, and self-excluded players who must not reopen an account</li><li><strong>Fake reviews</strong>: one person running several buyer accounts to boost their own listings</li></ul><p>If your onboarding already asks for a selfie (for eKYC or a profile photo), you already have the input. The missing piece is a one-to-many search across everyone who signed up before.</p><h3>1:N Search, Not 1:1 Comparison</h3><p>A face comparison answers “are these two photos the same person?”. Duplicate detection asks “is this person anywhere among my existing users?”. Comparing a new selfie against every user one pair at a time does not scale.</p><p>A face repository does. You save each verified face once, with your own user ID as the label (external_id). A search returns the matching labels and a Similarity score from 0 to 100 in a single call.</p><p>The signup flow:</p><ol><li>Create one face repository for your user base (once)</li><li>On signup, search the new selfie in the repository</li><li>Match above the threshold: hold the signup for review, show which account matched</li><li>No match: create the account, save the face with the new user ID, store the returned face ID</li><li>No face in the photo: ask for a retake</li></ol><p>Duplicates are never indexed, so a repeat offender cannot add a second entry.</p><h3>The Signup Check in Python</h3><pre>import requests<br>API = &quot;https://faceanalyzer-ai.p.rapidapi.com&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-host&quot;: &quot;faceanalyzer-ai.p.rapidapi.com&quot;,<br>    &quot;x-rapidapi-key&quot;: &quot;YOUR_API_KEY&quot;,<br>}<br>REPO = &quot;signup-faces&quot;<br>DUPLICATE_THRESHOLD = 95.0<br>def search_face(selfie_path):<br>    with open(selfie_path, &quot;rb&quot;) as f:<br>        r = requests.post(<br>            f&quot;{API}/search-face-in-repository&quot;,<br>            headers=HEADERS,<br>            files={&quot;image&quot;: f},<br>            data={&quot;repository_id&quot;: REPO},<br>        )<br>    body = r.json()[&quot;body&quot;]<br>    if &quot;error&quot; in body:<br>        raise ValueError(body[&quot;error&quot;])  # e.g. no face in the photo<br>    return body[&quot;FaceMatches&quot;]<br>def index_face(user_id, selfie_path):<br>    with open(selfie_path, &quot;rb&quot;) as f:<br>        r = requests.post(<br>            f&quot;{API}/save-face-in-repository&quot;,<br>            headers=HEADERS,<br>            files={&quot;image&quot;: f},<br>            data={&quot;repository_id&quot;: REPO, &quot;external_id&quot;: user_id, &quot;max_faces&quot;: 1},<br>        )<br>    return r.json()[&quot;body&quot;][&quot;FacesId&quot;][0]<br>def check_signup(user_id, selfie_path):<br>    try:<br>        matches = search_face(selfie_path)<br>    except ValueError:<br>        return {&quot;decision&quot;: &quot;retake_selfie&quot;}<br>    duplicates = [m for m in matches if m[&quot;Similarity&quot;] &gt;= DUPLICATE_THRESHOLD]<br>    if duplicates:<br>        return {<br>            &quot;decision&quot;: &quot;review&quot;,<br>            &quot;matched_accounts&quot;: [<br>                (m[&quot;ExternalImageId&quot;], round(m[&quot;Similarity&quot;], 2)) for m in duplicates<br>            ],<br>        }<br>    face_id = index_face(user_id, selfie_path)<br>    return {&quot;decision&quot;: &quot;approve&quot;, &quot;face_id&quot;: face_id}<br>print(check_signup(&quot;user_7731&quot;, &quot;selfie.jpg&quot;))</pre><p>Create the repository once with a POST to /create-facial-repository and repository_id=signup-faces.</p><p>Two details the code handles: pass max_faces on the save call (1 for a signup selfie), and read the result from body, where errors are reported under an error key.</p><h3>Real Results: 5 Users, 3 New Signups</h3><p>We indexed five existing users (anonymous stock models), then ran check_signup on three new signups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d6pH2mR6dWs_5hsO.jpg" /></figure><ul><li><strong>Second photo of user_1001</strong> (other outfit, background, expression): matched user_1001 at 99.99, held for review</li><li><strong>Second photo of user_1003</strong>: matched user_1003 at 100.0, held for review</li><li><strong>Never indexed person</strong>: no match, account created and indexed</li><li><strong>Photo with no face</strong>: retake requested</li></ul><p>When we indexed the same woman under a second ID, the next search returned both accounts. A face that maps to three accounts is a fraud ring, not a coincidence.</p><blockquote><em>See the </em><a href="https://ai-engine.net/blog/detect-duplicate-accounts-face-search?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>full guide with the cURL calls, the raw JSON response and the deletion code</em></a><em> on ai-engine.net.</em></blockquote><h3>Choosing a Similarity Threshold</h3><p>We searched degraded copies of photos whose owners were indexed from a different picture:</p><ul><li>Different photo, full resolution: 99.62 to 99.9998</li><li>Downscaled 14x (face about 30 px wide): 99.49</li><li>Heavy blur: 99.98</li><li>Grayscale: 99.98</li><li>Rotated 90 degrees: 99.99</li><li>11 different people who were not indexed: no match returned at all</li></ul><p>True duplicates land very close to 100. Unrelated faces do not come back with a low score: the search only returns candidates above an internal floor, so they produce an empty list. A threshold of 95 sits far below every genuine duplicate we measured.</p><ul><li><strong>Review, do not auto-ban.</strong> Some returning users have a legitimate reason (a forgotten login, a new email address); a human decides in seconds.</li><li><strong>Show the reviewer the matched account</strong> and its status. A match to a banned account is a stronger signal than a match to an active one.</li><li><strong>Combine with your other signals.</strong> Same face plus same device or card is a near-certain duplicate.</li></ul><h3>Privacy, Consent and Deletion</h3><p>A face used to recognize a person is biometric data: a special category under GDPR Article 9, and covered in the US by laws such as Illinois’ Biometric Information Privacy Act.</p><ul><li>Ask for explicit consent at the selfie step and state the purpose</li><li>Keep the face index, not the photos</li><li>Label faces with an opaque user ID, never a name or email</li><li>Delete on request and on account closure, using the face ID you stored:</li></ul><pre>def erase_user(face_id):<br>    r = requests.post(<br>        f&quot;{API}/delete-face-from-repository&quot;,<br>        headers=HEADERS,<br>        data={&quot;repository_id&quot;: REPO, &quot;face_ids&quot;: [face_id]},<br>    )<br>    return r.json()[&quot;body&quot;]  # {&quot;message&quot;: &quot;OK&quot;}</pre><p>After deleting an indexed user, a new search with their photo returned an empty list.</p><h3>Scaling Notes</h3><ul><li>Two calls per genuine new user (search + save), one per flagged duplicate. Logins never touch the API.</li><li>One search per signup whatever the size of your user base: no loop over users in your code.</li><li>One repository per product or region if your data must stay separated.</li><li>Backfill existing users who already gave a selfie, with consent.</li><li>Keep a liveness check in front for high-risk flows: the search says a face is known, not that the selfie is live.</li></ul><h3>Sources</h3><ul><li><a href="https://gdpr-info.eu/art-4-gdpr/">GDPR Article 4</a>: definition of biometric data, including facial images used for unique identification</li><li><a href="https://gdpr-info.eu/art-9-gdpr/">GDPR Article 9</a>: special categories of personal data</li><li><a href="https://gdpr-info.eu/art-17-gdpr/">GDPR Article 17</a>: right to erasure</li><li><a href="https://www.ilga.gov/legislation/ilcs/ilcs3.asp?ActID=3004&amp;ChapterID=57">Illinois Biometric Information Privacy Act</a>: consent and retention rules for biometric identifiers</li></ul><blockquote><em>Ready to add it to your signup? Grab a key from the </em><a href="https://ai-engine.net/apis/face-analyzer?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Face Analyzer API page</em></a><em>, create a repository and run the check on a few photos of the same person.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/detect-duplicate-accounts-face-search?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29bfb877d85d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NSFW Filter for AI-Generated Images: Check Before You Show]]></title>
            <link>https://medium.com/@ai-engine/nsfw-filter-for-ai-generated-images-check-before-you-show-6562224fe0a2?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6562224fe0a2</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[content-moderation]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 19:52:02 GMT</pubDate>
            <atom:updated>2026-10-30T19:52:02.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l2oTseQ59K8SxJqh.jpg" /></figure><p>If your product generates images (an avatar app, an AI art tool, an ad creative generator, a chatbot that draws), every output is content you publish. An NSFW filter for AI-generated images checks each output before a user sees it, so a bad generation becomes a retry instead of a screenshot on social media.</p><p>Every image in this article was produced by a text-to-image model and scored by a live moderation API. The numbers are real responses.</p><blockquote><em>Want to see how your own generations score? </em><a href="https://ai-engine.net/apis/nsfw-detect?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Run them through the NSFW Detect API</em></a><em> and compare the labels.</em></blockquote><h3>Why Prompt Filters and Built-in Checkers Are Not Enough</h3><ul><li><strong>Harmless prompts can produce unsafe images.</strong> Models fill in details nobody asked for: a moody street scene comes back with a cigarette in hand.</li><li><strong>Users route around word lists</strong> with misspellings, other languages and image-to-image uploads.</li><li><strong>Built-in checkers are coarse.</strong> The Stable Diffusion safety checker in Hugging Face diffusers returns one boolean per image (or None when it is not loaded), and the pipeline accepts safety_checker=None. A yes/no flag cannot tell alcohol from nudity.</li><li><strong>Hosted providers moderate on their terms</strong>, and their policy changes when you switch provider. Your platform still owns what it shows.</li></ul><h3>Where the Check Goes</h3><ol><li>Prompt filter (cheap, stops obvious abuse)</li><li>Generate the image</li><li><strong>Moderate the generated bytes</strong></li><li>Only then: storage, CDN, client</li></ol><p>The common mistake is uploading to a public bucket first and moderating from the URL. If the check fails, the image is already public.</p><h3>Step 1: Moderate the Generated Bytes</h3><pre>import requests<br>NSFW_URL = &quot;https://nsfw-detect3.p.rapidapi.com/nsfw-detect&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-key&quot;: &quot;YOUR_API_KEY&quot;,<br>    &quot;x-rapidapi-host&quot;: &quot;nsfw-detect3.p.rapidapi.com&quot;,<br>}<br>def moderate(image_bytes, filename=&quot;output.png&quot;):<br>    &quot;&quot;&quot;Send generated image bytes to the moderation API, return its labels.&quot;&quot;&quot;<br>    r = requests.post(<br>        NSFW_URL,<br>        headers=HEADERS,<br>        files={&quot;image&quot;: (filename, image_bytes, &quot;image/png&quot;)},<br>        timeout=30,<br>    )<br>    r.raise_for_status()<br>    return r.json()[&quot;body&quot;][&quot;ModerationLabels&quot;]</pre><p>On a generated photo of a man smoking, the API returned Smoking under Drugs &amp; Tobacco Paraphernalia &amp; Use under Drugs &amp; Tobacco, all at 97.1%. The label with an empty ParentName is the top-level category, and that is what your policy should key on: a generated joint and grinder came back under the sub-label Pills, but its top-level category was still Drugs &amp; Tobacco at 99.7%.</p><h3>Step 2: A Policy Built for Generated Content</h3><p>For a general-audience avatar app:</p><ul><li><strong>Block:</strong> Explicit, Non-Explicit Nudity of Intimate parts and Kissing, Violence, Visually Disturbing, Hate Symbols, Drugs &amp; Tobacco</li><li><strong>Review:</strong> Swimwear or Underwear, Gambling, Rude Gestures</li><li><strong>Allow:</strong> Alcohol (and anything not listed)</li></ul><p>An adult (18+) art platform flips several of these: nudity and swimwear allowed, Explicit reviewed per its terms, violence and hate symbols still blocked.</p><pre># Top-level category -&gt; (action, minimum confidence). Absent = allowed.<br>POLICY = {<br>    &quot;Explicit&quot;: (&quot;block&quot;, 50),<br>    &quot;Non-Explicit Nudity of Intimate parts and Kissing&quot;: (&quot;block&quot;, 50),<br>    &quot;Violence&quot;: (&quot;block&quot;, 60),<br>    &quot;Visually Disturbing&quot;: (&quot;block&quot;, 60),<br>    &quot;Hate Symbols&quot;: (&quot;block&quot;, 40),<br>    &quot;Drugs &amp; Tobacco&quot;: (&quot;block&quot;, 60),<br>    &quot;Swimwear or Underwear&quot;: (&quot;review&quot;, 60),<br>    &quot;Gambling&quot;: (&quot;review&quot;, 50),<br>    &quot;Rude Gestures&quot;: (&quot;review&quot;, 60),<br>}<br>def decide(labels):<br>    verdict, reasons = &quot;allow&quot;, []<br>    for label in labels:<br>        if label[&quot;ParentName&quot;]:  # keep top-level categories only<br>            continue<br>        rule = POLICY.get(label[&quot;Name&quot;])<br>        if not rule or label[&quot;Confidence&quot;] &lt; rule[1]:<br>            continue<br>        reasons.append(f&quot;{label[&#39;Name&#39;]} ({label[&#39;Confidence&#39;]:.1f}%)&quot;)<br>        if rule[0] == &quot;block&quot;:<br>            verdict = &quot;block&quot;<br>        elif verdict == &quot;allow&quot;:<br>            verdict = &quot;review&quot;<br>    return verdict, reasons</pre><p>The thresholds are set per category, so one table covers every style your generator produces. In our run, the illustrated casino was caught as Gambling and sent to review, the wine dinner passed and the cannabis scene was blocked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5DcRYAPk_rPzsC9Y.jpg" /></figure><blockquote><em>See the </em><a href="https://ai-engine.net/blog/nsfw-filter-ai-generated-images?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>full guide with the policy table and the measured latency numbers</em></a><em> on ai-engine.net.</em></blockquote><h3>Step 3: generate_safely() With Retries and an Audit Log</h3><pre>import hashlib<br>import json<br>import random<br>import time<br>def audit(record):<br>    with open(&quot;moderation_audit.jsonl&quot;, &quot;a&quot;) as f:<br>        f.write(json.dumps(record) + &quot;\n&quot;)<br>def generate_safely(prompt, generate, user_id, max_attempts=3):<br>    &quot;&quot;&quot;generate(prompt, seed) is your image model or provider, returning PNG bytes.&quot;&quot;&quot;<br>    for attempt in range(1, max_attempts + 1):<br>        seed = random.randint(0, 2**31 - 1)<br>        image = generate(prompt, seed)<br>        started = time.time()<br>        try:<br>            verdict, reasons = decide(moderate(image))<br>        except requests.RequestException as e:<br>            verdict, reasons = &quot;review&quot;, [f&quot;moderation unavailable: {e}&quot;]  # fail closed<br>        audit({<br>            &quot;ts&quot;: time.time(), &quot;user&quot;: user_id, &quot;prompt&quot;: prompt, &quot;seed&quot;: seed,<br>            &quot;attempt&quot;: attempt, &quot;verdict&quot;: verdict, &quot;reasons&quot;: reasons,<br>            &quot;sha256&quot;: hashlib.sha256(image).hexdigest(),<br>            &quot;check_ms&quot;: round((time.time() - started) * 1000),<br>        })<br>        if verdict == &quot;allow&quot;:<br>            return {&quot;status&quot;: &quot;ok&quot;, &quot;image&quot;: image, &quot;seed&quot;: seed}<br>        if verdict == &quot;review&quot;:<br>            return {&quot;status&quot;: &quot;held_for_review&quot;, &quot;seed&quot;: seed, &quot;reasons&quot;: reasons}<br>        # blocked: discard this image and try a new seed<br>    return {&quot;status&quot;: &quot;refused&quot;, &quot;reasons&quot;: reasons}</pre><ul><li><strong>Block means regenerate, not error.</strong> A new seed often gives a clean image for a benign prompt. Cap the attempts: each retry costs a generation.</li><li><strong>Review means hold</strong> until a moderator approves.</li><li><strong>Fail closed.</strong> If moderation errors, the image goes to review, never straight to the user.</li><li><strong>Log the decision, not the image.</strong> Prompt, seed, verdict, reasons and a SHA-256 answer “why was this shown?” months later.</li></ul><p>A user whose prompts hit refused several times an hour is probing your filter. Count refusals per user from the audit log and act on the pattern.</p><h3>Latency</h3><p>Measured end to end: about 0.8 seconds for a 140 KB JPEG, about 1.3 seconds for a 1.2 MB PNG straight from the generator. Generation takes several seconds, so the check is a small slice of the wait. Moderate the exact bytes you publish: if you serve JPEGs, check the JPEG.</p><h3>The Rules Are Tightening</h3><ul><li><strong>Google Play’s AI-Generated Content policy</strong> requires generative AI apps to prevent restricted content and to offer in-app reporting or flagging.</li><li><strong>EU AI Act, Article 50</strong> requires machine-readable marking of synthetic images, applicable from 2 August 2026. It is a transparency duty, but an audit trail of what your system produced helps answer it.</li></ul><h3>Production Tips</h3><ul><li>Calibrate on your own presets: run a few hundred outputs per style through the API and tune the per-category thresholds.</li><li>Start strict, then relax: send borderline categories to review first, then move them to allow or block.</li><li>Extend to video: generated clips use the same policy on sampled frames (<a href="https://ai-engine.net/blog/nsfw-video-moderation-python?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost">NSFW video and GIF moderation in Python</a>).</li></ul><h3>Sources</h3><ul><li><a href="https://support.google.com/googleplay/android-developer/answer/13985936">Google Play: Understanding the AI-Generated Content policy</a></li><li><a href="https://artificialintelligenceact.eu/article/50/">EU AI Act, Article 50</a></li><li><a href="https://huggingface.co/docs/diffusers/en/api/pipelines/stable_diffusion/text2img">Hugging Face diffusers: StableDiffusionPipeline</a></li></ul><blockquote><em>Point the wrapper at your own generator and </em><a href="https://ai-engine.net/apis/nsfw-detect?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>try the NSFW Detect API on your outputs</em></a><em> before real users arrive.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/nsfw-filter-ai-generated-images?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6562224fe0a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can AI Make Transparent PNGs? Gemini, ChatGPT, Grok]]></title>
            <link>https://medium.com/@ai-engine/can-ai-make-transparent-pngs-gemini-chatgpt-grok-f50532220071?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f50532220071</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 19:14:27 GMT</pubDate>
            <atom:updated>2026-10-25T19:14:27.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BTp47RLtM5j6dB88.jpg" /></figure><p>You asked an image generator for a logo, a sticker or a product mockup “on a transparent background”, downloaded the PNG, dropped it on your site, and got a white box or a grey checkerboard around it. Most AI image tools cannot output a real alpha channel, and the ones that try often paint the checkerboard into the pixels.</p><p>Here is the answer tool by tool, a way to check whether a file is really transparent, and a Python fix that turns any AI-generated image into a true transparent PNG.</p><blockquote><em>Want to test it on your own generated images? </em><a href="https://ai-engine.net/apis/background-removal?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Try the Background Removal API</em></a><em> on one of them.</em></blockquote><h3>Which AI Image Generators Support Transparency?</h3><p>Based on each tool’s official documentation, checked in October 2026:</p><ul><li><strong>Gemini / nano banana:</strong> no documented transparency option. You get a solid background, or a checkerboard drawn into the image.</li><li><strong>OpenAI GPT Image API:</strong> yes, on supported models. Set background to transparent with PNG or WebP output.</li><li><strong>Grok (xAI):</strong> no documented option. Treat every image as opaque.</li><li><strong>Midjourney:</strong> no parameter for it in the full parameter list. Prompt a plain background and remove it afterwards.</li></ul><p>On the Google AI developer forum, users asking how to get a transparent background with Nano Banana Pro describe the same result: the background is “only graphically represented as tiles”, not see-through. Typing “transparent background” in the prompt makes it worse, because the model draws the checkerboard it has seen in thousands of screenshots.</p><h3>The Fake Checkerboard Problem</h3><p>A painted checkerboard looks right in the preview. The grey and white squares are regular pixels with full opacity, so they show up around your logo on a dark website header. Check a file before it reaches production:</p><pre>from PIL import Image<br>def has_real_transparency(path: str) -&gt; bool:<br>    im = Image.open(path)<br>    if im.mode not in (&quot;RGBA&quot;, &quot;LA&quot;, &quot;PA&quot;) and &quot;transparency&quot; not in im.info:<br>        return False  # no alpha channel at all<br>    # at least one pixel must be less than fully opaque<br>    return im.convert(&quot;RGBA&quot;).getchannel(&quot;A&quot;).getextrema()[0] &lt; 255<br>print(has_real_transparency(&quot;generated.png&quot;))  # False for a painted checkerboard</pre><p>On the cover image, the left half returns False (plain RGB). The right half returns True: the robot sits on a background that is half checkerboard, half blue, which only works when the pixels around it are truly empty.</p><h3>The Fix: Plain Background, Then One API Call</h3><p><strong>Step 1: generate on a plain, contrasting background.</strong> Ask for “a plain solid orange background, no shadow, no floor”. Avoid the word “transparent” in the prompt, it is what triggers the painted checkerboard.</p><p><strong>Step 2: remove the background.</strong> Send the file to the /remove-background endpoint. The response is JSON with a link to an RGBA PNG:</p><pre>import requests<br>API_URL = &quot;https://background-removal-ai.p.rapidapi.com/remove-background&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-host&quot;: &quot;background-removal-ai.p.rapidapi.com&quot;,<br>    &quot;x-rapidapi-key&quot;: &quot;YOUR_API_KEY&quot;,<br>}<br>with open(&quot;robot.png&quot;, &quot;rb&quot;) as f:<br>    r = requests.post(API_URL, headers=HEADERS, files={&quot;image&quot;: f}, timeout=60)<br>r.raise_for_status()<br>data = r.json()<br>print(data[&quot;image_url&quot;], data[&quot;width&quot;], data[&quot;height&quot;])<br>png = requests.get(data[&quot;image_url&quot;], timeout=60).content<br>with open(&quot;robot-transparent.png&quot;, &quot;wb&quot;) as f:<br>    f.write(png)</pre><p>If your generator returns a URL, pass it directly with json={&quot;image_url&quot;: &quot;https://example.com/generated.png&quot;} instead of uploading the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VAvrN6X_pO5OIMG5.jpg" /></figure><p>The test image is a 3D character render on a flat orange backdrop, the same kind of output an image generator returns. The cutout keeps the hands, the thin arm joints and the reflective visor. We also sent a recreated checkerboard version: the API removed the painted squares and returned a clean RGBA file.</p><blockquote><em>See the </em><a href="https://ai-engine.net/blog/transparent-png-ai-generated-images?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>full guide with the tool-by-tool table, cURL example and sources</em></a><em> on ai-engine.net.</em></blockquote><h3>Batch Script for Stickers and Icons</h3><p>AI-generated assets come in sets. This script converts a whole folder in parallel (PNG, JPEG and WebP in, transparent PNG out):</p><pre>import requests<br>from pathlib import Path<br>from concurrent.futures import ThreadPoolExecutor<br>API_URL = &quot;https://background-removal-ai.p.rapidapi.com/remove-background&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-host&quot;: &quot;background-removal-ai.p.rapidapi.com&quot;,<br>    &quot;x-rapidapi-key&quot;: &quot;YOUR_API_KEY&quot;,<br>}<br>SRC = Path(&quot;generated&quot;)  # images exported from your AI generator<br>OUT = Path(&quot;transparent&quot;)<br>OUT.mkdir(exist_ok=True)<br>def make_transparent(path: Path) -&gt; str:<br>    with open(path, &quot;rb&quot;) as f:<br>        r = requests.post(API_URL, headers=HEADERS, files={&quot;image&quot;: f}, timeout=60)<br>    r.raise_for_status()<br>    png = requests.get(r.json()[&quot;image_url&quot;], timeout=60).content<br>    out = OUT / f&quot;{path.stem}.png&quot;<br>    out.write_bytes(png)<br>    return out.name<br>files = sorted(p for p in SRC.iterdir() if p.suffix.lower() in {&quot;.png&quot;, &quot;.jpg&quot;, &quot;.jpeg&quot;, &quot;.webp&quot;})<br>with ThreadPoolExecutor(max_workers=4) as pool:<br>    for name in pool.map(make_transparent, files):<br>        print(&quot;saved&quot;, name)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hKK6u1sgLH-1vG4F.jpg" /></figure><h3>Chroma Key or an API?</h3><p>If you control the prompt, you can generate on pure green and delete green pixels with a color mask. It is free, and it breaks on:</p><ul><li>Green or yellow-green subjects (plants, mascots, neon logos)</li><li>Soft edges like hair, fur and smoke, which keep a green fringe</li><li>Reflections and glass that pick up the green cast</li><li>Images you did not generate: user uploads, painted checkerboards, old asset libraries</li></ul><p>A segmentation-based API looks at the subject, not at a color, so one call handles all of these.</p><h3>Tips for Clean Cutouts</h3><ul><li><strong>Ask for contrast, not transparency.</strong> Dark subject on a light flat color, or the reverse.</li><li><strong>Ban shadows and floors in the prompt.</strong> A soft drop shadow is part of the image.</li><li><strong>Generate at full size.</strong> Upscale before the cutout, not after.</li><li><strong>Need a brand color instead?</strong> The /color-background endpoint takes bg_color as &quot;R,G,B,A&quot; (for example &quot;37,99,235,255&quot;) and returns the subject on your exact color.</li></ul><h3>Sources</h3><ul><li><a href="https://developers.openai.com/api/docs/guides/image-generation">OpenAI image generation guide</a>: background option and PNG/WebP output</li><li><a href="https://discuss.ai.google.dev/t/how-can-i-make-the-background-transparent/111698">Google AI developer forum: “How can I make the background transparent?”</a>: Nano Banana Pro output shows tiles</li><li><a href="https://docs.x.ai/docs/guides/image-generations">xAI image generation guide</a>: no transparency setting</li><li><a href="https://docs.midjourney.com/hc/en-us/articles/32859204029709-Parameter-List">Midjourney parameter list</a>: no transparency parameter</li><li><a href="https://www.philschmid.de/generate-stickers">Transparent PNG stickers with Nano Banana Pro</a>: the chroma key approach</li></ul><blockquote><em>Ready to fix your generated assets? </em><a href="https://ai-engine.net/apis/background-removal?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Get a key for the Background Removal API</em></a><em>, point the batch script at your folder and run it.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/transparent-png-ai-generated-images?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f50532220071" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Age Verification APIs in 2026: Pricing Compared]]></title>
            <link>https://medium.com/@ai-engine/best-age-verification-apis-in-2026-pricing-compared-0ab2dab72262?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ab2dab72262</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[compliance]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 06:34:04 GMT</pubDate>
            <atom:updated>2026-10-17T06:34:04.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c6dNPEr5gafdwT0y.jpg" /></figure><p>If you run an online shop for alcohol or vapes, a dating app, a gaming platform or any service with adult content, you now need a real age verification API, not an “Are you over 18?” checkbox. Regulators in the UK and Germany have moved to enforcement, and the vendors split into two camps: certified identity platforms that run liveness and ID checks, and fast facial age estimation APIs that cost a fraction of a cent.</p><p>Here is what developers can sign up for in 2026, what it costs at 10,000 checks a month, and how to build an age gate that does not let borderline faces through.</p><blockquote><em>Want to see what an estimate looks like on your own users? </em><a href="https://ai-engine.net/apis/face-analyzer?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Try the Face Analyzer API</em></a><em> on a few selfies.</em></blockquote><h3>Quick Comparison</h3><p>Prices from each provider’s official pages, checked in October 2026:</p><ul><li><strong>AI Engine Face Analyzer:</strong> selfie age range for every face. About $0.0023 per call</li><li><strong>Didit:</strong> age estimation with passive liveness. $0.10 per check</li><li><strong>Yoti:</strong> predicted age with uncertainty, optional anti-spoofing. Price not published</li><li><strong>Persona:</strong> age estimation with liveness and deepfake detection. Price not published</li><li><strong>Veriff:</strong> age estimation sold separately, liveness certified to ISO/IEC 30107–3. ID checks from $0.80, age estimation price not published</li><li><strong>Sumsub:</strong> age estimation enabled on request, with liveness. Verifications from $1.35</li></ul><h3>Estimation, Verification and Liveness</h3><ul><li><strong>Facial age estimation</strong> looks at a selfie and returns an estimated age or range. No document, a result in about a second. Combined with a safety buffer, it screens every user at a fraction of a cent.</li><li><strong>Document-based age verification</strong> reads the date of birth from an ID, checks the document and matches the selfie to it. Slower, but it proves an exact age.</li><li><strong>Liveness detection</strong> checks the camera sees a real person, not a printed photo, a replay or a deepfake. Without it, a teenager can hold up a photo of an adult.</li></ul><p>Most production flows combine them: estimate first, and only ask for an ID when the estimate is too close to the legal age.</p><h3>When a Regulator Expects a Certified Provider</h3><p>Under the UK Online Safety Act, Ofcom lists facial age estimation among the methods capable of being “highly effective” age assurance, next to photo-ID matching, open banking and credit card checks. Self-declaration does not qualify. The whole process must also meet four criteria (accuracy, robustness against circumvention, reliability and fairness), and you need evidence. In Germany, the KJM assesses and approves age verification systems for adult content.</p><p>The right split: if you fall under those adult content rules, buy from a provider that sells liveness, published accuracy figures and audit evidence. For lower-risk cases (a first filter before checkout, age-appropriate content, flagging likely minors for review), a fast estimation API with a safety buffer does the job for much less.</p><h3>The Providers</h3><p><strong>1. AI Engine Face Analyzer.</strong> Returns an AgeRange with Low and High bounds for every face, plus gender, glasses and emotions, with one REST call and no SDK. The cheapest way to estimate age at volume, and it works on photos you already store. Best for age gates, minor flagging and content routing at volume; for regulated adult-content duties, pair it with a certified ID or liveness provider.</p><p><strong>2. Didit.</strong> Publishes its prices: age estimation $0.10 per check, bundled with passive liveness; ID verification $0.15; 500 free verifications a month for its ID bundle.</p><p><strong>3. Yoti.</strong> Returns an age check result or a predicted age with a standard deviation, with optional anti-spoofing. Its July 2025 white paper reports a mean absolute error of 1.1 years for 13 to 17 year olds (self-reported), and it has been evaluated in NIST’s face analysis program. Price on quote.</p><p><strong>4. Persona.</strong> Selfie age estimation with liveness and deepfake detection, configurable cutoffs and buffers, and a government ID fallback for borderline results. Vimeo uses it for its age checks. No published per-check price.</p><p><strong>5. Veriff.</strong> Age Estimation is a separate product: selfie, real-time liveness, estimated age to approve, deny or escalate. ID verification plans start at $0.80 per verification with a $49 monthly minimum; the age estimation price is not published.</p><p><strong>6. Sumsub.</strong> Document-based age verification plus Facial Age Estimation on its liveness tech. Its docs claim a typical error of 1 to 2 years and recommend buffers of 3, 7 or 10 years. Approved by the KJM in Germany. Plans from $1.35 per verification with a $149 minimum.</p><h3>Cost at 10,000 Checks a Month</h3><ul><li><strong>AI Engine Face Analyzer</strong> (age range estimate): $22.99</li><li><strong>Didit</strong> (estimate with passive liveness): about $1,000</li><li><strong>Veriff Essential</strong> (full ID verification): about $8,000</li><li><strong>Sumsub Basic</strong> (full verification): about $13,500</li><li><strong>Yoti, Persona:</strong> quote only</li></ul><p>These rows do not buy the same thing. The useful takeaway is the structure: an estimate for everyone plus an ID check for the borderline few costs far less than an ID check for everyone.</p><blockquote><em>See the </em><a href="https://ai-engine.net/blog/best-age-verification-apis?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>full comparison with the decision guide</em></a><em> on ai-engine.net.</em></blockquote><h3>Build an Age Gate with a Safety Buffer in Python</h3><p>Do not pass everyone whose estimate is above 18: a 17-year-old estimated at 16 to 21 would get through. Define a challenge age (legal age plus a buffer), pass only users whose lowest estimate clears it, block clear minors, and send everyone in between to an ID check:</p><pre>import requests<br>API_URL = &quot;https://faceanalyzer-ai.p.rapidapi.com/faceanalysis&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-host&quot;: &quot;faceanalyzer-ai.p.rapidapi.com&quot;,<br>    &quot;x-rapidapi-key&quot;: &quot;YOUR_API_KEY&quot;,<br>}<br>def age_gate(selfie_path, legal_age=18, buffer=5):<br>    &quot;&quot;&quot;Return &#39;pass&#39;, &#39;id_check&#39;, &#39;deny&#39; or &#39;retry&#39; for one selfie.&quot;&quot;&quot;<br>    with open(selfie_path, &quot;rb&quot;) as f:<br>        resp = requests.post(API_URL, headers=HEADERS, files={&quot;image&quot;: f}, timeout=30)<br>    faces = resp.json()[&quot;body&quot;][&quot;faces&quot;]<br>    if len(faces) != 1:<br>        return &quot;retry&quot;, None  # no face or several faces: ask for a new selfie<br>    age = faces[0][&quot;facialFeatures&quot;][&quot;AgeRange&quot;]<br>    if age[&quot;Low&quot;] &gt;= legal_age + buffer:<br>        return &quot;pass&quot;, age  # clearly above the challenge age<br>    if age[&quot;High&quot;] &lt; legal_age:<br>        return &quot;deny&quot;, age  # clearly under age<br>    return &quot;id_check&quot;, age  # too close to call: fall back to an ID document<br>for photo in [&quot;selfie_1.jpg&quot;, &quot;selfie_2.jpg&quot;, &quot;selfie_3.jpg&quot;]:<br>    decision, age = age_gate(photo)<br>    print(photo, age, decision)</pre><p>We ran this exact function on six stock photos with an 18+ rule and a 5-year buffer (challenge age 23):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G06mlnVRxxuYnFCo.jpg" /></figure><p>Clear adults pass, the clear minor is denied, the two borderline faces go to an ID check. A larger buffer sends more adults to the ID step but lets fewer minors through. Sumsub’s 3, 7 or 10 years is a reasonable starting range, and UK shops already apply the same idea with “Challenge 25”.</p><p>For a full build with a Flask endpoint, edge cases and data retention, see the <a href="https://ai-engine.net/blog/face-based-age-verification-api?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost">face-based age verification tutorial</a>.</p><h3>Which One Should You Choose?</h3><ul><li><strong>AI Engine Face Analyzer</strong> for lower-risk age gates and minor-flagging at the lowest cost per check, including on photos you already have</li><li><strong>Didit</strong> for published prices with liveness included</li><li><strong>Yoti, Persona, Veriff or Sumsub</strong> if you fall under adult content regulation, or need liveness, deepfake detection, audit evidence and an ID fallback from one vendor</li></ul><h3>Sources</h3><ul><li><a href="https://www.ofcom.org.uk/online-safety/protecting-children/statement-age-assurance-and-childrens-access">Ofcom: Age Assurance and Children’s Access statement</a></li><li><a href="https://didit.me/pricing">Didit pricing</a></li><li><a href="https://developers.yoti.com/age-estimation">Yoti age estimation developer docs</a></li><li><a href="https://www.yoti.com/wp-content/uploads/2025/07/Yoti-Age-Estimation-White-Paper-July-2025-PUBLIC-v1.pdf">Yoti Age Estimation White Paper, July 2025</a></li><li><a href="https://withpersona.com/product/verifications/selfie-age-estimation">Persona selfie age estimation</a></li><li><a href="https://www.veriff.com/plans">Veriff plans</a> and <a href="https://www.veriff.com/product/age-estimation">Veriff Age Estimation</a></li><li><a href="https://sumsub.com/pricing/">Sumsub pricing</a> and <a href="https://docs.sumsub.com/docs/age-estimation">Sumsub Facial Age Estimation docs</a></li></ul><blockquote><em>Test it on your own selfies: </em><a href="https://ai-engine.net/apis/face-analyzer?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>grab a key on the Face Analyzer API page</em></a><em> and run the age gate above.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/best-age-verification-apis?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ab2dab72262" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NSFW Video and GIF Moderation with Python and an API]]></title>
            <link>https://medium.com/@ai-engine/nsfw-video-and-gif-moderation-with-python-and-an-api-37603378151f?source=rss-075c3c29f0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/37603378151f</guid>
            <category><![CDATA[content-moderation]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[trust-and-safety]]></category>
            <category><![CDATA[videos]]></category>
            <dc:creator><![CDATA[AIEngine]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 16:36:21 GMT</pubDate>
            <atom:updated>2026-10-16T16:36:21.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7jQNsCc1PlfseCuY.jpg" /></figure><p>If your app accepts video or GIF uploads (short clips in a social feed, reaction GIFs in chat, product videos on a marketplace), checking only the thumbnail is not moderation. The problem frame can sit at second 12 of a 30 second clip. NSFW video moderation with an image API works by sampling frames, scoring each one, and deciding on the whole clip.</p><p>Every number below comes from a real run on a public domain 25 second clip of a beer being poured: it starts with an empty glass and ends with a full one, a good test for how detections change over time.</p><blockquote><em>Want to see the labels on your own clips? </em><a href="https://ai-engine.net/apis/nsfw-detect?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>Try the NSFW Detect API</em></a><em> on a frame from one of your uploads.</em></blockquote><h3>How it works</h3><p>A moderation API looks at images, so a video becomes a list of frames:</p><ol><li><strong>Sample</strong> frames with ffmpeg, at a fixed interval or on scene changes.</li><li><strong>Score</strong> each frame with the API, in parallel.</li><li><strong>Aggregate</strong> per top-level category: highest confidence, number of flagged frames, timestamps.</li><li><strong>Decide</strong> allow, review, or block for the clip, and stop early when a frame already settles it.</li></ol><h3>Step 1: Sample frames with ffmpeg</h3><pre>import os<br>import subprocess<br>def extract_frames(video_path, out_dir, every_seconds=1.0):<br>    &quot;&quot;&quot;Grab one frame every N seconds. Returns [(timestamp, path), ...].&quot;&quot;&quot;<br>    subprocess.run(<br>        [&quot;ffmpeg&quot;, &quot;-v&quot;, &quot;error&quot;, &quot;-i&quot;, video_path,<br>         &quot;-vf&quot;, f&quot;fps=1/{every_seconds},scale=&#39;min(1280,iw)&#39;:-2&quot;,<br>         &quot;-q:v&quot;, &quot;3&quot;, f&quot;{out_dir}/frame_%05d.jpg&quot;],<br>        check=True,<br>    )<br>    files = sorted(os.listdir(out_dir))<br>    return [(i * every_seconds, os.path.join(out_dir, f)) for i, f in enumerate(files)]</pre><p>On the 25 second test clip, one frame per second gives 26 frames; one every 2 seconds gives 13.</p><h3>Step 2: Score frames in parallel</h3><p>Keep only the top-level categories (empty ParentName) so every sub-label maps to one policy rule:</p><pre>import tempfile<br>from concurrent.futures import ThreadPoolExecutor<br>import requests<br>API_URL = &quot;https://nsfw-detect3.p.rapidapi.com/nsfw-detect&quot;<br>HEADERS = {<br>    &quot;x-rapidapi-key&quot;: &quot;YOUR_API_KEY&quot;,<br>    &quot;x-rapidapi-host&quot;: &quot;nsfw-detect3.p.rapidapi.com&quot;,<br>}<br>def moderate_frame(path):<br>    &quot;&quot;&quot;Return the top-level categories found in one frame: {name: confidence}.&quot;&quot;&quot;<br>    with open(path, &quot;rb&quot;) as f:<br>        r = requests.post(API_URL, headers=HEADERS, files={&quot;image&quot;: f}, timeout=30)<br>    r.raise_for_status()<br>    labels = r.json()[&quot;body&quot;][&quot;ModerationLabels&quot;]<br>    return {l[&quot;Name&quot;]: l[&quot;Confidence&quot;] for l in labels if l[&quot;ParentName&quot;] == &quot;&quot;}<br>def moderate_video(video_path, every_seconds=1.0, workers=4):<br>    &quot;&quot;&quot;Moderate sampled frames in parallel. Returns [(timestamp, categories), ...].&quot;&quot;&quot;<br>    with tempfile.TemporaryDirectory() as tmp:<br>        frames = extract_frames(video_path, tmp, every_seconds)<br>        with ThreadPoolExecutor(max_workers=workers) as pool:<br>            results = list(pool.map(lambda fr: moderate_frame(fr[1]), frames))<br>    return [(t, cats) for (t, _), cats in zip(frames, results)]<br>for t, cats in moderate_video(&quot;beer_pour.mp4&quot;):<br>    print(f&quot;{t:&gt;3.0f}s&quot;, {k: round(v, 1) for k, v in cats.items()})<br>#   0s {}                    empty glass<br>#   8s {&#39;Alcohol&#39;: 94.9}<br>#  11s {&#39;Alcohol&#39;: 95.9}<br>#  21s {&#39;Alcohol&#39;: 99.3}<br>#  25s {&#39;Alcohol&#39;: 99.8}<br>#  (26 frames in total)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Q_8Jn82QQjsnjmx.jpg" /></figure><p>The empty glass at second 0 comes back clean, and Alcohol is flagged from second 3, as soon as beer is in the glass, up to 99.8% on the full glass. That timeline is what turns frame scores into a decision: when the category first appears, how often, and how confident the API is at its peak.</p><h3>Step 3: Aggregate per category and decide</h3><p>Each policy rule gets one extra field compared with a single image policy: min_frames, the number of frames that must cross the threshold before the rule fires.</p><pre>POLICY = {<br>    &quot;Explicit&quot;:                                          {&quot;action&quot;: &quot;block&quot;,  &quot;threshold&quot;: 60, &quot;min_frames&quot;: 1},<br>    &quot;Non-Explicit Nudity of Intimate parts and Kissing&quot;: {&quot;action&quot;: &quot;review&quot;, &quot;threshold&quot;: 70, &quot;min_frames&quot;: 2},<br>    &quot;Violence&quot;:                                          {&quot;action&quot;: &quot;block&quot;,  &quot;threshold&quot;: 70, &quot;min_frames&quot;: 2},<br>    &quot;Hate Symbols&quot;:                                      {&quot;action&quot;: &quot;block&quot;,  &quot;threshold&quot;: 50, &quot;min_frames&quot;: 1},<br>    &quot;Drugs &amp; Tobacco&quot;:                                   {&quot;action&quot;: &quot;review&quot;, &quot;threshold&quot;: 80, &quot;min_frames&quot;: 2},<br>    &quot;Alcohol&quot;:                                           {&quot;action&quot;: &quot;review&quot;, &quot;threshold&quot;: 90, &quot;min_frames&quot;: 2},<br>}<br>def summarize(results):<br>    &quot;&quot;&quot;Per category: max confidence, number of flagged frames, timestamps.&quot;&quot;&quot;<br>    summary = {}<br>    for t, cats in results:<br>        for name, conf in cats.items():<br>            s = summary.setdefault(name, {&quot;max&quot;: 0.0, &quot;frames&quot;: 0, &quot;times&quot;: []})<br>            s[&quot;max&quot;] = max(s[&quot;max&quot;], conf)<br>            s[&quot;frames&quot;] += 1<br>            s[&quot;times&quot;].append(t)<br>    return summary<br>def decide(summary):<br>    &quot;&quot;&quot;Turn the per-category summary into allow / review / block.&quot;&quot;&quot;<br>    verdict, reasons = &quot;allow&quot;, []<br>    for name, s in summary.items():<br>        rule = POLICY.get(name)<br>        if not rule or s[&quot;max&quot;] &lt; rule[&quot;threshold&quot;] or s[&quot;frames&quot;] &lt; rule[&quot;min_frames&quot;]:<br>            continue<br>        reasons.append(f&quot;{name}: {s[&#39;frames&#39;]} frames, max {s[&#39;max&#39;]:.1f}%, first at {s[&#39;times&#39;][0]:.0f}s&quot;)<br>        if rule[&quot;action&quot;] == &quot;block&quot;:<br>            verdict = &quot;block&quot;<br>        elif verdict != &quot;block&quot;:<br>            verdict = &quot;review&quot;<br>    return verdict, reasons<br>print(decide(summarize(moderate_video(&quot;beer_pour.mp4&quot;))))<br># (&#39;review&#39;, [&#39;Alcohol: 9 frames, max 99.8%, first at 3s&#39;])</pre><p>The reasons string tells a reviewer where to jump in the clip instead of watching all of it.</p><blockquote><em>The </em><a href="https://ai-engine.net/blog/nsfw-video-moderation-python?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>full guide</em></a><em> adds a scene-change sampler with a frame gap cap and the exact numbers behind each sampling choice.</em></blockquote><h3>Step 4: Stop early on a clear block</h3><p>Once a block rule fires, the remaining frames cannot change the verdict:</p><pre>def moderate_with_early_stop(frames, workers=4):<br>    &quot;&quot;&quot;Moderate frames in time order, batch by batch; stop at the first block.&quot;&quot;&quot;<br>    results, calls = [], 0<br>    with ThreadPoolExecutor(max_workers=workers) as pool:<br>        for i in range(0, len(frames), workers):<br>            batch = frames[i:i + workers]<br>            cats = list(pool.map(lambda fr: moderate_frame(fr[1]), batch))<br>            results += [(t, c) for (t, _), c in zip(batch, cats)]<br>            calls += len(batch)<br>            verdict, reasons = decide(summarize(results))<br>            if verdict == &quot;block&quot;:<br>                break<br>    return verdict, reasons, calls<br>POLICY[&quot;Alcohol&quot;] = {&quot;action&quot;: &quot;block&quot;, &quot;threshold&quot;: 90, &quot;min_frames&quot;: 2}  # kids platform<br>with tempfile.TemporaryDirectory() as tmp:<br>    frames = extract_frames(&quot;beer_pour.mp4&quot;, tmp, every_seconds=1.0)<br>    print(moderate_with_early_stop(frames))<br># (&#39;block&#39;, [&#39;Alcohol: 3 frames, max 95.9%, first at 3s&#39;], 12)</pre><p>Blocked after 12 calls instead of 26. Clean videos still need every sampled frame.</p><h3>Choosing a sampling rate</h3><p>Real results on the same clip, with the review policy:</p><ul><li><strong>Every 1 second:</strong> 26 calls, peak 99.8%, verdict review</li><li><strong>Every 2 seconds:</strong> 13 calls, peak 99.8%, verdict review</li></ul><p>Both rates flag the clip. For short user uploads, one frame every one to two seconds is a solid default; for long edited videos, scene-change sampling with a gap cap cuts calls further.</p><h3>GIF uploads</h3><p>ffmpeg reads GIFs directly, so extract_frames(&quot;reaction.gif&quot;, tmp, 2.0) works unchanged. Without ffmpeg, Pillow can sample by frame duration:</p><pre>from PIL import Image, ImageSequence<br>def extract_gif_frames(gif_path, out_dir, every_seconds=1.0):<br>    &quot;&quot;&quot;Sample a GIF every N seconds using each frame&#39;s own duration.&quot;&quot;&quot;<br>    gif = Image.open(gif_path)<br>    frames, t, next_t = [], 0.0, 0.0<br>    for i, frame in enumerate(ImageSequence.Iterator(gif)):<br>        if t &gt;= next_t:<br>            path = os.path.join(out_dir, f&quot;gif_{i:05d}.jpg&quot;)<br>            frame.convert(&quot;RGB&quot;).save(path, quality=90)<br>            frames.append((t, path))<br>            next_t += every_seconds<br>        t += frame.info.get(&quot;duration&quot;, 100) / 1000<br>    return frames</pre><p>On a GIF made from the same clip, sampling every 2 seconds gave 13 frames, Alcohol on 7 (max 99.9%) and a review verdict. The convert(&quot;RGB&quot;) is required: GIF frames are palette images and JPEG cannot store them.</p><h3>How many API calls?</h3><p>One call per sampled frame. A 30 second clip sampled every 2 seconds costs 15 calls, and 1,000 such clips come to about 15,000 calls over the month before early stops. Upload duration limits bound the worst case, and hashing uploads avoids re-moderating reposted GIFs.</p><h3>Production tips</h3><ul><li><strong>Publish after the verdict.</strong> Keep new videos pending and moderate in a background worker; 26 frames with 4 workers took about 6 seconds in this test.</li><li><strong>Fail safe to review</strong> when a frame call errors out.</li><li><strong>Moderate the poster frame</strong> shown in the feed too.</li></ul><h3>Sources</h3><ul><li><a href="https://commons.wikimedia.org/wiki/File:One_example_of_how_to_pour_beer.theora.ogv">One example of how to pour beer (Wikimedia Commons)</a>: the public domain test clip</li><li><a href="https://ffmpeg.org/ffmpeg-filters.html#select_002c-aselect">ffmpeg select filter documentation</a>: scene and prev_selected_t variables</li></ul><blockquote><em>Run it on the clips your users actually upload: </em><a href="https://ai-engine.net/apis/nsfw-detect?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>grab a key on the NSFW Detect API page</em></a><em> and tune the thresholds on real data.</em></blockquote><p><em>Originally published at </em><a href="https://ai-engine.net/blog/nsfw-video-moderation-python?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=crosspost"><em>ai-engine.net</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37603378151f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>