File size: 6,513 Bytes
db6921e
 
 
 
 
 
ee34000
db6921e
ee34000
db6921e
994a3de
ee34000
db6921e
ee34000
 
db6921e
 
 
ee34000
c02b756
994a3de
c02b756
ee34000
c02b756
 
ee34000
c02b756
 
ee34000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
994a3de
db6921e
 
202c514
247a174
 
 
202c514
db6921e
ee34000
994a3de
ee34000
db6921e
ee34000
994a3de
db6921e
 
 
 
 
 
d679dee
 
 
 
 
202c514
ee34000
db6921e
994a3de
ee34000
994a3de
ee34000
994a3de
ee34000
 
 
994a3de
ee34000
 
 
82ee417
e9e2e09
e10acfb
d1ba119
0b95b54
1689721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef82c39
 
0b95b54
d1ba119
ee34000
84e915c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d679dee
ee34000
 
 
9867bc2
ee34000
db6921e
 
ee34000
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import gradio as gr
import tensorflow as tf
import joblib
import numpy as np
import zipfile
import os
import re

# Step 1: Unzip models only once
unzip_dir = "unzipped_models"
zip_file = "Models.zip"  # Ensure this matches exactly the file name uploaded in your Space repo

if not os.path.exists(unzip_dir):
    print("Extracting model zip file...")
    with zipfile.ZipFile(zip_file, 'r') as zip_ref:
        zip_ref.extractall(unzip_dir)
    print("Extraction complete.")

# Step 2: Parse folders to dynamically populate dropdowns

model_root = os.path.join(unzip_dir, 'Models')  # Adjust if ZIP structure is different

activations = []
seeds_dict = dict()
neurons_dict = dict()

for act in os.listdir(model_root):
    act_path = os.path.join(model_root, act)
    if os.path.isdir(act_path) and not act.startswith("linear_models"):
        activations.append(act)
        seeds = []
        for seed_folder in os.listdir(act_path):
            seed_path = os.path.join(act_path, seed_folder)
            if os.path.isdir(seed_path):
                seeds.append(seed_folder)
                neuron_list = []
                for model_file in os.listdir(seed_path):
                    match = re.match(r"model_(\d+)\.keras", model_file)
                    if match:
                        neuron_list.append(int(match.group(1)))
                neurons_dict[(act, seed_folder)] = sorted(neuron_list)
        seeds_dict[act] = sorted(seeds)

activations = sorted(activations)

# Step 3: Prediction function
def predict(r, g, b, activation, seed, neurons):
    try:
        # Normalise R G B 
        r = r/256
        g = g/256
        b = b/256
        
        X = np.array([[r, g, b]])
        
        # Linear prediction (you can replace this with your actual linear model)
        lin_pred_rgb = (1.9221 * r) - (1.3817 * g) + (1.4058 * b) - 0.1318

        # ANN prediction
        keras_path = os.path.join(model_root, activation, seed, f"model_{neurons}.keras")
        if not os.path.exists(keras_path):
            raise FileNotFoundError(f"Model not found: {keras_path}")
        
        model = tf.keras.models.load_model(keras_path)
        ann_pred = model.predict(X)[0][0]

        # Rescale cholestrol concentration prediction in mM and adjust to zero if negative
        if ann_pred < 0:
            ann_pred = 0;
        if lin_pred_rgb < 0:
            lin_pred_rgb = 0;
        return ann_pred*50, lin_pred_rgb*50

    except Exception as e:
        return f"Error: {str(e)}", ""

# Step 4: Dynamic UI update functions (Gradio 4.x compliant)
def update_seeds(activation):
    return gr.update(choices=seeds_dict[activation], value=seeds_dict[activation][0])

def update_neurons(activation, seed):
    neurons = neurons_dict[(activation, seed)]
    return gr.update(choices=neurons, value=neurons[0])

# Gradio Interface
with gr.Blocks() as demo:
    gr.Markdown("# **Au@CeO₂ Nanozyme-Based Smart Colourimetric Sensor for Cholesterol:**")
    gr.Markdown("# **A Neural Network-Powered Point-of-Care Solution Model**")
    gr.Markdown("### **Cholestrol Concentration Prediction Models (CCPM) - Linear and ANN Models**")
    gr.Markdown("**Licence: Creative Commons Attribution Non Commercial Share Alike 4.0	cc-by-nc-sa-4.0**")
    gr.Markdown("Dynamically select models and predict cholesterol concentration. For more information on dataset preparation and the associated experiment, kindly refer to and cite the journal article.")
    
    with gr.Row():
        r = gr.Number(label="Mean R (0 -255)")
        g = gr.Number(label="Mean G (0 -255)")
        b = gr.Number(label="Mean B (0 -255)")

    with gr.Row():
        activation = gr.Dropdown(choices=activations, label="Activation Function", interactive=True)
        seed = gr.Dropdown(choices=seeds, label="Seed", interactive=True)
        neurons = gr.Dropdown(choices=neuron_list, label="Neurons", interactive=True)

    activation.change(update_seeds, inputs=[activation], outputs=[seed])
    seed.change(update_neurons, inputs=[activation, seed], outputs=[neurons])

    with gr.Row():
        btn = gr.Button("Predict")
    
    with gr.Row():
        ann_output = gr.Text(label="Cholestrol Conentration (mM) - ANN Model Prediction ")
        lin_rgb_output = gr.Text(label="Cholestrol Conentration (mM) - Linear Model Prediction")

    gr.Markdown("* Predicted negative concentration adjusted to zero.")

    gr.Markdown("This study presents Artificial Neural Networks (ANNs) and Linear Regression models for predicting cholesterol concentration from RGB colourimetric measurements. Around 2,500 single hidden layered ANN models, with varying activation functions, seed initialisations, and neuron counts were trained to approximate the non-linear relationship between colour channels and concentration levels. The trained models follow a 3-×-1 architecture with three input features (mean R, mean G, mean B), a single hidden layer of varying neurons, and one output neuron. A simple linear regression model was developed alongside as a baseline for comparison. The interface allows users to dynamically select the ANN model configuration and compare its predictions against the linear model. It also supports model selection, and performance evaluation for colour-based biosensing applications.")

    
    
    gr.Markdown("### **Authors:**")
    gr.Markdown("""
**Poornima G**  
Research Scholar, Centre for Nanoscience and Technology, Pondicherry University, Puducherry-605 014  
[Google Scholar](https://scholar.google.com/citations?user=N2uAkJEAAAAJ&hl=en) | [ORCiD](https://orcid.org/0000-0002-7398-5651)

**Nihad Alungal**  
Research Scholar, Centre for Nanoscience and Technology, Pondicherry University, Puducherry-605 014  
[Google Scholar](https://scholar.google.com/citations?hl=en&user=Qi-xkEYAAAAJ) | [ORCiD](https://orcid.org/0009-0000-4561-1874)

**Caxton Emerald S**  
Research Scholar, Department of Computer Science, School of Engineering and Technology, Pondicherry University, Puducherry - 605 014  
[Google Scholar](https://scholar.google.com/citations?user=OgCHQv4AAAAJ&hl=en) | [ORCiD](https://orcid.org/0000-0002-7763-3987)

**Dr. S. Kannan**  
Professor, Centre for Nanoscience and Technology, Pondicherry University, Puducherry-605 014  
[Web Page](http://www.pondiuni.edu.in/profile/dr-s-kannan)
    """)

    btn.click(
        fn=predict, 
        inputs=[r, g, b, activation, seed, neurons],
        outputs=[ann_output, lin_rgb_output]
    )

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