<jupyter_start><jupyter_text>Steel Defect Detection> POC from multiple Severstal Kaggle Competition solutions.<jupyter_code>#hide
%load_ext autoreload
%autoreload 2
%matplotlib inline
from steel_segmentation.all import *
from fastai.vision.all import *

import torch
import torch.nn as nn
import torch.nn.functional as F
import segmentation_models_pytorch as smp

import ipywidgets as widgets
from ipywidgets import interact, interact_manual, interactive, VBox
from IPython.display import Image
def opt_func(params, **kwargs): return OptimWrapper(params, torch.optim.Adam, **kwargs)
def splitter(m): return convert_params([[m.encoder], [m.decoder], [m.segmentation_head]])
learner = load_learner(models_dir/"exports"/"efficientnet-b2.pkl")
#hide_output
btn_upload = widgets.FileUpload()
img_widget = widgets.Image()
lbl_pred = widgets.Label()
out_pl = widgets.Output()
btn_run = widgets.Button(description='Classify')
def get_defects(preds) -> str:
    argmax_defects = list(preds.float().argmax(0).unique().numpy())[1:]
    types_defects = [str(o+1) for o in argmax_defects]
    n_defects = len(types_defects)
    defects_word = "defects" if n_defects!=1 else "defect"
    types_word = "types" if n_defects!=1 else "type"
    if n_defects > 0:
        return f"Predicted: n°{n_defects} {defects_word} of {types_word}: {' '.join(types_defects)}"
    else:
        return f"Predicted: n°0 {defects_word}"

def segment_img(img):
    rles, preds, probs = learner.predict(img)
    title = get_defects(preds)
    img_np = np.array(img)
    w,h,_ = img_np.shape
    
    out_pl.clear_output()
    with out_pl: 
        plot_mask_image("Original", img_np, np.zeros((w,h,4)))
        plot_mask_image("Predicted", np.array(img), preds.permute(1,2,0).float().numpy())
        
    lbl_pred.value = title
    
def on_click_classify(change):
    img = PILImage.create(btn_upload.data[-1]) # new release .content.tobytes()
    segment_img(img)
        
btn_run.on_click(on_click_classify)
VBox([widgets.Label('Detect steel defects with image segmentation'), 
      btn_upload, btn_run, out_pl, lbl_pred])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12305516265912306, 'fraction_numerical': 0.006600660066006601, 'mean_word_length': 4.861878453038674, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '263064', 'license': 'Apache-2.0', 'n_tokens_mistral': 778, 'n_tokens_neox': 765, 'n_words': 159, 'path': 'nbs/old/_22_prod_inference.ipynb', 'repo_name': 'marcomatteo/steel-segmentation-nbdev', 'size': '2121'}