Coverage for rdgai/tei.py: 100.00%

115 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-24 23:53 +0000

1import re 

2from pathlib import Path 

3from lxml import etree as ET 

4from lxml.etree import _ElementTree as ElementTree 

5from lxml.etree import _Element as Element 

6 

7from .languages import convert_language_code 

8 

9 

10def get_language_code(doc:ElementTree|Element) -> str: 

11 """ Reads the element <text> and returns the value of the xml:lang attribute.""" 

12 text = find_element(doc, ".//text") 

13 if text is None: 

14 return "" 

15 

16 return text.attrib.get("{http://www.w3.org/XML/1998/namespace}lang", "") 

17 

18 

19def get_language(doc:ElementTree|Element) -> str: 

20 code = get_language_code(doc) 

21 return convert_language_code(code) 

22 

23 

24def make_nc_name(string): 

25 invalid_chars = "!\"#$%&'()*+/:;<=>?@[\\]^,{|}~` " 

26 result = string.translate(str.maketrans(invalid_chars, '_' * len(invalid_chars))) 

27 # if result[0].isdigit or result[0] in [".", "-"]: 

28 # result = "id-" + result 

29 

30 return result 

31 

32 

33def extract_text(node:Element, include_tail:bool=True, sep:str=" ") -> str: 

34 if node is None: 

35 return "" 

36 

37 if isinstance(node.tag, str): 

38 tag = re.sub(r"{.*}", "", node.tag) 

39 else: 

40 return "" 

41 

42 if tag in ["pc", "witDetail", "note"]: 

43 return "" 

44 if tag == "app": 

45 lemma = find_element(node, ".//lem") 

46 if lemma is None: 

47 lemma = find_element(node, ".//rdg") 

48 return extract_text(lemma) or "" 

49 if tag == "ref": 

50 root = node.getroottree().getroot() 

51 target_id = node.attrib['target'].lstrip("#") 

52 ns = {"tei": "http://www.tei-c.org/ns/1.0"} 

53 target = root.xpath(f"//*[@xml:id='{target_id}']", namespaces=ns) 

54 

55 if target: 

56 return extract_text(target[0]) 

57 

58 if tag == "w": 

59 sep = "" 

60 

61 text = node.text or "" 

62 for child in node: 

63 text += sep + extract_text(child, sep=sep) 

64 

65 if include_tail and node.tail: 

66 text += sep + node.tail 

67 

68 return text.strip() 

69 

70 

71def read_tei(path:Path) -> ElementTree: 

72 parser = ET.XMLParser(remove_blank_text=True) 

73 with open(path, 'r') as f: 

74 return ET.parse(f, parser) 

75 

76 

77def parse_tei(data:bytes) -> ElementTree: 

78 """ Parses a TEI document already read from a file (as read_tei does from the path). """ 

79 return ET.ElementTree(ET.fromstring(data, ET.XMLParser(remove_blank_text=True))) 

80 

81 

82def find_element(doc:ElementTree|Element, xpath:str) -> Element|None: 

83 assert doc is not None, f"Document is None in find_element({doc}, {xpath})" 

84 if isinstance(doc, ElementTree): 

85 doc = doc.getroot() 

86 namespaces = doc.nsmap | {"xml": "http://www.w3.org/XML/1998/namespace"} 

87 element = doc.find(xpath, namespaces=namespaces) 

88 if element is None: 

89 try: 

90 element = doc.find(xpath) 

91 except SyntaxError: 

92 return None 

93 return element 

94 

95 

96def find_elements(doc:ElementTree|Element|None, xpath:str) -> list[Element]: 

97 if doc is None: 

98 return [] 

99 if isinstance(doc, ElementTree): 

100 doc = doc.getroot() 

101 namespaces = doc.nsmap | {"xml": "http://www.w3.org/XML/1998/namespace"} 

102 results = doc.findall(xpath, namespaces=namespaces) 

103 results += doc.findall(xpath) 

104 return results 

105 

106 

107def find_parent(element:Element, tag:str) -> Element|None: 

108 """ 

109 Finds the nearest ancestor of the given element with the specified tag. 

110 

111 Args: 

112 element (Element): The starting XML element from which to search upward. 

113 tag (str): The tag name of the ancestor element to find. 

114 

115 Returns: 

116 Optional[Element]: The nearest ancestor element with the specified tag, or None if no such element is found. 

117 

118 Example: 

119 >>> from xml.etree.ElementTree import Element 

120 >>> root = Element('root') 

121 >>> ab = Element('ab') 

122 >>> section = Element('section') 

123 >>> target = Element('target') 

124 >>> root.append(ab) 

125 >>> ab.append(section) 

126 >>> section.append(target) 

127 >>> result = find_parent(target, 'ab') 

128 >>> assert result == ab 

129 

130 This will find the <ab> ancestor of the <target> element. 

131 """ 

132 while element is not None: 

133 element_tag = re.sub(r"{.*}", "", element.tag) 

134 if element_tag == tag: 

135 return element 

136 element = element.getparent() 

137 return None 

138 

139 

140def write_tei(doc:ElementTree, path:Path|str) -> None: 

141 Path(path).parent.mkdir(parents=True, exist_ok=True) 

142 doc.write(str(path), encoding="utf-8", xml_declaration=True, pretty_print=True) 

143 

144 

145def get_reading_identifier(reading:Element, check:bool=False, create_if_necessary:bool=True) -> str: 

146 identifier = reading.attrib.get("{http://www.w3.org/XML/1998/namespace}id", "") 

147 if not identifier: 

148 identifier = reading.attrib.get("n", "") 

149 

150 if not identifier and create_if_necessary: 

151 app = reading.getparent() 

152 identifier = 1 

153 while find_element(app, f".//rdg[@n='{identifier}']") is not None: 

154 identifier += 1 

155 identifier = str(identifier) 

156 reading.attrib["n"] = identifier 

157 

158 if check: 

159 assert identifier, f"Reading {reading} must have a name attribute 'xml:id' or 'n'." 

160 

161 return identifier 

162 

163 

164def extract_text_siblings(element:Element, until_tag:str, preceding:bool=False, truncate:int|None=None) -> str: 

165 """ 

166 Extracts text from sibling elements of the given element until a sibling with the specified tag is encountered. 

167  

168 Args: 

169 element (Element): The starting XML element from which to extract text from its siblings. 

170 until_tag (str): The tag name of the sibling element that will stop the extraction process. 

171 preceding (bool): If True, extracts text from preceding siblings; if False, extracts from following siblings. 

172 truncate (int|None): If specified, limits the number of words extracted to this value. 

173  

174 Returns: 

175 str: A string containing the concatenated text from the sibling elements, up to the specified limit if provided. 

176 """ 

177 words = [] 

178 for sibling in element.itersiblings(preceding=preceding): 

179 tag = sibling.tag 

180 if isinstance(tag, str) and tag.rsplit("}", 1)[-1] == until_tag: 

181 break 

182 

183 text = extract_text(sibling) 

184 if text: 

185 my_words = text.split() 

186 if preceding: 

187 # Reverse the order of words for preceding context because we are iterating backwards through the siblings. 

188 my_words.reverse() 

189 

190 words.extend(my_words) 

191 if truncate and len(words) >= truncate: 

192 words = words[:truncate] 

193 break 

194 

195 if preceding: 

196 words.reverse() 

197 

198 return " ".join(words)