File size: 1,962 Bytes
776deff
 
 
d6d596e
 
4d2cb74
 
 
 
 
d6d596e
 
 
776deff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b5c58
776deff
 
 
 
 
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
import gradio as gr
from PIL import Image
import os
import sys

current_dir = os.path.dirname(os.path.abspath(__file__))
defake_dir = os.path.join(current_dir, "defake")
if defake_dir not in sys.path:
    sys.path.insert(0, defake_dir)

import defake.test_api
# 把 defake.test_api 里的 NeuralNet 类,“挂载”到当前的主模块 (__main__) 上
setattr(sys.modules['__main__'], 'NeuralNet', defake.test_api.NeuralNet)

from app_infer import run_infer_from_image

APP_API_TOKEN = os.environ.get("APP_API_TOKEN", "")

def detect_api(image: Image.Image, api_token: str = ""):
    if APP_API_TOKEN and api_token != APP_API_TOKEN:
        raise gr.Error("Invalid API token.")
    result = run_infer_from_image(image)
    return result

def detect_ui(image: Image.Image):
    result = run_infer_from_image(image)
    return result["fake_score"], str(result["is_fake"])

with gr.Blocks(title="CISPA Citizen DeFake") as demo:
    gr.Markdown("# CISPA Citizen DeFake")
    gr.Markdown("Upload an image to detect if it is fake.")

    with gr.Row():
        with gr.Column():
            img_input = gr.Image(type="pil", label="Upload Image")
            btn = gr.Button("Detect")
        with gr.Column():
            score_out = gr.Number(label="Fake score (1=fake)")
            is_fake_out = gr.Textbox(label="Prediction (True=fake)")

    btn.click(fn=detect_ui, inputs=img_input, outputs=[score_out, is_fake_out])

    gr.Markdown("## API")
    gr.Markdown(
        "POST to `/run/predict` with form-data: `image`, `api_token`.\n"
        "Returns JSON: `{fake_score: float, is_fake: bool, probs: [p0,p1], pred_class: int}`."
    )

    api = gr.Interface(
        fn=detect_api,
        inputs=[
            gr.Image(type="pil", label="image"),
            gr.Textbox(label="api_token", type="password"),
        ],
        outputs="json",
        # allow_flagging="never",
        title="API Endpoint",
    )

if __name__ == "__main__":
    demo.launch()