utils.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import aiohttp
  2. import asyncio
  3. def get_engine(engine_name, engines, default_engine):
  4. """
  5. Returns the corresponding engine for `engine_name` from `engines`, or
  6. `default_engine` if no corresponding engine is found.
  7. """
  8. return next(
  9. (engine for engine in engines if engine.name == engine_name), default_engine
  10. )
  11. async def to_full_name(lang_code, engine, type_="source"):
  12. """
  13. Returns the full name of `lang_code` from
  14. `engine.get_supported_languages()` ("auto" can also be passed), or `None`
  15. if no corresponding name could be found.
  16. """
  17. lang_code = lang_code.lower()
  18. if lang_code == "auto":
  19. return "Autodetect"
  20. supported_langs = None
  21. if type_ == "source":
  22. supported_langs = await engine.get_supported_source_languages()
  23. elif type_ == "target":
  24. supported_langs = await engine.get_supported_target_languages()
  25. for key, value in supported_langs.items():
  26. if value.lower() == lang_code:
  27. return key
  28. return None
  29. async def to_lang_code(lang, engine, type_="source"):
  30. """
  31. Returns the corresponding language code of `lang` from
  32. `engine.get_supported_languages()` (a language code can also be passed,
  33. which if valid, will be returned as-is). "Autodetect" or "auto" can also be
  34. passed. If no match could be found, returns `None`.
  35. """
  36. lang = lang.lower()
  37. if lang == "autodetect" or lang == "auto":
  38. return "auto"
  39. supported_langs = None
  40. if type_ == "source":
  41. supported_langs = await engine.get_supported_source_languages()
  42. elif type_ == "target":
  43. supported_langs = await engine.get_supported_target_languages()
  44. for key, value in supported_langs.items():
  45. if key.lower() == lang or value.lower() == lang:
  46. return value
  47. return None
  48. # only the parameters that are ever being used will be added here to avoid clutter
  49. async def async_get(url: str, params={}) -> str:
  50. async with aiohttp.ClientSession() as session:
  51. async with session.get(url, params=params) as resp:
  52. return await resp.text()
  53. async def async_post(url: str, headers={}, data="") -> str:
  54. async with aiohttp.ClientSession() as session:
  55. async with session.post(url, headers=headers, data=data) as resp:
  56. return await resp.text()