syuanteng315 commited on
Commit
2ea68e4
·
verified ·
1 Parent(s): 45eb1df

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoImageProcessor, SiglipForImageClassification
3
+ from PIL import Image
4
+ import torch
5
+
6
+ # 加载 Trash-Net 模型
7
+ model_name = "prithivMLmods/Trash-Net"
8
+ model = SiglipForImageClassification.from_pretrained(model_name)
9
+ processor = AutoImageProcessor.from_pretrained(model_name)
10
+
11
+ # 定义垃圾分类函数
12
+ def trash_classification(image):
13
+ """输入图片,返回垃圾分类结果"""
14
+ if image is None:
15
+ return {}
16
+
17
+ # 转换图片为 RGB
18
+ image = Image.fromarray(image).convert("RGB")
19
+
20
+ # 转换成模型需要的 tensor
21
+ inputs = processor(images=image, return_tensors="pt")
22
+
23
+ # 模型预测
24
+ with torch.no_grad():
25
+ outputs = model(**inputs)
26
+ logits = outputs.logits
27
+ probs = torch.nn.functional.softmax(logits, dim=1).squeeze().tolist()
28
+
29
+ # 分类标签
30
+ labels = ["cardboard", "glass", "metal", "paper", "plastic", "trash"]
31
+
32
+ # 返回每个类别的概率
33
+ predictions = {labels[i]: round(probs[i], 3) for i in range(len(probs))}
34
+ return predictions
35
+
36
+ # 创建 Gradio 接口
37
+ iface = gr.Interface(
38
+ fn=trash_classification,
39
+ inputs=gr.Image(type="numpy"),
40
+ outputs=gr.Label(label="Prediction Scores"),
41
+ title="Trash Classification",
42
+ description="Upload an image to classify the type of waste material."
43
+ )
44
+
45
+ # 启动
46
+ if __name__ == "__main__":
47
+ iface.launch()