File size: 2,377 Bytes
30a7879
 
 
 
4be3314
 
30a7879
 
 
 
 
 
 
 
 
 
 
4be3314
30a7879
 
 
 
 
 
 
 
4be3314
30a7879
4be3314
30a7879
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4be3314
30a7879
 
 
 
 
 
 
 
 
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
import gradio as gr
from PIL import Image
from detector import FakeImageDetector  

FIXED_THRESHOLD = 0.4999

print("正在初始化检测器,请稍候...")
try:
    detector = FakeImageDetector()
    
    print("检测器初始化完成,Web 服务准备就绪。")
    models_loaded = True
except Exception as e:
    print(f"模型加载失败: {e}")
    models_loaded = False
    detector = None

def predict_image(input_image_numpy):
    """
    接收 Gradio 的输入 (numpy array),调用检测器,并返回结果。
    """
    if not models_loaded or detector is None:
        return "错误:模型未能成功加载,请检查后台日志。", None

    pil_image = Image.fromarray(input_image_numpy)
    
    result_text, score = detector.detect(pil_image, FIXED_THRESHOLD)
    
    label_color = "red" if score > FIXED_THRESHOLD else "green"
    
    return result_text, gr.Label(value=f"{score:.10f}", label=label_color)


with gr.Blocks(title="伪造图像检测器", theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
        # 伪造图像检测器 (Fake Image Detector)
        上传一张图片,模型将判断其为 **真实的 (Real)** 还是 **AI 生成的伪造图像 (Fake)**。
        """
    )
    
    with gr.Row():
        with gr.Column(scale=1):
            # 输入组件
            image_input = gr.Image(type="numpy", label="上传图片", height=300)
            # threshold_slider = gr.Slider(
            #     minimum=0.495, maximum=0.55, value=0.499892068, step=0.0001, 
            #     label="检测门限 (Threshold)",
            #     info="得分低于此门限的图片被认为是伪造的"
            # )
            submit_btn = gr.Button("开始检测", variant="primary")
        
        with gr.Column(scale=1):
            # 输出组件
            result_output_text = gr.Textbox(label="检测结论", lines=2)
            # 这里我们用一个临时的 Label 来显示带颜色的分数
            result_output_score = gr.Label(label="模型原始得分")

    submit_btn.click(
        fn=predict_image, 
        inputs=[image_input], 
        outputs=[result_output_text, result_output_score]
    )

if not models_loaded:
    print("\n由于模型加载失败,Gradio Web服务无法启动。")
else:
    print("正在启动 Gradio 服务...")
    
    demo.launch(server_name="0.0.0.0")