Update app.py
Browse files
app.py
CHANGED
|
@@ -2,10 +2,10 @@ import gradio as gr
|
|
| 2 |
from transformers import pipeline
|
| 3 |
import spaces
|
| 4 |
|
| 5 |
-
#
|
| 6 |
classifier = None
|
| 7 |
|
| 8 |
-
# 2. 核心预测逻辑(使用 ZeroGPU)
|
| 9 |
@spaces.GPU
|
| 10 |
def predict_plant(image):
|
| 11 |
global classifier
|
|
@@ -15,26 +15,42 @@ def predict_plant(image):
|
|
| 15 |
# 首次识别时才在 GPU 上加载模型
|
| 16 |
if classifier is None:
|
| 17 |
print("正在 GPU 上初始化植物识别模型...")
|
|
|
|
|
|
|
| 18 |
classifier = pipeline(
|
| 19 |
task="image-classification",
|
| 20 |
-
model="
|
| 21 |
)
|
| 22 |
print("模型加载完成!")
|
| 23 |
|
| 24 |
# 推理
|
| 25 |
results = classifier(image, top_k=5)
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
return formatted_results
|
| 28 |
|
| 29 |
|
| 30 |
-
# 3. 极简 Interface 布局
|
| 31 |
demo = gr.Interface(
|
| 32 |
fn=predict_plant,
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
| 36 |
)
|
| 37 |
|
| 38 |
-
# 4. 启动
|
| 39 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 40 |
demo.launch()
|
|
|
|
| 2 |
from transformers import pipeline
|
| 3 |
import spaces
|
| 4 |
|
| 5 |
+
# 全局变量(懒加载用)
|
| 6 |
classifier = None
|
| 7 |
|
| 8 |
+
# 2. 核心预测逻辑(使用 ZeroGPU 加速)
|
| 9 |
@spaces.GPU
|
| 10 |
def predict_plant(image):
|
| 11 |
global classifier
|
|
|
|
| 15 |
# 首次识别时才在 GPU 上加载模型
|
| 16 |
if classifier is None:
|
| 17 |
print("正在 GPU 上初始化植物识别模型...")
|
| 18 |
+
# 【关键修改】换成了专门针对植物叶片的微调模型
|
| 19 |
+
# 它比 google/vit 更能准确识别植物品种
|
| 20 |
classifier = pipeline(
|
| 21 |
task="image-classification",
|
| 22 |
+
model="Nymphaea/plant-classifier"
|
| 23 |
)
|
| 24 |
print("模型加载完成!")
|
| 25 |
|
| 26 |
# 推理
|
| 27 |
results = classifier(image, top_k=5)
|
| 28 |
+
|
| 29 |
+
# 格式化结果,并过滤掉置信度极低(如 0.00x)的干扰项
|
| 30 |
+
formatted_results = {}
|
| 31 |
+
for res in results:
|
| 32 |
+
# 保留有实际置信度的结果
|
| 33 |
+
if res["score"] > 0.001:
|
| 34 |
+
formatted_results[res["label"]] = float(res["score"])
|
| 35 |
+
|
| 36 |
+
# 如果过滤后结果为空(极少发生),则返回一个提示
|
| 37 |
+
if not formatted_results:
|
| 38 |
+
return {"未能识别出明显植物": 1.0}
|
| 39 |
+
|
| 40 |
return formatted_results
|
| 41 |
|
| 42 |
|
| 43 |
+
# 3. 极简 Interface 布局
|
| 44 |
demo = gr.Interface(
|
| 45 |
fn=predict_plant,
|
| 46 |
+
# 建议用户在手机/上传时尽量裁剪掉过多的背景(花盆、栏杆),只拍叶子
|
| 47 |
+
inputs=gr.Image(type="pil", sources=["upload", "webcam"], label="📸 请拍摄植物叶片特写(尽量避开花盆和背景)"),
|
| 48 |
+
outputs=gr.Label(num_top_classes=5, label="🔍 植物识别结果 (Top 5)"),
|
| 49 |
+
title="🌱 智能植物品种识别"
|
| 50 |
)
|
| 51 |
|
| 52 |
+
# 4. 启动
|
| 53 |
if __name__ == "__main__":
|
| 54 |
+
# 这里的 server_name 和 server_port 在 Hugging Face 上会自动忽略,
|
| 55 |
+
# 保留是为了方便你在本地测试时运行
|
| 56 |
demo.launch()
|