File size: 2,430 Bytes
f2e6302
757d49e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dee7795
 
757d49e
 
 
dee7795
757d49e
dee7795
757d49e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dee7795
757d49e
 
 
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
from PIL import Image
from transformers import pipeline
import gradio as gr

# 🌐 Load pre-trained image classification model
classifier = pipeline("image-classification", model="microsoft/resnet-50")

# 🔍 Define bilingual label mapping
label_map = {
    "agaric": ("Edible", "กินได้"),
    "bolete": ("Edible", "กินได้"),
    "gyromitra": ("Poisonous", "พิษ"),
    "amanita": ("Poisonous", "พิษ"),
    "earthstar": ("Edible", "กินได้"),
    "hen-of-the-woods": ("Edible", "กินได้"),
    "mushroom": ("Unknown", "ไม่ทราบ"),
    "coral fungus": ("Poisonous", "พิษ"),
    # Add more if needed
}

def classify_mushroom(image: Image.Image):
    print("✅ classify_mushroom: NEW VERSION")

    try:
        image = image.convert("RGB")
        result = classifier(image)
        print("🔍 Raw result from model:", result)

        result = result[0]
        label = result['label'].lower()
        score = round(result['score'] * 100, 2)

        prediction_en, prediction_th = label_map.get(label, ("Unknown", "ไม่ทราบ"))
        print("✅ RETURNING:", prediction_en, prediction_th, f"{score:.2f}%")
        return prediction_en, prediction_th, f"{score:.2f}%"

    except Exception as e:
        print(f"❌ Error: {e}")
        return "Error", "ผิดพลาด", "N/A"

# ✅ Put Gradio inside the main block
if __name__ == "__main__":
    with gr.Blocks() as demo:
        gr.Markdown("## 🍄 Mushroom Safety Classifier")
        gr.Markdown("Upload a mushroom photo to check if it’s edible or poisonous.\nอัปโหลดรูปเห็ดเพื่อทำนายว่าเห็ดกินได้หรือมีพิษ")

        with gr.Row():
            image_input = gr.Image(type="pil", label="📷 Upload Mushroom Image")
            with gr.Column():
                label_en = gr.Textbox(label="🧠 Prediction (English)")
                label_th = gr.Textbox(label="🗣️ คำทำนาย (ภาษาไทย)")
                confidence = gr.Textbox(label="📶 Confidence Score")

        classify_btn = gr.Button("🔍 Classify")

        classify_btn.click(
            fn=classify_mushroom,
            inputs=image_input,
            outputs=[label_en, label_th, confidence]
        )

    demo.launch()