stevafernandes commited on
Commit
3c12e23
·
verified ·
1 Parent(s): d593f78

Deploy CellQuant

Browse files
README.md CHANGED
@@ -90,7 +90,10 @@ images with the v2 recipe; the peak-distance rule is post-processing only.
90
  single pass). `CELLQUANT_TTA=1` or `4` changes this for local runs.
91
  3. Click **Analyse**. You get a counts table, colour overlays and a zip with
92
  `counts.csv`, `objects.csv` (every nucleus and punctum with centroid, area, probabilities)
93
- and `results.json`.
 
 
 
94
  4. A written summary follows the counts in both sections when the Space has a `GEMINI_API_KEY`
95
  secret (optionally `GEMINI_MODEL`, default `gemini-4-argon`); without the key a one-line notice
96
  takes its place. Gemini only restates the counts in prose and comments on image quality or on
 
90
  single pass). `CELLQUANT_TTA=1` or `4` changes this for local runs.
91
  3. Click **Analyse**. You get a counts table, colour overlays and a zip with
92
  `counts.csv`, `objects.csv` (every nucleus and punctum with centroid, area, probabilities)
93
+ and `results.json`. The table and `counts.csv` have one row per image and eight count columns:
94
+ the four nucleus labels followed by their total, **All nuclei**, then the two punctum labels
95
+ followed by their total, **All puncta** (the same totals as in the validation table of
96
+ section 2; `results.json` carries them under `totals`). Each overlay caption gives the two totals.
97
  4. A written summary follows the counts in both sections when the Space has a `GEMINI_API_KEY`
98
  secret (optionally `GEMINI_MODEL`, default `gemini-4-argon`); without the key a one-line notice
99
  takes its place. Gemini only restates the counts in prose and comments on image quality or on
app.py CHANGED
@@ -38,7 +38,7 @@ from cellquant.gemini_summary import enabled as gemini_enabled
38
  from cellquant.gemini_summary import summarize as gemini_summarize
39
  from cellquant.gemini_summary import summarize_comparison as gemini_summarize_comparison
40
  from cellquant.infer import Predictor
41
- from cellquant.labels import ALL_LABELS, LABEL_COLORS
42
  from cellquant.model import load_checkpoint
43
  from cellquant.postprocess import PostConfig, analyze, render_overlay, result_to_json
44
  from cellquant.validation import COMPARISON_HEADERS, COMPARISON_NOTE, DIFF_HEADERS, ValidationSet, compare, write_bundle
@@ -144,9 +144,12 @@ def _analyze_gpu(files, antibody_thr, cellnos_thr, min_cell_area, nostril_rule,
144
  overlays[name] = ov
145
  out_png = os.path.join(tmpdir, os.path.splitext(name)[0] + "_overlay.png")
146
  Image.fromarray(ov).save(out_png)
147
- gallery.append((out_png, f"{name}: {res.counts['Cell, Antibody +'] + res.counts['Cell, Antibody -'] + res.counts['Cell, Nostril, Antibody +'] + res.counts['Cell, Nostril, Antibody -']} nuclei"))
148
- rows.append([name] + [res.counts[lab] for lab in ALL_LABELS])
149
- per_image_json[name] = {"image_size_hw": list(img.shape[:2]), **result_to_json(res)}
 
 
 
150
  for c in res.cells:
151
  csv_objects.append([name, "nucleus", c["id"], c["label"], round(c["area_px"], 1), round(c["centroid_xy"][0], 1), round(c["centroid_xy"][1], 1), round(c["p_antibody"], 3), round(c["p_nostril"], 3), c["n_puncta_inside"]])
152
  for n_ in res.nostrils:
@@ -155,7 +158,7 @@ def _analyze_gpu(files, antibody_thr, cellnos_thr, min_cell_area, nostril_rule,
155
  counts_csv = os.path.join(tmpdir, "counts.csv")
156
  with open(counts_csv, "w", newline="") as fh:
157
  w = csv.writer(fh)
158
- w.writerow(["image"] + list(ALL_LABELS))
159
  w.writerows(rows)
160
  objects_csv = os.path.join(tmpdir, "objects.csv")
161
  with open(objects_csv, "w", newline="") as fh:
@@ -187,7 +190,7 @@ def analyze_files(files, antibody_thr, cellnos_thr, min_cell_area, nostril_rule,
187
  _safe_progress(progress, 0.95, desc="writing the summary")
188
  text = None
189
  if gemini_enabled():
190
- text = gemini_summarize([{"image": r[0], "counts": dict(zip(ALL_LABELS, r[1:]))} for r in rows],
191
  overlay=Image.open(gallery[0][0]))
192
  return rows, gallery, zip_path, summary + "\n\n" + _gemini_section(text)
193
 
@@ -295,7 +298,7 @@ def build_demo() -> gr.Blocks:
295
  if examples:
296
  gr.Examples(examples=[[[e]] for e in examples], inputs=[files], label="Example (512 px crop of a training image)")
297
  with gr.Column(scale=2):
298
- table = gr.Dataframe(headers=["image"] + list(ALL_LABELS), label="Counts", interactive=False, wrap=True)
299
  gallery = gr.Gallery(label="Overlays", columns=2, height="auto")
300
  zip_out = gr.File(label="Download results (CSV + JSON + overlays)")
301
  summary = gr.Markdown()
 
38
  from cellquant.gemini_summary import summarize as gemini_summarize
39
  from cellquant.gemini_summary import summarize_comparison as gemini_summarize_comparison
40
  from cellquant.infer import Predictor
41
+ from cellquant.labels import COUNT_COLUMNS, LABEL_COLORS, TOTAL_NUCLEI, TOTAL_PUNCTA, count_row
42
  from cellquant.model import load_checkpoint
43
  from cellquant.postprocess import PostConfig, analyze, render_overlay, result_to_json
44
  from cellquant.validation import COMPARISON_HEADERS, COMPARISON_NOTE, DIFF_HEADERS, ValidationSet, compare, write_bundle
 
144
  overlays[name] = ov
145
  out_png = os.path.join(tmpdir, os.path.splitext(name)[0] + "_overlay.png")
146
  Image.fromarray(ov).save(out_png)
147
+ row = count_row(res.counts)
148
+ n_nuclei, n_puncta = row[COUNT_COLUMNS.index(TOTAL_NUCLEI)], row[COUNT_COLUMNS.index(TOTAL_PUNCTA)]
149
+ gallery.append((out_png, f"{name}: {n_nuclei} nuclei, {n_puncta} puncta"))
150
+ rows.append([name] + row)
151
+ per_image_json[name] = {"image_size_hw": list(img.shape[:2]), **result_to_json(res),
152
+ "totals": {TOTAL_NUCLEI: n_nuclei, TOTAL_PUNCTA: n_puncta}}
153
  for c in res.cells:
154
  csv_objects.append([name, "nucleus", c["id"], c["label"], round(c["area_px"], 1), round(c["centroid_xy"][0], 1), round(c["centroid_xy"][1], 1), round(c["p_antibody"], 3), round(c["p_nostril"], 3), c["n_puncta_inside"]])
155
  for n_ in res.nostrils:
 
158
  counts_csv = os.path.join(tmpdir, "counts.csv")
159
  with open(counts_csv, "w", newline="") as fh:
160
  w = csv.writer(fh)
161
+ w.writerow(["image"] + list(COUNT_COLUMNS))
162
  w.writerows(rows)
163
  objects_csv = os.path.join(tmpdir, "objects.csv")
164
  with open(objects_csv, "w", newline="") as fh:
 
190
  _safe_progress(progress, 0.95, desc="writing the summary")
191
  text = None
192
  if gemini_enabled():
193
+ text = gemini_summarize([{"image": r[0], "counts": dict(zip(COUNT_COLUMNS, r[1:]))} for r in rows],
194
  overlay=Image.open(gallery[0][0]))
195
  return rows, gallery, zip_path, summary + "\n\n" + _gemini_section(text)
196
 
 
298
  if examples:
299
  gr.Examples(examples=[[[e]] for e in examples], inputs=[files], label="Example (512 px crop of a training image)")
300
  with gr.Column(scale=2):
301
+ table = gr.Dataframe(headers=["image"] + list(COUNT_COLUMNS), label="Counts", interactive=False, wrap=True)
302
  gallery = gr.Gallery(label="Overlays", columns=2, height="auto")
303
  zip_out = gr.File(label="Download results (CSV + JSON + overlays)")
304
  summary = gr.Markdown()
cellquant/__init__.py CHANGED
@@ -3,4 +3,4 @@
3
  Trained on CVAT polygon annotations of 1024x1024 RGB images (blue = DAPI nuclei,
4
  green = antibody stain such as Iba1 or Tmem119, red = puncta).
5
  """
6
- __version__ = "1.2.3"
 
3
  Trained on CVAT polygon annotations of 1024x1024 RGB images (blue = DAPI nuclei,
4
  green = antibody stain such as Iba1 or Tmem119, red = puncta).
5
  """
6
+ __version__ = "1.2.4"
cellquant/gemini_summary.py CHANGED
@@ -34,7 +34,8 @@ def _prompt(rows: list[dict]) -> str:
34
  "exclusive, so total nuclei = sum of the four). 'Cell, Antibody +' = nucleus with green antibody signal and no "
35
  "punctum; 'Cell, Antibody -' = nucleus without antibody signal and no punctum; 'Cell, Nostril, Antibody +/-' = "
36
  "nucleus containing a red punctum, with/without antibody signal. 'Nostril in Nucleus' = punctum inside a nucleus; "
37
- "'Nostril External of Nucleus' = punctum outside nuclei.\n"
 
38
  "Write a concise summary (max 150 words) for the lab notebook: restate the counts exactly as given "
39
  "(do not round, estimate or invent numbers), give the fraction of nuclei that are antibody positive "
40
  "and the fraction that contain a punctum, and mention anything in the overlay thumbnail that looks "
 
34
  "exclusive, so total nuclei = sum of the four). 'Cell, Antibody +' = nucleus with green antibody signal and no "
35
  "punctum; 'Cell, Antibody -' = nucleus without antibody signal and no punctum; 'Cell, Nostril, Antibody +/-' = "
36
  "nucleus containing a red punctum, with/without antibody signal. 'Nostril in Nucleus' = punctum inside a nucleus; "
37
+ "'Nostril External of Nucleus' = punctum outside nuclei. 'All nuclei' and 'All puncta' are the totals of "
38
+ "the four nucleus categories and of the two punctum categories.\n"
39
  "Write a concise summary (max 150 words) for the lab notebook: restate the counts exactly as given "
40
  "(do not round, estimate or invent numbers), give the fraction of nuclei that are antibody positive "
41
  "and the fraction that contain a punctum, and mention anything in the overlay thumbnail that looks "
cellquant/labels.py CHANGED
@@ -14,6 +14,12 @@ NOSTRIL_LABELS = (
14
  )
15
  ALL_LABELS = CELL_LABELS + NOSTRIL_LABELS
16
 
 
 
 
 
 
 
17
  # Display colours (RGB) used for overlays, one per label.
18
  LABEL_COLORS = {
19
  "Cell, Antibody +": (0, 255, 0),
@@ -25,6 +31,14 @@ LABEL_COLORS = {
25
  }
26
 
27
 
 
 
 
 
 
 
 
 
28
  def is_cell_label(label: str) -> bool:
29
  return label.startswith("Cell")
30
 
 
14
  )
15
  ALL_LABELS = CELL_LABELS + NOSTRIL_LABELS
16
 
17
+ # Columns of the per-image counts table and counts.csv (app section 1): each group of labels
18
+ # is followed by its total, as in the validation table of section 2.
19
+ TOTAL_NUCLEI = "All nuclei"
20
+ TOTAL_PUNCTA = "All puncta"
21
+ COUNT_COLUMNS = CELL_LABELS + (TOTAL_NUCLEI,) + NOSTRIL_LABELS + (TOTAL_PUNCTA,)
22
+
23
  # Display colours (RGB) used for overlays, one per label.
24
  LABEL_COLORS = {
25
  "Cell, Antibody +": (0, 255, 0),
 
31
  }
32
 
33
 
34
+ def count_row(counts: dict) -> list[int]:
35
+ """Per-image counts in COUNT_COLUMNS order: the four nucleus labels, their sum, the two
36
+ punctum labels, their sum. Labels missing from ``counts`` count as 0."""
37
+ nuclei = [int(counts.get(lab, 0)) for lab in CELL_LABELS]
38
+ puncta = [int(counts.get(lab, 0)) for lab in NOSTRIL_LABELS]
39
+ return nuclei + [sum(nuclei)] + puncta + [sum(puncta)]
40
+
41
+
42
  def is_cell_label(label: str) -> bool:
43
  return label.startswith("Cell")
44
 
tests/test_app.py CHANGED
@@ -19,17 +19,32 @@ def test_analyze_files_end_to_end(tmp_path, monkeypatch):
19
  p2 = tmp_path / "b.tif"
20
  tifffile.imwrite(str(p2), img)
21
  rows, gallery, zip_path, summary = app.analyze_files([str(p1), str(p2)], 0.5, 0.5, 50, "head", "contains")
22
- assert len(rows) == 2 and rows[0][0] == "a.png" and len(rows[0]) == 7
 
 
 
23
  assert len(gallery) == 2 and os.path.exists(gallery[0][0])
 
24
  assert os.path.exists(zip_path) and summary.startswith("Analysed 2 images in ") and "on the CPU" in summary
25
  assert "Gemini summary is off" in summary # no key: the write-up is replaced by a one-line notice
26
  assert app._gpu_seconds(3) == 15 + 3 * {1: 4, 4: 6, 8: 10}[app.TTA] and app._gpu_seconds(0) == 15 + {1: 4, 4: 6, 8: 10}[app.TTA]
27
  with pytest.raises(Exception):
28
  app.analyze_files([], 0.5, 0.5, 50, "head", "contains")
 
 
 
29
  import zipfile
30
  with zipfile.ZipFile(zip_path) as zf:
31
  names = zf.namelist()
 
 
32
  assert "counts.csv" in names and "objects.csv" in names and "results.json" in names
 
 
 
 
 
 
33
 
34
 
35
  def test_build_demo_constructs():
 
19
  p2 = tmp_path / "b.tif"
20
  tifffile.imwrite(str(p2), img)
21
  rows, gallery, zip_path, summary = app.analyze_files([str(p1), str(p2)], 0.5, 0.5, 50, "head", "contains")
22
+ from cellquant.labels import COUNT_COLUMNS
23
+ assert len(rows) == 2 and rows[0][0] == "a.png" and len(rows[0]) == 1 + len(COUNT_COLUMNS) == 9
24
+ for r in rows: # "All nuclei" after the four nucleus labels, "All puncta" after the two punctum labels
25
+ assert r[5] == sum(r[1:5]) and r[8] == sum(r[6:8])
26
  assert len(gallery) == 2 and os.path.exists(gallery[0][0])
27
+ assert gallery[0][1] == f"a.png: {rows[0][5]} nuclei, {rows[0][8]} puncta"
28
  assert os.path.exists(zip_path) and summary.startswith("Analysed 2 images in ") and "on the CPU" in summary
29
  assert "Gemini summary is off" in summary # no key: the write-up is replaced by a one-line notice
30
  assert app._gpu_seconds(3) == 15 + 3 * {1: 4, 4: 6, 8: 10}[app.TTA] and app._gpu_seconds(0) == 15 + {1: 4, 4: 6, 8: 10}[app.TTA]
31
  with pytest.raises(Exception):
32
  app.analyze_files([], 0.5, 0.5, 50, "head", "contains")
33
+ import csv
34
+ import io
35
+ import json
36
  import zipfile
37
  with zipfile.ZipFile(zip_path) as zf:
38
  names = zf.namelist()
39
+ counts_csv = list(csv.reader(io.StringIO(zf.read("counts.csv").decode())))
40
+ results = json.loads(zf.read("results.json"))
41
  assert "counts.csv" in names and "objects.csv" in names and "results.json" in names
42
+ assert counts_csv[0] == ["image"] + list(COUNT_COLUMNS)
43
+ assert counts_csv[0][5] == "All nuclei" and counts_csv[0][8] == "All puncta"
44
+ assert [[r[0]] + [int(v) for v in r[1:]] for r in counts_csv[1:]] == rows
45
+ assert results["cellquant_version"] == app.__version__
46
+ assert results["images"]["a.png"]["totals"] == {"All nuclei": rows[0][5], "All puncta": rows[0][8]}
47
+ assert results["images"]["a.png"]["totals"]["All nuclei"] == sum(results["images"]["a.png"]["counts"][lab] for lab in COUNT_COLUMNS[:4])
48
 
49
 
50
  def test_build_demo_constructs():
tests/test_labels.py CHANGED
@@ -1,4 +1,5 @@
1
- from cellquant.labels import ALL_LABELS, CELL_LABELS, NOSTRIL_LABELS, cell_attributes, cell_label, nostril_in_nucleus, nostril_label
 
2
 
3
 
4
  def test_cell_label_roundtrip():
@@ -14,3 +15,28 @@ def test_nostril_label_roundtrip():
14
 
15
  def test_label_sets_disjoint():
16
  assert len(ALL_LABELS) == 6 and set(CELL_LABELS).isdisjoint(NOSTRIL_LABELS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cellquant.labels import (ALL_LABELS, CELL_LABELS, COUNT_COLUMNS, NOSTRIL_LABELS, TOTAL_NUCLEI, TOTAL_PUNCTA, cell_attributes,
2
+ cell_label, count_row, nostril_in_nucleus, nostril_label)
3
 
4
 
5
  def test_cell_label_roundtrip():
 
15
 
16
  def test_label_sets_disjoint():
17
  assert len(ALL_LABELS) == 6 and set(CELL_LABELS).isdisjoint(NOSTRIL_LABELS)
18
+
19
+
20
+ def test_count_columns_order():
21
+ # each group of labels is followed by its total, nuclei first
22
+ assert COUNT_COLUMNS == CELL_LABELS + (TOTAL_NUCLEI,) + NOSTRIL_LABELS + (TOTAL_PUNCTA,)
23
+ assert len(COUNT_COLUMNS) == 8 and COUNT_COLUMNS.index(TOTAL_NUCLEI) == 4 and COUNT_COLUMNS.index(TOTAL_PUNCTA) == 7
24
+ assert [c for c in COUNT_COLUMNS if c not in (TOTAL_NUCLEI, TOTAL_PUNCTA)] == list(ALL_LABELS)
25
+
26
+
27
+ def test_count_row_sums_each_group():
28
+ counts = {"Cell, Antibody +": 3, "Cell, Antibody -": 5, "Cell, Nostril, Antibody +": 7, "Cell, Nostril, Antibody -": 11,
29
+ "Nostril in Nucleus": 13, "Nostril External of Nucleus": 17}
30
+ row = count_row(counts)
31
+ assert row == [3, 5, 7, 11, 26, 13, 17, 30]
32
+ assert len(row) == len(COUNT_COLUMNS)
33
+ assert row[COUNT_COLUMNS.index(TOTAL_NUCLEI)] == sum(counts[lab] for lab in CELL_LABELS)
34
+ assert row[COUNT_COLUMNS.index(TOTAL_PUNCTA)] == sum(counts[lab] for lab in NOSTRIL_LABELS)
35
+ assert all(isinstance(v, int) for v in row)
36
+
37
+
38
+ def test_count_row_missing_labels_count_as_zero():
39
+ assert count_row({}) == [0] * 8
40
+ row = count_row({"Cell, Antibody -": 2, "Nostril External of Nucleus": 4, "unknown label": 99})
41
+ assert row == [0, 2, 0, 0, 2, 0, 4, 4]
42
+ assert count_row({"Cell, Antibody +": 1.0}) == [1, 0, 0, 0, 1, 0, 0, 0] # numpy / float counts become ints