CoolFace
Apppublic

kmunzwa/gatekeeper_float16

sourceHugging Faceapache-2.0updated 4mo agoView on Hugging Face
0likes
app.py149 linesDownload Raw Back to root
1# gradio is the library used to build the web interface2import gradio as gr3 4# numpy is used for numerical operations5import numpy as np6 7# ai_edge_litert is Google's official TFLite runtime8from ai_edge_litert.interpreter import Interpreter9 10# PIL is used for image loading and conversion11from PIL import Image12 13 14# ------------------------------------15# LOAD THE MODEL16# ------------------------------------17 18interpreter = Interpreter(model_path="resnet50_float32.tflite")19interpreter.allocate_tensors()20 21input_details  = interpreter.get_input_details()22output_details = interpreter.get_output_details()23 24INPUT_SIZE = (224, 224)25 26print("Gatekeeper model loaded successfully")27 28 29# ------------------------------------30# THRESHOLD31# ------------------------------------32 33# cervix must score at least 0.55 to be accepted as a positive detection34CERVIX_THRESHOLD = 0.5535 36 37# ------------------------------------38# IMAGE PREPROCESSING FUNCTION39# ------------------------------------40 41def preprocess_image(image):42    img = Image.fromarray(image).convert("RGB").resize(INPUT_SIZE)43    img = np.array(img, dtype=np.float32) / 255.044    img = np.expand_dims(img, axis=0)45    return img46 47 48# ------------------------------------49# CLASSIFICATION FUNCTION50# ------------------------------------51 52def classify_image(image):53    if image is None:54        return None, "Please upload an image first"55 56    # preprocess and run inference57    processed = preprocess_image(image)58    interpreter.set_tensor(input_details[0]['index'], processed)59    interpreter.invoke()60    output = interpreter.get_tensor(output_details[0]['index'])61 62    print(f"Raw model output: {output}")63 64    prob_non_cervix = float(output[0][0])65    prob_cervix     = float(output[0][1])66 67    print(f"Non-Cervix: {prob_non_cervix:.4f} | Cervix: {prob_cervix:.4f}")68 69    # simple threshold check70    if prob_cervix >= CERVIX_THRESHOLD:71        prediction_text = "Cervix Detected"72    else:73        prediction_text = "Non-Cervix"74 75    scores = {76        "Cervix":     round(prob_cervix, 4),77        "Non-Cervix": round(prob_non_cervix, 4),78    }79 80    return scores, prediction_text81 82 83# ------------------------------------84# GRADIO USER INTERFACE85# ------------------------------------86 87with gr.Blocks(theme=gr.themes.Soft()) as app:88 89    gr.Markdown("""90    # Gatekeeper Model91    ### Cervix Image Binary Classifier92    Upload an image to classify it as Cervix or Non-Cervix93    ---94    """)95 96    with gr.Row():97 98        with gr.Column():99            input_image = gr.Image(100                label="Upload Image",101                type="numpy"102            )103            classify_btn = gr.Button(104                "Run Classification",105                variant="primary",106                size="lg"107            )108            clear_btn = gr.Button(109                "Clear",110                variant="secondary",111                size="sm"112            )113 114        with gr.Column():115            output_scores = gr.Label(116                label="Confidence Scores",117                num_top_classes=2118            )119            output_text = gr.Textbox(120                label="Prediction",121                interactive=False,122                text_align="center"123            )124 125    gr.Markdown("""126    ---127    | Index | Label       | Meaning                          |128    |-------|-------------|----------------------------------|129    | 0     | Non-Cervix  | Image does NOT contain cervix    |130    | 1     | Cervix      | Image contains cervix            |131 132    ---133    Disclaimer: This tool is for research purposes only.134    It is not intended for clinical diagnosis or medical use.135    """)136 137    classify_btn.click(138        fn=classify_image,139        inputs=input_image,140        outputs=[output_scores, output_text]141    )142 143    clear_btn.click(144        fn=lambda: (None, None, ""),145        inputs=None,146        outputs=[input_image, output_scores, output_text]147    )148 149app.launch()