diff --git a/src/humanize/__init__.py b/src/humanize/__init__.py index 6fb9959..ab3aaef 100644 --- a/src/humanize/__init__.py +++ b/src/humanize/__init__.py @@ -2,6 +2,7 @@ from __future__ import annotations +from humanize.bitrate import natural_bitrate from humanize.filesize import naturalsize from humanize.i18n import activate, deactivate, decimal_separator, thousands_separator from humanize.lists import natural_list @@ -36,6 +37,7 @@ "intcomma", "intword", "metric", + "natural_bitrate", "natural_list", "naturaldate", "naturalday", diff --git a/src/humanize/bitrate.py b/src/humanize/bitrate.py new file mode 100644 index 0000000..63ebed8 --- /dev/null +++ b/src/humanize/bitrate.py @@ -0,0 +1,23 @@ +from __future__ import annotations + + +def natural_bitrate(value: float) -> str: + """Format a bitrate value (bps) into a human-readable string using SI units (1000-based). + + Args: + value: Bitrate in bits per second (bps). + + Returns: + Human-readable bitrate string (e.g., "1 kbps", "5.2 Mbps", "10 Gbps"). + """ + units = ["bps", "kbps", "Mbps", "Gbps", "Tbps"] + unit_index = 0 + + while value >= 1000 and unit_index < len(units) - 1: + value /= 1000 + unit_index += 1 + + if unit_index == 0: + return f"{value:.0f} {units[unit_index]}" + else: + return f"{value:.1f} {units[unit_index]}"