File size: 1,919 Bytes
114f0e2
3ace57d
812c5d6
3ace57d
8b207f2
812c5d6
 
114f0e2
 
 
 
 
16013be
21abe67
16013be
 
114f0e2
16013be
 
812c5d6
21abe67
114f0e2
21abe67
114f0e2
21abe67
 
114f0e2
21abe67
3ace57d
 
 
16013be
114f0e2
16013be
8b207f2
 
 
 
 
812c5d6
16013be
114f0e2
16013be
 
812c5d6
 
16013be
3742916
8b207f2
3742916
8b207f2
21abe67
8b207f2
544afc8
114f0e2
 
544afc8
3ace57d
 
16013be
114f0e2
16013be
812c5d6
 
16013be
114f0e2
16013be
114f0e2
812c5d6
3ace57d
812c5d6
3742916
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
import os, json
import gradio as gr
import numpy as np
from PIL import Image
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import preprocess_input

# -----------------------------
# Environment
# -----------------------------
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"

# -----------------------------
# Load model
# -----------------------------
MODEL_PATH = "solarguard_resnet_final.keras"
CLASS_JSON = "class_indices.json"

model = tf.keras.models.load_model(MODEL_PATH, compile=False)

# -----------------------------
# Load class mapping (CRITICAL)
# -----------------------------
with open(CLASS_JSON, "r") as f:
    class_indices = json.load(f)

# reverse index -> class
idx_to_class = {v: k for k, v in class_indices.items()}

IMG_SIZE = (224, 224)

# -----------------------------
# Preprocess (same as training)
# -----------------------------
def preprocess_image(img):
    img = img.resize(IMG_SIZE)
    arr = np.array(img).astype("float32")
    arr = np.expand_dims(arr, axis=0)
    return preprocess_input(arr)

# -----------------------------
# Predict
# -----------------------------
def predict(img: Image.Image):
    img = img.convert("RGB")
    x = preprocess_image(img)

    preds = model(x, training=False).numpy()[0]
    idx = int(np.argmax(preds))

    return {
        "Prediction": idx_to_class[idx],
        "Confidence": f"{preds[idx] * 100:.2f}%",
        "Probabilities": {
            idx_to_class[i]: float(preds[i])
            for i in range(len(preds))
        }
    }

# -----------------------------
# UI
# -----------------------------
demo = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil", label="Upload Solar Panel Image"),
    outputs=gr.JSON(label="Result"),
    title="⚡ SolarGuard – Solar Panel Defect Detection",
    description="Accurate ResNet50-based solar panel defect classification"
)

if __name__ == "__main__":
    demo.launch()