unitcorn 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of unitcorn might be problematic. Click here for more details.

Files changed (59) hide show
  1. unitcorn/__init__.py +110 -0
  2. unitcorn/airQuality/__init__.py +99 -0
  3. unitcorn/area/__init__.py +3 -0
  4. unitcorn/area/area.py +103 -0
  5. unitcorn/base/Decorators.py +72 -0
  6. unitcorn/base/Registry.py +75 -0
  7. unitcorn/base/SmartBases.py +26 -0
  8. unitcorn/base/_Algebra.py +205 -0
  9. unitcorn/base/_Measurement.py +1122 -0
  10. unitcorn/base/_ScalingMeasurement.py +398 -0
  11. unitcorn/base/_SmartFloat.py +1635 -0
  12. unitcorn/base/__init__.py +6 -0
  13. unitcorn/config/__init__.py +318 -0
  14. unitcorn/config/__main__.py +8 -0
  15. unitcorn/config/si.toml +53 -0
  16. unitcorn/config/template.toml +146 -0
  17. unitcorn/config/us.toml +53 -0
  18. unitcorn/defaults/WeatherFlow/__init__.py +176 -0
  19. unitcorn/defaults/__init__.py +1 -0
  20. unitcorn/derived/__init__.py +16 -0
  21. unitcorn/derived/density.py +26 -0
  22. unitcorn/derived/partsPer.py +96 -0
  23. unitcorn/derived/precipitation.py +96 -0
  24. unitcorn/derived/rate.py +80 -0
  25. unitcorn/derived/volume.py +122 -0
  26. unitcorn/derived/wind.py +54 -0
  27. unitcorn/digital/__init__.py +21 -0
  28. unitcorn/energy/__init__.py +4 -0
  29. unitcorn/energy/energy.py +120 -0
  30. unitcorn/energy/power.py +83 -0
  31. unitcorn/errors/Conversion.py +12 -0
  32. unitcorn/errors/Unit.py +4 -0
  33. unitcorn/errors/__init__.py +7 -0
  34. unitcorn/length/__init__.py +19 -0
  35. unitcorn/length/imperial.py +46 -0
  36. unitcorn/length/length.py +74 -0
  37. unitcorn/length/metric.py +56 -0
  38. unitcorn/mass/__init__.py +15 -0
  39. unitcorn/mass/imperial.py +47 -0
  40. unitcorn/mass/mass.py +57 -0
  41. unitcorn/mass/metric.py +47 -0
  42. unitcorn/others/__init__.py +338 -0
  43. unitcorn/others/light.py +51 -0
  44. unitcorn/pressure/__init__.py +3 -0
  45. unitcorn/pressure/pressure.py +189 -0
  46. unitcorn/py.typed +0 -0
  47. unitcorn/temperature/__init__.py +19 -0
  48. unitcorn/temperature/celsius.py +23 -0
  49. unitcorn/temperature/change.py +156 -0
  50. unitcorn/temperature/fahrenheit.py +24 -0
  51. unitcorn/temperature/kelvin.py +25 -0
  52. unitcorn/temperature/temperature.py +154 -0
  53. unitcorn/time_/__init__.py +1 -0
  54. unitcorn/time_/time.py +387 -0
  55. unitcorn/utils.py +399 -0
  56. unitcorn-0.9.0.dist-info/METADATA +536 -0
  57. unitcorn-0.9.0.dist-info/RECORD +59 -0
  58. unitcorn-0.9.0.dist-info/WHEEL +4 -0
  59. unitcorn-0.9.0.dist-info/licenses/LICENSE.txt +17 -0
unitcorn/utils.py ADDED
@@ -0,0 +1,399 @@
1
+ import logging
2
+ import re
3
+ from collections.abc import Mapping as _MappingABC
4
+ from difflib import get_close_matches, SequenceMatcher
5
+ from functools import lru_cache
6
+ from heapq import nlargest
7
+ from itertools import product
8
+ from os import environ
9
+ from typing import (
10
+ Hashable, Type, TYPE_CHECKING, TypeAlias, TypeVar, Union, Final, Any, Mapping, Callable, Set, Tuple, Optional,
11
+ NamedTuple
12
+ )
13
+
14
+ def getEnv(name: str, default: Any = None) -> Any:
15
+ """Read ``UNITCORN_<name>``, falling back to the pre-rename ``WU_<name>``."""
16
+ return environ.get(f'UNITCORN_{name}', environ.get(f'WU_{name}', default))
17
+
18
+
19
+ DEBUG = getEnv('DEBUG', False)
20
+
21
+ if TYPE_CHECKING:
22
+ from .base import Measurement
23
+
24
+ log = logging.getLogger('unitcorn').getChild('utils')
25
+
26
+ numeric = re.compile(r'^[-+]?[0-9]*\.?[0-9]+$')
27
+
28
+ Self: TypeAlias = TypeVar('Self', bound='Measurement')
29
+ Other: TypeAlias = TypeVar('Other', bound='Measurement')
30
+
31
+ @lru_cache()
32
+ def loadUnitLocalization(measurement: Type['Measurement'], config):
33
+ if not isinstance(measurement, type):
34
+ measurement = type(measurement)
35
+ unitName = measurement.type.name.lower()
36
+ keys = config.localUnits.keys()
37
+ match = get_close_matches(unitName, keys, n=1, cutoff=0.85)
38
+ if not match:
39
+ # Then each generic ancestor, nearest first. Kilometer's are Metric Length,
40
+ # Measurement and Length: only the last one is what `[Units] length = mi`
41
+ # names, so stopping at the first (as this once did, on whichever one a set
42
+ # happened to yield) left it unconverted on some runs. The bare Measurement
43
+ # is skipped, it is every unit's ancestor and names nothing.
44
+ for generic in measurement.__mro__:
45
+ if generic is measurement or generic.__name__ in ('Measurement', 'SmartFloat') or not getattr(generic, 'isGeneric', False):
46
+ continue
47
+ if match := get_close_matches(generic.name.lower(), keys, n=1, cutoff=0.8):
48
+ break
49
+ return config.localUnits[match[0]] if match else None
50
+
51
+
52
+ def toCamelCase(string, titleCase: bool = False) -> str:
53
+ string = (string.lower() if string.isupper() else string)
54
+ for char in ['-', ' ', '.', '_']:
55
+ string.replace(char, '')
56
+ return string[0].upper() if titleCase else string[0].lower() + string[1:]
57
+
58
+
59
+ def convertString(value: str) -> Union[int, float, str, bool]:
60
+ if value is None:
61
+ return value
62
+ if value.isnumeric():
63
+ value = float(value)
64
+ if value.is_integer():
65
+ value = int(value)
66
+ return value
67
+ if value == 'True':
68
+ value = True
69
+ elif value == 'False':
70
+ value = False
71
+ return value
72
+
73
+
74
+ ScoredMatch = NamedTuple('Match', [('ratio', 'float'), ('value', 'str')])
75
+
76
+
77
+ def scored_get_close_matches(word, possibilities, n=3, cutoff=0.8) -> Tuple[ScoredMatch, ...]:
78
+ if not n > 0:
79
+ raise ValueError("n must be > 0: %r"%(n,))
80
+ if not 0.0 <= cutoff <= 1.0:
81
+ raise ValueError("cutoff must be in [0.0, 1.0]: %r"%(cutoff,))
82
+ result = []
83
+ s = SequenceMatcher()
84
+ s.set_seq2(word)
85
+ for x in possibilities:
86
+ s.set_seq1(x)
87
+ if s.real_quick_ratio() >= cutoff and \
88
+ s.quick_ratio() >= cutoff and \
89
+ s.ratio() >= cutoff:
90
+ result.append((s.ratio(), x))
91
+
92
+ result = nlargest(n, result)
93
+ return tuple(ScoredMatch(k, v) for (k, v) in result)
94
+
95
+
96
+ def best_match(word, possibilities, cutoff=0) -> Optional[str]:
97
+ """
98
+ Returns the best guess at a match to the word.
99
+ """
100
+ guesses = get_close_matches(word, possibilities, n=1, cutoff=cutoff)
101
+ return guesses[0] if guesses else None
102
+
103
+
104
+ class classproperty:
105
+ """A read-only descriptor that behaves like a ``property`` but is accessible on
106
+ both the owning class and its instances, always receiving the class as its argument.
107
+
108
+ This replaces the ``@classmethod`` + ``@property`` chaining that was removed in
109
+ Python 3.13.
110
+ """
111
+ __slots__ = ('fget',)
112
+
113
+ def __init__(self, fget: Callable[[type], Any]):
114
+ self.fget = fget
115
+
116
+ def __get__(self, obj: Any, owner: type = None) -> Any:
117
+ if owner is None:
118
+ owner = type(obj)
119
+ return self.fget(owner)
120
+
121
+
122
+ class CaseInsensitiveKey(str):
123
+
124
+ def __hash__(self):
125
+ return hash(self.lower())
126
+
127
+ def __eq__(self, other):
128
+ return self.lower() == other.lower()
129
+
130
+
131
+ def parseString(item: str):
132
+ key, value = item.split('=')
133
+ value = convertString(value)
134
+ return f'_{key}', value
135
+
136
+
137
+ def strToDict(string: str, cls: type) -> type:
138
+ conf = [parseString(a) for a in [(y.strip(' ')) for y in string.split(',')]]
139
+ for item in conf:
140
+ setattr(cls, *item)
141
+ return cls
142
+
143
+
144
+ def setPropertiesFromConfig(cls, config) -> None:
145
+ """
146
+ Modifies the class in place to add the properties defined in the config.
147
+ :param cls: Class to modify
148
+ :type cls: Type[Measurement]
149
+ :param config: Config to use
150
+ :type config: Config
151
+ """
152
+ possibleNames = [cls.__name__.lower(), cls._unit, toCamelCase(cls.__name__), cls.__name__]
153
+ if hasattr(cls, '_type') and cls._type is not None and not isinstance(cls._type, str):
154
+ possibleTypes = [cls._type.__name__.lower(), toCamelCase(cls._type.__name__), cls._type.__name__]
155
+ for classType in possibleTypes:
156
+ try:
157
+ cls = strToDict(config.unitProperties[classType], cls)
158
+ config.configuredUnits[cls.__name__] = cls
159
+ break
160
+ except KeyError:
161
+ pass
162
+ else:
163
+ log.debug(f'{cls.__name__} has no type defined')
164
+
165
+ for name in possibleNames:
166
+ try:
167
+ cls = strToDict(config.unitProperties[name], cls)
168
+ config.configuredUnits[name] = cls
169
+ break
170
+ except KeyError:
171
+ pass
172
+
173
+
174
+ def getPropertiesFromConfig(name: str, cls: dict, config) -> dict:
175
+ """
176
+ Modifies the class in place to add the properties defined in the config.
177
+ :param config: Config to use
178
+ :type config: Config
179
+ """
180
+ possibleNames = [name.__name__.lower(), cls.get('_unit'), toCamelCase(cls.__name__), name]
181
+ # if hasattr(cls, '_type') and cls._type is not None and not isinstance(cls._type, str):
182
+ # possibleTypes = [cls._type.__name__.lower(), toCamelCase(cls._type.__name__), cls._type.__name__]
183
+ # for classType in possibleTypes:
184
+ # try:
185
+ # cls = strToDict(config.unitProperties[classType], cls)
186
+ # config.configuredUnits[cls.__name__] = cls
187
+ # break
188
+ # except KeyError:
189
+ # pass
190
+ # else:
191
+ # log.debug(f'{cls.__name__} has no type defined')
192
+ result = {}
193
+ for name in possibleNames:
194
+ try:
195
+ cls = strToDict(config.unitProperties[name], cls)
196
+ config.configuredUnits[name] = cls
197
+ break
198
+ except KeyError:
199
+ pass
200
+
201
+
202
+ class HashSlice:
203
+ __slots__ = ('start', 'stop', 'step')
204
+ start: Union[Hashable, type]
205
+ stop: Union[Hashable, type]
206
+ step: Union[Hashable, type]
207
+
208
+ def __init__(self, start: Union[Hashable, slice], stop: Hashable = None, step: Hashable = None):
209
+ if isinstance(start, (slice, HashSlice)):
210
+ stop = start.stop
211
+ step = start.step
212
+ start = start.start
213
+ elif isinstance(start, tuple) and stop is None and step is None:
214
+ tupleLength = len(start)
215
+ if tupleLength == 1:
216
+ start = start[0]
217
+ elif tupleLength == 2:
218
+ start, stop = start
219
+ elif tupleLength == 3:
220
+ start, stop, step = start
221
+ else:
222
+ raise ValueError(f'Invalid start tuple length: {tupleLength}')
223
+ self.start = start
224
+ self.stop = stop
225
+ self.step = step
226
+
227
+ def __iter__(self) -> iter:
228
+ return iter((self.start, self.stop, self.step))
229
+
230
+ def __repr__(self) -> str:
231
+ return f"HashSlice[{self.start or ''}:{self.stop or ''}:{self.step or ''}]"
232
+
233
+ def __str__(self) -> str:
234
+ return f"[{self.start or ''}:{self.stop or ''}:{self.step or ''}]"
235
+
236
+ def __eq__(self, other: object) -> bool:
237
+ if hasattr(other, 'start') and hasattr(other, 'stop') and hasattr(other, 'step'):
238
+ return self.start == other.start and self.stop == other.stop and self.step == other.step
239
+ if self.stop is None and self.step is None:
240
+ return self.start == other
241
+ return False
242
+
243
+ def __hash__(self) -> int:
244
+ values = [self.start, self.stop, self.step]
245
+ if self.step is None:
246
+ values.pop()
247
+ if self.stop is None and self.step is None:
248
+ values.pop()
249
+ if len(values) == 1:
250
+ return hash(values[0])
251
+ return hash(tuple(values))
252
+
253
+ @property
254
+ def isSlice(self) -> bool:
255
+ return self.stop is not None
256
+
257
+
258
+ def modifyCase(string: str, titleCase: bool = True, joiner: str = '') -> str:
259
+ if string.isupper():
260
+ return string
261
+ stringParts = re.findall(r'((?=[A-Z\_]?)[A-Z]?[A-Za-z][a-z]+)', string) or []
262
+ if titleCase and stringParts:
263
+ return joiner.join(i.title() for i in stringParts)
264
+ return joiner.join(stringParts)
265
+
266
+
267
+ @lru_cache(maxsize=1024)
268
+ def pluralize(word: str) -> str:
269
+ if re.search('[sxz]$', word):
270
+ if len(word) <= 2:
271
+ return word
272
+ return re.sub('$', 'es', word)
273
+ elif re.search('[^aeioudgkprt]h$', word):
274
+ return re.sub('$', 'es', word)
275
+ elif re.search('[aeiou]y$', word):
276
+ return re.sub('y$', 'ies', word)
277
+ else:
278
+ return f'{word}s'
279
+
280
+
281
+ class Infix:
282
+ def __init__(self, function=lambda x, y: x if x is not None else y):
283
+ self.function = function
284
+
285
+ def __ror__(self, other):
286
+ return Infix(lambda x, self=self, other=other: self.function(other, x))
287
+
288
+ def __or__(self, other):
289
+ return self.function(other)
290
+
291
+ def __rlshift__(self, other):
292
+ return Infix(lambda x, self=self, other=other: self.function(other, x))
293
+
294
+ def __rshift__(self, other):
295
+ return self.function(other)
296
+
297
+ def __call__(self, value1, value2):
298
+ return self.function(value1, value2)
299
+
300
+ def __rmatmul__(self, other):
301
+ return Infix(lambda x, self=self, other=other: self.function(other, x))
302
+
303
+ def __matmul__(self, other):
304
+ return self.function(other)
305
+
306
+
307
+ class _Empty:
308
+
309
+ def __bool__(self) -> bool:
310
+ return True
311
+
312
+ def __str__(self) -> str:
313
+ return ''
314
+
315
+ def __repr__(self) -> str:
316
+ return ''
317
+
318
+ def __iter__(self) -> iter:
319
+ return iter(())
320
+
321
+ def __getitem__(self, item: object) -> object:
322
+ return self
323
+
324
+ def __getattr__(self, item):
325
+ return self
326
+
327
+ def __call__(self, *args, **kwargs):
328
+ return self
329
+
330
+ def __len__(self) -> int:
331
+ return 0
332
+
333
+ def __contains__(self, item: object) -> bool:
334
+ return False
335
+
336
+ def __int__(self) -> int:
337
+ return 0
338
+
339
+ def __float__(self) -> float:
340
+ return 0.0
341
+
342
+
343
+ NotNone: Final = Infix()
344
+ empty: Final = _Empty()
345
+ UnsetKwarg: Final = object()
346
+ Unset: Final = object()
347
+
348
+
349
+ def getFrom(
350
+ key: Hashable | str | Tuple[Hashable | str, ...],
351
+ *objs: Mapping | object,
352
+ default: Any = UnsetKwarg,
353
+ expectedType: type | Tuple[type, ...] = object,
354
+ factory: Callable[[Any], Any] = lambda x: x,
355
+ ignore: Set[Any] = None,
356
+ findAll: bool = False,
357
+ pop: bool = False,
358
+ ):
359
+ """
360
+ Returns the first acceptable attr or value from a list of objects
361
+ :param objs: The mapping or object to search.
362
+ :type objs: Mapping | object
363
+ :param key: The keys to search for.
364
+ :type key: Hashable | str
365
+ :param default: The default value to return if the key is not found.
366
+ :type default: Any
367
+ :return: The value of the key in the mapping or the default value.
368
+ :rtype: Any
369
+ """
370
+ if ignore is None:
371
+ ignore = set()
372
+ if not isinstance(key, tuple):
373
+ key = (key,)
374
+ if findAll:
375
+ found = []
376
+ for obj, subKey in product(objs, key):
377
+ # NB: the miss sentinel here must be UnsetKwarg, NOT `default`. Using
378
+ # `default` makes the first object short-circuit the whole search --
379
+ # a miss returns the caller's default, which then passes the
380
+ # is-not-unset/type checks below and returns immediately, so every
381
+ # remaining object is unreachable. `default` is only correct once the
382
+ # search is exhausted (see the return at the end).
383
+ # the ABC, not typing.Mapping: isinstance against the typing alias goes through a Python-level __subclasscheck__
384
+ if isinstance(obj, _MappingABC):
385
+ value = obj.get(subKey, UnsetKwarg)
386
+ else:
387
+ value = getattr(obj, subKey, UnsetKwarg)
388
+ if value is not UnsetKwarg and value not in ignore and isinstance(value, expectedType):
389
+ if pop and (_pop := getattr(obj, 'pop', None)) is not None:
390
+ _pop(subKey)
391
+ if not findAll:
392
+ return factory(value)
393
+ else:
394
+ found.append(factory(value))
395
+ if findAll:
396
+ return found
397
+ elif default is UnsetKwarg:
398
+ raise KeyError(key)
399
+ return default