Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,6 +5,9 @@ from PIL import Image
|
|
| 5 |
import json
|
| 6 |
import os
|
| 7 |
import logging
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Set up logging
|
| 10 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -21,41 +24,30 @@ def load_model():
|
|
| 21 |
for model_path in complete_model_paths:
|
| 22 |
if os.path.exists(model_path):
|
| 23 |
logger.info(f"Loading complete model from {model_path}")
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
logger.info(f"Model input shape: {mdl.input_shape}")
|
| 27 |
-
logger.info(f"Model output shape: {mdl.output_shape}")
|
| 28 |
-
return mdl
|
| 29 |
|
| 30 |
json_path = 'completemodel1 (1).json'
|
| 31 |
weights_path = 'completeweights.weights.h5'
|
|
|
|
| 32 |
if os.path.exists(json_path) and os.path.exists(weights_path):
|
| 33 |
-
logger.info(f"Loading model architecture from {json_path} and weights from {weights_path}")
|
| 34 |
with open(json_path, 'r') as json_file:
|
| 35 |
model_json = json_file.read()
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
logger.info(f"Model input shape: {mdl.input_shape}")
|
| 40 |
-
logger.info(f"Model output shape: {mdl.output_shape}")
|
| 41 |
-
return mdl
|
| 42 |
|
| 43 |
alternative_json_paths = ['model.json', 'completemodel1.json', 'architecture.json']
|
| 44 |
-
for
|
| 45 |
-
if os.path.exists(
|
| 46 |
-
|
| 47 |
-
with open(alt_json, 'r') as json_file:
|
| 48 |
model_json = json_file.read()
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
logger.info(f"Model input shape: {mdl.input_shape}")
|
| 53 |
-
logger.info(f"Model output shape: {mdl.output_shape}")
|
| 54 |
-
return mdl
|
| 55 |
|
| 56 |
if os.path.exists(weights_path):
|
| 57 |
-
|
| 58 |
-
mdl = tf.keras.Sequential([
|
| 59 |
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(71, 71, 3)),
|
| 60 |
tf.keras.layers.BatchNormalization(),
|
| 61 |
tf.keras.layers.MaxPooling2D(2, 2),
|
|
@@ -75,16 +67,10 @@ def load_model():
|
|
| 75 |
tf.keras.layers.Dropout(0.3),
|
| 76 |
tf.keras.layers.Dense(7, activation='softmax')
|
| 77 |
])
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
logger.info("Weights loaded into fallback architecture")
|
| 81 |
-
return mdl
|
| 82 |
-
except Exception as e:
|
| 83 |
-
logger.error(f"Failed to load weights into fallback architecture: {e}")
|
| 84 |
-
return None
|
| 85 |
|
| 86 |
logger.error("No valid model files found")
|
| 87 |
-
logger.error("Available files: %s", os.listdir('.'))
|
| 88 |
return None
|
| 89 |
|
| 90 |
except Exception as e:
|
|
@@ -92,48 +78,40 @@ def load_model():
|
|
| 92 |
return None
|
| 93 |
|
| 94 |
def load_class_names():
|
| 95 |
-
"""Load class names with multiple fallback options"""
|
| 96 |
try:
|
| 97 |
HAM10000_CLASSES = [
|
| 98 |
'Melanoma',
|
| 99 |
'Melanocytic nevus',
|
| 100 |
'Basal cell carcinoma',
|
| 101 |
-
|
| 102 |
'Benign keratosis',
|
| 103 |
'Dermatofibroma',
|
| 104 |
'Vascular lesion'
|
| 105 |
]
|
|
|
|
| 106 |
json_path = 'class_names_example.json'
|
| 107 |
if os.path.exists(json_path):
|
| 108 |
with open(json_path, 'r') as f:
|
| 109 |
loaded_classes = json.load(f)
|
| 110 |
-
if isinstance(loaded_classes,
|
| 111 |
-
ordered_classes = []
|
| 112 |
-
for class_name in HAM10000_CLASSES:
|
| 113 |
-
ordered_classes.append(loaded_classes.get(class_name, class_name))
|
| 114 |
-
logger.info("Loaded and mapped class names from JSON")
|
| 115 |
-
return ordered_classes
|
| 116 |
-
elif isinstance(loaded_classes, list) and len(loaded_classes) == len(HAM10000_CLASSES):
|
| 117 |
-
logger.info("Loaded class names from JSON list")
|
| 118 |
return loaded_classes
|
|
|
|
|
|
|
| 119 |
|
| 120 |
txt_path = 'class_names.txt'
|
| 121 |
if os.path.exists(txt_path):
|
| 122 |
with open(txt_path, 'r') as f:
|
| 123 |
-
|
| 124 |
-
if len(loaded_classes) == len(HAM10000_CLASSES):
|
| 125 |
-
logger.info("Loaded class names from TXT")
|
| 126 |
-
return loaded_classes
|
| 127 |
|
| 128 |
-
logger.warning("No class name file found, using default")
|
| 129 |
return HAM10000_CLASSES
|
|
|
|
| 130 |
except Exception as e:
|
| 131 |
logger.error(f"Error loading class names: {e}")
|
| 132 |
return [
|
| 133 |
'Melanoma',
|
| 134 |
'Melanocytic nevus',
|
| 135 |
'Basal cell carcinoma',
|
| 136 |
-
|
| 137 |
'Benign keratosis',
|
| 138 |
'Dermatofibroma',
|
| 139 |
'Vascular lesion'
|
|
@@ -141,9 +119,6 @@ def load_class_names():
|
|
| 141 |
|
| 142 |
def preprocess_image(image):
|
| 143 |
try:
|
| 144 |
-
if image is None:
|
| 145 |
-
logger.warning("No image provided")
|
| 146 |
-
return None
|
| 147 |
if image.mode != 'RGB':
|
| 148 |
image = image.convert('RGB')
|
| 149 |
image = image.resize((71, 71), Image.Resampling.LANCZOS)
|
|
@@ -155,86 +130,59 @@ def preprocess_image(image):
|
|
| 155 |
return None
|
| 156 |
|
| 157 |
def predict_image(image):
|
| 158 |
-
global model, class_names
|
| 159 |
try:
|
| 160 |
-
if image is None:
|
| 161 |
-
return "β Please upload an image"
|
| 162 |
if model is None:
|
| 163 |
return "β Model not loaded"
|
| 164 |
if not class_names:
|
| 165 |
-
return "β Class names not
|
| 166 |
-
|
| 167 |
processed_image = preprocess_image(image)
|
| 168 |
if processed_image is None:
|
| 169 |
return "β Error processing image"
|
| 170 |
-
|
| 171 |
predictions = model.predict(processed_image, verbose=0)
|
| 172 |
-
probabilities = predictions[0]
|
| 173 |
-
if len(probabilities) != len(class_names):
|
| 174 |
-
return "β Output size mismatch with class names"
|
| 175 |
-
|
| 176 |
predicted_index = np.argmax(probabilities)
|
| 177 |
predicted_class = class_names[predicted_index]
|
| 178 |
confidence = float(probabilities[predicted_index])
|
| 179 |
-
return f"
|
| 180 |
except Exception as e:
|
| 181 |
-
logger.error(f"Prediction error: {e}")
|
| 182 |
return f"β Prediction error: {str(e)}"
|
| 183 |
|
| 184 |
def initialize_model():
|
| 185 |
global model, class_names
|
| 186 |
-
logger.info("Initializing model and
|
| 187 |
class_names = load_class_names()
|
| 188 |
model = load_model()
|
| 189 |
-
if model is None:
|
| 190 |
-
logger.error("β οΈ Model failed to load. Please check files.")
|
| 191 |
-
else:
|
| 192 |
-
logger.info("β
Model loaded.")
|
| 193 |
|
| 194 |
def create_interface():
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
font-family: 'Helvetica Neue', Arial, sans-serif;
|
| 198 |
-
}
|
| 199 |
-
"""
|
| 200 |
-
with gr.Blocks(css=css, title="Skin Cancer Classifier") as demo:
|
| 201 |
-
gr.Markdown("## π¬ Skin Cancer Classification Demo")
|
| 202 |
-
model_status = "β
Loaded" if model is not None else "β Not Loaded"
|
| 203 |
-
gr.Markdown(f"**Model Status:** {model_status}<br>**Classes:** {len(class_names)}<br>**Input Size:** 71x71")
|
| 204 |
-
|
| 205 |
with gr.Row():
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
input_image.change(fn=predict_image, inputs=[input_image], outputs=[output_text])
|
| 215 |
-
clear_btn.click(lambda: (None, "Waiting for image..."), outputs=[input_image, output_text])
|
| 216 |
-
|
| 217 |
-
with gr.Accordion("βΉοΈ Model Info", open=False):
|
| 218 |
-
gr.Markdown(
|
| 219 |
-
f"""
|
| 220 |
-
**Architecture:** CNN with Conv + BatchNorm + Dense<br>
|
| 221 |
-
**Expected Input Size:** 71x71 RGB<br>
|
| 222 |
-
**Classes:** {", ".join(class_names)}
|
| 223 |
-
"""
|
| 224 |
-
)
|
| 225 |
|
| 226 |
return demo
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import json
|
| 6 |
import os
|
| 7 |
import logging
|
| 8 |
+
from fastapi import FastAPI, File, UploadFile
|
| 9 |
+
from fastapi.responses import JSONResponse
|
| 10 |
+
import io
|
| 11 |
|
| 12 |
# Set up logging
|
| 13 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 24 |
for model_path in complete_model_paths:
|
| 25 |
if os.path.exists(model_path):
|
| 26 |
logger.info(f"Loading complete model from {model_path}")
|
| 27 |
+
model = tf.keras.models.load_model(model_path, compile=False)
|
| 28 |
+
return model
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
json_path = 'completemodel1 (1).json'
|
| 31 |
weights_path = 'completeweights.weights.h5'
|
| 32 |
+
|
| 33 |
if os.path.exists(json_path) and os.path.exists(weights_path):
|
|
|
|
| 34 |
with open(json_path, 'r') as json_file:
|
| 35 |
model_json = json_file.read()
|
| 36 |
+
model = tf.keras.models.model_from_json(model_json)
|
| 37 |
+
model.load_weights(weights_path)
|
| 38 |
+
return model
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
alternative_json_paths = ['model.json', 'completemodel1.json', 'architecture.json']
|
| 41 |
+
for json_path in alternative_json_paths:
|
| 42 |
+
if os.path.exists(json_path) and os.path.exists(weights_path):
|
| 43 |
+
with open(json_path, 'r') as json_file:
|
|
|
|
| 44 |
model_json = json_file.read()
|
| 45 |
+
model = tf.keras.models.model_from_json(model_json)
|
| 46 |
+
model.load_weights(weights_path)
|
| 47 |
+
return model
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
if os.path.exists(weights_path):
|
| 50 |
+
model = tf.keras.Sequential([
|
|
|
|
| 51 |
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(71, 71, 3)),
|
| 52 |
tf.keras.layers.BatchNormalization(),
|
| 53 |
tf.keras.layers.MaxPooling2D(2, 2),
|
|
|
|
| 67 |
tf.keras.layers.Dropout(0.3),
|
| 68 |
tf.keras.layers.Dense(7, activation='softmax')
|
| 69 |
])
|
| 70 |
+
model.load_weights(weights_path)
|
| 71 |
+
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
logger.error("No valid model files found")
|
|
|
|
| 74 |
return None
|
| 75 |
|
| 76 |
except Exception as e:
|
|
|
|
| 78 |
return None
|
| 79 |
|
| 80 |
def load_class_names():
|
|
|
|
| 81 |
try:
|
| 82 |
HAM10000_CLASSES = [
|
| 83 |
'Melanoma',
|
| 84 |
'Melanocytic nevus',
|
| 85 |
'Basal cell carcinoma',
|
| 86 |
+
"Actinic keratosis / Bowen's disease",
|
| 87 |
'Benign keratosis',
|
| 88 |
'Dermatofibroma',
|
| 89 |
'Vascular lesion'
|
| 90 |
]
|
| 91 |
+
|
| 92 |
json_path = 'class_names_example.json'
|
| 93 |
if os.path.exists(json_path):
|
| 94 |
with open(json_path, 'r') as f:
|
| 95 |
loaded_classes = json.load(f)
|
| 96 |
+
if isinstance(loaded_classes, list):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
return loaded_classes
|
| 98 |
+
elif isinstance(loaded_classes, dict):
|
| 99 |
+
return list(loaded_classes.values())
|
| 100 |
|
| 101 |
txt_path = 'class_names.txt'
|
| 102 |
if os.path.exists(txt_path):
|
| 103 |
with open(txt_path, 'r') as f:
|
| 104 |
+
return [line.strip() for line in f.readlines() if line.strip()]
|
|
|
|
|
|
|
|
|
|
| 105 |
|
|
|
|
| 106 |
return HAM10000_CLASSES
|
| 107 |
+
|
| 108 |
except Exception as e:
|
| 109 |
logger.error(f"Error loading class names: {e}")
|
| 110 |
return [
|
| 111 |
'Melanoma',
|
| 112 |
'Melanocytic nevus',
|
| 113 |
'Basal cell carcinoma',
|
| 114 |
+
"Actinic keratosis / Bowen's disease",
|
| 115 |
'Benign keratosis',
|
| 116 |
'Dermatofibroma',
|
| 117 |
'Vascular lesion'
|
|
|
|
| 119 |
|
| 120 |
def preprocess_image(image):
|
| 121 |
try:
|
|
|
|
|
|
|
|
|
|
| 122 |
if image.mode != 'RGB':
|
| 123 |
image = image.convert('RGB')
|
| 124 |
image = image.resize((71, 71), Image.Resampling.LANCZOS)
|
|
|
|
| 130 |
return None
|
| 131 |
|
| 132 |
def predict_image(image):
|
|
|
|
| 133 |
try:
|
|
|
|
|
|
|
| 134 |
if model is None:
|
| 135 |
return "β Model not loaded"
|
| 136 |
if not class_names:
|
| 137 |
+
return "β Class names not loaded"
|
|
|
|
| 138 |
processed_image = preprocess_image(image)
|
| 139 |
if processed_image is None:
|
| 140 |
return "β Error processing image"
|
|
|
|
| 141 |
predictions = model.predict(processed_image, verbose=0)
|
| 142 |
+
probabilities = predictions[0]
|
|
|
|
|
|
|
|
|
|
| 143 |
predicted_index = np.argmax(probabilities)
|
| 144 |
predicted_class = class_names[predicted_index]
|
| 145 |
confidence = float(probabilities[predicted_index])
|
| 146 |
+
return f"β
Predicted: {predicted_class} (Confidence: {confidence*100:.2f}%)"
|
| 147 |
except Exception as e:
|
|
|
|
| 148 |
return f"β Prediction error: {str(e)}"
|
| 149 |
|
| 150 |
def initialize_model():
|
| 151 |
global model, class_names
|
| 152 |
+
logger.info("Initializing model and class names...")
|
| 153 |
class_names = load_class_names()
|
| 154 |
model = load_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
def create_interface():
|
| 157 |
+
with gr.Blocks(title="Skin Cancer Classifier") as demo:
|
| 158 |
+
gr.Markdown("# π¬ Skin Cancer Classification")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
with gr.Row():
|
| 160 |
+
image_input = gr.Image(type="pil", label="Upload Image")
|
| 161 |
+
result_output = gr.Markdown()
|
| 162 |
+
predict_btn = gr.Button("Analyze")
|
| 163 |
+
clear_btn = gr.Button("Clear")
|
| 164 |
+
|
| 165 |
+
predict_btn.click(fn=predict_image, inputs=[image_input], outputs=[result_output])
|
| 166 |
+
image_input.change(fn=predict_image, inputs=[image_input], outputs=[result_output])
|
| 167 |
+
clear_btn.click(lambda: (None, ""), outputs=[image_input, result_output])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
return demo
|
| 170 |
|
| 171 |
+
# ---- Setup for Web API ----
|
| 172 |
+
initialize_model()
|
| 173 |
+
demo = create_interface()
|
| 174 |
+
|
| 175 |
+
app = FastAPI()
|
| 176 |
+
|
| 177 |
+
@app.post("/predict")
|
| 178 |
+
async def predict_endpoint(file: UploadFile = File(...)):
|
| 179 |
+
try:
|
| 180 |
+
image_bytes = await file.read()
|
| 181 |
+
image = Image.open(io.BytesIO(image_bytes))
|
| 182 |
+
result = predict_image(image)
|
| 183 |
+
return JSONResponse({"result": result})
|
| 184 |
+
except Exception as e:
|
| 185 |
+
return JSONResponse({"error": str(e)})
|
| 186 |
+
|
| 187 |
+
# Mount Gradio app to FastAPI
|
| 188 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|