| 1 |
""" |
| 2 |
Parsing various forms of tabular data embedded in VOTables. |
| 3 |
|
| 4 |
WARNING: This will fail if the parser exposes namespaces in its |
| 5 |
events (utils.iterparse doesn't). |
| 6 |
""" |
| 7 |
|
| 8 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 9 |
#c |
| 10 |
#c This program is free software, covered by the GNU GPL. See the |
| 11 |
#c COPYING file in the source distribution. |
| 12 |
|
| 13 |
|
| 14 |
import base64 |
| 15 |
|
| 16 |
from gavo.votable import coding |
| 17 |
from gavo.votable import common |
| 18 |
from gavo.votable import dec_binary |
| 19 |
from gavo.votable import dec_binary2 |
| 20 |
from gavo.votable import dec_tabledata |
| 21 |
from gavo.votable.model import VOTable as V |
| 22 |
from gavo.utils.plainxml import iterparse |
| 23 |
|
| 24 |
from gavo.utils.dachstypes import (cast, |
| 25 |
Any, Dict, Iterator, List, Optional) |
| 26 |
|
| 27 |
|
| 28 |
class DataIterator: |
| 29 |
"""A base for the classes actually doing the iteration. |
| 30 |
|
| 31 |
You need to give a decoderModule attribute and implement _getRawRow. |
| 32 |
""" |
| 33 |
decoderModule = dec_tabledata # stand-in; override on derivation. |
| 34 |
|
| 35 |
def __init__(self, tableDefinition: V.TABLE, nodeIterator: iterparse) -> None: |
| 36 |
self.nodeIterator = nodeIterator |
| 37 |
self._decodeRawRow = coding.buildDecoder( |
| 38 |
tableDefinition, |
| 39 |
self.decoderModule) |
| 40 |
|
| 41 |
def __iter__(self) -> Iterator[Dict[str, Any]]: |
| 42 |
while True: |
| 43 |
rawRow = self._getRawRow() |
| 44 |
if rawRow is None: |
| 45 |
break |
| 46 |
yield self._decodeRawRow(rawRow) |
| 47 |
|
| 48 |
def _getRawRow(self) -> Optional[List[Any]]: |
| 49 |
raise NotImplementedError("You must override _getRawRow on derivation") |
| 50 |
|
| 51 |
|
| 52 |
class TableDataIterator(DataIterator): |
| 53 |
"""An internal class used by Rows to actually iterate over rows |
| 54 |
in TABLEDATA serialization. |
| 55 |
""" |
| 56 |
decoderModule = dec_tabledata |
| 57 |
|
| 58 |
def _getRawRow(self) -> Optional[List[Any]]: |
| 59 |
"""returns a row in strings or None. |
| 60 |
""" |
| 61 |
# Wait for TR open |
| 62 |
for type, tag, payload in self.nodeIterator: |
| 63 |
if type=="end" and tag=="TABLEDATA": |
| 64 |
return None |
| 65 |
elif type=="start": |
| 66 |
if tag=="TR": |
| 67 |
break |
| 68 |
else: |
| 69 |
raise self.nodeIterator.getParseError( |
| 70 |
"Unexpected element %s"%tag) |
| 71 |
# ignore everything else; we're not validating, and sensible stuff |
| 72 |
# might yet follow (usually, it's whitespace data anyway) |
| 73 |
|
| 74 |
rawRow: List[str] = [] |
| 75 |
dataBuffer: List[str] = [] |
| 76 |
for type, tag, payload in self.nodeIterator: |
| 77 |
if type=="start": # new TD |
| 78 |
dataBuffer = [] |
| 79 |
if tag!="TD": |
| 80 |
raise self.nodeIterator.getParseError( |
| 81 |
"Unexpected element %s"%tag) |
| 82 |
|
| 83 |
elif type=="data": # TD content |
| 84 |
dataBuffer.append(cast(str, payload)) |
| 85 |
|
| 86 |
elif type=="end": # could be row end or cell end |
| 87 |
if tag=="TR": |
| 88 |
break |
| 89 |
elif tag=="TD": |
| 90 |
rawRow.append("".join(dataBuffer)) |
| 91 |
else: # pragma: no cover |
| 92 |
assert False |
| 93 |
dataBuffer = [] |
| 94 |
|
| 95 |
else: # pragma: no cover |
| 96 |
assert False |
| 97 |
return rawRow |
| 98 |
|
| 99 |
|
| 100 |
class _StreamData: |
| 101 |
"""A stand-in for a file that decodes VOTable stream data on |
| 102 |
an as-needed basis. |
| 103 |
""" |
| 104 |
minChunk = 20000 # min length of encoded data decoded at a time |
| 105 |
lastRes = None # last thing read (convenient for error msgs) |
| 106 |
|
| 107 |
def __init__(self, nodeIterator: iterparse) -> None: |
| 108 |
self.nodeIterator = nodeIterator |
| 109 |
self.curChunk = b"" # binary data already decoded |
| 110 |
self.leftover = b"" # undecoded base64 data |
| 111 |
self.fPos = 0 # index of next char to be returned |
| 112 |
self._eof = False # True when we've seen the </STREAM> event |
| 113 |
|
| 114 |
def _setEOF(self) -> None: |
| 115 |
"""cleans up at end of stream and sets eof flag. |
| 116 |
|
| 117 |
This is called by _fillBuffer exclusively. |
| 118 |
""" |
| 119 |
for evtype, element, payload in self.nodeIterator: |
| 120 |
if evtype!="data": |
| 121 |
break |
| 122 |
self._eof = True |
| 123 |
|
| 124 |
def _fillBuffer(self, nBytes: int) -> None: |
| 125 |
"""obtains events from node iterator to fill curChunk. |
| 126 |
""" |
| 127 |
if self._eof: |
| 128 |
return |
| 129 |
destBytes = max(nBytes*2, self.minChunk) |
| 130 |
curBytes, hadLf = 0, False |
| 131 |
encoded = [self.leftover] |
| 132 |
|
| 133 |
for type, tag, value in self.nodeIterator: |
| 134 |
if type=="end": # must be </STREAM> or expat would've crapped. |
| 135 |
self._setEOF() |
| 136 |
break |
| 137 |
assert type=="data" |
| 138 |
payload = cast(str, value).encode("ascii") |
| 139 |
encoded.append(payload) |
| 140 |
curBytes += len(payload) |
| 141 |
hadLf = hadLf or b"\n" in payload or b"\r" in payload |
| 142 |
if hadLf and curBytes>destBytes: |
| 143 |
break |
| 144 |
|
| 145 |
self._decodeBase64(b"".join(encoded)) |
| 146 |
|
| 147 |
def _decodeBase64(self, input: bytes) -> None: |
| 148 |
"""decodes input and sets curChunk, leftover, and fPos accordingly. |
| 149 |
|
| 150 |
The method behaves slightly differently when the _eof attribute is |
| 151 |
true -- normally, it will leave anything after the last line feed |
| 152 |
alone, but at _eof, it will decode even that. |
| 153 |
|
| 154 |
It is an error to pass in anything that has no line break unless |
| 155 |
at _eof. |
| 156 |
""" |
| 157 |
if not self._eof: # put back anything after the last break mid-stream |
| 158 |
try: |
| 159 |
lastBreak = input.rindex(b"\n")+1 |
| 160 |
except ValueError: |
| 161 |
lastBreak = input.rindex(b"\r")+1 |
| 162 |
self.leftover = input[lastBreak:] |
| 163 |
input = input[:lastBreak] |
| 164 |
|
| 165 |
self.curChunk = self.curChunk[self.fPos:]+base64.b64decode(input) |
| 166 |
self.fPos = 0 |
| 167 |
|
| 168 |
def read(self, nBytes: int) -> bytes: |
| 169 |
"""returns a string containing the next nBytes of the input |
| 170 |
stream. |
| 171 |
|
| 172 |
The function raises an IOError if there's not enough data left. |
| 173 |
""" |
| 174 |
if self.fPos+nBytes>len(self.curChunk): |
| 175 |
self._fillBuffer(nBytes) |
| 176 |
if self.fPos+nBytes>len(self.curChunk): |
| 177 |
raise IOError("No data left") |
| 178 |
self.lastRes = self.curChunk[self.fPos:self.fPos+nBytes] |
| 179 |
self.fPos += nBytes |
| 180 |
return self.lastRes |
| 181 |
|
| 182 |
def atEnd(self) -> bool: |
| 183 |
return self._eof and self.fPos==len(self.curChunk) |
| 184 |
|
| 185 |
|
| 186 |
class BinaryIteratorBase(DataIterator): |
| 187 |
"""A base class used by Rows to actually iterate over rows |
| 188 |
in BINARY(2) serialization. |
| 189 |
|
| 190 |
Since the VOTable binary serialization has no framing, we need to |
| 191 |
present the data stream coming from the parser as a file to the decoder. |
| 192 |
""" |
| 193 |
|
| 194 |
# I need to override __iter__ since we're not actually doing XML parsing |
| 195 |
# here; almost all of our work is done within the stream element. |
| 196 |
def __iter__(self) -> Iterator[Dict[str, Any]]: |
| 197 |
for type, tag, payload in self.nodeIterator: |
| 198 |
if type!="data": |
| 199 |
break |
| 200 |
if not (type=="start" |
| 201 |
and tag=="STREAM" |
| 202 |
and cast(dict, payload).get("encoding")=="base64"): |
| 203 |
raise common.VOTableError("Can only read BINARY data from base64" |
| 204 |
" encoded streams") |
| 205 |
|
| 206 |
inF = _StreamData(self.nodeIterator) |
| 207 |
while not inF.atEnd(): |
| 208 |
row = self._decodeRawRow(inF) |
| 209 |
if row is not None: |
| 210 |
yield row |
| 211 |
|
| 212 |
|
| 213 |
class BinaryIterator(BinaryIteratorBase): |
| 214 |
decoderModule = dec_binary |
| 215 |
|
| 216 |
|
| 217 |
class Binary2Iterator(BinaryIteratorBase): |
| 218 |
decoderModule = dec_binary2 |
| 219 |
|
| 220 |
|
| 221 |
def _makeTableIterator( |
| 222 |
elementName: str, |
| 223 |
tableDefinition: V.TABLE, |
| 224 |
nodeIterator: iterparse) -> Iterator[Dict[str, Any]]: |
| 225 |
"""returns an iterator for the rows contained within node. |
| 226 |
""" |
| 227 |
if elementName=='TABLEDATA': |
| 228 |
return iter(TableDataIterator(tableDefinition, nodeIterator)) |
| 229 |
elif elementName=='BINARY': |
| 230 |
return iter(BinaryIterator(tableDefinition, nodeIterator)) |
| 231 |
elif elementName=='BINARY2': |
| 232 |
return iter(Binary2Iterator(tableDefinition, nodeIterator)) |
| 233 |
|
| 234 |
else: |
| 235 |
raise common.VOTableError("Unknown table serialization: %s"% |
| 236 |
elementName, hint="We only support TABLEDATA, BINARY2," |
| 237 |
" and BINARY coding") |
| 238 |
|
| 239 |
|
| 240 |
class Rows: |
| 241 |
"""a wrapper for data within a VOTable. |
| 242 |
|
| 243 |
Tabledatas are constructed with a model.VOTable.TABLE instance and |
| 244 |
the iterator maintained by parser.parse. They yield individual |
| 245 |
table lines (as lists of Python values). |
| 246 |
|
| 247 |
In reality, __iter__ just dispatches to the various deserializers. |
| 248 |
""" |
| 249 |
def __init__(self, |
| 250 |
tableDefinition: V.TABLE, |
| 251 |
nodeIterator: iterparse) -> None: |
| 252 |
self.tableDefinition, self.nodeIterator = tableDefinition, nodeIterator |
| 253 |
|
| 254 |
def __iter__(self) -> Iterator[Dict[str, Any]]: |
| 255 |
for type, tag, payload in self.nodeIterator: |
| 256 |
if type=="data": # ignore whitespace (or other stuff...) |
| 257 |
pass |
| 258 |
elif tag=="INFO": |
| 259 |
pass # XXX TODO: What do we do with those INFOs? |
| 260 |
else: |
| 261 |
return _makeTableIterator(cast(str, tag), |
| 262 |
self.tableDefinition, self.nodeIterator) |
| 263 |
|
| 264 |
return iter([]) |