esssyjr's picture
Update app.py
8335128 verified
Raw History Blame Contribute Delete
8.65 kB
import os
# Configure TensorFlow before importing it or Keras.
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
os.environ["GRADIO_SSR_MODE"] = "False"
import pickle
from pathlib import Path
import numpy as np
from PIL import Image
import gradio as gr
from gtts import gTTS
# --------------------------------------------------
# CONFIGURATION
# --------------------------------------------------
BASE_DIR = Path(__file__).resolve().parent
MODEL_PATH = BASE_DIR / "malaria.pki"
IMAGE_SIZE = (64, 64)
AUDIO_DIR = Path("/tmp/malaria_audio")
AUDIO_DIR.mkdir(parents=True, exist_ok=True)
model = None
audio_cache = {}
# --------------------------------------------------
# LOAD MODEL
# --------------------------------------------------
print("=" * 50)
print("Starting Malaria Classification App")
print("Application directory:", BASE_DIR)
print("Model path:", MODEL_PATH)
print("Model file exists:", MODEL_PATH.is_file())
try:
if not MODEL_PATH.is_file():
raise FileNotFoundError(
f"Model file not found: {MODEL_PATH}"
)
with open(MODEL_PATH, "rb") as f:
model = pickle.load(f)
print("Model loaded successfully.")
print("Model type:", type(model).__name__)
except Exception as e:
model = None
print(
f"MODEL LOADING ERROR: "
f"{type(e).__name__}: {e}"
)
print("=" * 50)
# --------------------------------------------------
# HAUSA AUDIO
# Generate audio only when requested by a prediction.
# Network/audio failures will not crash the app.
# --------------------------------------------------
def generate_hausa_audio(text: str, filename: str):
path = AUDIO_DIR / filename
if path.is_file():
return str(path)
try:
print("Generating Hausa audio:", filename)
tts = gTTS(
text=text,
lang="ha",
slow=False
)
tts.save(str(path))
print("Audio generated successfully:", path)
return str(path)
except Exception as e:
print(
f"AUDIO GENERATION ERROR: "
f"{type(e).__name__}: {e}"
)
return None
# --------------------------------------------------
# PREDICTION
# --------------------------------------------------
def predict_malaria(input_image):
if input_image is None:
return (
"Please upload an image.",
"",
None
)
if model is None:
return (
"Model failed to load. Check the application logs.",
"Ba a iya gudanar da gwajin ba. "
"A tuntubi mai kula da tsarin.",
None
)
try:
# Gradio supplies a NumPy image.
img = Image.fromarray(
np.asarray(input_image)
).convert("RGB")
img = img.resize(IMAGE_SIZE)
img_array = (
np.asarray(img, dtype=np.float32) / 255.0
)
# First try the usual CNN image input:
# (batch, height, width, channels)
processed_input = np.expand_dims(
img_array, axis=0
)
try:
prediction = model.predict(
processed_input,
verbose=0
)
except TypeError:
# Some model wrappers do not accept verbose.
prediction = model.predict(processed_input)
except Exception as first_error:
# Some classical ML models expect flattened images.
print(
"Image-shaped prediction failed:",
repr(first_error)
)
flattened_input = img_array.reshape(1, -1)
prediction = model.predict(flattened_input)
prediction = np.asarray(prediction)
print("Prediction shape:", prediction.shape)
print("Prediction output:", prediction)
values = prediction.reshape(-1)
if values.size == 0:
raise ValueError("Model returned an empty prediction.")
if values.size == 1:
# Assumes a sigmoid probability or binary class output.
value = float(values[0])
if not np.isfinite(value):
raise ValueError("Model returned a non-finite value.")
if value in (0.0, 1.0):
pred_idx = int(value)
elif 0.0 <= value <= 1.0:
pred_idx = int(value >= 0.5)
else:
raise ValueError(
"Single model output is outside [0, 1]. "
"Confirm whether this is a probability or class label."
)
else:
# Assumes a multiclass probability/score vector.
pred_idx = int(np.argmax(values))
# IMPORTANT:
# This assumes class 1 = parasitized and class 0 = uninfected.
if pred_idx == 1:
text_result = "Parasitized (Akwai malaria)"
advice = (
"Sakamako: Ana zargin akwai alamun malaria. "
"A tuntubi likita domin tabbatarwa."
)
audio_path = generate_hausa_audio(
"Akwai yiwuwar malaria. "
"Ka je ka ga likita domin tabbatarwa.",
"parasitized.mp3"
)
elif pred_idx == 0:
text_result = "Uninfected (Babu malaria)"
advice = (
"Sakamako: Ba a gano alamun malaria a wannan hoton ba. "
"Wannan ba ya kawar da yiwuwar cutar. "
"A tuntubi likita idan akwai alamun rashin lafiya."
)
audio_path = generate_hausa_audio(
"Ba a gano alamun malaria a wannan hoton ba. "
"Ka tuntubi likita idan kana jin rashin lafiya.",
"uninfected.mp3"
)
else:
raise ValueError(
f"Unexpected class index: {pred_idx}"
)
return text_result, advice, audio_path
except Exception as e:
print(
f"PREDICTION ERROR: {type(e).__name__}: {e}"
)
return (
f"Prediction failed: {type(e).__name__}: {e}",
"Ba a iya kammala gwajin ba. "
"A sake gwadawa ko a tuntubi mai kula da tsarin.",
None
)
# --------------------------------------------------
# GRADIO INTERFACE
# --------------------------------------------------
with gr.Blocks(title="Malaria Cell Detection") as demo:
gr.Markdown(
"""
# 🔬 Malaria Cell Detection & Hausa Audio Advisor
Upload a cell smear image to run the experimental
classification model and view the Hausa explanation.
**Important:** This is an experimental AI result,
not a medical diagnosis. Consult a qualified healthcare
professional for appropriate testing and interpretation.
"""
)
with gr.Row():
with gr.Column():
image_input = gr.Image(
type="numpy",
label="Upload Cell Smear Image"
)
submit_btn = gr.Button(
"Analyze Image",
variant="primary"
)
with gr.Column():
result_label = gr.Textbox(
label="Classification Result",
interactive=False
)
hausa_text = gr.Textbox(
label="Hausa Explanation",
interactive=False,
lines=4
)
audio_output = gr.Audio(
label="Hausa Voice Response",
type="filepath",
autoplay=False
)
submit_btn.click(
fn=predict_malaria,
inputs=[image_input],
outputs=[
result_label,
hausa_text,
audio_output
]
)
# --------------------------------------------------
# LAUNCH
# --------------------------------------------------
if __name__ == "__main__":
print("Launching Gradio on port 7860...")
try:
# Disable SSR where supported by this Gradio version.
demo.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True,
ssr_mode=False
)
except TypeError as e:
if "ssr_mode" not in str(e):
raise
print(
"This Gradio version does not support ssr_mode. "
"Retrying without that argument."
)
demo.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True
)