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
5 changes: 5 additions & 0 deletions src/humanize/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
54 changes: 54 additions & 0 deletions src/humanize/reading.py
Original file line number Diff line number Diff line change
@@ -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))
32 changes: 32 additions & 0 deletions tests/test_reading.py
Original file line number Diff line number Diff line change
@@ -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]