Debian Codegraph @

gavo/votable/coding.py

raw
1 """
2 Common code for coding and decoding VOTable data.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import re
12
13 from gavo import utils
14 from gavo.votable import common
15 from gavo.votable.model import VOTable
16 from functools import reduce
17
18
19 from gavo.utils.dachstypes import (cast, TYPE_CHECKING,
20 Any, Callable, Dict, List, Optional, ModuleType, Sequence, Tuple, Union)
21
22 SequenceForArray = Union[List[Optional[int]], List[Optional[float]]]
23
24 if TYPE_CHECKING:
25 from gavo.votable.tableparser import _StreamData
26
27
28 def getRowEncoderSource(
29 tableDefinition: VOTable.TABLE,
30 encoderModule: ModuleType) -> str:
31 """returns the source for a function encoding rows of tableDefition
32 in the format implied encoderModule
33
34 tableDefinition is a VOTable.TABLE instance, encoderModule
35 is one of the enc_whatever modules (this function needs getLinesFor
36 and getPostamble from them).
37 """
38
39 source = [
40 "def codec(tableRow):",
41 " tokens = []",
42 " val = None"]
43
44 source.extend(
45 common.indentList(
46 cast(List[str], getattr(encoderModule, "getPreamble", lambda td: [])(
47 tableDefinition)), " "))
48
49 for index, field in enumerate(
50 tableDefinition.iterChildrenOfType(VOTable.FIELD)):
51 source.extend([
52 " try:",
53 " val = tableRow[%d]"%index])
54 source.extend(common.indentList(encoderModule.getLinesFor(field), " "))
55 source.extend([
56 " except common.VOTableError:",
57 " raise",
58 " except Exception as ex:",
59 # " import traceback; traceback.print_exc()",
60 " raise common.BadVOTableData(str(ex), repr(val), '%s')"%
61 field.getDesignation()])
62 source.extend(common.indentList(
63 encoderModule.getPostamble(tableDefinition), " "))
64 return "\n".join(source)
65
66
67 def buildCodec(source: str, env: Dict[str, Any]
68 ) -> Callable:
69 """returns a compiled function for source in env.
70
71 Source is the result of one of the makeXXX functions in this module,
72 env typically the result of a getGlobals() on the codec module.
73 """
74 ns = {}
75 ns.update(env)
76
77 # with open("codec.py", "wb") as f: f.write(source.encode("utf-8"))
78 return utils.compileFunction(source, "codec", useGlobals=ns)
79
80
81 def buildEncoder(tableDefinition: VOTable.TABLE, encoderModule: ModuleType
82 ) -> Callable[[Dict[str, Any]], bytes]:
83 return buildCodec(
84 getRowEncoderSource(tableDefinition, encoderModule),
85 encoderModule.getGlobals(tableDefinition))
86
87
88 def buildDecoder(tableDefinition: VOTable.TABLE, decoderModule: ModuleType
89 ) -> Callable[["_StreamData" | List[str]], Dict[str, Any]]:
90 return buildCodec(
91 decoderModule.getRowDecoderSource(tableDefinition),
92 decoderModule.getGlobals(tableDefinition))
93
94
95 def getNullvalue(
96 field: VOTable.TypedElement,
97 validator: Callable[[Any], Any],
98 default: Optional[str] = None) -> Optional[str]:
99 """returns None or the nullvalue defined for field.
100
101 validator is a function that raises some exception if the nullvalue
102 is inappropriate. It should do so in particular on everything that
103 contains quotes and such; the nullvalues are included in source code
104 and thus might be used to inject code if not validated.
105 """
106 nullvalue = None
107 for values in field.iterChildrenOfType(VOTable.VALUES):
108 if values.null is not None:
109 nullvalue = values.null
110 if nullvalue is None or nullvalue=='':
111 return default
112 else:
113 validator(nullvalue)
114 return nullvalue
115
116
117 def unravelArray(
118 arraysize: str,
119 seq: Sequence) -> Sequence:
120 """turns a flat sequence into an n-dim array as specified by the votable
121 arraysize spec arraysize.
122
123 arraysize is <int>{"x"<int>}*?|*.
124
125 No padding or cropping will take place. This means that the last
126 row(s) may have improper sizes if seq is incompatible with arraysize.
127
128 >>> unravelArray("2x3", "012345")
129 ['01', '23', '45']
130 >>> unravelArray("2x*", "012345")
131 ['01', '23', '45']
132 >>> unravelArray("3x2x*", "012345012345")
133 [['012', '345'], ['012', '345']]
134 """
135 parts = arraysize.split("x")
136 if len(parts)<2:
137 return seq
138 del parts[-1]
139
140 # this is so we preserve utils.intlist and friends.
141 listCons = list
142 if isinstance(seq, list):
143 listCons = seq.__class__ # type: ignore # mypy confusion, I'd say
144
145 for step in map(int, parts):
146 seq = listCons(seq[i:i+step] for i in range(0, len(seq), step))
147 return seq
148
149
150 def parseVOTableArraysizeEl(
151 spec: str,
152 fieldName: Optional[str]) -> Tuple[bool, int]:
153 """parses a single VOTable arraysize number to a pair of (flexible, length).
154
155 This will accept single numbers (returns False, number),
156 number* (returns True, number) and just * (returns 0, number).
157
158 This is used to parse the last part of an n-d array spec. Everything
159 before that must be an integer only.
160 """
161 try:
162 if spec=="*":
163 return True, 0
164
165 elif spec.endswith("*"):
166 return True, int(spec[:-1])
167
168 else:
169 return False, int(spec)
170 except ValueError:
171 raise common.VOTableError("Invalid arraysize fragment '%s' in"
172 " field or param name '%s'"%(spec, fieldName))
173
174
175 def makeShapeValidator(field: VOTable.TypedElement) -> List[str]:
176 """returns code lines to validate an an array shape against a flat
177 sequence in row.
178
179 This is used by the array decoders.
180 """
181 arraysize = field.arraysize
182 if not arraysize:
183 return []
184 dimensions = arraysize.strip().split("x")
185
186 stride = 1
187 # all dimensions except the last must be integers
188 if len(dimensions)>1:
189 try:
190 stride = reduce(lambda a,b: a*b, [int(l) for l in dimensions[:-1]])
191 except ValueError:
192 raise common.VOTableError("Invalid arraysize '%s' specified in"
193 " field or param name '%s'"%(
194 field.arraysize, field.name))
195
196 flexible, length = parseVOTableArraysizeEl(dimensions[-1], field.name)
197
198 if flexible:
199 # 0..n; all we have to do is check that the length is a multiple of
200 # stride, if that's non-trivial.
201 # TODO: enfoce length limits? By error or by cropping?
202 if stride>1:
203 return [
204 "if len(row) %% %d:"%stride,
205 " raise common.BadVOTableLiteral('%s[%s]',"
206 " '<%%d token(s)>'%%(len(row)), name=%r)"%(
207 field.datatype, field.arraysize, field.name)]
208
209 else:
210 # exact size specification
211 return [
212 "if len(row)!=%d:"%(length*stride),
213 " raise common.BadVOTableLiteral('%s[%s]',"
214 " '<%%d token(s)>'%%(len(row)), name=%r)"%(
215 field.datatype, field.arraysize, field.name)]
216
217 # fallback: no validation
218 return []
219
220
221 def ravel(seq: Sequence) -> SequenceForArray:
222 """expands flattens out any sub-sequences (lists or tuples) in seq
223 recursively.
224
225 This is used by the array encoders.
226 """
227 res = []
228 iteratorStack = [iter(seq)]
229 while iteratorStack:
230 try:
231 item = next(iteratorStack[-1])
232 if isinstance(item, (list, tuple)):
233 iteratorStack.append(iter(item))
234 # continue iterating from the current item
235 else:
236 res.append(item)
237 except StopIteration:
238 iteratorStack.pop()
239 return res
240
241
242 def trim(
243 seq: SequenceForArray,
244 arraysize: Optional[int],
245 padder: SequenceForArray) -> SequenceForArray:
246 """returns seq with length arraysize.
247
248 arraysize is an int; you should just use field.getLength() when
249 trimming VOTable arraysizes since the arraysize attribute is rather
250 complex. Arraysize may be None for convenience; trim is a no-op then.
251
252 If seq is shorter, padder*missing will be appended, if it is longer, seq will
253 be shortened from the end.
254
255 This is intended as a helper for array encoders.
256 """
257 seq = ravel(seq)
258 if arraysize is None:
259 return seq
260 if len(seq)<arraysize:
261 seq = seq+padder*(arraysize-len(seq)) # type: ignore # float/intlist
262 elif len(seq)>arraysize:
263 seq = seq[:arraysize]
264 return seq
265
266
267 def trimString(
268 val: Union[List[Optional[str]], Optional[str]],
269 arraysize: str,
270 padChar: str = " ") -> str:
271 """returns val flattened and padded with padChar/cropped to length.
272
273 field is a V.FIELD or V.PARAM instance for which val should be
274 prepared.
275
276 val can also be a sequence of strings (or nested more deeply). In that
277 case, trimString will flatten the value(s), padding and cropping as
278 necessary.
279
280 If val is None, then as many padChars will be returned as arraysize
281 wants (which is 0 for variable-length fields).
282
283 trimString expects to deal with strings. It will ascii-decode
284 bytes if it sees them, though.
285
286 For chars, arraysize None is equivalent to arraysize 1.
287
288 >>> trimString("abc", "4")
289 'abc '
290 >>> trimString(["abc", "de", "f"], "2x*")
291 'abdef '
292 >>> trimString([["abc", "cd", "e"], ["", "fgh", "i"]], "2x4x3")
293 'abcde fgi '
294 >>> trimString(None, "4x2", 'z')
295 'zzzzzzzz'
296 >>> trimString(None, "4x2*", 'z')
297 ''
298 >>> trimString("abc", None)
299 'a'
300 >>> trimString(b"abc", "5", "x")
301 'abcxx'
302 """
303 if arraysize is None:
304 arraysize = "1"
305
306 if val is None:
307 expected = common.getLength(arraysize)
308 if expected:
309 return padChar*expected
310 else:
311 return ""
312
313 if isinstance(val, bytes):
314 val = val.decode("ascii")
315
316 if "x" in arraysize:
317 # 2D: val is a list (we don't really do >2D for chars yet
318 rest, destLength = arraysize.rsplit("x", 1)
319
320 if not destLength.endswith('*'):
321 if isinstance(val, list):
322 nItems = int(destLength)
323 val = val[:nItems]+[None]*max(0, nItems-len(val))
324 else:
325 raise NotImplementedError(f"Cannot trim plain string to {arraysize}")
326
327 return "".join(trimString(item, rest, padChar) for item in val)
328
329 else:
330 # 1D val: is a char
331 if isinstance(val, str):
332 if arraysize.endswith('*'):
333 return val
334 else:
335 nItems = int(arraysize)
336 return val[:nItems]+padChar*max(0, nItems-len(val))
337 else:
338 raise NotImplementedError(f"Cannot trim non-str to {arraysize}")
339
340
341 def _toJSONEscape(mat: re.Match) -> str:
342 """returns a json escape for a one-char re match.
343
344 This is mostly ripped from json.encoder
345 """
346 n = ord(mat.group())
347 if n < 0x10000:
348 return '\\u{0:04x}'.format(n)
349 else:
350 raise common.BadVOTableData("Will not produce utf-8 surrogates",
351 f"\\u{n}", "a JSON column")
352
353
354 _ASCII_ESCAPE_PAT = re.compile("[^ -~]")
355
356 def forceASCII(s: Optional[str]) -> str:
357 """returns s with all non-ascii replaced by json escapes.
358
359 This is like json.encoder.encode_basestring_ascii, except we don't escape
360 anything else under the assumption we already have json otherwise.
361
362 >>> forceASCII("malformed ' [ json")
363 "malformed ' [ json"
364 >>> forceASCII("Krämerei")
365 'Kr\\\\u00e4merei'
366 >>> forceASCII("🄁")
367 Traceback (most recent call last):
368 gavo.votable.common.BadVOTableData: Field 'a JSON column', value '\\\\u127233': Will not produce utf-8 surrogates
369 """
370 if s is None:
371 return ""
372
373 return _ASCII_ESCAPE_PAT.sub(_toJSONEscape, s)
374
375
376
377 if __name__=="__main__": # pragma: no cover
378 import doctest
379 doctest.testmod()