selva1909 commited on
Commit
b9f1790
·
verified ·
1 Parent(s): a975b32

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -47
app.py CHANGED
@@ -1,69 +1,68 @@
1
  import gradio as gr
2
- import tensorflow as tf
3
- from tensorflow.keras import layers, models
4
  import numpy as np
 
 
 
5
  import os
6
- import joblib
7
 
8
  MODEL_FILE = "brain_tumor_cnn.h5"
 
9
 
10
- # ---------------------------
11
- # 1. Build or Load Model
12
- # ---------------------------
13
  if not os.path.exists(MODEL_FILE):
14
- # Simple CNN for demo (not trained on real data here!)
15
- model = models.Sequential([
16
- layers.Input(shape=(128, 128, 3)),
17
- layers.Conv2D(16, (3,3), activation='relu'),
18
- layers.MaxPooling2D((2,2)),
19
- layers.Conv2D(32, (3,3), activation='relu'),
20
- layers.MaxPooling2D((2,2)),
21
- layers.Flatten(),
22
- layers.Dense(64, activation='relu'),
23
- layers.Dense(1, activation='sigmoid') # binary: tumor / no tumor
 
 
 
24
  ])
25
- model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
26
-
27
- # Fake training with random data (for demo purposes only!)
28
- X_fake = np.random.rand(50, 128, 128, 3)
29
- y_fake = np.random.randint(0, 2, 50)
30
- model.fit(X_fake, y_fake, epochs=1, verbose=1)
31
-
32
  model.save(MODEL_FILE)
33
- else:
34
- model = tf.keras.models.load_model(MODEL_FILE)
35
 
 
 
 
 
36
 
37
- # ---------------------------
38
- # 2. Prediction Function
39
- # ---------------------------
40
- def predict_tumor(image):
41
- # Resize & normalize
42
- img = image.resize((128, 128))
43
- img_array = np.array(img) / 255.0
44
- img_array = np.expand_dims(img_array, axis=0)
45
 
46
- pred = model.predict(img_array)[0][0]
47
 
48
- if pred > 0.5:
49
- return "🧠 Tumor Detected (Probability: {:.2f})".format(pred)
50
  else:
51
- return "✅ No Tumor Detected (Probability: {:.2f})".format(1 - pred)
52
-
53
 
54
- # ---------------------------
55
- # 3. Gradio UI
56
- # ---------------------------
57
  with gr.Blocks() as demo:
58
- gr.Markdown("# 🧠 Brain Tumor Detection from MRI Image")
59
- gr.Markdown("Upload an MRI scan to predict whether a brain tumor is present (demo with fake training).")
60
 
61
- with gr.Row():
62
- input_img = gr.Image(type="pil", label="Upload MRI Image")
63
-
64
  output_text = gr.Textbox(label="Prediction")
65
 
66
  predict_btn = gr.Button("Predict")
67
- predict_btn.click(fn=predict_tumor, inputs=input_img, outputs=output_text)
68
 
69
  demo.launch()
 
1
  import gradio as gr
 
 
2
  import numpy as np
3
+ import tensorflow as tf
4
+ from tensorflow.keras.models import Sequential, load_model
5
+ from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
6
  import os
 
7
 
8
  MODEL_FILE = "brain_tumor_cnn.h5"
9
+ IMG_SIZE = (128, 128)
10
 
11
+ # -------------------------
12
+ # 1. Train Model (if not exists)
13
+ # -------------------------
14
  if not os.path.exists(MODEL_FILE):
15
+ # ⚠️ Dummy training with random data (replace with actual dataset for real use)
16
+ X_train = np.random.rand(100, IMG_SIZE[0], IMG_SIZE[1], 3)
17
+ y_train = np.random.randint(0, 2, 100)
18
+
19
+ model = Sequential([
20
+ Conv2D(32, (3,3), activation="relu", input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3)),
21
+ MaxPooling2D(2,2),
22
+ Conv2D(64, (3,3), activation="relu"),
23
+ MaxPooling2D(2,2),
24
+ Flatten(),
25
+ Dense(128, activation="relu"),
26
+ Dropout(0.5),
27
+ Dense(1, activation="sigmoid")
28
  ])
29
+
30
+ model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
31
+ model.fit(X_train, y_train, epochs=2, batch_size=8, verbose=1)
32
+
 
 
 
33
  model.save(MODEL_FILE)
 
 
34
 
35
+ # -------------------------
36
+ # 2. Load model
37
+ # -------------------------
38
+ model = load_model(MODEL_FILE)
39
 
40
+ # -------------------------
41
+ # 3. Prediction Function
42
+ # -------------------------
43
+ def predict_brain_tumor(image):
44
+ image = image.resize(IMG_SIZE)
45
+ img_array = np.array(image) / 255.0
46
+ img_array = np.expand_dims(img_array, axis=0) # (1, 128, 128, 3)
 
47
 
48
+ prediction = model.predict(img_array)[0][0]
49
 
50
+ if prediction > 0.5:
51
+ return "🧠 Tumor Detected"
52
  else:
53
+ return "✅ No Tumor Detected"
 
54
 
55
+ # -------------------------
56
+ # 4. Gradio UI
57
+ # -------------------------
58
  with gr.Blocks() as demo:
59
+ gr.Markdown("# 🧠 Brain Tumor Detection (CNN on MRI Images)")
60
+ gr.Markdown("Upload an MRI image to check if a brain tumor is detected.")
61
 
62
+ image_input = gr.Image(type="pil", label="Upload MRI Image")
 
 
63
  output_text = gr.Textbox(label="Prediction")
64
 
65
  predict_btn = gr.Button("Predict")
66
+ predict_btn.click(fn=predict_brain_tumor, inputs=image_input, outputs=output_text)
67
 
68
  demo.launch()