diff --git a/anyway/accidents_around_schools.py b/anyway/accidents_around_schools.py index 253324788..12a8b972f 100644 --- a/anyway/accidents_around_schools.py +++ b/anyway/accidents_around_schools.py @@ -5,7 +5,7 @@ import sqlalchemy as sa from sqlalchemy import or_ -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.models import AccidentMarker, Involved, School from anyway.app_and_db import db @@ -57,8 +57,8 @@ def acc_inv_query(longitude, latitude, distance, start_date, end_date, school): .filter(AccidentMarker.provider_and_id == Involved.provider_and_id) .filter( or_( - (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_1_CODE), - (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_3_CODE), + (AccidentMarker.provider_code == BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE), + (AccidentMarker.provider_code == BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE), ) ) .filter(AccidentMarker.created >= start_date) diff --git a/anyway/app_and_db.py b/anyway/app_and_db.py index 80e4cbf9d..45ffa2bd2 100644 --- a/anyway/app_and_db.py +++ b/anyway/app_and_db.py @@ -3,7 +3,7 @@ import flask_restx from http import HTTPStatus -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.config import SERVER_ENV @@ -28,9 +28,9 @@ def set_render_root_function(self, func): def get_cors_config() -> dict: - cors_site_list = BE_CONST.ANYWAY_CORS_SITE_LIST_PROD + cors_site_list = BackEndConstants.ANYWAY_CORS_SITE_LIST_PROD if SERVER_ENV == "dev": - cors_site_list = BE_CONST.ANYWAY_CORS_SITE_LIST_DEV + cors_site_list = BackEndConstants.ANYWAY_CORS_SITE_LIST_DEV return { r"/location-subscription": {"origins": "*"}, diff --git a/anyway/backend_constants.py b/anyway/backend_constants.py deleted file mode 100644 index 25a2ebe07..000000000 --- a/anyway/backend_constants.py +++ /dev/null @@ -1,295 +0,0 @@ -from enum import Enum -from typing import List, Iterable - -try: - from flask_babel import _ -except ImportError: - pass -# noinspection PyProtectedMember - - -class BackEndConstants(object): - - MARKER_TYPE_ACCIDENT = 1 - MARKER_TYPE_DISCUSSION = 2 - - CBS_ACCIDENT_TYPE_1_CODE = 1 - UNITED_HATZALA_CODE = 2 - CBS_ACCIDENT_TYPE_3_CODE = 3 - RSA_PROVIDER_CODE = 4 - - BIKE_ACCIDENTS = 21 - - AGE_GROUPS_NUMBER = 18 - - ALL_AGE_GROUPS_LIST = list(range(1, AGE_GROUPS_NUMBER + 1)) + [99] - - # This class should be correlated with the Roles table - class Roles2Names(Enum): - Admins = "admins" - Or_yarok = "or_yarok" - Authenticated = "authenticated" - - # This is a type for the 'road_type' table field name - ROAD_TYPE_NOT_IN_CITY_IN_INTERSECTION = 3 - ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION = 4 - NON_CITY_ROAD_TYPES = [ - ROAD_TYPE_NOT_IN_CITY_IN_INTERSECTION, - ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION, - ] - - # other global constants (python only) - DEFAULT_NUMBER_OF_YEARS_AGO = 5 - - # years ago to store in cache - INFOGRAPHICS_CACHE_YEARS_AGO = [1, 3, 5, 8] - SOURCE_MAPPING = {"walla": "וואלה", "twitter": "מד״א", "ynet": "ynet"} - - UNKNOWN = "UNKNOWN" - DEFAULT_REDIRECT_URL = "https://anyway-infographics.web.app/" - ANYWAY_CORS_SITE_LIST_PROD = [ - "https://anyway-infographics-staging.web.app", - "https://anyway-infographics.web.app", - "https://www.anyway.co.il", - "https://anyway-infographics-demo.web.app", - "https://media.anyway.co.il", - "https://dev.anyway.co.il", - ] - - ANYWAY_CORS_SITE_LIST_DEV = ANYWAY_CORS_SITE_LIST_PROD + [ - "https://dev.anyway.co.il", - "http://localhost:3000", - "https://localhost:3000", - "http://127.0.0.1:3000", - "https://127.0.0.1:3000", - ] - - class ResolutionCategories(Enum): - REGION = "מחוז" - DISTRICT = "נפה" - CITY = "עיר" - STREET = "רחוב" - URBAN_JUNCTION = "צומת עירוני" - SUBURBAN_ROAD = "כביש בינעירוני" - SUBURBAN_JUNCTION = "צומת בינעירוני" - OTHER = "אחר" - - SUPPORTED_RESOLUTIONS: List[ResolutionCategories] = [ - ResolutionCategories.STREET, - ResolutionCategories.SUBURBAN_ROAD, - ] - - class Source(Enum): - @classmethod - def _missing_(cls, value): - for member in cls: - if member.value == value.lower(): - return member - - YNET = "ynet" - WALLA = "walla" - TWITTER = "twitter" - - SUPPORTED_SOURCES: List[Source] = [ - Source.YNET, - Source.WALLA, - Source.TWITTER, - ] - - # If in the future there will be a number of organizations or a need for a dynamic setting change, move this - # data to a table in the DB. - OR_YAROK_WIDGETS = [ - "accident_count_by_severity", - "most_severe_accidents_table", - "most_severe_accidents", - "vision_zero_2_plus_1", - "head_on_collisions_comparison", - ] - - LKEY = "label_key" - VAL = "value" - SERIES = "series" - - -BE_CONST = BackEndConstants() - - -class LabeledCode(Enum): - def get_label(self) -> str: - return type(self).labels()[self] - - @classmethod - def codes(cls: Iterable) -> List[int]: - if isinstance(cls, Iterable): - return [a.value for a in cls] - else: - raise NotImplementedError(f"{cls}: needs to be derived from Enum") - - @classmethod - def labels(cls): - return {} - - -# This is a type for the field 'injury_severity' in the table 'involved_markers_hebrew' -class InjurySeverity(LabeledCode): - KILLED = 1 - SEVERE_INJURED = 2 - LIGHT_INJURED = 3 - - @classmethod - def labels(cls): - return { - InjurySeverity.KILLED: "killed", - InjurySeverity.SEVERE_INJURED: "severe injured", - InjurySeverity.LIGHT_INJURED: "light injured", - } - - -try: - _("killed") - _("severe injured") - _("light injured") -except NameError: - pass - - -# This is a type for the 'accident_severity' table field name -class AccidentSeverity(LabeledCode): - FATAL = 1 - SEVERE = 2 - LIGHT = 3 - - @classmethod - def labels(cls): - return { - AccidentSeverity.FATAL: "fatal", - AccidentSeverity.SEVERE: "severe", - AccidentSeverity.LIGHT: "light", - } - - -class AccidentType(LabeledCode): - PEDESTRIAN_INJURY = 1 - COLLISION_OF_FRONT_TO_SIDE = 2 - COLLISION_OF_FRONT_TO_REAR_END = 3 - COLLISION_OF_SIDE_TO_SIDE_LATERAL = 4 - HEAD_ON_FRONTAL_COLLISION = 5 - COLLISION_WITH_A_STOPPED_NON_PARKED_VEHICLE = 6 - COLLISION_WITH_A_PARKED_VEHICLE = 7 - COLLISION_WITH_AN_INANIMATE_OBJECT = 8 - SWERVING_OFF_THE_ROAD_OR_ONTO_THE_PAVEMENT = 9 - OVERTURNED_VEHICLE = 10 - SKID = 11 - INJURY_OF_A_PASSENGER_IN_A_VEHICLE = 12 - A_FALL_FROM_A_MOVING_VEHICLE = 13 - FIRE = 14 - OTHER = 15 - COLLISION_OF_REAR_END_TO_FRONT = 17 - COLLISION_OF_REAR_END_TO_SIDE = 18 - COLLISION_WITH_AN_ANIMAL = 19 - DAMAGE_CAUSED_BY_A_FALLING_LOAD_OFF_A_VEHICLE = 20 - - @classmethod - def labels(cls): - return { - AccidentType.PEDESTRIAN_INJURY: "Pedestrian injury", - AccidentType.COLLISION_OF_FRONT_TO_SIDE: "Collision of front to side", - AccidentType.COLLISION_OF_FRONT_TO_REAR_END: "Collision of front to rear-end", - AccidentType.COLLISION_OF_SIDE_TO_SIDE_LATERAL: "Collision of side to side (lateral)", - AccidentType.HEAD_ON_FRONTAL_COLLISION: "Head-on frontal collision", - AccidentType.COLLISION_WITH_A_STOPPED_NON_PARKED_VEHICLE: "Collision with a stopped non-parked vehicle", - AccidentType.COLLISION_WITH_A_PARKED_VEHICLE: "Collision with a parked vehicle", - AccidentType.COLLISION_WITH_AN_INANIMATE_OBJECT: "Collision with an inanimate object", - AccidentType.SWERVING_OFF_THE_ROAD_OR_ONTO_THE_PAVEMENT: "Swerving off the road or onto the pavement", - AccidentType.OVERTURNED_VEHICLE: "Overturned vehicle", - AccidentType.SKID: "Skid", - AccidentType.INJURY_OF_A_PASSENGER_IN_A_VEHICLE: "Injury of a passenger in a vehicle", - AccidentType.A_FALL_FROM_A_MOVING_VEHICLE: "A fall from a moving vehicle", - AccidentType.FIRE: "Fire", - AccidentType.OTHER: "Other", - AccidentType.COLLISION_OF_REAR_END_TO_FRONT: "Collision of rear-end to front", - AccidentType.COLLISION_OF_REAR_END_TO_SIDE: "Collision of rear-end to side", - AccidentType.COLLISION_WITH_AN_ANIMAL: "Collision with an animal", - AccidentType.DAMAGE_CAUSED_BY_A_FALLING_LOAD_OFF_A_VEHICLE: "Damage caused by a falling load off a vehicle", - } - - -class DriverType(LabeledCode): - PROFESSIONAL_DRIVER = 1 - PRIVATE_VEHICLE_DRIVER = 2 - OTHER_DRIVER = 3 - - @classmethod - def labels(cls): - return { - DriverType.PROFESSIONAL_DRIVER: "professional_driver", - DriverType.PRIVATE_VEHICLE_DRIVER: "private_vehicle_driver", - DriverType.OTHER_DRIVER: "other_driver", - } - - -class InjuredType(LabeledCode): - PEDESTRIAN = 1 - DRIVER_FOUR_WHEELS_AND_ABOVE = 2 - PASSENGER_FOUR_WHEELS_AND_ABOVE = 3 - DRIVER_MOTORCYCLE = 4 - PASSENGER_MOTORCYCLE = 5 - DRIVER_BICYCLE = 6 - PASSENGER_BICYCLE = 7 - DRIVER_UNKNOWN_VEHICLE = 8 - PASSENGER_UNKNOWN_VEHICLE = 9 - - @classmethod - def labels(cls): - return { - InjuredType.PEDESTRIAN: "Pedestrian", - InjuredType.DRIVER_FOUR_WHEELS_AND_ABOVE: "Driver of a vehicle with 4 wheel or more", - InjuredType.PASSENGER_FOUR_WHEELS_AND_ABOVE: "Passenger of a vehicle with 4 wheel or more", - InjuredType.DRIVER_MOTORCYCLE: "Motorcycle driver", - InjuredType.PASSENGER_MOTORCYCLE: "Motorcycle passenger", - InjuredType.DRIVER_BICYCLE: "Bicycle driver", - InjuredType.PASSENGER_BICYCLE: "Bicycle passenger", - InjuredType.DRIVER_UNKNOWN_VEHICLE: "Driver of an unknown vehicle", - InjuredType.PASSENGER_UNKNOWN_VEHICLE: "Passenger of an unknown vehicle", - } - - -class CrossLocation(Enum): - UNKNOWN = 9 - OUTNEAR = 1 - OUTFAR = 2 - YESNONE = 3 - YESLIGHT = 4 - - @classmethod - def labels(cls): - return { - CrossLocation.UNKNOWN: "Location unknown", - CrossLocation.OUTNEAR: "Near the intersection, outside the crosswalk", - CrossLocation.OUTFAR: "Away from the intersection, outside the crosswalk", - CrossLocation.YESNONE: "In the crosswalk, without a crossing light", - CrossLocation.YESLIGHT: "In the crosswalk, with a crossing light", - } - - -class CrossCategory(Enum): - UNKNOWN = 0 - NONE = 1 - CROSSWALK = 2 - - def get_codes(self) -> List[int]: - """returns CrossLocation codes of category""" - category_cross_locations = { - CrossCategory.UNKNOWN: [ - CrossLocation.UNKNOWN, - ], - CrossCategory.NONE: [ - CrossLocation.OUTFAR, - CrossLocation.OUTNEAR, - ], - CrossCategory.CROSSWALK: [ - CrossLocation.YESLIGHT, - CrossLocation.YESNONE, - ], - } - return list(map(lambda x: x.value, category_cross_locations[self])) diff --git a/anyway/constants/__init__.py b/anyway/constants/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/anyway/constants/accident_severity.py b/anyway/constants/accident_severity.py new file mode 100644 index 000000000..97548cb11 --- /dev/null +++ b/anyway/constants/accident_severity.py @@ -0,0 +1,15 @@ +from anyway.constants.label_code import LabeledCode + + +class AccidentSeverity(LabeledCode): + FATAL = 1 + SEVERE = 2 + LIGHT = 3 + + @classmethod + def labels(cls): + return { + AccidentSeverity.FATAL: "fatal", + AccidentSeverity.SEVERE: "severe", + AccidentSeverity.LIGHT: "light", + } diff --git a/anyway/constants/accident_type.py b/anyway/constants/accident_type.py new file mode 100644 index 000000000..277eecc1e --- /dev/null +++ b/anyway/constants/accident_type.py @@ -0,0 +1,47 @@ +from anyway.constants.label_code import LabeledCode + + +class AccidentType(LabeledCode): + PEDESTRIAN_INJURY = 1 + COLLISION_OF_FRONT_TO_SIDE = 2 + COLLISION_OF_FRONT_TO_REAR_END = 3 + COLLISION_OF_SIDE_TO_SIDE_LATERAL = 4 + HEAD_ON_FRONTAL_COLLISION = 5 + COLLISION_WITH_A_STOPPED_NON_PARKED_VEHICLE = 6 + COLLISION_WITH_A_PARKED_VEHICLE = 7 + COLLISION_WITH_AN_INANIMATE_OBJECT = 8 + SWERVING_OFF_THE_ROAD_OR_ONTO_THE_PAVEMENT = 9 + OVERTURNED_VEHICLE = 10 + SKID = 11 + INJURY_OF_A_PASSENGER_IN_A_VEHICLE = 12 + A_FALL_FROM_A_MOVING_VEHICLE = 13 + FIRE = 14 + OTHER = 15 + COLLISION_OF_REAR_END_TO_FRONT = 17 + COLLISION_OF_REAR_END_TO_SIDE = 18 + COLLISION_WITH_AN_ANIMAL = 19 + DAMAGE_CAUSED_BY_A_FALLING_LOAD_OFF_A_VEHICLE = 20 + + @classmethod + def labels(cls): + return { + AccidentType.PEDESTRIAN_INJURY: "Pedestrian injury", + AccidentType.COLLISION_OF_FRONT_TO_SIDE: "Collision of front to side", + AccidentType.COLLISION_OF_FRONT_TO_REAR_END: "Collision of front to rear-end", + AccidentType.COLLISION_OF_SIDE_TO_SIDE_LATERAL: "Collision of side to side (lateral)", + AccidentType.HEAD_ON_FRONTAL_COLLISION: "Head-on frontal collision", + AccidentType.COLLISION_WITH_A_STOPPED_NON_PARKED_VEHICLE: "Collision with a stopped non-parked vehicle", + AccidentType.COLLISION_WITH_A_PARKED_VEHICLE: "Collision with a parked vehicle", + AccidentType.COLLISION_WITH_AN_INANIMATE_OBJECT: "Collision with an inanimate object", + AccidentType.SWERVING_OFF_THE_ROAD_OR_ONTO_THE_PAVEMENT: "Swerving off the road or onto the pavement", + AccidentType.OVERTURNED_VEHICLE: "Overturned vehicle", + AccidentType.SKID: "Skid", + AccidentType.INJURY_OF_A_PASSENGER_IN_A_VEHICLE: "Injury of a passenger in a vehicle", + AccidentType.A_FALL_FROM_A_MOVING_VEHICLE: "A fall from a moving vehicle", + AccidentType.FIRE: "Fire", + AccidentType.OTHER: "Other", + AccidentType.COLLISION_OF_REAR_END_TO_FRONT: "Collision of rear-end to front", + AccidentType.COLLISION_OF_REAR_END_TO_SIDE: "Collision of rear-end to side", + AccidentType.COLLISION_WITH_AN_ANIMAL: "Collision with an animal", + AccidentType.DAMAGE_CAUSED_BY_A_FALLING_LOAD_OFF_A_VEHICLE: "Damage caused by a falling load off a vehicle", + } diff --git a/anyway/constants/backend_constants.py b/anyway/constants/backend_constants.py new file mode 100644 index 000000000..b5a7cede9 --- /dev/null +++ b/anyway/constants/backend_constants.py @@ -0,0 +1,109 @@ +from enum import Enum +from typing import List +from flask_babel import _ + + +class BackEndConstants(object): + MARKER_TYPE_ACCIDENT = 1 + MARKER_TYPE_DISCUSSION = 2 + + CBS_ACCIDENT_TYPE_1_CODE = 1 + UNITED_HATZALA_CODE = 2 + CBS_ACCIDENT_TYPE_3_CODE = 3 + RSA_PROVIDER_CODE = 4 + + BIKE_ACCIDENTS = 21 + + AGE_GROUPS_NUMBER = 18 + + ALL_AGE_GROUPS_LIST = list(range(1, AGE_GROUPS_NUMBER + 1)) + [99] + + # This class should be correlated with the Roles table + class Roles2Names(Enum): + Admins = "admins" + Or_yarok = "or_yarok" + Authenticated = "authenticated" + + # This is a type for the 'road_type' table field name + ROAD_TYPE_NOT_IN_CITY_IN_INTERSECTION = 3 + ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION = 4 + NON_CITY_ROAD_TYPES = [ + ROAD_TYPE_NOT_IN_CITY_IN_INTERSECTION, + ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION, + ] + + # other global constants (python only) + DEFAULT_NUMBER_OF_YEARS_AGO = 5 + + # years ago to store in cache + INFOGRAPHICS_CACHE_YEARS_AGO = [1, 3, 5, 8] + SOURCE_MAPPING = {"walla": "וואלה", "twitter": "מד״א", "ynet": "ynet"} + + UNKNOWN = "UNKNOWN" + DEFAULT_REDIRECT_URL = "https://anyway-infographics.web.app/" + ANYWAY_CORS_SITE_LIST_PROD = [ + "https://anyway-infographics-staging.web.app", + "https://anyway-infographics.web.app", + "https://www.anyway.co.il", + "https://anyway-infographics-demo.web.app", + "https://media.anyway.co.il", + "https://dev.anyway.co.il", + ] + + ANYWAY_CORS_SITE_LIST_DEV = ANYWAY_CORS_SITE_LIST_PROD + [ + "https://dev.anyway.co.il", + "http://localhost:3000", + "https://localhost:3000", + "http://127.0.0.1:3000", + "https://127.0.0.1:3000", + ] + + class ResolutionCategories(Enum): + REGION = "מחוז" + DISTRICT = "נפה" + CITY = "עיר" + STREET = "רחוב" + URBAN_JUNCTION = "צומת עירוני" + SUBURBAN_ROAD = "כביש בינעירוני" + SUBURBAN_JUNCTION = "צומת בינעירוני" + OTHER = "אחר" + + SUPPORTED_RESOLUTIONS: List[ResolutionCategories] = [ + ResolutionCategories.STREET, + ResolutionCategories.SUBURBAN_ROAD, + ] + + class Source(Enum): + @classmethod + def _missing_(cls, value): + for member in cls: + if member.value == value.lower(): + return member + + YNET = "ynet" + WALLA = "walla" + TWITTER = "twitter" + + SUPPORTED_SOURCES: List[Source] = [Source.YNET, Source.WALLA, Source.TWITTER] + + # If in the future there will be a number of organizations or a need for a dynamic setting change, move this + # data to a table in the DB. + OR_YAROK_WIDGETS = [ + "accident_count_by_severity", + "most_severe_accidents_table", + "most_severe_accidents", + "vision_zero_2_plus_1", + "head_on_collisions_comparison", + ] + + LKEY = "label_key" + VAL = "value" + SERIES = "series" + + +try: + _("killed") + _("severe injured") + _("light injured") +except NameError: + pass diff --git a/anyway/constants.py b/anyway/constants/constants.py old mode 100755 new mode 100644 similarity index 98% rename from anyway/constants.py rename to anyway/constants/constants.py index 717a4abf7..cfe39cb48 --- a/anyway/constants.py +++ b/anyway/constants/constants.py @@ -57,6 +57,3 @@ def to_dict(self): for a in dir(self) if not a.startswith("__") and not callable(getattr(self, a)) } - - -CONST = Constants() diff --git a/anyway/constants/cross_category.py b/anyway/constants/cross_category.py new file mode 100644 index 000000000..b906c9aeb --- /dev/null +++ b/anyway/constants/cross_category.py @@ -0,0 +1,19 @@ +from enum import Enum +from typing import List + +from anyway.constants.cross_location import CrossLocation + + +class CrossCategory(Enum): + UNKNOWN = 0 + NONE = 1 + CROSSWALK = 2 + + def get_codes(self) -> List[int]: + """returns CrossLocation codes of category""" + category_cross_locations = { + CrossCategory.UNKNOWN: [CrossLocation.UNKNOWN], + CrossCategory.NONE: [CrossLocation.OUTFAR, CrossLocation.OUTNEAR], + CrossCategory.CROSSWALK: [CrossLocation.YESLIGHT, CrossLocation.YESNONE], + } + return list(map(lambda x: x.value, category_cross_locations[self])) diff --git a/anyway/constants/cross_location.py b/anyway/constants/cross_location.py new file mode 100644 index 000000000..8c6a41772 --- /dev/null +++ b/anyway/constants/cross_location.py @@ -0,0 +1,19 @@ +from enum import Enum + + +class CrossLocation(Enum): + UNKNOWN = 9 + OUTNEAR = 1 + OUTFAR = 2 + YESNONE = 3 + YESLIGHT = 4 + + @classmethod + def labels(cls): + return { + CrossLocation.UNKNOWN: "Location unknown", + CrossLocation.OUTNEAR: "Near the intersection, outside the crosswalk", + CrossLocation.OUTFAR: "Away from the intersection, outside the crosswalk", + CrossLocation.YESNONE: "In the crosswalk, without a crossing light", + CrossLocation.YESLIGHT: "In the crosswalk, with a crossing light", + } diff --git a/anyway/constants/driver_type.py b/anyway/constants/driver_type.py new file mode 100644 index 000000000..44f482e3a --- /dev/null +++ b/anyway/constants/driver_type.py @@ -0,0 +1,15 @@ +from anyway.constants.label_code import LabeledCode + + +class DriverType(LabeledCode): + PROFESSIONAL_DRIVER = 1 + PRIVATE_VEHICLE_DRIVER = 2 + OTHER_DRIVER = 3 + + @classmethod + def labels(cls): + return { + DriverType.PROFESSIONAL_DRIVER: "professional_driver", + DriverType.PRIVATE_VEHICLE_DRIVER: "private_vehicle_driver", + DriverType.OTHER_DRIVER: "other_driver", + } diff --git a/anyway/constants/injured_type.py b/anyway/constants/injured_type.py new file mode 100644 index 000000000..fea89b3f6 --- /dev/null +++ b/anyway/constants/injured_type.py @@ -0,0 +1,27 @@ +from anyway.constants.label_code import LabeledCode + + +class InjuredType(LabeledCode): + PEDESTRIAN = 1 + DRIVER_FOUR_WHEELS_AND_ABOVE = 2 + PASSENGER_FOUR_WHEELS_AND_ABOVE = 3 + DRIVER_MOTORCYCLE = 4 + PASSENGER_MOTORCYCLE = 5 + DRIVER_BICYCLE = 6 + PASSENGER_BICYCLE = 7 + DRIVER_UNKNOWN_VEHICLE = 8 + PASSENGER_UNKNOWN_VEHICLE = 9 + + @classmethod + def labels(cls): + return { + InjuredType.PEDESTRIAN: "Pedestrian", + InjuredType.DRIVER_FOUR_WHEELS_AND_ABOVE: "Driver of a vehicle with 4 wheel or more", + InjuredType.PASSENGER_FOUR_WHEELS_AND_ABOVE: "Passenger of a vehicle with 4 wheel or more", + InjuredType.DRIVER_MOTORCYCLE: "Motorcycle driver", + InjuredType.PASSENGER_MOTORCYCLE: "Motorcycle passenger", + InjuredType.DRIVER_BICYCLE: "Bicycle driver", + InjuredType.PASSENGER_BICYCLE: "Bicycle passenger", + InjuredType.DRIVER_UNKNOWN_VEHICLE: "Driver of an unknown vehicle", + InjuredType.PASSENGER_UNKNOWN_VEHICLE: "Passenger of an unknown vehicle", + } diff --git a/anyway/constants/injury_severity.py b/anyway/constants/injury_severity.py new file mode 100644 index 000000000..429408dcc --- /dev/null +++ b/anyway/constants/injury_severity.py @@ -0,0 +1,15 @@ +from anyway.constants.label_code import LabeledCode + + +class InjurySeverity(LabeledCode): + KILLED = 1 + SEVERE_INJURED = 2 + LIGHT_INJURED = 3 + + @classmethod + def labels(cls): + return { + InjurySeverity.KILLED: "killed", + InjurySeverity.SEVERE_INJURED: "severe injured", + InjurySeverity.LIGHT_INJURED: "light injured", + } diff --git a/anyway/constants/label_code.py b/anyway/constants/label_code.py new file mode 100644 index 000000000..8ff7affe3 --- /dev/null +++ b/anyway/constants/label_code.py @@ -0,0 +1,18 @@ +from enum import Enum +from typing import Iterable, List + + +class LabeledCode(Enum): + def get_label(self) -> str: + return type(self).labels()[self] + + @classmethod + def codes(cls: Iterable) -> List[int]: + if isinstance(cls, Iterable): + return [a.value for a in cls] + else: + raise NotImplementedError(f"{cls}: needs to be derived from Enum") + + @classmethod + def labels(cls): + return {} diff --git a/anyway/flask_app.py b/anyway/flask_app.py index faececef7..5baa60fb4 100755 --- a/anyway/flask_app.py +++ b/anyway/flask_app.py @@ -25,7 +25,7 @@ from anyway.app_and_db import api, get_cors_config from anyway.clusters_calculator import retrieve_clusters from anyway.config import ENTRIES_PER_PAGE -from anyway.constants import CONST +from anyway.constants.constants import Constants from anyway.infographics_utils import ( get_infographics_data, get_infographics_mock_data, @@ -76,7 +76,7 @@ app.config.from_object(__name__) -app.config["SWAGGER_UI_DOC_EXPANSION"] = 'list' +app.config["SWAGGER_UI_DOC_EXPANSION"] = "list" app.config["SESSION_COOKIE_SAMESITE"] = "none" app.config["SESSION_COOKIE_SECURE"] = True app.config["REMEMBER_COOKIE_SECURE"] = True @@ -158,10 +158,7 @@ ), ) -CORS( - app, - resources=get_cors_config(), -) +CORS(app, resources=get_cors_config()) jinja_environment = jinja2.Environment( autoescape=True, @@ -267,7 +264,7 @@ def generate_csv(results): "fetch_markers": (bool, True), "fetch_vehicles": (bool, True), "fetch_involved": (bool, True), - "age_groups": (str, str(CONST.ALL_AGE_GROUPS_LIST).strip("[]").replace(" ", "")), + "age_groups": (str, str(Constants.ALL_AGE_GROUPS_LIST).strip("[]").replace(" ", "")), "page": (int, 0), "per_page": (int, 0), } @@ -320,7 +317,7 @@ def markers(): logging.debug("getting markers") kwargs = get_kwargs() logging.debug("querying markers in bounding box: %s" % kwargs) - is_thin = kwargs["zoom"] < CONST.MINIMAL_ZOOM + is_thin = kwargs["zoom"] < Constants.MINIMAL_ZOOM result = AccidentMarker.bounding_box_query( is_thin, yield_per=50, involved_and_vehicles=False, **kwargs ) @@ -706,7 +703,7 @@ def highlightpoint(): return make_response("") # if it's a user gps type (user location), only handle a single post request per session - if int(highlight.type) == CONST.HIGHLIGHT_TYPE_USER_GPS: + if int(highlight.type) == Constants.HIGHLIGHT_TYPE_USER_GPS: if SESSION_HIGHLIGHTPOINT_KEY not in session: session[SESSION_HIGHLIGHTPOINT_KEY] = "saved" else: @@ -763,7 +760,7 @@ def log_bad_request(request): def index(marker=None, message=None): context = {"url": request.base_url, "index_url": request.url_root} - context["CONST"] = CONST.to_dict() + context["CONST"] = Constants().to_dict() if "marker" in request.values: markers = AccidentMarker.get_marker(request.values["marker"]) if markers.count() == 1: @@ -1045,8 +1042,8 @@ def acc_in_area_query(): .filter(AccidentMarker.geom.intersects(pol_str)) .filter( or_( - (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_1_CODE), - (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_3_CODE), + (AccidentMarker.provider_code == BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE), + (AccidentMarker.provider_code == BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE), ) ) ) @@ -1212,7 +1209,9 @@ def infographics_data(): log_bad_request(request) return abort(http_client.BAD_REQUEST) - number_of_years_ago = request.values.get("years_ago", BE_CONST.DEFAULT_NUMBER_OF_YEARS_AGO) + number_of_years_ago = request.values.get( + "years_ago", BackEndConstants.DEFAULT_NUMBER_OF_YEARS_AGO + ) lang: str = request.values.get("lang", "he") logging.debug( ( @@ -1325,7 +1324,7 @@ def widgets_personalisation_for_user(raw_info: typing.Dict) -> typing.Dict: roles_names = [role.name for role in current_user.roles] - if BE_CONST.Roles2Names.Or_yarok.value in roles_names: + if BackEndConstants.Roles2Names.Or_yarok.value in roles_names: widgets_list = raw_info.get("widgets") if not widgets_list: return raw_info @@ -1337,7 +1336,7 @@ def widgets_personalisation_for_user(raw_info: typing.Dict) -> typing.Dict: new_list.append(wig) continue - if wig_name in BE_CONST.OR_YAROK_WIDGETS: + if wig_name in BackEndConstants.OR_YAROK_WIDGETS: new_list.append(wig) raw_info["widgets"] = new_list return raw_info @@ -1377,7 +1376,7 @@ def embedded_reports_api(): # log_bad_request(request) # return abort(http_client.BAD_REQUEST) # -# number_of_years_ago = request.values.get("years_ago", BE_CONST.DEFAULT_NUMBER_OF_YEARS_AGO) +# number_of_years_ago = request.values.get("years_ago", BackEndConstants.DEFAULT_NUMBER_OF_YEARS_AGO) # lang: str = request.values.get("lang", "he") # logging.debug( # ( diff --git a/anyway/infographics_utils.py b/anyway/infographics_utils.py index 474f77929..0f75ecba9 100755 --- a/anyway/infographics_utils.py +++ b/anyway/infographics_utils.py @@ -21,7 +21,8 @@ extract_news_flash_location, get_request_params_from_request_values, ) -from anyway.backend_constants import BE_CONST, AccidentType +from anyway.constants.backend_constants import BackEndConstants +from anyway.constants.accident_type import AccidentType from anyway.models import NewsFlash, AccidentMarkerView from anyway.parsers import resolution_dict from anyway.infographics_dictionaries import head_on_collisions_comparison_dict @@ -289,10 +290,8 @@ def get_infographics_data_for_road_segment(road_segment_id, years_ago, lang: str output = create_infographics_items(request_params) else: try: - output = ( - infographics_data_cache_updater.get_infographics_data_from_cache_by_road_segment( - road_segment_id, years_ago - ) + output = infographics_data_cache_updater.get_infographics_data_from_cache_by_road_segment( + road_segment_id, years_ago ) except Exception as e: logging.error( @@ -350,7 +349,7 @@ def is_news_flash_resolution_supported(news_flash_obj: NewsFlash) -> bool: if location_data is None or location_data["data"]["resolution"] is None: return False location = location_data["data"] - for cat in BE_CONST.SUPPORTED_RESOLUTIONS: + for cat in BackEndConstants.SUPPORTED_RESOLUTIONS: if cat.value in resolution_dict and set(resolution_dict[cat.value]) <= location.keys(): return True return False diff --git a/anyway/models.py b/anyway/models.py index 500d669e1..9e4cbc7cc 100755 --- a/anyway/models.py +++ b/anyway/models.py @@ -40,7 +40,7 @@ class UserMixin: from sqlalchemy import or_, and_ from anyway import localization -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.database import Base from anyway.utilities import decode_hebrew @@ -118,14 +118,10 @@ class Users(Base, UserMixin): user_desc = Column(String(2048)) is_user_completed_registration = Column(Boolean) roles = relationship( - "Roles", - secondary=users_to_roles, - backref=backref("users", lazy="dynamic"), + "Roles", secondary=users_to_roles, backref=backref("users", lazy="dynamic") ) organizations = relationship( - "Organization", - secondary=users_to_organizations, - backref=backref("users", lazy="dynamic"), + "Organization", secondary=users_to_organizations, backref=backref("users", lazy="dynamic") ) def serialize_exposed_to_user(self): @@ -256,7 +252,7 @@ class AccidentMarker(MarkerMixin, Base): Index("idx_markers_created", "created", unique=False), ) - __mapper_args__ = {"polymorphic_identity": BE_CONST.MARKER_TYPE_ACCIDENT} + __mapper_args__ = {"polymorphic_identity": BackEndConstants.MARKER_TYPE_ACCIDENT} id = Column(BigInteger(), primary_key=True) provider_and_id = Column(BigInteger()) provider_code = Column(Integer(), primary_key=True) @@ -337,7 +333,10 @@ def get_latest_marker_created_date(): db.session.query(func.max(AccidentMarker.created)) .filter( AccidentMarker.provider_code.in_( - [BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, BE_CONST.CBS_ACCIDENT_TYPE_3_CODE] + [ + BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE, + ] ) ) .first() @@ -386,7 +385,7 @@ def serialize(self, is_thin=False): } ) # United Hatzala accidents description are not json: - if self.provider_code == BE_CONST.UNITED_HATZALA_CODE: + if self.provider_code == BackEndConstants.UNITED_HATZALA_CODE: fields.update({"description": self.description}) else: fields.update({"description": AccidentMarker.json_to_description(self.description)}) @@ -449,7 +448,7 @@ def bounding_box_query( .filter(AccidentMarker.geom.intersects(polygon_str)) .filter(AccidentMarker.created >= kwargs["start_date"]) .filter(AccidentMarker.created < kwargs["end_date"]) - .filter(AccidentMarker.provider_code != BE_CONST.RSA_PROVIDER_CODE) + .filter(AccidentMarker.provider_code != BackEndConstants.RSA_PROVIDER_CODE) .order_by(desc(AccidentMarker.created)) ) @@ -459,7 +458,7 @@ def bounding_box_query( .filter(AccidentMarker.geom.intersects(polygon_str)) .filter(AccidentMarker.created >= kwargs["start_date"]) .filter(AccidentMarker.created < kwargs["end_date"]) - .filter(AccidentMarker.provider_code == BE_CONST.RSA_PROVIDER_CODE) + .filter(AccidentMarker.provider_code == BackEndConstants.RSA_PROVIDER_CODE) .order_by(desc(AccidentMarker.created)) ) else: @@ -468,7 +467,7 @@ def bounding_box_query( .filter(AccidentMarker.geom.intersects(polygon_str)) .filter(AccidentMarker.created >= kwargs["start_date"]) .filter(AccidentMarker.created < kwargs["end_date"]) - .filter(AccidentMarker.provider_code != BE_CONST.RSA_PROVIDER_CODE) + .filter(AccidentMarker.provider_code != BackEndConstants.RSA_PROVIDER_CODE) .order_by(desc(AccidentMarker.created)) ) @@ -477,7 +476,7 @@ def bounding_box_query( .filter(AccidentMarker.geom.intersects(polygon_str)) .filter(AccidentMarker.created >= kwargs["start_date"]) .filter(AccidentMarker.created < kwargs["end_date"]) - .filter(AccidentMarker.provider_code == BE_CONST.RSA_PROVIDER_CODE) + .filter(AccidentMarker.provider_code == BackEndConstants.RSA_PROVIDER_CODE) .order_by(desc(AccidentMarker.created)) ) @@ -486,9 +485,9 @@ def bounding_box_query( if not kwargs["show_accidents"]: markers = markers.filter( and_( - AccidentMarker.provider_code != BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, - AccidentMarker.provider_code != BE_CONST.CBS_ACCIDENT_TYPE_3_CODE, - AccidentMarker.provider_code != BE_CONST.UNITED_HATZALA_CODE, + AccidentMarker.provider_code != BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE, + AccidentMarker.provider_code != BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE, + AccidentMarker.provider_code != BackEndConstants.UNITED_HATZALA_CODE, ) ) if yield_per: @@ -589,7 +588,7 @@ def bounding_box_query( if kwargs.get("acctype", 0) != 0: if kwargs["acctype"] <= 20: markers = markers.filter(AccidentMarker.accident_type == kwargs["acctype"]) - elif kwargs["acctype"] == BE_CONST.BIKE_ACCIDENTS: + elif kwargs["acctype"] == BackEndConstants.BIKE_ACCIDENTS: markers = markers.filter( AccidentMarker.vehicles.any(Vehicle.vehicle_type == BE_VehicleType.BIKE.value) ) @@ -606,7 +605,7 @@ def bounding_box_query( if kwargs.get("age_groups"): age_groups_list = kwargs.get("age_groups").split(",") - if len(age_groups_list) < (BE_CONST.AGE_GROUPS_NUMBER + 1): + if len(age_groups_list) < (BackEndConstants.AGE_GROUPS_NUMBER + 1): markers = markers.filter( AccidentMarker.involved.any(Involved.age_group.in_(age_groups_list)) ) @@ -693,7 +692,7 @@ def get_marker(marker_id): @classmethod def parse(cls, data): return AccidentMarker( - type=BE_CONST.MARKER_TYPE_ACCIDENT, + type=BackEndConstants.MARKER_TYPE_ACCIDENT, title=data["title"], description=data["description"], latitude=data["latitude"], @@ -708,7 +707,7 @@ class DiscussionMarker(MarkerMixin, Base): Index("idx_discussions_geom", "geom", unique=False), ) - __mapper_args__ = {"polymorphic_identity": BE_CONST.MARKER_TYPE_DISCUSSION} + __mapper_args__ = {"polymorphic_identity": BackEndConstants.MARKER_TYPE_DISCUSSION} identifier = Column(String(50), unique=True) geom = Column(Geometry("POINT")) @@ -739,7 +738,7 @@ def parse(cls, data): created=datetime.datetime.now(), title=data["title"], identifier=data["identifier"], - type=BE_CONST.MARKER_TYPE_DISCUSSION, + type=BackEndConstants.MARKER_TYPE_DISCUSSION, ) @staticmethod @@ -975,20 +974,24 @@ def serialize(self): @staticmethod def get_street_name_by_street(yishuv_symbol: int, street: int) -> str: - res = db.session.query(Streets.street_hebrew) \ - .filter(Streets.yishuv_symbol == yishuv_symbol) \ - .filter(Streets.street == street)\ + res = ( + db.session.query(Streets.street_hebrew) + .filter(Streets.yishuv_symbol == yishuv_symbol) + .filter(Streets.street == street) .first() + ) if res is None: raise ValueError(f"{street}: could not find street in yishuv:{yishuv_symbol}") return res.street_hebrew @staticmethod def get_street_by_street_name(yishuv_symbol: int, name: str) -> int: - res = db.session.query(Streets.street) \ - .filter(Streets.yishuv_symbol == yishuv_symbol) \ - .filter(Streets.street_hebrew == name)\ + res = ( + db.session.query(Streets.street) + .filter(Streets.yishuv_symbol == yishuv_symbol) + .filter(Streets.street_hebrew == name) .first() + ) if res is None: raise ValueError(f"{name}: could not find street in yishuv:{yishuv_symbol}") return res @@ -2491,24 +2494,37 @@ class InfographicsTwoRoadsDataCacheFields(object): class InfographicsTwoRoadsDataCache(InfographicsTwoRoadsDataCacheFields, Base): __tablename__ = "infographics_two_roads_data_cache" __table_args__ = ( - Index("infographics_two_roads_data_cache_id_years_idx", "road1", "road2", - "years_ago", unique=True), + Index( + "infographics_two_roads_data_cache_id_years_idx", + "road1", + "road2", + "years_ago", + unique=True, + ), ) def get_data(self): return self.data def serialize(self): - return {"road1": self.road1, "road2": self.road2, "years_ago": self.years_ago, - "data": self.data} + return { + "road1": self.road1, + "road2": self.road2, + "years_ago": self.years_ago, + "data": self.data, + } class InfographicsTwoRoadsDataCacheTemp(InfographicsTwoRoadsDataCacheFields, Base): __tablename__ = "infographics_two_roads_data_cache_temp" def serialize(self): - return {"road1": self.road1, "road2": self.road2, "years_ago": self.years_ago, - "data": self.data} + return { + "road1": self.road1, + "road2": self.road2, + "years_ago": self.years_ago, + "data": self.data, + } # # Flask-Login integration # def is_authenticated(self): diff --git a/anyway/parsers/cbs/executor.py b/anyway/parsers/cbs/executor.py index f3235910f..248f5f0f4 100644 --- a/anyway/parsers/cbs/executor.py +++ b/anyway/parsers/cbs/executor.py @@ -15,7 +15,7 @@ from anyway.parsers.cbs import preprocessing_cbs_files from anyway import field_names, localization -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.models import ( AccidentMarker, Involved, @@ -881,8 +881,8 @@ def delete_cbs_entries(start_year, batch_size): .filter(AccidentMarker.created >= datetime.strptime(start_date, "%Y-%m-%d")) .filter( or_( - (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_1_CODE), - (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_3_CODE), + (AccidentMarker.provider_code == BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE), + (AccidentMarker.provider_code == BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE), ) ) .all() @@ -1078,11 +1078,7 @@ def get_file_type_and_year(file_path): return int(provider_code), int(year) -def main( - batch_size, - source, - load_start_year=None, -): +def main(batch_size, source, load_start_year=None): try: load_existing_streets() total = 0 @@ -1096,10 +1092,12 @@ def main( s3_data_retriever.get_files_from_s3(start_year=load_start_year) delete_cbs_entries(load_start_year, batch_size) for provider_code in [ - BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, - BE_CONST.CBS_ACCIDENT_TYPE_3_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE, ]: - logging.info(f"Loading min year {s3_data_retriever.min_year} Loading max year {s3_data_retriever.max_year}") + logging.info( + f"Loading min year {s3_data_retriever.min_year} Loading max year {s3_data_retriever.max_year}" + ) for year in range(s3_data_retriever.min_year, s3_data_retriever.max_year + 1): cbs_files_dir = os.path.join( s3_data_retriever.local_files_directory, diff --git a/anyway/parsers/cbs/s3/data_retriever.py b/anyway/parsers/cbs/s3/data_retriever.py index 1b6edd6de..40bd839c4 100644 --- a/anyway/parsers/cbs/s3/data_retriever.py +++ b/anyway/parsers/cbs/s3/data_retriever.py @@ -112,7 +112,6 @@ def __download_accidents_type_files(self, accidents_type, start_year): self.__max_year = year if self.__max_year is None else max(year, self.__max_year) self.__min_year = year if self.__min_year is None else min(year, self.__min_year) - def get_files_from_s3(self, start_year, accidents_types=None): if accidents_types is None: desired_accidents_types = self.__accidents_types diff --git a/anyway/parsers/infographics_data_cache_updater.py b/anyway/parsers/infographics_data_cache_updater.py index d05ac8ff9..b13d63a40 100755 --- a/anyway/parsers/infographics_data_cache_updater.py +++ b/anyway/parsers/infographics_data_cache_updater.py @@ -14,8 +14,8 @@ Streets, ) from typing import Dict, Iterable -from anyway.constants import CONST -from anyway.backend_constants import BE_CONST +from anyway.constants.constants import Constants +from anyway.constants.backend_constants import BackEndConstants from anyway.app_and_db import db from anyway.request_params import RequestParams import anyway.infographics_utils @@ -31,7 +31,7 @@ def is_in_cache(nf): return ( - len(CONST.INFOGRAPHICS_CACHE_YEARS_AGO) + len(Constants.INFOGRAPHICS_CACHE_YEARS_AGO) == db.session.query(InfographicsDataCache) .filter(InfographicsDataCache.news_flash_id == nf.get_id()) .count() @@ -59,7 +59,7 @@ def add_news_flash_to_cache(news_flash: NewsFlash): news_flash.get_id(), y, "he" ), } - for y in CONST.INFOGRAPHICS_CACHE_YEARS_AGO + for y in Constants.INFOGRAPHICS_CACHE_YEARS_AGO ], ) logging.info(f"{news_flash.get_id()} added to cache") @@ -120,7 +120,7 @@ def get_infographics_data_from_cache_by_road_segment(road_segment_id, years_ago) def get_cache_retrieval_query(params: RequestParams): res = params.resolution loc = params.location_info - if res == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + if res == BackEndConstants.ResolutionCategories.SUBURBAN_ROAD: return ( db.session.query(InfographicsRoadSegmentsDataCache) .filter( @@ -129,7 +129,7 @@ def get_cache_retrieval_query(params: RequestParams): ) .filter(InfographicsRoadSegmentsDataCache.years_ago == int(params.years_ago)) ) - elif res == BE_CONST.ResolutionCategories.STREET: + elif res == BackEndConstants.ResolutionCategories.STREET: t = InfographicsStreetDataCache return ( db.session.query(t) @@ -198,8 +198,8 @@ def build_cache_into_temp(): start = datetime.now() db.session.query(InfographicsDataCacheTemp).delete() db.session.commit() - supported_resolutions = set([x.value for x in BE_CONST.SUPPORTED_RESOLUTIONS]) - for y in CONST.INFOGRAPHICS_CACHE_YEARS_AGO: + supported_resolutions = set([x.value for x in BackEndConstants.SUPPORTED_RESOLUTIONS]) + for y in Constants.INFOGRAPHICS_CACHE_YEARS_AGO: logging.debug(f"processing years_ago:{y}") db.get_engine().execute( InfographicsDataCacheTemp.__table__.insert(), # pylint: disable=no-member @@ -232,7 +232,7 @@ def get_streets() -> Iterable[Streets]: def get_street_infographic_keys() -> Iterable[Dict[str, int]]: for street in get_streets(): - for y in CONST.INFOGRAPHICS_CACHE_YEARS_AGO: + for y in Constants.INFOGRAPHICS_CACHE_YEARS_AGO: yield { "yishuv_symbol": street.yishuv_symbol, "street1": street.street, @@ -266,7 +266,7 @@ def build_cache_for_road_segments(): start = datetime.now() db.session.query(InfographicsRoadSegmentsDataCache).delete() db.session.commit() - for y in CONST.INFOGRAPHICS_CACHE_YEARS_AGO: + for y in Constants.INFOGRAPHICS_CACHE_YEARS_AGO: logging.debug(f"processing years_ago:{y}") db.get_engine().execute( InfographicsRoadSegmentsDataCache.__table__.insert(), # pylint: disable=no-member diff --git a/anyway/parsers/injured_around_schools.py b/anyway/parsers/injured_around_schools.py index 7578a45db..29a7bc4a1 100644 --- a/anyway/parsers/injured_around_schools.py +++ b/anyway/parsers/injured_around_schools.py @@ -8,7 +8,7 @@ import pandas as pd from sqlalchemy import or_, not_, and_ -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.models import ( AccidentMarker, Involved, @@ -67,8 +67,8 @@ def acc_inv_query(longitude, latitude, distance, start_date, end_date, school): .filter(AccidentMarker.provider_and_id == Involved.provider_and_id) .filter( or_( - (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_1_CODE), - (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_3_CODE), + (AccidentMarker.provider_code == BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE), + (AccidentMarker.provider_code == BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE), ) ) .filter(AccidentMarker.created >= start_date) diff --git a/anyway/parsers/location_extraction.py b/anyway/parsers/location_extraction.py index 8cd891838..bd37001c8 100644 --- a/anyway/parsers/location_extraction.py +++ b/anyway/parsers/location_extraction.py @@ -5,14 +5,12 @@ import googlemaps import numpy as np from geographiclib.geodesic import Geodesic -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.models import NewsFlash from anyway.parsers import resolution_dict from anyway import secrets from anyway.models import AccidentMarkerView, RoadSegments -from sqlalchemy import ( - not_, -) +from sqlalchemy import not_ import pandas as pd @@ -107,7 +105,7 @@ def get_bounding_box(latitude, longitude, distance_in_km): db.session.query(AccidentMarkerView) .filter(AccidentMarkerView.geom.intersects(polygon_str)) .filter(AccidentMarkerView.accident_year >= 2014) - .filter(AccidentMarkerView.provider_code != BE_CONST.RSA_PROVIDER_CODE) + .filter(AccidentMarkerView.provider_code != BackEndConstants.RSA_PROVIDER_CODE) .filter(not_(AccidentMarkerView.road_segment_name == None)) ) markers = pd.read_sql_query(query_obj.statement, query_obj.session.bind) diff --git a/anyway/parsers/rsa.py b/anyway/parsers/rsa.py index 09d084efb..f36620893 100644 --- a/anyway/parsers/rsa.py +++ b/anyway/parsers/rsa.py @@ -3,7 +3,7 @@ from dateutil import parser from openpyxl import load_workbook from anyway.parsers.utils import batch_iterator -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.models import AccidentMarker from anyway.app_and_db import db @@ -25,7 +25,7 @@ def _iter_rows(filename): assert [cell.value for cell in first_row] == headers for row in rows: id_ = int(row[0].value) - provider_and_id_ = int(str(BE_CONST.RSA_PROVIDER_CODE) + str(id_)) + provider_and_id_ = int(str(BackEndConstants.RSA_PROVIDER_CODE) + str(id_)) violation = row[3].value vehicle_type = row[4].value @@ -53,12 +53,12 @@ def _iter_rows(filename): "latitude": latitude, "longitude": longitude, "created": timestamp, - "provider_code": BE_CONST.RSA_PROVIDER_CODE, + "provider_code": BackEndConstants.RSA_PROVIDER_CODE, "accident_severity": 0, "title": "שומרי הדרך", "description": json.dumps(description), "location_accuracy": 1, - "type": BE_CONST.MARKER_TYPE_ACCIDENT, + "type": BackEndConstants.MARKER_TYPE_ACCIDENT, "video_link": video_link, "vehicle_type_rsa": vehicle_type, "violation_type_rsa": violation, @@ -68,7 +68,9 @@ def _iter_rows(filename): def parse(filename): - db.session.execute(f"DELETE from markers where provider_code = {BE_CONST.RSA_PROVIDER_CODE}") + db.session.execute( + f"DELETE from markers where provider_code = {BackEndConstants.RSA_PROVIDER_CODE}" + ) for batch in batch_iterator(_iter_rows(filename), batch_size=50000): db.session.bulk_insert_mappings(AccidentMarker, batch) db.session.commit() diff --git a/anyway/request_params.py b/anyway/request_params.py index 9c971cc6b..f9a4d637c 100644 --- a/anyway/request_params.py +++ b/anyway/request_params.py @@ -7,8 +7,11 @@ import pandas as pd from anyway.models import NewsFlash, AccidentMarkerView, City, Streets -from anyway.parsers.location_extraction import get_road_segment_name_and_number, get_road_segment_by_name -from anyway.backend_constants import BE_CONST +from anyway.parsers.location_extraction import ( + get_road_segment_name_and_number, + get_road_segment_by_name, +) +from anyway.constants.backend_constants import BackEndConstants from anyway.app_and_db import db from anyway.parsers import resolution_dict @@ -22,7 +25,7 @@ class RequestParams: years_ago: int location_text: str location_info: Dict[str, Any] - resolution: BE_CONST.ResolutionCategories + resolution: BackEndConstants.ResolutionCategories gps: Dict start_time: datetime.date end_time: datetime.date @@ -50,7 +53,7 @@ def get_request_params_from_request_values(vals: dict) -> Optional[RequestParams logging.debug("location_info:{}".format(location_info)) logging.debug("location_text:{}".format(location_text)) resolution = location_info.pop("resolution") - if resolution is None or resolution not in BE_CONST.SUPPORTED_RESOLUTIONS: + if resolution is None or resolution not in BackEndConstants.SUPPORTED_RESOLUTIONS: logging.error(f"Resolution empty or not supported: {resolution}.") return None @@ -104,20 +107,21 @@ def get_location_from_news_flash(news_flash_id: str) -> dict: news_flash = extract_news_flash_obj(news_flash_id) loc = extract_news_flash_location(news_flash) res = loc["data"]["resolution"] - loc["data"]["resolution"] = BE_CONST.ResolutionCategories(res) + loc["data"]["resolution"] = BackEndConstants.ResolutionCategories(res) loc["text"] = get_news_flash_location_text(news_flash) add_numeric_field_values(loc, news_flash) return loc def add_numeric_field_values(loc: dict, news_flash: NewsFlash) -> None: - if loc["data"]["resolution"] == BE_CONST.ResolutionCategories.STREET: + if loc["data"]["resolution"] == BackEndConstants.ResolutionCategories.STREET: if "yishuv_symbol" not in loc["data"]: loc["data"]["yishuv_symbol"] = City.get_symbol_from_name(loc["data"]["yishuv_name"]) if "street1" not in loc["data"]: - loc["data"]["street1"] = Streets.get_street_by_street_name(loc["data"]["yishuv_symbol"], - loc["data"]["street1_hebrew"]) - elif loc["data"]["resolution"] == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + loc["data"]["street1"] = Streets.get_street_by_street_name( + loc["data"]["yishuv_symbol"], loc["data"]["street1_hebrew"] + ) + elif loc["data"]["resolution"] == BackEndConstants.ResolutionCategories.SUBURBAN_ROAD: if "road_segment_id" not in loc["data"]: segment = get_road_segment_by_name(loc["data"]["road_segment_name"]) loc["data"]["road_segment_id"] = segment.segment_id @@ -167,7 +171,7 @@ def get_street_location_text(yishuv_name, street1_hebrew): def extract_road_segment_location(road_segment_id): - data = {"resolution": BE_CONST.ResolutionCategories.SUBURBAN_ROAD} + data = {"resolution": BackEndConstants.ResolutionCategories.SUBURBAN_ROAD} road1, road_segment_name = get_road_segment_name_and_number(road_segment_id) data["road1"] = int(road1) data["road_segment_name"] = road_segment_name @@ -182,7 +186,7 @@ def extract_road_segment_location(road_segment_id): def extract_street_location(input_vals: dict): vals = fill_missing_street_values(input_vals) # noinspection PyDictCreation - data = {"resolution": BE_CONST.ResolutionCategories.STREET} + data = {"resolution": BackEndConstants.ResolutionCategories.STREET} for k in ["yishuv_name", "yishuv_symbol", "street1", "street1_hebrew"]: data[k] = vals[k] text = get_street_location_text(vals["yishuv_name"], vals["street1_hebrew"]) @@ -198,9 +202,13 @@ def fill_missing_street_values(vals: dict) -> dict: else: res["yishuv_symbol"] = City.get_symbol_from_name(res["yishuv_name"]) if "street1" in res and "street1_hebrew" not in res: - res["street1_hebrew"] = Streets.get_street_name_by_street(res["yishuv_symbol"], res["street1"]) + res["street1_hebrew"] = Streets.get_street_name_by_street( + res["yishuv_symbol"], res["street1"] + ) else: - res["street1"] = Streets.get_street_by_street_name(res["yishuv_symbol"], res["street1_hebrew"]) + res["street1"] = Streets.get_street_by_street_name( + res["yishuv_symbol"], res["street1_hebrew"] + ) return res @@ -218,8 +226,8 @@ def extract_news_flash_obj(news_flash_id) -> Optional[NewsFlash]: def get_latest_accident_date(table_obj, filters): filters = filters or {} filters["provider_code"] = [ - BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, - BE_CONST.CBS_ACCIDENT_TYPE_3_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE, ] query = db.session.query(func.max(table_obj.accident_timestamp)) df = pd.read_sql_query(query.statement, query.session.bind) diff --git a/anyway/scripts/build_redacted_tables_for_dev.py b/anyway/scripts/build_redacted_tables_for_dev.py index 979c213c5..4ed3790d6 100644 --- a/anyway/scripts/build_redacted_tables_for_dev.py +++ b/anyway/scripts/build_redacted_tables_for_dev.py @@ -24,9 +24,7 @@ def create_db(): Users.metadata.create_all(engine) role_admins = Roles( - name="admins", - description="This is the default admin role.", - create_date=datetime.now(), + name="admins", description="This is the default admin role.", create_date=datetime.now() ) Session = sessionmaker(bind=engine) session = Session() @@ -62,9 +60,7 @@ def create_db(): ) if admin_role is None: insert_users_to_roles = users_to_roles.insert().values( - user_id=user_id.id, - role_id=role_id.id, - create_date=datetime.now(), + user_id=user_id.id, role_id=role_id.id, create_date=datetime.now() ) session.execute(insert_users_to_roles) session.commit() diff --git a/anyway/utilities.py b/anyway/utilities.py index dcc415e21..7f4298076 100644 --- a/anyway/utilities.py +++ b/anyway/utilities.py @@ -259,10 +259,7 @@ def is_a_safe_redirect_url(url: str) -> bool: return False # Note that we don't support ipv6 localhost address or ipv4 localhost full range of address - if netloc in [ - "localhost", - "127.0.0.1", - ]: + if netloc in ["localhost", "127.0.0.1"]: return True else: # Check localhost with port localhost_regex = re.compile(r"^127\.0\.0\.1:[0-9]{1,7}$|^localhost:[0-9]{1,7}$") @@ -280,11 +277,7 @@ def is_a_safe_redirect_url(url: str) -> bool: if ( config.SERVER_ENV == "dev" and url_obj.scheme == "https" - and netloc - in [ - "dev.anyway.co.il", - "www.dev.anyway.co.il", - ] + and netloc in ["dev.anyway.co.il", "www.dev.anyway.co.il"] ): return True @@ -293,10 +286,6 @@ def is_a_safe_redirect_url(url: str) -> bool: def is_a_valid_email(tmp_given_user_email: str) -> bool: is_valid = validate_email( - email_address=tmp_given_user_email, - check_regex=True, - check_mx=False, - use_blacklist=False, + email_address=tmp_given_user_email, check_regex=True, check_mx=False, use_blacklist=False ) return is_valid - diff --git a/anyway/views/news_flash/api.py b/anyway/views/news_flash/api.py index cbfa71d1f..62f5236ff 100644 --- a/anyway/views/news_flash/api.py +++ b/anyway/views/news_flash/api.py @@ -12,7 +12,7 @@ from anyway.app_and_db import db -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.models import NewsFlash from anyway.infographics_utils import is_news_flash_resolution_supported @@ -29,7 +29,7 @@ class NewsFlashQuery(BaseModel): offset: Optional[int] = DEFAULT_OFFSET_REQ_PARAMETER limit: Optional[int] = DEFAULT_LIMIT_REQ_PARAMETER resolution: Optional[List[str]] - source: Optional[List[BE_CONST.Source]] + source: Optional[List[BackEndConstants.Source]] # Must set default value in order to allow access from "check_missing_date" validator when no value provided # from the request start_date: Optional[datetime.datetime] = None @@ -163,7 +163,7 @@ def gen_news_flash_query( status=404, mimetype="application/json", ) - supported_resolutions = set([x.value for x in BE_CONST.SUPPORTED_RESOLUTIONS]) + supported_resolutions = set([x.value for x in BackEndConstants.SUPPORTED_RESOLUTIONS]) query = query.filter(NewsFlash.resolution.in_(supported_resolutions)) if interurban_only == "true" or interurban_only == "True": query = query.filter(NewsFlash.resolution.in_(["כביש בינעירוני"])) @@ -212,10 +212,10 @@ def gen_news_flash_query_v2(session, valid_params: dict): def set_display_source(news_flash): - news_flash["display_source"] = BE_CONST.SOURCE_MAPPING.get( - news_flash["source"], BE_CONST.UNKNOWN + news_flash["display_source"] = BackEndConstants.SOURCE_MAPPING.get( + news_flash["source"], BackEndConstants.UNKNOWN ) - if news_flash["display_source"] == BE_CONST.UNKNOWN: + if news_flash["display_source"] == BackEndConstants.UNKNOWN: logging.warning(f"Unknown source of news-flash with id") @@ -236,7 +236,7 @@ def single_news_flash(news_flash_id: int): def get_supported_resolutions() -> set: - return set([x.name.lower() for x in BE_CONST.SUPPORTED_RESOLUTIONS]) + return set([x.name.lower() for x in BackEndConstants.SUPPORTED_RESOLUTIONS]) def get_news_flash_by_id(id: int): @@ -256,14 +256,14 @@ def filter_by_resolutions(query, resolutions: List[str]): if "suburban_road" in resolutions: ands.append( and_( - NewsFlash.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD.value, + NewsFlash.resolution == BackEndConstants.ResolutionCategories.SUBURBAN_ROAD.value, NewsFlash.road_segment_name != None, ) ) if "street" in resolutions: ands.append( and_( - NewsFlash.resolution == BE_CONST.ResolutionCategories.STREET.value, + NewsFlash.resolution == BackEndConstants.ResolutionCategories.STREET.value, NewsFlash.street1_hebrew != None, ) ) diff --git a/anyway/views/user_system/api.py b/anyway/views/user_system/api.py index a3857ecc5..190783eae 100644 --- a/anyway/views/user_system/api.py +++ b/anyway/views/user_system/api.py @@ -23,7 +23,7 @@ from anyway.anyway_dataclasses.user_data import UserData from anyway.app_and_db import db, app -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.base import _set_cookie_hijack, _clear_cookie_hijack from anyway.error_code_and_strings import ( Errors as Es, @@ -136,7 +136,7 @@ def oauth_authorize(provider: str) -> Response: return return_json_error(Es.BR_USER_ALREADY_LOGGED_IN) redirect_url_from_url = request.args.get("redirect_url", type=str) - redirect_url = BE_CONST.DEFAULT_REDIRECT_URL + redirect_url = BackEndConstants.DEFAULT_REDIRECT_URL if redirect_url_from_url and is_a_safe_redirect_url(redirect_url_from_url): redirect_url = redirect_url_from_url @@ -211,7 +211,7 @@ def oauth_callback(provider: str) -> Response: db.session.commit() - redirect_url = BE_CONST.DEFAULT_REDIRECT_URL + redirect_url = BackEndConstants.DEFAULT_REDIRECT_URL redirect_url_json_base64 = request.args.get("state", type=str) if redirect_url_json_base64: redirect_url_json = json.loads(base64.b64decode(redirect_url_json_base64.encode("UTF8"))) @@ -226,7 +226,7 @@ def oauth_callback(provider: str) -> Response: # TODO: in the future add pagination if needed -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def get_all_users_info() -> Response: dict_ret = [] for user_obj in db.session.query(Users).order_by(Users.user_register_date).all(): @@ -234,18 +234,18 @@ def get_all_users_info() -> Response: return jsonify(dict_ret) -@roles_accepted(BE_CONST.Roles2Names.Authenticated.value) +@roles_accepted(BackEndConstants.Roles2Names.Authenticated.value) def get_user_info() -> Response: user_obj = get_current_user() return jsonify(user_obj.serialize_exposed_to_user()) -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def remove_from_role() -> Response: return change_user_roles("remove") -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def add_to_role() -> Response: return change_user_roles("add") @@ -310,7 +310,7 @@ def get_role_object(role_name): return role -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def admin_update_user() -> Response: allowed_fields = [ "user_current_email", @@ -366,7 +366,7 @@ def admin_update_user() -> Response: # This code is also used as part of the user first registration -@roles_accepted(BE_CONST.Roles2Names.Authenticated.value) +@roles_accepted(BackEndConstants.Roles2Names.Authenticated.value) def user_update() -> Response: allowed_fields = [ "first_name", @@ -445,7 +445,7 @@ def update_user_in_db( db.session.commit() -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def change_user_active_mode() -> Response: req_dict = request.json if not req_dict: @@ -468,7 +468,7 @@ def change_user_active_mode() -> Response: return Response(status=HTTPStatus.OK) -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def add_role() -> Response: req_dict = request.json if not req_dict: @@ -516,7 +516,7 @@ def is_a_valid_role_description(name: str) -> bool: return True -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def get_roles_list() -> Response: roles_list = db.session.query(Roles).all() send_list = [ @@ -524,25 +524,21 @@ def get_roles_list() -> Response: ] return Response( - response=json.dumps(send_list), - status=HTTPStatus.OK, - mimetype="application/json", + response=json.dumps(send_list), status=HTTPStatus.OK, mimetype="application/json" ) -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def get_organization_list() -> Response: orgs_list = db.session.query(Organization).all() send_list = [org.name for org in orgs_list] return Response( - response=json.dumps(send_list), - status=HTTPStatus.OK, - mimetype="application/json", + response=json.dumps(send_list), status=HTTPStatus.OK, mimetype="application/json" ) -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def add_organization(name: str) -> Response: if not name: return return_json_error(Es.BR_FIELD_MISSING) @@ -556,7 +552,7 @@ def add_organization(name: str) -> Response: return Response(status=HTTPStatus.OK) -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def remove_user_from_org() -> Response: req_dict = request.json if req_dict is None: @@ -591,7 +587,7 @@ def remove_user_from_org() -> Response: return Response(status=HTTPStatus.OK) -@roles_accepted(BE_CONST.Roles2Names.Admins.value) +@roles_accepted(BackEndConstants.Roles2Names.Admins.value) def add_user_to_org() -> Response: req_dict = request.json if req_dict is None: diff --git a/anyway/widgets/suburban_widgets/accident_count_by_accident_type_widget.py b/anyway/widgets/suburban_widgets/accident_count_by_accident_type_widget.py index dc5df9edd..58d4bd561 100644 --- a/anyway/widgets/suburban_widgets/accident_count_by_accident_type_widget.py +++ b/anyway/widgets/suburban_widgets/accident_count_by_accident_type_widget.py @@ -42,7 +42,5 @@ def get_accident_count_by_accident_type(location_info, start_time, end_time): @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - items["data"]["text"] = { - "title": _("Number of accidents by accident type"), - } - return items \ No newline at end of file + items["data"]["text"] = {"title": _("Number of accidents by accident type")} + return items diff --git a/anyway/widgets/suburban_widgets/accident_count_by_accident_year_widget.py b/anyway/widgets/suburban_widgets/accident_count_by_accident_year_widget.py index f355d10fa..752362d08 100644 --- a/anyway/widgets/suburban_widgets/accident_count_by_accident_year_widget.py +++ b/anyway/widgets/suburban_widgets/accident_count_by_accident_year_widget.py @@ -3,7 +3,7 @@ from flask_babel import _ from anyway.request_params import RequestParams -from anyway.backend_constants import AccidentSeverity +from anyway.constants.accident_severity import AccidentSeverity from anyway.infographics_dictionaries import segment_dictionary from anyway.models import AccidentMarkerView from anyway.widgets.widget import register diff --git a/anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py b/anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py index c60ac647f..66b28414c 100644 --- a/anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py +++ b/anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py @@ -3,7 +3,7 @@ from functools import lru_cache from typing import Dict from flask_babel import _ -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.infographics_dictionaries import segment_dictionary from anyway.models import InvolvedMarkerView from anyway.vehicle_type import VehicleCategory @@ -91,8 +91,8 @@ def percentage_accidents_by_car_type_national_data_cache(start_time, end_time): table_obj=InvolvedMarkerView, filters={ "road_type": [ - BE_CONST.ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION, - BE_CONST.ROAD_TYPE_NOT_IN_CITY_IN_INTERSECTION, + BackEndConstants.ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION, + BackEndConstants.ROAD_TYPE_NOT_IN_CITY_IN_INTERSECTION, ] }, group_by="involve_vehicle_type", diff --git a/anyway/widgets/suburban_widgets/accident_count_by_day_night_widget.py b/anyway/widgets/suburban_widgets/accident_count_by_day_night_widget.py index 3ea1c3d07..a578fd202 100644 --- a/anyway/widgets/suburban_widgets/accident_count_by_day_night_widget.py +++ b/anyway/widgets/suburban_widgets/accident_count_by_day_night_widget.py @@ -6,6 +6,7 @@ from typing import Dict from flask_babel import _ + @register class AccidentCountByDayNightWidget(SubUrbanWidget): name: str = "accident_count_by_day_night" @@ -26,7 +27,5 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - items["data"]["text"] = { - "title": _("Number of accidents by day/night"), - } + items["data"]["text"] = {"title": _("Number of accidents by day/night")} return items diff --git a/anyway/widgets/suburban_widgets/accident_count_by_driver_type_widget.py b/anyway/widgets/suburban_widgets/accident_count_by_driver_type_widget.py index 26f86bc57..59e893704 100644 --- a/anyway/widgets/suburban_widgets/accident_count_by_driver_type_widget.py +++ b/anyway/widgets/suburban_widgets/accident_count_by_driver_type_widget.py @@ -5,7 +5,7 @@ from flask_babel import _ from anyway.request_params import RequestParams -from anyway.backend_constants import DriverType +from anyway.constants.driver_type import DriverType from anyway.widgets.widget_utils import get_accidents_stats, get_injured_filters from anyway.models import InvolvedMarkerView from anyway.vehicle_type import VehicleCategory @@ -72,7 +72,8 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: f"AccidentCountByDriverTypeWidget.localize_items: Exception while translating {item}." ) items["data"]["text"] = { - "title": _('Number of accidents by driver type') +f" - {request_params.location_info['road_segment_name']}" + "title": _("Number of accidents by driver type") + + f" - {request_params.location_info['road_segment_name']}" } return items diff --git a/anyway/widgets/suburban_widgets/accident_count_by_hour_widget.py b/anyway/widgets/suburban_widgets/accident_count_by_hour_widget.py index cbadb1116..03b17e259 100644 --- a/anyway/widgets/suburban_widgets/accident_count_by_hour_widget.py +++ b/anyway/widgets/suburban_widgets/accident_count_by_hour_widget.py @@ -6,6 +6,7 @@ from typing import Dict from flask_babel import _ + @register class AccidentCountByHourWidget(SubUrbanWidget): name: str = "accident_count_by_hour" @@ -27,6 +28,7 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { - "title": _('Number of accidents by hour') +f" - {request_params.location_info['road_segment_name']}" + "title": _("Number of accidents by hour") + + f" - {request_params.location_info['road_segment_name']}" } - return items \ No newline at end of file + return items diff --git a/anyway/widgets/suburban_widgets/accident_count_by_road_light_widget.py b/anyway/widgets/suburban_widgets/accident_count_by_road_light_widget.py index 221b39674..0ecbd1adb 100644 --- a/anyway/widgets/suburban_widgets/accident_count_by_road_light_widget.py +++ b/anyway/widgets/suburban_widgets/accident_count_by_road_light_widget.py @@ -6,6 +6,7 @@ from typing import Dict from flask_babel import _ + @register class AccidentCountByRoadLightWidget(SubUrbanWidget): name: str = "accident_count_by_road_light" @@ -27,6 +28,7 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { - "title": _('Number of accidents by road light') +f" - {request_params.location_info['road_segment_name']}" + "title": _("Number of accidents by road light") + + f" - {request_params.location_info['road_segment_name']}" } return items diff --git a/anyway/widgets/suburban_widgets/accident_count_by_severity_widget.py b/anyway/widgets/suburban_widgets/accident_count_by_severity_widget.py index 59fa1b4d4..ead5d4507 100644 --- a/anyway/widgets/suburban_widgets/accident_count_by_severity_widget.py +++ b/anyway/widgets/suburban_widgets/accident_count_by_severity_widget.py @@ -1,4 +1,4 @@ -from anyway.backend_constants import AccidentSeverity +from anyway.constants.accident_severity import AccidentSeverity from anyway.widgets.widget_utils import get_accidents_stats from anyway.request_params import RequestParams from anyway.models import AccidentMarkerView @@ -7,6 +7,7 @@ from flask_babel import _ from typing import Dict + @register class AccidentCountBySeverityWidget(SubUrbanWidget): name: str = "accident_count_by_severity" @@ -58,8 +59,10 @@ def get_accident_count_by_severity(location_info, start_time, end_time): @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { - "title": _('Number of accidents by severity') +f" - {request_params.location_info['road_segment_name']}" + "title": _("Number of accidents by severity") + + f" - {request_params.location_info['road_segment_name']}" } return items + _("Fatal, severe and light accidents count in the specified location.") diff --git a/anyway/widgets/suburban_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py b/anyway/widgets/suburban_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py index e6adea267..151a05fb7 100644 --- a/anyway/widgets/suburban_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py +++ b/anyway/widgets/suburban_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py @@ -40,4 +40,4 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": "Number of pedestrian accidents on Ben Yehuda street in Tel Aviv by type of hitting vehicle compared to urban accidents across the country" } - return items \ No newline at end of file + return items diff --git a/anyway/widgets/suburban_widgets/accident_severity_by_cross_location_widget.py b/anyway/widgets/suburban_widgets/accident_severity_by_cross_location_widget.py index 112c102f5..edc9db6d6 100644 --- a/anyway/widgets/suburban_widgets/accident_severity_by_cross_location_widget.py +++ b/anyway/widgets/suburban_widgets/accident_severity_by_cross_location_widget.py @@ -3,6 +3,7 @@ from anyway.widgets.suburban_widgets.sub_urban_widget import SubUrbanWidget from typing import Dict + @register class AccidentSeverityByCrossLocationWidget(SubUrbanWidget): name: str = "accident_severity_by_cross_location" @@ -49,4 +50,4 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": "Number of pedestrian accidents on Ben Yehuda street in Tel Aviv by crossing location" } - return items \ No newline at end of file + return items diff --git a/anyway/widgets/suburban_widgets/accidents_heat_map_widget.py b/anyway/widgets/suburban_widgets/accidents_heat_map_widget.py index 4694f6ae0..86309441b 100644 --- a/anyway/widgets/suburban_widgets/accidents_heat_map_widget.py +++ b/anyway/widgets/suburban_widgets/accidents_heat_map_widget.py @@ -4,12 +4,13 @@ from flask_babel import _ from anyway.request_params import RequestParams -from anyway.backend_constants import AccidentSeverity, BE_CONST +from anyway.constants.accident_severity import AccidentSeverity from anyway.infographics_dictionaries import segment_dictionary from anyway.widgets.widget_utils import get_query from anyway.models import AccidentMarkerView from anyway.widgets.widget import register from anyway.widgets.suburban_widgets.sub_urban_widget import SubUrbanWidget +from anyway.constants.backend_constants import BackEndConstants @register @@ -38,8 +39,8 @@ def generate_items(self) -> None: def get_accidents_heat_map(filters, start_time, end_time): filters = filters or {} filters["provider_code"] = [ - BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, - BE_CONST.CBS_ACCIDENT_TYPE_3_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE, ] query = get_query(AccidentMarkerView, filters, start_time, end_time) query = query.with_entities("longitude", "latitude") diff --git a/anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py b/anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py index 38fb0dea8..4ca0d9b3f 100644 --- a/anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py +++ b/anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py @@ -3,7 +3,10 @@ from flask_babel import _ from anyway.request_params import RequestParams -from anyway.backend_constants import BE_CONST, AccidentSeverity, AccidentType +from anyway.constants.backend_constants import BackEndConstants +from anyway.constants.accident_severity import AccidentSeverity +from anyway.constants.accident_type import AccidentType + from anyway.widgets.widget_utils import get_accidents_stats from anyway.models import AccidentMarkerView from anyway.widgets.widget import register @@ -31,7 +34,7 @@ def get_head_to_head_stat(self) -> Dict: road_data = {} filter_dict = { - "road_type": BE_CONST.ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION, + "road_type": BackEndConstants.ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION, "accident_severity": AccidentSeverity.FATAL.value, # pylint: disable=no-member } all_roads_data = get_accidents_stats( @@ -91,9 +94,7 @@ def sum_count_of_accident_type(data: Dict, acc_type: int) -> Dict: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: i = items["data"]["items"] - items["data"]["text"] = { - "title": _("Fatal head on collisions vs other accidents") - } + items["data"]["text"] = {"title": _("Fatal head on collisions vs other accidents")} for val in i.values(): for e in val: e["desc"] = _(e["desc"]) diff --git a/anyway/widgets/suburban_widgets/injured_count_by_accident_year_widget.py b/anyway/widgets/suburban_widgets/injured_count_by_accident_year_widget.py index 38d11ea23..f408ed96a 100644 --- a/anyway/widgets/suburban_widgets/injured_count_by_accident_year_widget.py +++ b/anyway/widgets/suburban_widgets/injured_count_by_accident_year_widget.py @@ -3,7 +3,7 @@ from flask_babel import _ from anyway.request_params import RequestParams -from anyway.backend_constants import InjurySeverity +from anyway.constants.injury_severity import InjurySeverity from anyway.infographics_dictionaries import segment_dictionary from anyway.widgets.widget_utils import ( get_accidents_stats, @@ -47,7 +47,8 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { - "title": _('Number of injured in accidents, per year, split by severity') +f" - {segment_dictionary[request_params.location_info['road_segment_name']]}", + "title": _("Number of injured in accidents, per year, split by severity") + + f" - {segment_dictionary[request_params.location_info['road_segment_name']]}", "labels_map": gen_entity_labels(InjurySeverity), } return items diff --git a/anyway/widgets/suburban_widgets/injured_count_by_severity_widget.py b/anyway/widgets/suburban_widgets/injured_count_by_severity_widget.py index 334e4af14..7a36258a1 100644 --- a/anyway/widgets/suburban_widgets/injured_count_by_severity_widget.py +++ b/anyway/widgets/suburban_widgets/injured_count_by_severity_widget.py @@ -1,7 +1,7 @@ from typing import Dict from anyway.request_params import RequestParams -from anyway.backend_constants import InjurySeverity +from anyway.constants.injury_severity import InjurySeverity from anyway.models import InvolvedMarkerView from anyway.widgets.widget import register from anyway.widgets.suburban_widgets.sub_urban_widget import SubUrbanWidget @@ -69,6 +69,7 @@ def get_injured_count_by_severity(road, segment, start_time, end_time): @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { - "title": _('Number of Injuries in accidents by severity') +f" - {request_params.location_info['road_segment_name']}" + "title": _("Number of Injuries in accidents by severity") + + f" - {request_params.location_info['road_segment_name']}" } return items diff --git a/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py b/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py index 6d532da38..ae9320c0c 100644 --- a/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py +++ b/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py @@ -2,7 +2,8 @@ from flask_babel import _ -from anyway.backend_constants import InjurySeverity as IS, BE_CONST as BE +from anyway.constants.backend_constants import BackEndConstants +from anyway.constants.injury_severity import InjurySeverity as IS from anyway.request_params import RequestParams from anyway.widgets.suburban_widgets.killed_and_injured_count_per_age_group_widget_utils import ( KilledAndInjuredCountPerAgeGroupWidgetUtils, @@ -11,18 +12,12 @@ from anyway.widgets.suburban_widgets.sub_urban_widget import SubUrbanWidget from anyway.widgets.widget import register -from anyway.widgets.widget_utils import ( - add_empty_keys_to_gen_two_level_dict, - gen_entity_labels, -) +from anyway.widgets.widget_utils import add_empty_keys_to_gen_two_level_dict, gen_entity_labels -INJURY_ORDER = [ - IS.KILLED, - IS.SEVERE_INJURED, - IS.LIGHT_INJURED, -] +INJURY_ORDER = [IS.KILLED, IS.SEVERE_INJURED, IS.LIGHT_INJURED] MAX_AGE = 200 + @register class KilledInjuredCountPerAgeGroupStackedWidget(SubUrbanWidget): name: str = "killed_and_injured_count_per_age_group_stacked" @@ -37,18 +32,21 @@ def generate_items(self) -> None: ) partial_processed = add_empty_keys_to_gen_two_level_dict( - raw_data, - self.get_age_range_list(), - IS.codes(), + raw_data, self.get_age_range_list(), IS.codes() ) structured_data_list = [] for age_group, severity_dict in partial_processed.items(): ordered_list = [ - {BE.LKEY: inj.get_label(), BE.VAL: severity_dict.get(inj.value, 0)} + { + BackEndConstants.LKEY: inj.get_label(), + BackEndConstants.VAL: severity_dict.get(inj.value, 0), + } for inj in INJURY_ORDER ] - structured_data_list.append({BE.LKEY: age_group, BE.SERIES: ordered_list}) + structured_data_list.append( + {BackEndConstants.LKEY: age_group, BackEndConstants.SERIES: ordered_list} + ) self.items = structured_data_list diff --git a/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py b/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py index 5f35172b0..f9102b48e 100644 --- a/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py +++ b/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py @@ -2,7 +2,7 @@ from flask_babel import _ -from anyway.backend_constants import BE_CONST as BE +from anyway.constants.backend_constants import BackEndConstants as BE from anyway.request_params import RequestParams from anyway.widgets.suburban_widgets.killed_and_injured_count_per_age_group_widget_utils import ( KilledAndInjuredCountPerAgeGroupWidgetUtils, diff --git a/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget_utils.py b/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget_utils.py index 866023fdf..0c0a48dab 100644 --- a/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget_utils.py +++ b/anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget_utils.py @@ -6,7 +6,8 @@ from sqlalchemy import func, asc from anyway.app_and_db import db -from anyway.backend_constants import BE_CONST, InjurySeverity as IS +from anyway.constants.backend_constants import BackEndConstants +from anyway.constants.injury_severity import InjurySeverity from anyway.models import InvolvedMarkerView from anyway.request_params import RequestParams from anyway.utilities import parse_age_from_range @@ -96,15 +97,18 @@ def create_query_for_killed_and_injured_count_per_age_group( .filter(InvolvedMarkerView.accident_timestamp <= end_time) .filter( InvolvedMarkerView.provider_code.in_( - [BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, BE_CONST.CBS_ACCIDENT_TYPE_3_CODE] + [ + BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE, + ] ) ) .filter( InvolvedMarkerView.injury_severity.in_( [ - IS.KILLED.value, # pylint: disable=no-member - IS.SEVERE_INJURED.value, # pylint: disable=no-member - IS.LIGHT_INJURED.value, # pylint: disable=no-member + InjurySeverity.KILLED.value, # pylint: disable=no-member + InjurySeverity.SEVERE_INJURED.value, # pylint: disable=no-member + InjurySeverity.LIGHT_INJURED.value, # pylint: disable=no-member ] ) ) diff --git a/anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py b/anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py index 51c01a146..2f6c7d808 100644 --- a/anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py +++ b/anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py @@ -4,7 +4,9 @@ import pandas as pd from flask_babel import _ from anyway.request_params import RequestParams -from anyway.backend_constants import BE_CONST, AccidentSeverity, AccidentType +from anyway.constants.backend_constants import BackEndConstants +from anyway.constants.accident_severity import AccidentSeverity +from anyway.constants.accident_type import AccidentType from anyway.infographics_dictionaries import segment_dictionary from anyway.widgets.widget_utils import get_query, get_accidents_stats from anyway.models import AccidentMarkerView, InvolvedMarkerView @@ -17,8 +19,8 @@ def get_most_severe_accidents_with_entities( ): filters = filters or {} filters["provider_code"] = [ - BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, - BE_CONST.CBS_ACCIDENT_TYPE_3_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE, ] # pylint: disable=no-member filters["accident_severity"] = [AccidentSeverity.FATAL.value, AccidentSeverity.SEVERE.value] diff --git a/anyway/widgets/suburban_widgets/most_severe_accidents_widget.py b/anyway/widgets/suburban_widgets/most_severe_accidents_widget.py index 3b142197c..fcbe021f4 100644 --- a/anyway/widgets/suburban_widgets/most_severe_accidents_widget.py +++ b/anyway/widgets/suburban_widgets/most_severe_accidents_widget.py @@ -4,7 +4,8 @@ from flask_babel import _ from anyway.request_params import RequestParams -from anyway.backend_constants import AccidentSeverity, AccidentType +from anyway.constants.accident_type import AccidentType +from anyway.constants.accident_severity import AccidentSeverity from anyway.widgets.suburban_widgets.most_severe_accidents_table_widget import ( get_most_severe_accidents_with_entities, ) diff --git a/anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py b/anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py index 1c4076133..fa0187cf3 100644 --- a/anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py +++ b/anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py @@ -5,7 +5,8 @@ from sqlalchemy import case, literal_column, func, distinct, desc from anyway.request_params import RequestParams -from anyway.backend_constants import BE_CONST, AccidentSeverity +from anyway.constants.backend_constants import BackEndConstants +from anyway.constants.accident_severity import AccidentSeverity from anyway.widgets.widget_utils import get_query from anyway.models import InvolvedMarkerView from anyway.vehicle_type import VehicleCategory @@ -71,7 +72,7 @@ def motorcycle_accidents_vs_all_accidents( case_vehicle, func.count(distinct(InvolvedMarkerView.provider_and_id)).label(num_accidents_label), ) - .filter(InvolvedMarkerView.road_type.in_(BE_CONST.NON_CITY_ROAD_TYPES)) + .filter(InvolvedMarkerView.road_type.in_(BackEndConstants.NON_CITY_ROAD_TYPES)) .filter( InvolvedMarkerView.accident_severity.in_( # pylint: disable=no-member @@ -134,6 +135,8 @@ def motorcycle_accidents_vs_all_accidents( @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { - "title": _('Number of fatal and severe motorcycle accidents') +f" - {request_params.location_info['road1']} " +_('compared to rest of country') + "title": _("Number of fatal and severe motorcycle accidents") + + f" - {request_params.location_info['road1']} " + + _("compared to rest of country") } return items diff --git a/anyway/widgets/suburban_widgets/road2_plus1_widget.py b/anyway/widgets/suburban_widgets/road2_plus1_widget.py index ef13aee8e..5525f8c2d 100644 --- a/anyway/widgets/suburban_widgets/road2_plus1_widget.py +++ b/anyway/widgets/suburban_widgets/road2_plus1_widget.py @@ -2,7 +2,8 @@ from typing import Optional, Dict from anyway.request_params import RequestParams -from anyway.backend_constants import BE_CONST, AccidentType +from anyway.constants.backend_constants import BackEndConstants +from anyway.constants.accident_type import AccidentType from anyway.widgets.widget_utils import get_accidents_stats from anyway.models import AccidentMarkerView from anyway.widgets.widget import register @@ -10,6 +11,7 @@ from typing import Dict from flask_babel import _ + @register class Road2Plus1Widget(SubUrbanWidget): name: str = "vision_zero_2_plus_1" @@ -25,7 +27,7 @@ def generate_items(self) -> None: def get_frontal_accidents_in_past_year(self) -> Optional[int]: location_info = self.request_params.location_info road_data = {} - filter_dict = {"road_type": BE_CONST.ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION} + filter_dict = {"road_type": BackEndConstants.ROAD_TYPE_NOT_IN_CITY_NOT_IN_INTERSECTION} if location_info["road1"] and location_info["road_segment_name"]: filter_dict.update( @@ -65,7 +67,5 @@ def is_included(self) -> bool: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - items["data"]["text"] = { - "title": _("Road 2 plus 1 solution to prevent fatal accidents"), - } + items["data"]["text"] = {"title": _("Road 2 plus 1 solution to prevent fatal accidents")} return items diff --git a/anyway/widgets/suburban_widgets/street_view_widget.py b/anyway/widgets/suburban_widgets/street_view_widget.py index c065c9d6c..6784b8bba 100644 --- a/anyway/widgets/suburban_widgets/street_view_widget.py +++ b/anyway/widgets/suburban_widgets/street_view_widget.py @@ -4,6 +4,7 @@ from typing import Dict from flask_babel import _ + @register class StreetViewWidget(SubUrbanWidget): name: str = "street_view" @@ -20,8 +21,5 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - items["data"]["text"] = { - "title": _("Street view widget"), - } + items["data"]["text"] = {"title": _("Street view widget")} return items - diff --git a/anyway/widgets/suburban_widgets/suburban_crosswalk_widget.py b/anyway/widgets/suburban_widgets/suburban_crosswalk_widget.py index 16d827cd8..c27ae56ff 100644 --- a/anyway/widgets/suburban_widgets/suburban_crosswalk_widget.py +++ b/anyway/widgets/suburban_widgets/suburban_crosswalk_widget.py @@ -1,13 +1,13 @@ from typing import Dict from anyway.request_params import RequestParams -from anyway.backend_constants import InjurySeverity +from anyway.constants.injury_severity import InjurySeverity from anyway.models import InvolvedMarkerView from anyway.widgets.suburban_widgets.sub_urban_widget import SubUrbanWidget from anyway.widgets.widget_utils import get_accidents_stats from flask_babel import _ -from anyway.backend_constants import CrossCategory +from anyway.constants.cross_category import CrossCategory # TODO: pretty sure there are errors in this widget, for example, is_included returns self.items diff --git a/anyway/widgets/suburban_widgets/top_road_segments_accidents_per_km_widget.py b/anyway/widgets/suburban_widgets/top_road_segments_accidents_per_km_widget.py index 24a4e1473..1c704ef21 100644 --- a/anyway/widgets/suburban_widgets/top_road_segments_accidents_per_km_widget.py +++ b/anyway/widgets/suburban_widgets/top_road_segments_accidents_per_km_widget.py @@ -7,7 +7,7 @@ # noinspection PyProtectedMember from flask_babel import _ from anyway.request_params import RequestParams -from anyway.backend_constants import AccidentSeverity +from anyway.constants.accident_severity import AccidentSeverity from anyway.widgets.widget import register from anyway.widgets.widget_utils import get_query from anyway.models import AccidentMarkerView @@ -78,8 +78,10 @@ def get_top_road_segments_accidents_per_km( @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { - "title": _('Segments with most accidents per Km') +f" - {request_params.location_info['road1']}" + "title": _("Segments with most accidents per Km") + + f" - {request_params.location_info['road1']}" } return items -_("Severe and fatal accidents per Km by section in road") \ No newline at end of file + +_("Severe and fatal accidents per Km by section in road") diff --git a/anyway/widgets/suburban_widgets/top_road_segments_accidents_widget.py b/anyway/widgets/suburban_widgets/top_road_segments_accidents_widget.py index a1d6a790f..025d87f4e 100644 --- a/anyway/widgets/suburban_widgets/top_road_segments_accidents_widget.py +++ b/anyway/widgets/suburban_widgets/top_road_segments_accidents_widget.py @@ -28,7 +28,5 @@ def top_road_segments_accidents_mock_data(): # Temporary for Frontend @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - items["data"]["text"] = { - "title": _("Segments with most accidents"), - } + items["data"]["text"] = {"title": _("Segments with most accidents")} return items diff --git a/anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py b/anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py index d774bf30b..d778e7cf1 100644 --- a/anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py +++ b/anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py @@ -6,7 +6,8 @@ from flask_babel import _ from anyway.request_params import RequestParams from anyway.app_and_db import db -from anyway.backend_constants import InjurySeverity, InjuredType +from anyway.constants.injured_type import InjuredType +from anyway.constants.injury_severity import InjurySeverity from anyway.widgets.widget_utils import add_empty_keys_to_gen_two_level_dict, gen_entity_labels from anyway.models import NewsFlash, InvolvedMarkerView from anyway.widgets.widget import register @@ -104,7 +105,8 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { - "title": _('Pedestrian accidents by severity and year') +f" - {request_params.location_text}", + "title": _("Pedestrian accidents by severity and year") + + f" - {request_params.location_text}", "labels": gen_entity_labels(InjurySeverity), } - return items \ No newline at end of file + return items diff --git a/anyway/widgets/urban_widgets/severe_fatal_count_by_vehicle_by_year_widget.py b/anyway/widgets/urban_widgets/severe_fatal_count_by_vehicle_by_year_widget.py index e2866d419..44db8e9ad 100644 --- a/anyway/widgets/urban_widgets/severe_fatal_count_by_vehicle_by_year_widget.py +++ b/anyway/widgets/urban_widgets/severe_fatal_count_by_vehicle_by_year_widget.py @@ -1,7 +1,7 @@ from typing import Dict from anyway.request_params import RequestParams -from anyway.backend_constants import InjurySeverity +from anyway.constants.injury_severity import InjurySeverity from anyway.models import InvolvedMarkerView from anyway.vehicle_type import VehicleType from anyway.widgets.urban_widgets.urban_widget import UrbanWidget diff --git a/anyway/widgets/urban_widgets/small_motor_severe_fatal_count_by_year_widget.py b/anyway/widgets/urban_widgets/small_motor_severe_fatal_count_by_year_widget.py index 08f49ab73..d716bcdf3 100644 --- a/anyway/widgets/urban_widgets/small_motor_severe_fatal_count_by_year_widget.py +++ b/anyway/widgets/urban_widgets/small_motor_severe_fatal_count_by_year_widget.py @@ -1,7 +1,7 @@ from typing import Dict from anyway.request_params import RequestParams -from anyway.backend_constants import InjurySeverity +from anyway.constants.injury_severity import InjurySeverity from anyway.models import InvolvedMarkerView from anyway.vehicle_type import VehicleCategory from anyway.widgets.urban_widgets.urban_widget import UrbanWidget diff --git a/anyway/widgets/urban_widgets/urban_crosswalk_widget.py b/anyway/widgets/urban_widgets/urban_crosswalk_widget.py index 3547ea7f9..68bb3c00e 100644 --- a/anyway/widgets/urban_widgets/urban_crosswalk_widget.py +++ b/anyway/widgets/urban_widgets/urban_crosswalk_widget.py @@ -1,13 +1,13 @@ from typing import Dict from anyway.request_params import RequestParams -from anyway.backend_constants import InjurySeverity +from anyway.constants.injury_severity import InjurySeverity from anyway.models import InvolvedMarkerView from anyway.widgets.urban_widgets.urban_widget import UrbanWidget from anyway.widgets.widget_utils import get_accidents_stats from flask_babel import _ -from anyway.backend_constants import CrossCategory +from anyway.constants.cross_category import CrossCategory # TODO: pretty sure there are errors in this widget, for example, is_included returns self.items diff --git a/anyway/widgets/widget_utils.py b/anyway/widgets/widget_utils.py index 0f78eb7a4..6fde1ab67 100644 --- a/anyway/widgets/widget_utils.py +++ b/anyway/widgets/widget_utils.py @@ -7,7 +7,8 @@ from sqlalchemy import func from anyway.app_and_db import db -from anyway.backend_constants import BE_CONST, LabeledCode +from anyway.constants.backend_constants import BackEndConstants +from anyway.constants.label_code import LabeledCode def get_query(table_obj, filters, start_time, end_time): @@ -31,8 +32,8 @@ def get_accidents_stats( ): filters = filters or {} filters["provider_code"] = [ - BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, - BE_CONST.CBS_ACCIDENT_TYPE_3_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_1_CODE, + BackEndConstants.CBS_ACCIDENT_TYPE_3_CODE, ] # get stats query = get_query(table_obj, filters, start_time, end_time) @@ -120,6 +121,6 @@ def format_2_level_items( series_data = [] for l2_code, num in year_res.items(): l2 = level2_vals.labels()[level2_vals(l2_code)] if level2_vals else l2_code - series_data.append({BE_CONST.LKEY: l2, BE_CONST.VAL: num}) - res.append({BE_CONST.LKEY: l1, BE_CONST.SERIES: series_data}) + series_data.append({BackEndConstants.LKEY: l2, BackEndConstants.VAL: num}) + res.append({BackEndConstants.LKEY: l1, BackEndConstants.SERIES: series_data}) return res diff --git a/messages.pot b/messages.pot index e81389302..3d6903221 100644 --- a/messages.pot +++ b/messages.pot @@ -8,26 +8,14 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2022-01-08 14:56+0200\n" +"POT-Creation-Date: 2022-01-15 12:35+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.9.1\n" - -#: anyway/backend_constants.py:149 -msgid "killed" -msgstr "" - -#: anyway/backend_constants.py:150 -msgid "severe injured" -msgstr "" - -#: anyway/backend_constants.py:151 -msgid "light injured" -msgstr "" +"Generated-By: Babel 2.6.0\n" #: anyway/flask_app.py:677 anyway/flask_app.py:782 msgid "Discussion not found:" @@ -261,6 +249,18 @@ msgstr "" msgid "other" msgstr "" +#: anyway/constants/backend_constants.py:109 +msgid "killed" +msgstr "" + +#: anyway/constants/backend_constants.py:110 +msgid "severe injured" +msgstr "" + +#: anyway/constants/backend_constants.py:111 +msgid "light injured" +msgstr "" + #: anyway/widgets/suburban_widgets/accident_count_by_accident_type_widget.py:46 msgid "Number of accidents by accident type" msgstr "" @@ -275,7 +275,7 @@ msgid "" "accident severity" msgstr "" -#: anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py:114 +#: anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py:115 msgid "" "comparing vehicle type percentage in accidents in {} relative to national" " average" @@ -316,27 +316,27 @@ msgstr "" msgid "Fatal, severe and light accidents count in the specified location." msgstr "" -#: anyway/widgets/suburban_widgets/accidents_heat_map_widget.py:52 +#: anyway/widgets/suburban_widgets/accidents_heat_map_widget.py:53 msgid "Fatal and severe accidents heat map" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:95 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:98 msgid "Fatal head on collisions vs other accidents" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:99 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:102 msgid "desc" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:126 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:129 msgid "others" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:127 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:130 msgid "frontal" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:128 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:131 msgid "" "Fatal accidents distribution by accident type - head on collisions vs " "other accidents." @@ -356,53 +356,53 @@ msgstr "" msgid "Number of Injuries in accidents by severity" msgstr "" -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:52 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:59 msgid "Killed and injury stacked per age group" msgstr "" -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:38 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:60 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:40 msgid "In" msgstr "" -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:37 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:39 msgid "Injury per age group" msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:36 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:38 msgid "Most severe accidents in segment" msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:130 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:132 msgid "accident_severity" msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:131 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:133 msgid "type" msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:143 -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:146 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:145 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:148 msgid "" "Most recent fatal and severe accidents in location, ordered by date. Up " "to 10 accidents are presented." msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_widget.py:63 +#: anyway/widgets/suburban_widgets/most_severe_accidents_widget.py:64 msgid "" "Most recent fatal and severe accidents displayed on a map. Up to 10 " "accidents are presented." msgstr "" -#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:137 +#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:138 msgid "Number of fatal and severe motorcycle accidents" msgstr "" -#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:137 +#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:138 msgid "compared to rest of country" msgstr "" -#: anyway/widgets/suburban_widgets/road2_plus1_widget.py:69 +#: anyway/widgets/suburban_widgets/road2_plus1_widget.py:70 msgid "Road 2 plus 1 solution to prevent fatal accidents" msgstr "" @@ -427,7 +427,7 @@ msgstr "" msgid "Segments with most accidents" msgstr "" -#: anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py:107 +#: anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py:108 msgid "Pedestrian accidents by severity and year" msgstr "" diff --git a/tests/test_flask.py b/tests/test_flask.py index 40e4aa767..14bb479a4 100644 --- a/tests/test_flask.py +++ b/tests/test_flask.py @@ -15,7 +15,7 @@ from urlobject import URLObject from anyway.app_and_db import app as flask_app -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.error_code_and_strings import ( ERROR_TO_HTTP_CODE_DICT, build_json_for_user_api_error, @@ -346,10 +346,10 @@ def user_add_or_remove_role(app: FlaskClient, path: str) -> None: with patch("anyway.views.user_system.api.get_role_object") as get_role_object: get_role_object.return_value = mock.MagicMock() - get_role_object.return_value.name = BE_CONST.Roles2Names.Admins.value + get_role_object.return_value.name = BackEndConstants.Roles2Names.Admins.value rv = post_json( - app, path, json_data={"role": BE_CONST.Roles2Names.Admins.value, "email": "a"} + app, path, json_data={"role": BackEndConstants.Roles2Names.Admins.value, "email": "a"} ) assert_return_code_for_user_update(Errors.BR_USER_NOT_FOUND, rv, extra="a") @@ -359,7 +359,7 @@ def set_mock_and_test_perm(app, current_user, path): rv = app.post(path, follow_redirects=True) assert_return_code_for_user_update(Errors.BR_BAD_AUTH, rv) role = mock.MagicMock() - role.name = BE_CONST.Roles2Names.Admins.value + role.name = BackEndConstants.Roles2Names.Admins.value current_user.return_value.roles = [role] diff --git a/tests/test_infographics_data_cache.py b/tests/test_infographics_data_cache.py index 098187d75..215317784 100644 --- a/tests/test_infographics_data_cache.py +++ b/tests/test_infographics_data_cache.py @@ -4,7 +4,7 @@ from unittest.mock import Mock, patch from anyway.infographics_utils import get_infographics_data from anyway.models import NewsFlash -from anyway.constants import CONST +from anyway.constants.constants import Constants from anyway.parsers.infographics_data_cache_updater import add_news_flash_to_cache import anyway.parsers.infographics_data_cache_updater @@ -59,11 +59,11 @@ def test_add_qualified_news_flash(self, utils, get_engine): res = add_news_flash_to_cache(nf) invocations = utils.call_args_list utils.assert_has_calls( - [unittest.mock.call(17, y, "he") for y in CONST.INFOGRAPHICS_CACHE_YEARS_AGO] + [unittest.mock.call(17, y, "he") for y in Constants.INFOGRAPHICS_CACHE_YEARS_AGO] ) for i in range(len(invocations)): self.assertEqual(invocations[i][0][0], 17, "incorrect news flash id") - self.assertEqual(invocations[i][0][1], CONST.INFOGRAPHICS_CACHE_YEARS_AGO[i]) + self.assertEqual(invocations[i][0][1], Constants.INFOGRAPHICS_CACHE_YEARS_AGO[i]) assert res, "Should return True when no error occurred" @patch("anyway.parsers.infographics_data_cache_updater.db.get_engine") diff --git a/tests/test_infographics_utils.py b/tests/test_infographics_utils.py index fc5ad0f6f..b8ff6eec2 100644 --- a/tests/test_infographics_utils.py +++ b/tests/test_infographics_utils.py @@ -1,6 +1,6 @@ import unittest from anyway.widgets.widget_utils import format_2_level_items -from anyway.backend_constants import AccidentSeverity +from anyway.constants.accident_severity import AccidentSeverity class TestInfographicsUtilsCase(unittest.TestCase): diff --git a/tests/test_news_flash_api.py b/tests/test_news_flash_api.py index f4ac44319..10920bac1 100644 --- a/tests/test_news_flash_api.py +++ b/tests/test_news_flash_api.py @@ -6,7 +6,7 @@ is_news_flash_resolution_supported, gen_news_flash_query ) -from anyway.backend_constants import BE_CONST +from anyway.constants.backend_constants import BackEndConstants from anyway.models import NewsFlash @@ -67,9 +67,9 @@ def test_is_news_flash_resolution_supported(self, mock_extract): def test_gen_news_flash_query(self): - orig_supported_resolutions = BE_CONST.SUPPORTED_RESOLUTIONS - BE_CONST.SUPPORTED_RESOLUTIONS = [ - BE_CONST.ResolutionCategories.DISTRICT + orig_supported_resolutions = BackEndConstants.SUPPORTED_RESOLUTIONS + BackEndConstants.SUPPORTED_RESOLUTIONS = [ + BackEndConstants.ResolutionCategories.DISTRICT ] actual = gen_news_flash_query(self.session, road_number=12345678) news_flashes = actual.all() @@ -77,8 +77,8 @@ def test_gen_news_flash_query(self): self.assertEqual(news_flashes[0].description, self.district_description, "district description") - BE_CONST.SUPPORTED_RESOLUTIONS = [ - BE_CONST.ResolutionCategories.REGION + BackEndConstants.SUPPORTED_RESOLUTIONS = [ + BackEndConstants.ResolutionCategories.REGION ] actual = gen_news_flash_query(self.session, road_number=12345678) news_flashes = actual.all() @@ -86,14 +86,14 @@ def test_gen_news_flash_query(self): self.assertEqual(news_flashes[0].description, self.region_description, "region description") - BE_CONST.SUPPORTED_RESOLUTIONS = [ - BE_CONST.ResolutionCategories.CITY + BackEndConstants.SUPPORTED_RESOLUTIONS = [ + BackEndConstants.ResolutionCategories.CITY ] actual = gen_news_flash_query(self.session, road_number=12345678) news_flashes = actual.all() self.assertEqual(len(news_flashes), 0, "zero news flash") - BE_CONST.SUPPORTED_RESOLUTIONS = orig_supported_resolutions + BackEndConstants.SUPPORTED_RESOLUTIONS = orig_supported_resolutions def tearDown(self): self.session.close() diff --git a/translations/en/LC_MESSAGES/messages.mo b/translations/en/LC_MESSAGES/messages.mo index 0720e3322..5531358c9 100644 Binary files a/translations/en/LC_MESSAGES/messages.mo and b/translations/en/LC_MESSAGES/messages.mo differ diff --git a/translations/en/LC_MESSAGES/messages.po b/translations/en/LC_MESSAGES/messages.po index 705bbd991..27b44a0cb 100644 --- a/translations/en/LC_MESSAGES/messages.po +++ b/translations/en/LC_MESSAGES/messages.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2022-01-08 14:56+0200\n" +"POT-Creation-Date: 2022-01-15 12:35+0200\n" "PO-Revision-Date: 2020-11-26 16:45+0200\n" "Last-Translator: FULL NAME \n" "Language: en\n" @@ -16,19 +16,7 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.9.1\n" - -#: anyway/backend_constants.py:149 -msgid "killed" -msgstr "killed" - -#: anyway/backend_constants.py:150 -msgid "severe injured" -msgstr "severe injured" - -#: anyway/backend_constants.py:151 -msgid "light injured" -msgstr "light injured" +"Generated-By: Babel 2.6.0\n" #: anyway/flask_app.py:677 anyway/flask_app.py:782 msgid "Discussion not found:" @@ -262,6 +250,18 @@ msgstr "" msgid "other" msgstr "" +#: anyway/constants/backend_constants.py:109 +msgid "killed" +msgstr "killed" + +#: anyway/constants/backend_constants.py:110 +msgid "severe injured" +msgstr "severe injured" + +#: anyway/constants/backend_constants.py:111 +msgid "light injured" +msgstr "light injured" + #: anyway/widgets/suburban_widgets/accident_count_by_accident_type_widget.py:46 msgid "Number of accidents by accident type" msgstr "" @@ -276,7 +276,7 @@ msgid "" "accident severity" msgstr "" -#: anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py:114 +#: anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py:115 msgid "" "comparing vehicle type percentage in accidents in {} relative to national" " average" @@ -317,27 +317,27 @@ msgstr "" msgid "Fatal, severe and light accidents count in the specified location." msgstr "" -#: anyway/widgets/suburban_widgets/accidents_heat_map_widget.py:52 +#: anyway/widgets/suburban_widgets/accidents_heat_map_widget.py:53 msgid "Fatal and severe accidents heat map" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:95 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:98 msgid "Fatal head on collisions vs other accidents" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:99 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:102 msgid "desc" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:126 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:129 msgid "others" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:127 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:130 msgid "frontal" msgstr "" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:128 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:131 msgid "" "Fatal accidents distribution by accident type - head on collisions vs " "other accidents." @@ -357,53 +357,53 @@ msgstr "" msgid "Number of Injuries in accidents by severity" msgstr "" -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:52 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:59 msgid "Killed and injury stacked per age group" msgstr "" -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:38 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:60 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:40 msgid "In" msgstr "" -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:37 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:39 msgid "Injury per age group" msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:36 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:38 msgid "Most severe accidents in segment" msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:130 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:132 msgid "accident_severity" msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:131 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:133 msgid "type" msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:143 -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:146 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:145 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:148 msgid "" "Most recent fatal and severe accidents in location, ordered by date. Up " "to 10 accidents are presented." msgstr "" -#: anyway/widgets/suburban_widgets/most_severe_accidents_widget.py:63 +#: anyway/widgets/suburban_widgets/most_severe_accidents_widget.py:64 msgid "" "Most recent fatal and severe accidents displayed on a map. Up to 10 " "accidents are presented." msgstr "" -#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:137 +#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:138 msgid "Number of fatal and severe motorcycle accidents" msgstr "" -#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:137 +#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:138 msgid "compared to rest of country" msgstr "" -#: anyway/widgets/suburban_widgets/road2_plus1_widget.py:69 +#: anyway/widgets/suburban_widgets/road2_plus1_widget.py:70 msgid "Road 2 plus 1 solution to prevent fatal accidents" msgstr "" @@ -428,7 +428,7 @@ msgstr "" msgid "Segments with most accidents" msgstr "" -#: anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py:107 +#: anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py:108 msgid "Pedestrian accidents by severity and year" msgstr "" diff --git a/translations/he/LC_MESSAGES/messages.mo b/translations/he/LC_MESSAGES/messages.mo index f2322de27..f268ca34f 100644 Binary files a/translations/he/LC_MESSAGES/messages.mo and b/translations/he/LC_MESSAGES/messages.mo differ diff --git a/translations/he/LC_MESSAGES/messages.po b/translations/he/LC_MESSAGES/messages.po index 305e35c9a..91177ec4e 100644 --- a/translations/he/LC_MESSAGES/messages.po +++ b/translations/he/LC_MESSAGES/messages.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2022-01-08 14:56+0200\n" +"POT-Creation-Date: 2022-01-15 12:35+0200\n" "PO-Revision-Date: 2020-10-16 15:42+0000\n" "Last-Translator: FULL NAME \n" "Language: he\n" @@ -16,19 +16,7 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.9.1\n" - -#: anyway/backend_constants.py:149 -msgid "killed" -msgstr "הרוג/ה" - -#: anyway/backend_constants.py:150 -msgid "severe injured" -msgstr "פצוע/ה קשה" - -#: anyway/backend_constants.py:151 -msgid "light injured" -msgstr "פצוע/ה קל" +"Generated-By: Babel 2.6.0\n" #: anyway/flask_app.py:677 anyway/flask_app.py:782 msgid "Discussion not found:" @@ -262,6 +250,18 @@ msgstr "אופניים/קורקינט" msgid "other" msgstr "אחרות" +#: anyway/constants/backend_constants.py:109 +msgid "killed" +msgstr "הרוג/ה" + +#: anyway/constants/backend_constants.py:110 +msgid "severe injured" +msgstr "פצוע/ה קשה" + +#: anyway/constants/backend_constants.py:111 +msgid "light injured" +msgstr "פצוע/ה קל" + #: anyway/widgets/suburban_widgets/accident_count_by_accident_type_widget.py:46 msgid "Number of accidents by accident type" msgstr "מספר תאונות לפי סוג" @@ -278,7 +278,7 @@ msgstr "" "כמות התאונות הקטלניות, הקשות והקלות במקטע, לפי שנת התאונה, מחולק לפי " "חומרת התאונה, בפרק הזמן הנבחר." -#: anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py:114 +#: anyway/widgets/suburban_widgets/accident_count_by_car_type_widget.py:115 msgid "" "comparing vehicle type percentage in accidents in {} relative to national" " average" @@ -322,27 +322,27 @@ msgstr "מספר תאונות לפי חומרה" msgid "Fatal, severe and light accidents count in the specified location." msgstr "כמות התאונות הקטלניות, הקשות והקלות במקטע בפרק הזמן הנבחר." -#: anyway/widgets/suburban_widgets/accidents_heat_map_widget.py:52 +#: anyway/widgets/suburban_widgets/accidents_heat_map_widget.py:53 msgid "Fatal and severe accidents heat map" msgstr "מוקדי תאונות קטלניות וקשות במקטע" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:95 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:98 msgid "Fatal head on collisions vs other accidents" msgstr "תאונות קטלניות בהתנגשות חזיתית כנגד שאר התאונות" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:99 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:102 msgid "desc" msgstr "תאור" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:126 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:129 msgid "others" msgstr "אחרות" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:127 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:130 msgid "frontal" msgstr "חזיתיות" -#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:128 +#: anyway/widgets/suburban_widgets/head_on_collisions_comparison_widget.py:131 msgid "" "Fatal accidents distribution by accident type - head on collisions vs " "other accidents." @@ -364,33 +364,33 @@ msgstr "" msgid "Number of Injuries in accidents by severity" msgstr "מספר תאונות לפי חומרה" -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:52 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:59 msgid "Killed and injury stacked per age group" msgstr "חומרת פגיעה לפי קבוצת גיל" -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:38 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:60 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:40 msgid "In" msgstr "במקטע" -#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:37 +#: anyway/widgets/suburban_widgets/killed_and_injured_count_per_age_group_widget.py:39 msgid "Injury per age group" msgstr "נפגעים לפי קבוצת גיל" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:36 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:38 msgid "Most severe accidents in segment" msgstr "תאונות חמורות במקטע" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:130 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:132 msgid "accident_severity" msgstr "חומרת תאונה" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:131 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:133 msgid "type" msgstr "סוג" -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:143 -#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:146 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:145 +#: anyway/widgets/suburban_widgets/most_severe_accidents_table_widget.py:148 msgid "" "Most recent fatal and severe accidents in location, ordered by date. Up " "to 10 accidents are presented." @@ -398,7 +398,7 @@ msgstr "" "התאונות החמורות (קשות וקטלניות) האחרונות, מסודרות לפי תאריך בסדר יורד. " "מוצגות עד 10 תאונות." -#: anyway/widgets/suburban_widgets/most_severe_accidents_widget.py:63 +#: anyway/widgets/suburban_widgets/most_severe_accidents_widget.py:64 msgid "" "Most recent fatal and severe accidents displayed on a map. Up to 10 " "accidents are presented." @@ -406,15 +406,15 @@ msgstr "" "התאונות החמורות (קשות וקטלניות) האחרונות מוצגות על גבי מפה. מוצגות עד 10 " "תאונות." -#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:137 +#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:138 msgid "Number of fatal and severe motorcycle accidents" msgstr "תאונות אופנוע קטלניות" -#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:137 +#: anyway/widgets/suburban_widgets/motorcycle_accidents_vs_all_accidents_widget.py:138 msgid "compared to rest of country" msgstr "בהשוואה לשאר הארץ" -#: anyway/widgets/suburban_widgets/road2_plus1_widget.py:69 +#: anyway/widgets/suburban_widgets/road2_plus1_widget.py:70 msgid "Road 2 plus 1 solution to prevent fatal accidents" msgstr "פתרון כביש 2 פלוס 1 למניעת תאונות קטלניות" @@ -440,7 +440,7 @@ msgstr "תאונות קטלניות וקשות לכל קילומטר לפי מק msgid "Segments with most accidents" msgstr "מקטעים עם הכי הרבה תאונות" -#: anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py:107 +#: anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py:108 msgid "Pedestrian accidents by severity and year" msgstr "תאונות הולכי רגל לפי חומרה ולפי שנה"