Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
python
|
2 |
+
import gradio as gr
|
3 |
+
import torch
|
4 |
+
from PIL import Image
|
5 |
+
import numpy as np
|
6 |
+
from transformers import AutoFeatureExtractor, AutoModelForImageClassification
|
7 |
+
|
8 |
+
# 加载预训练的AI图像检测器
|
9 |
+
model_name = "SehwanHong/Stable-Diffusion-Detector"
|
10 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
|
11 |
+
model = AutoModelForImageClassification.from_pretrained(model_name)
|
12 |
+
|
13 |
+
def detect_ai_image(image):
|
14 |
+
# 处理图像
|
15 |
+
inputs = feature_extractor(images=image, return_tensors="pt")
|
16 |
+
with torch.no_grad():
|
17 |
+
outputs = model(**inputs)
|
18 |
+
|
19 |
+
# 获取预测结果
|
20 |
+
logits = outputs.logits
|
21 |
+
predicted_class_idx = logits.argmax(-1).item()
|
22 |
+
|
23 |
+
# 获取概率
|
24 |
+
probabilities = torch.nn.functional.softmax(logits, dim=-1)
|
25 |
+
ai_probability = probabilities[0][1].item() # 假设索引1是AI生成类
|
26 |
+
|
27 |
+
# 分析图像特征
|
28 |
+
features = analyze_image_features(image)
|
29 |
+
|
30 |
+
return {
|
31 |
+
"ai_probability": float(ai_probability),
|
32 |
+
"features": features,
|
33 |
+
"predicted_class": model.config.id2label[predicted_class_idx]
|
34 |
+
}
|
35 |
+
|
36 |
+
def analyze_image_features(image):
|
37 |
+
# 简单图像特征分析
|
38 |
+
features = {}
|
39 |
+
|
40 |
+
# 转换为numpy数组
|
41 |
+
img_array = np.array(image)
|
42 |
+
|
43 |
+
# 基本特征
|
44 |
+
features["width"] = image.width
|
45 |
+
features["height"] = image.height
|
46 |
+
features["aspect_ratio"] = image.width / max(1, image.height)
|
47 |
+
|
48 |
+
# 颜色分析
|
49 |
+
if len(img_array.shape) == 3: # 彩色图像
|
50 |
+
features["avg_red"] = float(np.mean(img_array[:,:,0]))
|
51 |
+
features["avg_green"] = float(np.mean(img_array[:,:,1]))
|
52 |
+
features["avg_blue"] = float(np.mean(img_array[:,:,2]))
|
53 |
+
|
54 |
+
return features
|
55 |
+
|
56 |
+
# 创建Gradio界面
|
57 |
+
iface = gr.Interface(
|
58 |
+
fn=detect_ai_image,
|
59 |
+
inputs=gr.Image(type="pil"),
|
60 |
+
outputs=gr.JSON(),
|
61 |
+
title="AI图像检测API",
|
62 |
+
description="检测图像是否由AI生成"
|
63 |
+
)
|
64 |
+
|
65 |
+
iface.launch()
|