Coverage for src/retrospeedlab/docs_site/labels.py: 100%

61 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-12-03 23:09 +0000

1import math 

2from datetime import datetime 

3from decimal import ROUND_HALF_UP, Decimal 

4 

5NOT_YET = "—" 

6BYTE_UNITS = ("B", "KB", "MB", "GB", "TB") 

7BYTES_PER_UNIT = 1024 

8COMPACT_UNITS = ("", "K", "M", "B", "T") 

9COMPACT_STEP = 1000 

10COMPACT_DIGITS = 3 

11SECONDS_PER_MINUTE = 60 

12MINUTES_PER_HOUR = 60 

13HOURS_PER_DAY = 24 

14PERCENT = 100 

15 

16 

17def fixed(value: float, digits: int) -> str: 

18 return str(Decimal(value).quantize(Decimal(1).scaleb(-digits), rounding=ROUND_HALF_UP)) 

19 

20 

21def rounded(value: float) -> int: 

22 return math.floor(value + 0.5) 

23 

24 

25def count_label(count: int) -> str: 

26 return f"{count:,}" 

27 

28 

29def counted(count: int, noun: str) -> str: 

30 return f"{count} {noun if count == 1 else f'{noun}s'}" 

31 

32 

33def bytes_label(size: int) -> str: 

34 unit = min(len(BYTE_UNITS) - 1, int(math.log(max(size, 1)) / math.log(BYTES_PER_UNIT))) 

35 if unit == 0: 

36 return f"{size} {BYTE_UNITS[0]}" 

37 return f"{fixed(size / BYTES_PER_UNIT**unit, 1)} {BYTE_UNITS[unit]}" 

38 

39 

40def duration_label(seconds: float) -> str: 

41 if seconds < SECONDS_PER_MINUTE: 

42 return f"{fixed(seconds, 1)} s" 

43 minutes = rounded(seconds / SECONDS_PER_MINUTE) 

44 if minutes < MINUTES_PER_HOUR: 

45 return f"{minutes} min" 

46 return f"{minutes // MINUTES_PER_HOUR} h {minutes % MINUTES_PER_HOUR} min" 

47 

48 

49def age_label(at: datetime, now: datetime) -> str: 

50 minutes = max(0, rounded((now - at).total_seconds() / SECONDS_PER_MINUTE)) 

51 if minutes < 1: 

52 return "just now" 

53 if minutes < MINUTES_PER_HOUR: 

54 return f"{minutes} min ago" 

55 hours = rounded(minutes / MINUTES_PER_HOUR) 

56 if hours < HOURS_PER_DAY: 

57 return f"{hours} h ago" 

58 return f"{rounded(hours / HOURS_PER_DAY)} d ago" 

59 

60 

61def compact_label(value: float) -> str: 

62 unit = min(len(COMPACT_UNITS) - 1, int(math.log10(max(abs(value), 1)) // COMPACT_DIGITS)) 

63 shown = Decimal(fixed(value / COMPACT_STEP**unit, 1)) 

64 if abs(shown) >= COMPACT_STEP and unit < len(COMPACT_UNITS) - 1: 

65 unit += 1 

66 shown = Decimal(fixed(value / COMPACT_STEP**unit, 1)) 

67 return f"{shown.normalize():f}{COMPACT_UNITS[unit]}" 

68 

69 

70def share_label(share: float) -> str: 

71 return f"{fixed(share * PERCENT, 1)}%" 

72 

73 

74def dollars(value: float) -> str: 

75 return f"${fixed(value, 2)}" 

76 

77 

78def tenths(value: float) -> str: 

79 return fixed(value, 1) 

80 

81 

82def sentence_case(name: str) -> str: 

83 spaced = name.replace("_", " ") 

84 return spaced[:1].upper() + spaced[1:] 

85 

86 

87def game_title(titles: dict[str, str], slug: str) -> str: 

88 # a lab run can outlive its game, so its slug still names it 

89 return titles[slug] if slug in titles else slug