endpoint_helpers.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. """
  13. Helpful utility functions and classes in relation to exploring API endpoints
  14. with the aim for a user-friendly interface.
  15. """
  16. import math
  17. import re
  18. from typing import TYPE_CHECKING
  19. from ..repocard_data import ModelCardData
  20. if TYPE_CHECKING:
  21. from ..hf_api import ModelInfo
  22. def _is_emission_within_threshold(model_info: "ModelInfo", minimum_threshold: float, maximum_threshold: float) -> bool:
  23. """Checks if a model's emission is within a given threshold.
  24. Args:
  25. model_info (`ModelInfo`):
  26. A model info object containing the model's emission information.
  27. minimum_threshold (`float`):
  28. A minimum carbon threshold to filter by, such as 1.
  29. maximum_threshold (`float`):
  30. A maximum carbon threshold to filter by, such as 10.
  31. Returns:
  32. `bool`: Whether the model's emission is within the given threshold.
  33. """
  34. if minimum_threshold is None and maximum_threshold is None:
  35. raise ValueError("Both `minimum_threshold` and `maximum_threshold` cannot both be `None`")
  36. if minimum_threshold is None:
  37. minimum_threshold = -1
  38. if maximum_threshold is None:
  39. maximum_threshold = math.inf
  40. card_data = getattr(model_info, "card_data", None)
  41. if card_data is None or not isinstance(card_data, (dict, ModelCardData)):
  42. return False
  43. # Get CO2 emission metadata
  44. emission = card_data.get("co2_eq_emissions", None)
  45. if isinstance(emission, dict):
  46. emission = emission["emissions"]
  47. if not emission:
  48. return False
  49. # Filter out if value is missing or out of range
  50. matched = re.search(r"\d+\.\d+|\d+", str(emission))
  51. if matched is None:
  52. return False
  53. emission_value = float(matched.group(0))
  54. return minimum_threshold <= emission_value <= maximum_threshold