Spaces:
Sleeping
Sleeping
Download plant_classifier/gui.py from ZZW45/image-classifier: direct link, hf CLI and curl.
- Browser
- Download file 6.77 kB
-
https://huggingface.co/spaces/ZZW45/image-classifier/resolve/main/plant_classifier/gui.py
- Command line
-
hf download hf://spaces/ZZW45/image-classifier/plant_classifier/gui.py
-
curl -L -o gui.py https://huggingface.co/spaces/ZZW45/image-classifier/resolve/main/plant_classifier/gui.py
6.77 kB
| """A small Gradio interface backed by one persistent image classifier.""" | |
| from __future__ import annotations | |
| from collections.abc import Callable | |
| from pathlib import Path | |
| import gradio as gr | |
| from PIL import Image | |
| import torch | |
| from .checkpoint import load_checkpoint | |
| from .inference import prediction_transform, resolve_device | |
| WAITING_MESSAGE = "### 等待识别\n\n上传图片后,点击左侧的“开始识别”。" | |
| def _readable_label(name: str) -> str: | |
| if name == "Background_without_leaves": | |
| return "无叶片背景" | |
| return name.replace("___", " · ").replace("_", " ") | |
| class ImageClassifier: | |
| """Load weights once and reuse the CLI's deterministic image preprocessing.""" | |
| def __init__(self, checkpoint_path: str, device: str = "cpu") -> None: | |
| path = Path(checkpoint_path) | |
| if not path.is_file(): | |
| raise FileNotFoundError(f"找不到模型文件:{path}。请先完成训练或指定已有权重。") | |
| self.device = resolve_device(device) | |
| self.model, checkpoint = load_checkpoint(path, self.device) | |
| self.class_names = list(checkpoint["class_names"]) | |
| self.transform = prediction_transform(checkpoint) | |
| def classify(self, image: Image.Image | None) -> tuple[str, dict[str, float], list[list[str]]]: | |
| if image is None: | |
| raise gr.Error("请先上传一张叶片图片,再点击“开始识别”。") | |
| if not isinstance(image, Image.Image): | |
| raise gr.Error("无法读取这张图片,请上传 JPG、PNG 或其他常见图片格式。") | |
| try: | |
| tensor = self.transform(image).unsqueeze(0).to(self.device) | |
| except (OSError, ValueError) as error: | |
| raise gr.Error("无法读取这张图片,请换一张图片重试。") from error | |
| with torch.inference_mode(): | |
| logits = self.model(tensor) | |
| if logits.shape != (1, len(self.class_names)): | |
| raise RuntimeError("Model output does not match the saved class mapping") | |
| probabilities = logits.float().softmax(dim=1)[0] | |
| if not torch.isfinite(probabilities).all(): | |
| raise gr.Error("本次识别未能完成,请重新上传图片后重试。") | |
| scores, indices = probabilities.topk(min(5, len(self.class_names))) | |
| ranking = { | |
| self.class_names[index]: float(score) | |
| for index, score in zip(indices.cpu().tolist(), scores.cpu().tolist()) | |
| } | |
| best_label, confidence = next(iter(ranking.items())) | |
| summary = f"### {_readable_label(best_label)}\n\n预测概率 **{confidence:.2%}**" | |
| rows = [[name, f"{score:.2%}"] for name, score in ranking.items()] | |
| return summary, ranking, rows | |
| def create_app( | |
| checkpoint_path: str, | |
| device: str = "cpu", | |
| example_path: str | None = None, | |
| *, | |
| prediction_decorator: Callable[[Callable], Callable] | None = None, | |
| ) -> gr.Blocks: | |
| """Build the page and load its classifier without starting a web server.""" | |
| classifier = ImageClassifier(checkpoint_path, device) | |
| classify = classifier.classify | |
| if prediction_decorator is not None: | |
| classify = prediction_decorator(classify) | |
| with gr.Blocks(title="植物病害识别", analytics_enabled=False, fill_width=True) as app: | |
| gr.Markdown("# 植物病害识别\n上传一张叶片照片,查看最可能的分类结果。") | |
| gr.Markdown(f"支持 **{len(classifier.class_names)} 个类别**,包含健康叶片、病害叶片和无叶片背景。") | |
| with gr.Row(equal_height=True, elem_id="classifier-layout"): | |
| with gr.Column(scale=1, min_width=0): | |
| image = gr.Image( | |
| label="叶片照片", type="pil", sources=["upload"], | |
| image_mode="RGB", height=360, | |
| ) | |
| with gr.Row(): | |
| submit = gr.Button("开始识别", variant="primary") | |
| clear = gr.ClearButton(value="清空", variant="secondary") | |
| if example_path is not None and Path(example_path).is_file(): | |
| gr.Examples( | |
| examples=[[str(Path(example_path).resolve())]], inputs=[image], | |
| label="试用示例图片", cache_examples=False, | |
| ) | |
| with gr.Column(scale=1, min_width=0): | |
| summary = gr.Markdown(WAITING_MESSAGE) | |
| probabilities = gr.Label(label="最可能的 5 个类别", num_top_classes=5) | |
| table = gr.Dataframe( | |
| headers=["类别", "预测概率"], datatype=["str", "str"], | |
| row_count=5, column_count=2, interactive=False, | |
| label="分类结果明细", wrap=True, | |
| ) | |
| gr.Markdown("建议选择叶片清晰、光照均匀的照片。概率表示模型对已有类别的判断。") | |
| prediction = submit.click( | |
| classify, inputs=[image], outputs=[summary, probabilities, table], | |
| api_name="classify", concurrency_limit=1, | |
| ) | |
| image.change( | |
| lambda: (WAITING_MESSAGE, None, []), | |
| inputs=None, outputs=[summary, probabilities, table], | |
| queue=False, api_visibility="private", cancels=[prediction], | |
| ) | |
| clear.add([image, summary, probabilities, table]) | |
| return app | |
| def launch_app( | |
| checkpoint_path: str, | |
| device: str = "cpu", | |
| host: str = "0.0.0.0", | |
| port: int = 7860, | |
| example_path: str | None = None, | |
| *, | |
| prediction_decorator: Callable[[Callable], Callable] | None = None, | |
| ) -> None: | |
| app = create_app( | |
| checkpoint_path, device, example_path, prediction_decorator=prediction_decorator, | |
| ) | |
| app.queue(max_size=16, default_concurrency_limit=1).launch( | |
| server_name=host, server_port=port, share=False, show_error=False, footer_links=[], | |
| theme=gr.themes.Soft( | |
| primary_hue="emerald", secondary_hue="green", neutral_hue="slate", | |
| font=["system-ui", "sans-serif"], font_mono=["ui-monospace", "monospace"], | |
| ), | |
| css=""" | |
| .gradio-container { | |
| width: 100% !important; max-width: 1120px !important; | |
| min-width: 0 !important; margin: 0 auto; | |
| } | |
| .gradio-container .main {width: 100%; min-width: 0; box-sizing: border-box;} | |
| #classifier-layout { | |
| display: grid !important; | |
| grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 24px; | |
| } | |
| @media (max-width: 760px) { | |
| .gradio-container .main {padding-left: 16px !important; padding-right: 16px !important;} | |
| #classifier-layout {grid-template-columns: minmax(0, 1fr); gap: 16px;} | |
| } | |
| """, | |
| ) | |