Debian Codegraph @

gavo/votable/votparse.py

raw
1 """
2 Stream parsing of VOTables.
3
4 This module builds on a shallow wrapping of expat in utils.iterparse.
5 There is an "almost-tight" parsing loop in the parse method. It
6 builds an xmlstan tree (mainly through the _processNodeDefault method).
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 # To fiddle with the nodes as they are generated, define an
16 # _end_ELEMENTNAME method. If you do this, you will have to do
17 # any adding of children to parents yourself (it happens in
18 # _processNodeDefault, which is called when no custom handler is
19 # present.
20
21 import io
22
23 from gavo import utils
24 from gavo.utils import ElementTree
25 from gavo.utils import stanxml
26 from gavo.votable import common
27 from gavo.votable import model
28 from gavo.votable import tableparser
29 from gavo.votable.model import VOTable as V
30
31 from gavo.utils.dachstypes import (cast,
32 Any, BinaryIO, BytesReadable, Callable, Dict, Iterator,
33 List, Optional, Set, Type)
34
35
36 DEFAULT_WATCHSET: Set[Type[V._VOTElement]] = set()
37
38 # We treat all VOTable versions as equal.
39 VOTABLE_NAMESPACES = [
40 "http://www.ivoa.net/xml/VOTable/v1.0",
41 "http://www.ivoa.net/xml/VOTable/v1.1",
42 "http://www.ivoa.net/xml/VOTable/v1.2",
43 "http://www.ivoa.net/xml/VOTable/v1.3",
44 ]
45
46
47 class IGNORE(V._VOTElement):
48 """a sentinel element used when an element is not known
49 but robust parsing is requested.
50
51 These should not end up in a DOM, but if they do, they're silent.
52
53 They're designed to largely behave like stanxml Elements; it can't
54 autoconstruct, though.
55 """
56 name_ = "(Unknown and ignored element)"
57
58 def __init__(self) -> None:
59 pass
60
61 def __call__(self, **kwargs: Any) -> "IGNORE":
62 return self
63
64 def __getitem__(self, item: V._VOTElement) -> "IGNORE":
65 return self
66
67 def isEmpty(self):
68 return True
69
70 def shouldBeSkipped(self):
71 return True
72
73 def apply(self, func):
74 return
75
76
77 def _processNodeDefault(
78 text: Optional[str],
79 child: stanxml.SomeElement,
80 parent: V._VOTElement) -> stanxml.SomeElement:
81 """the default node processor: Append child to parent, return child.
82 """
83 assert not (text and text.strip()), (
84 "Content '%s' in must-empty VOTable element %s"%(text, repr(child)))
85 parent[child]
86 return child
87
88
89 def _processNodeWithContent(
90 text: Optional[str],
91 child: stanxml.SomeElement,
92 parent: V._VOTElement) -> stanxml.SomeElement:
93 """the node processor for nodes with text content.
94 """
95 if text and text.strip():
96 child[text] # Attention: mixed content not supported
97 parent[child]
98 return child
99
100
101 _end_DESCRIPTION = _processNodeWithContent
102 _end_INFO = _processNodeWithContent
103 _end_MODEL = _processNodeWithContent
104 _end_URL = _processNodeWithContent
105 _end_LITERAL = _processNodeWithContent
106 _end_NAME = _processNodeWithContent
107 # STREAMs and TABLEDATA should ordinarily be processed by the table
108 # iterator, so this really is only interesting for special applications:
109 _end_STREAM = _processNodeWithContent
110 _end_TD = _processNodeWithContent
111 _end_IDREF = _processNodeWithContent
112 _end_LITERAL = _processNodeWithContent
113
114
115 def _end_VOTABLE(
116 text: Optional[str],
117 child: V.VOTABLE,
118 parent: Optional[V._VOTElement]) -> V.VOTABLE:
119 # VOTABLEs have no useful parents.
120 return child
121
122
123 def _computeEndProcessorsImpl() -> Dict[str, Callable]:
124 """returns a dictionary of tag names to end processors.
125
126 Each processor as defined using _end_XXXX has an entry each for
127 each namespace we're likely to encounter, and one non-namespaced.
128 """
129 res, globs = {}, globals()
130 for n, v in globs.items():
131 if n.startswith("_end_"):
132 elName = n[5:]
133 res[elName] = v
134 for ns in VOTABLE_NAMESPACES:
135 res["%s:%s"%(ns, elName)] = v
136 return res
137
138 computeEndProcessors = utils.CachedGetter(_computeEndProcessorsImpl)
139
140
141 def _computeElementsImpl():
142 """returns a dictionary of tag names to xmlstan elements building them.
143
144 All elements are present for each VOTABLE_NAMESPACE, plus once non-namespaced.
145 """
146 res = {}
147 for n in dir(model.VOTable):
148 if not n.startswith("_"):
149 val = getattr(model.VOTable, n)
150 res[n] = val
151 for ns in VOTABLE_NAMESPACES:
152 res[ElementTree.QName(ns, n)] = val
153 return res
154
155 computeElements = utils.CachedGetter(_computeElementsImpl)
156
157
158 def _cleanAttributes(
159 attrDict: Dict[str, str],
160 element: V._VOTElement,
161 raiseOnInvalid: bool) -> Dict[str, str]:
162 """returns a sanitised version of attDict for element.
163
164 We force attribute keys to be strings (since they're being used
165 as keyword arguments), and we drop everything that's namespace related
166 -- it's not necessary for VOTables and people mess it up anyway.
167
168 Also, we complain about or filter out attributes that element
169 cannot deal with.
170 """
171 cleaned = {}
172 for key, value in attrDict.items():
173 if ":" in key or key=="xmlns":
174 continue
175 key = str(key.replace("-", "_"))
176 if not hasattr(element, "_a_"+key):
177 if raiseOnInvalid:
178 raise KeyError(key)
179 else:
180 continue
181 cleaned[key] = value
182 return cleaned
183
184
185 def parse(
186 inFile: BytesReadable,
187 watchset: Set[Type[V._VOTElement]] = DEFAULT_WATCHSET,
188 raiseOnInvalid: bool = True
189 ) -> Iterator[V._VOTElement | tableparser.Rows]:
190 """returns an iterator yielding items of interest.
191
192 inFile is a something that supports read(bytes)
193
194 watchset is a set of items of VOTable you want yielded. By
195 default, that's just VOTable.TABLE. You may want to see INFO
196 or PARAM with certain protocols.
197
198 DATA elements are always returned, although as instances
199 of Rows rather than a raw VOTable element; that is unmaskable.
200 """
201 # This parser has gotten a bit too fat. Maybe move the whole thing
202 # to a class? All this isn't terribly critical to performance...
203 idmap: Dict[str, Any] = {}
204 processors = computeEndProcessors()
205 elements = computeElements()
206 elementStack: List[Optional[V._VOTElement]
207 ] = [None] # None is VOTABLE's parent
208 iterator = utils.iterparse(
209 cast(BinaryIO, inFile), common.VOTableParseError)
210 content: List[str] = []
211
212 for type, tag, payload in iterator:
213 if type=="data":
214 content.append(cast(str, payload))
215
216 elif type=="start":
217 # Element open: push new node on the stack...
218 if tag not in elements:
219 if raiseOnInvalid:
220 raise iterator.getParseError("Unknown tag: %s"%tag)
221 else:
222 element = IGNORE()
223 else:
224 element = elements[tag]()
225
226 if isinstance(payload, dict):
227 try:
228 elAttrs = _cleanAttributes(payload, element, raiseOnInvalid)
229 except KeyError as msg:
230 raise iterator.getParseError("Attribute %s invalid on %s"%(
231 str(msg), element.name_))
232 elementStack.append(element(**elAttrs))
233
234 # ...prepare for new content,...
235 content = []
236
237 # ...add the node to the id map if it has an ID...
238 if isinstance(payload, dict):
239 elId = payload.get("ID")
240 if elId is not None:
241 idmap[elId] = elementStack[-1]
242
243 # ...and pass control to special iterator if DATA is coming in.
244 if tag=="DATA":
245 yield tableparser.Rows(cast(V.TABLE, elementStack[-2]), iterator)
246
247 elif type=="end":
248 # Element close: process text content...
249 if content:
250 text = "".join(content)
251 content = []
252 else:
253 text = None
254
255 # ...see if we have any special procssing to do for the node type...
256 nodeProc = processors.get(tag, _processNodeDefault)
257 preChild = elementStack.pop()
258 if not isinstance(preChild, IGNORE):
259 # ...call handler with the current node and its future parent...
260 child = nodeProc(text, preChild, elementStack[-1])
261
262 # ...and let user do something with the element if she ordered it.
263 if child is not None and child.__class__ in watchset:
264 child.idmap = idmap
265 yield child
266
267 else:
268 assert False
269
270
271 def readRaw(inFile: BytesReadable) -> V.VOTABLE:
272 """returns a V.VOTABLE instance with filled-in data for the input from
273 inFile.
274 """
275 for el in parse(inFile, {V.TABLE, V.VOTABLE}):
276 if isinstance(el, tableparser.Rows):
277 el.tableDefinition.rows = list(el) # type: ignore # dynamic attribute
278 return cast(V.VOTABLE, el)
279
280
281 def parseBytes(
282 string: bytes,
283 watchset: Set[Type[V._VOTElement]] = DEFAULT_WATCHSET,
284 raiseOnInvalid: bool = True) -> Iterator[V._VOTElement | tableparser.Rows]:
285 """returns an iterator yielding pairs of (table definition, row iterator).
286
287 string contains a VOTable literal as bytes (where we fall back to utf-8
288 encoding strings if necessary).
289 """
290 return parse(io.BytesIO(utils.bytify(string)), watchset, raiseOnInvalid)