""" 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 = "
Độ tin cậy: {confidence:.2f}%
💡 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.
🤖 Model: EfficientNet-B0 | 📊 Dataset: 100 loài từ GBIF
🔬 Framework: PyTorch + Gradio | 📚 Data: Wikipedia