Spaces:
Running on Zero
Running on Zero
Download app.py from inter00stellar/truthlens: direct link, hf CLI and curl.
- Browser
- Download file 5.48 kB
-
https://huggingface.co/spaces/inter00stellar/truthlens/resolve/main/app.py
- Command line
-
hf download hf://spaces/inter00stellar/truthlens/app.py
-
curl -L -o app.py https://huggingface.co/spaces/inter00stellar/truthlens/resolve/main/app.py
5.48 kB
| import os, subprocess, tempfile | |
| import spaces, cv2, numpy as np, requests, gradio as gr | |
| from PIL import Image | |
| from transformers import pipeline | |
| # ---- Models (Hugging Face; verify names on hf.co if one fails to load) ---- | |
| IMG = pipeline("image-classification", model="dima806/deepfake_vs_real_image_detection", device="cuda") | |
| AUD = pipeline("audio-classification", model="MelodyMachine/Deepfake-audio-detection-V2", device="cuda") | |
| TXT = pipeline("text-classification", model="mrm8488/bert-tiny-finetuned-fake-news-detection", device="cuda") | |
| try: | |
| import easyocr | |
| OCR = easyocr.Reader(["en"], gpu=False) | |
| except Exception: | |
| OCR = None | |
| NOTE = "\n\n*AI estimate, not proof. Detectors miss new generators, and a real photo can carry a false headline.*" | |
| FAKE_KEYS = ("fake", "spoof", "synthetic", "deepfake", "ai_generated") | |
| def p_fake(res): | |
| for r in res: | |
| if any(k in r["label"].lower() for k in FAKE_KEYS): | |
| return r["score"] | |
| for r in res: | |
| if "real" in r["label"].lower(): | |
| return 1 - r["score"] | |
| return 0.5 | |
| def verdict(p): | |
| if p >= 0.7: return f"## π΄ LIKELY FAKE ({p:.0%})" | |
| if p <= 0.3: return f"## π’ LIKELY REAL ({1-p:.0%})" | |
| return f"## π‘ UNCERTAIN ({p:.0%} fake score)" | |
| def label(p): | |
| return {"Fake": float(p), "Real": float(1 - p)} | |
| def fact_check(text): | |
| key = os.environ.get("FACTCHECK_API_KEY") # optional Space secret | |
| if not key or not text.strip(): | |
| return "" | |
| try: | |
| r = requests.get("https://factchecktools.googleapis.com/v1alpha1/claims:search", | |
| params={"query": text[:150], "key": key}, timeout=10).json() | |
| lines = [] | |
| for c in r.get("claims", [])[:3]: | |
| rv = c["claimReview"][0] | |
| lines.append(f"- {rv.get('publisher',{}).get('name','?')}: **{rv.get('textualRating','?')}** ([link]({rv.get('url','')}))") | |
| return "\n\n**Published fact-checks:**\n" + "\n".join(lines) if lines else "\n\nNo published fact-checks found for this claim." | |
| except Exception: | |
| return "" | |
| def check_text(txt): | |
| if not txt or not txt.strip(): | |
| return "Paste some text.", None | |
| p = p_fake(TXT(txt[:1500])) | |
| return verdict(p) + "\n\nJudges writing style, not truth." + fact_check(txt) + NOTE, label(p) | |
| def check_image(img): | |
| if img is None: | |
| return "Upload an image.", None | |
| p = p_fake(IMG(img)) | |
| out = verdict(p) + "\n\n*Image check: looks for AI-generated pixels.*" | |
| if OCR: | |
| text = " ".join(OCR.readtext(np.array(img.convert("RGB")), detail=0)) | |
| if len(text) > 30: | |
| tp = p_fake(TXT(text[:1000])) | |
| out += f"\n\n**Text found in image:** {text[:300]}\n\nClaim-style fake-news score: {tp:.0%}" + fact_check(text) | |
| return out + NOTE, label(p) | |
| def check_audio(path): | |
| if not path: | |
| return "Upload or record audio.", None | |
| p = p_fake(AUD(path)) | |
| return verdict(p) + "\n\n*Voice-clone check.*" + NOTE, label(p) | |
| def check_video(path): | |
| if not path: | |
| return "Upload a video.", None | |
| cap = cv2.VideoCapture(path) | |
| n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 1 | |
| scores = [] | |
| for i in np.linspace(0, n - 1, 8).astype(int): # 8 frames spread across the video | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, int(i)) | |
| ok, f = cap.read() | |
| if ok: | |
| scores.append(p_fake(IMG(Image.fromarray(cv2.cvtColor(f, cv2.COLOR_BGR2RGB))))) | |
| cap.release() | |
| if not scores: | |
| return "Could not read video.", None | |
| pv, extra = float(np.mean(scores)), "" | |
| p = pv | |
| try: # also check the audio track | |
| wav = tempfile.mktemp(suffix=".wav") | |
| subprocess.run(["ffmpeg", "-y", "-i", path, "-ac", "1", "-ar", "16000", "-t", "30", wav], | |
| capture_output=True, check=True) | |
| pa = p_fake(AUD(wav)) | |
| p = 0.6 * pv + 0.4 * pa | |
| extra = f"\n\nFrames: {pv:.0%} fake Β· Audio: {pa:.0%} fake" | |
| except Exception: | |
| extra = f"\n\nFrames: {pv:.0%} fake (no audio checked)" | |
| return verdict(p) + extra + NOTE, label(p) | |
| def live(img): | |
| return label(p_fake(IMG(img))) if img is not None else None | |
| # ---- UI ---- | |
| with gr.Blocks(title="TruthLens") as demo: | |
| gr.Markdown("# π TruthLens\nCheck images, videos, voice clips and news text for AI fakes.") | |
| with gr.Tab("Image / News screenshot"): | |
| i = gr.Image(type="pil", sources=["upload", "clipboard"]) | |
| b = gr.Button("Check", variant="primary"); m = gr.Markdown(); l = gr.Label() | |
| b.click(check_image, i, [m, l]) | |
| with gr.Tab("Video"): | |
| v = gr.Video(sources=["upload", "webcam"]) | |
| b = gr.Button("Check", variant="primary"); m = gr.Markdown(); l = gr.Label() | |
| b.click(check_video, v, [m, l]) | |
| with gr.Tab("Voice / Audio"): | |
| a = gr.Audio(type="filepath", sources=["upload", "microphone"]) | |
| b = gr.Button("Check", variant="primary"); m = gr.Markdown(); l = gr.Label() | |
| b.click(check_audio, a, [m, l]) | |
| with gr.Tab("News text"): | |
| t = gr.Textbox(lines=6, label="Paste headline or article") | |
| b = gr.Button("Check", variant="primary"); m = gr.Markdown(); l = gr.Label() | |
| b.click(check_text, t, [m, l]) | |
| with gr.Tab("π΄ Live webcam"): | |
| w = gr.Image(sources=["webcam"], streaming=True, type="pil") | |
| lo = gr.Label(label="Live deepfake score") | |
| w.stream(live, w, lo, stream_every=1, time_limit=120) | |
| demo.queue().launch() | |