Spaces:
Sleeping

File size: 3,128 Bytes
fb14bd4
 
 
 
 
 
 
 
 
 
 
 
 
cec4326
 
 
 
 
 
 
 
 
 
fb14bd4
cec4326
 
fb14bd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7463dc
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import sys
from pathlib import Path

# Ensure UTF-8 output on Windows terminals
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")

import gradio as gr
from PIL import Image
from model import predict_flower, CATEGORIES, FLOWER_DETAILS

# Hugging Face ZeroGPU decorator support
try:
    import spaces
except ImportError:
    class DummySpaces:
        def GPU(self, fn=None, duration=60):
            if fn is None:
                return lambda f: f
            return fn
    spaces = DummySpaces()


@spaces.GPU
def classify_flower(image):
    if image is None:
        return "Please upload an image.", {}, ""

    res = predict_flower(image)
    top_name = res["display_name"]
    confidence = res["confidence_pct"]
    info = res["flower_info"]
    icon = info.get("icon", "🌸")
    sci_name = info.get("scientific_name", "")

    # Top prediction badge text
    title_text = f"## {icon} {top_name} ({confidence})\n*{sci_name}*"

    # Dictionary of label -> probability for Gradio Label component
    prob_dict = {item["display_name"]: item["probability"] for item in res["ranked_list"]}

    # Botanical details
    details_md = f"""
### 🌿 Botanical Profile:
- **Family:** {info.get('family', 'N/A')}
- **Blooms:** {info.get('season', 'N/A')}
- **Description:** {info.get('description', '')}

*Inference Hardware:* `{res['device'].upper()}`
    """

    return title_text, prob_dict, details_md


# Gather sample examples
examples = []
sample_dir = Path("static/samples")
if sample_dir.is_dir():
    for f in sorted(sample_dir.glob("*.jpg")):
        examples.append([str(f)])

with gr.Blocks(title="ScratchNet — 7-Class Flower Classifier") as demo:
    gr.Markdown("""
    # 🪷 ScratchNet AI — 7-Class Flower Classifier
    Upload or capture a photo of a flower to classify between **Daisy, Dandelion, Rose, Sunflower, Tulip, Bellflower, and Lotus**.
    Powered by a custom 3-block 2D Convolutional Neural Network (PyTorch).
    """)

    with gr.Row():
        with gr.Column():
            input_image = gr.Image(type="pil", label="Upload Flower Image")
            predict_btn = gr.Button("🌸 Classify Flower", variant="primary")
            if examples:
                gr.Examples(examples=examples, inputs=input_image, label="Verified Flower Samples")

        with gr.Column():
            output_title = gr.Markdown(label="Predicted Flower")
            output_labels = gr.Label(num_top_classes=7, label="Class Probabilities")
            output_details = gr.Markdown(label="Botanical Insights")

    predict_btn.click(
        fn=classify_flower,
        inputs=input_image,
        outputs=[output_title, output_labels, output_details],
    )
    input_image.change(
        fn=classify_flower,
        inputs=input_image,
        outputs=[output_title, output_labels, output_details],
    )

if __name__ == "__main__":
    print("Launching Gradio interface...")
    demo.queue().launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)