Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
464 lines (389 loc) · 15.6 KB
/
Copy path__init__.py
File metadata and controls
464 lines (389 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# -*- coding: utf-8 -*-
"""
Unit converter based on the [Pint Python library](https://pint.readthedocs.io/en/stable/).
Usage examples:
- `convert 180 minutes to hrs`
- `convert 100 km to miles`
- `convert 88 mph to kph`
- `convert 32 degrees F to C`
- `convert 3.14159 rad to degrees`
- `convert 100 USD to EUR`
"""
import json
import re
import traceback
from datetime import datetime
from pathlib import Path
from typing import Any, Optional
from urllib.error import URLError
from urllib.request import urlopen
import inflect
import pint
from albert import *
md_iid = "5.0"
md_version = "1.8.2"
md_name = "Unit Converter"
md_description = "Convert between units"
md_license = "MIT"
md_url = "https://github.com/albertlauncher/albert-plugin-python-unit-converter"
md_lib_dependencies = ["pint", "inflect"]
md_authors = ["@DenverCoder1", "@Pete-Hamlin"]
md_maintainers = ["@DenverCoder1", "@Pete-Hamlin"]
class ConversionResult:
"""A class to represent the result of a unit conversion"""
def __init__(
self,
from_amount: float,
from_unit: str,
to_amount: float,
to_unit: str,
dimensionality: str,
source: str = "",
):
"""Initialize the ConversionResult
Args:
from_amount (float): The amount to convert from
from_unit (str): The unit to convert from
to_amount (float): The resulting amount
to_unit (str): The unit converted to
dimensionality (str): The dimensionality of the result
source (str): The source of the conversion for attribution
"""
self.from_amount = from_amount
self.from_unit = from_unit
self.to_amount = to_amount
self.to_unit = to_unit
self.dimensionality = dimensionality
self.source = source
self.display_names: dict[str, str] = Plugin.config["display_names"]
self.inflect_engine = inflect.engine()
def __pluralize_unit(self, unit: str) -> str:
"""Pluralize the unit
Args:
unit (str): The unit to pluralize
Returns:
str: The pluralized unit
"""
# if all characters are uppercase, don't pluralize
if unit.isupper():
return unit
return self.inflect_engine.plural(unit)
def __display_unit_name(self, amount: float, unit: str) -> str:
"""Display the name of the unit with plural if necessary
Args:
amount (float): The amount to display
unit (str): The unit to display
Returns:
str: The name of the unit
"""
unit = self.__pluralize_unit(unit) if amount != 1 else unit
return self.display_names.get(unit, unit)
@staticmethod
def __format_float(num: float) -> str:
"""Format a float to remove trailing zeros and avoid scientific notation
Args:
num (float): The number to format
Returns:
str: The formatted number
"""
# format the float to remove trailing zeros and decimal point
precision: int = Plugin.config["precision"]
return f"{num:.{precision}f}".rstrip("0").rstrip(".")
@property
def formatted_result(self) -> str:
"""Return the formatted result amount and unit"""
units = self.__display_unit_name(self.to_amount, self.to_unit)
return f"{self.__format_float(self.to_amount)} {units}"
@property
def formatted_from(self) -> str:
"""Return the formatted from amount and unit"""
units = self.__display_unit_name(self.from_amount, self.from_unit)
result = f"{self.__format_float(self.from_amount)} {units}"
if self.source:
result += f" ({self.source})"
return result
@property
def icon(self) -> str:
"""Return the icon for the result's dimensionality"""
# strip characters from the dimensionality if not alphanumeric or underscore
dimensionality = re.sub(r"\W", "", self.dimensionality)
return f"{dimensionality}.svg"
def __repr__(self):
"""Return the representation of the result"""
return f"{self.formatted_from} = {self.formatted_result}"
class UnitConverter:
"""Base class for unit converters"""
def __init__(self):
"""Initialize the UnitConverter"""
self.aliases: dict[str, str] = Plugin.config["aliases"]
def convert(self, amount: float, from_unit: str, to_unit: str) -> ConversionResult:
"""Convert a unit to another unit
Args:
amount (float): The amount to convert
from_unit (str): The unit to convert from
to_unit (str): The unit to convert to
Returns:
ConversionResult: Object containing information about the conversion result
"""
raise NotImplementedError
class StandardUnitConverter(UnitConverter):
"""Class to convert standard units of measurement"""
def __init__(self):
"""Initialize the StandardUnitConverter"""
self.units = pint.UnitRegistry()
super().__init__()
def _get_unit(self, unit: str) -> pint.Unit:
"""Check if the unit is a valid unit and return it
If any aliases are found, replace the unit with the alias
If the unit is not valid, check if making it lowercase will fix it
If not, raise the UndefinedUnitError
Args:
unit (str): The unit to check
Returns:
pint.Unit: The unit
Raises:
pint.errors.UndefinedUnitError: If the unit is not valid
"""
unit = self.aliases.get(unit, unit)
if unit in self.units:
# return the unit if it is valid
return self.units.__getattr__(unit)
# check if the lowercase version is a valid unit
return self.units.__getattr__(unit.lower())
def convert(self, amount: float, from_unit: str, to_unit: str) -> ConversionResult:
"""Convert a unit to another unit
Args:
amount (float): The amount to convert
from_unit (str): The unit to convert from
to_unit (str): The unit to convert to
Returns:
ConversionResult: Object containing information about the conversion result
Raises:
pint.errors.UndefinedUnitError: If the unit is not valid
pint.errors.DimensionalityError: If the units are not compatible
"""
input_unit = self.units.Quantity(amount, self._get_unit(from_unit))
output_unit = self._get_unit(to_unit)
result = input_unit.to(output_unit)
return ConversionResult(
from_amount=float(amount),
from_unit=str(self._get_unit(from_unit)),
to_amount=result.magnitude,
to_unit=str(result.units),
dimensionality=str(self.units._get_dimensionality(result.units)),
)
class UnknownCurrencyError(Exception):
"""Exception to raise when an unknown currency is passed to convert"""
def __init__(self, currency: str):
"""Initialize the UnknownCurrencyError
Args:
currency (str): The unknown currency
"""
self.currency = currency
super().__init__(f"Unknown currency: {currency}")
class CurrencyConverter(UnitConverter):
"""Class to convert currencies"""
API_URL = "https://open.er-api.com/v6/latest/USD"
ATTRIBUTION = "Rates by https://www.exchangerate-api.com"
def __init__(self):
"""Initialize the CurrencyConverter"""
self.last_update = datetime.now()
self.currencies = self._get_currencies()
super().__init__()
def _get_currencies(self) -> dict[str, float]:
"""Get the currencies from the API
Returns:
dict[str, float]: The currencies
"""
try:
with urlopen(self.API_URL) as response:
data = json.loads(response.read().decode("utf-8"))
if not data or "rates" not in data:
info("No currencies found")
return {}
info(f"Currencies updated")
return data["rates"]
except URLError as error:
warning(f"Error getting currencies: {error}")
return {}
def get_currency(self, currency: str) -> Optional[str]:
"""Get the currency name normalized using aliases and capitalization
Args:
currency (str): The currency to normalize
Returns:
Optional[str]: The currency name or None if not found
"""
# update the currencies every 24 hours
if not self.currencies or (datetime.now() - self.last_update).days >= 1:
self.currencies = self._get_currencies()
self.last_update = datetime.now()
currency = self.aliases.get(currency, currency).upper()
return currency if currency in self.currencies else None
def convert(self, amount: float, from_unit: str, to_unit: str) -> ConversionResult:
"""Convert a currency to another currency
Args:
amount (float): The amount to convert
from_unit (str): The currency to convert from
to_unit (str): The currency to convert to
Returns:
ConversionResult: Object containing information about the conversion result
Raises:
UnknownCurrencyError: If the currency is not valid
"""
# get the currency rates
from_currency = self.get_currency(from_unit)
to_currency = self.get_currency(to_unit)
# convert the currency
if from_currency is None:
raise UnknownCurrencyError(from_unit)
if to_currency is None:
raise UnknownCurrencyError(to_unit)
from_rate = self.currencies[from_currency]
to_rate = self.currencies[to_currency]
result = amount * to_rate / from_rate
return ConversionResult(
from_amount=float(amount),
from_unit=from_currency,
to_amount=result,
to_unit=to_currency,
dimensionality="currency",
source=self.ATTRIBUTION,
)
class Plugin(PluginInstance, GlobalQueryHandler):
"""The plugin class"""
config: dict[str, Any] = {
# Maximum number of decimal places for precision
"precision": 12,
# Unit aliases to replace when parsing
# Units may be added here to override the default behavior or create aliases for existing units
# The alias is the key, the string to replace it with is the value
"aliases": {
"sec": "second",
"kph": "km/hour",
"km/h": "km/hour",
"mph": "mile/hour",
"degrees F": "degF",
"degrees C": "degC",
"F": "degF",
"C": "degC",
},
# Display names for units
# Units may be added here to override the default display names
# The string version of the unit is the key, the display name to replace with is the value
# Both the unpluralized and the pluralized version should be included
"display_names": {
"degree_Celsius": "°C",
"degree_Celsiuses": "°C",
"degree_Fahrenheit": "°F",
"degree_Fahrenheits": "°F",
"mile / hour": "mph",
"mile / hours": "mph",
"kilometer / hour": "km/h",
"kilometer / hours": "km/h",
"kilometer_per_hour": "km/h",
"kilometer_per_hours": "km/h",
},
}
def __init__(self):
PluginInstance.__init__(self)
GlobalQueryHandler.__init__(self)
self.unit_convert_regex = re.compile(
r"(?P<from_amount>-?\d+\.?\d*)\s?(?P<from_unit>.*)\s(?:to|in)\s(?P<to_unit>.*)",
re.I,
)
self.unit_converter = StandardUnitConverter()
self.currency_converter = CurrencyConverter()
def defaultTrigger(self):
return "convert "
def synopsis(self, query):
return "<amount> <from_unit> to <to_unit>"
def items(self, ctx):
if query_string := ctx.query.strip():
yield self.match_query(query_string)
def rankItems(self, ctx):
return [RankItem(item=item, score=1) for item in self.match_query(ctx.query.strip())]
def match_query(self, query_string: str):
match = self.unit_convert_regex.fullmatch(query_string)
if match:
try:
return self._get_items(
float(match.group("from_amount")),
match.group("from_unit").strip(),
match.group("to_unit").strip(),
)
except Exception as error:
warning(f"Error: {error}")
tb = "".join(traceback.format_exception(error.__class__, error, error.__traceback__))
warning(tb)
info("Something went wrong. Make sure you're using the correct format.")
return []
@staticmethod
def _create_item(text: str, subtext: str, icon: str = "") -> Item:
"""Create an Item from a text and subtext
Args:
text (str): The text to display
subtext (str): The subtext to display
icon (Optional[str]): The icon to display. If not specified, the default icon will be used
Returns:
Item: The item to be added to the list of results
"""
icon_path = Path(__file__).parent / "icons" / icon
if not icon or not icon_path.exists():
warning(f"Icon {icon} does not exist")
icon_path = Path(__file__).parent / "icons" / "unit_converter.svg"
return StandardItem(
id=str(icon_path),
icon_factory=lambda: Icon.image(icon_path),
text=text,
subtext=subtext,
actions=[
Action(
id="copy",
text="Copy result to clipboard",
callable=lambda: setClipboardText(text=text),
)
],
)
def _get_converter(self, from_unit: str, to_unit: str) -> UnitConverter:
"""Get the converter to use
Args:
from_unit (str): The unit to convert from
to_unit (str): The unit to convert to
Returns:
UnitConverter: The converter to use
"""
if (
self.currency_converter.get_currency(from_unit) is not None
and self.currency_converter.get_currency(to_unit) is not None
):
return self.currency_converter
return self.unit_converter
def _get_items(self, amount: float, from_unit: str, to_unit: str) -> list[Item]:
"""Generate the Albert items to display for the query
Args:
amount (float): The amount to convert from
from_unit (str): The unit to convert from
to_unit (str): The unit to convert to
Returns:
List[Item]: The list of items to display
"""
try:
converter = self._get_converter(from_unit, to_unit)
result = converter.convert(amount, from_unit, to_unit)
# return the result
return [
self._create_item(
result.formatted_result,
f"Converted from {result.formatted_from}",
result.icon,
)
]
except pint.errors.DimensionalityError as e:
warning(f"DimensionalityError: {e}")
return [self._create_item(f"Unable to convert {amount} {from_unit} to {to_unit}", str(e))]
except pint.errors.UndefinedUnitError as e:
warning(f"UndefinedUnitError: {e}")
return []
except UnknownCurrencyError as e:
warning(f"UnknownCurrencyError: {e}")
return []