Buckets:
| """Streamlit: segmentasi lesi stroke dari NCCT (model Phase 3). | |
| Jalankan: python -m streamlit run app.py | |
| - Bongkar pasang: taruh checkpoint *_best.pth Phase 3 di folder weights/, lalu pilih di sidebar. Encoder dan | |
| decoder dibaca otomatis dari config di dalam checkpoint. | |
| - Decoder attention jalan di CPU/GPU. Checkpoint U-Mamba muncul dua kali: versi GPU (mamba-ssm, butuh GPU CUDA) | |
| dan versi CPU (Mamba PyTorch murni, bobot sama, lebih lambat). | |
| - Input: NIfTI terpreproses (256 x 256 x Z, nilai 0..1) ATAU NCCT mentah (HU). NCCT mentah dipreproses dulu | |
| dengan pipeline tim (preprocess.py): kanonik, brain mask, crop 256, window W80/L40, histogram equalization. | |
| """ | |
| import gzip | |
| import hashlib | |
| import os | |
| from pathlib import Path | |
| import nibabel as nib | |
| import numpy as np | |
| import plotly.graph_objects as go | |
| import streamlit as st | |
| import torch | |
| from inference import (as_volume, default_device, dice, load_checkpoint, predict_slices, predict_volume, | |
| read_meta) | |
| from model import mamba_status | |
| from preprocess import BRAIN_METHODS, looks_preprocessed, preprocess_raw, totalseg_available | |
| APP_DIR = Path(__file__).resolve().parent | |
| WEIGHTS_DIR = APP_DIR / 'weights' | |
| SAMPLES_DIR = APP_DIR / 'samples' | |
| MIN_LESION_VOXELS = 10 # sama dengan DEGENERATE_VOXELS di notebook Phase 3 | |
| DEVICE = default_device() | |
| if DEVICE == 'cpu': | |
| torch.set_num_threads(max(1, os.cpu_count() or 1)) | |
| ENCODER_INFO = { | |
| 'efficientnetb3': ('EfficientNet-B3', 'CNN ringan (compound scaling). Bobot awal ImageNet-1K, lalu dilatih ' | |
| 'klasifikasi slice di Phase 2.'), | |
| 'resnet50': ('ResNet-50', 'CNN dengan residual connection. Bobot awal RadImageNet, lalu dilatih ' | |
| 'klasifikasi slice di Phase 2.'), | |
| 'swinv2tiny': ('Swin V2 Tiny', 'Transformer dengan shifted-window attention. Bobot awal ImageNet-1K, lalu ' | |
| 'dilatih di Phase 2. Ditambah ConvStem untuk skip 128x128.'), | |
| } | |
| DECODER_INFO = { | |
| 'attention': ('Attention U-Net', 'Attention gate menyaring skip connection dari encoder sebelum digabung. ' | |
| 'Bisa jalan di CPU.'), | |
| 'umamba': ('U-Mamba (adaptasi)', 'ResConv untuk detail lokal + Mamba untuk konteks global (gamma ReZero).'), | |
| } | |
| MAMBA_IMPL_INFO = { | |
| 'cuda': ('GPU', 'Versi GPU: kernel CUDA mamba-ssm, sama dengan saat training. Butuh GPU CUDA + mamba-ssm.'), | |
| 'torch': ('CPU', 'Versi CPU: Mamba ditulis ulang dengan PyTorch biasa (rumus dan bobot sama), jalan tanpa ' | |
| 'GPU tetapi lebih lambat.'), | |
| } | |
| TEACHER_NAMES = {'resenc': 'ResEnc M', 'umamba': 'U-Mamba', 'transunet': 'TransUNet'} | |
| CONTEXT_LABELS = { | |
| 'neighbors': '3 slice (z-1, z, z+1)', | |
| 'single': '1 slice (z diulang 3x)', | |
| } | |
| COLOR_PRED, COLOR_GT = '#ef4444', '#22c55e' | |
| st.set_page_config(page_title='Segmentasi Lesi Stroke NCCT', layout='wide') | |
| st.markdown(""" | |
| <style> | |
| div[data-testid="stMetric"] {border: 1px solid rgba(128,128,128,.25); border-radius: 10px; padding: 10px 14px;} | |
| .model-card {border: 1px solid rgba(128,128,128,.3); border-radius: 10px; padding: 10px 12px; margin-bottom: 8px;} | |
| .model-card .label {font-size: .75rem; opacity: .7; text-transform: uppercase; letter-spacing: .04em;} | |
| .model-card .name {font-weight: 600; font-size: 1rem; margin: 2px 0 4px 0;} | |
| .model-card .desc {font-size: .8rem; opacity: .8; line-height: 1.35;} | |
| .legend {font-size: .85rem; opacity: .85;} | |
| .legend span {display: inline-block; width: 12px; height: 12px; border-radius: 2px; margin: 0 4px -1px 10px;} | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # ------------------------------------------------------------------ util | |
| def get_model(path, mamba_impl): | |
| return load_checkpoint(path, device=DEVICE, mamba_impl=mamba_impl) | |
| def get_meta(path, mtime): | |
| return read_meta(path) | |
| def read_nifti(data, name): | |
| """Baca NIfTI langsung dari memori (tanpa file sementara; aman di Windows).""" | |
| if data[:2] == b'\x1f\x8b': # .nii.gz -> buka gzip dulu | |
| data = gzip.decompress(data) | |
| img = nib.Nifti1Image.from_bytes(data) | |
| arr = np.asarray(img.dataobj, dtype=np.float32) | |
| zooms = tuple(float(z) for z in img.header.get_zooms()[:3]) + (1.0, 1.0, 1.0) | |
| return arr, img.affine, zooms[:3] | |
| def find_file(folder, stem): | |
| for ext in ('.nii.gz', '.nii'): | |
| path = folder / (stem + ext) | |
| if path.is_file(): | |
| return path | |
| return None | |
| def nifti_bytes(array, affine, dtype=np.uint8): | |
| """NIfTI (.nii.gz) sebagai bytes, dibuat di memori.""" | |
| return gzip.compress(nib.Nifti1Image(array.astype(dtype), affine).to_bytes()) | |
| def fmt_dice(value): | |
| return '-' if value is None else '%.4f' % value | |
| def model_card(label, name, desc): | |
| st.markdown('<div class="model-card"><div class="label">%s</div><div class="name">%s</div>' | |
| '<div class="desc">%s</div></div>' % (label, name, desc), unsafe_allow_html=True) | |
| def slice_view(ct, prob, pred, gt, show_pred, show_gt, show_prob, alpha, rotate, height=520): | |
| """Viewer interaktif (zoom, geser, hover probabilitas) untuk satu slice.""" | |
| rot = lambda a: np.rot90(a, rotate) | |
| ct, prob = rot(ct), rot(prob) | |
| lo, hi = np.percentile(ct, (1, 99)) | |
| fig = go.Figure(go.Heatmap( | |
| z=ct, colorscale='gray', zmin=lo, zmax=hi if hi > lo else lo + 1, showscale=False, | |
| customdata=prob, hovertemplate='x %{x}, y %{y}<br>prob lesi %{customdata:.3f}<extra></extra>')) | |
| if show_prob: | |
| overlay = np.where(prob >= 0.05, prob, np.nan) | |
| fig.add_trace(go.Heatmap(z=overlay, colorscale='Inferno', zmin=0, zmax=1, opacity=alpha, | |
| hoverinfo='skip', colorbar=dict(title='prob', thickness=12, len=0.6))) | |
| for show, mask, color in ((show_gt, gt, COLOR_GT), (show_pred, pred, COLOR_PRED)): | |
| if show and mask is not None and mask.any(): | |
| # coloring='lines' mewarnai garis dari colorscale (bukan line.color), jadi colorscale dibuat 1 warna | |
| fig.add_trace(go.Contour(z=rot(mask).astype(float), showscale=False, hoverinfo='skip', | |
| colorscale=[[0, color], [1, color]], | |
| contours=dict(start=0.5, end=0.5, size=1, coloring='lines'), | |
| line=dict(width=2))) | |
| fig.update_xaxes(visible=False, constrain='domain') | |
| fig.update_yaxes(visible=False, autorange='reversed', scaleanchor='x') | |
| fig.update_layout(height=height, margin=dict(l=0, r=0, t=0, b=0), dragmode='pan') | |
| return fig | |
| def legend(has_gt): | |
| text = '<span style="background:%s"></span>prediksi' % COLOR_PRED | |
| if has_gt: | |
| text += '<span style="background:%s"></span>ground truth' % COLOR_GT | |
| st.markdown('<div class="legend">%s | scroll untuk zoom, geser untuk pan, arahkan kursor untuk ' | |
| 'melihat probabilitas</div>' % text, unsafe_allow_html=True) | |
| def gray_fig(image, rotate, title, lo=None, hi=None, contour=None, height=380): | |
| image = np.rot90(image, rotate) | |
| if lo is None: | |
| lo, hi = np.percentile(image, (1, 99)) | |
| fig = go.Figure(go.Heatmap(z=image, colorscale='gray', zmin=lo, zmax=hi if hi > lo else lo + 1, | |
| showscale=False, hovertemplate='%{z:.2f}<extra></extra>')) | |
| if contour is not None and contour.any(): | |
| fig.add_trace(go.Contour(z=np.rot90(contour, rotate).astype(float), showscale=False, hoverinfo='skip', | |
| colorscale=[[0, '#38bdf8'], [1, '#38bdf8']], | |
| contours=dict(start=0.5, end=0.5, size=1, coloring='lines'), line=dict(width=1.5))) | |
| fig.update_xaxes(visible=False, constrain='domain') | |
| fig.update_yaxes(visible=False, autorange='reversed', scaleanchor='x') | |
| fig.update_layout(height=height, margin=dict(l=0, r=0, t=28, b=0), title=dict(text=title, font=dict(size=13))) | |
| return fig | |
| def preprocess_tab(pp, z, rotate): | |
| info_pp = pp['info'] | |
| st.markdown('Input asli %s, spacing %s mm, orientasi %s -> kanonik RAS. Crop skala %.3f, piksel hasil %s mm. ' | |
| 'Brain mask: %s. HE: %s.' | |
| % (' x '.join(map(str, info_pp['shape_in'])), ' x '.join(map(str, info_pp['spacing_in'])), | |
| info_pp['orientation_in'], info_pp['crop_scale'], ' x '.join(map(str, info_pp['pixel_mm'])), | |
| BRAIN_METHODS[info_pp['brain_method']], 'ya' if info_pp['he'] else 'tidak')) | |
| a, b, c = st.columns(3) | |
| a.plotly_chart(gray_fig(pp['raw'][:, :, z], rotate, 'Asli (HU, window 0..80)', 0, 80), width='stretch', | |
| key='pp_raw') | |
| b.plotly_chart(gray_fig(pp['ncct'][:, :, z], rotate, 'Input model (0..1)', 0, 1, pp['brain'][:, :, z]), | |
| width='stretch', key='pp_model') | |
| hist = pp['ncct'][pp['brain']] | |
| fig = go.Figure(go.Histogram(x=hist[::max(1, hist.size // 200000)], nbinsx=64, marker_color='#64748b')) | |
| fig.update_layout(height=380, margin=dict(l=10, r=10, t=28, b=10), title=dict(text='Histogram intensitas ' | |
| 'di dalam otak', font=dict(size=13)), xaxis_title='nilai input', yaxis_title='voxel') | |
| c.plotly_chart(fig, width='stretch', key='pp_hist') | |
| st.caption('Slice %d (ikut slider di tab Viewer). Garis biru = keep mask (otak + ring 2.5 mm).' % z) | |
| # ------------------------------------------------------------------ sidebar: perangkat & model | |
| st.sidebar.header('Perangkat') | |
| if DEVICE == 'cuda': | |
| st.sidebar.success('GPU: %s' % torch.cuda.get_device_name(0)) | |
| else: | |
| st.sidebar.info('CPU (tanpa GPU)') | |
| _mamba_ok, _mamba_why = mamba_status() | |
| if not _mamba_ok: | |
| st.sidebar.caption('U-Mamba versi GPU tidak tersedia (%s). U-Mamba versi CPU tetap bisa dipakai.' % _mamba_why) | |
| st.sidebar.header('Model') | |
| weight_files = sorted(WEIGHTS_DIR.glob('*.pth')) | |
| if not weight_files: | |
| st.error('Folder weights/ kosong. Taruh checkpoint Phase 3 (*_best.pth) di sana.') | |
| st.stop() | |
| metas = {} | |
| for _path in weight_files: | |
| try: | |
| metas[_path] = get_meta(str(_path), _path.stat().st_mtime) | |
| except Exception as error: # noqa: BLE001 - tampilkan di daftar | |
| metas[_path] = {'error': str(error)[:80], 'student': '?', 'decoder': '?', 'kd': None} | |
| # satu opsi per (checkpoint, implementasi Mamba); checkpoint U-Mamba muncul dua kali: GPU dan CPU | |
| options = [(_path, impl) for _path in weight_files | |
| for impl in (('cuda', 'torch') if metas[_path]['decoder'] == 'umamba' else (None,))] | |
| def _status(option): | |
| path, impl = option | |
| if 'error' in metas[path]: | |
| return False, metas[path]['error'] | |
| return (_mamba_ok, _mamba_why) if impl == 'cuda' else (True, 'ok') | |
| def _label(option): | |
| path, impl = option | |
| meta = metas[path] | |
| enc = ENCODER_INFO.get(meta['student'], (meta['student'],))[0] | |
| dec = DECODER_INFO.get(meta['decoder'], (meta['decoder'],))[0].split(' (')[0] | |
| if impl: | |
| dec += ' ' + MAMBA_IMPL_INFO[impl][0] | |
| kd = 'KD %s' % TEACHER_NAMES.get(meta.get('kd'), meta.get('kd')) if meta.get('kd') else 'Non-KD' | |
| ok, _ = _status(option) | |
| suffix = '' if ok else ' (gagal dibaca)' if 'error' in meta else ' (butuh GPU)' | |
| return '%s + %s, %s%s' % (enc, dec, kd, suffix) | |
| weight_path, mamba_impl = st.sidebar.selectbox('Checkpoint', options, format_func=_label, | |
| help='Semua file .pth di folder weights/. Checkpoint U-Mamba ' | |
| 'muncul dua kali: versi GPU dan versi CPU.') | |
| st.sidebar.caption(weight_path.name) | |
| meta = metas[weight_path] | |
| enc_name, enc_desc = ENCODER_INFO.get(meta['student'], (meta['student'], '')) | |
| dec_name, dec_desc = DECODER_INFO.get(meta['decoder'], (meta['decoder'], '')) | |
| if mamba_impl: | |
| dec_name = '%s, versi %s' % (dec_name, MAMBA_IMPL_INFO[mamba_impl][0]) | |
| dec_desc = '%s %s' % (dec_desc, MAMBA_IMPL_INFO[mamba_impl][1]) | |
| with st.sidebar: | |
| model_card('Encoder', enc_name, enc_desc) | |
| model_card('Decoder', dec_name, dec_desc) | |
| model_card('Knowledge distillation (Phase 3)', | |
| 'Teacher %s' % TEACHER_NAMES.get(meta.get('kd'), meta.get('kd')) if meta.get('kd') else 'Tanpa KD', | |
| 'Teacher DWI hanya dipakai saat training; inferensi cukup NCCT.' if meta.get('kd') else | |
| 'Dilatih hanya dengan loss segmentasi.') | |
| _ok, _why = _status((weight_path, mamba_impl)) | |
| if not _ok: | |
| if 'error' in meta: | |
| st.error('Gagal membaca %s: %s' % (weight_path.name, _why)) | |
| else: | |
| st.error('U-Mamba versi GPU butuh GPU CUDA + mamba-ssm (%s). Pilih versi CPU dari checkpoint yang sama, ' | |
| 'atau jalankan app di Vast.' % _why) | |
| st.stop() | |
| try: | |
| model, info = get_model(str(weight_path), mamba_impl) | |
| except Exception as error: # noqa: BLE001 - tampilkan pesan apa adanya | |
| st.error('Gagal memuat %s: %s' % (weight_path.name, error)) | |
| st.stop() | |
| _n_blocks = 3 if info['out_grid'] == 16 else 4 | |
| _scores = ' | '.join(s for s in ( | |
| 'Dice val %.3f' % info['val_dice'] if info.get('val_dice') is not None else '', | |
| 'Dice test %.3f' % info['test_dice'] if info.get('test_dice') is not None else '') if s) | |
| st.sidebar.caption('Bottleneck grid %d (%d blok decoder) | epoch %s | bobot %s%s' | |
| % (info['out_grid'], _n_blocks, info['epoch'], info['weights'], | |
| ' \n' + _scores + ' (per pasien)' if _scores else '')) | |
| # threshold: slider + input angka, saling sinkron | |
| st.sidebar.header('Threshold') | |
| thr_default = round(float(info['threshold']), 2) | |
| key_s, key_n = 'thr_s_' + weight_path.name, 'thr_n_' + weight_path.name | |
| st.session_state.setdefault(key_s, thr_default) | |
| st.session_state.setdefault(key_n, thr_default) | |
| def _sync(src, dst): | |
| st.session_state[dst] = round(float(st.session_state[src]), 2) | |
| def _reset_thr(): | |
| st.session_state[key_s] = st.session_state[key_n] = thr_default | |
| st.sidebar.slider('Geser', 0.01, 0.99, step=0.01, key=key_s, on_change=_sync, args=(key_s, key_n), | |
| label_visibility='collapsed') | |
| col_n, col_r = st.sidebar.columns([3, 2]) | |
| col_n.number_input('Ketik nilai', 0.01, 0.99, step=0.01, format='%.2f', key=key_n, | |
| on_change=_sync, args=(key_n, key_s), label_visibility='collapsed') | |
| col_r.button('Reset', on_click=_reset_thr, width='stretch', | |
| help='Kembali ke threshold hasil validasi (%.2f).' % thr_default) | |
| threshold = float(st.session_state[key_n]) | |
| st.sidebar.caption('Threshold validasi: %.2f%s' % (thr_default, '' if info['threshold_from_val'] | |
| else ' (checkpoint belum berisi threshold, default 0.5)')) | |
| st.sidebar.header('Opsi') | |
| tta = st.sidebar.toggle('TTA (flip horizontal)', value=True, help='Sama dengan evaluasi test. Mati = 2x lebih cepat.') | |
| rotate = st.sidebar.select_slider('Putar tampilan', options=[0, 90, 180, 270], value=0, | |
| format_func=lambda d: '%d derajat' % d) // 90 | |
| use_brain = st.sidebar.toggle('Potong prediksi ke brain mask', value=False, | |
| help='Prediksi di luar otak dibuang (varian "masked" di notebook). Metrik utama ' | |
| 'tesis (Dice per pasien) memakai prediksi tanpa dipotong. Butuh brain mask: ' | |
| 'dari preprocessing NCCT mentah, atau brain.nii di folder samples.') | |
| # ------------------------------------------------------------------ input | |
| st.title('Segmentasi Lesi Stroke dari NCCT') | |
| st.caption('Demo penelitian, bukan alat diagnosis.') | |
| with st.container(border=True): | |
| st.subheader('1. Input') | |
| st.caption('NIfTI NCCT: mentah (HU, ukuran asli) atau sudah terpreproses (256 x 256 x Z, nilai 0..1). ' | |
| 'Z boleh 1 slice, 3 slice, atau volume penuh. Mask ground truth opsional: kalau diisi, Dice dihitung.') | |
| sample_dirs = sorted(d for d in SAMPLES_DIR.glob('*') if d.is_dir() and find_file(d, 'ncct')) \ | |
| if SAMPLES_DIR.is_dir() else [] | |
| source = st.segmented_control('Sumber data', ['Contoh (samples/)', 'Upload file'], | |
| default='Contoh (samples/)' if sample_dirs else 'Upload file') | |
| ct_bytes = mask_bytes = brain_bytes = None | |
| ct_name = mask_name = brain_name = '' | |
| if source == 'Contoh (samples/)': | |
| if not sample_dirs: | |
| st.info('Belum ada contoh. Buat folder samples/<id_pasien>/ berisi ncct.nii (mask.nii dan brain.nii ' | |
| 'opsional).') | |
| st.stop() | |
| pid = st.selectbox('Pasien', sample_dirs, format_func=lambda d: d.name) | |
| ct_path, mask_path, brain_path = find_file(pid, 'ncct'), find_file(pid, 'mask'), find_file(pid, 'brain') | |
| ct_bytes, ct_name = ct_path.read_bytes(), ct_path.name | |
| if mask_path is not None: | |
| mask_bytes, mask_name = mask_path.read_bytes(), mask_path.name | |
| if brain_path is not None: | |
| brain_bytes, brain_name = brain_path.read_bytes(), brain_path.name | |
| elif source == 'Upload file': | |
| col_a, col_b, col_c = st.columns(3) | |
| up_ct = col_a.file_uploader('NCCT (.nii / .nii.gz)', type=['nii', 'gz']) | |
| up_mask = col_b.file_uploader('Mask ground truth (opsional)', type=['nii', 'gz']) | |
| up_brain = col_c.file_uploader('Brain mask (opsional)', type=['nii', 'gz'], | |
| help='Untuk data terpreproses: brain.nii dari dataset. Untuk NCCT mentah: ' | |
| 'dipakai kalau metode brain mask = upload.') | |
| if up_ct is None: | |
| st.stop() | |
| ct_bytes, ct_name = up_ct.getvalue(), up_ct.name | |
| if up_mask is not None: | |
| mask_bytes, mask_name = up_mask.getvalue(), up_mask.name | |
| if up_brain is not None: | |
| brain_bytes, brain_name = up_brain.getvalue(), up_brain.name | |
| else: | |
| st.stop() | |
| raw, affine, zooms = read_nifti(ct_bytes, ct_name) | |
| auto_pre = looks_preprocessed(raw) | |
| kind = st.segmented_control( | |
| 'Jenis input', ['pre', 'raw'], default='pre' if auto_pre else 'raw', | |
| format_func=lambda k: {'pre': 'Sudah terpreproses', 'raw': 'NCCT mentah (HU)'}[k], | |
| help='Dipilih otomatis dari isi file (256 x 256, nilai 0..1 = terpreproses). Ganti kalau tebakannya salah.') | |
| is_raw = (kind or ('pre' if auto_pre else 'raw')) == 'raw' | |
| preprocessed = None | |
| if is_raw: | |
| methods = list(BRAIN_METHODS) | |
| has_ts = totalseg_available() | |
| p1, p2, p3 = st.columns([3, 2, 2]) | |
| method = p1.selectbox('Brain mask', methods, index=0 if has_ts else 2, | |
| format_func=lambda m: BRAIN_METHODS[m] | |
| + ('' if m != 'totalseg' or has_ts else ' - tidak terpasang')) | |
| he = p2.toggle('Histogram equalization', value=True, | |
| help='Dataset training = preprocessed_data_unzipped_he, jadi HE aktif.') | |
| if method == 'totalseg' and not has_ts: | |
| st.error('TotalSegmentator tidak terpasang. Pasang dengan `pip install TotalSegmentator`, ' | |
| 'atau pilih metode lain.') | |
| st.stop() | |
| if method == 'upload' and brain_bytes is None: | |
| st.info('Unggah brain mask (grid sama dengan NCCT mentah) di kolom kanan atas.') | |
| st.stop() | |
| if method == 'approx': | |
| st.warning('Brain mask perkiraan ambang HU BUKAN cara training (TotalSegmentator). Crop dan ' | |
| 'normalisasi bisa sedikit berbeda, jadi hasil prediksi bisa ikut berbeda.') | |
| pp_key = '%s|%s|%d|%s|%s' % (hashlib.md5(ct_bytes).hexdigest(), method, he, | |
| hashlib.md5(brain_bytes).hexdigest() if method == 'upload' else '', | |
| hashlib.md5(mask_bytes).hexdigest() if mask_bytes else '') | |
| pp_cache = st.session_state.setdefault('pp_cache', {}) | |
| if pp_key not in pp_cache: | |
| if not p3.button('Jalankan preprocessing', type='primary', width='stretch'): | |
| st.caption('Langkah: kanonik (RAS) -> brain mask -> keep mask (+ring 2.5 mm) -> crop & resample ' | |
| '256 x 256 -> window W80/L40 -> 0..1 -> histogram equalization -> luar otak = 0.') | |
| st.stop() | |
| with st.status('Preprocessing NCCT mentah ...', expanded=True) as status: | |
| try: | |
| pp_cache.clear() | |
| pp_cache[pp_key] = preprocess_raw( | |
| ct_bytes, mask_bytes, method, brain_bytes if method == 'upload' else None, he=he, | |
| device='gpu' if DEVICE == 'cuda' else 'cpu', log=st.write) | |
| except Exception as error: # noqa: BLE001 - pesan apa adanya | |
| status.update(label='Preprocessing gagal', state='error') | |
| st.error(str(error)) | |
| st.stop() | |
| status.update(label='Preprocessing selesai', state='complete', expanded=False) | |
| preprocessed = pp_cache[pp_key] | |
| volume, affine = preprocessed['ncct'], preprocessed['affine'] | |
| zooms = tuple(float(v) for v in nib.affines.voxel_sizes(affine)) | |
| gt, brain = preprocessed['mask'], preprocessed['brain'] | |
| H, W, Z = volume.shape | |
| else: | |
| try: | |
| volume = as_volume(raw) | |
| except ValueError as error: | |
| st.error(str(error)) | |
| st.stop() | |
| H, W, Z = volume.shape | |
| if (H, W) != (256, 256): | |
| st.warning('Ukuran slice %d x %d, bukan 256 x 256 seperti data training. Kalau ini NCCT mentah, ' | |
| 'pilih jenis input "NCCT mentah (HU)".' % (H, W)) | |
| elif float(volume.max()) > 1.01: | |
| st.warning('Nilai NCCT di luar 0..1. Kalau ini NCCT mentah (HU), pilih jenis input "NCCT mentah".') | |
| def _aux_mask(data, name, label): | |
| if data is None: | |
| return None | |
| arr = read_nifti(data, name)[0] | |
| try: | |
| out = as_volume(arr) > 0.5 | |
| except ValueError: | |
| out = None | |
| if out is None or out.shape != volume.shape: | |
| st.warning('Ukuran %s %s berbeda dengan NCCT %s; %s diabaikan.' | |
| % (label, getattr(arr, 'shape', '?'), volume.shape, label)) | |
| return None | |
| return out | |
| gt = _aux_mask(mask_bytes, mask_name, 'mask') | |
| brain = _aux_mask(brain_bytes, brain_name, 'brain mask') | |
| c1, c2 = st.columns([2, 3]) | |
| c1.markdown('**Ukuran input model:** %d x %d x %d slice \n**Ground truth:** %s | **Brain mask:** %s' | |
| % (H, W, Z, 'ada' if gt is not None else 'tidak ada', 'ada' if brain is not None else 'tidak ada')) | |
| if Z == 1: | |
| mode = 'slice' | |
| c2.info('File berisi 1 slice: slice itu diulang 3x sebagai input model.') | |
| else: | |
| mode = c2.segmented_control('Mode', ['volume', 'slice'], default='volume', | |
| format_func=lambda m: {'volume': 'Seluruh volume (3D)', | |
| 'slice': 'Satu slice'}[m]) or 'volume' | |
| if use_brain and brain is None: | |
| st.caption('Brain mask tidak tersedia: opsi "potong prediksi ke brain mask" diabaikan.') | |
| input_hash = hashlib.md5(ct_bytes).hexdigest() + ('|' + pp_key if preprocessed is not None else '|pre') | |
| key_base = input_hash + '|' + weight_path.name + '|%s' % mamba_impl + '|tta%d' % tta | |
| clip_brain = use_brain and brain is not None | |
| cache = st.session_state.setdefault('pred_cache', {}) | |
| if len(cache) > 12: | |
| cache.clear() | |
| # ------------------------------------------------------------------ mode volume | |
| if mode == 'volume': | |
| key = key_base + '|volume' | |
| if key not in cache: | |
| bar = st.progress(0.0, text='Memproses %d slice ...' % Z) | |
| cache[key] = predict_volume(model, volume, info['slice_context'], tta=tta, | |
| progress=lambda f: bar.progress(f, text='Memproses ... %d%%' % (100 * f))) | |
| bar.empty() | |
| probs = cache[key] * brain if clip_brain else cache[key] | |
| pred = probs >= threshold | |
| st.subheader('2. Hasil') | |
| voxel_ml = float(np.prod(zooms)) / 1000.0 | |
| n_pred = int(pred.sum()) | |
| area_pred = pred.sum(axis=(0, 1)) | |
| area_gt = gt.sum(axis=(0, 1)) if gt is not None else None | |
| cols = st.columns(4 if gt is not None else 3) | |
| cols[0].metric('Status', 'Lesi terdeteksi' if n_pred > MIN_LESION_VOXELS else 'Tidak terdeteksi') | |
| cols[1].metric('Volume prediksi', '%.2f mL' % (n_pred * voxel_ml), '%d voxel' % n_pred, delta_color='off') | |
| cols[2].metric('Slice berlesi (prediksi)', '%d / %d' % (int((area_pred > 0).sum()), Z)) | |
| if gt is not None: | |
| cols[3].metric('Dice vs ground truth', fmt_dice(dice(pred, gt)), | |
| 'GT %.2f mL' % (gt.sum() * voxel_ml), delta_color='off') | |
| # navigasi slice | |
| zkey = 'z_%s' % input_hash | |
| ref_area = area_pred if n_pred else (area_gt if area_gt is not None else area_pred) | |
| lesion_z = [int(i) for i in np.flatnonzero(ref_area > 0)] | |
| if zkey not in st.session_state: | |
| st.session_state[zkey] = int(np.argmax(ref_area)) if ref_area.max() > 0 else Z // 2 | |
| def _jump(step): | |
| cur = st.session_state[zkey] | |
| cand = [i for i in lesion_z if (i < cur if step < 0 else i > cur)] | |
| if cand: | |
| st.session_state[zkey] = cand[-1] if step < 0 else cand[0] | |
| tab_names = ['Viewer', 'Profil per slice'] + (['Preprocessing'] if preprocessed is not None else []) + ['Unduh'] | |
| tabs = dict(zip(tab_names, st.tabs(tab_names))) | |
| tab_view, tab_profile, tab_download = tabs['Viewer'], tabs['Profil per slice'], tabs['Unduh'] | |
| with tab_view: | |
| left, right = st.columns([3, 1]) | |
| with right: | |
| show_pred = st.toggle('Prediksi', value=True) | |
| show_gt = st.toggle('Ground truth', value=gt is not None, disabled=gt is None) | |
| show_prob = st.toggle('Heatmap probabilitas', value=False) | |
| alpha = st.slider('Opasitas heatmap', 0.1, 1.0, 0.5, 0.05, disabled=not show_prob) | |
| b1, b2 = st.columns(2) | |
| b1.button('< Lesi', on_click=_jump, args=(-1,), width='stretch', | |
| disabled=not lesion_z, help='Lompat ke slice berlesi sebelumnya') | |
| b2.button('Lesi >', on_click=_jump, args=(1,), width='stretch', | |
| disabled=not lesion_z, help='Lompat ke slice berlesi berikutnya') | |
| z = st.session_state[zkey] | |
| st.markdown('**Slice %d** \nprediksi: %d piksel%s' | |
| % (z, int(area_pred[z]), ' \nGT: %d piksel' % int(area_gt[z]) if area_gt is not None else '')) | |
| if gt is not None: | |
| st.caption('Dice slice: %s' % fmt_dice(dice(pred[:, :, z], gt[:, :, z]))) | |
| with left: | |
| st.slider('Slice (z)', 0, Z - 1, key=zkey) | |
| z = st.session_state[zkey] | |
| st.plotly_chart(slice_view(volume[:, :, z], probs[:, :, z], pred[:, :, z], | |
| gt[:, :, z] if gt is not None else None, | |
| show_pred, show_gt, show_prob, alpha, rotate), | |
| width='stretch', config={'scrollZoom': True, 'displaylogo': False}) | |
| legend(gt is not None) | |
| with tab_profile: | |
| fig = go.Figure() | |
| fig.add_trace(go.Scatter(x=list(range(Z)), y=area_pred, name='prediksi', mode='lines', | |
| line=dict(color=COLOR_PRED))) | |
| if area_gt is not None: | |
| fig.add_trace(go.Scatter(x=list(range(Z)), y=area_gt, name='ground truth', mode='lines', | |
| line=dict(color=COLOR_GT))) | |
| fig.add_vline(x=st.session_state[zkey], line_dash='dot', opacity=0.6) | |
| fig.update_layout(height=360, margin=dict(l=10, r=10, t=10, b=10), xaxis_title='slice (z)', | |
| yaxis_title='luas lesi (piksel)', hovermode='x unified') | |
| st.plotly_chart(fig, width='stretch') | |
| st.caption('Garis putus-putus = slice yang sedang dilihat di tab Viewer.') | |
| with tab_download: | |
| stem = Path(ct_name).name.split('.')[0] | |
| st.download_button('Mask prediksi (.nii.gz)', nifti_bytes(pred, affine), | |
| file_name=stem + '_pred_mask.nii.gz', mime='application/gzip') | |
| st.download_button('Peta probabilitas (.nii.gz)', nifti_bytes(probs, affine, np.float32), | |
| file_name=stem + '_prob.nii.gz', mime='application/gzip') | |
| if preprocessed is not None: | |
| st.download_button('NCCT terpreproses (.nii.gz)', nifti_bytes(volume, affine, np.float32), | |
| file_name=stem + '_ncct_preprocessed.nii.gz', mime='application/gzip') | |
| st.download_button('Brain / keep mask (.nii.gz)', nifti_bytes(brain, affine), | |
| file_name=stem + '_brain.nii.gz', mime='application/gzip') | |
| st.caption('Mask memakai threshold %.2f%s.' % (threshold, ', dipotong ke brain mask' if clip_brain else '')) | |
| if preprocessed is not None: | |
| with tabs['Preprocessing']: | |
| preprocess_tab(preprocessed, st.session_state[zkey], rotate) | |
| st.stop() | |
| # ------------------------------------------------------------------ mode satu slice | |
| st.subheader('2. Hasil satu slice') | |
| if Z > 1: | |
| zkey = 'zs_%s' % input_hash | |
| if zkey not in st.session_state: | |
| st.session_state[zkey] = int(np.argmax(gt.sum(axis=(0, 1)))) if gt is not None and gt.any() else Z // 2 | |
| st.slider('Slice (z)', 0, Z - 1, key=zkey) | |
| z = st.session_state[zkey] | |
| else: | |
| z = 0 | |
| if info['slice_context'] == 1 or Z == 1: | |
| contexts = ['single'] | |
| if info['slice_context'] == 1: | |
| st.caption('Model ini dilatih dengan 1 slice, jadi konteks tetangga tidak dipakai.') | |
| else: | |
| choice = st.segmented_control('Konteks input model', ['neighbors', 'single', 'both'], default='neighbors', | |
| format_func=lambda c: {'neighbors': CONTEXT_LABELS['neighbors'], | |
| 'single': CONTEXT_LABELS['single'], | |
| 'both': 'Bandingkan keduanya'}[c]) or 'neighbors' | |
| contexts = ['neighbors', 'single'] if choice == 'both' else [choice] | |
| st.caption('3 slice = cara model dilatih (paling sesuai). 1 slice = hanya slice z, diulang 3x.' | |
| + (' Slice di tepi volume: tetangga yang tidak ada diganti slice terdekat.' | |
| if choice != 'single' and z in (0, Z - 1) else '')) | |
| t1, t2, t3 = st.columns(3) | |
| show_pred = t1.toggle('Prediksi', value=True, key='sp') | |
| show_gt = t2.toggle('Ground truth', value=gt is not None, disabled=gt is None, key='sg') | |
| show_prob = t3.toggle('Heatmap probabilitas', value=False, key='sh') | |
| pixel_mm2 = float(zooms[0] * zooms[1]) | |
| gt_slice = gt[:, :, z] if gt is not None else None | |
| columns = st.columns(len(contexts)) | |
| for column, context in zip(columns, contexts): | |
| key = key_base + '|slice%d|%s' % (z, context) | |
| if key not in cache: | |
| cache[key] = predict_slices(model, volume, [z], info['slice_context'], context, tta=tta)[:, :, 0] | |
| prob = cache[key] * brain[:, :, z] if clip_brain else cache[key] | |
| pred = prob >= threshold | |
| n_pred = int(pred.sum()) | |
| with column, st.container(border=True): | |
| st.markdown('**%s**' % CONTEXT_LABELS[context]) | |
| m = st.columns(3 if gt_slice is not None else 2) | |
| m[0].metric('Status', 'Lesi terdeteksi' if n_pred > MIN_LESION_VOXELS else 'Tidak terdeteksi') | |
| m[1].metric('Luas prediksi', '%.1f mm2' % (n_pred * pixel_mm2), '%d piksel' % n_pred, delta_color='off') | |
| if gt_slice is not None: | |
| m[2].metric('Dice slice', fmt_dice(dice(pred, gt_slice)), | |
| 'GT %d piksel' % int(gt_slice.sum()), delta_color='off') | |
| st.plotly_chart(slice_view(volume[:, :, z], prob, pred, gt_slice, show_pred, show_gt, show_prob, 0.5, | |
| rotate, height=460 if len(contexts) > 1 else 560), | |
| width='stretch', config={'scrollZoom': True, 'displaylogo': False}, | |
| key='plot_%s' % context) | |
| st.download_button('Unduh mask slice (.nii.gz)', nifti_bytes(pred[:, :, None], affine), | |
| file_name='%s_z%d_%s_pred_mask.nii.gz' % (Path(ct_name).name.split('.')[0], z, context), | |
| mime='application/gzip', key='dl_%s' % context) | |
| legend(gt is not None) | |
| if gt_slice is not None and not gt_slice.any(): | |
| st.caption('Ground truth slice ini kosong: Dice tidak terdefinisi (-) kalau prediksi juga kosong, ' | |
| 'dan 0 kalau ada prediksi.') | |
Xet Storage Details
- Size:
- 32.7 kB
- Xet hash:
- 2e57c497efd539cf6d7233f1f72a66119663c564931fa4f3f630f3044646b010
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.