Spaces:
Running on Zero

File size: 5,484 Bytes
b977214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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 ""

@spaces.GPU
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)

@spaces.GPU
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)

@spaces.GPU
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)

@spaces.GPU
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)

@spaces.GPU
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()