Coverage for collectra/display.py: 98.78%

82 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""Artefact display protocol, independent of the desktop GUI. 

2 

3``display(context)`` returns a JSON-compatible dict with ``kind`` set to 

4``image``, ``text``, or ``properties``. Image sources are PNG data URLs; image 

5annotations use viewer-relative normalized coordinates. Text formats are 

6``plain``, ``markdown``, or ``xml``. Custom classes may reuse these views. 

7""" 

8 

9import base64 

10import io 

11from pathlib import Path 

12 

13from collectra.utils import load_class_from_string 

14 

15 

16class DisplayContext: 

17 def __init__(self, records: dict, directory: Path, rgb_view: int = 0, max_pixels: int | None = None): 

18 from collectra.displays.preview import MAX_PREVIEW_EDGE 

19 

20 if max_pixels is None: 

21 max_pixels = MAX_PREVIEW_EDGE 

22 if type(max_pixels) is not int or max_pixels < 1: 

23 raise ValueError("max_pixels must be a positive integer") 

24 if type(rgb_view) is not int or rgb_view < 0: 

25 raise ValueError("RGB view index must be a non-negative integer") 

26 self.records = records 

27 self.directory = Path(directory).resolve() 

28 self.instances = {} 

29 self.rgb_view = rgb_view 

30 self.max_pixels = max_pixels 

31 

32 def path(self, value): 

33 path = Path(value) 

34 return path if path.is_absolute() else self.directory / path 

35 

36 def artefact(self, node_id): 

37 from collectra.types.images import Image, ImageSegmentation 

38 from collectra.types.links import Link 

39 from collectra.types.texts import Text 

40 

41 if node_id in self.instances: 

42 return self.instances[node_id] 

43 record = dict(self.records[node_id]) 

44 cls = load_class_from_string(record.pop("type")) 

45 record["name"] = record.pop("label", record.get("name", "")) 

46 if isinstance(record.get("parents"), str): 

47 record["parents"] = [record["parents"]] 

48 if issubclass(cls, Image): 

49 record["data"] = self.path(record.get("data", record.get("path", ""))) 

50 if issubclass(cls, ImageSegmentation): 

51 record["mask"] = self.path(record.get("mask", "")) 

52 elif issubclass(cls, Text): 

53 source = self.text_path(node_id) 

54 if source: 

55 if "path" not in record: 

56 record.pop("data", None) 

57 record["path"] = source 

58 accepted = set(cls.model_fields) - cls._runtime_fields 

59 item = cls(**{k: v for k, v in record.items() if k in accepted}) 

60 self.instances[node_id] = item 

61 if type(item) is Link: 

62 item.target = self.artefact(item.parent_id) 

63 return item 

64 

65 def text_path(self, node_id): 

66 record = self.records[node_id] 

67 value = record.get("path", record.get("data", "")) 

68 if not isinstance(value, (str, Path)) or not value: 

69 return None 

70 try: 

71 path = self.path(value) 

72 return path if path.is_file() else None 

73 except (OSError, ValueError): 

74 return None 

75 

76 def text(self, item): 

77 from collectra.displays.texts import text 

78 

79 return text(self, item) 

80 

81 @staticmethod 

82 def publish_image(image): 

83 buffer = io.BytesIO() 

84 image.save(buffer, format="PNG") 

85 return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode() 

86 

87 @staticmethod 

88 def renderer(module_path): 

89 """Publish a local JavaScript ES module supplied by an artefact package. 

90 

91 Return this URL as ``renderer`` in a display descriptor. The module 

92 exports a default render function; see docs/artefacts/display.rst. 

93 Use a path relative to the artefact's Python module, not results data. 

94 """ 

95 source = Path(module_path).read_bytes() 

96 return "data:text/javascript;base64," + base64.b64encode(source).decode() 

97 

98 def region(self, image, region, inverse=False): 

99 from collectra.displays.images import region as transform_region 

100 

101 return transform_region(self, image, region, inverse=inverse) 

102 

103 def annotations(self, image): 

104 from collectra.displays.images import annotations 

105 

106 return annotations(self, image) 

107 

108 def links(self, item): 

109 """The Link nodes whose parent is ``item``, as ``{"id", "name"}``.""" 

110 from collectra.displays.images import links 

111 

112 return links(self, item) 

113 

114 def image(self, item): 

115 from collectra.displays.images import image 

116 

117 return image(self, item)