Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions monai/data/csv_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from __future__ import annotations

import codecs
import os
import warnings
from collections import OrderedDict
Expand All @@ -31,6 +32,10 @@ class CSVSaver:
the cached data into CSV file. If no metadata provided, use index from 0 to save data.
Note that this saver can't support multi-processing because it reads / writes single
CSV file and can't guarantee the data order in multi-processing situation.
The saver assumes it is the only writer while active; concurrent external modifications
to the output file are unsupported.
Output files are encoded as UTF-8. Appending to an existing file that is not valid
UTF-8 raises a ``ValueError`` instead of mixing encodings.

"""

Expand Down Expand Up @@ -62,23 +67,51 @@ def __init__(
if self._filepath.exists() and overwrite:
os.remove(self._filepath)

self._validated_file: tuple[int, ...] | None = None
self.flush = flush
self.delimiter = delimiter
self._data_index = 0

@staticmethod
def _file_fingerprint(file_stat: os.stat_result) -> tuple[int, ...]:
return (file_stat.st_dev, file_stat.st_ino, file_stat.st_size, file_stat.st_mtime_ns, file_stat.st_ctime_ns)

def _validate_utf8_file(self) -> None:
file_stat = self._filepath.stat()
fingerprint = self._file_fingerprint(file_stat)
if self._validated_file == fingerprint:
return

try:
decoder = codecs.getincrementaldecoder("utf-8")("strict")
with open(self._filepath, "rb") as existing:
for chunk in iter(lambda: existing.read(1024 * 1024), b""):
decoder.decode(chunk)
decoder.decode(b"", final=True)
except UnicodeDecodeError as error:
raise ValueError(f"{self._filepath} is not valid UTF-8; convert it to UTF-8 before appending.") from error
self._validated_file = fingerprint

def finalize(self) -> None:
"""
Writes the cached dict to a csv
Write the cached dict to a CSV file.

Raises:
ValueError: If appending to an existing file that is not valid UTF-8.
The existing file is left unchanged and the cache is preserved.

"""
if not self.output_dir.exists():
self.output_dir.mkdir(parents=True, exist_ok=True)
with open(self._filepath, "a") as f:
if self._filepath.exists():
self._validate_utf8_file()
with open(self._filepath, "a", encoding="utf-8") as f:
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
for k, v in self._cache_dict.items():
f.write(k)
for result in v.flatten():
f.write(self.delimiter + str(result))
f.write("\n")
self._validated_file = self._file_fingerprint(self._filepath.stat())
# clear cache content after writing
self.reset_cache()

Expand All @@ -105,6 +138,10 @@ def save_batch(self, batch_data: torch.Tensor | np.ndarray, meta_data: dict | No
batch_data: target batch data content that save into cache.
meta_data: every key-value in the meta_data is corresponding to 1 batch of data.

Raises:
ValueError: If ``flush`` is True and appending to an existing file that
is not valid UTF-8. The exception is propagated from ``finalize``.

"""
for i, data in enumerate(batch_data): # save a batch of files
self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None)
Expand Down
7 changes: 4 additions & 3 deletions monai/handlers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ def write_metrics_reports(
1. if `metrics` dict is not None, write overall metrics into file, every line is a metric name and value pair.
2. if `metric_details` dict is not None, write raw metric data of every image into file, every line for 1 image.
3. if `summary_ops` is not None, compute summary based on operations on `metric_details` and write to file.
All output files are encoded as UTF-8.

Args:
save_dir: directory to save all the metrics reports.
Expand Down Expand Up @@ -106,7 +107,7 @@ class mean median max 5percentile 95percentile notnans
os.makedirs(save_dir)

if metrics is not None and len(metrics) > 0:
with open(os.path.join(save_dir, "metrics.csv"), "w") as f:
with open(os.path.join(save_dir, "metrics.csv"), "w", encoding="utf-8") as f:
for k, v in metrics.items():
f.write(f"{k}{deli}{str(v)}\n")
if metric_details is not None and len(metric_details) > 0:
Expand All @@ -129,7 +130,7 @@ class mean median max 5percentile 95percentile notnans
labels += ["mean"]
v = np.concatenate([v, np.nanmean(v, axis=1, keepdims=True)], axis=1)

with open(os.path.join(save_dir, f"{k}_raw.csv"), "w") as f:
with open(os.path.join(save_dir, f"{k}_raw.csv"), "w", encoding="utf-8") as f:
f.write(f"filename{deli}{deli.join(labels)}\n")
for i, b in enumerate(v):
f.write(
Expand Down Expand Up @@ -161,7 +162,7 @@ def _compute_op(op: str, d: np.ndarray) -> Any:
threshold = int(op.split("percentile")[0])
return supported_ops["90percentile"]((d, threshold)) # type: ignore

with open(os.path.join(save_dir, f"{k}_summary.csv"), "w") as f:
with open(os.path.join(save_dir, f"{k}_summary.csv"), "w", encoding="utf-8") as f:
f.write(f"class{deli}{deli.join(ops)}\n")
for i, c in enumerate(np.transpose(v)):
f.write(f"{labels[i]}{deli}{deli.join([f'{_compute_op(k, c):.4f}' for k in ops])}\n")
Expand Down
87 changes: 87 additions & 0 deletions tests/data/test_csv_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,93 @@ def test_saved_content(self):
i += 1
self.assertEqual(i, 8)

def test_utf8_non_ascii_filename_and_metadata(self):
patient_name = "\u60a3\u8005_01_\U0001f600.nii.gz"
csv_filename = "\u9884\u6d4b_\U0001f600.csv"
with tempfile.TemporaryDirectory() as tempdir:
saver = CSVSaver(output_dir=tempdir, filename=csv_filename, delimiter="\t")
saver.save_batch(torch.tensor([1, 2]), {"filename_or_obj": [patient_name, "patient_02"]})
saver.finalize()

filepath = os.path.join(tempdir, csv_filename)
with open(filepath, encoding="utf-8") as f:
rows = [line.split("\t") for line in f.read().splitlines()]

self.assertEqual(rows[0], [patient_name, "1.0"])
self.assertEqual(rows[1], ["patient_02", "2.0"])

def test_utf8_append_preserves_existing_rows(self):
patient_name = "\u60a3\u8005_02_\u75c5\u7076.nii.gz"
csv_filename = "predictions.csv"
with tempfile.TemporaryDirectory() as tempdir:
saver = CSVSaver(output_dir=tempdir, filename=csv_filename, delimiter="\t")
saver.save(torch.tensor(1), {"filename_or_obj": patient_name})
saver.finalize()

appender = CSVSaver(output_dir=tempdir, filename=csv_filename, overwrite=False, delimiter="\t")
appender.save(torch.tensor(2), {"filename_or_obj": "patient_03"})
appender.finalize()

filepath = os.path.join(tempdir, csv_filename)
with open(filepath, encoding="utf-8") as f:
rows = [line.split("\t") for line in f.read().splitlines()]

self.assertEqual(rows[0], [patient_name, "1.0"])
self.assertEqual(rows[1], ["patient_03", "2.0"])

def test_utf8_append_rejects_non_utf8_existing_file(self):
csv_filename = "predictions.csv"
legacy_contents = b"caf\xe9,1.0\n"
with tempfile.TemporaryDirectory() as tempdir:
filepath = os.path.join(tempdir, csv_filename)
with open(filepath, "wb") as f:
f.write(legacy_contents)

appender = CSVSaver(output_dir=tempdir, filename=csv_filename, overwrite=False, delimiter="\t")
appender.save(torch.tensor(2), {"filename_or_obj": "patient_03"})
with self.assertRaisesRegex(ValueError, "not valid UTF-8"):
appender.finalize()

with open(filepath, "rb") as f:
self.assertEqual(f.read(), legacy_contents)

def test_utf8_flush_rejects_non_utf8_suffix(self):
csv_filename = "predictions.csv"
patient_name = "\u60a3\u8005_04_\u75c5\u7076.nii.gz"
with tempfile.TemporaryDirectory() as tempdir:
saver = CSVSaver(output_dir=tempdir, filename=csv_filename, flush=True, delimiter="\t")
saver.save_batch(torch.tensor([1]), {"filename_or_obj": [patient_name]})
filepath = os.path.join(tempdir, csv_filename)
with open(filepath, "rb") as f:
valid_contents = f.read()
with open(filepath, "ab") as f:
f.write(b"\xff")

with self.assertRaisesRegex(ValueError, "not valid UTF-8"):
saver.save_batch(torch.tensor([2]), {"filename_or_obj": ["patient_05"]})

with open(filepath, "rb") as f:
self.assertEqual(f.read(), valid_contents + b"\xff")

def test_utf8_flush_rejects_same_size_rewrite(self):
csv_filename = "predictions.csv"
with tempfile.TemporaryDirectory() as tempdir:
saver = CSVSaver(output_dir=tempdir, filename=csv_filename, flush=True, delimiter="\t")
saver.save_batch(torch.tensor([1]), {"filename_or_obj": ["patient_06"]})
filepath = os.path.join(tempdir, csv_filename)
with open(filepath, "rb") as f:
valid_contents = f.read()
with open(filepath, "wb") as f:
f.write(b"\xff" + valid_contents[1:])
original_stat = os.stat(filepath)
os.utime(filepath, ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns + 1_000_000_000))

with self.assertRaisesRegex(ValueError, "not valid UTF-8"):
saver.save_batch(torch.tensor([2]), {"filename_or_obj": ["patient_07"]})

with open(filepath, "rb") as f:
self.assertEqual(f.read(), b"\xff" + valid_contents[1:])


if __name__ == "__main__":
unittest.main()
44 changes: 44 additions & 0 deletions tests/handlers/test_write_metrics_reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,50 @@ def test_multi_metric_details_headers(self):
header = f.readline().strip().split(",")
self.assertEqual(header, ["filename"] + [f"class{i}" for i in range(nclass)] + ["mean"])

def test_utf8_non_ascii_reports(self):
patient_names = ["\u60a3\u8005_01_\U0001f600.nii.gz", "\u60a3\u8005_02_\u75c5\u7076.nii.gz"]
class_labels = ["\u6b63\u5e38", "\u75c5\u7076\U0001f600"]
metric_name = "dice_\u75c5\u7076\U0001f600"
with tempfile.TemporaryDirectory() as tempdir:
save_dir = Path(tempdir) / "\u8bc4\u6d4b\u62a5\u544a"
write_metrics_reports(
save_dir=save_dir,
images=patient_names,
metrics={metric_name: torch.tensor(0.75)},
metric_details={"dice": torch.tensor([[0.5, 0.25], [0.75, 0.8]])},
summary_ops=["mean"],
class_labels=class_labels,
)

metrics_text = (save_dir / "metrics.csv").read_text(encoding="utf-8")
raw_text = (save_dir / "dice_raw.csv").read_text(encoding="utf-8")
summary_text = (save_dir / "dice_summary.csv").read_text(encoding="utf-8")

self.assertTrue(metrics_text.startswith(f"{metric_name},"))
self.assertIn(patient_names[0], raw_text)
self.assertIn(",".join(class_labels), raw_text)
self.assertIn(class_labels[0], summary_text)
self.assertIn(class_labels[1], summary_text)

def test_utf8_metric_name_in_output_filename(self):
metric_name = "dice_\u75c5\u7076"
patient_name = "\u60a3\u8005_03_\u75c5\u7076.nii.gz"
with tempfile.TemporaryDirectory() as tempdir:
save_dir = Path(tempdir)
write_metrics_reports(
save_dir=save_dir,
images=[patient_name],
metrics=None,
metric_details={metric_name: torch.tensor([[0.75]])},
summary_ops=None,
)

raw_path = save_dir / f"{metric_name}_raw.csv"
raw_text = raw_path.read_text(encoding="utf-8")

self.assertTrue(raw_path.name.startswith(metric_name))
self.assertIn(patient_name, raw_text)


if __name__ == "__main__":
unittest.main()