Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -2,46 +2,51 @@ import gradio as gr
|
|
2 |
import torch
|
3 |
from PIL import Image
|
4 |
import numpy as np
|
|
|
5 |
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
6 |
|
7 |
-
#
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
# 通常索引1对应AI生成,索引0对应真实图像,但我们需要确认模型的标签
|
27 |
-
ai_index = 1 if "ai" in model.config.id2label[1].lower() else 0
|
28 |
-
ai_probability = probabilities[0][ai_index].item()
|
29 |
-
|
30 |
-
# 分析图像特征
|
31 |
-
features = analyze_image_features(image)
|
32 |
-
|
33 |
-
return {
|
34 |
-
"ai_probability": float(ai_probability),
|
35 |
-
"features": features,
|
36 |
-
"predicted_class": model.config.id2label[predicted_class_idx]
|
37 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
def analyze_image_features(image):
|
40 |
-
#
|
41 |
-
features = {}
|
42 |
-
|
43 |
-
# 转换为numpy数组
|
44 |
img_array = np.array(image)
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
# 基本特征
|
47 |
features["width"] = image.width
|
@@ -49,20 +54,119 @@ def analyze_image_features(image):
|
|
49 |
features["aspect_ratio"] = image.width / max(1, image.height)
|
50 |
|
51 |
# 颜色分析
|
52 |
-
if len(img_array.shape) == 3:
|
53 |
features["avg_red"] = float(np.mean(img_array[:,:,0]))
|
54 |
features["avg_green"] = float(np.mean(img_array[:,:,1]))
|
55 |
features["avg_blue"] = float(np.mean(img_array[:,:,2]))
|
56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
return features
|
58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
# 创建Gradio界面
|
60 |
iface = gr.Interface(
|
61 |
fn=detect_ai_image,
|
62 |
inputs=gr.Image(type="pil"),
|
63 |
outputs=gr.JSON(),
|
64 |
-
title="AI图像检测API",
|
65 |
-
description="
|
|
|
|
|
|
|
|
|
|
|
66 |
)
|
67 |
|
68 |
iface.launch()
|
|
|
2 |
import torch
|
3 |
from PIL import Image
|
4 |
import numpy as np
|
5 |
+
import cv2
|
6 |
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
7 |
|
8 |
+
# 加载多个检测模型
|
9 |
+
models = {
|
10 |
+
"model1": {
|
11 |
+
"name": "umm-maybe/AI-image-detector",
|
12 |
+
"processor": None,
|
13 |
+
"model": None,
|
14 |
+
"weight": 0.4
|
15 |
+
},
|
16 |
+
"model2": {
|
17 |
+
"name": "sayakpaul/convnext-base-finetuned-ai-generated-detection",
|
18 |
+
"processor": None,
|
19 |
+
"model": None,
|
20 |
+
"weight": 0.3
|
21 |
+
},
|
22 |
+
"model3": {
|
23 |
+
"name": "Xenova/clip-image-classification-ai-generated",
|
24 |
+
"processor": None,
|
25 |
+
"model": None,
|
26 |
+
"weight": 0.3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
}
|
28 |
+
}
|
29 |
+
|
30 |
+
# 初始化模型
|
31 |
+
for key in models:
|
32 |
+
try:
|
33 |
+
models[key]["processor"] = AutoImageProcessor.from_pretrained(models[key]["name"])
|
34 |
+
models[key]["model"] = AutoModelForImageClassification.from_pretrained(models[key]["name"])
|
35 |
+
print(f"成功加载模型: {models[key]['name']}")
|
36 |
+
except Exception as e:
|
37 |
+
print(f"加载模型 {models[key]['name']} 失败: {str(e)}")
|
38 |
+
models[key]["processor"] = None
|
39 |
+
models[key]["model"] = None
|
40 |
|
41 |
def analyze_image_features(image):
|
42 |
+
# 转换为OpenCV格式
|
|
|
|
|
|
|
43 |
img_array = np.array(image)
|
44 |
+
if len(img_array.shape) == 3 and img_array.shape[2] == 3:
|
45 |
+
img_cv = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
|
46 |
+
else:
|
47 |
+
img_cv = img_array
|
48 |
+
|
49 |
+
features = {}
|
50 |
|
51 |
# 基本特征
|
52 |
features["width"] = image.width
|
|
|
54 |
features["aspect_ratio"] = image.width / max(1, image.height)
|
55 |
|
56 |
# 颜色分析
|
57 |
+
if len(img_array.shape) == 3:
|
58 |
features["avg_red"] = float(np.mean(img_array[:,:,0]))
|
59 |
features["avg_green"] = float(np.mean(img_array[:,:,1]))
|
60 |
features["avg_blue"] = float(np.mean(img_array[:,:,2]))
|
61 |
|
62 |
+
# 边缘一致性分析
|
63 |
+
edges = cv2.Canny(img_cv, 100, 200)
|
64 |
+
features["edge_density"] = float(np.sum(edges > 0) / (image.width * image.height))
|
65 |
+
|
66 |
+
# 纹理分析 - 使用灰度共生矩阵
|
67 |
+
if len(img_array.shape) == 3:
|
68 |
+
gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
|
69 |
+
glcm = cv2.createGLCM(gray, 5) # 创建灰度共生矩阵
|
70 |
+
features["texture_contrast"] = cv2.GLCMContrast(glcm)
|
71 |
+
features["texture_homogeneity"] = cv2.GLCMHomogeneity(glcm)
|
72 |
+
|
73 |
+
# 噪声分析
|
74 |
+
if len(img_array.shape) == 3:
|
75 |
+
blurred = cv2.GaussianBlur(img_cv, (5, 5), 0)
|
76 |
+
noise = cv2.absdiff(img_cv, blurred)
|
77 |
+
features["noise_level"] = float(np.mean(noise))
|
78 |
+
|
79 |
return features
|
80 |
|
81 |
+
def detect_ai_image(image):
|
82 |
+
if image is None:
|
83 |
+
return {"error": "未提供图像"}
|
84 |
+
|
85 |
+
results = {}
|
86 |
+
valid_models = 0
|
87 |
+
weighted_ai_probability = 0
|
88 |
+
|
89 |
+
# 使用每个模型进行预测
|
90 |
+
for key, model_info in models.items():
|
91 |
+
if model_info["processor"] is not None and model_info["model"] is not None:
|
92 |
+
try:
|
93 |
+
# 处理图像
|
94 |
+
inputs = model_info["processor"](images=image, return_tensors="pt")
|
95 |
+
with torch.no_grad():
|
96 |
+
outputs = model_info["model"](**inputs)
|
97 |
+
|
98 |
+
# 获取预测结果
|
99 |
+
logits = outputs.logits
|
100 |
+
predicted_class_idx = logits.argmax(-1).item()
|
101 |
+
|
102 |
+
# 获取概率
|
103 |
+
probabilities = torch.nn.functional.softmax(logits, dim=-1)
|
104 |
+
|
105 |
+
# 确定AI生成概率
|
106 |
+
ai_label_idx = None
|
107 |
+
for idx, label in model_info["model"].config.id2label.items():
|
108 |
+
if "ai" in label.lower() or "generated" in label.lower() or "fake" in label.lower():
|
109 |
+
ai_label_idx = idx
|
110 |
+
break
|
111 |
+
|
112 |
+
if ai_label_idx is None:
|
113 |
+
ai_label_idx = 1 # 默认索引1为AI生成
|
114 |
+
|
115 |
+
ai_probability = float(probabilities[0][ai_label_idx].item())
|
116 |
+
|
117 |
+
# 添加到结果
|
118 |
+
results[key] = {
|
119 |
+
"model_name": model_info["name"],
|
120 |
+
"ai_probability": ai_probability,
|
121 |
+
"predicted_class": model_info["model"].config.id2label[predicted_class_idx]
|
122 |
+
}
|
123 |
+
|
124 |
+
# 累加加权概率
|
125 |
+
weighted_ai_probability += ai_probability * model_info["weight"]
|
126 |
+
valid_models += 1
|
127 |
+
|
128 |
+
except Exception as e:
|
129 |
+
results[key] = {
|
130 |
+
"model_name": model_info["name"],
|
131 |
+
"error": str(e)
|
132 |
+
}
|
133 |
+
|
134 |
+
# 计算最终加权概率
|
135 |
+
final_ai_probability = weighted_ai_probability / max(sum(m["weight"] for k, m in models.items() if m["processor"] is not None), 1)
|
136 |
+
|
137 |
+
# 分析图像特征
|
138 |
+
image_features = analyze_image_features(image)
|
139 |
+
|
140 |
+
# 确定置信度级别
|
141 |
+
if final_ai_probability > 0.7:
|
142 |
+
confidence_level = "高概率AI生成"
|
143 |
+
elif final_ai_probability < 0.3:
|
144 |
+
confidence_level = "高概率人类创作"
|
145 |
+
else:
|
146 |
+
confidence_level = "无法确定"
|
147 |
+
|
148 |
+
# 构建最终结果
|
149 |
+
final_result = {
|
150 |
+
"ai_probability": final_ai_probability,
|
151 |
+
"confidence_level": confidence_level,
|
152 |
+
"individual_model_results": results,
|
153 |
+
"features": image_features
|
154 |
+
}
|
155 |
+
|
156 |
+
return final_result
|
157 |
+
|
158 |
# 创建Gradio界面
|
159 |
iface = gr.Interface(
|
160 |
fn=detect_ai_image,
|
161 |
inputs=gr.Image(type="pil"),
|
162 |
outputs=gr.JSON(),
|
163 |
+
title="增强型AI图像检测API",
|
164 |
+
description="多模型集成检测图像是否由AI生成",
|
165 |
+
examples=[
|
166 |
+
["example1.jpg"],
|
167 |
+
["example2.jpg"]
|
168 |
+
],
|
169 |
+
allow_flagging="never"
|
170 |
)
|
171 |
|
172 |
iface.launch()
|