Spaces:
Sleeping
Sleeping
Update app.py
Browse files265 unmodified lines2662672682692702712721 unmodified line27427527627727827928028128228328428528628728828929029129229329429529629729829930030122 unmodified lines32432532632732832933033117 unmodified lines34935035135235335426 unmodified lines38138238338438538623 unmodified lines410411412413414415265 unmodified linesreturn heatmapdef analyze_image(image, ground_truth, filename):"""Main analysis function - FIXED VERSION"""if model is None:return None, "Model not loaded. Please restart the application."1 unmodified linereturn None, "Please select an image first."try:# Preprocessinput_tensor = preprocess_for_model(image).to(device)# Get prediction and attention mapswith torch.no_grad():# Get model output (prediction + attention maps)model_output, attention_maps = model(input_tensor)# Apply sigmoid and threshold to get binary maskpred_mask = torch.sigmoid(model_output)binary_mask = (pred_mask > 0.5).float()# Convert to numpy for further processingbinary_mask_np = binary_mask.squeeze().cpu().numpy()# Post-processing (morphological operations)kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))binary_mask_np = cv2.morphologyEx(binary_mask_np.astype(np.uint8), cv2.MORPH_OPEN, kernel)binary_mask_np = cv2.morphologyEx(binary_mask_np, cv2.MORPH_CLOSE, kernel)# Generate attention heatmapatt_heatmap = generate_attention_heatmap(attention_maps)# Create visualizationif ground_truth is not None:22 unmodified lines# Ground truthgt_array = np.array(ground_truth.resize((256, 256)))# Normalize ground truth to binary (0 or 1)gt_binary = (gt_array > 128).astype(np.uint8)axes[1,0].imshow(gt_binary, cmap='gray')axes[1,0].set_title('Ground Truth Mask', fontsize=12, weight='bold')17 unmodified lines# Dice scoredice = (2 * intersection) / (np.sum(pred_binary) + np.sum(gt_binary_bool) + 1e-8)axes[1,2].text(0.1, 0.6, f'IoU: {iou:.4f}', fontsize=16, weight='bold')axes[1,2].text(0.1, 0.4, f'Dice: {dice:.4f}', fontsize=16, weight='bold')axes[1,2].set_xlim(0, 1)26 unmodified linestotal_pixels = binary_mask_np.sizetumor_percentage = (tumor_pixels / total_pixels) * 100analysis_text = f"""# Analysis Results23 unmodified linesprint(error_msg) # For debuggingreturn None, error_msg# Initialize model and dataset at startupprint("Initializing application components...")model_loaded = download_and_load_model()265 unmodified lines2662672682692702712721 unmodified line27427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833922 unmodified lines36236336436536636736836937037137237317 unmodified lines39139239339439539639739839940040140240326 unmodified lines43043143243343443543643743843923 unmodified lines463464465466467468469265 unmodified linesreturn heatmapdef analyze_image(image, ground_truth, filename):"""Main analysis function - DEBUG VERSION"""if model is None:return None, "Model not loaded. Please restart the application."1 unmodified linereturn None, "Please select an image first."try:print("="*50)print("DEBUG: Starting analysis...")print(f"Input image mode: {image.mode}")print(f"Input image size: {image.size}")# Preprocessinput_tensor = preprocess_for_model(image).to(device)print(f"Input tensor shape: {input_tensor.shape}")print(f"Input tensor min/max: {input_tensor.min():.4f}/{input_tensor.max():.4f}")# Get prediction and attention mapswith torch.no_grad():print("Getting model output...")model_output, attention_maps = model(input_tensor)print(f"Model output shape: {model_output.shape}")print(f"Model output min/max BEFORE sigmoid: {model_output.min():.4f}/{model_output.max():.4f}")# Apply sigmoidpred_mask = torch.sigmoid(model_output)print(f"After sigmoid min/max: {pred_mask.min():.4f}/{pred_mask.max():.4f}")# Check values before thresholdingunique_vals = torch.unique(pred_mask)print(f"Unique values in prediction: {unique_vals[:10]}") # Show first 10 unique values# Apply thresholdbinary_mask = (pred_mask > 0.5).float()print(f"Binary mask shape: {binary_mask.shape}")print(f"Binary mask sum (number of 1s): {binary_mask.sum()}")# Convert to numpybinary_mask_np = binary_mask.squeeze().cpu().numpy()print(f"Numpy binary mask shape: {binary_mask_np.shape}")print(f"Numpy binary mask unique values: {np.unique(binary_mask_np)}")print(f"Numpy binary mask sum: {np.sum(binary_mask_np)}")# Try different thresholds if 0.5 doesn't workif np.sum(binary_mask_np) == 0:print("No pixels detected with threshold 0.5, trying lower thresholds...")for thresh in [0.3, 0.2, 0.1, 0.05]:test_mask = (pred_mask > thresh).float().squeeze().cpu().numpy()pixel_count = np.sum(test_mask)print(f"Threshold {thresh}: {pixel_count} pixels")if pixel_count > 0:print(f"Using threshold {thresh} instead of 0.5")binary_mask_np = test_maskbreak# Post-processing (morphological operations)print("Applying morphological operations...")kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))binary_mask_np = cv2.morphologyEx(binary_mask_np.astype(np.uint8), cv2.MORPH_OPEN, kernel)binary_mask_np = cv2.morphologyEx(binary_mask_np, cv2.MORPH_CLOSE, kernel)print(f"After morphological ops sum: {np.sum(binary_mask_np)}")# Generate attention heatmapprint("Generating attention heatmap...")att_heatmap = generate_attention_heatmap(attention_maps)print(f"Attention heatmap shape: {att_heatmap.shape}")# Create visualizationif ground_truth is not None:22 unmodified lines# Ground truthgt_array = np.array(ground_truth.resize((256, 256)))print(f"Ground truth array shape: {gt_array.shape}")print(f"Ground truth unique values: {np.unique(gt_array)}")# Normalize ground truth to binary (0 or 1)gt_binary = (gt_array > 128).astype(np.uint8)print(f"GT binary sum: {np.sum(gt_binary)}")axes[1,0].imshow(gt_binary, cmap='gray')axes[1,0].set_title('Ground Truth Mask', fontsize=12, weight='bold')17 unmodified lines# Dice scoredice = (2 * intersection) / (np.sum(pred_binary) + np.sum(gt_binary_bool) + 1e-8)print(f"Final IoU: {iou:.4f}")print(f"Final Dice: {dice:.4f}")print(f"Intersection: {intersection}")print(f"Union: {union}")print(f"Pred pixels: {np.sum(pred_binary)}")print(f"GT pixels: {np.sum(gt_binary_bool)}")axes[1,2].text(0.1, 0.6, f'IoU: {iou:.4f}', fontsize=16, weight='bold')axes[1,2].text(0.1, 0.4, f'Dice: {dice:.4f}', fontsize=16, weight='bold')axes[1,2].set_xlim(0, 1)26 unmodified linestotal_pixels = binary_mask_np.sizetumor_percentage = (tumor_pixels / total_pixels) * 100print(f"Final tumor pixels: {tumor_pixels}")print(f"Final tumor percentage: {tumor_percentage:.2f}%")print("="*50)analysis_text = f"""# Analysis Results23 unmodified linesprint(error_msg) # For debuggingreturn None, error_msg# Initialize model and dataset at startupprint("Initializing application components...")model_loaded = download_and_load_model()
app.py+58-4