""" Plant Species Classifier - Hugging Face Space AI-powered plant identification with detailed species information """ import gradio as gr import torch import torch.nn as nn from torchvision import models, transforms from PIL import Image import wikipediaapi from io import BytesIO import requests print("🌿 Loading Plant Species Classifier...") # Setup device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"Device: {device}") # Load model checkpoint = torch.load('best_model.pt', map_location=device) num_classes = checkpoint['num_classes'] idx_to_label = checkpoint['idx_to_label'] model_name = checkpoint.get('model_name', 'resnet18') print(f"Model: {model_name}, Classes: {num_classes}") # Build model if model_name == 'efficientnet_b0': model = models.efficientnet_b0(weights=None) model.classifier[1] = nn.Linear(model.classifier[1].in_features, num_classes) else: model = models.resnet18(weights=None) model.fc = nn.Linear(model.fc.in_features, num_classes) model.load_state_dict(checkpoint['model_state_dict']) model = model.to(device) model.eval() # Transform transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # Wikipedia API wiki = wikipediaapi.Wikipedia( language='en', user_agent='PlantClassifier/1.0 (https://huggingface.co/spaces)' ) def get_species_info(species_name): """Fetch species information from Wikipedia""" try: page = wiki.page(species_name) if page.exists(): summary = page.summary[:600] + ("..." if len(page.summary) > 600 else "") return {'title': page.title, 'summary': summary, 'url': page.fullurl, 'found': True} # Try genus genus = species_name.split()[0] page = wiki.page(genus) if page.exists(): summary = page.summary[:600] + ("..." if len(page.summary) > 600 else "") return {'title': f"{page.title} (genus)", 'summary': summary, 'url': page.fullurl, 'found': True} return { 'title': species_name, 'summary': f"No Wikipedia information found for {species_name}. This is a plant species from GBIF dataset.", 'url': '', 'found': False } except Exception as e: return {'title': species_name, 'summary': f"Error: {str(e)}", 'url': '', 'found': False} def load_image(image_source): """Load image from upload or URL""" if isinstance(image_source, str) and image_source.startswith('http'): # URL response = requests.get(image_source, timeout=10, headers={"User-Agent": "Mozilla/5.0"}) response.raise_for_status() return Image.open(BytesIO(response.content)).convert('RGB') else: # Uploaded file return image_source.convert('RGB') if isinstance(image_source, Image.Image) else Image.open(image_source).convert('RGB') def predict(image_input, url_input): """Main prediction function""" try: # Load image if url_input and url_input.strip(): img = load_image(url_input.strip()) elif image_input is not None: img = load_image(image_input) else: return None, "⚠️ Vui lòng upload ảnh hoặc nhập URL", None # Predict img_tensor = transform(img).unsqueeze(0).to(device) with torch.no_grad(): outputs = model(img_tensor) probs = torch.nn.functional.softmax(outputs, dim=1) # Get top 5 topk_probs, topk_indices = probs.topk(5, dim=1) predictions = [] for prob, idx in zip(topk_probs[0], topk_indices[0]): label = idx_to_label[str(idx.item())] predictions.append({'species': label, 'confidence': prob.item()}) # Create prediction buttons HTML buttons_html = "
" buttons_html += "

🎯 Top 5 Dự Đoán (Click để xem chi tiết)

" for i, pred in enumerate(predictions, 1): conf = pred['confidence'] * 100 color = "#2ecc71" if conf > 50 else "#f39c12" if conf > 20 else "#95a5a6" buttons_html += f"""
#{i} {pred['species']}
{conf:.1f}%
""" buttons_html += "
" return img, buttons_html, predictions except Exception as e: return None, f"❌ Lỗi: {str(e)}", None def show_details(predictions, selected_idx): """Show detailed information for selected species""" if not predictions or selected_idx < 1 or selected_idx > 5: return "⚠️ Vui lòng chọn một loài từ danh sách dự đoán" pred = predictions[int(selected_idx) - 1] species = pred['species'] confidence = pred['confidence'] * 100 # Get Wikipedia info info = get_species_info(species) # Build HTML html = f"""

🌿 {species}

Độ tin cậy: {confidence:.2f}%

📚 {info['title']}

{info['summary']}

{f"📖 Đọc thêm trên Wikipedia →" if info['url'] else ""}

💡 Lưu ý: Thông tin được lấy từ Wikipedia. Kết quả dự đoán dựa trên mô hình AI được huấn luyện trên 100 loài thực vật phổ biến từ GBIF.

""" return html # Create Gradio Interface with gr.Blocks(title="🌿 Plant Species Classifier", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # 🌿 Nhận Diện Loài Thực Vật ### Sử dụng AI để xác định loài cây từ ảnh **Hướng dẫn sử dụng:** 1. 📤 Upload ảnh hoặc dán URL ảnh vào ô bên dưới 2. 🔍 Nhấn "Nhận Diện" để xem kết quả 3. 👆 Click vào loài bạn cho là đúng để xem thông tin chi tiết """) predictions_state = gr.State([]) with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 📤 Đầu Vào") image_input = gr.Image( label="Upload Ảnh", type="pil", height=350 ) url_input = gr.Textbox( label="Hoặc Paste URL Ảnh", placeholder="https://example.com/plant.jpg", lines=1 ) with gr.Row(): predict_btn = gr.Button("🔍 Nhận Diện", variant="primary", size="lg") clear_btn = gr.ClearButton([image_input, url_input], value="🗑️ Xóa", size="lg") with gr.Column(scale=1): gr.Markdown("### 🖼️ Ảnh & Kết Quả") display_img = gr.Image(label="Ảnh đã tải", height=350) predictions_display = gr.HTML() gr.Markdown("---") gr.Markdown("### 📖 Thông Tin Chi Tiết") with gr.Row(): species_selector = gr.Slider( minimum=1, maximum=5, step=1, value=1, label="Chọn loài (1-5)", info="Chọn số thứ tự loài để xem thông tin", elem_id="species_selector" ) show_details_btn = gr.Button("📊 Xem Chi Tiết", variant="secondary", size="lg", elem_id="show_details_btn") details_html = gr.HTML() # Event handlers predict_btn.click( fn=predict, inputs=[image_input, url_input], outputs=[display_img, predictions_display, predictions_state] ) show_details_btn.click( fn=show_details, inputs=[predictions_state, species_selector], outputs=[details_html] ) gr.Markdown(""" ---

🤖 Model: EfficientNet-B0 | 📊 Dataset: 100 loài từ GBIF

🔬 Framework: PyTorch + Gradio | 📚 Data: Wikipedia

""") print("✅ App ready!") if __name__ == "__main__": demo.launch()