diff --git a/src/humanize/__init__.py b/src/humanize/__init__.py index 4f54bc46..acc4134c 100644 --- a/src/humanize/__init__.py +++ b/src/humanize/__init__.py @@ -56,3 +56,8 @@ "scientific", "thousands_separator", ] + +# Custom extension (Arda-06 fork): reading-time estimate +from humanize.reading import reading_time + +__all__ = [*__all__, "reading_time"] diff --git a/src/humanize/reading.py b/src/humanize/reading.py new file mode 100644 index 00000000..5a96ba78 --- /dev/null +++ b/src/humanize/reading.py @@ -0,0 +1,54 @@ +"""Reading-time humanization (custom extension, Arda-06 fork).""" + +from __future__ import annotations + +import datetime as dt +import math +import re + +from .time import naturaldelta + +__all__ = ["reading_time"] + +_WORD_RE = re.compile(r"\b\w+\b", re.UNICODE) + + +def reading_time(text: str, wpm: int = 200, *, minimum_seconds: int = 1) -> str: + """Return a human-readable estimate of how long *text* takes to read. + + Examples: + ```pycon + >>> reading_time("word " * 400) + '2 minutes' + >>> reading_time("Hello world") + 'a second' + >>> reading_time("") + 'a moment' + + ``` + + Args: + text: The text to estimate. Words are counted with a Unicode-aware regex. + wpm: Reading speed in words per minute. Must be a positive integer. + minimum_seconds: Non-empty text never reports less than this. + + Returns: + A string like ``"3 minutes"`` produced by ``humanize.naturaldelta``. + + Raises: + TypeError: If *text* is not a string. + ValueError: If *wpm* is not positive. + """ + if not isinstance(text, str): + msg = f"text must be str, not {type(text).__name__}" + raise TypeError(msg) + if wpm <= 0: + msg = "wpm must be a positive integer" + raise ValueError(msg) + + words = len(_WORD_RE.findall(text)) + if words == 0: + return naturaldelta(dt.timedelta(0)) + + seconds = max(minimum_seconds, math.ceil(words * 60 / wpm)) + return naturaldelta(dt.timedelta(seconds=seconds)) diff --git a/tests/test_reading.py b/tests/test_reading.py new file mode 100644 index 00000000..29b43348 --- /dev/null +++ b/tests/test_reading.py @@ -0,0 +1,32 @@ +"""Tests for the custom reading_time() extension.""" + +from __future__ import annotations + +import pytest + +import humanize + + +@pytest.mark.parametrize( + "text, wpm, expected", + [ + ("", 200, "a moment"), + ("Hello world", 200, "a second"), + ("word " * 200, 200, "a minute"), + ("word " * 400, 200, "2 minutes"), + ("word " * 300, 100, "3 minutes"), + ("Merhaba dünya, nasılsın?", 200, "a second"), + ], +) +def test_reading_time(text: str, wpm: int, expected: str) -> None: + assert humanize.reading_time(text, wpm=wpm) == expected + + +def test_reading_time_invalid_wpm() -> None: + with pytest.raises(ValueError): + humanize.reading_time("text", wpm=0) + + +def test_reading_time_invalid_type() -> None: + with pytest.raises(TypeError): + humanize.reading_time(123) # type: ignore[arg-type]