Coverage for collectra/types/texts.py: 84.88%

86 statements  

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

1import re 

2from difflib import SequenceMatcher 

3from io import StringIO 

4from pathlib import Path 

5from typing import Any 

6 

7from markdown import Markdown as MDown 

8from pydantic import PrivateAttr, field_validator 

9 

10from .base import Artefact 

11 

12__all__ = ["Text"] 

13 

14 

15def unmark_element(element, stream=None): 

16 if stream is None: 

17 stream = StringIO() 

18 if element.text: 

19 stream.write(element.text) 

20 for sub in element: 

21 unmark_element(sub, stream) 

22 if element.tail: 

23 stream.write(element.tail) 

24 return stream.getvalue() 

25 

26 

27# patching Markdown 

28MDown.output_formats["plain"] = unmark_element 

29__md = MDown(output_format="plain") 

30__md.stripTopLevelTags = False 

31 

32 

33def unmark(text): 

34 return __md.convert(text) 

35 

36 

37class Text(Artefact): 

38 

39 data: str | Path | None = None 

40 path: str | Path | None = None 

41 

42 # Set by a task that was asked to save its output; consumed by ``finalise``. 

43 _file_extension: str | None = PrivateAttr(default=None) 

44 

45 @field_validator("data", mode="before") 

46 @classmethod 

47 def _numbers_are_text(cls, value): 

48 # YAML reads ``book: 1`` as a number, but a Text always holds text. 

49 if isinstance(value, (bool, int, float)): 

50 return str(value) 

51 return value 

52 

53 def model_post_init(self, __context: Any) -> None: 

54 super().model_post_init(__context) 

55 if self.path is not None and self.data is not None: 

56 raise ValueError("Text accepts either data or path, not both") 

57 # Continue accepting legacy file references in data. 

58 if self.path is None and self.data: 

59 try: 

60 if Path(self.data).is_file(): 

61 self.path, self.data = Path(self.data), None 

62 except (OSError, ValueError): 

63 pass 

64 if self.path is not None: 

65 self.path = Path(self.path) 

66 self.data = self.path.read_text(encoding="utf-8") 

67 elif self.data is None: 

68 self.data = "" 

69 

70 @staticmethod 

71 def file_extensions() -> set[str]: 

72 return { 

73 ".txt", 

74 ".md", 

75 ".markdown", 

76 ".xml", 

77 ".html", 

78 ".htm", 

79 ".json", 

80 ".yaml", 

81 ".yml", 

82 ".csv", 

83 ".tsv", 

84 ".rst", 

85 ".tex", 

86 } 

87 

88 @staticmethod 

89 def _file_safe(name: str) -> str: 

90 """Keep a name inside its folder: no separators or leading dots.""" 

91 return re.sub(r"[^\w.\-]", "_", name).lstrip(".") 

92 

93 def stored_files(self, folder: Path) -> list[Path]: 

94 return [Path(folder) / self.path] if self.path is not None else [] 

95 

96 @classmethod 

97 def output_directory(cls, node: str) -> str: 

98 """Name of the results subfolder that holds a node's saved text files.""" 

99 return cls._file_safe(node) or "text" 

100 

101 def finalise(self, folder: Path, node: str) -> None: 

102 """Write the text to ``{node}/{id}.{extension}`` and refer to that file. 

103 

104 Only texts that a task marked for saving are written, and only once. 

105 Empty text stays inline: an empty file would say nothing. 

106 The content stays available in memory for later tasks. 

107 """ 

108 extension, self._file_extension = self._file_extension, None 

109 if not extension or self.path is not None or not str(self.data): 

110 return 

111 directory = self.output_directory(node) 

112 relative = f"{directory}/{self._file_safe(self.id) or directory}.{extension}" 

113 target = Path(folder) / relative 

114 target.parent.mkdir(parents=True, exist_ok=True) 

115 target.write_text(str(self.data), encoding="utf-8") 

116 self.path = relative 

117 

118 def serialize(self) -> dict: 

119 serialized = super().serialize() 

120 if self.path is not None: 

121 serialized.pop("data", None) 

122 serialized["path"] = str(self.path) 

123 else: 

124 serialized.pop("path", None) 

125 return serialized 

126 

127 def __call__(self) -> str: 

128 return str(self.data) 

129 

130 def display(self, context) -> dict: 

131 return context.text(self) 

132 

133 def evaluate(self, gold: "Text") -> float: 

134 if not isinstance(gold, Text): 

135 raise ValueError("Reference data must be an instance of Text.") 

136 ratio = SequenceMatcher(None, str(self.data), str(gold.data)).ratio() 

137 return ratio