diff --git a/src/imcflibs/imagej/misc.py b/src/imcflibs/imagej/misc.py index 20b02540..0c612a87 100644 --- a/src/imcflibs/imagej/misc.py +++ b/src/imcflibs/imagej/misc.py @@ -10,15 +10,13 @@ from ij import IJ # pylint: disable-msg=import-error from ij.plugin import Duplicator, ImageCalculator, StackWriter +from org.scijava.widget import TextWidget, WidgetStyle from .. import pathtools from ..log import LOG as log from . import bioformats as bf from . import prefs -from org.scijava.widget import WidgetStyle -from org.scijava.widget import TextWidget - def show_status(msg): """Update the ImageJ status bar and issue a log message. @@ -533,7 +531,9 @@ def write_ordereddict_to_csv(out_file, content): dict_writer.writerows(content) -def save_image_in_format(imp, format, out_dir, series, pad_number, split_channels, suffix=""): +def save_image_in_format( + imp, format, out_dir, series, pad_number, split_channels, suffix="" +): """Save an ImagePlus object in the specified format. This function provides flexible options for saving ImageJ images in various @@ -790,3 +790,33 @@ def save_script_parameters(destination, save_file_name="script_parameters.txt"): f.write("%s: %s\n" % (key, str(val))) timed_log("Saved script parameters to: %s" % out_path) + + +def bytes_to_human_readable(size): + """Convert a byte count to a human-readable string using binary units. + + Parameters + ---------- + size : int + Byte size (number of bytes). + + Returns + ------- + str + Human-friendly size string, e.g. `"512.0 bytes"`, `"2.0 KB"`, + `"1.0 MB"`. + + Notes + ----- + - Uses powers of 1024 (KB = 1024 bytes). + - Always returns a string with one decimal place and the unit. + """ + + for unit in ["bytes", "KB", "MB", "GB", "TB"]: + if size < 1024.0: + return "%3.1f %s" % (size, unit) + size /= 1024.0 + + # If the value is larger than the largest unit, fall back to TB with + # the current value (already divided accordingly). + return "%3.1f %s" % (size, "TB") diff --git a/tests/test_misc.py b/tests/test_misc.py new file mode 100644 index 00000000..cabe80e6 --- /dev/null +++ b/tests/test_misc.py @@ -0,0 +1,18 @@ +"""Tests for `imcflibs.imagej.misc` utility functions.""" + +from imcflibs.imagej.misc import bytes_to_human_readable + + +def test_bytes_to_human_readable_simple(): + """Ensure common sizes are formatted into human-readable strings.""" + assert bytes_to_human_readable(500) == "500.0 bytes" + assert bytes_to_human_readable(2048) == "2.0 KB" + assert bytes_to_human_readable(1024 * 1024) == "1.0 MB" + assert bytes_to_human_readable(5 * 1024**3) == "5.0 GB" + + +def test_bytes_to_human_readable_large(): + """Verify formatting for large sizes such as terabytes.""" + # 1.5 TB in bytes should format as 1.5 TB + size = int(1.5 * (1024**4)) + assert bytes_to_human_readable(size) == "1.5 TB"