Spaces:
Runtime error

aqpahm's picture
Upload 5 files
029eeea verified
Raw History Blame Contribute Delete
10.4 kB
"""
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 = "<div style='margin-top: 20px;'>"
buttons_html += "<h3 style='color: #2c3e50; margin-bottom: 15px;'>🎯 Top 5 Dự Đoán (Click để xem chi tiết)</h3>"
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"""
<div style='margin-bottom: 12px; padding: 15px; background: #f8f9fa;
border-radius: 8px; border-left: 5px solid {color}; cursor: pointer;'
onclick='document.getElementById("species_selector").value={i};
document.getElementById("show_details_btn").click();'>
<div style='display: flex; justify-content: space-between; align-items: center;'>
<div>
<span style='font-weight: bold; color: #2c3e50; font-size: 16px;'>#{i}</span>
<span style='color: #34495e; font-size: 15px; margin-left: 10px;'>{pred['species']}</span>
</div>
<span style='font-weight: bold; color: {color}; font-size: 16px;'>{conf:.1f}%</span>
</div>
<div style='width: 100%; height: 8px; background: #e0e0e0; border-radius: 4px; margin-top: 8px;'>
<div style='width: {conf}%; height: 100%; background: {color}; border-radius: 4px;'></div>
</div>
</div>
"""
buttons_html += "</div>"
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"""
<div style='padding: 25px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 15px; color: white; margin-bottom: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);'>
<h1 style='margin: 0 0 10px 0; font-size: 32px; font-weight: bold;'>🌿 {species}</h1>
<p style='margin: 0; font-size: 20px; opacity: 0.95;'>Độ tin cậy: {confidence:.2f}%</p>
</div>
<div style='background: white; padding: 25px; border-radius: 15px; margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);'>
<h2 style='color: #2c3e50; margin-top: 0; font-size: 24px;'>📚 {info['title']}</h2>
<p style='line-height: 1.8; color: #34495e; font-size: 16px; text-align: justify;'>{info['summary']}</p>
{f"<a href='{info['url']}' target='_blank' style='display: inline-block; margin-top: 15px; padding: 10px 20px; background: #3498db; color: white; text-decoration: none; border-radius: 8px; font-weight: 600;'>📖 Đọc thêm trên Wikipedia →</a>" if info['url'] else ""}
</div>
<div style='background: #fff3cd; padding: 20px; border-radius: 10px; border-left: 5px solid #ffc107;'>
<p style='margin: 0; color: #856404; font-size: 15px;'>
<strong>💡 Lưu ý:</strong> 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.
</p>
</div>
"""
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("""
---
<div style='text-align: center; color: #7f8c8d; padding: 20px;'>
<p><strong>🤖 Model:</strong> EfficientNet-B0 | <strong>📊 Dataset:</strong> 100 loài từ GBIF</p>
<p><strong>🔬 Framework:</strong> PyTorch + Gradio | <strong>📚 Data:</strong> Wikipedia</p>
</div>
""")
print("✅ App ready!")
if __name__ == "__main__":
demo.launch()