Skip to content

Commit

Permalink
Implements editing
Browse files Browse the repository at this point in the history
  • Loading branch information
anneschuth committed Oct 20, 2024
1 parent bcc19bd commit a074bb7
Show file tree
Hide file tree
Showing 20 changed files with 493 additions and 272 deletions.
55 changes: 51 additions & 4 deletions amt/api/deps.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import logging
import typing
from collections.abc import Sequence
from enum import Enum
from os import PathLike
from typing import Any, AnyStr, TypeVar

from fastapi import Request
from fastapi.responses import HTMLResponse
Expand All @@ -10,6 +12,7 @@
from starlette.templating import _TemplateResponse # pyright: ignore [reportPrivateUsage]

from amt.api.http_browser_caching import url_for_cache
from amt.api.localizable import LocalizableEnum
from amt.api.navigation import NavigationItem, get_main_menu
from amt.core.authorization import get_user
from amt.core.config import VERSION, get_settings
Expand All @@ -24,6 +27,9 @@
supported_translations,
time_ago,
)
from amt.schema.localized_value_item import LocalizedValueItem

T = TypeVar("T", bound=Enum | LocalizableEnum)

logger = logging.getLogger(__name__)

Expand All @@ -47,12 +53,49 @@ def get_undefined_behaviour() -> type[Undefined]:
return StrictUndefined if get_settings().DEBUG else Undefined


def get_nested(obj: Any, attr_path: str) -> Any: # noqa: ANN401
attrs = attr_path.lstrip(".").split(".")
for attr in attrs:
if hasattr(obj, attr):
obj = getattr(obj, attr)
elif isinstance(obj, dict) and attr in obj:
obj = obj[attr]
else:
obj = None
break
return obj


def nested_value(obj: Any, attr_path: str) -> Any: # noqa: ANN401
obj = get_nested(obj, attr_path)
if isinstance(obj, Enum):
return obj.value
return obj


def is_nested_enum(obj: Any, attr_path: str) -> bool: # noqa: ANN401
obj = get_nested(obj, attr_path)
return bool(isinstance(obj, Enum))


def nested_enum(obj: Any, attr_path: str, language: str) -> list[LocalizedValueItem]: # noqa: ANN401
nested_obj = get_nested(obj, attr_path)
if not isinstance(nested_obj, LocalizableEnum):
return []
enum_class = type(nested_obj)
return [e.localize(language) for e in enum_class if isinstance(e, LocalizableEnum)]


def nested_enum_value(obj: Any, attr_path: str, language: str) -> Any: # noqa: ANN401
return get_nested(obj, attr_path).localize(language)


# we use a custom override so we can add the translation per request, which is parsed in the Request object in kwargs
class LocaleJinja2Templates(Jinja2Templates):
def _create_env(
self,
directory: str | PathLike[typing.AnyStr] | typing.Sequence[str | PathLike[typing.AnyStr]],
**env_options: typing.Any, # noqa: ANN401
directory: str | PathLike[AnyStr] | Sequence[str | PathLike[AnyStr]],
**env_options: Any, # noqa: ANN401
) -> Environment:
env: Environment = super()._create_env(directory, **env_options) # pyright: ignore [reportUnknownMemberType, reportUnknownVariableType, reportArgumentType]
env.add_extension("jinja2.ext.i18n") # pyright: ignore [reportUnknownMemberType]
Expand All @@ -62,7 +105,7 @@ def TemplateResponse( # pyright: ignore [reportIncompatibleMethodOverride]
self,
request: Request,
name: str,
context: dict[str, typing.Any] | None = None,
context: dict[str, Any] | None = None,
status_code: int = 200,
headers: dict[str, str] | None = None,
media_type: str | None = None,
Expand Down Expand Up @@ -99,3 +142,7 @@ def Redirect(self, request: Request, url: str) -> HTMLResponse:
templates.env.filters["format_timedelta"] = format_timedelta # pyright: ignore [reportUnknownMemberType]
templates.env.filters["time_ago"] = time_ago # pyright: ignore [reportUnknownMemberType]
templates.env.globals.update(url_for_cache=url_for_cache) # pyright: ignore [reportUnknownMemberType]
templates.env.globals.update(nested_value=nested_value) # pyright: ignore [reportUnknownMemberType]
templates.env.globals.update(is_nested_enum=is_nested_enum) # pyright: ignore [reportUnknownMemberType]
templates.env.globals.update(nested_enum=nested_enum) # pyright: ignore [reportUnknownMemberType]
templates.env.globals.update(nested_enum_value=nested_enum_value) # pyright: ignore [reportUnknownMemberType]
68 changes: 25 additions & 43 deletions amt/api/lifecycles.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import logging
from enum import Enum
from collections.abc import Callable

from fastapi import Request

from amt.core.internationalization import get_current_translation
from amt.schema.lifecycle import Lifecycle
from ..schema.localized_value_item import LocalizedValueItem
from .localizable import LocalizableEnum, get_localized_enum, get_localized_enums

logger = logging.getLogger(__name__)


class Lifecycles(Enum):
class Lifecycles(LocalizableEnum):
ORGANIZATIONAL_RESPONSIBILITIES = "ORGANIZATIONAL_RESPONSIBILITIES"
PROBLEM_ANALYSIS = "PROBLEM_ANALYSIS"
DESIGN = "DESIGN"
Expand All @@ -20,39 +17,24 @@ class Lifecycles(Enum):
MONITORING_AND_MANAGEMENT = "MONITORING_AND_MANAGEMENT"
PHASING_OUT = "PHASING_OUT"

@property
def index(self) -> int:
return list(Lifecycles).index(self)


def get_lifecycle(key: Lifecycles | None, request: Request) -> Lifecycle | None:
"""
Given the key and translation, returns the translated text.
:param key: the key
:param request: request to get the current language
:return: a Lifecycle model with the correct translation
"""

if key is None:
return None

translations = get_current_translation(request)
_ = translations.gettext
# translations are determined at runtime, which is why we use the dictionary below
keys = {
Lifecycles.ORGANIZATIONAL_RESPONSIBILITIES: _("Organizational Responsibilities"),
Lifecycles.PROBLEM_ANALYSIS: _("Problem Analysis"),
Lifecycles.DESIGN: _("Design"),
Lifecycles.DATA_EXPLORATION_AND_PREPARATION: _("Data Exploration and Preparation"),
Lifecycles.DEVELOPMENT: _("Development"),
Lifecycles.VERIFICATION_AND_VALIDATION: _("Verification and Validation"),
Lifecycles.IMPLEMENTATION: _("Implementation"),
Lifecycles.MONITORING_AND_MANAGEMENT: _("Monitoring and Management"),
Lifecycles.PHASING_OUT: _("Phasing Out"),
}
return Lifecycle(id=key.value, name=keys[key])


def get_lifecycles(request: Request) -> list[Lifecycle | None]:
lifecycles: list[Lifecycle | None] = [get_lifecycle(lifecycle, request) for lifecycle in Lifecycles]
return lifecycles
@classmethod
def get_display_values(cls: type["Lifecycles"], _: Callable[[str], str]) -> dict["Lifecycles", str]:
return {
cls.ORGANIZATIONAL_RESPONSIBILITIES: _("Organizational Responsibilities"),
cls.PROBLEM_ANALYSIS: _("Problem Analysis"),
cls.DESIGN: _("Design"),
cls.DATA_EXPLORATION_AND_PREPARATION: _("Data Exploration and Preparation"),
cls.DEVELOPMENT: _("Development"),
cls.VERIFICATION_AND_VALIDATION: _("Verification and Validation"),
cls.IMPLEMENTATION: _("Implementation"),
cls.MONITORING_AND_MANAGEMENT: _("Monitoring and Management"),
cls.PHASING_OUT: _("Phasing Out"),
}


def get_localized_lifecycle(key: Lifecycles | None, request: Request) -> LocalizedValueItem | None:
return get_localized_enum(key, request)


def get_localized_lifecycles(request: Request) -> list[LocalizedValueItem | None]:
return get_localized_enums(Lifecycles, request)
43 changes: 43 additions & 0 deletions amt/api/localizable.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from collections.abc import Callable
from enum import Enum
from typing import TypeVar

from fastapi import Request

from amt.core.internationalization import get_requested_language, get_supported_translation, get_translation
from amt.schema.localized_value_item import LocalizedValueItem

T = TypeVar("T", bound="LocalizableEnum", covariant=True)


class LocalizableEnum(Enum):
@property
def index(self) -> int:
return list(self.__class__).index(self)

def localize(self, language: str) -> LocalizedValueItem:
translations = get_translation(get_supported_translation(language))
_ = translations.gettext
display_values = self.get_display_values(_)
return LocalizedValueItem(value=self.name, display_value=display_values[self])

@classmethod
def get_display_values(cls: type[T], _: Callable[[str], str]) -> dict[T, str]:
raise NotImplementedError("Subclasses must implement this method")


def get_localized_enum(key: LocalizableEnum | None, request: Request) -> LocalizedValueItem | None:
"""
Given the key and translation, returns the translated text.
:param key: the key
:param request: request to get the current language
:return: a LocalizedValueItem with the correct translation
"""
if key is None:
return None

return key.localize(get_requested_language(request))


def get_localized_enums(enum_class: type[T], request: Request) -> list[LocalizedValueItem | None]:
return [get_localized_enum(enum_value, request) for enum_value in enum_class]
59 changes: 25 additions & 34 deletions amt/api/publication_category.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,38 @@
import logging
from enum import Enum
from collections.abc import Callable

from fastapi import Request

from amt.core.internationalization import get_current_translation
from amt.schema.publication_category import PublicationCategory
from ..schema.localized_value_item import LocalizedValueItem
from .localizable import LocalizableEnum, get_localized_enum, get_localized_enums

logger = logging.getLogger(__name__)


class PublicationCategories(Enum):
class PublicationCategories(LocalizableEnum):
IMPACTVOL_ALGORITME = "impactvol algoritme"
NIET_IMPACTVOL_ALGORITME = "niet-impactvol algoritme"
HOOG_RISICO_AI = "hoog-risico AI"
GEEN_HOOG_RISICO_AI = "geen hoog-risico AI"
VERBODEN_AI = "verboden AI"
UITZONDERING_VAN_TOEPASSING = "uitzondering van toepassing"

@classmethod
def get_display_values(
cls: type["PublicationCategories"], _: Callable[[str], str]
) -> dict["PublicationCategories", str]:
return {
cls.IMPACTVOL_ALGORITME: _("Impactful algorithm"),
cls.NIET_IMPACTVOL_ALGORITME: _("Non-impactful algorithm"),
cls.HOOG_RISICO_AI: _("High-risk AI"),
cls.GEEN_HOOG_RISICO_AI: _("No high-risk AI"),
cls.VERBODEN_AI: _("Forbidden AI"),
cls.UITZONDERING_VAN_TOEPASSING: _("Exception of application"),
}


def get_localized_publication_category(
key: PublicationCategories | None, request: Request
) -> LocalizedValueItem | None:
return get_localized_enum(key, request)


def get_publication_category(key: PublicationCategories | None, request: Request) -> PublicationCategory | None:
"""
Given the key and translation, returns the translated text.
:param key: the key
:param request: request to get the current language
:return: a Publication Category model with the correct translation
"""

if key is None:
return None

translations = get_current_translation(request)
_ = translations.gettext
# translations are determined at runtime, which is why we use the dictionary below
keys = {
PublicationCategories.IMPACTVOL_ALGORITME: _("Impactful algorithm"),
PublicationCategories.NIET_IMPACTVOL_ALGORITME: _("Non-impactful algorithm"),
PublicationCategories.HOOG_RISICO_AI: _("High-risk AI"),
PublicationCategories.GEEN_HOOG_RISICO_AI: _("No high-risk AI"),
PublicationCategories.VERBODEN_AI: _("Forbidden AI"),
PublicationCategories.UITZONDERING_VAN_TOEPASSING: _("Exception of application"),
}
return PublicationCategory(id=key.name, name=keys[key])


def get_publication_categories(request: Request) -> list[PublicationCategory | None]:
return [get_publication_category(p, request) for p in PublicationCategories]
def get_localized_publication_categories(request: Request) -> list[LocalizedValueItem | None]:
return get_localized_enums(PublicationCategories, request)
Loading

0 comments on commit a074bb7

Please sign in to comment.