File size: 17,143 Bytes
d487db0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
"""
Cochlear Neurofilament Tracer — HuggingFace Gradio app
======================================================

Traces auditory-nerve fibers (Neurofilament channel) in confocal z-stacks of
the organ of Corti, uses the Myo7a hair-cell channel to separate
IHC-innervating from OHC-innervating fibers, and reports per-region
quantification (number of fibers, diameter, length, branch points, area
covered) plus a black-background skeleton image and an Excel workbook.

Accepts Zeiss **CZI** z-stacks and generic **TIFF** stacks.
"""

import os
import tempfile
import zipfile
import traceback

import numpy as np
import pandas as pd
import gradio as gr
from skimage.io import imsave
from scipy import ndimage as ndi

import processing as P

OUT_DIR = tempfile.mkdtemp(prefix="neuron_tracer_")

METRIC_COLS = [
    "File", "Frequency region", "Region", "Number of fibers",
    "Total length (um)", "Mean diameter (um)", "Median diameter (um)",
    "Branch points", "Area covered (um^2)", "FOV area (um^2)",
    "Area covered (% of FOV)",
]


# --------------------------------------------------------------------------- #
#  Small helpers
# --------------------------------------------------------------------------- #

def _channel_choices(img: P.LoadedImage):
    choices = []
    for i, ch in enumerate(img.channels):
        dye = ch.get("dye") or "no dye / transmitted"
        choices.append((f"Ch {i}{ch.get('name','?')} ({dye})", i))
    return choices


def _draw_boundary_on(gray_u8, boundary_frac, axis="Y"):
    """Return an RGB copy of a grayscale MIP with a yellow boundary line."""
    rgb = np.stack([gray_u8] * 3, axis=-1)
    ny, nx = gray_u8.shape
    if axis.upper() == "Y":
        b = min(max(int(round(boundary_frac * ny)), 0), ny - 1)
        rgb[b, :] = (255, 255, 0)
    else:
        b = min(max(int(round(boundary_frac * nx)), 0), nx - 1)
        rgb[:, b] = (255, 255, 0)
    return rgb


def _save_png(arr, name):
    path = os.path.join(OUT_DIR, name)
    imsave(path, arr)
    return path


def _build_excel(rows, path):
    """Write a tidy per-region sheet plus a frequency×region summary sheet."""
    df = pd.DataFrame(rows, columns=METRIC_COLS)
    with pd.ExcelWriter(path, engine="openpyxl") as xl:
        df.to_excel(xl, sheet_name="Per region", index=False)
        # Summary: only IHC / OHC rows, pivoted by frequency region.
        sub = df[df["Region"].isin(["IHC region", "OHC region"])]
        if not sub.empty:
            for metric in ["Number of fibers", "Total length (um)",
                           "Mean diameter (um)", "Branch points",
                           "Area covered (um^2)"]:
                piv = sub.pivot_table(index="Frequency region",
                                      columns="Region", values=metric,
                                      aggfunc="mean")
                sheet = metric.split(" (")[0][:28]
                piv.to_excel(xl, sheet_name=f"{sheet}")
    return df


# --------------------------------------------------------------------------- #
#  Single-image interactive flow
# --------------------------------------------------------------------------- #

def load_and_preview(file_obj, dz, dy, dx):
    if file_obj is None:
        return (None, gr.update(), gr.update(), gr.update(),
                gr.update(), None, None, "Please upload a CZI or TIFF file.")
    try:
        img = P.load_image(file_obj, dz=float(dz), dy=float(dy), dx=float(dx))
    except Exception as e:
        return (None, gr.update(), gr.update(), gr.update(),
                gr.update(), None, None,
                f"❌ Failed to load file:\n{e}\n{traceback.format_exc()}")

    nf, myo = P.guess_channels(img)
    choices = _channel_choices(img)
    freq = P.detect_frequency(img.source_name)
    bfrac = P.suggest_boundary(img.data[myo])

    nf_prev = P.channel_preview(img.data[nf])
    myo_prev = _draw_boundary_on(P.channel_preview(img.data[myo]), bfrac, "Y")

    dz_, dy_, dx_ = img.voxel
    status = (f"✅ Loaded **{img.source_name}** — shape "
              f"{img.data.shape} (C,Z,Y,X)\n\n"
              f"Voxel size: dz={dz_:.3f}, dy={dy_:.4f}, dx={dx_:.4f} µm.  "
              f"Detected frequency region: **{freq}**.\n\n"
              f"Auto-picked Neurofilament = Ch {nf}, Myo7a = Ch {myo}. "
              f"Adjust below if needed, then press **Run analysis**.")
    return (img,
            gr.update(choices=choices, value=nf),
            gr.update(choices=choices, value=myo),
            gr.update(value=freq),
            gr.update(value=round(bfrac, 3)),
            nf_prev, myo_prev, status)


def refresh_boundary_preview(img, myo_idx, boundary, axis):
    if img is None or myo_idx is None:
        return None
    myo_prev = P.channel_preview(img.data[int(myo_idx)])
    return _draw_boundary_on(myo_prev, float(boundary), axis)


def run_single(img, nf_idx, myo_idx, freq, axis, ihc_side, boundary,
               sensitivity, min_fiber):
    if img is None:
        return None, None, None, None, None, "Please load an image first."
    if nf_idx is None:
        return None, None, None, None, None, "Please select the Neurofilament channel."
    try:
        nf_idx, myo_idx = int(nf_idx), int(myo_idx)
        trace = P.trace_neurites(img.data[nf_idx], img.voxel,
                                 sensitivity=float(sensitivity))
        shape_yx = img.data[nf_idx].shape[1:]
        side = "low" if ihc_side.startswith("Low") else "high"
        ihc_roi, ohc_roi = P.make_region_masks(shape_yx, float(boundary),
                                               ihc_side=side, axis=axis)

        whole = P.compute_metrics(trace, "Whole field",
                                  min_fiber_um=float(min_fiber))
        m_ihc = P.compute_metrics(trace, "IHC region", ihc_roi,
                                  min_fiber_um=float(min_fiber))
        m_ohc = P.compute_metrics(trace, "OHC region", ohc_roi,
                                  min_fiber_um=float(min_fiber))

        skel_img = P.skeleton_image(trace.skeleton)
        region_img = P.region_overlay(trace.skeleton, ihc_roi, ohc_roi,
                                      float(boundary), axis)
        myo_img = _draw_boundary_on(P.channel_preview(img.data[myo_idx]),
                                    float(boundary), axis)

        stem = os.path.splitext(img.source_name)[0]
        skel_path = _save_png(skel_img, f"{stem}_skeleton.png")

        rows = []
        for m in (whole, m_ihc, m_ohc):
            r = m.as_row()
            r = {"File": img.source_name, "Frequency region": freq, **r}
            rows.append(r)
        df = pd.DataFrame(rows, columns=METRIC_COLS)
        xl_path = os.path.join(OUT_DIR, f"{stem}_quantification.xlsx")
        _build_excel(rows, xl_path)

        status = (f"✅ Done. Traced {int(trace.skeleton.sum())} skeleton voxels. "
                  f"IHC={m_ihc.n_fibers} fibers / {m_ihc.total_length_um:.0f} µm, "
                  f"OHC={m_ohc.n_fibers} fibers / {m_ohc.total_length_um:.0f} µm.")
        # Return skeleton path also as downloadable file
        return (skel_img, region_img, myo_img, df,
                [skel_path, xl_path], status)
    except Exception as e:
        return (None, None, None, None, None,
                f"❌ Error:\n{e}\n{traceback.format_exc()}")


# --------------------------------------------------------------------------- #
#  Batch flow
# --------------------------------------------------------------------------- #

def run_batch(files, axis, ihc_side, sensitivity, min_fiber, dz, dy, dx,
              progress=gr.Progress()):
    if not files:
        return None, None, None, "Please upload one or more files."
    side = "low" if ihc_side.startswith("Low") else "high"
    all_rows, gallery, skel_paths = [], [], []
    log = []
    for f in progress.tqdm(files, desc="Processing"):
        path = f if isinstance(f, str) else f.name
        name = os.path.basename(path)
        try:
            img = P.load_image(path, dz=float(dz), dy=float(dy), dx=float(dx))
            nf, myo = P.guess_channels(img)
            freq = P.detect_frequency(name)
            trace = P.trace_neurites(img.data[nf], img.voxel,
                                     sensitivity=float(sensitivity))
            bfrac = P.suggest_boundary(img.data[myo])
            shape_yx = img.data[nf].shape[1:]
            ihc_roi, ohc_roi = P.make_region_masks(shape_yx, bfrac,
                                                   ihc_side=side, axis=axis)
            for m in (P.compute_metrics(trace, "Whole field",
                                        min_fiber_um=float(min_fiber)),
                      P.compute_metrics(trace, "IHC region", ihc_roi,
                                        min_fiber_um=float(min_fiber)),
                      P.compute_metrics(trace, "OHC region", ohc_roi,
                                        min_fiber_um=float(min_fiber))):
                all_rows.append({"File": name, "Frequency region": freq,
                                 **m.as_row()})
            skel_img = P.skeleton_image(trace.skeleton)
            stem = os.path.splitext(name)[0]
            sp = _save_png(skel_img, f"{stem}_skeleton.png")
            skel_paths.append(sp)
            gallery.append((skel_img, f"{name} ({freq})"))
            log.append(f"✅ {name}: {freq}")
        except Exception as e:
            log.append(f"❌ {name}: {e}")

    if not all_rows:
        return None, None, gallery, "No files processed.\n" + "\n".join(log)

    xl_path = os.path.join(OUT_DIR, "batch_quantification.xlsx")
    df = _build_excel(all_rows, xl_path)

    zip_path = os.path.join(OUT_DIR, "batch_skeletons.zip")
    with zipfile.ZipFile(zip_path, "w") as z:
        for sp in skel_paths:
            z.write(sp, os.path.basename(sp))
        z.write(xl_path, os.path.basename(xl_path))

    return df, [xl_path, zip_path], gallery, "\n".join(log)


# --------------------------------------------------------------------------- #
#  UI
# --------------------------------------------------------------------------- #

INTRO = """
# 🧠 Cochlear Neurofilament Tracer

Trace auditory-nerve fibers in confocal z-stacks and quantify them **per
frequency region**, separating **IHC-innervating** from **OHC-innervating**
fibers using the Myo7a hair-cell channel.

**Channels expected:** *Neurofilament* (traces the neuron) and *Myo7a* (hair
cells — reference to split IHC vs OHC). IHCs form a single row, OHCs form three
rows, so the Myo7a band is used to place the IHC/OHC boundary — which you can
fine-tune by hand.

**Input:** Zeiss `.czi` z-stacks or generic `.tif/.tiff` stacks.
"""

with gr.Blocks(title="Cochlear Neurofilament Tracer", theme=gr.themes.Soft()) as demo:
    gr.Markdown(INTRO)

    with gr.Tab("Single image (interactive)"):
        img_state = gr.State()
        with gr.Row():
            with gr.Column(scale=1):
                file_in = gr.File(label="Upload CZI or TIFF",
                                  file_types=[".czi", ".tif", ".tiff"],
                                  type="filepath")
                with gr.Accordion("Voxel size (µm) — used for TIFF; CZI reads "
                                  "its own", open=False):
                    dz_in = gr.Number(0.35, label="dz (µm/plane)")
                    dy_in = gr.Number(0.0895, label="dy (µm/px)")
                    dx_in = gr.Number(0.0895, label="dx (µm/px)")
                load_btn = gr.Button("① Load & preview", variant="secondary")

                nf_dd = gr.Dropdown(label="Neurofilament channel", choices=[])
                myo_dd = gr.Dropdown(label="Myo7a channel", choices=[])
                freq_dd = gr.Dropdown(label="Frequency region",
                                      choices=P.FREQ_CHOICES,
                                      value="Other / unknown")

                gr.Markdown("**IHC / OHC region split** (Myo7a-guided)")
                axis_dd = gr.Radio(["Y", "X"], value="Y",
                                   label="Split axis (Y = radial, usual)")
                side_dd = gr.Radio(["Low side = IHC", "High side = IHC"],
                                   value="Low side = IHC",
                                   label="Which side is IHC?")
                boundary_sl = gr.Slider(0.0, 1.0, value=0.5, step=0.005,
                                        label="Boundary position (fraction "
                                              "along split axis)")

                gr.Markdown("**Tracing**")
                sens_sl = gr.Slider(0.5, 1.5, value=1.0, step=0.05,
                                    label="Sensitivity (↑ = capture more/thinner "
                                          "fibers)")
                minfib_sl = gr.Slider(0.0, 20.0, value=5.0, step=0.5,
                                      label="Min fiber length to count (µm)")
                run_btn = gr.Button("② Run analysis", variant="primary")

            with gr.Column(scale=2):
                status = gr.Markdown()
                with gr.Row():
                    nf_prev = gr.Image(label="Neurofilament (MIP)",
                                       height=220)
                    myo_prev = gr.Image(label="Myo7a (MIP) + boundary",
                                        height=220)
                skel_out = gr.Image(label="Traced neurons — white on black",
                                    height=300)
                region_out = gr.Image(label="Region overlay (cyan = IHC, "
                                            "magenta = OHC)", height=300)
                table = gr.Dataframe(label="Quantification", wrap=True)
                files_out = gr.Files(label="Downloads (skeleton PNG + Excel)")

        load_btn.click(load_and_preview,
                       [file_in, dz_in, dy_in, dx_in],
                       [img_state, nf_dd, myo_dd, freq_dd, boundary_sl,
                        nf_prev, myo_prev, status])
        # Live boundary preview
        for comp in (boundary_sl, myo_dd, axis_dd):
            comp.change(refresh_boundary_preview,
                        [img_state, myo_dd, boundary_sl, axis_dd], myo_prev)
        run_btn.click(run_single,
                      [img_state, nf_dd, myo_dd, freq_dd, axis_dd, side_dd,
                       boundary_sl, sens_sl, minfib_sl],
                      [skel_out, region_out, myo_prev, table, files_out, status])

    with gr.Tab("Batch (multiple images)"):
        gr.Markdown(
            "Upload several z-stacks (e.g. all frequency regions of one "
            "cochlea). Each is auto-traced with an auto-placed IHC/OHC "
            "boundary, and results are combined into one Excel workbook "
            "organized by frequency region.")
        with gr.Row():
            with gr.Column(scale=1):
                batch_files = gr.File(label="Upload CZI/TIFF files",
                                      file_count="multiple",
                                      file_types=[".czi", ".tif", ".tiff"],
                                      type="filepath")
                b_axis = gr.Radio(["Y", "X"], value="Y", label="Split axis")
                b_side = gr.Radio(["Low side = IHC", "High side = IHC"],
                                  value="Low side = IHC",
                                  label="Which side is IHC?")
                b_sens = gr.Slider(0.5, 1.5, value=1.0, step=0.05,
                                   label="Sensitivity")
                b_minfib = gr.Slider(0.0, 20.0, value=5.0, step=0.5,
                                     label="Min fiber length (µm)")
                with gr.Accordion("Voxel size (µm) for TIFF", open=False):
                    b_dz = gr.Number(0.35, label="dz")
                    b_dy = gr.Number(0.0895, label="dy")
                    b_dx = gr.Number(0.0895, label="dx")
                batch_btn = gr.Button("Run batch", variant="primary")
            with gr.Column(scale=2):
                batch_log = gr.Textbox(label="Log", lines=6)
                batch_table = gr.Dataframe(label="Combined quantification",
                                           wrap=True)
                batch_files_out = gr.Files(label="Downloads (Excel + ZIP)")
                batch_gallery = gr.Gallery(label="Skeleton traces",
                                           columns=3, height=400)
        batch_btn.click(run_batch,
                        [batch_files, b_axis, b_side, b_sens, b_minfib,
                         b_dz, b_dy, b_dx],
                        [batch_table, batch_files_out, batch_gallery, batch_log])

    gr.Markdown(
        "---\n*Method:* the Neurofilament channel is smoothed, thresholded "
        "(Otsu, scaled by the sensitivity control) and skeletonised in 3D; "
        "length, diameter (from the 3D distance transform), branch points and "
        "footprint area are measured with physical voxel spacing. Each fiber is "
        "a connected skeleton component ≥ the minimum length. The Myo7a band "
        "defines the IHC/OHC boundary, and metrics are reported for each "
        "region.")

if __name__ == "__main__":
    demo.launch()