util.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from pathlib import Path
  2. import unfccc_di_api
  3. # imports for copied functions
  4. import pycountry
  5. root_path = Path(__file__).parents[2].absolute()
  6. root_path = root_path.resolve()
  7. log_path = root_path / "log"
  8. code_path = root_path / "code"
  9. downloaded_data_path = root_path / "downloaded_data" / "UNFCCC"
  10. extracted_data_path = root_path / "extracted_data" / "UNFCCC"
  11. reader = unfccc_di_api.UNFCCCApiReader()
  12. nAI_countries = list(reader.non_annex_one_reader.parties["code"])
  13. AI_countries = list(reader.annex_one_reader.parties["code"])
  14. class NoDIDataError(Exception):
  15. pass
  16. # the following is copied from other sub-packages
  17. # TODO: move these fucntions to common location to allow easy importing into all modules
  18. custom_country_mapping = {
  19. "EUA": "European Union",
  20. "EUC": "European Union",
  21. "FRK": "France",
  22. "DKE": "Denmark",
  23. "DNM": "Denmark",
  24. "GBK": "United Kingdom of Great Britain and Northern Ireland",
  25. }
  26. def get_country_name(
  27. country_code: str,
  28. ) -> str:
  29. """get country name from code """
  30. if country_code in custom_country_mapping:
  31. country_name = custom_country_mapping[country_code]
  32. else:
  33. try:
  34. country = pycountry.countries.get(alpha_3=country_code)
  35. country_name = country.name
  36. except:
  37. raise ValueError(f"Country code {country_code} can not be mapped to "
  38. f"any country")
  39. return country_name
  40. def get_country_code(
  41. country_name: str,
  42. )->str:
  43. """
  44. obtain country code. If the input is a code it will be returned, if the input
  45. is not a three letter code a search will be performed
  46. Parameters
  47. __________
  48. country_name: str
  49. Country code or name to get the three-letter code for.
  50. """
  51. try:
  52. # check if it's a 3 letter code
  53. country = pycountry.countries.get(alpha_3=country_name)
  54. country_code = country.alpha_3
  55. except:
  56. try:
  57. country = pycountry.countries.search_fuzzy(country_name)
  58. except:
  59. raise ValueError(f"Country name {country_name} can not be mapped to "
  60. f"any country code")
  61. if len(country) > 1:
  62. country_code = None
  63. for current_country in country:
  64. if current_country.name == country_name:
  65. country_code = current_country.alpha_3
  66. if country_code is None:
  67. raise ValueError(f"Country name {country_name} has {len(country)} "
  68. f"possible results for country codes.")
  69. country_code = country[0].alpha_3
  70. return country_code