| 1 |
""" |
| 2 |
Functions taking strings and returning python values. |
| 3 |
|
| 4 |
All of them accept None and return None for Nullvalue processing. |
| 5 |
|
| 6 |
All of them leave values alone if they already have the right type. |
| 7 |
|
| 8 |
This is usually used in conjunction with |
| 9 |
base.typesystems.ToPythonCodeConverter. |
| 10 |
""" |
| 11 |
|
| 12 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 13 |
#c |
| 14 |
#c This program is free software, covered by the GNU GPL. See the |
| 15 |
#c COPYING file in the source distribution. |
| 16 |
|
| 17 |
|
| 18 |
import functools |
| 19 |
import json |
| 20 |
import re |
| 21 |
|
| 22 |
# let's depend on psycopg2 for now as regards ranges. We can always |
| 23 |
# provide a thin shim here if we want to use different databases. |
| 24 |
# Advise users to only use base.NumericRange, though. |
| 25 |
from psycopg2.extras import NumericRange |
| 26 |
|
| 27 |
from gavo import utils |
| 28 |
from gavo.stc import parseSimpleSTCS |
| 29 |
from gavo.utils import pgsphere |
| 30 |
from gavo.utils import identity #noflake: exported name |
| 31 |
from gavo.utils import (parseDefaultDatetime, #noflake: exported names |
| 32 |
parseDefaultDate, parseDefaultTime) |
| 33 |
from gavo.utils.serializers import AnnotatedColumn |
| 34 |
|
| 35 |
from gavo.utils.dachstypes import ( |
| 36 |
Any, Callable, Dict, List, Numeric, Optional, Tuple, Union) |
| 37 |
|
| 38 |
|
| 39 |
@utils.document |
| 40 |
def parseInt(literal: Union[None, int, str]) -> Optional[int]: |
| 41 |
"""returns an int from a literal, or None if literal is None or an empty |
| 42 |
string. |
| 43 |
|
| 44 |
>>> parseInt("32") |
| 45 |
32 |
| 46 |
>>> parseInt("") |
| 47 |
>>> parseInt(None) |
| 48 |
""" |
| 49 |
if literal is None or (isinstance(literal, str |
| 50 |
) and not literal.strip()): |
| 51 |
return None |
| 52 |
return int(literal) |
| 53 |
|
| 54 |
|
| 55 |
_inf = float("Inf") |
| 56 |
@utils.document |
| 57 |
def parseFloat(literal: Union[None, float, str]) -> Optional[float]: |
| 58 |
"""returns a float from a literal, or None if literal is None or an empty |
| 59 |
string. |
| 60 |
|
| 61 |
>>> parseFloat(" 5e9 ") |
| 62 |
5000000000.0 |
| 63 |
>>> parseFloat(None) |
| 64 |
>>> parseFloat(" ") |
| 65 |
>>> parseFloat("wobbadobba") |
| 66 |
Traceback (most recent call last): |
| 67 |
ValueError: could not convert string to float: 'wobbadobba' |
| 68 |
""" |
| 69 |
if (literal is None or |
| 70 |
(isinstance(literal, str) and not literal.strip())): |
| 71 |
return None |
| 72 |
res = float(literal) |
| 73 |
return res |
| 74 |
|
| 75 |
_trueLiterals = set(["true", "yes", "t", "on", "enabled", "1"]) |
| 76 |
_falseLiterals = set(["false", "no", "f", "off", "disabled", "0"]) |
| 77 |
|
| 78 |
@utils.document |
| 79 |
def parseBooleanLiteral(literal: Union[bool, str]) -> bool: |
| 80 |
"""returns a python boolean from some string. |
| 81 |
|
| 82 |
Boolean literals are strings like True, false, on, Off, yes, No in |
| 83 |
some capitalization. |
| 84 |
""" |
| 85 |
if literal is None or isinstance(literal, bool): |
| 86 |
return literal |
| 87 |
if hasattr(literal, "item"): |
| 88 |
# numpy _bool |
| 89 |
return literal.item() |
| 90 |
|
| 91 |
literal = literal.lower() |
| 92 |
if literal in _trueLiterals: |
| 93 |
return True |
| 94 |
elif literal in _falseLiterals: |
| 95 |
return False |
| 96 |
else: |
| 97 |
raise ValueError( |
| 98 |
"'%s' is no recognized boolean literal."%literal) |
| 99 |
|
| 100 |
|
| 101 |
def parseUnicode(literal: Union[None, float, str]) -> Optional[str]: |
| 102 |
if literal is None: |
| 103 |
return None |
| 104 |
if isinstance(literal, bytes): |
| 105 |
literal = literal.decode("ascii", "replace") |
| 106 |
return str(literal) |
| 107 |
|
| 108 |
|
| 109 |
def parseBytes(literal: Union[bytes, str]) -> bytes: |
| 110 |
r"""returns bytes from a literal. |
| 111 |
|
| 112 |
This will interpret hex and octal byte escapes, and it'll support lists |
| 113 |
of integer-like things; not sure if that's actually more harmful than good. |
| 114 |
But then people can always override the default behaviour. |
| 115 |
|
| 116 |
>>> parseBytes("abc") |
| 117 |
b'abc' |
| 118 |
>>> parseBytes(r"\xab\000") |
| 119 |
b'\xab\x00' |
| 120 |
>>> parseBytes([123, 231, 23]) |
| 121 |
b'{\xe7\x17' |
| 122 |
>>> parseBytes([10002]) |
| 123 |
Traceback (most recent call last): |
| 124 |
ValueError: bytes must be in range(0, 256) |
| 125 |
""" |
| 126 |
if literal is None: |
| 127 |
return |
| 128 |
|
| 129 |
elif isinstance(literal, bytes): |
| 130 |
return literal |
| 131 |
|
| 132 |
elif isinstance(literal, list): |
| 133 |
return bytes(literal) |
| 134 |
|
| 135 |
elif isinstance(literal, str): |
| 136 |
return re.sub( |
| 137 |
br"\\(\d\d\d)", |
| 138 |
lambda mat: bytes([int(mat.group(1), 8)]), |
| 139 |
re.sub(br"\\x([a-zA-Z0-9][a-zA-Z0-9])", |
| 140 |
lambda mat: bytes([int(mat.group(1), 16)]), |
| 141 |
literal.encode("ascii"))) |
| 142 |
|
| 143 |
else: |
| 144 |
raise ValueError("No idea how to make bytes from %s"%repr(literal)) |
| 145 |
|
| 146 |
|
| 147 |
def parseCooPair(soup: str) -> Tuple[float, float]: |
| 148 |
"""returns a pair of RA, DEC floats if they can be made out in soup |
| 149 |
or raises a value error. |
| 150 |
|
| 151 |
No range checking is done (yet), i.e., as long as two numbers can be |
| 152 |
made out, the function is happy. |
| 153 |
|
| 154 |
>>> parseCooPair("23 12") |
| 155 |
(23.0, 12.0) |
| 156 |
>>> parseCooPair("23.5,-12.25") |
| 157 |
(23.5, -12.25) |
| 158 |
>>> parseCooPair("3.75 -12.125") |
| 159 |
(3.75, -12.125) |
| 160 |
>>> parseCooPair("3 25,-12 30") |
| 161 |
(51.25, -12.5) |
| 162 |
>>> ["{:.9f}".format(v) for v in parseCooPair("12 15 30.5 +52 18 27.5")] |
| 163 |
['183.877083333', '52.307638889'] |
| 164 |
>>> parseCooPair("3.39 -12 39") |
| 165 |
Traceback (most recent call last): |
| 166 |
ValueError: Invalid time with sepChar None: '3.39' |
| 167 |
>>> parseCooPair("12 15 30.5 +52 18 27.5e") |
| 168 |
Traceback (most recent call last): |
| 169 |
ValueError: 12 15 30.5 +52 18 27.5e has no discernible position in it |
| 170 |
>>> parseCooPair("QSO2230+44.3") |
| 171 |
Traceback (most recent call last): |
| 172 |
ValueError: QSO2230+44.3 has no discernible position in it |
| 173 |
""" |
| 174 |
soup = soup.strip() |
| 175 |
|
| 176 |
def parseFloatPair(soup: str) -> Optional[Tuple[float, float]]: |
| 177 |
mat = re.match(r"(%s)\s*[\s,/]\s*(%s)$"%(utils.floatRE, |
| 178 |
utils.floatRE), soup) |
| 179 |
if mat: |
| 180 |
return float(mat.group(1)), float(mat.group(2)) |
| 181 |
return None |
| 182 |
|
| 183 |
def parseSexa(soup: str) -> Optional[Tuple[float, float]]: |
| 184 |
timeangleRE = r"(?:\d+\s+)?(?:\d+\s+)?\d+(?:\.\d*)?" |
| 185 |
dmsRE = r"[+-]?\s*(?:\d+\s+)?(?:\d+\s+)?\d+(?:\.\d*)?" |
| 186 |
mat = re.match(r"(%s)\s*[\s,/]?\s*(%s)$"%(timeangleRE, dmsRE), soup) |
| 187 |
if mat: |
| 188 |
try: |
| 189 |
return utils.hmsToDeg(mat.group(1)), utils.dmsToDeg( |
| 190 |
mat.group(2)) |
| 191 |
except utils.Error as msg: |
| 192 |
raise utils.logOldExc(ValueError(str(msg))) |
| 193 |
|
| 194 |
return None |
| 195 |
|
| 196 |
def parseSexaColon(soup: str) -> Optional[Tuple[float, float]]: |
| 197 |
timeangleRE = r"(?:\d+:)?(?:\d+:)?\d+(?:\.\d*)?" |
| 198 |
dmsRE = r"[+-]?\s*(?:\d+:)?(?:\d+:)?\d+(?:\.\d*)?" |
| 199 |
mat = re.match(r"(%s)\s*[\s,/]?\s*(%s)$"%(timeangleRE, dmsRE), soup) |
| 200 |
if mat: |
| 201 |
try: |
| 202 |
return (utils.hmsToDeg(mat.group(1), sepChar=":"), |
| 203 |
utils.dmsToDeg(mat.group(2), sepChar=":")) |
| 204 |
except utils.Error as msg: |
| 205 |
raise utils.logOldExc(ValueError(str(msg))) |
| 206 |
|
| 207 |
return None |
| 208 |
|
| 209 |
for func in [parseFloatPair, parseSexa, parseSexaColon]: |
| 210 |
res = func(soup) |
| 211 |
if res: |
| 212 |
return res |
| 213 |
|
| 214 |
raise ValueError("%s has no discernible position in it"%soup) |
| 215 |
|
| 216 |
|
| 217 |
def parseSPoint(soup: Optional[Union[str, pgsphere.SPoint]] |
| 218 |
) -> Optional[pgsphere.SPoint]: |
| 219 |
"""returns an ``SPoint`` for a coordinate pair. |
| 220 |
|
| 221 |
The coordinate pair can be formatted in a variety of ways; see the |
| 222 |
`function parseCooPair`_. Input is always in degrees. |
| 223 |
""" |
| 224 |
if soup is None or isinstance(soup, pgsphere.SPoint): |
| 225 |
return soup |
| 226 |
return pgsphere.SPoint.fromDegrees(*parseCooPair(soup)) |
| 227 |
|
| 228 |
|
| 229 |
def parseInterval(soup: str) -> NumericRange: |
| 230 |
"""tries to parse a numeric interval out of soup. |
| 231 |
|
| 232 |
Technically, we expect a space-separated pair of numeric somethings. |
| 233 |
If a part can be parsed as an int is, else it becomes a float. |
| 234 |
|
| 235 |
What's returned is a NumericRange object (currently from psycopg2, but |
| 236 |
you should only import NumericRange from base). |
| 237 |
|
| 238 |
Invalid literals raise some sort of ValueError. |
| 239 |
|
| 240 |
>>> parseInterval('3 4') |
| 241 |
NumericRange(3, 4, '[)') |
| 242 |
>>> parseInterval('3.5 4.75') |
| 243 |
NumericRange(3.5, 4.75, '[)') |
| 244 |
>>> parseInterval('20') |
| 245 |
Traceback (most recent call last): |
| 246 |
ValueError: Not a valid numeric interval literal: '20' |
| 247 |
>>> parseInterval('gabba gubbu') |
| 248 |
Traceback (most recent call last): |
| 249 |
ValueError: could not convert string to float: 'gabba' |
| 250 |
""" |
| 251 |
try: |
| 252 |
lower, upper = soup.split() |
| 253 |
except ValueError: |
| 254 |
raise ValueError("Not a valid numeric interval literal: %s"%repr(soup)) |
| 255 |
|
| 256 |
lowerParsed: Numeric = 0 |
| 257 |
upperParsed: Numeric = 0 |
| 258 |
|
| 259 |
try: |
| 260 |
lowerParsed = int(lower) |
| 261 |
except ValueError: |
| 262 |
lowerParsed = float(lower) |
| 263 |
try: |
| 264 |
upperParsed = int(upper) |
| 265 |
except ValueError: |
| 266 |
upperParsed = float(upper) |
| 267 |
|
| 268 |
return NumericRange(lowerParsed, upperParsed) |
| 269 |
|
| 270 |
|
| 271 |
def originalOrIdentity(soup: Any) -> Any: |
| 272 |
"""returns soup.original or soup if there is no original attribute. |
| 273 |
|
| 274 |
This is for cooperation with BinaryItem coming in from the web into |
| 275 |
ContextGrammars. |
| 276 |
""" |
| 277 |
return getattr(soup, "original", soup) |
| 278 |
|
| 279 |
|
| 280 |
def _numericRangeFactory(colDesc: AnnotatedColumn |
| 281 |
) -> Optional[ |
| 282 |
Callable[[Optional[NumericRange]], Optional[Tuple[Numeric, Numeric]]]]: |
| 283 |
"""A factory to serialise psycopg numeric ranges into VOTables. |
| 284 |
|
| 285 |
If what's coming in is a NumericRange, it's turned into a 2-tuple; |
| 286 |
else it's left alone. |
| 287 |
|
| 288 |
(as of 1.2, DaCHS can't really read the result again properly) |
| 289 |
""" |
| 290 |
if colDesc["xtype"]=="interval" and colDesc["datatype"] in [ |
| 291 |
"int", "long", "float", "double"]: |
| 292 |
|
| 293 |
def mapper(val: Optional[NumericRange] |
| 294 |
) -> Optional[Tuple[Numeric, Numeric]]: |
| 295 |
if val is None or val.upper is None or val.lower is None: |
| 296 |
return None |
| 297 |
if isinstance(val, NumericRange): |
| 298 |
if val.upper_inc and colDesc["datatype"] in ["int", "long"]: |
| 299 |
return (val.lower, val.upper+1) |
| 300 |
return (val.lower, val.upper) |
| 301 |
return val |
| 302 |
|
| 303 |
return mapper |
| 304 |
|
| 305 |
return None |
| 306 |
|
| 307 |
utils.registerDefaultMF(_numericRangeFactory) |
| 308 |
|
| 309 |
|
| 310 |
def parseJSON(val: Union[Dict, List, str]) -> Optional[str]: |
| 311 |
# we allow JSON input as dicts or lists; keep psycopg from serialising |
| 312 |
# things that probably came from json in non-json ways |
| 313 |
if isinstance(val, (dict, list)): |
| 314 |
return json.dumps(val) |
| 315 |
return val or None |
| 316 |
|
| 317 |
|
| 318 |
@functools.lru_cache(1) |
| 319 |
def getDefaultValueParsers() -> Dict[str, Callable]: |
| 320 |
"""returns a dict containing all exported names from this module. |
| 321 |
|
| 322 |
This is useful with typesystems.ToPythonCodeConverter; see |
| 323 |
rscdef.column.Parameter for an example. |
| 324 |
|
| 325 |
This is always the same dict; thus, if you change it, copy it first. |
| 326 |
""" |
| 327 |
all = set(__all__) |
| 328 |
return dict((n,v) for n,v in globals().items() if n in all) |
| 329 |
|
| 330 |
|
| 331 |
def _test(): |
| 332 |
import doctest |
| 333 |
doctest.testmod() |
| 334 |
|
| 335 |
|
| 336 |
if __name__=="__main__": |
| 337 |
_test() |
| 338 |
|
| 339 |
|
| 340 |
__all__ = ["parseInt", "parseFloat", "parseBooleanLiteral", "parseUnicode", |
| 341 |
"parseDefaultDate", "parseDefaultTime", "parseDefaultDatetime", |
| 342 |
"parseCooPair", "getDefaultValueParsers", "parseSPoint", "parseSimpleSTCS", |
| 343 |
"NumericRange", "originalOrIdentity", "parseBytes", "parseJSON"] |