Coverage for app / documents / visuals / fence.py: 86%

37 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""Reading a visual fence: its JSON, and the numbers inside it.""" 

2 

3from __future__ import annotations 

4 

5import math 

6from typing import Any 

7 

8from app.util import safe_json 

9 

10 

11class VisualError(ValueError): 

12 """A fence that cannot be drawn; its message says why, in words a reader 

13 of the PDF can take ("it has no data").""" 

14 

15 

16def read_object(source: str) -> dict[str, Any]: 

17 """A fence's JSON object, read whole: a fence is the whole of what its 

18 tool wrote, never a span from inside it.""" 

19 try: 

20 value = safe_json.loads_exact(source) 

21 except ValueError as exc: 

22 raise VisualError("its JSON could not be read") from exc 

23 if not isinstance(value, dict): 

24 raise VisualError("its JSON is not an object") 

25 return value 

26 

27 

28def number(value: Any) -> float | None: 

29 """A finite number, as a chart reads a value: numbers and numeric 

30 strings; a boolean, ``NaN`` or anything else is no value.""" 

31 if isinstance(value, bool): 

32 return None 

33 if isinstance(value, (int, float)): 

34 out = float(value) 

35 elif isinstance(value, str): 

36 try: 

37 out = float(value.strip().replace(",", "")) 

38 except ValueError: 

39 return None 

40 else: 

41 return None 

42 return out if math.isfinite(out) else None 

43 

44 

45def text(value: Any) -> str: 

46 """A label as a chart shows it: a string as written, a number as JS 

47 would print it, anything else empty.""" 

48 if isinstance(value, bool): 

49 return "true" if value else "false" 

50 if isinstance(value, int): 

51 return str(value) 

52 if isinstance(value, float): 

53 if not math.isfinite(value): 

54 return "" 

55 return str(int(value)) if value.is_integer() else repr(value) 

56 if isinstance(value, str): 

57 return " ".join(value.split()) 

58 return ""