Spaces:
Sleeping
Sleeping
Download app.py from aee4/G17-AMFU-Net-Demo: direct link, hf CLI and curl.
- Browser
- Download file 6.36 kB
-
https://huggingface.co/spaces/aee4/G17-AMFU-Net-Demo/resolve/main/app.py
- Command line
-
hf download hf://spaces/aee4/G17-AMFU-Net-Demo/app.py
-
curl -L -o app.py https://huggingface.co/spaces/aee4/G17-AMFU-Net-Demo/resolve/main/app.py
6.36 kB
| import cv2 | |
| import gradio as gr | |
| import numpy as np | |
| import spaces | |
| import torch | |
| from PIL import Image | |
| from modeling_amfu import AMFUNet | |
| from preprocessing import preprocess_ultrasound | |
| MODEL_REPOSITORY = "aee4/G17-AMFU-Net-Paper" | |
| CUSTOM_CSS = """ | |
| html, | |
| body { | |
| overflow-x: hidden !important; | |
| } | |
| .gradio-container { | |
| width: 100% !important; | |
| max-width: 1200px !important; | |
| margin: 0 auto !important; | |
| padding: 16px !important; | |
| } | |
| @media (max-width: 700px) { | |
| .gradio-container { | |
| padding: 8px !important; | |
| } | |
| h1 { | |
| font-size: 1.55rem !important; | |
| line-height: 1.25 !important; | |
| } | |
| } | |
| """ | |
| # Load the trained model once when the Space starts. | |
| model = AMFUNet.from_pretrained( | |
| MODEL_REPOSITORY, | |
| ) | |
| model.eval() | |
| def create_overlay(original_gray, binary_mask): | |
| original_rgb = cv2.cvtColor( | |
| original_gray, | |
| cv2.COLOR_GRAY2RGB, | |
| ) | |
| colour_mask = np.zeros_like( | |
| original_rgb, | |
| dtype=np.uint8, | |
| ) | |
| # Red region represents the predicted lesion. | |
| colour_mask[:, :, 0] = binary_mask | |
| overlay = cv2.addWeighted( | |
| original_rgb, | |
| 0.72, | |
| colour_mask, | |
| 0.28, | |
| 0, | |
| ) | |
| contours, _ = cv2.findContours( | |
| binary_mask, | |
| cv2.RETR_EXTERNAL, | |
| cv2.CHAIN_APPROX_SIMPLE, | |
| ) | |
| # Yellow line represents the predicted lesion boundary. | |
| cv2.drawContours( | |
| overlay, | |
| contours, | |
| contourIdx=-1, | |
| color=(255, 255, 0), | |
| thickness=2, | |
| ) | |
| return overlay | |
| def predict(image, threshold): | |
| if image is None: | |
| raise gr.Error( | |
| "Please upload a breast-ultrasound image." | |
| ) | |
| processed = preprocess_ultrasound(image) | |
| device = torch.device( | |
| "cuda" | |
| if torch.cuda.is_available() | |
| else "cpu" | |
| ) | |
| model.to(device) | |
| model.eval() | |
| input_tensor = processed["tensor"].to(device) | |
| with torch.inference_mode(): | |
| output = model( | |
| pixel_values=input_tensor | |
| ) | |
| logits = output["logits"] | |
| probability = torch.sigmoid(logits) | |
| probability = ( | |
| probability[0, 0] | |
| .detach() | |
| .cpu() | |
| .numpy() | |
| ) | |
| original_height, original_width = ( | |
| processed["original_size"] | |
| ) | |
| probability = cv2.resize( | |
| probability, | |
| (original_width, original_height), | |
| interpolation=cv2.INTER_LINEAR, | |
| ) | |
| binary_mask = ( | |
| probability >= float(threshold) | |
| ).astype(np.uint8) * 255 | |
| overlay = create_overlay( | |
| processed["original"], | |
| binary_mask, | |
| ) | |
| enhanced_image = Image.fromarray( | |
| processed["enhanced"] | |
| ) | |
| mask_image = Image.fromarray( | |
| binary_mask | |
| ) | |
| overlay_image = Image.fromarray( | |
| overlay | |
| ) | |
| # Release allocated GPU memory after inference. | |
| model.to("cpu") | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| return ( | |
| enhanced_image, | |
| mask_image, | |
| overlay_image, | |
| ) | |
| with gr.Blocks( | |
| title="G17 AMFU-Net Demo", | |
| fill_width=True, | |
| css=CUSTOM_CSS, | |
| ) as demo: | |
| gr.Markdown( | |
| """ | |
| # G17 AMFU-Net Breast Lesion Segmentation | |
| Upload a breast-ultrasound image to identify and outline the | |
| predicted lesion using the paper-based AMFU-Net model. | |
| **Research demonstration only. This system has not been | |
| validated for clinical diagnosis or treatment decisions.** | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column( | |
| scale=2, | |
| min_width=300, | |
| ): | |
| input_image = gr.Image( | |
| type="pil", | |
| label="Ultrasound image", | |
| sources=["upload"], | |
| height=360, | |
| ) | |
| with gr.Column( | |
| scale=1, | |
| min_width=300, | |
| ): | |
| threshold = gr.Slider( | |
| minimum=0.10, | |
| maximum=0.90, | |
| value=0.50, | |
| step=0.05, | |
| label="Segmentation threshold", | |
| info=( | |
| "Higher values produce more " | |
| "conservative lesion masks." | |
| ), | |
| ) | |
| gr.Markdown( | |
| """ | |
| **Threshold guide** | |
| - `0.30`: detects more possible lesion pixels | |
| - `0.50`: standard evaluation threshold | |
| - `0.70`: includes only high-confidence pixels | |
| """ | |
| ) | |
| segment_button = gr.Button( | |
| "Segment lesion", | |
| variant="primary", | |
| size="lg", | |
| ) | |
| with gr.Tabs(): | |
| with gr.Tab("Enhanced image"): | |
| enhanced_output = gr.Image( | |
| label="SRAD + CLAHE enhanced image", | |
| format="png", | |
| height=420, | |
| ) | |
| with gr.Tab("Lesion mask"): | |
| mask_output = gr.Image( | |
| label="Predicted lesion mask", | |
| format="png", | |
| height=420, | |
| ) | |
| gr.Markdown( | |
| """ | |
| White pixels represent the predicted lesion. | |
| Black pixels represent the background. | |
| """ | |
| ) | |
| with gr.Tab("Lesion overlay"): | |
| overlay_output = gr.Image( | |
| label="Lesion boundary overlay", | |
| format="png", | |
| height=420, | |
| ) | |
| gr.Markdown( | |
| """ | |
| The transparent red area represents the predicted lesion. | |
| The yellow line represents its predicted boundary. | |
| """ | |
| ) | |
| segment_button.click( | |
| fn=predict, | |
| inputs=[ | |
| input_image, | |
| threshold, | |
| ], | |
| outputs=[ | |
| enhanced_output, | |
| mask_output, | |
| overlay_output, | |
| ], | |
| ) | |
| input_image.clear( | |
| fn=lambda: (None, None, None), | |
| outputs=[ | |
| enhanced_output, | |
| mask_output, | |
| overlay_output, | |
| ], | |
| ) | |
| gr.Markdown( | |
| """ | |
| --- | |
| The G17 adaptation uses SRAD despeckling and CLAHE enhancement | |
| in place of the original paper's unavailable multimodal USCT | |
| fusion stage. | |
| The model was trained using enhanced images from BUSI, | |
| BUS-BRA and BUS-UCLM. Performance may vary across ultrasound | |
| machines, acquisition settings and patient populations. | |
| """ | |
| ) | |
| if __name__ == "__main__": | |
| demo.queue( | |
| max_size=10, | |
| default_concurrency_limit=1, | |
| ).launch() |