selva1909 commited on
Commit
688899b
·
verified ·
1 Parent(s): b85d42b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -43
app.py CHANGED
@@ -1,63 +1,103 @@
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")
 
1
  import gradio as gr
2
  import numpy as np
3
  import tensorflow as tf
4
+ from tensorflow.keras.models import Model, load_model
5
+ from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
6
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
7
  import os
8
 
9
+ # Settings
10
+ MODEL_FILE = "brain_tumor_mobilenet.h5"
11
+ IMG_SIZE = (224, 224)
12
+ BATCH_SIZE = 16
13
+ EPOCHS = 5 # change/fine-tune more if you have real data
14
 
15
+ # Utility: prepare data
16
+ def get_dataset(data_dir="data"):
17
+ """
18
+ Expect data_dir with two subfolders: `tumor` and `no_tumor`, containing images.
19
+ """
20
+ datagen = ImageDataGenerator(
21
+ rescale=1./255,
22
+ validation_split=0.2
23
+ )
24
+ train_gen = datagen.flow_from_directory(
25
+ data_dir,
26
+ target_size=IMG_SIZE,
27
+ batch_size=BATCH_SIZE,
28
+ class_mode="binary",
29
+ subset="training"
30
+ )
31
+ val_gen = datagen.flow_from_directory(
32
+ data_dir,
33
+ target_size=IMG_SIZE,
34
+ batch_size=BATCH_SIZE,
35
+ class_mode="binary",
36
+ subset="validation"
37
+ )
38
+ return train_gen, val_gen
39
+
40
+ # 1. Build or Load model
41
  if not os.path.exists(MODEL_FILE):
42
+ # if you have dataset
43
+ has_data = os.path.isdir("data")
44
+ base_model = tf.keras.applications.MobileNetV2(
45
+ weights="imagenet",
46
+ include_top=False,
47
+ input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3)
48
+ )
49
+ x = base_model.output
50
+ x = GlobalAveragePooling2D()(x)
51
+ x = Dropout(0.5)(x)
52
+ output = Dense(1, activation="sigmoid")(x)
53
+ model = Model(inputs=base_model.input, outputs=output)
54
 
55
+ # Freeze base layers first
56
+ for layer in base_model.layers:
57
+ layer.trainable = False
 
 
 
 
 
 
 
58
 
59
  model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
 
60
 
61
+ if has_data:
62
+ train_gen, val_gen = get_dataset("data")
63
+ model.fit(train_gen, validation_data=val_gen, epochs=EPOCHS)
64
+ # Optionally unfreeze some layers and fine‐tune
65
+ else:
66
+ # Dummy training if no dataset, just random noise (NOT for real use)
67
+ dummy_x = np.random.rand(20, IMG_SIZE[0], IMG_SIZE[1], 3)
68
+ dummy_y = np.random.randint(0, 2, size=(20,))
69
+ model.fit(dummy_x, dummy_y, epochs=2, batch_size=4)
70
 
71
+ model.save(MODEL_FILE)
72
+ else:
73
+ model = load_model(MODEL_FILE)
 
74
 
75
+ # 2. Prediction function
 
 
76
  def predict_brain_tumor(image):
77
+ """
78
+ Input: PIL image via Gradio upload
79
+ Output: prediction string + probability
80
+ """
81
+ if image is None:
82
+ return "No image provided"
83
+ img = image.resize(IMG_SIZE)
84
+ img_arr = np.array(img) / 255.0
85
+ if img_arr.shape[-1] == 1:
86
+ img_arr = np.stack([img_arr]*3, axis=-1) # grayscale → 3 channels
87
+ elif img_arr.shape[-1] == 4:
88
+ # drop alpha
89
+ img_arr = img_arr[..., :3]
90
+ img_batch = np.expand_dims(img_arr, axis=0)
91
+ prob = model.predict(img_batch)[0][0]
92
+ if prob > 0.5:
93
+ return f"🧠 Tumor Detected (confidence {prob:.2f})"
94
  else:
95
+ return f"✅ No Tumor Detected (confidence {1-prob:.2f})"
96
 
97
+ # 3. Gradio UI
 
 
98
  with gr.Blocks() as demo:
99
+ gr.Markdown("# Brain Tumor Detection via Transfer Learning (MobileNetV2)")
100
+ gr.Markdown("Upload an MRI brain scan to detect presence of tumor vs no tumor.")
101
 
102
  image_input = gr.Image(type="pil", label="Upload MRI Image")
103
  output_text = gr.Textbox(label="Prediction")