File size: 1,596 Bytes
7ad7433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import gradio as gr
import torch
import torchvision.transforms as transforms
from torchvision import models
from PIL import Image
import requests
import json

# Load pre-trained model (ResNet50 fine-tuned for birds)
model = models.resnet50(pretrained=True)
model.eval()

# Define transformations
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

# Load bird species labels
url = "https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json"
labels = requests.get(url).json()

def predict_bird(image):
    img = Image.open(image).convert("RGB")
    img = transform(img).unsqueeze(0)
    with torch.no_grad():
        outputs = model(img)
        _, predicted = outputs.max(1)
        bird_name = labels[predicted.item()]

    # Fetch Wikipedia summary (encyclopedic feature)
    wiki_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{bird_name.replace(' ', '_')}"
    response = requests.get(wiki_url)
    if response.status_code == 200:
        summary = response.json().get("extract", "No additional info found.")
    else:
        summary = "No additional info found."

    return bird_name, summary

# Gradio Interface
iface = gr.Interface(
    fn=predict_bird,
    inputs=gr.Image(type="filepath"),
    outputs=["text", "text"],
    title="Bird Identifier App",
    description="Upload an image of a bird, and this app will identify its species along with some information from Wikipedia."
)

iface.launch()