From 2bdeeb6b14eaf9de99754cddd308f4d1c97f7513 Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Wed, 20 Dec 2023 23:51:43 +0200 Subject: [PATCH 01/12] move widgets to all locations --- .../anyway-newsflash-infographics | 1 + anyway/flask_app.py | 2 +- .../widgets/all_locations_widgets/__init__.py | 5 +- .../accident_count_by_severity_widget.py | 4 + .../injured_count_by_severity_widget.py | 60 +++-- ...ured_count_per_age_group_stacked_widget.py | 11 +- ..._and_injured_count_per_age_group_widget.py | 11 +- ...njured_count_per_age_group_widget_utils.py | 42 ++- ...jured_killed_in_bicycles_scooter_widget.py | 2 +- .../widgets/road_segment_widgets/__init__.py | 3 - messages.pot | 211 ++++++++------- translations/en/LC_MESSAGES/messages.mo | Bin 1827 -> 1827 bytes translations/en/LC_MESSAGES/messages.po | 249 +++++++++--------- translations/he/LC_MESSAGES/messages.mo | Bin 11777 -> 11777 bytes translations/he/LC_MESSAGES/messages.po | 211 ++++++++------- 15 files changed, 428 insertions(+), 384 deletions(-) create mode 160000 anyway-newsflash-infographics/anyway-newsflash-infographics rename anyway/widgets/{road_segment_widgets => all_locations_widgets}/injured_count_by_severity_widget.py (75%) rename anyway/widgets/{road_segment_widgets => all_locations_widgets}/killed_and_injured_count_per_age_group_stacked_widget.py (81%) rename anyway/widgets/{road_segment_widgets => all_locations_widgets}/killed_and_injured_count_per_age_group_widget.py (71%) rename anyway/widgets/{road_segment_widgets => all_locations_widgets}/killed_and_injured_count_per_age_group_widget_utils.py (68%) diff --git a/anyway-newsflash-infographics/anyway-newsflash-infographics b/anyway-newsflash-infographics/anyway-newsflash-infographics new file mode 160000 index 000000000..f659f4182 --- /dev/null +++ b/anyway-newsflash-infographics/anyway-newsflash-infographics @@ -0,0 +1 @@ +Subproject commit f659f4182df238c032831eb6cefc41bb0aed6d91 diff --git a/anyway/flask_app.py b/anyway/flask_app.py index 534a848b8..d1b94d31b 100755 --- a/anyway/flask_app.py +++ b/anyway/flask_app.py @@ -1194,7 +1194,7 @@ def get(self): Returns infographics-data API """ parser = reqparse.RequestParser() -parser.add_argument("id", type=int, help="News flash id") +parser.add_argument("news_flash_id", type=int, help="News flash id") parser.add_argument( "years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years" ) diff --git a/anyway/widgets/all_locations_widgets/__init__.py b/anyway/widgets/all_locations_widgets/__init__.py index 0eb943e35..4f55bfa5e 100644 --- a/anyway/widgets/all_locations_widgets/__init__.py +++ b/anyway/widgets/all_locations_widgets/__init__.py @@ -1,6 +1,9 @@ from . import ( accident_count_by_severity_widget, + injured_count_by_severity_widget, most_severe_accidents_widget, most_severe_accidents_table_widget, - seriously_injured_killed_in_bicycles_scooter_widget + seriously_injured_killed_in_bicycles_scooter_widget, + killed_and_injured_count_per_age_group_stacked_widget, + killed_and_injured_count_per_age_group_widget ) diff --git a/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py index 546ad583e..d67cdcef7 100644 --- a/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py @@ -97,6 +97,10 @@ def get_transcription(request_params: RequestParams, items: Dict): in_segment_keyword=_("in segment"), segment_name=_(request_params.location_info.get('road_segment_name')), ) + elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_JUNCTION: + text = "{in_urban_intersection}".format( + in_urban_intersection=request_params.location_info.get('non_urban_intersection_hebrew') + ) else: raise Exception(f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}") text += "{between_years_keyword} {start_year} - {end_year}, {separator_keyword} {incidents_num} {incident_keyword}, {out_of_them_keywoard} ".format( diff --git a/anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py similarity index 75% rename from anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py rename to anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py index 0f6b297a8..8e0a27108 100644 --- a/anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py @@ -1,17 +1,17 @@ from typing import Dict - +import copy from anyway.request_params import RequestParams from anyway.backend_constants import InjurySeverity from anyway.models import InvolvedMarkerView +from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget from anyway.widgets.widget import register -from anyway.widgets.road_segment_widgets.road_segment_widget import RoadSegmentWidget from anyway.widgets.widget_utils import get_accidents_stats, join_strings from anyway.backend_constants import BE_CONST from flask_babel import _ @register -class InjuredCountBySeverityWidget(RoadSegmentWidget): +class InjuredCountBySeverityWidget(AllLocationsWidget): name: str = "injured_count_by_severity" files = [__file__] @@ -22,29 +22,35 @@ def __init__(self, request_params: RequestParams): def generate_items(self) -> None: self.items = InjuredCountBySeverityWidget.get_injured_count_by_severity( - self.request_params.location_info["road1"], - self.request_params.location_info["road_segment_name"], + self.request_params.resolution, + self.request_params.location_info, self.request_params.start_time, - self.request_params.end_time, + self.request_params.end_time ) @staticmethod - def get_injured_count_by_severity(road, segment, start_time, end_time): - count_by_severity = get_accidents_stats( - table_obj=InvolvedMarkerView, - filters={ - "injury_severity": [ + def get_injured_count_by_severity(resolution, location_info, start_time, end_time): + filters = {} + filters["injury_severity"] = [ InjurySeverity.KILLED.value, InjurySeverity.SEVERE_INJURED.value, InjurySeverity.LIGHT_INJURED.value, - ], - "road1": road, - "road_segment_name": segment, - }, - group_by="injury_severity", - count="injury_severity", - start_time=start_time, - end_time=end_time, + ] + + if resolution == BE_CONST.ResolutionCategories.STREET: + filters["involve_yishuv_name"] = location_info.get('yishuv_name') + filters["street1_hebrew"] = location_info.get('street1_hebrew') + elif resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + filters["road1"] = location_info.get('road1') + filters["road_segment_name"] = location_info.get('road_segment_name') + + count_by_severity = get_accidents_stats( + table_obj = InvolvedMarkerView, + filters = filters, + group_by = "injury_severity", + count = "injury_severity", + start_time = start_time, + end_time = end_time, ) found_severities = [d["injury_severity"] for d in count_by_severity] items = {} @@ -128,13 +134,25 @@ def get_transcription(request_params: RequestParams, items: Dict): @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: + + subtitle = InjuredCountBySeverityWidget.get_injured_count_by_severity_table_title(request_params.location_info, + request_params.resolution) items["data"]["text"] = { "title": _("Number of Injuries in accidents by severity"), - "subtitle": _(request_params.location_info['road_segment_name']), + "subtitle": _(subtitle), "transcription": InjuredCountBySeverityWidget.get_transcription(request_params=request_params, items=items["data"]["items"]) } return items + + @staticmethod + def get_injured_count_by_severity_table_title(location_info: dict, resolution: BE_CONST.ResolutionCategories): + if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + return location_info["road_segment_name"] + elif resolution == BE_CONST.ResolutionCategories.STREET: + in_str = _("in") + return f"{location_info['street1_hebrew']} {in_str}{location_info['yishuv_name']}" + _("injured/killed") @@ -144,4 +162,4 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: _("one severe injured") _("severe injured plural") _("one light injured") -_("light injured plural") \ No newline at end of file +_("light injured plural") diff --git a/anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_stacked_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py similarity index 81% rename from anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_stacked_widget.py rename to anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py index 140a1bc40..32b5a6f12 100644 --- a/anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_stacked_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py @@ -4,13 +4,13 @@ from anyway.backend_constants import InjurySeverity, BE_CONST as BE from anyway.request_params import RequestParams -from anyway.widgets.road_segment_widgets.killed_and_injured_count_per_age_group_widget_utils import ( +from anyway.widgets.all_locations_widgets.killed_and_injured_count_per_age_group_widget_utils import ( KilledAndInjuredCountPerAgeGroupWidgetUtils, AGE_RANGE_DICT, ) -from anyway.widgets.road_segment_widgets import killed_and_injured_count_per_age_group_widget_utils +from anyway.widgets.all_locations_widgets import killed_and_injured_count_per_age_group_widget_utils -from anyway.widgets.road_segment_widgets.road_segment_widget import RoadSegmentWidget +from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget from anyway.widgets.widget import register from anyway.widgets.widget_utils import add_empty_keys_to_gen_two_level_dict, gen_entity_labels @@ -19,7 +19,7 @@ @register -class KilledInjuredCountPerAgeGroupStackedWidget(RoadSegmentWidget): +class KilledInjuredCountPerAgeGroupStackedWidget(AllLocationsWidget): name: str = "killed_and_injured_count_per_age_group_stacked" files = [__file__, killed_and_injured_count_per_age_group_widget_utils.__file__] @@ -48,9 +48,10 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: + location_text = KilledAndInjuredCountPerAgeGroupWidgetUtils.get_location_text(request_params) items["data"]["text"] = { "title": _("Killed and injury stacked per age group"), - "subtitle": _(request_params.location_info["road_segment_name"]), + "subtitle": location_text, "labels_map": gen_entity_labels(InjurySeverity), } return items diff --git a/anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py similarity index 71% rename from anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py rename to anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py index 93d9f1fe3..1dc5b4b41 100644 --- a/anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py @@ -4,15 +4,15 @@ from anyway.backend_constants import BE_CONST as BE from anyway.request_params import RequestParams -from anyway.widgets.road_segment_widgets.killed_and_injured_count_per_age_group_widget_utils import ( +from anyway.widgets.all_locations_widgets.killed_and_injured_count_per_age_group_widget_utils import ( KilledAndInjuredCountPerAgeGroupWidgetUtils ) -from anyway.widgets.road_segment_widgets import killed_and_injured_count_per_age_group_widget_utils -from anyway.widgets.road_segment_widgets.road_segment_widget import RoadSegmentWidget +from anyway.widgets.all_locations_widgets import killed_and_injured_count_per_age_group_widget_utils +from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget from anyway.widgets.widget import register @register -class KilledInjuredCountPerAgeGroupWidget(RoadSegmentWidget): +class KilledInjuredCountPerAgeGroupWidget(AllLocationsWidget): name: str = "killed_and_injured_count_per_age_group" files = [__file__, killed_and_injured_count_per_age_group_widget_utils.__file__] @@ -35,8 +35,9 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: + location_text = KilledAndInjuredCountPerAgeGroupWidgetUtils.get_location_text(request_params) items["data"]["text"] = { "title": _("Injury per age group"), - "subtitle": _(request_params.location_info["road_segment_name"]), + "subtitle": location_text, } return items diff --git a/anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget_utils.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py similarity index 68% rename from anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget_utils.py rename to anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py index dcdf17088..4cc42f92d 100644 --- a/anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget_utils.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py @@ -28,16 +28,24 @@ class KilledAndInjuredCountPerAgeGroupWidgetUtils: def filter_and_group_injured_count_per_age_group( request_params: RequestParams, ) -> Dict[str, Dict[int, int]]: - road_number = request_params.location_info["road1"] - road_segment = request_params.location_info["road_segment_name"] + start_time = request_params.start_time end_time = request_params.end_time - cache_key = (road_number, road_segment, start_time, end_time) + if request_params.resolution == BE_CONST.ResolutionCategories.STREET: + involve_yishuv_name = request_params.location_info['yishuv_name'] + street1_hebrew = request_params.location_info['street1_hebrew'] + cache_key = (involve_yishuv_name, street1_hebrew, start_time, end_time) + + elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + road_number = request_params.location_info["road1"] + road_segment = request_params.location_info["road_segment_name"] + cache_key = (road_number, road_segment, start_time, end_time) + if cache_dict.get(cache_key): return cache_dict.get(cache_key) query = KilledAndInjuredCountPerAgeGroupWidgetUtils.create_query_for_killed_and_injured_count_per_age_group( - end_time, road_number, road_segment, start_time + end_time, start_time, request_params.location_info, request_params.resolution ) dict_grouped, has_data = KilledAndInjuredCountPerAgeGroupWidgetUtils.parse_query_data(query) @@ -84,13 +92,19 @@ def defaultdict_int_factory() -> Callable: # Rename the last key dict_grouped[SIXTY_FIVE_PLUS] = dict_grouped[SIXTY_TWOHUNDRED] del dict_grouped[SIXTY_TWOHUNDRED] - dict_grouped[_("unknown")] = dict_grouped.pop(UNKNOWN) + if UNKNOWN in dict_grouped: + dict_grouped[_("unknown")] = dict_grouped.pop(UNKNOWN) return dict_grouped, has_data @staticmethod def create_query_for_killed_and_injured_count_per_age_group( - end_time: datetime.date, road_number: int, road_segment: str, start_time: datetime.date + end_time, start_time, location_info, resolution ) -> BaseQuery: + if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + location_filter = ((InvolvedMarkerView.road1 == location_info["road1"]) | (InvolvedMarkerView.road2 == location_info["road1"])) & (InvolvedMarkerView.road_segment_name == location_info["road_segment_name"]) + elif resolution == BE_CONST.ResolutionCategories.STREET: + location_filter = (InvolvedMarkerView.involve_yishuv_name == location_info["yishuv_name"]) & ((InvolvedMarkerView.street1_hebrew == location_info["street1_hebrew"]) | (InvolvedMarkerView.street2_hebrew == location_info["street1_hebrew"])) + query = ( db.session.query(InvolvedMarkerView) .filter(InvolvedMarkerView.accident_timestamp >= start_time) @@ -109,11 +123,7 @@ def create_query_for_killed_and_injured_count_per_age_group( ] ) ) - .filter( - (InvolvedMarkerView.road1 == road_number) - | (InvolvedMarkerView.road2 == road_number) - ) - .filter(InvolvedMarkerView.road_segment_name == road_segment) + .filter(location_filter) .group_by(InvolvedMarkerView.age_group, InvolvedMarkerView.injury_severity) .with_entities( InvolvedMarkerView.age_group, @@ -122,4 +132,12 @@ def create_query_for_killed_and_injured_count_per_age_group( ) .order_by(asc(InvolvedMarkerView.age_group)) ) - return query \ No newline at end of file + return query + + @staticmethod + def get_location_text(request_params : RequestParams) -> str : + if request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + return request_params.location_info["road_segment_name"] + elif request_params.resolution == BE_CONST.ResolutionCategories.STREET: + return str.format("{0}-{1}",request_params.location_info["yishuv_name"], request_params.location_info["street1_hebrew"]) + \ No newline at end of file diff --git a/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py b/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py index 46316db7c..a120a207e 100644 --- a/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py +++ b/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py @@ -46,7 +46,7 @@ def get_seriously_injured_killed_in_bicycles_scooter( @staticmethod def create_location_description(location_info: LocationInfo, location_text: str) -> str: - return "in " + location_info[Constants.YISHUV_NAME] \ + return _("in") + location_info[Constants.YISHUV_NAME] \ if Constants.YISHUV_NAME in location_info \ else location_text diff --git a/anyway/widgets/road_segment_widgets/__init__.py b/anyway/widgets/road_segment_widgets/__init__.py index 24799d77b..6edf15e2b 100644 --- a/anyway/widgets/road_segment_widgets/__init__.py +++ b/anyway/widgets/road_segment_widgets/__init__.py @@ -9,7 +9,6 @@ accident_severity_by_cross_location_widget, accidents_heat_map_widget, head_on_collisions_comparison_widget, - killed_and_injured_count_per_age_group_widget, pedestrian_injured_in_junctions_widget, accident_count_by_hour_widget, accident_count_by_driver_type_widget, @@ -19,10 +18,8 @@ accident_count_by_accident_type_widget, accident_count_by_car_type_widget, injured_count_by_accident_year_widget, - injured_count_by_severity_widget, motorcycle_accidents_vs_all_accidents_widget, suburban_crosswalk_widget, - killed_and_injured_count_per_age_group_stacked_widget, fatal_accident_yoy_same_month, front_to_side_accidents_by_severity, ) diff --git a/messages.pot b/messages.pot index 050a5cd8a..e571f56dd 100644 --- a/messages.pot +++ b/messages.pot @@ -8,14 +8,14 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2023-09-14 15:58+0300\n" +"POT-Creation-Date: 2023-12-20 23:08+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.12.1\n" +"Generated-By: Babel 2.14.0\n" #: anyway/backend_constants.py:148 msgid "killed" @@ -170,157 +170,212 @@ msgid "other vehicle" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:69 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:158 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:162 msgid "one light" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:71 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:159 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:163 msgid "light plural" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:76 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:160 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:164 msgid "one severe" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:78 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:161 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:165 msgid "severe plural" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:83 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:162 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:166 msgid "one fatal" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:85 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:163 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:167 msgid "fatal plural" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:88 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:106 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:164 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:100 msgid "in yishuv" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:90 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:165 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:169 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:108 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:166 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:102 msgid "in street" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:95 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:166 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:170 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:113 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:171 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:107 msgid "in road" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:97 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:164 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:167 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:168 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:171 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:115 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:173 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:109 msgid "in segment" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:103 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:168 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:107 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:172 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:121 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:179 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:115 msgid "between the years" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:106 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:140 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:169 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:110 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:144 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:173 msgid "took place" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:108 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:142 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:171 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:112 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:146 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:175 msgid "accidents" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:109 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:170 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:121 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:113 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:174 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:127 msgid "out of them" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:113 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:172 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:125 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:117 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:176 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:131 msgid " and " msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:122 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:126 msgid "Number of accidents by severity" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:123 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:127 #: anyway/widgets/road_segment_widgets/accident_count_by_accident_year_widget.py:57 #: anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py:145 #: anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py:31 #: anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py:33 #: anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py:54 #: anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py:56 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:133 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py:50 #: anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py:73 msgid "road_segment_name" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:124 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:128 msgid "non_urban_intersection_hebrew" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:129 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:149 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:133 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:153 msgid "Fatal, severe and light accidents count in " msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:130 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:134 msgid "segment" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:130 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:157 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:134 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:161 msgid "junction" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:131 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:151 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:173 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:135 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:155 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:177 msgid "in the selected time" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:137 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:141 msgid "in years" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:144 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:148 msgid "{street_name}, {yishuv_name}" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:150 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:154 msgid "street" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:156 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:160 msgid "Fatal, severe and light accidents count in the specified location." msgstr "" +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:87 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:164 +msgid "one light injured" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:89 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:165 +msgid "light injured plural" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:94 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:162 +msgid "one severe injured" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:96 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:163 +msgid "severe injured plural" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:101 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:160 +msgid "one killed" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:103 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:161 +msgid "killed plural" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:124 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:158 +msgid "injured/killed" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:126 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:159 +msgid "people from car accidents" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:141 +msgid "Number of Injuries in accidents by severity" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:153 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:51 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:226 +#: anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py:49 msgid "in" msgstr "" +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 +msgid "Killed and injury stacked per age group" +msgstr "" + +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py:40 +msgid "Injury per age group" +msgstr "" + +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py:96 +msgid "unknown" +msgstr "" + #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:158 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:227 msgid "latest severe accident took place" @@ -533,64 +588,6 @@ msgid "" "injury severity" msgstr "" -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:81 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:146 -msgid "one light injured" -msgstr "" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:83 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:147 -msgid "light injured plural" -msgstr "" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:88 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:144 -msgid "one severe injured" -msgstr "" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:90 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:145 -msgid "severe injured plural" -msgstr "" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:95 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:142 -msgid "one killed" -msgstr "" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:97 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:143 -msgid "killed plural" -msgstr "" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:118 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:140 -msgid "injured/killed" -msgstr "" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:120 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:141 -msgid "people from car accidents" -msgstr "" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:132 -msgid "Number of Injuries in accidents by severity" -msgstr "" - -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:52 -msgid "Killed and injury stacked per age group" -msgstr "" - -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py:29 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget_utils.py:87 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget_utils.py:91 -msgid "unknown" -msgstr "" - -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py:49 -msgid "Injury per age group" -msgstr "" - #: anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py:21 msgid "all roads" msgstr "" diff --git a/translations/en/LC_MESSAGES/messages.mo b/translations/en/LC_MESSAGES/messages.mo index 7d2ae166d625c250e194d34e625fc258952da6fa..c469bd97e88b763e9e077059241be6179cad0c9a 100644 GIT binary patch delta 36 rcmZ3?x0r8(KMS9sk*<+}f|0S6frYk#(dJkdSw?0PJ%i1)tjibyrMC#Z delta 36 rcmZ3?x0r8(KMS9MnXZwMf}ydMv5~fc!RA;NSw?09J>$)_tjibyrNRii diff --git a/translations/en/LC_MESSAGES/messages.po b/translations/en/LC_MESSAGES/messages.po index da0cb81c2..a2952b278 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: 2023-06-22 13:32+0000\n" +"POT-Creation-Date: 2023-12-20 23:08+0200\n" "PO-Revision-Date: 2020-11-26 16:45+0200\n" "Last-Translator: FULL NAME \n" "Language: en\n" @@ -16,7 +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.10.3\n" +"Generated-By: Babel 2.14.0\n" #: anyway/backend_constants.py:148 msgid "killed" @@ -30,11 +30,11 @@ msgstr "severe injured" msgid "light injured" msgstr "light injured" -#: anyway/flask_app.py:678 anyway/flask_app.py:782 +#: anyway/flask_app.py:682 anyway/flask_app.py:786 msgid "Discussion not found:" msgstr "" -#: anyway/flask_app.py:681 +#: anyway/flask_app.py:685 msgid "Illegal Discussion" msgstr "" @@ -171,143 +171,220 @@ msgid "other vehicle" msgstr "" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:69 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:158 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:162 msgid "one light" msgstr "one light" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:71 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:159 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:163 msgid "light plural" msgstr "light" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:76 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:160 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:164 msgid "one severe" msgstr "one severe" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:78 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:161 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:165 msgid "severe plural" msgstr "severe" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:83 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:162 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:166 msgid "one fatal" msgstr "one fatal" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:85 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:163 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:167 msgid "fatal plural" msgstr "fatal" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:88 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:106 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:164 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:100 msgid "in yishuv" msgstr "in yishuv" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:90 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:165 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:169 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:108 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:166 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:102 msgid "in street" msgstr "in street" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:95 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:166 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:170 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:113 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:171 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:107 msgid "in road" msgstr "in road" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:97 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:164 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:167 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:168 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:171 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:115 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:173 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:109 msgid "in segment" msgstr "in segment" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:103 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:168 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:107 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:172 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:121 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:179 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:115 msgid "between the years" msgstr "between the years" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:106 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:140 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:169 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:110 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:144 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:173 msgid "took place" msgstr "took place" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:108 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:142 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:171 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:112 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:146 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:175 msgid "accidents" msgstr "accidents" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:109 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:170 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:121 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:113 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:174 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:127 msgid "out of them" msgstr "out of them" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:113 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:172 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:125 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:117 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:176 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:131 msgid " and " msgstr " and " -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:122 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:126 msgid "Number of accidents by severity" msgstr "Number of accidents by severity" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:123 -msgid "road_segment_namenon_urban_intersection_hebrew" +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:127 +#: anyway/widgets/road_segment_widgets/accident_count_by_accident_year_widget.py:57 +#: anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py:145 +#: anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py:31 +#: anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py:33 +#: anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py:54 +#: anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py:56 +#: anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py:73 +msgid "road_segment_name" +msgstr "" + +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:128 +msgid "non_urban_intersection_hebrew" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:129 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:149 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:133 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:153 msgid "Fatal, severe and light accidents count in " msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:130 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:134 msgid "segment" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:130 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:157 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:134 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:161 msgid "junction" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:131 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:151 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:173 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:135 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:155 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:177 msgid "in the selected time" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:137 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:141 msgid "in years" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:144 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:148 msgid "{street_name}, {yishuv_name}" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:150 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:154 msgid "street" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:156 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:160 msgid "Fatal, severe and light accidents count in the specified location." msgstr "" +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:87 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:164 +#, fuzzy +msgid "one light injured" +msgstr "light injured" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:89 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:165 +#, fuzzy +msgid "light injured plural" +msgstr "light injured" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:94 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:162 +#, fuzzy +msgid "one severe injured" +msgstr "severe injured" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:96 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:163 +#, fuzzy +msgid "severe injured plural" +msgstr "severe injured" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:101 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:160 +#, fuzzy +msgid "one killed" +msgstr "killed" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:103 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:161 +#, fuzzy +msgid "killed plural" +msgstr "killed" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:124 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:158 +#, fuzzy +msgid "injured/killed" +msgstr "killed" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:126 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:159 +#, fuzzy +msgid "people from car accidents" +msgstr "severe injured" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:141 +msgid "Number of Injuries in accidents by severity" +msgstr "" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:153 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:51 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:226 +#: anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py:49 msgid "in" msgstr "in " +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 +msgid "Killed and injury stacked per age group" +msgstr "" + +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py:40 +msgid "Injury per age group" +msgstr "" + +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py:96 +msgid "unknown" +msgstr "" + #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:158 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:227 msgid "latest severe accident took place" @@ -408,19 +485,6 @@ msgstr "" msgid "Accidents in segment" msgstr "" -#: anyway/widgets/road_segment_widgets/accident_count_by_accident_year_widget.py:57 -#: anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py:145 -#: anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py:31 -#: anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py:33 -#: anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py:54 -#: anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py:56 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:133 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py:42 -#: anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py:73 -msgid "road_segment_name" -msgstr "" - #: anyway/widgets/road_segment_widgets/accident_count_by_accident_year_widget.py:63 msgid "" "Fatal, severe and light accidents count in the specified years, split by " @@ -533,66 +597,6 @@ msgid "" "injury severity" msgstr "" -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:81 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:146 -#, fuzzy -msgid "one light injured" -msgstr "light injured" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:83 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:147 -#, fuzzy -msgid "light injured plural" -msgstr "light injured" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:88 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:144 -#, fuzzy -msgid "one severe injured" -msgstr "severe injured" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:90 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:145 -#, fuzzy -msgid "severe injured plural" -msgstr "severe injured" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:95 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:142 -#, fuzzy -msgid "one killed" -msgstr "killed" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:97 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:143 -#, fuzzy -msgid "killed plural" -msgstr "killed" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:118 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:140 -#, fuzzy -msgid "injured/killed" -msgstr "killed" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:120 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:141 -#, fuzzy -msgid "people from car accidents" -msgstr "severe injured" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:132 -msgid "Number of Injuries in accidents by severity" -msgstr "" - -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:52 -msgid "Killed and injury stacked per age group" -msgstr "" - -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py:41 -msgid "Injury per age group" -msgstr "" - #: anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py:21 msgid "all roads" msgstr "" @@ -753,3 +757,6 @@ msgstr "" #~ msgid "in yishuv" #~ msgstr "" +#~ msgid "road_segment_namenon_urban_intersection_hebrew" +#~ msgstr "" + diff --git a/translations/he/LC_MESSAGES/messages.mo b/translations/he/LC_MESSAGES/messages.mo index 4861651221ae3824fedfeecac0a5c7be7904aaea..02350b0f1b664dbba65ea634f9550d46c7652823 100644 GIT binary patch delta 36 rcmZpSX^hz*F2QGLq-$iLU}S7%V4-bbv{_X`mXX;+&tS8w\n" "Language: he\n" @@ -16,7 +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.12.1\n" +"Generated-By: Babel 2.14.0\n" #: anyway/backend_constants.py:148 msgid "killed" @@ -171,157 +171,212 @@ msgid "other vehicle" msgstr "רכב אחר" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:69 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:158 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:162 msgid "one light" msgstr "קלה אחת" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:71 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:159 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:163 msgid "light plural" msgstr "קלות" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:76 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:160 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:164 msgid "one severe" msgstr "קשה אחת" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:78 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:161 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:165 msgid "severe plural" msgstr "פצוע/ה קשה" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:83 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:162 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:166 msgid "one fatal" msgstr "קטלנית אחת" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:85 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:163 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:167 msgid "fatal plural" msgstr "קטלניות" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:88 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:106 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:164 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:100 msgid "in yishuv" msgstr "ביישוב" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:90 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:165 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:169 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:108 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:166 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:102 msgid "in street" msgstr "ברחוב" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:95 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:166 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:170 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:113 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:171 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:107 msgid "in road" msgstr "בכביש" #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:97 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:164 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:167 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:168 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:171 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:115 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:173 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:109 msgid "in segment" msgstr "במקטע" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:103 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:168 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:107 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:172 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:121 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:179 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:115 msgid "between the years" msgstr "בין השנים" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:106 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:140 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:169 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:110 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:144 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:173 msgid "took place" msgstr "התרחשו" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:108 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:142 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:171 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:112 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:146 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:175 msgid "accidents" msgstr "תאונות" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:109 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:170 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:121 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:113 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:174 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:127 msgid "out of them" msgstr "מתוכן" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:113 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:172 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:125 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:117 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:176 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:131 msgid " and " msgstr " ו-" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:122 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:126 msgid "Number of accidents by severity" msgstr "מספר תאונות לפי חומרה" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:123 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:127 #: anyway/widgets/road_segment_widgets/accident_count_by_accident_year_widget.py:57 #: anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py:145 #: anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py:31 #: anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py:33 #: anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py:54 #: anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py:56 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:133 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py:50 #: anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py:73 msgid "road_segment_name" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:124 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:128 msgid "non_urban_intersection_hebrew" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:129 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:149 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:133 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:153 msgid "Fatal, severe and light accidents count in " msgstr "כמות התאונות הקטלניות, הקשות והקלות ב" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:130 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:134 msgid "segment" msgstr "מקטע" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:130 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:157 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:134 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:161 msgid "junction" msgstr "צמת" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:131 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:151 -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:173 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:135 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:155 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:177 msgid "in the selected time" msgstr "בפרק הזמן הנבחר" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:137 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:141 msgid "in years" msgstr "בשנים" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:144 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:148 msgid "{street_name}, {yishuv_name}" msgstr "" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:150 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:154 msgid "street" msgstr "רחוב" -#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:156 +#: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:160 msgid "Fatal, severe and light accidents count in the specified location." msgstr "כמות התאונות הקטלניות, הקשות והקלות במקטע בפרק הזמן הנבחר." +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:87 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:164 +msgid "one light injured" +msgstr "פצוע/ה קל" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:89 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:165 +msgid "light injured plural" +msgstr "פצועים/ות קל" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:94 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:162 +msgid "one severe injured" +msgstr "פצוע/ה קשה" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:96 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:163 +msgid "severe injured plural" +msgstr "פצועים קשה" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:101 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:160 +msgid "one killed" +msgstr "הרוג" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:103 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:161 +msgid "killed plural" +msgstr "הרוגים" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:124 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:158 +msgid "injured/killed" +msgstr "נפצעו/נהרגו" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:126 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:159 +msgid "people from car accidents" +msgstr "אנשים מתאונות דרכים" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:141 +msgid "Number of Injuries in accidents by severity" +msgstr "מספר תאונות לפי חומרה" + +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:153 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:51 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:226 +#: anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py:49 msgid "in" msgstr "ב" +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 +msgid "Killed and injury stacked per age group" +msgstr "חומרת פגיעה לפי קבוצת גיל" + +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py:40 +msgid "Injury per age group" +msgstr "נפגעים לפי קבוצת גיל" + +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py:96 +msgid "unknown" +msgstr "לא ידוע" + #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:158 #: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:227 msgid "latest severe accident took place" @@ -549,64 +604,6 @@ msgstr "" "מספר הרוגים, פצועים קשה וקל, לפי שנה במקטע, מחולק לפי חומרת הפגיעה, בפרק " "הזמן הנבחר." -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:81 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:146 -msgid "one light injured" -msgstr "פצוע/ה קל" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:83 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:147 -msgid "light injured plural" -msgstr "פצועים/ות קל" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:88 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:144 -msgid "one severe injured" -msgstr "פצוע/ה קשה" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:90 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:145 -msgid "severe injured plural" -msgstr "פצועים קשה" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:95 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:142 -msgid "one killed" -msgstr "הרוג" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:97 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:143 -msgid "killed plural" -msgstr "הרוגים" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:118 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:140 -msgid "injured/killed" -msgstr "נפצעו/נהרגו" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:120 -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:141 -msgid "people from car accidents" -msgstr "אנשים מתאונות דרכים" - -#: anyway/widgets/road_segment_widgets/injured_count_by_severity_widget.py:132 -msgid "Number of Injuries in accidents by severity" -msgstr "מספר תאונות לפי חומרה" - -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:52 -msgid "Killed and injury stacked per age group" -msgstr "חומרת פגיעה לפי קבוצת גיל" - -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py:29 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget_utils.py:87 -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget_utils.py:91 -msgid "unknown" -msgstr "לא ידוע" - -#: anyway/widgets/road_segment_widgets/killed_and_injured_count_per_age_group_widget.py:49 -msgid "Injury per age group" -msgstr "נפגעים לפי קבוצת גיל" - #: anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py:21 msgid "all roads" msgstr "כל הכבישים" From 0e6e9f320da9106943d8ef57ff90d8cb059df225 Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 13:14:03 +0200 Subject: [PATCH 02/12] merge chagnes from dev and subtitle adjustments --- .../injured_count_by_severity_widget.py | 13 +------ ...ured_count_per_age_group_stacked_widget.py | 6 +-- ..._and_injured_count_per_age_group_widget.py | 5 ++- ...njured_count_per_age_group_widget_utils.py | 8 ---- anyway/widgets/widget_utils.py | 8 ++++ messages.pot | 36 +++++++++--------- translations/en/LC_MESSAGES/messages.mo | Bin 1827 -> 1827 bytes translations/en/LC_MESSAGES/messages.po | 36 +++++++++--------- translations/he/LC_MESSAGES/messages.mo | Bin 11777 -> 11777 bytes translations/he/LC_MESSAGES/messages.po | 36 +++++++++--------- 10 files changed, 70 insertions(+), 78 deletions(-) diff --git a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py index 8e0a27108..a09f60a3c 100644 --- a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py @@ -5,7 +5,7 @@ from anyway.models import InvolvedMarkerView from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget from anyway.widgets.widget import register -from anyway.widgets.widget_utils import get_accidents_stats, join_strings +from anyway.widgets.widget_utils import get_accidents_stats, join_strings, get_location_text from anyway.backend_constants import BE_CONST from flask_babel import _ @@ -135,8 +135,7 @@ def get_transcription(request_params: RequestParams, items: Dict): @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - subtitle = InjuredCountBySeverityWidget.get_injured_count_by_severity_table_title(request_params.location_info, - request_params.resolution) + subtitle = get_location_text(request_params) items["data"]["text"] = { "title": _("Number of Injuries in accidents by severity"), "subtitle": _(subtitle), @@ -145,14 +144,6 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: } return items - @staticmethod - def get_injured_count_by_severity_table_title(location_info: dict, resolution: BE_CONST.ResolutionCategories): - if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - return location_info["road_segment_name"] - elif resolution == BE_CONST.ResolutionCategories.STREET: - in_str = _("in") - return f"{location_info['street1_hebrew']} {in_str}{location_info['yishuv_name']}" - _("injured/killed") diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py index 32b5a6f12..ef3e406ec 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py @@ -12,7 +12,7 @@ from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget 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, get_location_text INJURY_ORDER = [InjurySeverity.LIGHT_INJURED, InjurySeverity.SEVERE_INJURED, InjurySeverity.KILLED] MAX_AGE = 200 @@ -48,10 +48,10 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - location_text = KilledAndInjuredCountPerAgeGroupWidgetUtils.get_location_text(request_params) + location_text = get_location_text(request_params) items["data"]["text"] = { "title": _("Killed and injury stacked per age group"), - "subtitle": location_text, + "subtitle": _(location_text), "labels_map": gen_entity_labels(InjurySeverity), } return items diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py index 1dc5b4b41..01b06bfc7 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py @@ -10,6 +10,7 @@ from anyway.widgets.all_locations_widgets import killed_and_injured_count_per_age_group_widget_utils from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget from anyway.widgets.widget import register +from anyway.widgets.widget_utils import get_location_text @register class KilledInjuredCountPerAgeGroupWidget(AllLocationsWidget): @@ -35,9 +36,9 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - location_text = KilledAndInjuredCountPerAgeGroupWidgetUtils.get_location_text(request_params) + location_text = get_location_text(request_params) items["data"]["text"] = { "title": _("Injury per age group"), - "subtitle": location_text, + "subtitle": _(location_text) } return items diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py index 4cc42f92d..90c7590fe 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py @@ -133,11 +133,3 @@ def create_query_for_killed_and_injured_count_per_age_group( .order_by(asc(InvolvedMarkerView.age_group)) ) return query - - @staticmethod - def get_location_text(request_params : RequestParams) -> str : - if request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - return request_params.location_info["road_segment_name"] - elif request_params.resolution == BE_CONST.ResolutionCategories.STREET: - return str.format("{0}-{1}",request_params.location_info["yishuv_name"], request_params.location_info["street1_hebrew"]) - \ No newline at end of file diff --git a/anyway/widgets/widget_utils.py b/anyway/widgets/widget_utils.py index 3e5c83587..e81be10f6 100644 --- a/anyway/widgets/widget_utils.py +++ b/anyway/widgets/widget_utils.py @@ -14,6 +14,7 @@ from anyway.request_params import LocationInfo from anyway.vehicle_type import VehicleType from anyway.models import NewsFlash +from anyway.request_params import RequestParams def get_query(table_obj, filters, start_time, end_time): @@ -243,3 +244,10 @@ def newsflash_has_location(newsflash: NewsFlash): resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD.value and newsflash.road_segment_name ) or (resolution == BE_CONST.ResolutionCategories.STREET.value and newsflash.street1_hebrew) + +def get_location_text(request_params : RequestParams) -> str : + in_str = _("in") + if request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + return f'{_("in segment")} {_(request_params.location_info["road_segment_name"])}' + elif request_params.resolution == BE_CONST.ResolutionCategories.STREET: + return f'{_("in street")} {request_params.location_info["street1_hebrew"]} {in_str}{request_params.location_info["yishuv_name"]}' diff --git a/messages.pot b/messages.pot index e571f56dd..6bc6dd5bd 100644 --- a/messages.pot +++ b/messages.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2023-12-20 23:08+0200\n" +"POT-Creation-Date: 2023-12-22 13:01+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -169,6 +169,13 @@ msgstr "" msgid "other vehicle" msgstr "" +#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:51 +#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:226 +#: anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py:49 +#: anyway/widgets/widget_utils.py:249 +msgid "in" +msgstr "" + #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:69 #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:162 msgid "one light" @@ -314,61 +321,54 @@ msgid "Fatal, severe and light accidents count in the specified location." msgstr "" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:87 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:164 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:155 msgid "one light injured" msgstr "" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:89 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:165 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:156 msgid "light injured plural" msgstr "" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:94 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:162 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:153 msgid "one severe injured" msgstr "" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:96 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:163 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:154 msgid "severe injured plural" msgstr "" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:101 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:160 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:151 msgid "one killed" msgstr "" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:103 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:161 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:152 msgid "killed plural" msgstr "" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:124 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:158 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:149 msgid "injured/killed" msgstr "" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:126 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:159 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:150 msgid "people from car accidents" msgstr "" -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:141 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:140 msgid "Number of Injuries in accidents by severity" msgstr "" -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:153 -#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:51 -#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:226 -#: anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py:49 -msgid "in" -msgstr "" - #: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 msgid "Killed and injury stacked per age group" msgstr "" -#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py:40 +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py:41 msgid "Injury per age group" msgstr "" diff --git a/translations/en/LC_MESSAGES/messages.mo b/translations/en/LC_MESSAGES/messages.mo index c469bd97e88b763e9e077059241be6179cad0c9a..ad4bba5112fdf1622f9a068ffb09a11204e8e485 100644 GIT binary patch delta 20 bcmZ3?x0r83Fblhpf}ydMf#K#TmXk~XJm>|U delta 20 bcmZ3?x0r83FblhZf|0S6fyL%1mXk~XJp=`$ diff --git a/translations/en/LC_MESSAGES/messages.po b/translations/en/LC_MESSAGES/messages.po index a2952b278..71063f2e0 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: 2023-12-20 23:08+0200\n" +"POT-Creation-Date: 2023-12-22 13:01+0200\n" "PO-Revision-Date: 2020-11-26 16:45+0200\n" "Last-Translator: FULL NAME \n" "Language: en\n" @@ -170,6 +170,13 @@ msgstr "" msgid "other vehicle" msgstr "" +#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:51 +#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:226 +#: anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py:49 +#: anyway/widgets/widget_utils.py:249 +msgid "in" +msgstr "in " + #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:69 #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:162 msgid "one light" @@ -315,69 +322,62 @@ msgid "Fatal, severe and light accidents count in the specified location." msgstr "" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:87 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:164 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:155 #, fuzzy msgid "one light injured" msgstr "light injured" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:89 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:165 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:156 #, fuzzy msgid "light injured plural" msgstr "light injured" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:94 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:162 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:153 #, fuzzy msgid "one severe injured" msgstr "severe injured" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:96 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:163 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:154 #, fuzzy msgid "severe injured plural" msgstr "severe injured" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:101 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:160 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:151 #, fuzzy msgid "one killed" msgstr "killed" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:103 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:161 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:152 #, fuzzy msgid "killed plural" msgstr "killed" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:124 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:158 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:149 #, fuzzy msgid "injured/killed" msgstr "killed" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:126 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:159 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:150 #, fuzzy msgid "people from car accidents" msgstr "severe injured" -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:141 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:140 msgid "Number of Injuries in accidents by severity" msgstr "" -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:153 -#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:51 -#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:226 -#: anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py:49 -msgid "in" -msgstr "in " - #: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 msgid "Killed and injury stacked per age group" msgstr "" -#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py:40 +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py:41 msgid "Injury per age group" msgstr "" diff --git a/translations/he/LC_MESSAGES/messages.mo b/translations/he/LC_MESSAGES/messages.mo index 02350b0f1b664dbba65ea634f9550d46c7652823..17c717c8c1955867e1a954287e746faff21d2799 100644 GIT binary patch delta 20 bcmZpSX^hz*Ex~T2U}$V*V7OUH;=U*VKtBc7 delta 20 bcmZpSX^hz*Ex~S}U}S7%V6j\n" "Language: he\n" @@ -170,6 +170,13 @@ msgstr "אופניים/קורקינט" msgid "other vehicle" msgstr "רכב אחר" +#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:51 +#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:226 +#: anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py:49 +#: anyway/widgets/widget_utils.py:249 +msgid "in" +msgstr "ב" + #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:69 #: anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py:162 msgid "one light" @@ -315,61 +322,54 @@ msgid "Fatal, severe and light accidents count in the specified location." msgstr "כמות התאונות הקטלניות, הקשות והקלות במקטע בפרק הזמן הנבחר." #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:87 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:164 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:155 msgid "one light injured" msgstr "פצוע/ה קל" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:89 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:165 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:156 msgid "light injured plural" msgstr "פצועים/ות קל" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:94 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:162 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:153 msgid "one severe injured" msgstr "פצוע/ה קשה" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:96 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:163 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:154 msgid "severe injured plural" msgstr "פצועים קשה" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:101 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:160 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:151 msgid "one killed" msgstr "הרוג" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:103 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:161 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:152 msgid "killed plural" msgstr "הרוגים" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:124 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:158 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:149 msgid "injured/killed" msgstr "נפצעו/נהרגו" #: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:126 -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:159 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:150 msgid "people from car accidents" msgstr "אנשים מתאונות דרכים" -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:141 +#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:140 msgid "Number of Injuries in accidents by severity" msgstr "מספר תאונות לפי חומרה" -#: anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py:153 -#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:51 -#: anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py:226 -#: anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py:49 -msgid "in" -msgstr "ב" - #: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py:53 msgid "Killed and injury stacked per age group" msgstr "חומרת פגיעה לפי קבוצת גיל" -#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py:40 +#: anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py:41 msgid "Injury per age group" msgstr "נפגעים לפי קבוצת גיל" From f1c9c20e97de92b2983a17d14b7b3af1b9962195 Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 13:36:52 +0200 Subject: [PATCH 03/12] remove import --- .../accident_count_by_severity_widget.py | 4 ---- .../all_locations_widgets/injured_count_by_severity_widget.py | 1 - 2 files changed, 5 deletions(-) diff --git a/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py index d67cdcef7..546ad583e 100644 --- a/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py @@ -97,10 +97,6 @@ def get_transcription(request_params: RequestParams, items: Dict): in_segment_keyword=_("in segment"), segment_name=_(request_params.location_info.get('road_segment_name')), ) - elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_JUNCTION: - text = "{in_urban_intersection}".format( - in_urban_intersection=request_params.location_info.get('non_urban_intersection_hebrew') - ) else: raise Exception(f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}") text += "{between_years_keyword} {start_year} - {end_year}, {separator_keyword} {incidents_num} {incident_keyword}, {out_of_them_keywoard} ".format( diff --git a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py index a09f60a3c..cdccd6735 100644 --- a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py @@ -1,5 +1,4 @@ from typing import Dict -import copy from anyway.request_params import RequestParams from anyway.backend_constants import InjurySeverity from anyway.models import InvolvedMarkerView From ac3e4d48511d383f7f6a7968e7b360788c823c47 Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 15:00:35 +0200 Subject: [PATCH 04/12] remove newsflash infographics dir --- anyway-newsflash-infographics/anyway-newsflash-infographics | 1 - 1 file changed, 1 deletion(-) delete mode 160000 anyway-newsflash-infographics/anyway-newsflash-infographics diff --git a/anyway-newsflash-infographics/anyway-newsflash-infographics b/anyway-newsflash-infographics/anyway-newsflash-infographics deleted file mode 160000 index f659f4182..000000000 --- a/anyway-newsflash-infographics/anyway-newsflash-infographics +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f659f4182df238c032831eb6cefc41bb0aed6d91 From ab74a2b12aeeea796c16909b007cb059652a42db Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 15:48:37 +0200 Subject: [PATCH 05/12] skip wall test --- tests/test_news_flash.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_news_flash.py b/tests/test_news_flash.py index 75f945df4..eed9fbf68 100755 --- a/tests/test_news_flash.py +++ b/tests/test_news_flash.py @@ -110,6 +110,7 @@ def test_scrape_sanity_online_ynet(): @pytest.mark.slow def test_scrape_sanity_online_walla(): + pytest.skip("") next(rss_sites.scrape("walla")) From 090f22023ba9f540b5f63b672c5f51343670bfc6 Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 16:14:53 +0200 Subject: [PATCH 06/12] fix widget location --- anyway/models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/anyway/models.py b/anyway/models.py index 8943cf2df..5116d5908 100755 --- a/anyway/models.py +++ b/anyway/models.py @@ -891,7 +891,7 @@ def set_critical( suburban_road_killed_value=3, urban_severe_value=2, ): - from anyway.widgets.road_segment_widgets.injured_count_by_severity_widget import ( + from anyway.widgets.all_locations_widgets.injured_count_by_severity_widget import ( InjuredCountBySeverityWidget, ) from anyway.request_params import get_latest_accident_date From 9737275b884574bbcc10db4c393d5e1ba3b0838a Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 17:08:44 +0200 Subject: [PATCH 07/12] fix black issues --- anyway/backend_constants.py | 3 +- anyway/db_views.py | 938 +++++++++++------- anyway/flask_app.py | 39 +- anyway/infographic_image_generator.py | 27 +- anyway/infographics_utils.py | 3 +- anyway/models.py | 97 +- anyway/parsers/cbs/executor.py | 162 +-- anyway/parsers/cbs/s3/base.py | 2 +- anyway/request_params.py | 10 +- anyway/telegram_accident_notifications.py | 88 +- anyway/utilities.py | 23 +- anyway/views/comments/api.py | 34 +- anyway/views/news_flash/api.py | 167 ++-- .../widgets/all_locations_widgets/__init__.py | 2 +- .../accident_count_by_severity_widget.py | 77 +- .../injured_count_by_severity_widget.py | 78 +- ...ured_count_per_age_group_stacked_widget.py | 6 +- ..._and_injured_count_per_age_group_widget.py | 6 +- ...njured_count_per_age_group_widget_utils.py | 20 +- .../most_severe_accidents_table_widget.py | 70 +- .../most_severe_accidents_widget.py | 8 +- ...jured_killed_in_bicycles_scooter_widget.py | 39 +- .../widgets/no_location_widgets/__init__.py | 4 +- .../vision_zero_bike_widget.py | 5 +- .../accident_count_by_car_type_widget.py | 2 +- .../accident_count_by_hour_widget.py | 2 +- .../accident_count_by_road_light_widget.py | 2 +- ...trians_per_vehicle_street_vs_all_widget.py | 2 +- ...ident_severity_by_cross_location_widget.py | 2 +- .../accidents_heat_map_widget.py | 2 +- .../front_to_side_accidents_by_severity.py | 6 +- .../injured_count_by_accident_year_widget.py | 2 +- ...cycle_accidents_vs_all_accidents_widget.py | 36 +- .../pedestrian_injured_in_junctions_widget.py | 2 +- .../suburban_crosswalk_widget.py | 2 +- ...p_road_segments_accidents_per_km_widget.py | 2 +- anyway/widgets/urban_widgets/__init__.py | 2 +- ...jured_accidents_with_pedestrians_widget.py | 4 +- ...e_fatal_count_by_vehicle_by_year_widget.py | 2 +- ...motor_severe_fatal_count_by_year_widget.py | 2 +- .../urban_widgets/urban_crosswalk_widget.py | 2 +- .../vision_zero_10_50_90_widget.py | 12 +- anyway/widgets/widget_utils.py | 26 +- 43 files changed, 1220 insertions(+), 800 deletions(-) diff --git a/anyway/backend_constants.py b/anyway/backend_constants.py index ef842cb74..295f092bd 100644 --- a/anyway/backend_constants.py +++ b/anyway/backend_constants.py @@ -78,7 +78,7 @@ class ResolutionCategories(Enum): SUPPORTED_RESOLUTIONS: List[ResolutionCategories] = [ ResolutionCategories.STREET, ResolutionCategories.SUBURBAN_ROAD, - ResolutionCategories.SUBURBAN_JUNCTION + ResolutionCategories.SUBURBAN_JUNCTION, ] class Source(Enum): @@ -110,6 +110,7 @@ def _missing_(cls, value): YISHUV_NAME = "yishuv_name" + BE_CONST = BackEndConstants() diff --git a/anyway/db_views.py b/anyway/db_views.py index 112226d16..e88e3e132 100644 --- a/anyway/db_views.py +++ b/anyway/db_views.py @@ -61,7 +61,7 @@ ProviderCode, VehicleDamage, RoadSegments, - AccidentMarkerView + AccidentMarkerView, ) @@ -77,7 +77,7 @@ def create_markers_hebrew_view(self): AccidentType.accident_type_hebrew, AccidentMarker.accident_severity, AccidentSeverity.accident_severity_hebrew, - AccidentMarker.created.label('accident_timestamp'), + AccidentMarker.created.label("accident_timestamp"), AccidentMarker.location_accuracy, LocationAccuracy.location_accuracy_hebrew, AccidentMarker.road_type, @@ -125,12 +125,12 @@ def create_markers_hebrew_view(self): AccidentMarker.km, AccidentMarker.km_raw, AccidentMarker.km_accurate, - RoadSegments.segment_id.label('road_segment_id'), - RoadSegments.segment.label('road_segment_number'), - (RoadSegments.from_name + " - " + RoadSegments.to_name).label('road_segment_name'), - RoadSegments.from_km.label('road_segment_from_km'), - RoadSegments.to_km.label('road_segment_to_km'), - (RoadSegments.to_km - RoadSegments.from_km).label('road_segment_length_km'), + RoadSegments.segment_id.label("road_segment_id"), + RoadSegments.segment.label("road_segment_number"), + (RoadSegments.from_name + " - " + RoadSegments.to_name).label("road_segment_name"), + RoadSegments.from_km.label("road_segment_from_km"), + RoadSegments.to_km.label("road_segment_to_km"), + (RoadSegments.to_km - RoadSegments.from_km).label("road_segment_length_km"), AccidentMarker.yishuv_symbol, AccidentMarker.yishuv_name, AccidentMarker.geo_area, @@ -171,186 +171,320 @@ def create_markers_hebrew_view(self): AccidentMarker.longitude, AccidentMarker.latitude, AccidentMarker.x, - AccidentMarker.y + AccidentMarker.y, ] table = AccidentMarker.__table__ - from_clause = table \ - .join(RoadSegments, - and_(AccidentMarker.road1 == RoadSegments.road, - RoadSegments.from_km <= AccidentMarker.km / 10, - AccidentMarker.km / 10 < RoadSegments.to_km), - isouter=True) \ - .join(AccidentType, - and_(AccidentMarker.accident_type == AccidentType.id, - AccidentMarker.accident_year == AccidentType.year, - AccidentMarker.provider_code == AccidentType.provider_code), - isouter=True) \ - .join(AccidentSeverity, - and_(AccidentMarker.accident_severity == AccidentSeverity.id, - AccidentMarker.accident_year == AccidentSeverity.year, - AccidentMarker.provider_code == AccidentSeverity.provider_code), - isouter=True) \ - .join(LocationAccuracy, - and_(AccidentMarker.location_accuracy == LocationAccuracy.id, - AccidentMarker.accident_year == LocationAccuracy.year, - AccidentMarker.provider_code == LocationAccuracy.provider_code), - isouter=True) \ - .join(RoadType, - and_(AccidentMarker.road_type == RoadType.id, - AccidentMarker.accident_year == RoadType.year, - AccidentMarker.provider_code == RoadType.provider_code), - isouter=True) \ - .join(RoadShape, - and_(AccidentMarker.road_shape == RoadShape.id, - AccidentMarker.accident_year == RoadShape.year, - AccidentMarker.provider_code == RoadShape.provider_code), - isouter=True) \ - .join(DayType, - and_(AccidentMarker.day_type == DayType.id, - AccidentMarker.accident_year == DayType.year, - AccidentMarker.provider_code == DayType.provider_code), - isouter=True) \ - .join(PoliceUnit, - and_(AccidentMarker.police_unit == PoliceUnit.id, - AccidentMarker.accident_year == PoliceUnit.year, - AccidentMarker.provider_code == PoliceUnit.provider_code), - isouter=True) \ - .join(OneLane, - and_(AccidentMarker.one_lane == OneLane.id, - AccidentMarker.accident_year == OneLane.year, - AccidentMarker.provider_code == OneLane.provider_code), - isouter=True) \ - .join(MultiLane, - and_(AccidentMarker.multi_lane == MultiLane.id, - AccidentMarker.accident_year == MultiLane.year, - AccidentMarker.provider_code == MultiLane.provider_code), - isouter=True) \ - .join(SpeedLimit, - and_(AccidentMarker.speed_limit == SpeedLimit.id, - AccidentMarker.accident_year == SpeedLimit.year, - AccidentMarker.provider_code == SpeedLimit.provider_code), - isouter=True) \ - .join(RoadIntactness, - and_(AccidentMarker.road_intactness == RoadIntactness.id, - AccidentMarker.accident_year == RoadIntactness.year, - AccidentMarker.provider_code == RoadIntactness.provider_code), - isouter=True) \ - .join(RoadWidth, - and_(AccidentMarker.road_width == RoadWidth.id, - AccidentMarker.accident_year == RoadWidth.year, - AccidentMarker.provider_code == RoadWidth.provider_code), - isouter=True) \ - .join(RoadSign, - and_(AccidentMarker.road_sign == RoadSign.id, - AccidentMarker.accident_year == RoadSign.year, - AccidentMarker.provider_code == RoadSign.provider_code), - isouter=True) \ - .join(RoadLight, - and_(AccidentMarker.road_light == RoadLight.id, - AccidentMarker.accident_year == RoadLight.year, - AccidentMarker.provider_code == RoadLight.provider_code), - isouter=True) \ - .join(RoadControl, - and_(AccidentMarker.road_control == RoadControl.id, - AccidentMarker.accident_year == RoadControl.year, - AccidentMarker.provider_code == RoadControl.provider_code), - isouter=True) \ - .join(Weather, - and_(AccidentMarker.weather == Weather.id, - AccidentMarker.accident_year == Weather.year, - AccidentMarker.provider_code == Weather.provider_code), - isouter=True) \ - .join(RoadSurface, - and_(AccidentMarker.road_surface == RoadSurface.id, - AccidentMarker.accident_year == RoadSurface.year, - AccidentMarker.provider_code == RoadSurface.provider_code), - isouter=True) \ - .join(RoadObjecte, - and_(AccidentMarker.road_object == RoadObjecte.id, - AccidentMarker.accident_year == RoadObjecte.year, - AccidentMarker.provider_code == RoadObjecte.provider_code), - isouter=True) \ - .join(ObjectDistance, - and_(AccidentMarker.object_distance == ObjectDistance.id, - AccidentMarker.accident_year == ObjectDistance.year, - AccidentMarker.provider_code == ObjectDistance.provider_code), - isouter=True) \ - .join(DidntCross, - and_(AccidentMarker.didnt_cross == DidntCross.id, - AccidentMarker.accident_year == DidntCross.year, - AccidentMarker.provider_code == DidntCross.provider_code), - isouter=True) \ - .join(CrossMode, - and_(AccidentMarker.cross_mode == CrossMode.id, - AccidentMarker.accident_year == CrossMode.year, - AccidentMarker.provider_code == CrossMode.provider_code), - isouter=True) \ - .join(CrossLocation, - and_(AccidentMarker.cross_location == CrossLocation.id, - AccidentMarker.accident_year == CrossLocation.year, - AccidentMarker.provider_code == CrossLocation.provider_code), - isouter=True) \ - .join(CrossDirection, - and_(AccidentMarker.cross_direction == CrossDirection.id, - AccidentMarker.accident_year == CrossDirection.year, - AccidentMarker.provider_code == CrossDirection.provider_code), - isouter=True) \ - .join(GeoArea, - and_(AccidentMarker.geo_area == GeoArea.id, - AccidentMarker.accident_year == GeoArea.year, - AccidentMarker.provider_code == GeoArea.provider_code), - isouter=True) \ - .join(DayNight, - and_(AccidentMarker.day_night == DayNight.id, - AccidentMarker.accident_year == DayNight.year, - AccidentMarker.provider_code == DayNight.provider_code), - isouter=True) \ - .join(DayInWeek, - and_(AccidentMarker.day_in_week == DayInWeek.id, - AccidentMarker.accident_year == DayInWeek.year, - AccidentMarker.provider_code == DayInWeek.provider_code), - isouter=True) \ - .join(TrafficLight, - and_(AccidentMarker.traffic_light == TrafficLight.id, - AccidentMarker.accident_year == TrafficLight.year, - AccidentMarker.provider_code == TrafficLight.provider_code), - isouter=True) \ - .join(Region, - and_(AccidentMarker.region == Region.id, - AccidentMarker.accident_year == Region.year, - AccidentMarker.provider_code == Region.provider_code), - isouter=True) \ - .join(District, - and_(AccidentMarker.district == District.id, - AccidentMarker.accident_year == District.year, - AccidentMarker.provider_code == District.provider_code), - isouter=True) \ - .join(NaturalArea, - and_(AccidentMarker.natural_area == NaturalArea.id, - AccidentMarker.accident_year == NaturalArea.year, - AccidentMarker.provider_code == NaturalArea.provider_code), - isouter=True) \ - .join(MunicipalStatus, - and_(AccidentMarker.municipal_status == MunicipalStatus.id, - AccidentMarker.accident_year == MunicipalStatus.year, - AccidentMarker.provider_code == MunicipalStatus.provider_code), - isouter=True) \ - .join(YishuvShape, - and_(AccidentMarker.yishuv_shape == YishuvShape.id, - AccidentMarker.accident_year == YishuvShape.year, - AccidentMarker.provider_code == YishuvShape.provider_code), - isouter=True) \ - .join(AccidentHourRaw, - and_(AccidentMarker.accident_hour_raw == AccidentHourRaw.id, - AccidentMarker.accident_year == AccidentHourRaw.year, - AccidentMarker.provider_code == AccidentHourRaw.provider_code), - isouter=True) \ - .join(ProviderCode, - and_(AccidentMarker.provider_code == ProviderCode.id), - isouter=True) - return select(selected_columns) \ - .select_from(from_clause) + from_clause = ( + table.join( + RoadSegments, + and_( + AccidentMarker.road1 == RoadSegments.road, + RoadSegments.from_km <= AccidentMarker.km / 10, + AccidentMarker.km / 10 < RoadSegments.to_km, + ), + isouter=True, + ) + .join( + AccidentType, + and_( + AccidentMarker.accident_type == AccidentType.id, + AccidentMarker.accident_year == AccidentType.year, + AccidentMarker.provider_code == AccidentType.provider_code, + ), + isouter=True, + ) + .join( + AccidentSeverity, + and_( + AccidentMarker.accident_severity == AccidentSeverity.id, + AccidentMarker.accident_year == AccidentSeverity.year, + AccidentMarker.provider_code == AccidentSeverity.provider_code, + ), + isouter=True, + ) + .join( + LocationAccuracy, + and_( + AccidentMarker.location_accuracy == LocationAccuracy.id, + AccidentMarker.accident_year == LocationAccuracy.year, + AccidentMarker.provider_code == LocationAccuracy.provider_code, + ), + isouter=True, + ) + .join( + RoadType, + and_( + AccidentMarker.road_type == RoadType.id, + AccidentMarker.accident_year == RoadType.year, + AccidentMarker.provider_code == RoadType.provider_code, + ), + isouter=True, + ) + .join( + RoadShape, + and_( + AccidentMarker.road_shape == RoadShape.id, + AccidentMarker.accident_year == RoadShape.year, + AccidentMarker.provider_code == RoadShape.provider_code, + ), + isouter=True, + ) + .join( + DayType, + and_( + AccidentMarker.day_type == DayType.id, + AccidentMarker.accident_year == DayType.year, + AccidentMarker.provider_code == DayType.provider_code, + ), + isouter=True, + ) + .join( + PoliceUnit, + and_( + AccidentMarker.police_unit == PoliceUnit.id, + AccidentMarker.accident_year == PoliceUnit.year, + AccidentMarker.provider_code == PoliceUnit.provider_code, + ), + isouter=True, + ) + .join( + OneLane, + and_( + AccidentMarker.one_lane == OneLane.id, + AccidentMarker.accident_year == OneLane.year, + AccidentMarker.provider_code == OneLane.provider_code, + ), + isouter=True, + ) + .join( + MultiLane, + and_( + AccidentMarker.multi_lane == MultiLane.id, + AccidentMarker.accident_year == MultiLane.year, + AccidentMarker.provider_code == MultiLane.provider_code, + ), + isouter=True, + ) + .join( + SpeedLimit, + and_( + AccidentMarker.speed_limit == SpeedLimit.id, + AccidentMarker.accident_year == SpeedLimit.year, + AccidentMarker.provider_code == SpeedLimit.provider_code, + ), + isouter=True, + ) + .join( + RoadIntactness, + and_( + AccidentMarker.road_intactness == RoadIntactness.id, + AccidentMarker.accident_year == RoadIntactness.year, + AccidentMarker.provider_code == RoadIntactness.provider_code, + ), + isouter=True, + ) + .join( + RoadWidth, + and_( + AccidentMarker.road_width == RoadWidth.id, + AccidentMarker.accident_year == RoadWidth.year, + AccidentMarker.provider_code == RoadWidth.provider_code, + ), + isouter=True, + ) + .join( + RoadSign, + and_( + AccidentMarker.road_sign == RoadSign.id, + AccidentMarker.accident_year == RoadSign.year, + AccidentMarker.provider_code == RoadSign.provider_code, + ), + isouter=True, + ) + .join( + RoadLight, + and_( + AccidentMarker.road_light == RoadLight.id, + AccidentMarker.accident_year == RoadLight.year, + AccidentMarker.provider_code == RoadLight.provider_code, + ), + isouter=True, + ) + .join( + RoadControl, + and_( + AccidentMarker.road_control == RoadControl.id, + AccidentMarker.accident_year == RoadControl.year, + AccidentMarker.provider_code == RoadControl.provider_code, + ), + isouter=True, + ) + .join( + Weather, + and_( + AccidentMarker.weather == Weather.id, + AccidentMarker.accident_year == Weather.year, + AccidentMarker.provider_code == Weather.provider_code, + ), + isouter=True, + ) + .join( + RoadSurface, + and_( + AccidentMarker.road_surface == RoadSurface.id, + AccidentMarker.accident_year == RoadSurface.year, + AccidentMarker.provider_code == RoadSurface.provider_code, + ), + isouter=True, + ) + .join( + RoadObjecte, + and_( + AccidentMarker.road_object == RoadObjecte.id, + AccidentMarker.accident_year == RoadObjecte.year, + AccidentMarker.provider_code == RoadObjecte.provider_code, + ), + isouter=True, + ) + .join( + ObjectDistance, + and_( + AccidentMarker.object_distance == ObjectDistance.id, + AccidentMarker.accident_year == ObjectDistance.year, + AccidentMarker.provider_code == ObjectDistance.provider_code, + ), + isouter=True, + ) + .join( + DidntCross, + and_( + AccidentMarker.didnt_cross == DidntCross.id, + AccidentMarker.accident_year == DidntCross.year, + AccidentMarker.provider_code == DidntCross.provider_code, + ), + isouter=True, + ) + .join( + CrossMode, + and_( + AccidentMarker.cross_mode == CrossMode.id, + AccidentMarker.accident_year == CrossMode.year, + AccidentMarker.provider_code == CrossMode.provider_code, + ), + isouter=True, + ) + .join( + CrossLocation, + and_( + AccidentMarker.cross_location == CrossLocation.id, + AccidentMarker.accident_year == CrossLocation.year, + AccidentMarker.provider_code == CrossLocation.provider_code, + ), + isouter=True, + ) + .join( + CrossDirection, + and_( + AccidentMarker.cross_direction == CrossDirection.id, + AccidentMarker.accident_year == CrossDirection.year, + AccidentMarker.provider_code == CrossDirection.provider_code, + ), + isouter=True, + ) + .join( + GeoArea, + and_( + AccidentMarker.geo_area == GeoArea.id, + AccidentMarker.accident_year == GeoArea.year, + AccidentMarker.provider_code == GeoArea.provider_code, + ), + isouter=True, + ) + .join( + DayNight, + and_( + AccidentMarker.day_night == DayNight.id, + AccidentMarker.accident_year == DayNight.year, + AccidentMarker.provider_code == DayNight.provider_code, + ), + isouter=True, + ) + .join( + DayInWeek, + and_( + AccidentMarker.day_in_week == DayInWeek.id, + AccidentMarker.accident_year == DayInWeek.year, + AccidentMarker.provider_code == DayInWeek.provider_code, + ), + isouter=True, + ) + .join( + TrafficLight, + and_( + AccidentMarker.traffic_light == TrafficLight.id, + AccidentMarker.accident_year == TrafficLight.year, + AccidentMarker.provider_code == TrafficLight.provider_code, + ), + isouter=True, + ) + .join( + Region, + and_( + AccidentMarker.region == Region.id, + AccidentMarker.accident_year == Region.year, + AccidentMarker.provider_code == Region.provider_code, + ), + isouter=True, + ) + .join( + District, + and_( + AccidentMarker.district == District.id, + AccidentMarker.accident_year == District.year, + AccidentMarker.provider_code == District.provider_code, + ), + isouter=True, + ) + .join( + NaturalArea, + and_( + AccidentMarker.natural_area == NaturalArea.id, + AccidentMarker.accident_year == NaturalArea.year, + AccidentMarker.provider_code == NaturalArea.provider_code, + ), + isouter=True, + ) + .join( + MunicipalStatus, + and_( + AccidentMarker.municipal_status == MunicipalStatus.id, + AccidentMarker.accident_year == MunicipalStatus.year, + AccidentMarker.provider_code == MunicipalStatus.provider_code, + ), + isouter=True, + ) + .join( + YishuvShape, + and_( + AccidentMarker.yishuv_shape == YishuvShape.id, + AccidentMarker.accident_year == YishuvShape.year, + AccidentMarker.provider_code == YishuvShape.provider_code, + ), + isouter=True, + ) + .join( + AccidentHourRaw, + and_( + AccidentMarker.accident_hour_raw == AccidentHourRaw.id, + AccidentMarker.accident_year == AccidentHourRaw.year, + AccidentMarker.provider_code == AccidentHourRaw.provider_code, + ), + isouter=True, + ) + .join(ProviderCode, and_(AccidentMarker.provider_code == ProviderCode.id), isouter=True) + ) + return select(selected_columns).select_from(from_clause) def create_involved_hebrew_view(self): selected_columns = [ @@ -402,107 +536,183 @@ def create_involved_hebrew_view(self): Involved.car_id, Involved.involve_id, Involved.accident_year, - Involved.accident_month + Involved.accident_month, ] table = Involved.__table__ - from_clause = table \ - .join(InvolvedType, - and_(Involved.involved_type == InvolvedType.id, - Involved.accident_year == InvolvedType.year, - Involved.provider_code == InvolvedType.provider_code), - isouter=True) \ - .join(AgeGroup, - and_(Involved.age_group == AgeGroup.id, - Involved.accident_year == AgeGroup.year, - Involved.provider_code == AgeGroup.provider_code), - isouter=True) \ - .join(Sex, - and_(Involved.sex == Sex.id, - Involved.accident_year == Sex.year, - Involved.provider_code == Sex.provider_code), - isouter=True) \ - .join(VehicleType, - and_(Involved.vehicle_type == VehicleType.id, - Involved.accident_year == VehicleType.year, - Involved.provider_code == VehicleType.provider_code), - isouter=True) \ - .join(SafetyMeasures, - and_(Involved.safety_measures == SafetyMeasures.id, - Involved.accident_year == SafetyMeasures.year, - Involved.provider_code == SafetyMeasures.provider_code), - isouter=True) \ - .join(InjurySeverity, - and_(Involved.injury_severity == InjurySeverity.id, - Involved.accident_year == InjurySeverity.year, - Involved.provider_code == InjurySeverity.provider_code), - isouter=True) \ - .join(InjuredType, - and_(Involved.injured_type == InjuredType.id, - Involved.accident_year == InjuredType.year, - Involved.provider_code == InjuredType.provider_code), - isouter=True) \ - .join(InjuredPosition, - and_(Involved.injured_position == InjuredPosition.id, - Involved.accident_year == InjuredPosition.year, - Involved.provider_code == InjuredPosition.provider_code), - isouter=True) \ - .join(PopulationType, - and_(Involved.population_type == PopulationType.id, - Involved.accident_year == PopulationType.year, - Involved.provider_code == PopulationType.provider_code), - isouter=True) \ - .join(Region, - and_(Involved.home_region == Region.id, - Involved.accident_year == Region.year, - Involved.provider_code == Region.provider_code), - isouter=True) \ - .join(District, - and_(Involved.home_district == District.id, - Involved.accident_year == District.year, - Involved.provider_code == District.provider_code), - isouter=True) \ - .join(NaturalArea, - and_(Involved.home_natural_area == NaturalArea.id, - Involved.accident_year == NaturalArea.year, - Involved.provider_code == NaturalArea.provider_code), - isouter=True) \ - .join(MunicipalStatus, - and_(Involved.home_municipal_status == MunicipalStatus.id, - Involved.accident_year == MunicipalStatus.year, - Involved.provider_code == MunicipalStatus.provider_code), - isouter=True) \ - .join(YishuvShape, - and_(Involved.home_yishuv_shape == YishuvShape.id, - Involved.accident_year == YishuvShape.year, - Involved.provider_code == YishuvShape.provider_code), - isouter=True) \ - .join(HospitalTime, - and_(Involved.hospital_time == HospitalTime.id, - Involved.accident_year == HospitalTime.year, - Involved.provider_code == HospitalTime.provider_code), - isouter=True) \ - .join(MedicalType, - and_(Involved.medical_type == MedicalType.id, - Involved.accident_year == MedicalType.year, - Involved.provider_code == MedicalType.provider_code), - isouter=True) \ - .join(ReleaseDest, - and_(Involved.release_dest == ReleaseDest.id, - Involved.accident_year == ReleaseDest.year, - Involved.provider_code == ReleaseDest.provider_code), - isouter=True) \ - .join(SafetyMeasuresUse, - and_(Involved.safety_measures_use == SafetyMeasuresUse.id, - Involved.accident_year == SafetyMeasuresUse.year, - Involved.provider_code == SafetyMeasuresUse.provider_code), - isouter=True) \ - .join(LateDeceased, - and_(Involved.late_deceased == LateDeceased.id, - Involved.accident_year == LateDeceased.year, - Involved.provider_code == LateDeceased.provider_code), - isouter=True) - return select(selected_columns) \ - .select_from(from_clause) + from_clause = ( + table.join( + InvolvedType, + and_( + Involved.involved_type == InvolvedType.id, + Involved.accident_year == InvolvedType.year, + Involved.provider_code == InvolvedType.provider_code, + ), + isouter=True, + ) + .join( + AgeGroup, + and_( + Involved.age_group == AgeGroup.id, + Involved.accident_year == AgeGroup.year, + Involved.provider_code == AgeGroup.provider_code, + ), + isouter=True, + ) + .join( + Sex, + and_( + Involved.sex == Sex.id, + Involved.accident_year == Sex.year, + Involved.provider_code == Sex.provider_code, + ), + isouter=True, + ) + .join( + VehicleType, + and_( + Involved.vehicle_type == VehicleType.id, + Involved.accident_year == VehicleType.year, + Involved.provider_code == VehicleType.provider_code, + ), + isouter=True, + ) + .join( + SafetyMeasures, + and_( + Involved.safety_measures == SafetyMeasures.id, + Involved.accident_year == SafetyMeasures.year, + Involved.provider_code == SafetyMeasures.provider_code, + ), + isouter=True, + ) + .join( + InjurySeverity, + and_( + Involved.injury_severity == InjurySeverity.id, + Involved.accident_year == InjurySeverity.year, + Involved.provider_code == InjurySeverity.provider_code, + ), + isouter=True, + ) + .join( + InjuredType, + and_( + Involved.injured_type == InjuredType.id, + Involved.accident_year == InjuredType.year, + Involved.provider_code == InjuredType.provider_code, + ), + isouter=True, + ) + .join( + InjuredPosition, + and_( + Involved.injured_position == InjuredPosition.id, + Involved.accident_year == InjuredPosition.year, + Involved.provider_code == InjuredPosition.provider_code, + ), + isouter=True, + ) + .join( + PopulationType, + and_( + Involved.population_type == PopulationType.id, + Involved.accident_year == PopulationType.year, + Involved.provider_code == PopulationType.provider_code, + ), + isouter=True, + ) + .join( + Region, + and_( + Involved.home_region == Region.id, + Involved.accident_year == Region.year, + Involved.provider_code == Region.provider_code, + ), + isouter=True, + ) + .join( + District, + and_( + Involved.home_district == District.id, + Involved.accident_year == District.year, + Involved.provider_code == District.provider_code, + ), + isouter=True, + ) + .join( + NaturalArea, + and_( + Involved.home_natural_area == NaturalArea.id, + Involved.accident_year == NaturalArea.year, + Involved.provider_code == NaturalArea.provider_code, + ), + isouter=True, + ) + .join( + MunicipalStatus, + and_( + Involved.home_municipal_status == MunicipalStatus.id, + Involved.accident_year == MunicipalStatus.year, + Involved.provider_code == MunicipalStatus.provider_code, + ), + isouter=True, + ) + .join( + YishuvShape, + and_( + Involved.home_yishuv_shape == YishuvShape.id, + Involved.accident_year == YishuvShape.year, + Involved.provider_code == YishuvShape.provider_code, + ), + isouter=True, + ) + .join( + HospitalTime, + and_( + Involved.hospital_time == HospitalTime.id, + Involved.accident_year == HospitalTime.year, + Involved.provider_code == HospitalTime.provider_code, + ), + isouter=True, + ) + .join( + MedicalType, + and_( + Involved.medical_type == MedicalType.id, + Involved.accident_year == MedicalType.year, + Involved.provider_code == MedicalType.provider_code, + ), + isouter=True, + ) + .join( + ReleaseDest, + and_( + Involved.release_dest == ReleaseDest.id, + Involved.accident_year == ReleaseDest.year, + Involved.provider_code == ReleaseDest.provider_code, + ), + isouter=True, + ) + .join( + SafetyMeasuresUse, + and_( + Involved.safety_measures_use == SafetyMeasuresUse.id, + Involved.accident_year == SafetyMeasuresUse.year, + Involved.provider_code == SafetyMeasuresUse.provider_code, + ), + isouter=True, + ) + .join( + LateDeceased, + and_( + Involved.late_deceased == LateDeceased.id, + Involved.accident_year == LateDeceased.year, + Involved.provider_code == LateDeceased.provider_code, + ), + isouter=True, + ) + ) + return select(selected_columns).select_from(from_clause) def create_involved_hebrew_markers_hebrew_view(self): selected_columns = [ @@ -666,23 +876,28 @@ def create_involved_hebrew_markers_hebrew_view(self): VehiclesView.vehicle_type.label("vehicle_vehicle_type"), VehiclesView.vehicle_type_hebrew.label("vehicle_vehicle_type_hebrew"), VehiclesView.vehicle_damage, - VehiclesView.vehicle_damage_hebrew + VehiclesView.vehicle_damage_hebrew, ] table = InvolvedView.__table__ - from_clause = table \ - .join(AccidentMarkerView, - and_(InvolvedView.provider_code == AccidentMarkerView.provider_code, - InvolvedView.accident_id == AccidentMarkerView.id, - InvolvedView.accident_year == AccidentMarkerView.accident_year), - isouter=True) \ - .join(VehiclesView, - and_(InvolvedView.provider_code == VehiclesView.provider_code, - InvolvedView.accident_id == VehiclesView.accident_id, - InvolvedView.accident_year == VehiclesView.accident_year, - InvolvedView.car_id == VehiclesView.car_id), - isouter=True) - return select(selected_columns) \ - .select_from(from_clause) + from_clause = table.join( + AccidentMarkerView, + and_( + InvolvedView.provider_code == AccidentMarkerView.provider_code, + InvolvedView.accident_id == AccidentMarkerView.id, + InvolvedView.accident_year == AccidentMarkerView.accident_year, + ), + isouter=True, + ).join( + VehiclesView, + and_( + InvolvedView.provider_code == VehiclesView.provider_code, + InvolvedView.accident_id == VehiclesView.accident_id, + InvolvedView.accident_year == VehiclesView.accident_year, + InvolvedView.car_id == VehiclesView.car_id, + ), + isouter=True, + ) + return select(selected_columns).select_from(from_clause) def create_vehicles_hebrew_view(self): selected_columns = [ @@ -709,47 +924,75 @@ def create_vehicles_hebrew_view(self): Vehicle.vehicle_damage, VehicleDamage.vehicle_damage_hebrew, Vehicle.accident_year, - Vehicle.accident_month + Vehicle.accident_month, ] table = Vehicle.__table__ - from_clause = table \ - .join(EngineVolume, - and_(Vehicle.engine_volume == EngineVolume.id, - Vehicle.accident_year == EngineVolume.year, - Vehicle.provider_code == EngineVolume.provider_code), - isouter=True) \ - .join(DrivingDirections, - and_(Vehicle.driving_directions == DrivingDirections.id, - Vehicle.accident_year == DrivingDirections.year, - Vehicle.provider_code == DrivingDirections.provider_code), - isouter=True) \ - .join(VehicleStatus, - and_(Vehicle.vehicle_status == VehicleStatus.id, - Vehicle.accident_year == VehicleStatus.year, - Vehicle.provider_code == VehicleStatus.provider_code), - isouter=True) \ - .join(VehicleAttribution, - and_(Vehicle.vehicle_attribution == VehicleAttribution.id, - Vehicle.accident_year == VehicleAttribution.year, - Vehicle.provider_code == VehicleAttribution.provider_code), - isouter=True) \ - .join(TotalWeight, - and_(Vehicle.total_weight == TotalWeight.id, - Vehicle.accident_year == TotalWeight.year, - Vehicle.provider_code == TotalWeight.provider_code), - isouter=True) \ - .join(VehicleType, - and_(Vehicle.vehicle_type == VehicleType.id, - Vehicle.accident_year == VehicleType.year, - Vehicle.provider_code == VehicleType.provider_code), - isouter=True) \ - .join(VehicleDamage, - and_(Vehicle.vehicle_damage == VehicleDamage.id, - Vehicle.accident_year == VehicleDamage.year, - Vehicle.provider_code == VehicleDamage.provider_code), - isouter=True) - return select(selected_columns) \ - .select_from(from_clause) + from_clause = ( + table.join( + EngineVolume, + and_( + Vehicle.engine_volume == EngineVolume.id, + Vehicle.accident_year == EngineVolume.year, + Vehicle.provider_code == EngineVolume.provider_code, + ), + isouter=True, + ) + .join( + DrivingDirections, + and_( + Vehicle.driving_directions == DrivingDirections.id, + Vehicle.accident_year == DrivingDirections.year, + Vehicle.provider_code == DrivingDirections.provider_code, + ), + isouter=True, + ) + .join( + VehicleStatus, + and_( + Vehicle.vehicle_status == VehicleStatus.id, + Vehicle.accident_year == VehicleStatus.year, + Vehicle.provider_code == VehicleStatus.provider_code, + ), + isouter=True, + ) + .join( + VehicleAttribution, + and_( + Vehicle.vehicle_attribution == VehicleAttribution.id, + Vehicle.accident_year == VehicleAttribution.year, + Vehicle.provider_code == VehicleAttribution.provider_code, + ), + isouter=True, + ) + .join( + TotalWeight, + and_( + Vehicle.total_weight == TotalWeight.id, + Vehicle.accident_year == TotalWeight.year, + Vehicle.provider_code == TotalWeight.provider_code, + ), + isouter=True, + ) + .join( + VehicleType, + and_( + Vehicle.vehicle_type == VehicleType.id, + Vehicle.accident_year == VehicleType.year, + Vehicle.provider_code == VehicleType.provider_code, + ), + isouter=True, + ) + .join( + VehicleDamage, + and_( + Vehicle.vehicle_damage == VehicleDamage.id, + Vehicle.accident_year == VehicleDamage.year, + Vehicle.provider_code == VehicleDamage.provider_code, + ), + isouter=True, + ) + ) + return select(selected_columns).select_from(from_clause) def create_vehicles_markers_hebrew_view(self): selected_columns = [ @@ -871,15 +1114,18 @@ def create_vehicles_markers_hebrew_view(self): VehiclesView.vehicle_type_hebrew, VehiclesView.vehicle_damage, VehiclesView.vehicle_damage_hebrew, - VehiclesView.car_id + VehiclesView.car_id, ] table = VehiclesView.__table__ - from_clause = table \ - .join(AccidentMarkerView, - and_(VehiclesView.provider_code == AccidentMarkerView.provider_code, - VehiclesView.accident_id == AccidentMarkerView.id, - VehiclesView.accident_year == AccidentMarkerView.accident_year)) - return select(selected_columns) \ - .select_from(from_clause) + from_clause = table.join( + AccidentMarkerView, + and_( + VehiclesView.provider_code == AccidentMarkerView.provider_code, + VehiclesView.accident_id == AccidentMarkerView.id, + VehiclesView.accident_year == AccidentMarkerView.accident_year, + ), + ) + return select(selected_columns).select_from(from_clause) + VIEWS = Views() diff --git a/anyway/flask_app.py b/anyway/flask_app.py index d1b94d31b..d5eb2d855 100755 --- a/anyway/flask_app.py +++ b/anyway/flask_app.py @@ -26,10 +26,7 @@ from anyway.clusters_calculator import retrieve_clusters from anyway.config import ENTRIES_PER_PAGE from anyway.constants import CONST -from anyway.infographics_utils import ( - get_infographics_mock_data, - get_infographics_data_for_location, -) +from anyway.infographics_utils import get_infographics_mock_data, get_infographics_data_for_location from anyway.models import ( @@ -68,7 +65,7 @@ get_downloaded_data, DEFAULT_LIMIT_REQ_PARAMETER, DEFAULT_OFFSET_REQ_PARAMETER, - DEFAULT_NUMBER_OF_YEARS_AGO + DEFAULT_NUMBER_OF_YEARS_AGO, ) from anyway.views.schools.api import ( schools_description_api, @@ -321,6 +318,7 @@ def schools(): else: return Response("Method Not Allowed", 405) + @app.route("/markers", methods=["GET"]) def markers(): logging.debug("getting markers") @@ -357,6 +355,7 @@ def markers(): accident_markers, rsa_markers, discussions, is_thin, total_records=result.total_records ) + @app.route("/markers_by_yishuv_symbol", methods=["GET"]) def markers_by_yishuv_symbol(): logging.debug("getting markers by yishuv symbol") @@ -1196,7 +1195,10 @@ def get(self): parser = reqparse.RequestParser() parser.add_argument("news_flash_id", type=int, help="News flash id") parser.add_argument( - "years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years" + "years_ago", + type=int, + default=DEFAULT_NUMBER_OF_YEARS_AGO, + help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years", ) parser.add_argument("lang", type=str, default="he", help="Language") @@ -1254,7 +1256,10 @@ def gps_to_cbs_location(): idbl_parser = reqparse.RequestParser() idbl_parser.add_argument("road_segment_id", type=int, help="Road Segment id") idbl_parser.add_argument( - "years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years" + "years_ago", + type=int, + default=DEFAULT_NUMBER_OF_YEARS_AGO, + help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years", ) idbl_parser.add_argument("lang", type=str, default="he", help="Language") @@ -1455,6 +1460,7 @@ def post(self): "road_segment_id", type=int, required=True, help="road segment id" ) + @api.route("/api/streets") @api.expect(get_streets_parser) class GetAllStreetsOfYishuv(Resource): @@ -1499,17 +1505,26 @@ def put(self, id): download_data_parser = reqparse.RequestParser() -download_data_parser.add_argument("format", type=str, default="csv", -help="Format for downloaded data (.csv/.xlsx)") -download_data_parser.add_argument("years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, -help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years") +download_data_parser.add_argument( + "format", type=str, default="csv", help="Format for downloaded data (.csv/.xlsx)" +) +download_data_parser.add_argument( + "years_ago", + type=int, + default=DEFAULT_NUMBER_OF_YEARS_AGO, + help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years", +) """ Download accidents data with regards to news flash/location """ + + @api.route("/api/download-data", methods=["GET"]) class DownloadData(Resource): @api.doc("download data") @api.expect(parser) def get(self): args = download_data_parser.parse_args() - return get_downloaded_data(args.get('format', 'csv'), args.get('years_ago', DEFAULT_NUMBER_OF_YEARS_AGO)) \ No newline at end of file + return get_downloaded_data( + args.get("format", "csv"), args.get("years_ago", DEFAULT_NUMBER_OF_YEARS_AGO) + ) diff --git a/anyway/infographic_image_generator.py b/anyway/infographic_image_generator.py index 051560d31..48bf2dd99 100644 --- a/anyway/infographic_image_generator.py +++ b/anyway/infographic_image_generator.py @@ -13,7 +13,7 @@ NEWSFLASH_PAGE_BASE_URL = "https://media.anyway.co.il/newsflash" IMAGES_DOWNLOAD_PATH_IN_CONTAINER = "/var/selenium/tempdata" -selenium_url = secrets.get('SELENIUM_URL') +selenium_url = secrets.get("SELENIUM_URL") selenium_hub_url = f"https://{selenium_url}/wd/hub" selenium_remote_results_url = f"https://{selenium_url}/tempdata" CHROME_PARTIALLY_DOWNLOADED_FILE_EXTENSION = "crdownload" @@ -29,10 +29,7 @@ def create_chrome_browser_session(newsflash_id): } options.add_experimental_option("prefs", prefs) - browser = webdriver.Remote( - command_executor=selenium_hub_url, - options=options - ) + browser = webdriver.Remote(command_executor=selenium_hub_url, options=options) return browser @@ -66,9 +63,8 @@ def contains_partial_files(filenames): def fetch_generated_image_filenames_for_newsflash(newsflash_id): - contents = requests.get( - f"{selenium_remote_results_url}/{newsflash_id}/").json() - filenames = [item['name'] for item in contents] + contents = requests.get(f"{selenium_remote_results_url}/{newsflash_id}/").json() + filenames = [item["name"] for item in contents] return get_unique_filenames(filenames) @@ -76,7 +72,9 @@ def wait_for_folder_to_contain_all_files(newsflash_id, number_of_expected_files, for _ in range(timeout): time.sleep(1) image_filenames = fetch_generated_image_filenames_for_newsflash(newsflash_id) - if len(image_filenames) == number_of_expected_files and not contains_partial_files(image_filenames): + if len(image_filenames) == number_of_expected_files and not contains_partial_files( + image_filenames + ): return True, image_filenames return False, [] @@ -94,9 +92,10 @@ def generate_infographics_in_selenium_container(browser, newsflash_id): if buttons_found > 0: for element in elements: ActionChains(browser).move_to_element(element).click().perform() - time.sleep(1) #prevents click arriving before the last finished - is_download_done, generated_images_names = wait_for_folder_to_contain_all_files(newsflash_id, - buttons_found, timeout=60) + time.sleep(1) # prevents click arriving before the last finished + is_download_done, generated_images_names = wait_for_folder_to_contain_all_files( + newsflash_id, buttons_found, timeout=60 + ) except Exception as e: logging.error(e) finally: @@ -113,7 +112,9 @@ def upload_infographics_images_to_s3(newsflash_id, should_download=True): local_infographics_folder = get_local_infographics_folder_name(newsflash_id) if should_download: generated_images_names = fetch_generated_image_filenames_for_newsflash(newsflash_id) - download_infographics_images(generated_images_names, newsflash_id, local_infographics_folder) + download_infographics_images( + generated_images_names, newsflash_id, local_infographics_folder + ) upload_directory_to_s3(local_infographics_folder, newsflash_id) diff --git a/anyway/infographics_utils.py b/anyway/infographics_utils.py index d6f48b748..14b66a289 100755 --- a/anyway/infographics_utils.py +++ b/anyway/infographics_utils.py @@ -33,6 +33,7 @@ import anyway.widgets.road_segment_widgets import anyway.widgets.all_locations_widgets import anyway.widgets.no_location_widgets + # pylint: enable=unused-import logger = logging.getLogger("infographics_utils") @@ -135,7 +136,7 @@ def get_request_params( start_time=start_time, end_time=end_time, lang=lang, - news_flash_description=news_flash_description + news_flash_description=news_flash_description, ) logging.debug(f"Ending get_request_params. params: {request_params}") return request_params diff --git a/anyway/models.py b/anyway/models.py index 5116d5908..478c4a48e 100755 --- a/anyway/models.py +++ b/anyway/models.py @@ -7,7 +7,6 @@ from typing import List, Set, Iterable - try: from flask_login import UserMixin except ModuleNotFoundError: @@ -880,7 +879,9 @@ class NewsFlash(Base): newsflash_location_qualification = Column( Integer(), nullable=False, - server_default=text(f"{NewsflashLocationQualification.NOT_VERIFIED.value}"), # pylint: disable=no-member + server_default=text( + f"{NewsflashLocationQualification.NOT_VERIFIED.value}" + ), # pylint: disable=no-member ) location_qualifying_user = Column(BigInteger(), nullable=True) @@ -892,7 +893,7 @@ def set_critical( urban_severe_value=2, ): from anyway.widgets.all_locations_widgets.injured_count_by_severity_widget import ( - InjuredCountBySeverityWidget, + InjuredCountBySeverityWidget ) from anyway.request_params import get_latest_accident_date @@ -1188,7 +1189,6 @@ def get_streets_by_yishuv(yishuv_symbol: int) -> List[dict]: raise RuntimeError(f"When retrieving streets of {yishuv_symbol}") return res1 - @staticmethod def get_streets_by_yishuv_name(yishuv_name: str) -> List[dict]: yishuv_symbol = City.get_symbol_from_name(yishuv_name) @@ -1207,45 +1207,58 @@ class SuburbanJunction(Base): __tablename__ = "suburban_junction" MAX_NAME_LEN = 100 non_urban_intersection = Column(Integer(), primary_key=True, nullable=False) - non_urban_intersection_hebrew = Column(String(length=MAX_NAME_LEN), - nullable=True) + non_urban_intersection_hebrew = Column(String(length=MAX_NAME_LEN), nullable=True) roads = Column(postgresql.ARRAY(Integer(), dimensions=1), nullable=False) @staticmethod def get_hebrew_name_from_id(non_urban_intersection: int) -> str: - res = db.session.query(SuburbanJunction.non_urban_intersection_hebrew).filter( - SuburbanJunction.non_urban_intersection == non_urban_intersection).first() + res = ( + db.session.query(SuburbanJunction.non_urban_intersection_hebrew) + .filter(SuburbanJunction.non_urban_intersection == non_urban_intersection) + .first() + ) if res is None: - raise ValueError(f"{non_urban_intersection}: could not find " - f"SuburbanJunction with that symbol") + raise ValueError( + f"{non_urban_intersection}: could not find " f"SuburbanJunction with that symbol" + ) return res.non_urban_intersection_hebrew @staticmethod def get_id_from_hebrew_name(non_urban_intersection_hebrew: str) -> int: - res = db.session.query(SuburbanJunction.non_urban_intersection).filter( - SuburbanJunction.non_urban_intersection == non_urban_intersection_hebrew).first() + res = ( + db.session.query(SuburbanJunction.non_urban_intersection) + .filter(SuburbanJunction.non_urban_intersection == non_urban_intersection_hebrew) + .first() + ) if res is None: - raise ValueError(f"{non_urban_intersection_hebrew}: could not find " - f"SuburbanJunction with that name") + raise ValueError( + f"{non_urban_intersection_hebrew}: could not find " + f"SuburbanJunction with that name" + ) return res.non_urban_intersection @staticmethod def get_intersection_from_roads(roads: Set[int]) -> dict: if not all([isinstance(x, int) for x in roads]): raise ValueError(f"{roads}: Should be integers") - res = db.session.query(SuburbanJunction).filter( - SuburbanJunction.roads.contains(roads)).first() + res = ( + db.session.query(SuburbanJunction) + .filter(SuburbanJunction.roads.contains(roads)) + .first() + ) if res is None: - raise ValueError(f"{roads}: could not find " - f"SuburbanJunction with these roads") + raise ValueError(f"{roads}: could not find " f"SuburbanJunction with these roads") return res.serialize() @staticmethod def get_all_from_key_value(key: str, val: Iterable) -> dict: if not isinstance(val, Iterable): val = [val] - res = db.session.query(SuburbanJunction).filter( - (getattr(SuburbanJunction, key)).in_(val)).first() + res = ( + db.session.query(SuburbanJunction) + .filter((getattr(SuburbanJunction, key)).in_(val)) + .first() + ) if res is None: raise ValueError(f"{key}:{val}: could not find SuburbanJunction") return res.serialize() @@ -2224,20 +2237,30 @@ def get_segment_id(self): @staticmethod def get_segments_by_segment(road_segment_id: int): - curr_road = (db.session.query(RoadSegments.road) - .filter(RoadSegments.segment_id == road_segment_id) - .all()) + curr_road = ( + db.session.query(RoadSegments.road) + .filter(RoadSegments.segment_id == road_segment_id) + .all() + ) curr_road_processed = [{"road": s.road} for s in curr_road] if curr_road is None or curr_road_processed is None: raise RuntimeError(f"When retrieving segments of {road_segment_id}") road = curr_road_processed[0]["road"] - res = (db.session.query(RoadSegments.segment_id, RoadSegments.from_name, RoadSegments.to_name) - .filter(RoadSegments.road == road) - .all()) - res1 = [{"road": road, "road_segment_id": s.segment_id, "road_segment_name": " - ".join([s.from_name, s.to_name])} for s in res] + res = ( + db.session.query(RoadSegments.segment_id, RoadSegments.from_name, RoadSegments.to_name) + .filter(RoadSegments.road == road) + .all() + ) + res1 = [ + { + "road": road, + "road_segment_id": s.segment_id, + "road_segment_name": " - ".join([s.from_name, s.to_name]), + } + for s in res + ] return res1 - @staticmethod def get_streets_by_yishuv_name(yishuv_name: str) -> List[dict]: yishuv_symbol = City.get_symbol_from_name(yishuv_name) @@ -2251,6 +2274,7 @@ def get_streets_by_yishuv_name(yishuv_name: str) -> List[dict]: raise RuntimeError(f"When retrieving streets of {yishuv_symbol}") return res1 + class Comment(Base): __tablename__ = "comments" id = Column(BigInteger(), autoincrement=True, primary_key=True, index=True) @@ -2258,7 +2282,7 @@ class Comment(Base): parent = Column(Integer, ForeignKey("comments.id"), nullable=True) created_time = Column(DateTime, default=datetime.datetime.now, index=True, nullable=False) street = Column(Text(), nullable=True, index=True) - city = Column(Text(), nullable=True, index=True) + city = Column(Text(), nullable=True, index=True) road_segment_id = Column(Integer(), nullable=True, index=True) def serialize(self): @@ -2269,12 +2293,10 @@ def serialize(self): "street": self.street, "parent": self.parent, "city": self.city, - "road_segment_id": self.road_segment_id - + "road_segment_id": self.road_segment_id, } - class ReportProblem(Base): __tablename__ = "report_problem" id = Column(BigInteger(), autoincrement=True, primary_key=True, index=True) @@ -2304,7 +2326,7 @@ class InvolvedMarkerView(Base): __table_args__ = ( Index("inv_markers_accident_yishuv_symbol_idx", "accident_yishuv_symbol", unique=False), Index("inv_markers_injury_severity_idx", "injury_severity", unique=False), - Index("inv_markers_involve_vehicle_type_idx", "involve_vehicle_type", unique=False) + Index("inv_markers_involve_vehicle_type_idx", "involve_vehicle_type", unique=False), ) accident_id = Column(BigInteger(), primary_key=True) @@ -2970,14 +2992,17 @@ class TelegramGroupsBase(Base): id = Column(Integer(), primary_key=True) filter = Column(JSON(), nullable=False, server_default="{}") + class TelegramGroups(TelegramGroupsBase): __tablename__ = "telegram_groups" + class TelegramGroupsTest(TelegramGroupsBase): __tablename__ = "telegram_groups_test" -class TelegramForwardedMessages(): - __tablename__ = 'telegram_forwarded_messages' + +class TelegramForwardedMessages: + __tablename__ = "telegram_forwarded_messages" message_id = Column(String(), primary_key=True) newsflash_id = Column(BigInteger(), nullable=False) - group_sent = Column(String(), nullable=False), + group_sent = (Column(String(), nullable=False),) diff --git a/anyway/parsers/cbs/executor.py b/anyway/parsers/cbs/executor.py index edc08eed8..aff61cdfa 100644 --- a/anyway/parsers/cbs/executor.py +++ b/anyway/parsers/cbs/executor.py @@ -85,8 +85,15 @@ VehicleMarkerView, ) from anyway.parsers.cbs.exceptions import CBSParsingFailed -from anyway.utilities import ItmToWGS84, time_delta, ImporterUI, truncate_tables, delete_all_rows_from_table, \ - chunks, run_query_and_insert_to_table_in_chunks +from anyway.utilities import ( + ItmToWGS84, + time_delta, + ImporterUI, + truncate_tables, + delete_all_rows_from_table, + chunks, + run_query_and_insert_to_table_in_chunks, +) from anyway.db_views import VIEWS from anyway.app_and_db import db from anyway.parsers.cbs.s3 import S3DataRetriever @@ -277,7 +284,7 @@ def get_address(accident, streets): house_number = ( int(accident.get(field_names.house_number)) if not pd.isnull(accident.get(field_names.house_number)) - and int(accident.get(field_names.house_number)) != 9999 + and int(accident.get(field_names.house_number)) != 9999 else None ) settlement = localization.get_city_name(accident.get(field_names.yishuv_symbol)) @@ -342,16 +349,16 @@ def get_junction(accident, roads): :return: returns the junction or None if it wasn't found """ if ( - accident.get(field_names.km) is not None - and accident.get(field_names.non_urban_intersection) is None + accident.get(field_names.km) is not None + and accident.get(field_names.non_urban_intersection) is None ): min_dist = 100000 key = (), () junc_km = 0 for option in roads: if ( - accident.get(field_names.road1) == option[0] - and abs(accident["KM"] - option[2]) < min_dist + accident.get(field_names.road1) == option[0] + and abs(accident["KM"] - option[2]) < min_dist ): min_dist = abs(accident.get(field_names.km) - option[2]) key = accident.get(field_names.road1), option[1], option[2] @@ -364,19 +371,19 @@ def get_junction(accident, roads): direction = "דרומית" if accident.get(field_names.road1) % 2 == 0 else "מערבית" if abs(float(accident["KM"] - junc_km) / 10) >= 1: string = ( - str(abs(float(accident["KM"]) - junc_km) / 10) - + " ק״מ " - + direction - + " ל" - + junction + str(abs(float(accident["KM"]) - junc_km) / 10) + + " ק״מ " + + direction + + " ל" + + junction ) elif 0 < abs(float(accident["KM"] - junc_km) / 10) < 1: string = ( - str(int((abs(float(accident.get(field_names.km)) - junc_km) / 10) * 1000)) - + " מטרים " - + direction - + " ל" - + junction + str(int((abs(float(accident.get(field_names.km)) - junc_km) / 10) * 1000)) + + " מטרים " + + direction + + " ל" + + junction ) else: string = junction @@ -460,10 +467,10 @@ def create_marker(provider_code, accident, streets, roads, non_urban_intersectio if field_names.x not in accident or field_names.y not in accident: raise ValueError("Missing x and y coordinates") if ( - accident.get(field_names.x) - and not math.isnan(accident.get(field_names.x)) - and accident.get(field_names.y) - and not math.isnan(accident.get(field_names.y)) + accident.get(field_names.x) + and not math.isnan(accident.get(field_names.x)) + and accident.get(field_names.y) + and not math.isnan(accident.get(field_names.y)) ): lng, lat = coordinates_converter.convert( accident.get(field_names.x), accident.get(field_names.y) @@ -584,7 +591,7 @@ def import_involved(provider_code, involved, **kwargs): involved_result = [] for _, involve in involved.iterrows(): if not involve.get(field_names.id) or pd.isnull( - involve.get(field_names.id) + involve.get(field_names.id) ): # skip lines with no accident id continue file_type_police = involve.get(field_names.file_type_police) @@ -699,7 +706,8 @@ def get_files(directory): field_names.street_sign: x[field_names.street_sign], field_names.street_name: x[field_names.street_name], } - for _, x in settlement.iterrows() if isinstance(x[field_names.street_name], str) + for _, x in settlement.iterrows() + if isinstance(x[field_names.street_name], str) ] output_files_dict[name] = streets_map @@ -719,7 +727,7 @@ def get_files(directory): def import_to_datastore( - directory, provider_code, year, batch_size + directory, provider_code, year, batch_size ) -> Tuple[int, Dict[int, List[dict]]]: """ goes through all the files in a given directory, parses and commits them @@ -843,13 +851,15 @@ def add_street_remove_name_duplicates(street: Dict[str, Any]): def import_suburban_junctions_into_db(): - items = [{"non_urban_intersection": k, - NON_URBAN_INTERSECTION_HEBREW: fix_name_len(v[NON_URBAN_INTERSECTION_HEBREW]), - ROADS: v[ROADS]} for - k, v in suburban_junctions_dict.items()] - logging.debug( - f"Writing to db: {len(items)} suburban junctions" - ) + items = [ + { + "non_urban_intersection": k, + NON_URBAN_INTERSECTION_HEBREW: fix_name_len(v[NON_URBAN_INTERSECTION_HEBREW]), + ROADS: v[ROADS], + } + for k, v in suburban_junctions_dict.items() + ] + logging.debug(f"Writing to db: {len(items)} suburban junctions") db.session.query(SuburbanJunction).delete() db.session.bulk_insert_mappings(SuburbanJunction, items) db.session.commit() @@ -860,10 +870,13 @@ def fix_name_len(name: str) -> str: if not isinstance(name, str): return name if len(name) > SuburbanJunction.MAX_NAME_LEN: - logging.error(f"Suburban_junction name too long ({len(name)}>" - f"{SuburbanJunction.MAX_NAME_LEN}):{name}.") + logging.error( + f"Suburban_junction name too long ({len(name)}>" + f"{SuburbanJunction.MAX_NAME_LEN}):{name}." + ) return name[: SuburbanJunction.MAX_NAME_LEN] + def load_existing_suburban_junctions(): junctions: List[SuburbanJunction] = db.session.query(SuburbanJunction).all() for j in junctions: @@ -1042,32 +1055,32 @@ def fill_dictionary_tables(cbs_dictionary, provider_code, year): if inner_v is None or (isinstance(inner_v, float) and math.isnan(inner_v)): continue sql_delete = ( - "DELETE FROM " - + curr_table - + " WHERE provider_code=" - + str(provider_code) - + " AND year=" - + str(year) - + " AND id=" - + str(inner_k) + "DELETE FROM " + + curr_table + + " WHERE provider_code=" + + str(provider_code) + + " AND year=" + + str(year) + + " AND id=" + + str(inner_k) ) db.session.execute(sql_delete) db.session.commit() sql_insert = ( - "INSERT INTO " - + curr_table - + " VALUES (" - + str(inner_k) - + "," - + str(year) - + "," - + str(provider_code) - + "," - + "'" - + inner_v.replace("'", "") - + "'" - + ")" - + " ON CONFLICT DO NOTHING" + "INSERT INTO " + + curr_table + + " VALUES (" + + str(inner_k) + + "," + + str(year) + + "," + + str(provider_code) + + "," + + "'" + + inner_v.replace("'", "") + + "'" + + ")" + + " ON CONFLICT DO NOTHING" ) db.session.execute(sql_insert) db.session.commit() @@ -1100,7 +1113,7 @@ def create_provider_code_table(): } for k, v in provider_code_dict.items(): sql_insert = ( - "INSERT INTO " + provider_code_table + " VALUES (" + str(k) + "," + "'" + v + "'" + ")" + "INSERT INTO " + provider_code_table + " VALUES (" + str(k) + "," + "'" + v + "'" + ")" ) db.session.execute(sql_insert) db.session.commit() @@ -1118,28 +1131,45 @@ def create_tables(): with db.get_engine().begin() as conn: event.listen(conn, "rollback", receive_rollback) delete_all_rows_from_table(conn, AccidentMarkerView) - run_query_and_insert_to_table_in_chunks(VIEWS.create_markers_hebrew_view(), AccidentMarkerView, - AccidentMarker.id, chunk_size, conn) + run_query_and_insert_to_table_in_chunks( + VIEWS.create_markers_hebrew_view(), + AccidentMarkerView, + AccidentMarker.id, + chunk_size, + conn, + ) logging.debug("after insertion to markers_hebrew ") delete_all_rows_from_table(conn, InvolvedView) - run_query_and_insert_to_table_in_chunks(VIEWS.create_involved_hebrew_view(), InvolvedView, - Involved.id, chunk_size, conn) + run_query_and_insert_to_table_in_chunks( + VIEWS.create_involved_hebrew_view(), InvolvedView, Involved.id, chunk_size, conn + ) logging.debug("after insertion to involved_hebrew ") delete_all_rows_from_table(conn, VehiclesView) - run_query_and_insert_to_table_in_chunks(VIEWS.create_vehicles_hebrew_view(), - VehiclesView, Vehicle.id, chunk_size, conn) + run_query_and_insert_to_table_in_chunks( + VIEWS.create_vehicles_hebrew_view(), VehiclesView, Vehicle.id, chunk_size, conn + ) logging.debug("after insertion to vehicles_hebrew ") delete_all_rows_from_table(conn, VehicleMarkerView) - run_query_and_insert_to_table_in_chunks(VIEWS.create_vehicles_markers_hebrew_view(), - VehicleMarkerView, VehiclesView.id, chunk_size, conn) + run_query_and_insert_to_table_in_chunks( + VIEWS.create_vehicles_markers_hebrew_view(), + VehicleMarkerView, + VehiclesView.id, + chunk_size, + conn, + ) logging.debug("after insertion to vehicles_markers_hebrew ") delete_all_rows_from_table(conn, InvolvedMarkerView) - run_query_and_insert_to_table_in_chunks(VIEWS.create_involved_hebrew_markers_hebrew_view(), - InvolvedMarkerView, InvolvedView.accident_id, chunk_size, conn) + run_query_and_insert_to_table_in_chunks( + VIEWS.create_involved_hebrew_markers_hebrew_view(), + InvolvedMarkerView, + InvolvedView.accident_id, + chunk_size, + conn, + ) logging.debug("after insertion to involved_markers_hebrew") logging.debug("Created DB Hebrew Tables") except Exception as e: diff --git a/anyway/parsers/cbs/s3/base.py b/anyway/parsers/cbs/s3/base.py index 6c295b54c..784ac68ab 100644 --- a/anyway/parsers/cbs/s3/base.py +++ b/anyway/parsers/cbs/s3/base.py @@ -25,4 +25,4 @@ def s3_resource(self): def s3_bucket(self): if self._s3_bucket is None: self._s3_bucket = self.s3_resource.Bucket(ANYWAY_BUCKET) - return self._s3_bucket \ No newline at end of file + return self._s3_bucket diff --git a/anyway/request_params.py b/anyway/request_params.py index d775bb2d9..06bf8d120 100644 --- a/anyway/request_params.py +++ b/anyway/request_params.py @@ -301,7 +301,9 @@ def fill_missing_non_urban_intersection_values(vals: dict) -> dict: and "road1" in res and "road2" in res ): - res.update(SuburbanJunction.get_intersection_from_roads({int(res["road1"]), int(res["road2"])})) + res.update( + SuburbanJunction.get_intersection_from_roads({int(res["road1"]), int(res["road2"])}) + ) else: raise ValueError(f"Cannot get non_urban_intersection from input: {vals}") # TODO: temporarily removing "roads" field, as it is not used correctly in the filters. @@ -357,9 +359,7 @@ def extract_news_flash_location(news_flash_obj: NewsFlash): return {"name": "location", "data": data, "gps": gps} -def get_location_from_request_values( - values: dict -): +def get_location_from_request_values(values: dict): road_segment_id = values.get("road_segment_id") if road_segment_id is not None: return extract_road_segment_location(road_segment_id) @@ -368,7 +368,7 @@ def get_location_from_request_values( data["street"] = values["street"] data["yishuv_name"] = values["yishuv_name"] - return {"name": "location", "data": data } + return {"name": "location", "data": data} logging.error(f"Unsupported location:{values.values()}") return None diff --git a/anyway/telegram_accident_notifications.py b/anyway/telegram_accident_notifications.py index 3d6cfb2fa..25b6ef639 100644 --- a/anyway/telegram_accident_notifications.py +++ b/anyway/telegram_accident_notifications.py @@ -11,92 +11,118 @@ TELEGRAM_CHANNEL_CHAT_ID = -1001666083560 TELEGRAM_LINKED_GROUP_CHAT_ID = -1001954877540 -TEXT_FOR_AFTER_INFOGRAPHICS_MESSAGE = 'מקור המידע בלמ"ס. נתוני התאונה שבמבזק לא נכללים באינפוגרפיקה. ' \ - 'הופק באמצעות ANYWAY מבית "נתון לשינוי" למידע נוסף:' +TEXT_FOR_AFTER_INFOGRAPHICS_MESSAGE = 'מקור המידע בלמ"ס. נתוני התאונה שבמבזק לא נכללים באינפוגרפיקה. ' 'הופק באמצעות ANYWAY מבית "נתון לשינוי" למידע נוסף:' + def send_initial_message_in_channel(bot, text): return bot.send_message(TELEGRAM_CHANNEL_CHAT_ID, text) -def fetch_message_id_for_initial_message_in_discussion_group(bot, thread_starting_message_in_channel): +def fetch_message_id_for_initial_message_in_discussion_group( + bot, thread_starting_message_in_channel +): tries = 3 for _ in range(tries): time.sleep(10) updates = bot.get_updates(allowed_updates=[]) for update in updates: - if update.message and update.message.content_type == "text" \ - and update.message.forward_from_message_id == thread_starting_message_in_channel.message_id: + if ( + update.message + and update.message.content_type == "text" + and update.message.forward_from_message_id + == thread_starting_message_in_channel.message_id + ): return update.message.message_id logging.error("failed to fetch message id in group") return None def remove_seconds_from_time_and_date(time_and_date): - return time_and_date[:time_and_date.rindex(":")] + return time_and_date[: time_and_date.rindex(":")] def create_accident_text(newsflash_id): newsflash = requests.get(f"{ANYWAY_BASE_API_URL}/news-flash/{newsflash_id}").json() - organization = newsflash['organization'] - date_and_time = remove_seconds_from_time_and_date(newsflash['date']) + organization = newsflash["organization"] + date_and_time = remove_seconds_from_time_and_date(newsflash["date"]) first_line = f"[{organization}] {date_and_time}:" return f"{first_line}\n\n{newsflash['description']}" def fetch_transcription_by_widget_name(newsflash_id): - widgets_url = f"{ANYWAY_BASE_API_URL}/infographics-data?lang=he&news_flash_id={newsflash_id}&years_ago=5" + widgets_url = ( + f"{ANYWAY_BASE_API_URL}/infographics-data?lang=he&news_flash_id={newsflash_id}&years_ago=5" + ) widgets_json = requests.get(widgets_url).json() - transcription_by_widget_name = {widget["name"]: widget["data"]["text"]["transcription"] - for widget in widgets_json["widgets"] - if "transcription" in widget["data"]["text"]} + transcription_by_widget_name = { + widget["name"]: widget["data"]["text"]["transcription"] + for widget in widgets_json["widgets"] + if "transcription" in widget["data"]["text"] + } return transcription_by_widget_name def send_after_infographics_message(bot, message_id_in_group, newsflash_id): newsflash_link = f"https://media.anyway.co.il/newsflash/{newsflash_id}" message = f"{TEXT_FOR_AFTER_INFOGRAPHICS_MESSAGE}\n{newsflash_link}" - return bot.send_message(TELEGRAM_LINKED_GROUP_CHAT_ID, message, reply_to_message_id=message_id_in_group) + return bot.send_message( + TELEGRAM_LINKED_GROUP_CHAT_ID, message, reply_to_message_id=message_id_in_group + ) + def publish_notification(newsflash_id): - #fetch data for send + # fetch data for send accident_text = create_accident_text(newsflash_id) transcription_by_widget_name = fetch_transcription_by_widget_name(newsflash_id) urls_by_infographic_name = create_public_urls_for_infographics_images(str(newsflash_id)) bot = telebot.TeleBot(secrets.get("BOT_TOKEN")) initial_message_in_channel = send_initial_message_in_channel(bot, accident_text) - #every message in the channel is automatically forwarded to the linked discussion group. - #to create a comment on the channel message, we need to send a reply to the - #forwareded message in the discussion group. - message_id_in_group = \ - fetch_message_id_for_initial_message_in_discussion_group(bot, initial_message_in_channel) + # every message in the channel is automatically forwarded to the linked discussion group. + # to create a comment on the channel message, we need to send a reply to the + # forwareded message in the discussion group. + message_id_in_group = fetch_message_id_for_initial_message_in_discussion_group( + bot, initial_message_in_channel + ) if message_id_in_group: for infographic_name, url in urls_by_infographic_name.items(): - text = transcription_by_widget_name[infographic_name] \ - if infographic_name in transcription_by_widget_name else None - bot.send_photo(TELEGRAM_LINKED_GROUP_CHAT_ID, url, reply_to_message_id=message_id_in_group, caption=text) + text = ( + transcription_by_widget_name[infographic_name] + if infographic_name in transcription_by_widget_name + else None + ) + bot.send_photo( + TELEGRAM_LINKED_GROUP_CHAT_ID, + url, + reply_to_message_id=message_id_in_group, + caption=text, + ) send_after_infographics_message(bot, message_id_in_group, newsflash_id) logging.info("notification send done") + def extract_infographic_name_from_s3_object(s3_object_name): left = s3_object_name.rindex("/") right = s3_object_name.rindex(".") - return s3_object_name[left + 1: right] + return s3_object_name[left + 1 : right] def create_public_urls_for_infographics_images(folder_name): - S3_client = boto3.client('s3', - aws_access_key_id=secrets.get("AWS_ACCESS_KEY"), - aws_secret_access_key=secrets.get("AWS_SECRET_KEY") - ) - objects_contents = S3_client.list_objects_v2(Bucket=INFOGRAPHICS_S3_BUCKET, - Prefix=folder_name)["Contents"] + S3_client = boto3.client( + "s3", + aws_access_key_id=secrets.get("AWS_ACCESS_KEY"), + aws_secret_access_key=secrets.get("AWS_SECRET_KEY"), + ) + objects_contents = S3_client.list_objects_v2(Bucket=INFOGRAPHICS_S3_BUCKET, Prefix=folder_name)[ + "Contents" + ] presigned_urls = {} for object in objects_contents: key = object["Key"] - url = S3_client.generate_presigned_url('get_object', Params={'Bucket': INFOGRAPHICS_S3_BUCKET, - 'Key': key}) + url = S3_client.generate_presigned_url( + "get_object", Params={"Bucket": INFOGRAPHICS_S3_BUCKET, "Key": key} + ) infographic_name = extract_infographic_name_from_s3_object(key) presigned_urls[infographic_name] = url return presigned_urls diff --git a/anyway/utilities.py b/anyway/utilities.py index 7181e3d54..675905335 100644 --- a/anyway/utilities.py +++ b/anyway/utilities.py @@ -174,13 +174,15 @@ def row_to_dict(row): def fetch_first_and_every_nth_value_for_column(conn, column_to_fetch, n): - sub_query = select([])\ - .column(column_to_fetch)\ - .column(func.row_number().over(order_by=column_to_fetch).label("row_number"))\ + sub_query = ( + select([]) + .column(column_to_fetch) + .column(func.row_number().over(order_by=column_to_fetch).label("row_number")) .alias() - select_query = select([sub_query]) \ - .where(or_(func.mod(sub_query.c.row_number, n) == 0, - sub_query.c.row_number == 1)) + ) + select_query = select([sub_query]).where( + or_(func.mod(sub_query.c.row_number, n) == 0, sub_query.c.row_number == 1) + ) ids_and_row_numbers = conn.execute(select_query).fetchall() ids = [id_and_row_number[0] for id_and_row_number in ids_and_row_numbers] return ids @@ -212,7 +214,9 @@ def split_query_to_chunks_by_column(base_select, column_to_chunk_by, chunk_size, logging.debug("after running query on all chunks") -def run_query_and_insert_to_table_in_chunks(query, table_inserted_to, column_to_chunk_by, chunk_size, conn): +def run_query_and_insert_to_table_in_chunks( + query, table_inserted_to, column_to_chunk_by, chunk_size, conn +): for chunk in split_query_to_chunks_by_column(query, column_to_chunk_by, chunk_size, conn): conn.execute(table_inserted_to.__table__.insert(), chunk) @@ -315,7 +319,7 @@ def is_a_safe_redirect_url(url: str) -> bool: "anyway-infographics-staging.web.app", "anyway-infographics.web.app", "anyway-infographics-demo.web.app", - "media.anyway.co.il" + "media.anyway.co.il", ]: return True @@ -339,6 +343,7 @@ def is_a_valid_email(tmp_given_user_email: str) -> bool: def half_rounded_up(num: int): return math.ceil(num / 2) + def trigger_airflow_dag(dag_id, conf=None): import airflow_client.client from airflow_client.client.api import dag_run_api @@ -351,7 +356,7 @@ def trigger_airflow_dag(dag_id, conf=None): configuration = airflow_client.client.Configuration( host=airflow_api_url, username=secrets.get("AIRFLOW_USER"), - password=secrets.get("AIRFLOW_PASSWORD") + password=secrets.get("AIRFLOW_PASSWORD"), ) with airflow_client.client.ApiClient(configuration) as api_client: dag_run_api_instance = dag_run_api.DAGRunApi(api_client) diff --git a/anyway/views/comments/api.py b/anyway/views/comments/api.py index 9b9866304..d5d7637bc 100644 --- a/anyway/views/comments/api.py +++ b/anyway/views/comments/api.py @@ -13,13 +13,14 @@ from anyway.request_params import get_location_from_request_values + def create_comment(): - current_user = get_current_user() + current_user = get_current_user() json_data = request.get_json(force=True) logging.debug(json_data) - + resolution = json_data["resolution"] parent = json_data["parent"] road_segment_id = None @@ -34,23 +35,24 @@ def create_comment(): raise ValueError("Invalid comment data") comment = Comment( - author= current_user.id, - parent=parent, - street=street, - city=city, - road_segment_id=road_segment_id, - ) + author=current_user.id, + parent=parent, + street=street, + city=city, + road_segment_id=road_segment_id, + ) db.session.add(comment) x = db.session.commit() return Response() + def get_comments(): logging.debug("getting comments by resolution") params = get_location_from_request_values(request.values) comments = get_comments_by_resolution(params) - + if not comments: log_bad_request(request) return abort(http_client.NOT_FOUND) @@ -60,17 +62,15 @@ def get_comments(): return Response(json.dumps(comments_jsons, default=str), mimetype="application/json") + def get_comments_by_resolution(params): location = params["data"] resolution = location["resolution"] - + if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - return ( - db.session.query(Comment) - .filter( - Comment.road_segment_id - == int(location["road_segment_id"]) - )) + return db.session.query(Comment).filter( + Comment.road_segment_id == int(location["road_segment_id"]) + ) elif resolution == BE_CONST.ResolutionCategories.STREET: return ( db.session.query(Comment) @@ -92,5 +92,3 @@ def log_bad_request(request): ) except AttributeError: logging.debug("Bad request:{0}".format(str(request))) - - diff --git a/anyway/views/news_flash/api.py b/anyway/views/news_flash/api.py index 5227c47b1..6fc7888c6 100644 --- a/anyway/views/news_flash/api.py +++ b/anyway/views/news_flash/api.py @@ -37,6 +37,7 @@ DEFAULT_LIMIT_REQ_PARAMETER = 100 DEFAULT_NUMBER_OF_YEARS_AGO = 5 + class NewsFlashQuery(BaseModel): id: Optional[int] @@ -157,7 +158,7 @@ def gen_news_flash_query( road_segment=None, offset=None, limit=None, - last_minutes=None + last_minutes=None, ): query = session.query(NewsFlash) # get all possible sources @@ -408,74 +409,73 @@ def update_news_flash_qualifying(id): def get_downloaded_data(format, years_ago): request_params = get_request_params_from_request_values(request.values) end_time = datetime.datetime.now() - start_time = end_time - datetime.timedelta(days=years_ago*365) + start_time = end_time - datetime.timedelta(days=years_ago * 365) columns = OrderedDict() - columns[AccidentMarkerView.id] = 'מס תאונה' - columns[AccidentMarkerView.provider_code_hebrew] = 'סוג תיק' - columns[AccidentMarkerView.accident_type_hebrew] = 'סוג תאונה' - columns[AccidentMarkerView.accident_severity_hebrew] = 'חומרת תאונה' - columns[AccidentMarkerView.speed_limit_hebrew] = 'מהירות מותרת' - columns[AccidentMarkerView.location_accuracy_hebrew] = 'איכות עיגון' - - columns[AccidentMarkerView.accident_year] = 'שנה' - columns[AccidentMarkerView.accident_month] = 'חודש' - columns[AccidentMarkerView.accident_day] = 'יום' - columns[AccidentMarkerView.accident_timestamp] = 'חתימת זמן' - columns[AccidentMarkerView.day_in_week_hebrew] = 'יום בשבוע' - columns[AccidentMarkerView.day_type_hebrew] = 'סוג יום' - - columns[AccidentMarkerView.road1] = 'מספר דרך- מקום אירוע התאונה' - columns[AccidentMarkerView.road2] = 'מספר דרך 2' + columns[AccidentMarkerView.id] = "מס תאונה" + columns[AccidentMarkerView.provider_code_hebrew] = "סוג תיק" + columns[AccidentMarkerView.accident_type_hebrew] = "סוג תאונה" + columns[AccidentMarkerView.accident_severity_hebrew] = "חומרת תאונה" + columns[AccidentMarkerView.speed_limit_hebrew] = "מהירות מותרת" + columns[AccidentMarkerView.location_accuracy_hebrew] = "איכות עיגון" + + columns[AccidentMarkerView.accident_year] = "שנה" + columns[AccidentMarkerView.accident_month] = "חודש" + columns[AccidentMarkerView.accident_day] = "יום" + columns[AccidentMarkerView.accident_timestamp] = "חתימת זמן" + columns[AccidentMarkerView.day_in_week_hebrew] = "יום בשבוע" + columns[AccidentMarkerView.day_type_hebrew] = "סוג יום" + + columns[AccidentMarkerView.road1] = "מספר דרך- מקום אירוע התאונה" + columns[AccidentMarkerView.road2] = "מספר דרך 2" columns[AccidentMarkerView.km] = 'מספר הק"מ- מקום אירוע התאונה' - columns[AccidentMarkerView.region_hebrew] = 'מחוז-מקום התאונה' - columns[AccidentMarkerView.yishuv_name] = 'שם היישוב בו אירעה התאונה' - columns[AccidentMarkerView.street1_hebrew] = 'רחוב- מקום אירוע התאונה' - columns[AccidentMarkerView.street2_hebrew] = 'רחוב 2' - columns[AccidentMarkerView.house_number] = 'מספר בית- מקום אירוע התאונה' - - columns[AccidentMarkerView.road_type_hebrew] = 'סוג דרך' - columns[AccidentMarkerView.non_urban_intersection_hebrew] = 'צומת בינעירוני' - columns[AccidentMarkerView.road_shape_hebrew] = 'צורת הדרך' - columns[AccidentMarkerView.road_surface_hebrew] = 'מצב פני הכביש' - columns[AccidentMarkerView.road_intactness_hebrew] = 'תקינות הכביש' - columns[AccidentMarkerView.road_width_hebrew] = 'רוחב הכביש' - columns[AccidentMarkerView.one_lane_hebrew] = 'דרך חד מסלולית' - columns[AccidentMarkerView.multi_lane_hebrew] = 'דרך רב מסלולית' - - columns[AccidentMarkerView.road_sign_hebrew] = 'סימון/תמרור' - columns[AccidentMarkerView.road_light_hebrew] = 'תאורה' - columns[AccidentMarkerView.road_control_hebrew] = 'בקרה בצומת' - columns[AccidentMarkerView.traffic_light_hebrew] = 'מרומזר/לא מרומזר' - columns[AccidentMarkerView.weather_hebrew] = 'מזג אוויר' - columns[AccidentMarkerView.day_night_hebrew] = 'יום/לילה' - columns[AccidentMarkerView.road_object_hebrew] = 'עצם-סוג' - - columns[AccidentMarkerView.didnt_cross_hebrew] = 'חצייה-לא חצה' - columns[AccidentMarkerView.cross_mode_hebrew] = 'חצייה-אופן' - columns[AccidentMarkerView.cross_location_hebrew] = 'חצייה-מקום' - columns[AccidentMarkerView.cross_direction_hebrew] = 'חצייה-כיוון' - - columns[AccidentMarkerView.longitude] = 'קו אורך' - columns[AccidentMarkerView.latitude] = 'קו רוחב' - columns[AccidentMarkerView.x] = 'X קואורדינטה' - columns[AccidentMarkerView.y] = 'Y קואורדינטה' - + columns[AccidentMarkerView.region_hebrew] = "מחוז-מקום התאונה" + columns[AccidentMarkerView.yishuv_name] = "שם היישוב בו אירעה התאונה" + columns[AccidentMarkerView.street1_hebrew] = "רחוב- מקום אירוע התאונה" + columns[AccidentMarkerView.street2_hebrew] = "רחוב 2" + columns[AccidentMarkerView.house_number] = "מספר בית- מקום אירוע התאונה" + + columns[AccidentMarkerView.road_type_hebrew] = "סוג דרך" + columns[AccidentMarkerView.non_urban_intersection_hebrew] = "צומת בינעירוני" + columns[AccidentMarkerView.road_shape_hebrew] = "צורת הדרך" + columns[AccidentMarkerView.road_surface_hebrew] = "מצב פני הכביש" + columns[AccidentMarkerView.road_intactness_hebrew] = "תקינות הכביש" + columns[AccidentMarkerView.road_width_hebrew] = "רוחב הכביש" + columns[AccidentMarkerView.one_lane_hebrew] = "דרך חד מסלולית" + columns[AccidentMarkerView.multi_lane_hebrew] = "דרך רב מסלולית" + + columns[AccidentMarkerView.road_sign_hebrew] = "סימון/תמרור" + columns[AccidentMarkerView.road_light_hebrew] = "תאורה" + columns[AccidentMarkerView.road_control_hebrew] = "בקרה בצומת" + columns[AccidentMarkerView.traffic_light_hebrew] = "מרומזר/לא מרומזר" + columns[AccidentMarkerView.weather_hebrew] = "מזג אוויר" + columns[AccidentMarkerView.day_night_hebrew] = "יום/לילה" + columns[AccidentMarkerView.road_object_hebrew] = "עצם-סוג" + + columns[AccidentMarkerView.didnt_cross_hebrew] = "חצייה-לא חצה" + columns[AccidentMarkerView.cross_mode_hebrew] = "חצייה-אופן" + columns[AccidentMarkerView.cross_location_hebrew] = "חצייה-מקום" + columns[AccidentMarkerView.cross_direction_hebrew] = "חצייה-כיוון" + + columns[AccidentMarkerView.longitude] = "קו אורך" + columns[AccidentMarkerView.latitude] = "קו רוחב" + columns[AccidentMarkerView.x] = "X קואורדינטה" + columns[AccidentMarkerView.y] = "Y קואורדינטה" related_accidents = get_accidents_stats( - table_obj=AccidentMarkerView, - columns=columns.keys(), - filters=request_params.location_info, - start_time=start_time, - end_time=end_time - ) - accident_ids = list(related_accidents['id'].values()) + table_obj=AccidentMarkerView, + columns=columns.keys(), + filters=request_params.location_info, + start_time=start_time, + end_time=end_time, + ) + accident_ids = list(related_accidents["id"].values()) accident_severities = get_accidents_stats( - table_obj=InvolvedView, - group_by=("accident_id", "injury_severity_hebrew"), - count="injury_severity_hebrew", - filters={"accident_id": accident_ids} - ) + table_obj=InvolvedView, + group_by=("accident_id", "injury_severity_hebrew"), + count="injury_severity_hebrew", + filters={"accident_id": accident_ids}, + ) severities_hebrew = set() for i, accident_id in enumerate(accident_ids): @@ -490,23 +490,40 @@ def get_downloaded_data(format, years_ago): json_data = json.dumps(related_accidents, default=str) buffer = BytesIO() df = pd.read_json(json_data) - df.rename(columns={key.name.replace('_hebrew', ''): value for key, value in columns.items()}, inplace=True) + df.rename( + columns={key.name.replace("_hebrew", ""): value for key, value in columns.items()}, + inplace=True, + ) - index_to_insert_severities = list(columns.values()).index('מהירות מותרת') - output_column_names = list(columns.values())[:index_to_insert_severities] + list(severities_hebrew) + list(columns.values())[index_to_insert_severities:] + index_to_insert_severities = list(columns.values()).index("מהירות מותרת") + output_column_names = ( + list(columns.values())[:index_to_insert_severities] + + list(severities_hebrew) + + list(columns.values())[index_to_insert_severities:] + ) df = df[output_column_names] - df.rename(columns={'פצוע קל': 'פצוע/ה קל', 'פצוע בינוני': 'פצוע/ה בינוני', 'פצוע קשה': 'פצוע/ה קשה', 'הרוג': 'הרוג/ה'}, inplace=True) + df.rename( + columns={ + "פצוע קל": "פצוע/ה קל", + "פצוע בינוני": "פצוע/ה בינוני", + "פצוע קשה": "פצוע/ה קשה", + "הרוג": "הרוג/ה", + }, + inplace=True, + ) - if format == 'csv': + if format == "csv": df.to_csv(buffer, encoding="utf-8") - mimetype ='text/csv' - file_type = 'csv' - elif format == 'xlsx': + mimetype = "text/csv" + file_type = "csv" + elif format == "xlsx": df.to_excel(buffer, encoding="utf-8") - mimetype='application/vnd.ms-excel' - file_type = 'xlsx' + mimetype = "application/vnd.ms-excel" + file_type = "xlsx" else: - raise Exception(f'File format not supported for downloading : {format}') + raise Exception(f"File format not supported for downloading : {format}") - headers = { 'Content-Disposition': f'attachment; filename=anyway_download_{datetime.datetime.now().strftime("%d_%m_%Y_%H_%M_%S")}.{file_type}' } + headers = { + "Content-Disposition": f'attachment; filename=anyway_download_{datetime.datetime.now().strftime("%d_%m_%Y_%H_%M_%S")}.{file_type}' + } return Response(buffer.getvalue(), mimetype=mimetype, headers=headers) diff --git a/anyway/widgets/all_locations_widgets/__init__.py b/anyway/widgets/all_locations_widgets/__init__.py index 4f55bfa5e..2d7769f7e 100644 --- a/anyway/widgets/all_locations_widgets/__init__.py +++ b/anyway/widgets/all_locations_widgets/__init__.py @@ -5,5 +5,5 @@ most_severe_accidents_table_widget, seriously_injured_killed_in_bicycles_scooter_widget, killed_and_injured_count_per_age_group_stacked_widget, - killed_and_injured_count_per_age_group_widget + killed_and_injured_count_per_age_group_widget, ) diff --git a/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py index 546ad583e..07bd10970 100644 --- a/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py @@ -61,44 +61,46 @@ def get_accident_count_by_severity(location_info, start_time, end_time): def get_transcription(request_params: RequestParams, items: Dict): total_accidents_count = items.get("total_accidents_count") if total_accidents_count == 0: - return '' + return "" severity_light_count = items.get("severity_light_count") if severity_light_count == 0: - severity_light_count_text = '' + severity_light_count_text = "" elif severity_light_count == 1: severity_light_count_text = _("one light") else: - severity_light_count_text = f'{severity_light_count} ' + _("light plural") + severity_light_count_text = f"{severity_light_count} " + _("light plural") severity_severe_count = items.get("severity_severe_count") if severity_severe_count == 0: - severity_severe_count_text = '' + severity_severe_count_text = "" elif severity_severe_count == 1: severity_severe_count_text = _("one severe") else: - severity_severe_count_text = f'{severity_severe_count} '+ _("severe plural") + severity_severe_count_text = f"{severity_severe_count} " + _("severe plural") severity_fatal_count = items.get("severity_fatal_count") if severity_fatal_count == 0: - severity_fatal_count_text = '' + severity_fatal_count_text = "" elif severity_fatal_count == 1: severity_fatal_count_text = _("one fatal") else: - severity_fatal_count_text = f'{severity_fatal_count} ' + _("fatal plural") + severity_fatal_count_text = f"{severity_fatal_count} " + _("fatal plural") if request_params.resolution == BE_CONST.ResolutionCategories.STREET: text = "{in_yishuv_keyword} {yishuv_name} {in_street_keyword} {street_name} ".format( in_yishuv_keyword=_("in yishuv"), - yishuv_name=_(request_params.location_info.get('yishuv_name')), + yishuv_name=_(request_params.location_info.get("yishuv_name")), in_street_keyword=_("in street"), - street_name=_(request_params.location_info.get('street1_hebrew')), + street_name=_(request_params.location_info.get("street1_hebrew")), ) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: text = "{in_road_keyword} {road_num} {in_segment_keyword} {segment_name} ".format( in_road_keyword=_("in road"), - road_num=request_params.location_info.get('road1'), + road_num=request_params.location_info.get("road1"), in_segment_keyword=_("in segment"), - segment_name=_(request_params.location_info.get('road_segment_name')), + segment_name=_(request_params.location_info.get("road_segment_name")), ) else: - raise Exception(f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}") + raise Exception( + f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}" + ) text += "{between_years_keyword} {start_year} - {end_year}, {separator_keyword} {incidents_num} {incident_keyword}, {out_of_them_keywoard} ".format( between_years_keyword=_("between the years"), start_year=request_params.start_time.year, @@ -108,24 +110,32 @@ def get_transcription(request_params: RequestParams, items: Dict): incident_keyword=_("accidents"), out_of_them_keywoard=_("out of them"), ) - text += join_strings([severity_fatal_count_text, severity_severe_count_text, severity_light_count_text], - sep_a=" ,", - sep_b=_(" and ")) + text += join_strings( + [severity_fatal_count_text, severity_severe_count_text, severity_light_count_text], + sep_a=" ,", + sep_b=_(" and "), + ) return text @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - if request_params.resolution in (BE_CONST.ResolutionCategories.SUBURBAN_ROAD, - BE_CONST.ResolutionCategories.SUBURBAN_JUNCTION): + if request_params.resolution in ( + BE_CONST.ResolutionCategories.SUBURBAN_ROAD, + BE_CONST.ResolutionCategories.SUBURBAN_JUNCTION, + ): is_segment = request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD items["data"]["text"] = { "title": _("Number of accidents by severity"), - "subtitle": _(request_params.location_info['road_segment_name']) if is_segment else - _(request_params.location_info['non_urban_intersection_hebrew']), - "transcription": AccidentCountBySeverityWidget.get_transcription(request_params=request_params, - items=items["data"]["items"]) + "subtitle": _(request_params.location_info["road_segment_name"]) + if is_segment + else _(request_params.location_info["non_urban_intersection_hebrew"]), + "transcription": AccidentCountBySeverityWidget.get_transcription( + request_params=request_params, items=items["data"]["items"] + ), } - items["meta"]["information"] = "{incident_description}{incident_location} {incident_time}.".format( + items["meta"][ + "information" + ] = "{incident_description}{incident_location} {incident_time}.".format( incident_description=_("Fatal, severe and light accidents count in "), incident_location=_("segment") if is_segment else _("junction"), incident_time=_("in the selected time"), @@ -141,11 +151,22 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: incidents_num=num_accidents, incident_keyword=_("accidents"), ) - subtitle = _("{street_name}, {yishuv_name}".format(street_name=request_params.location_info["street1_hebrew"], - yishuv_name=request_params.location_info["yishuv_name"])) - items["data"]["text"] = {"title": s, "subtitle": subtitle, "transcription": AccidentCountBySeverityWidget.get_transcription(request_params=request_params, - items=items["data"]["items"])} - items["meta"]["information"] = "{incident_description}{incident_location} {incident_time}.".format( + subtitle = _( + "{street_name}, {yishuv_name}".format( + street_name=request_params.location_info["street1_hebrew"], + yishuv_name=request_params.location_info["yishuv_name"], + ) + ) + items["data"]["text"] = { + "title": s, + "subtitle": subtitle, + "transcription": AccidentCountBySeverityWidget.get_transcription( + request_params=request_params, items=items["data"]["items"] + ), + } + items["meta"][ + "information" + ] = "{incident_description}{incident_location} {incident_time}.".format( incident_description=_("Fatal, severe and light accidents count in "), incident_location=_("street"), incident_time=_("in the selected time"), @@ -170,4 +191,4 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: _("out of them") _("accidents") _(" and ") -_("in the selected time") \ No newline at end of file +_("in the selected time") diff --git a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py index cdccd6735..d9ef739a9 100644 --- a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py @@ -24,32 +24,32 @@ def generate_items(self) -> None: self.request_params.resolution, self.request_params.location_info, self.request_params.start_time, - self.request_params.end_time + self.request_params.end_time, ) @staticmethod def get_injured_count_by_severity(resolution, location_info, start_time, end_time): filters = {} filters["injury_severity"] = [ - InjurySeverity.KILLED.value, - InjurySeverity.SEVERE_INJURED.value, - InjurySeverity.LIGHT_INJURED.value, - ] - - if resolution == BE_CONST.ResolutionCategories.STREET: - filters["involve_yishuv_name"] = location_info.get('yishuv_name') - filters["street1_hebrew"] = location_info.get('street1_hebrew') + InjurySeverity.KILLED.value, + InjurySeverity.SEVERE_INJURED.value, + InjurySeverity.LIGHT_INJURED.value, + ] + + if resolution == BE_CONST.ResolutionCategories.STREET: + filters["involve_yishuv_name"] = location_info.get("yishuv_name") + filters["street1_hebrew"] = location_info.get("street1_hebrew") elif resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - filters["road1"] = location_info.get('road1') - filters["road_segment_name"] = location_info.get('road_segment_name') - + filters["road1"] = location_info.get("road1") + filters["road_segment_name"] = location_info.get("road_segment_name") + count_by_severity = get_accidents_stats( - table_obj = InvolvedMarkerView, - filters = filters, - group_by = "injury_severity", - count = "injury_severity", - start_time = start_time, - end_time = end_time, + table_obj=InvolvedMarkerView, + filters=filters, + group_by="injury_severity", + count="injury_severity", + start_time=start_time, + end_time=end_time, ) found_severities = [d["injury_severity"] for d in count_by_severity] items = {} @@ -73,49 +73,50 @@ def get_injured_count_by_severity(resolution, location_info, start_time, end_tim items["total_injured_count"] = total_injured_count return items - @staticmethod def get_transcription(request_params: RequestParams, items: Dict): total_injured_count = items.get("total_injured_count") if total_injured_count == 0: - return '' + return "" severity_light_count = items.get("light_injured_count") if severity_light_count == 0: - severity_light_count_text = '' + severity_light_count_text = "" elif severity_light_count == 1: severity_light_count_text = _("one light injured") else: - severity_light_count_text = f'{severity_light_count} ' + _("light injured plural") + severity_light_count_text = f"{severity_light_count} " + _("light injured plural") severity_severe_count = items.get("severe_injured_count") if severity_severe_count == 0: - severity_severe_count_text = '' + severity_severe_count_text = "" elif severity_severe_count == 1: severity_severe_count_text = _("one severe injured") else: - severity_severe_count_text = f'{severity_severe_count} '+ _("severe injured plural") + severity_severe_count_text = f"{severity_severe_count} " + _("severe injured plural") killed_count = items.get("killed_count") if killed_count == 0: - killed_count_text = '' + killed_count_text = "" elif killed_count == 1: killed_count_text = _("one killed") else: - killed_count_text = f'{killed_count} ' + _("killed plural") + killed_count_text = f"{killed_count} " + _("killed plural") if request_params.resolution == BE_CONST.ResolutionCategories.STREET: text = "{in_yishuv_keyword} {yishuv_name} {in_street_keyword} {street_name} ".format( in_yishuv_keyword=_("in yishuv"), - yishuv_name=_(request_params.location_info.get('yishuv_name')), + yishuv_name=_(request_params.location_info.get("yishuv_name")), in_street_keyword=_("in street"), - street_name=_(request_params.location_info.get('street1_hebrew')), + street_name=_(request_params.location_info.get("street1_hebrew")), ) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: text = "{in_road_keyword} {road_num} {in_segment_keyword} {segment_name} ".format( in_road_keyword=_("in road"), - road_num=request_params.location_info.get('road1'), + road_num=request_params.location_info.get("road1"), in_segment_keyword=_("in segment"), - segment_name=_(request_params.location_info.get('road_segment_name')), + segment_name=_(request_params.location_info.get("road_segment_name")), ) else: - raise Exception(f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}") + raise Exception( + f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}" + ) text += "{between_years_keyword} {start_year} - {end_year}, {injured_killed_keyword} {injured_num} {people_phrase}, {out_of_them_keywoard} ".format( between_years_keyword=_("between the years"), start_year=request_params.start_time.year, @@ -125,12 +126,13 @@ def get_transcription(request_params: RequestParams, items: Dict): people_phrase=_("people from car accidents"), out_of_them_keywoard=_("out of them"), ) - text += join_strings([killed_count_text, severity_severe_count_text, severity_light_count_text], - sep_a=" ,", - sep_b=_(" and ")) + text += join_strings( + [killed_count_text, severity_severe_count_text, severity_light_count_text], + sep_a=" ,", + sep_b=_(" and "), + ) return text - @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: @@ -138,11 +140,11 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Number of Injuries in accidents by severity"), "subtitle": _(subtitle), - "transcription": InjuredCountBySeverityWidget.get_transcription(request_params=request_params, - items=items["data"]["items"]) + "transcription": InjuredCountBySeverityWidget.get_transcription( + request_params=request_params, items=items["data"]["items"] + ), } return items - _("injured/killed") diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py index ef3e406ec..7ca1716cc 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py @@ -12,7 +12,11 @@ from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget from anyway.widgets.widget import register -from anyway.widgets.widget_utils import add_empty_keys_to_gen_two_level_dict, gen_entity_labels, get_location_text +from anyway.widgets.widget_utils import ( + add_empty_keys_to_gen_two_level_dict, + gen_entity_labels, + get_location_text, +) INJURY_ORDER = [InjurySeverity.LIGHT_INJURED, InjurySeverity.SEVERE_INJURED, InjurySeverity.KILLED] MAX_AGE = 200 diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py index 01b06bfc7..b255d593f 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py @@ -12,6 +12,7 @@ from anyway.widgets.widget import register from anyway.widgets.widget_utils import get_location_text + @register class KilledInjuredCountPerAgeGroupWidget(AllLocationsWidget): name: str = "killed_and_injured_count_per_age_group" @@ -37,8 +38,5 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: location_text = get_location_text(request_params) - items["data"]["text"] = { - "title": _("Injury per age group"), - "subtitle": _(location_text) - } + items["data"]["text"] = {"title": _("Injury per age group"), "subtitle": _(location_text)} return items diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py index 90c7590fe..00ce478b9 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py @@ -28,19 +28,19 @@ class KilledAndInjuredCountPerAgeGroupWidgetUtils: def filter_and_group_injured_count_per_age_group( request_params: RequestParams, ) -> Dict[str, Dict[int, int]]: - + start_time = request_params.start_time end_time = request_params.end_time if request_params.resolution == BE_CONST.ResolutionCategories.STREET: - involve_yishuv_name = request_params.location_info['yishuv_name'] - street1_hebrew = request_params.location_info['street1_hebrew'] + involve_yishuv_name = request_params.location_info["yishuv_name"] + street1_hebrew = request_params.location_info["street1_hebrew"] cache_key = (involve_yishuv_name, street1_hebrew, start_time, end_time) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: road_number = request_params.location_info["road1"] road_segment = request_params.location_info["road_segment_name"] cache_key = (road_number, road_segment, start_time, end_time) - + if cache_dict.get(cache_key): return cache_dict.get(cache_key) @@ -101,9 +101,17 @@ def create_query_for_killed_and_injured_count_per_age_group( end_time, start_time, location_info, resolution ) -> BaseQuery: if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - location_filter = ((InvolvedMarkerView.road1 == location_info["road1"]) | (InvolvedMarkerView.road2 == location_info["road1"])) & (InvolvedMarkerView.road_segment_name == location_info["road_segment_name"]) + location_filter = ( + (InvolvedMarkerView.road1 == location_info["road1"]) + | (InvolvedMarkerView.road2 == location_info["road1"]) + ) & (InvolvedMarkerView.road_segment_name == location_info["road_segment_name"]) elif resolution == BE_CONST.ResolutionCategories.STREET: - location_filter = (InvolvedMarkerView.involve_yishuv_name == location_info["yishuv_name"]) & ((InvolvedMarkerView.street1_hebrew == location_info["street1_hebrew"]) | (InvolvedMarkerView.street2_hebrew == location_info["street1_hebrew"])) + location_filter = ( + InvolvedMarkerView.involve_yishuv_name == location_info["yishuv_name"] + ) & ( + (InvolvedMarkerView.street1_hebrew == location_info["street1_hebrew"]) + | (InvolvedMarkerView.street2_hebrew == location_info["street1_hebrew"]) + ) query = ( db.session.query(InvolvedMarkerView) diff --git a/anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py b/anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py index b0d9b3e6d..950c20e24 100644 --- a/anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py +++ b/anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py @@ -44,12 +44,22 @@ def get_most_severe_accidents_table_title( location_info: dict, resolution: BE_CONST.ResolutionCategories ): if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - return "Most severe accidents in segment", segment_dictionary[location_info["road_segment_name"]] + return ( + "Most severe accidents in segment", + segment_dictionary[location_info["road_segment_name"]], + ) elif resolution == BE_CONST.ResolutionCategories.SUBURBAN_JUNCTION: - return "Severe accidents in suburban junction", f" {location_info['non_urban_intersection_hebrew']}" + return ( + "Severe accidents in suburban junction", + f" {location_info['non_urban_intersection_hebrew']}", + ) elif resolution == BE_CONST.ResolutionCategories.STREET: in_str = _("in") - return "Severe accidents in street", f" {location_info['street1_hebrew']} {in_str}{location_info['yishuv_name']}" + return ( + "Severe accidents in street", + f" {location_info['street1_hebrew']} {in_str}{location_info['yishuv_name']}", + ) + # count of dead and severely injured def get_casualties_count_in_accident(accident_id, provider_code, injury_severity, accident_year): @@ -149,11 +159,10 @@ def prepare_table( ).get_label() return accidents - @staticmethod def get_transcription(request_params: RequestParams, items: Dict): if len(items) == 0: - return '' + return "" elif len(items) == 1: text = _("latest severe accident took place") else: @@ -162,40 +171,45 @@ def get_transcription(request_params: RequestParams, items: Dict): if request_params.resolution == BE_CONST.ResolutionCategories.STREET: text += " {in_yishuv_keyword} {yishuv_name} {in_street_keyword} {street_name} ".format( in_yishuv_keyword=_("in yishuv"), - yishuv_name=_(request_params.location_info.get('yishuv_name')), + yishuv_name=_(request_params.location_info.get("yishuv_name")), in_street_keyword=_("in street"), - street_name=_(request_params.location_info.get('street1_hebrew')), + street_name=_(request_params.location_info.get("street1_hebrew")), ) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: text += " {in_road_keyword} {road_num} {in_segment_keyword} {segment_name} ".format( in_road_keyword=_("in road"), - road_num=request_params.location_info.get('road1'), + road_num=request_params.location_info.get("road1"), in_segment_keyword=_("in segment"), - segment_name=_(request_params.location_info.get('road_segment_name')), + segment_name=_(request_params.location_info.get("road_segment_name")), ) else: - raise Exception(f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}") + raise Exception( + f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}" + ) text += "{between_years_keyword} {start_year} - {end_year}:\n".format( between_years_keyword=_("between the years"), start_year=request_params.start_time.year, end_year=request_params.end_time.year, ) logging.debug(items) - text += '\n'.join(['{in_date_keyword} {date} {in_hour_keyword} {hour} {accident_occured_text} {accident_type_keyword} {type}, {injured_count_keyword}: {injured_count}.'.format( - in_date_keyword=_("in date"), - date=item.get("date"), - in_hour_keyword=_("in hour"), - hour=item.get("hour"), - accident_occured_text=_("occured accident"), - accident_type_keyword=_("of type"), - type=_(item.get("type")), - injured_count_keyword=_("injured"), - injured_count=item.get("injured_count") - ) - for item in items]) + text += "\n".join( + [ + "{in_date_keyword} {date} {in_hour_keyword} {hour} {accident_occured_text} {accident_type_keyword} {type}, {injured_count_keyword}: {injured_count}.".format( + in_date_keyword=_("in date"), + date=item.get("date"), + in_hour_keyword=_("in hour"), + hour=item.get("hour"), + accident_occured_text=_("occured accident"), + accident_type_keyword=_("of type"), + type=_(item.get("type")), + injured_count_keyword=_("injured"), + injured_count=item.get("injured_count"), + ) + for item in items + ] + ) return text - @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: if request_params.lang != "en": @@ -207,13 +221,15 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: logging.exception( f"MostSevereAccidentsTableWidget.localize_items: Exception while translating {item}." ) - title, subtitle = get_most_severe_accidents_table_title(request_params.location_info, - request_params.resolution) + title, subtitle = get_most_severe_accidents_table_title( + request_params.location_info, request_params.resolution + ) items["data"]["text"] = { "title": _(title), "subtitle": _(subtitle), - "transcription": MostSevereAccidentsTableWidget.get_transcription(request_params=request_params, - items=items["data"]["items"]) + "transcription": MostSevereAccidentsTableWidget.get_transcription( + request_params=request_params, items=items["data"]["items"] + ), } return items diff --git a/anyway/widgets/all_locations_widgets/most_severe_accidents_widget.py b/anyway/widgets/all_locations_widgets/most_severe_accidents_widget.py index fa18cc83a..f25e2e61c 100644 --- a/anyway/widgets/all_locations_widgets/most_severe_accidents_widget.py +++ b/anyway/widgets/all_locations_widgets/most_severe_accidents_widget.py @@ -70,11 +70,9 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: f"MostSevereAccidentsWidget.localize_items: Exception while translating {item}." ) title, subtitle = get_most_severe_accidents_table_title( - request_params.location_info, request_params.resolution) - items["data"]["text"] = { - "title": _(title), - "subtitle": _(subtitle) - } + request_params.location_info, request_params.resolution + ) + items["data"]["text"] = {"title": _(title), "subtitle": _(subtitle)} return items diff --git a/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py b/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py index a120a207e..2ea07c8fe 100644 --- a/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py +++ b/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py @@ -33,34 +33,43 @@ def generate_items(self) -> None: @staticmethod def get_seriously_injured_killed_in_bicycles_scooter( - start_year: int, - end_year: int, - location_info: LocationInfo + start_year: int, end_year: int, location_info: LocationInfo ): - res = get_involved_counts(start_year, end_year, - SeriouslyInjuredKilledInBicyclesScooterWidget.severities, - SeriouslyInjuredKilledInBicyclesScooterWidget.vehicle_types, - location_info) + res = get_involved_counts( + start_year, + end_year, + SeriouslyInjuredKilledInBicyclesScooterWidget.severities, + SeriouslyInjuredKilledInBicyclesScooterWidget.vehicle_types, + location_info, + ) return res @staticmethod def create_location_description(location_info: LocationInfo, location_text: str) -> str: - return _("in") + location_info[Constants.YISHUV_NAME] \ - if Constants.YISHUV_NAME in location_info \ + return ( + _("in") + location_info[Constants.YISHUV_NAME] + if Constants.YISHUV_NAME in location_info else location_text + ) @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - subtitle = _(SeriouslyInjuredKilledInBicyclesScooterWidget.create_location_description( - request_params.location_info, - request_params.location_text)) - items["data"]["text"] = {"title": _("Number of severely injured or killed in bike, e-bike, or scooter accidents"), - "subtitle": subtitle} + subtitle = _( + SeriouslyInjuredKilledInBicyclesScooterWidget.create_location_description( + request_params.location_info, request_params.location_text + ) + ) + items["data"]["text"] = { + "title": _( + "Number of severely injured or killed in bike, e-bike, or scooter accidents" + ), + "subtitle": subtitle, + } return items def is_included(self) -> bool: num_of_years_in_query = len(self.items) years_with_accidents = [item["label_key"] for item in self.items if item["value"] > 0] num_of_years_with_accidents = len(years_with_accidents) - return num_of_years_with_accidents >= half_rounded_up(num_of_years_in_query) \ No newline at end of file + return num_of_years_with_accidents >= half_rounded_up(num_of_years_in_query) diff --git a/anyway/widgets/no_location_widgets/__init__.py b/anyway/widgets/no_location_widgets/__init__.py index a3b81e09e..41d407810 100644 --- a/anyway/widgets/no_location_widgets/__init__.py +++ b/anyway/widgets/no_location_widgets/__init__.py @@ -1,3 +1 @@ -from . import ( - vision_zero_bike_widget -) +from . import vision_zero_bike_widget diff --git a/anyway/widgets/no_location_widgets/vision_zero_bike_widget.py b/anyway/widgets/no_location_widgets/vision_zero_bike_widget.py index 1f8f8abc9..c4a64faae 100644 --- a/anyway/widgets/no_location_widgets/vision_zero_bike_widget.py +++ b/anyway/widgets/no_location_widgets/vision_zero_bike_widget.py @@ -14,7 +14,9 @@ class VisionZeroBikeWidget(Widget): def __init__(self, request_params: RequestParams): if request_params.news_flash_description is None: - logging.error(f"VisionZeroBikeWidget initialized with missing description field : {request_params}") + logging.error( + f"VisionZeroBikeWidget initialized with missing description field : {request_params}" + ) super().__init__(request_params) self.information = _("Main principles in zero vision's bike transportation development") self.rank = 33 @@ -22,7 +24,6 @@ def __init__(self, request_params: RequestParams): def generate_items(self) -> None: self.items = {"image_src": "vision_zero_bike"} - # noinspection PyUnboundLocalVariable def is_included(self) -> bool: if self.request_params.news_flash_description: diff --git a/anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py b/anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py index ef1f7f8b4..4c10db6e4 100644 --- a/anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py @@ -142,7 +142,7 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: base_title = _("Comparing vehicle type in accidents relative to national average") items["data"]["text"] = { "title": base_title, - "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]) + "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]), } items["meta"]["information"] = _( "Vehicle accidents by type in specific segment, sorted by segment, compared to the national average" diff --git a/anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py b/anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py index 50b28c883..681dc8030 100644 --- a/anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py @@ -28,6 +28,6 @@ def generate_items(self) -> None: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Number of accidents by hour"), - "subtitle": _(request_params.location_info['road_segment_name']) + "subtitle": _(request_params.location_info["road_segment_name"]), } return items diff --git a/anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py b/anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py index 4f4bca83f..a938fadc5 100644 --- a/anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py @@ -30,6 +30,6 @@ def generate_items(self) -> None: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Number of accidents by road light"), - "subtitle": _(request_params.location_info['road_segment_name']) + "subtitle": _(request_params.location_info["road_segment_name"]), } return items diff --git a/anyway/widgets/road_segment_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py b/anyway/widgets/road_segment_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py index 7de8f07a7..b687b02b2 100644 --- a/anyway/widgets/road_segment_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py @@ -41,6 +41,6 @@ def accidents_count_pedestrians_per_vehicle_street_vs_all_mock_data(): # Tempor def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": "Number of pedestrian accidents by type of hitting vehicle compared to urban accidents across the country", - "subtitle": "Ben Yehuda street in Tel Aviv" + "subtitle": "Ben Yehuda street in Tel Aviv", } return items diff --git a/anyway/widgets/road_segment_widgets/accident_severity_by_cross_location_widget.py b/anyway/widgets/road_segment_widgets/accident_severity_by_cross_location_widget.py index 0e0ba815c..c99f1f8b0 100644 --- a/anyway/widgets/road_segment_widgets/accident_severity_by_cross_location_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_severity_by_cross_location_widget.py @@ -50,6 +50,6 @@ def injury_severity_by_cross_location_mock_data(): # Temporary for Frontend def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": "Number of pedestrian accidents by crossing location", - "subtitle": "Ben Yehuda street in Tel Aviv" + "subtitle": "Ben Yehuda street in Tel Aviv", } return items diff --git a/anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py b/anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py index b355f6c8b..dd25a3cef 100644 --- a/anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py +++ b/anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py @@ -51,6 +51,6 @@ def get_accidents_heat_map(filters, start_time, end_time): def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Fatal and severe accidents heat map"), - "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]) + "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]), } return items diff --git a/anyway/widgets/road_segment_widgets/front_to_side_accidents_by_severity.py b/anyway/widgets/road_segment_widgets/front_to_side_accidents_by_severity.py index 280af910a..810a9ab7d 100644 --- a/anyway/widgets/road_segment_widgets/front_to_side_accidents_by_severity.py +++ b/anyway/widgets/road_segment_widgets/front_to_side_accidents_by_severity.py @@ -61,11 +61,7 @@ def _clac_percentage(self, result: List[Dict[str, Any]]) -> List[Dict]: DESC: FRONT_SIDE_DESC, COUNT: row[FRONT_SIDE_ACCIDENTS_LABEL], }, - { - SEVERITY: severity_text, - DESC: OTHERS_DESC, - COUNT: row[OTHER_ACCIDENTS_LABEL], - }, + {SEVERITY: severity_text, DESC: OTHERS_DESC, COUNT: row[OTHER_ACCIDENTS_LABEL]}, ] ) diff --git a/anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py b/anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py index 133f5fa9e..191659c37 100644 --- a/anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py +++ b/anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py @@ -53,7 +53,7 @@ def generate_items(self) -> None: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Number of injured in accidents, per year, split by severity"), - "subtitle": _(segment_dictionary[request_params.location_info['road_segment_name']]), + "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]), "labels_map": gen_entity_labels(InjurySeverity), } return items diff --git a/anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py b/anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py index 55d872a32..4dd438f04 100644 --- a/anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py +++ b/anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py @@ -30,21 +30,21 @@ def __init__(self, request_params: RequestParams): super().__init__(request_params) self.rank = 20 self.road_number: str = request_params.location_info["road1"] - self.information = ( - "Percentage of serious and fatal motorcycle accidents in the selected section compared to the average percentage of accidents in other road sections throughout the country" - ) + self.information = "Percentage of serious and fatal motorcycle accidents in the selected section compared to the average percentage of accidents in other road sections throughout the country" def generate_items(self) -> None: # noinspection PyUnresolvedReferences res = MotorcycleAccidentsVsAllAccidentsWidget.motorcycle_accidents_vs_all_accidents( self.request_params.start_time, self.request_params.end_time, self.road_number ) - self.items, self.counter_road_motorcycle, self.motorcycle_road_percentage, self.motorcycle_all_roads_percentage = res + self.items, self.counter_road_motorcycle, self.motorcycle_road_percentage, self.motorcycle_all_roads_percentage = ( + res + ) @staticmethod def motorcycle_accidents_vs_all_accidents( start_time: datetime.date, end_time: datetime.date, road_number: str - ) -> Tuple: + ) -> Tuple: location_label = "location" case_location = case( [ @@ -118,7 +118,9 @@ def motorcycle_accidents_vs_all_accidents( sum_road = 1 # prevent division by zero sum_all = counter_other_other + counter_other_motorcycle + sum_road motorcycle_road_percentage = counter_road_motorcycle / sum_road - motorcycle_all_roads_percentage = (counter_other_motorcycle + counter_road_motorcycle) / sum_all + motorcycle_all_roads_percentage = ( + counter_other_motorcycle + counter_road_motorcycle + ) / sum_all items = [ { "label_key": location_road, @@ -130,10 +132,7 @@ def motorcycle_accidents_vs_all_accidents( { "label_key": location_all_label, "series": [ - { - "label_key": vehicle_motorcycle, - "value": motorcycle_all_roads_percentage, - }, + {"label_key": vehicle_motorcycle, "value": motorcycle_all_roads_percentage}, { "label_key": vehicle_other, "value": (counter_other_other + counter_road_other) / sum_all, @@ -141,7 +140,12 @@ def motorcycle_accidents_vs_all_accidents( ], }, ] - return items, counter_road_motorcycle, motorcycle_road_percentage, motorcycle_all_roads_percentage + return ( + items, + counter_road_motorcycle, + motorcycle_road_percentage, + motorcycle_all_roads_percentage, + ) @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: @@ -177,7 +181,13 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: """ # noinspection PyUnboundLocalVariable def is_included(self) -> bool: - return self.counter_road_motorcycle >= 3 and self.motorcycle_road_percentage >= 2*self.motorcycle_all_roads_percentage + return ( + self.counter_road_motorcycle >= 3 + and self.motorcycle_road_percentage >= 2 * self.motorcycle_all_roads_percentage + ) + _("road") -_("Percentage of serious and fatal motorcycle accidents in the selected section compared to the average percentage of accidents in other road sections throughout the country") +_( + "Percentage of serious and fatal motorcycle accidents in the selected section compared to the average percentage of accidents in other road sections throughout the country" +) diff --git a/anyway/widgets/road_segment_widgets/pedestrian_injured_in_junctions_widget.py b/anyway/widgets/road_segment_widgets/pedestrian_injured_in_junctions_widget.py index 4b37b11aa..6810b3405 100644 --- a/anyway/widgets/road_segment_widgets/pedestrian_injured_in_junctions_widget.py +++ b/anyway/widgets/road_segment_widgets/pedestrian_injured_in_junctions_widget.py @@ -30,6 +30,6 @@ def pedestrian_injured_in_junctions_mock_data(): # Temporary for Frontend def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": "Number of pedestrian accidents on junctions", - "subtitle": "Ben Yehuda street in Tel Aviv" + "subtitle": "Ben Yehuda street in Tel Aviv", } return items diff --git a/anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py b/anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py index 597233a57..706847c20 100644 --- a/anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py +++ b/anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py @@ -70,7 +70,7 @@ def get_crosswalk(road, start_time, end_time) -> Dict[str, Any]: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Pedestrian injury comparison"), - "subtitle": _(request_params.location_info["road_segment_name"]) + "subtitle": _(request_params.location_info["road_segment_name"]), } return items diff --git a/anyway/widgets/road_segment_widgets/top_road_segments_accidents_per_km_widget.py b/anyway/widgets/road_segment_widgets/top_road_segments_accidents_per_km_widget.py index 3bc615039..427366971 100644 --- a/anyway/widgets/road_segment_widgets/top_road_segments_accidents_per_km_widget.py +++ b/anyway/widgets/road_segment_widgets/top_road_segments_accidents_per_km_widget.py @@ -86,7 +86,7 @@ def is_included(self) -> bool: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Segments with most accidents per Km"), - "subtitle": _(request_params.location_info['road1']) + "subtitle": _(request_params.location_info["road1"]), } return items diff --git a/anyway/widgets/urban_widgets/__init__.py b/anyway/widgets/urban_widgets/__init__.py index 10a322a08..c2ef30cb2 100644 --- a/anyway/widgets/urban_widgets/__init__.py +++ b/anyway/widgets/urban_widgets/__init__.py @@ -4,5 +4,5 @@ severe_fatal_count_by_vehicle_by_year_widget, small_motor_severe_fatal_count_by_year_widget, urban_crosswalk_widget, - vision_zero_10_50_90_widget + vision_zero_10_50_90_widget, ) 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 645b8cbce..83a552fb1 100644 --- a/anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py +++ b/anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py @@ -56,7 +56,9 @@ def generate_items(self) -> None: if not self.validate_parameters(yishuv_name, street1_hebrew): # TODO: this will fail since there is no news_flash_obj in request_params - logging.exception(f"Could not validate parameters yishuv_name + street1_hebrew in widget : {self.name}") + logging.exception( + f"Could not validate parameters yishuv_name + street1_hebrew in widget : {self.name}" + ) return None query = ( 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 866c436d5..1f964f634 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 @@ -96,7 +96,7 @@ def separate_data(yishuv, start_time, end_time) -> Dict[str, Any]: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Severe or fatal accidents on bikes, e-bikes, or scooters"), - "subtitle": _(request_params.location_info["yishuv_name"]) + "subtitle": _(request_params.location_info["yishuv_name"]), } return items 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 f6834cb0a..060beb8fa 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 @@ -58,6 +58,6 @@ def is_included(self) -> bool: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Severe or fatal accidents on bikes, e-bikes, or scooters"), - "subtitle": _(request_params.location_info["yishuv_name"]) + "subtitle": _(request_params.location_info["yishuv_name"]), } return items diff --git a/anyway/widgets/urban_widgets/urban_crosswalk_widget.py b/anyway/widgets/urban_widgets/urban_crosswalk_widget.py index 0d6eb6973..52b0ca83d 100644 --- a/anyway/widgets/urban_widgets/urban_crosswalk_widget.py +++ b/anyway/widgets/urban_widgets/urban_crosswalk_widget.py @@ -73,7 +73,7 @@ def get_crosswalk(yishuv, street, start_time, end_time) -> Dict[str, Any]: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Pedestrian injury comparison"), - "subtitle": _(request_params.location_info["street1_hebrew"]) + "subtitle": _(request_params.location_info["street1_hebrew"]), } return items diff --git a/anyway/widgets/urban_widgets/vision_zero_10_50_90_widget.py b/anyway/widgets/urban_widgets/vision_zero_10_50_90_widget.py index ad7cda59f..063d6c419 100644 --- a/anyway/widgets/urban_widgets/vision_zero_10_50_90_widget.py +++ b/anyway/widgets/urban_widgets/vision_zero_10_50_90_widget.py @@ -15,21 +15,19 @@ def __init__(self, request_params: RequestParams): self.rank = 38 self.information = "A speed limit solution on an urban road" - def generate_items(self) -> None: self.items = {"image_src": "vision_zero_10_50_90"} - def is_included(self) -> bool: for pedestrian_adjective in ["הולך רגל", "הולכת רגל", "הולכי רגל", "הולכות רגל"]: - if self.request_params.news_flash_description and pedestrian_adjective in self.request_params.news_flash_description: + if ( + self.request_params.news_flash_description + and pedestrian_adjective in self.request_params.news_flash_description + ): return True return False - @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - items["data"]["text"] = { - "title": _("A speed limit solution on an urban road") - } + items["data"]["text"] = {"title": _("A speed limit solution on an urban road")} return items diff --git a/anyway/widgets/widget_utils.py b/anyway/widgets/widget_utils.py index e81be10f6..20f36c6cc 100644 --- a/anyway/widgets/widget_utils.py +++ b/anyway/widgets/widget_utils.py @@ -53,10 +53,7 @@ def get_accidents_stats( end_time=None, ): filters = filters or {} - provider_code_filters = [ - BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, - BE_CONST.CBS_ACCIDENT_TYPE_3_CODE, - ] + provider_code_filters = [BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, BE_CONST.CBS_ACCIDENT_TYPE_3_CODE] filters["provider_code"] = filters.get("provider_code", provider_code_filters) # get stats @@ -78,8 +75,7 @@ def get_accidents_stats( else: query = query.group_by(group_by) query = query.with_entities( - group_by, - func.count(count) if not cnt_distinct else func.count(distinct(count)), + group_by, func.count(count) if not cnt_distinct else func.count(distinct(count)) ) df = pd.read_sql_query(query.statement, query.session.bind) df.rename(columns={"count_1": "count"}, inplace=True) # pylint: disable=no-member @@ -103,10 +99,7 @@ def retro_dictify(indexable) -> Dict[Any, Dict[Any, Any]]: def add_empty_keys_to_gen_two_level_dict( - d, - level_1_values: List[Any], - level_2_values: List[Any], - default_level_3_value: int = 0, + d, level_1_values: List[Any], level_2_values: List[Any], default_level_3_value: int = 0 ) -> Dict[Any, Dict[Any, int]]: for v1 in level_1_values: if v1 not in d: @@ -245,9 +238,10 @@ def newsflash_has_location(newsflash: NewsFlash): and newsflash.road_segment_name ) or (resolution == BE_CONST.ResolutionCategories.STREET.value and newsflash.street1_hebrew) -def get_location_text(request_params : RequestParams) -> str : - in_str = _("in") - if request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - return f'{_("in segment")} {_(request_params.location_info["road_segment_name"])}' - elif request_params.resolution == BE_CONST.ResolutionCategories.STREET: - return f'{_("in street")} {request_params.location_info["street1_hebrew"]} {in_str}{request_params.location_info["yishuv_name"]}' + +def get_location_text(request_params: RequestParams) -> str: + in_str = _("in") + if request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + return f'{_("in segment")} {_(request_params.location_info["road_segment_name"])}' + elif request_params.resolution == BE_CONST.ResolutionCategories.STREET: + return f'{_("in street")} {request_params.location_info["street1_hebrew"]} {in_str}{request_params.location_info["yishuv_name"]}' From 695390ba900556215544d08784194b1fa217360d Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 17:39:49 +0200 Subject: [PATCH 08/12] remove unused imprted datetime --- .../killed_and_injured_count_per_age_group_widget_utils.py | 1 - 1 file changed, 1 deletion(-) diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py index 00ce478b9..aea2c36a9 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py @@ -1,5 +1,4 @@ from collections import defaultdict, OrderedDict -from datetime import datetime from typing import Dict, Tuple, Callable from flask_sqlalchemy import BaseQuery From 253e4c4d3893b2286e011a46a344632f499e8304 Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 18:02:33 +0200 Subject: [PATCH 09/12] Revert "skip wall test" This reverts commit ab74a2b12aeeea796c16909b007cb059652a42db. --- tests/test_news_flash.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_news_flash.py b/tests/test_news_flash.py index eed9fbf68..75f945df4 100755 --- a/tests/test_news_flash.py +++ b/tests/test_news_flash.py @@ -110,7 +110,6 @@ def test_scrape_sanity_online_ynet(): @pytest.mark.slow def test_scrape_sanity_online_walla(): - pytest.skip("") next(rss_sites.scrape("walla")) From b7c206971e1895c256e02791f3b5badc571c758d Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 18:28:23 +0200 Subject: [PATCH 10/12] Revert "fix black issues" This reverts commit 9737275b884574bbcc10db4c393d5e1ba3b0838a. --- anyway/backend_constants.py | 3 +- anyway/db_views.py | 938 +++++++----------- anyway/flask_app.py | 39 +- anyway/infographic_image_generator.py | 27 +- anyway/infographics_utils.py | 3 +- anyway/models.py | 97 +- anyway/parsers/cbs/executor.py | 162 ++- anyway/parsers/cbs/s3/base.py | 2 +- anyway/request_params.py | 10 +- anyway/telegram_accident_notifications.py | 88 +- anyway/utilities.py | 23 +- anyway/views/comments/api.py | 34 +- anyway/views/news_flash/api.py | 167 ++-- .../widgets/all_locations_widgets/__init__.py | 2 +- .../accident_count_by_severity_widget.py | 77 +- .../injured_count_by_severity_widget.py | 78 +- ...ured_count_per_age_group_stacked_widget.py | 6 +- ..._and_injured_count_per_age_group_widget.py | 6 +- ...njured_count_per_age_group_widget_utils.py | 20 +- .../most_severe_accidents_table_widget.py | 70 +- .../most_severe_accidents_widget.py | 8 +- ...jured_killed_in_bicycles_scooter_widget.py | 39 +- .../widgets/no_location_widgets/__init__.py | 4 +- .../vision_zero_bike_widget.py | 5 +- .../accident_count_by_car_type_widget.py | 2 +- .../accident_count_by_hour_widget.py | 2 +- .../accident_count_by_road_light_widget.py | 2 +- ...trians_per_vehicle_street_vs_all_widget.py | 2 +- ...ident_severity_by_cross_location_widget.py | 2 +- .../accidents_heat_map_widget.py | 2 +- .../front_to_side_accidents_by_severity.py | 6 +- .../injured_count_by_accident_year_widget.py | 2 +- ...cycle_accidents_vs_all_accidents_widget.py | 36 +- .../pedestrian_injured_in_junctions_widget.py | 2 +- .../suburban_crosswalk_widget.py | 2 +- ...p_road_segments_accidents_per_km_widget.py | 2 +- anyway/widgets/urban_widgets/__init__.py | 2 +- ...jured_accidents_with_pedestrians_widget.py | 4 +- ...e_fatal_count_by_vehicle_by_year_widget.py | 2 +- ...motor_severe_fatal_count_by_year_widget.py | 2 +- .../urban_widgets/urban_crosswalk_widget.py | 2 +- .../vision_zero_10_50_90_widget.py | 12 +- anyway/widgets/widget_utils.py | 26 +- 43 files changed, 800 insertions(+), 1220 deletions(-) diff --git a/anyway/backend_constants.py b/anyway/backend_constants.py index 295f092bd..ef842cb74 100644 --- a/anyway/backend_constants.py +++ b/anyway/backend_constants.py @@ -78,7 +78,7 @@ class ResolutionCategories(Enum): SUPPORTED_RESOLUTIONS: List[ResolutionCategories] = [ ResolutionCategories.STREET, ResolutionCategories.SUBURBAN_ROAD, - ResolutionCategories.SUBURBAN_JUNCTION, + ResolutionCategories.SUBURBAN_JUNCTION ] class Source(Enum): @@ -110,7 +110,6 @@ def _missing_(cls, value): YISHUV_NAME = "yishuv_name" - BE_CONST = BackEndConstants() diff --git a/anyway/db_views.py b/anyway/db_views.py index e88e3e132..112226d16 100644 --- a/anyway/db_views.py +++ b/anyway/db_views.py @@ -61,7 +61,7 @@ ProviderCode, VehicleDamage, RoadSegments, - AccidentMarkerView, + AccidentMarkerView ) @@ -77,7 +77,7 @@ def create_markers_hebrew_view(self): AccidentType.accident_type_hebrew, AccidentMarker.accident_severity, AccidentSeverity.accident_severity_hebrew, - AccidentMarker.created.label("accident_timestamp"), + AccidentMarker.created.label('accident_timestamp'), AccidentMarker.location_accuracy, LocationAccuracy.location_accuracy_hebrew, AccidentMarker.road_type, @@ -125,12 +125,12 @@ def create_markers_hebrew_view(self): AccidentMarker.km, AccidentMarker.km_raw, AccidentMarker.km_accurate, - RoadSegments.segment_id.label("road_segment_id"), - RoadSegments.segment.label("road_segment_number"), - (RoadSegments.from_name + " - " + RoadSegments.to_name).label("road_segment_name"), - RoadSegments.from_km.label("road_segment_from_km"), - RoadSegments.to_km.label("road_segment_to_km"), - (RoadSegments.to_km - RoadSegments.from_km).label("road_segment_length_km"), + RoadSegments.segment_id.label('road_segment_id'), + RoadSegments.segment.label('road_segment_number'), + (RoadSegments.from_name + " - " + RoadSegments.to_name).label('road_segment_name'), + RoadSegments.from_km.label('road_segment_from_km'), + RoadSegments.to_km.label('road_segment_to_km'), + (RoadSegments.to_km - RoadSegments.from_km).label('road_segment_length_km'), AccidentMarker.yishuv_symbol, AccidentMarker.yishuv_name, AccidentMarker.geo_area, @@ -171,320 +171,186 @@ def create_markers_hebrew_view(self): AccidentMarker.longitude, AccidentMarker.latitude, AccidentMarker.x, - AccidentMarker.y, + AccidentMarker.y ] table = AccidentMarker.__table__ - from_clause = ( - table.join( - RoadSegments, - and_( - AccidentMarker.road1 == RoadSegments.road, - RoadSegments.from_km <= AccidentMarker.km / 10, - AccidentMarker.km / 10 < RoadSegments.to_km, - ), - isouter=True, - ) - .join( - AccidentType, - and_( - AccidentMarker.accident_type == AccidentType.id, - AccidentMarker.accident_year == AccidentType.year, - AccidentMarker.provider_code == AccidentType.provider_code, - ), - isouter=True, - ) - .join( - AccidentSeverity, - and_( - AccidentMarker.accident_severity == AccidentSeverity.id, - AccidentMarker.accident_year == AccidentSeverity.year, - AccidentMarker.provider_code == AccidentSeverity.provider_code, - ), - isouter=True, - ) - .join( - LocationAccuracy, - and_( - AccidentMarker.location_accuracy == LocationAccuracy.id, - AccidentMarker.accident_year == LocationAccuracy.year, - AccidentMarker.provider_code == LocationAccuracy.provider_code, - ), - isouter=True, - ) - .join( - RoadType, - and_( - AccidentMarker.road_type == RoadType.id, - AccidentMarker.accident_year == RoadType.year, - AccidentMarker.provider_code == RoadType.provider_code, - ), - isouter=True, - ) - .join( - RoadShape, - and_( - AccidentMarker.road_shape == RoadShape.id, - AccidentMarker.accident_year == RoadShape.year, - AccidentMarker.provider_code == RoadShape.provider_code, - ), - isouter=True, - ) - .join( - DayType, - and_( - AccidentMarker.day_type == DayType.id, - AccidentMarker.accident_year == DayType.year, - AccidentMarker.provider_code == DayType.provider_code, - ), - isouter=True, - ) - .join( - PoliceUnit, - and_( - AccidentMarker.police_unit == PoliceUnit.id, - AccidentMarker.accident_year == PoliceUnit.year, - AccidentMarker.provider_code == PoliceUnit.provider_code, - ), - isouter=True, - ) - .join( - OneLane, - and_( - AccidentMarker.one_lane == OneLane.id, - AccidentMarker.accident_year == OneLane.year, - AccidentMarker.provider_code == OneLane.provider_code, - ), - isouter=True, - ) - .join( - MultiLane, - and_( - AccidentMarker.multi_lane == MultiLane.id, - AccidentMarker.accident_year == MultiLane.year, - AccidentMarker.provider_code == MultiLane.provider_code, - ), - isouter=True, - ) - .join( - SpeedLimit, - and_( - AccidentMarker.speed_limit == SpeedLimit.id, - AccidentMarker.accident_year == SpeedLimit.year, - AccidentMarker.provider_code == SpeedLimit.provider_code, - ), - isouter=True, - ) - .join( - RoadIntactness, - and_( - AccidentMarker.road_intactness == RoadIntactness.id, - AccidentMarker.accident_year == RoadIntactness.year, - AccidentMarker.provider_code == RoadIntactness.provider_code, - ), - isouter=True, - ) - .join( - RoadWidth, - and_( - AccidentMarker.road_width == RoadWidth.id, - AccidentMarker.accident_year == RoadWidth.year, - AccidentMarker.provider_code == RoadWidth.provider_code, - ), - isouter=True, - ) - .join( - RoadSign, - and_( - AccidentMarker.road_sign == RoadSign.id, - AccidentMarker.accident_year == RoadSign.year, - AccidentMarker.provider_code == RoadSign.provider_code, - ), - isouter=True, - ) - .join( - RoadLight, - and_( - AccidentMarker.road_light == RoadLight.id, - AccidentMarker.accident_year == RoadLight.year, - AccidentMarker.provider_code == RoadLight.provider_code, - ), - isouter=True, - ) - .join( - RoadControl, - and_( - AccidentMarker.road_control == RoadControl.id, - AccidentMarker.accident_year == RoadControl.year, - AccidentMarker.provider_code == RoadControl.provider_code, - ), - isouter=True, - ) - .join( - Weather, - and_( - AccidentMarker.weather == Weather.id, - AccidentMarker.accident_year == Weather.year, - AccidentMarker.provider_code == Weather.provider_code, - ), - isouter=True, - ) - .join( - RoadSurface, - and_( - AccidentMarker.road_surface == RoadSurface.id, - AccidentMarker.accident_year == RoadSurface.year, - AccidentMarker.provider_code == RoadSurface.provider_code, - ), - isouter=True, - ) - .join( - RoadObjecte, - and_( - AccidentMarker.road_object == RoadObjecte.id, - AccidentMarker.accident_year == RoadObjecte.year, - AccidentMarker.provider_code == RoadObjecte.provider_code, - ), - isouter=True, - ) - .join( - ObjectDistance, - and_( - AccidentMarker.object_distance == ObjectDistance.id, - AccidentMarker.accident_year == ObjectDistance.year, - AccidentMarker.provider_code == ObjectDistance.provider_code, - ), - isouter=True, - ) - .join( - DidntCross, - and_( - AccidentMarker.didnt_cross == DidntCross.id, - AccidentMarker.accident_year == DidntCross.year, - AccidentMarker.provider_code == DidntCross.provider_code, - ), - isouter=True, - ) - .join( - CrossMode, - and_( - AccidentMarker.cross_mode == CrossMode.id, - AccidentMarker.accident_year == CrossMode.year, - AccidentMarker.provider_code == CrossMode.provider_code, - ), - isouter=True, - ) - .join( - CrossLocation, - and_( - AccidentMarker.cross_location == CrossLocation.id, - AccidentMarker.accident_year == CrossLocation.year, - AccidentMarker.provider_code == CrossLocation.provider_code, - ), - isouter=True, - ) - .join( - CrossDirection, - and_( - AccidentMarker.cross_direction == CrossDirection.id, - AccidentMarker.accident_year == CrossDirection.year, - AccidentMarker.provider_code == CrossDirection.provider_code, - ), - isouter=True, - ) - .join( - GeoArea, - and_( - AccidentMarker.geo_area == GeoArea.id, - AccidentMarker.accident_year == GeoArea.year, - AccidentMarker.provider_code == GeoArea.provider_code, - ), - isouter=True, - ) - .join( - DayNight, - and_( - AccidentMarker.day_night == DayNight.id, - AccidentMarker.accident_year == DayNight.year, - AccidentMarker.provider_code == DayNight.provider_code, - ), - isouter=True, - ) - .join( - DayInWeek, - and_( - AccidentMarker.day_in_week == DayInWeek.id, - AccidentMarker.accident_year == DayInWeek.year, - AccidentMarker.provider_code == DayInWeek.provider_code, - ), - isouter=True, - ) - .join( - TrafficLight, - and_( - AccidentMarker.traffic_light == TrafficLight.id, - AccidentMarker.accident_year == TrafficLight.year, - AccidentMarker.provider_code == TrafficLight.provider_code, - ), - isouter=True, - ) - .join( - Region, - and_( - AccidentMarker.region == Region.id, - AccidentMarker.accident_year == Region.year, - AccidentMarker.provider_code == Region.provider_code, - ), - isouter=True, - ) - .join( - District, - and_( - AccidentMarker.district == District.id, - AccidentMarker.accident_year == District.year, - AccidentMarker.provider_code == District.provider_code, - ), - isouter=True, - ) - .join( - NaturalArea, - and_( - AccidentMarker.natural_area == NaturalArea.id, - AccidentMarker.accident_year == NaturalArea.year, - AccidentMarker.provider_code == NaturalArea.provider_code, - ), - isouter=True, - ) - .join( - MunicipalStatus, - and_( - AccidentMarker.municipal_status == MunicipalStatus.id, - AccidentMarker.accident_year == MunicipalStatus.year, - AccidentMarker.provider_code == MunicipalStatus.provider_code, - ), - isouter=True, - ) - .join( - YishuvShape, - and_( - AccidentMarker.yishuv_shape == YishuvShape.id, - AccidentMarker.accident_year == YishuvShape.year, - AccidentMarker.provider_code == YishuvShape.provider_code, - ), - isouter=True, - ) - .join( - AccidentHourRaw, - and_( - AccidentMarker.accident_hour_raw == AccidentHourRaw.id, - AccidentMarker.accident_year == AccidentHourRaw.year, - AccidentMarker.provider_code == AccidentHourRaw.provider_code, - ), - isouter=True, - ) - .join(ProviderCode, and_(AccidentMarker.provider_code == ProviderCode.id), isouter=True) - ) - return select(selected_columns).select_from(from_clause) + from_clause = table \ + .join(RoadSegments, + and_(AccidentMarker.road1 == RoadSegments.road, + RoadSegments.from_km <= AccidentMarker.km / 10, + AccidentMarker.km / 10 < RoadSegments.to_km), + isouter=True) \ + .join(AccidentType, + and_(AccidentMarker.accident_type == AccidentType.id, + AccidentMarker.accident_year == AccidentType.year, + AccidentMarker.provider_code == AccidentType.provider_code), + isouter=True) \ + .join(AccidentSeverity, + and_(AccidentMarker.accident_severity == AccidentSeverity.id, + AccidentMarker.accident_year == AccidentSeverity.year, + AccidentMarker.provider_code == AccidentSeverity.provider_code), + isouter=True) \ + .join(LocationAccuracy, + and_(AccidentMarker.location_accuracy == LocationAccuracy.id, + AccidentMarker.accident_year == LocationAccuracy.year, + AccidentMarker.provider_code == LocationAccuracy.provider_code), + isouter=True) \ + .join(RoadType, + and_(AccidentMarker.road_type == RoadType.id, + AccidentMarker.accident_year == RoadType.year, + AccidentMarker.provider_code == RoadType.provider_code), + isouter=True) \ + .join(RoadShape, + and_(AccidentMarker.road_shape == RoadShape.id, + AccidentMarker.accident_year == RoadShape.year, + AccidentMarker.provider_code == RoadShape.provider_code), + isouter=True) \ + .join(DayType, + and_(AccidentMarker.day_type == DayType.id, + AccidentMarker.accident_year == DayType.year, + AccidentMarker.provider_code == DayType.provider_code), + isouter=True) \ + .join(PoliceUnit, + and_(AccidentMarker.police_unit == PoliceUnit.id, + AccidentMarker.accident_year == PoliceUnit.year, + AccidentMarker.provider_code == PoliceUnit.provider_code), + isouter=True) \ + .join(OneLane, + and_(AccidentMarker.one_lane == OneLane.id, + AccidentMarker.accident_year == OneLane.year, + AccidentMarker.provider_code == OneLane.provider_code), + isouter=True) \ + .join(MultiLane, + and_(AccidentMarker.multi_lane == MultiLane.id, + AccidentMarker.accident_year == MultiLane.year, + AccidentMarker.provider_code == MultiLane.provider_code), + isouter=True) \ + .join(SpeedLimit, + and_(AccidentMarker.speed_limit == SpeedLimit.id, + AccidentMarker.accident_year == SpeedLimit.year, + AccidentMarker.provider_code == SpeedLimit.provider_code), + isouter=True) \ + .join(RoadIntactness, + and_(AccidentMarker.road_intactness == RoadIntactness.id, + AccidentMarker.accident_year == RoadIntactness.year, + AccidentMarker.provider_code == RoadIntactness.provider_code), + isouter=True) \ + .join(RoadWidth, + and_(AccidentMarker.road_width == RoadWidth.id, + AccidentMarker.accident_year == RoadWidth.year, + AccidentMarker.provider_code == RoadWidth.provider_code), + isouter=True) \ + .join(RoadSign, + and_(AccidentMarker.road_sign == RoadSign.id, + AccidentMarker.accident_year == RoadSign.year, + AccidentMarker.provider_code == RoadSign.provider_code), + isouter=True) \ + .join(RoadLight, + and_(AccidentMarker.road_light == RoadLight.id, + AccidentMarker.accident_year == RoadLight.year, + AccidentMarker.provider_code == RoadLight.provider_code), + isouter=True) \ + .join(RoadControl, + and_(AccidentMarker.road_control == RoadControl.id, + AccidentMarker.accident_year == RoadControl.year, + AccidentMarker.provider_code == RoadControl.provider_code), + isouter=True) \ + .join(Weather, + and_(AccidentMarker.weather == Weather.id, + AccidentMarker.accident_year == Weather.year, + AccidentMarker.provider_code == Weather.provider_code), + isouter=True) \ + .join(RoadSurface, + and_(AccidentMarker.road_surface == RoadSurface.id, + AccidentMarker.accident_year == RoadSurface.year, + AccidentMarker.provider_code == RoadSurface.provider_code), + isouter=True) \ + .join(RoadObjecte, + and_(AccidentMarker.road_object == RoadObjecte.id, + AccidentMarker.accident_year == RoadObjecte.year, + AccidentMarker.provider_code == RoadObjecte.provider_code), + isouter=True) \ + .join(ObjectDistance, + and_(AccidentMarker.object_distance == ObjectDistance.id, + AccidentMarker.accident_year == ObjectDistance.year, + AccidentMarker.provider_code == ObjectDistance.provider_code), + isouter=True) \ + .join(DidntCross, + and_(AccidentMarker.didnt_cross == DidntCross.id, + AccidentMarker.accident_year == DidntCross.year, + AccidentMarker.provider_code == DidntCross.provider_code), + isouter=True) \ + .join(CrossMode, + and_(AccidentMarker.cross_mode == CrossMode.id, + AccidentMarker.accident_year == CrossMode.year, + AccidentMarker.provider_code == CrossMode.provider_code), + isouter=True) \ + .join(CrossLocation, + and_(AccidentMarker.cross_location == CrossLocation.id, + AccidentMarker.accident_year == CrossLocation.year, + AccidentMarker.provider_code == CrossLocation.provider_code), + isouter=True) \ + .join(CrossDirection, + and_(AccidentMarker.cross_direction == CrossDirection.id, + AccidentMarker.accident_year == CrossDirection.year, + AccidentMarker.provider_code == CrossDirection.provider_code), + isouter=True) \ + .join(GeoArea, + and_(AccidentMarker.geo_area == GeoArea.id, + AccidentMarker.accident_year == GeoArea.year, + AccidentMarker.provider_code == GeoArea.provider_code), + isouter=True) \ + .join(DayNight, + and_(AccidentMarker.day_night == DayNight.id, + AccidentMarker.accident_year == DayNight.year, + AccidentMarker.provider_code == DayNight.provider_code), + isouter=True) \ + .join(DayInWeek, + and_(AccidentMarker.day_in_week == DayInWeek.id, + AccidentMarker.accident_year == DayInWeek.year, + AccidentMarker.provider_code == DayInWeek.provider_code), + isouter=True) \ + .join(TrafficLight, + and_(AccidentMarker.traffic_light == TrafficLight.id, + AccidentMarker.accident_year == TrafficLight.year, + AccidentMarker.provider_code == TrafficLight.provider_code), + isouter=True) \ + .join(Region, + and_(AccidentMarker.region == Region.id, + AccidentMarker.accident_year == Region.year, + AccidentMarker.provider_code == Region.provider_code), + isouter=True) \ + .join(District, + and_(AccidentMarker.district == District.id, + AccidentMarker.accident_year == District.year, + AccidentMarker.provider_code == District.provider_code), + isouter=True) \ + .join(NaturalArea, + and_(AccidentMarker.natural_area == NaturalArea.id, + AccidentMarker.accident_year == NaturalArea.year, + AccidentMarker.provider_code == NaturalArea.provider_code), + isouter=True) \ + .join(MunicipalStatus, + and_(AccidentMarker.municipal_status == MunicipalStatus.id, + AccidentMarker.accident_year == MunicipalStatus.year, + AccidentMarker.provider_code == MunicipalStatus.provider_code), + isouter=True) \ + .join(YishuvShape, + and_(AccidentMarker.yishuv_shape == YishuvShape.id, + AccidentMarker.accident_year == YishuvShape.year, + AccidentMarker.provider_code == YishuvShape.provider_code), + isouter=True) \ + .join(AccidentHourRaw, + and_(AccidentMarker.accident_hour_raw == AccidentHourRaw.id, + AccidentMarker.accident_year == AccidentHourRaw.year, + AccidentMarker.provider_code == AccidentHourRaw.provider_code), + isouter=True) \ + .join(ProviderCode, + and_(AccidentMarker.provider_code == ProviderCode.id), + isouter=True) + return select(selected_columns) \ + .select_from(from_clause) def create_involved_hebrew_view(self): selected_columns = [ @@ -536,183 +402,107 @@ def create_involved_hebrew_view(self): Involved.car_id, Involved.involve_id, Involved.accident_year, - Involved.accident_month, + Involved.accident_month ] table = Involved.__table__ - from_clause = ( - table.join( - InvolvedType, - and_( - Involved.involved_type == InvolvedType.id, - Involved.accident_year == InvolvedType.year, - Involved.provider_code == InvolvedType.provider_code, - ), - isouter=True, - ) - .join( - AgeGroup, - and_( - Involved.age_group == AgeGroup.id, - Involved.accident_year == AgeGroup.year, - Involved.provider_code == AgeGroup.provider_code, - ), - isouter=True, - ) - .join( - Sex, - and_( - Involved.sex == Sex.id, - Involved.accident_year == Sex.year, - Involved.provider_code == Sex.provider_code, - ), - isouter=True, - ) - .join( - VehicleType, - and_( - Involved.vehicle_type == VehicleType.id, - Involved.accident_year == VehicleType.year, - Involved.provider_code == VehicleType.provider_code, - ), - isouter=True, - ) - .join( - SafetyMeasures, - and_( - Involved.safety_measures == SafetyMeasures.id, - Involved.accident_year == SafetyMeasures.year, - Involved.provider_code == SafetyMeasures.provider_code, - ), - isouter=True, - ) - .join( - InjurySeverity, - and_( - Involved.injury_severity == InjurySeverity.id, - Involved.accident_year == InjurySeverity.year, - Involved.provider_code == InjurySeverity.provider_code, - ), - isouter=True, - ) - .join( - InjuredType, - and_( - Involved.injured_type == InjuredType.id, - Involved.accident_year == InjuredType.year, - Involved.provider_code == InjuredType.provider_code, - ), - isouter=True, - ) - .join( - InjuredPosition, - and_( - Involved.injured_position == InjuredPosition.id, - Involved.accident_year == InjuredPosition.year, - Involved.provider_code == InjuredPosition.provider_code, - ), - isouter=True, - ) - .join( - PopulationType, - and_( - Involved.population_type == PopulationType.id, - Involved.accident_year == PopulationType.year, - Involved.provider_code == PopulationType.provider_code, - ), - isouter=True, - ) - .join( - Region, - and_( - Involved.home_region == Region.id, - Involved.accident_year == Region.year, - Involved.provider_code == Region.provider_code, - ), - isouter=True, - ) - .join( - District, - and_( - Involved.home_district == District.id, - Involved.accident_year == District.year, - Involved.provider_code == District.provider_code, - ), - isouter=True, - ) - .join( - NaturalArea, - and_( - Involved.home_natural_area == NaturalArea.id, - Involved.accident_year == NaturalArea.year, - Involved.provider_code == NaturalArea.provider_code, - ), - isouter=True, - ) - .join( - MunicipalStatus, - and_( - Involved.home_municipal_status == MunicipalStatus.id, - Involved.accident_year == MunicipalStatus.year, - Involved.provider_code == MunicipalStatus.provider_code, - ), - isouter=True, - ) - .join( - YishuvShape, - and_( - Involved.home_yishuv_shape == YishuvShape.id, - Involved.accident_year == YishuvShape.year, - Involved.provider_code == YishuvShape.provider_code, - ), - isouter=True, - ) - .join( - HospitalTime, - and_( - Involved.hospital_time == HospitalTime.id, - Involved.accident_year == HospitalTime.year, - Involved.provider_code == HospitalTime.provider_code, - ), - isouter=True, - ) - .join( - MedicalType, - and_( - Involved.medical_type == MedicalType.id, - Involved.accident_year == MedicalType.year, - Involved.provider_code == MedicalType.provider_code, - ), - isouter=True, - ) - .join( - ReleaseDest, - and_( - Involved.release_dest == ReleaseDest.id, - Involved.accident_year == ReleaseDest.year, - Involved.provider_code == ReleaseDest.provider_code, - ), - isouter=True, - ) - .join( - SafetyMeasuresUse, - and_( - Involved.safety_measures_use == SafetyMeasuresUse.id, - Involved.accident_year == SafetyMeasuresUse.year, - Involved.provider_code == SafetyMeasuresUse.provider_code, - ), - isouter=True, - ) - .join( - LateDeceased, - and_( - Involved.late_deceased == LateDeceased.id, - Involved.accident_year == LateDeceased.year, - Involved.provider_code == LateDeceased.provider_code, - ), - isouter=True, - ) - ) - return select(selected_columns).select_from(from_clause) + from_clause = table \ + .join(InvolvedType, + and_(Involved.involved_type == InvolvedType.id, + Involved.accident_year == InvolvedType.year, + Involved.provider_code == InvolvedType.provider_code), + isouter=True) \ + .join(AgeGroup, + and_(Involved.age_group == AgeGroup.id, + Involved.accident_year == AgeGroup.year, + Involved.provider_code == AgeGroup.provider_code), + isouter=True) \ + .join(Sex, + and_(Involved.sex == Sex.id, + Involved.accident_year == Sex.year, + Involved.provider_code == Sex.provider_code), + isouter=True) \ + .join(VehicleType, + and_(Involved.vehicle_type == VehicleType.id, + Involved.accident_year == VehicleType.year, + Involved.provider_code == VehicleType.provider_code), + isouter=True) \ + .join(SafetyMeasures, + and_(Involved.safety_measures == SafetyMeasures.id, + Involved.accident_year == SafetyMeasures.year, + Involved.provider_code == SafetyMeasures.provider_code), + isouter=True) \ + .join(InjurySeverity, + and_(Involved.injury_severity == InjurySeverity.id, + Involved.accident_year == InjurySeverity.year, + Involved.provider_code == InjurySeverity.provider_code), + isouter=True) \ + .join(InjuredType, + and_(Involved.injured_type == InjuredType.id, + Involved.accident_year == InjuredType.year, + Involved.provider_code == InjuredType.provider_code), + isouter=True) \ + .join(InjuredPosition, + and_(Involved.injured_position == InjuredPosition.id, + Involved.accident_year == InjuredPosition.year, + Involved.provider_code == InjuredPosition.provider_code), + isouter=True) \ + .join(PopulationType, + and_(Involved.population_type == PopulationType.id, + Involved.accident_year == PopulationType.year, + Involved.provider_code == PopulationType.provider_code), + isouter=True) \ + .join(Region, + and_(Involved.home_region == Region.id, + Involved.accident_year == Region.year, + Involved.provider_code == Region.provider_code), + isouter=True) \ + .join(District, + and_(Involved.home_district == District.id, + Involved.accident_year == District.year, + Involved.provider_code == District.provider_code), + isouter=True) \ + .join(NaturalArea, + and_(Involved.home_natural_area == NaturalArea.id, + Involved.accident_year == NaturalArea.year, + Involved.provider_code == NaturalArea.provider_code), + isouter=True) \ + .join(MunicipalStatus, + and_(Involved.home_municipal_status == MunicipalStatus.id, + Involved.accident_year == MunicipalStatus.year, + Involved.provider_code == MunicipalStatus.provider_code), + isouter=True) \ + .join(YishuvShape, + and_(Involved.home_yishuv_shape == YishuvShape.id, + Involved.accident_year == YishuvShape.year, + Involved.provider_code == YishuvShape.provider_code), + isouter=True) \ + .join(HospitalTime, + and_(Involved.hospital_time == HospitalTime.id, + Involved.accident_year == HospitalTime.year, + Involved.provider_code == HospitalTime.provider_code), + isouter=True) \ + .join(MedicalType, + and_(Involved.medical_type == MedicalType.id, + Involved.accident_year == MedicalType.year, + Involved.provider_code == MedicalType.provider_code), + isouter=True) \ + .join(ReleaseDest, + and_(Involved.release_dest == ReleaseDest.id, + Involved.accident_year == ReleaseDest.year, + Involved.provider_code == ReleaseDest.provider_code), + isouter=True) \ + .join(SafetyMeasuresUse, + and_(Involved.safety_measures_use == SafetyMeasuresUse.id, + Involved.accident_year == SafetyMeasuresUse.year, + Involved.provider_code == SafetyMeasuresUse.provider_code), + isouter=True) \ + .join(LateDeceased, + and_(Involved.late_deceased == LateDeceased.id, + Involved.accident_year == LateDeceased.year, + Involved.provider_code == LateDeceased.provider_code), + isouter=True) + return select(selected_columns) \ + .select_from(from_clause) def create_involved_hebrew_markers_hebrew_view(self): selected_columns = [ @@ -876,28 +666,23 @@ def create_involved_hebrew_markers_hebrew_view(self): VehiclesView.vehicle_type.label("vehicle_vehicle_type"), VehiclesView.vehicle_type_hebrew.label("vehicle_vehicle_type_hebrew"), VehiclesView.vehicle_damage, - VehiclesView.vehicle_damage_hebrew, + VehiclesView.vehicle_damage_hebrew ] table = InvolvedView.__table__ - from_clause = table.join( - AccidentMarkerView, - and_( - InvolvedView.provider_code == AccidentMarkerView.provider_code, - InvolvedView.accident_id == AccidentMarkerView.id, - InvolvedView.accident_year == AccidentMarkerView.accident_year, - ), - isouter=True, - ).join( - VehiclesView, - and_( - InvolvedView.provider_code == VehiclesView.provider_code, - InvolvedView.accident_id == VehiclesView.accident_id, - InvolvedView.accident_year == VehiclesView.accident_year, - InvolvedView.car_id == VehiclesView.car_id, - ), - isouter=True, - ) - return select(selected_columns).select_from(from_clause) + from_clause = table \ + .join(AccidentMarkerView, + and_(InvolvedView.provider_code == AccidentMarkerView.provider_code, + InvolvedView.accident_id == AccidentMarkerView.id, + InvolvedView.accident_year == AccidentMarkerView.accident_year), + isouter=True) \ + .join(VehiclesView, + and_(InvolvedView.provider_code == VehiclesView.provider_code, + InvolvedView.accident_id == VehiclesView.accident_id, + InvolvedView.accident_year == VehiclesView.accident_year, + InvolvedView.car_id == VehiclesView.car_id), + isouter=True) + return select(selected_columns) \ + .select_from(from_clause) def create_vehicles_hebrew_view(self): selected_columns = [ @@ -924,75 +709,47 @@ def create_vehicles_hebrew_view(self): Vehicle.vehicle_damage, VehicleDamage.vehicle_damage_hebrew, Vehicle.accident_year, - Vehicle.accident_month, + Vehicle.accident_month ] table = Vehicle.__table__ - from_clause = ( - table.join( - EngineVolume, - and_( - Vehicle.engine_volume == EngineVolume.id, - Vehicle.accident_year == EngineVolume.year, - Vehicle.provider_code == EngineVolume.provider_code, - ), - isouter=True, - ) - .join( - DrivingDirections, - and_( - Vehicle.driving_directions == DrivingDirections.id, - Vehicle.accident_year == DrivingDirections.year, - Vehicle.provider_code == DrivingDirections.provider_code, - ), - isouter=True, - ) - .join( - VehicleStatus, - and_( - Vehicle.vehicle_status == VehicleStatus.id, - Vehicle.accident_year == VehicleStatus.year, - Vehicle.provider_code == VehicleStatus.provider_code, - ), - isouter=True, - ) - .join( - VehicleAttribution, - and_( - Vehicle.vehicle_attribution == VehicleAttribution.id, - Vehicle.accident_year == VehicleAttribution.year, - Vehicle.provider_code == VehicleAttribution.provider_code, - ), - isouter=True, - ) - .join( - TotalWeight, - and_( - Vehicle.total_weight == TotalWeight.id, - Vehicle.accident_year == TotalWeight.year, - Vehicle.provider_code == TotalWeight.provider_code, - ), - isouter=True, - ) - .join( - VehicleType, - and_( - Vehicle.vehicle_type == VehicleType.id, - Vehicle.accident_year == VehicleType.year, - Vehicle.provider_code == VehicleType.provider_code, - ), - isouter=True, - ) - .join( - VehicleDamage, - and_( - Vehicle.vehicle_damage == VehicleDamage.id, - Vehicle.accident_year == VehicleDamage.year, - Vehicle.provider_code == VehicleDamage.provider_code, - ), - isouter=True, - ) - ) - return select(selected_columns).select_from(from_clause) + from_clause = table \ + .join(EngineVolume, + and_(Vehicle.engine_volume == EngineVolume.id, + Vehicle.accident_year == EngineVolume.year, + Vehicle.provider_code == EngineVolume.provider_code), + isouter=True) \ + .join(DrivingDirections, + and_(Vehicle.driving_directions == DrivingDirections.id, + Vehicle.accident_year == DrivingDirections.year, + Vehicle.provider_code == DrivingDirections.provider_code), + isouter=True) \ + .join(VehicleStatus, + and_(Vehicle.vehicle_status == VehicleStatus.id, + Vehicle.accident_year == VehicleStatus.year, + Vehicle.provider_code == VehicleStatus.provider_code), + isouter=True) \ + .join(VehicleAttribution, + and_(Vehicle.vehicle_attribution == VehicleAttribution.id, + Vehicle.accident_year == VehicleAttribution.year, + Vehicle.provider_code == VehicleAttribution.provider_code), + isouter=True) \ + .join(TotalWeight, + and_(Vehicle.total_weight == TotalWeight.id, + Vehicle.accident_year == TotalWeight.year, + Vehicle.provider_code == TotalWeight.provider_code), + isouter=True) \ + .join(VehicleType, + and_(Vehicle.vehicle_type == VehicleType.id, + Vehicle.accident_year == VehicleType.year, + Vehicle.provider_code == VehicleType.provider_code), + isouter=True) \ + .join(VehicleDamage, + and_(Vehicle.vehicle_damage == VehicleDamage.id, + Vehicle.accident_year == VehicleDamage.year, + Vehicle.provider_code == VehicleDamage.provider_code), + isouter=True) + return select(selected_columns) \ + .select_from(from_clause) def create_vehicles_markers_hebrew_view(self): selected_columns = [ @@ -1114,18 +871,15 @@ def create_vehicles_markers_hebrew_view(self): VehiclesView.vehicle_type_hebrew, VehiclesView.vehicle_damage, VehiclesView.vehicle_damage_hebrew, - VehiclesView.car_id, + VehiclesView.car_id ] table = VehiclesView.__table__ - from_clause = table.join( - AccidentMarkerView, - and_( - VehiclesView.provider_code == AccidentMarkerView.provider_code, - VehiclesView.accident_id == AccidentMarkerView.id, - VehiclesView.accident_year == AccidentMarkerView.accident_year, - ), - ) - return select(selected_columns).select_from(from_clause) - + from_clause = table \ + .join(AccidentMarkerView, + and_(VehiclesView.provider_code == AccidentMarkerView.provider_code, + VehiclesView.accident_id == AccidentMarkerView.id, + VehiclesView.accident_year == AccidentMarkerView.accident_year)) + return select(selected_columns) \ + .select_from(from_clause) VIEWS = Views() diff --git a/anyway/flask_app.py b/anyway/flask_app.py index d5eb2d855..d1b94d31b 100755 --- a/anyway/flask_app.py +++ b/anyway/flask_app.py @@ -26,7 +26,10 @@ from anyway.clusters_calculator import retrieve_clusters from anyway.config import ENTRIES_PER_PAGE from anyway.constants import CONST -from anyway.infographics_utils import get_infographics_mock_data, get_infographics_data_for_location +from anyway.infographics_utils import ( + get_infographics_mock_data, + get_infographics_data_for_location, +) from anyway.models import ( @@ -65,7 +68,7 @@ get_downloaded_data, DEFAULT_LIMIT_REQ_PARAMETER, DEFAULT_OFFSET_REQ_PARAMETER, - DEFAULT_NUMBER_OF_YEARS_AGO, + DEFAULT_NUMBER_OF_YEARS_AGO ) from anyway.views.schools.api import ( schools_description_api, @@ -318,7 +321,6 @@ def schools(): else: return Response("Method Not Allowed", 405) - @app.route("/markers", methods=["GET"]) def markers(): logging.debug("getting markers") @@ -355,7 +357,6 @@ def markers(): accident_markers, rsa_markers, discussions, is_thin, total_records=result.total_records ) - @app.route("/markers_by_yishuv_symbol", methods=["GET"]) def markers_by_yishuv_symbol(): logging.debug("getting markers by yishuv symbol") @@ -1195,10 +1196,7 @@ def get(self): parser = reqparse.RequestParser() parser.add_argument("news_flash_id", type=int, help="News flash id") parser.add_argument( - "years_ago", - type=int, - default=DEFAULT_NUMBER_OF_YEARS_AGO, - help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years", + "years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years" ) parser.add_argument("lang", type=str, default="he", help="Language") @@ -1256,10 +1254,7 @@ def gps_to_cbs_location(): idbl_parser = reqparse.RequestParser() idbl_parser.add_argument("road_segment_id", type=int, help="Road Segment id") idbl_parser.add_argument( - "years_ago", - type=int, - default=DEFAULT_NUMBER_OF_YEARS_AGO, - help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years", + "years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years" ) idbl_parser.add_argument("lang", type=str, default="he", help="Language") @@ -1460,7 +1455,6 @@ def post(self): "road_segment_id", type=int, required=True, help="road segment id" ) - @api.route("/api/streets") @api.expect(get_streets_parser) class GetAllStreetsOfYishuv(Resource): @@ -1505,26 +1499,17 @@ def put(self, id): download_data_parser = reqparse.RequestParser() -download_data_parser.add_argument( - "format", type=str, default="csv", help="Format for downloaded data (.csv/.xlsx)" -) -download_data_parser.add_argument( - "years_ago", - type=int, - default=DEFAULT_NUMBER_OF_YEARS_AGO, - help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years", -) +download_data_parser.add_argument("format", type=str, default="csv", +help="Format for downloaded data (.csv/.xlsx)") +download_data_parser.add_argument("years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, +help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years") """ Download accidents data with regards to news flash/location """ - - @api.route("/api/download-data", methods=["GET"]) class DownloadData(Resource): @api.doc("download data") @api.expect(parser) def get(self): args = download_data_parser.parse_args() - return get_downloaded_data( - args.get("format", "csv"), args.get("years_ago", DEFAULT_NUMBER_OF_YEARS_AGO) - ) + return get_downloaded_data(args.get('format', 'csv'), args.get('years_ago', DEFAULT_NUMBER_OF_YEARS_AGO)) \ No newline at end of file diff --git a/anyway/infographic_image_generator.py b/anyway/infographic_image_generator.py index 48bf2dd99..051560d31 100644 --- a/anyway/infographic_image_generator.py +++ b/anyway/infographic_image_generator.py @@ -13,7 +13,7 @@ NEWSFLASH_PAGE_BASE_URL = "https://media.anyway.co.il/newsflash" IMAGES_DOWNLOAD_PATH_IN_CONTAINER = "/var/selenium/tempdata" -selenium_url = secrets.get("SELENIUM_URL") +selenium_url = secrets.get('SELENIUM_URL') selenium_hub_url = f"https://{selenium_url}/wd/hub" selenium_remote_results_url = f"https://{selenium_url}/tempdata" CHROME_PARTIALLY_DOWNLOADED_FILE_EXTENSION = "crdownload" @@ -29,7 +29,10 @@ def create_chrome_browser_session(newsflash_id): } options.add_experimental_option("prefs", prefs) - browser = webdriver.Remote(command_executor=selenium_hub_url, options=options) + browser = webdriver.Remote( + command_executor=selenium_hub_url, + options=options + ) return browser @@ -63,8 +66,9 @@ def contains_partial_files(filenames): def fetch_generated_image_filenames_for_newsflash(newsflash_id): - contents = requests.get(f"{selenium_remote_results_url}/{newsflash_id}/").json() - filenames = [item["name"] for item in contents] + contents = requests.get( + f"{selenium_remote_results_url}/{newsflash_id}/").json() + filenames = [item['name'] for item in contents] return get_unique_filenames(filenames) @@ -72,9 +76,7 @@ def wait_for_folder_to_contain_all_files(newsflash_id, number_of_expected_files, for _ in range(timeout): time.sleep(1) image_filenames = fetch_generated_image_filenames_for_newsflash(newsflash_id) - if len(image_filenames) == number_of_expected_files and not contains_partial_files( - image_filenames - ): + if len(image_filenames) == number_of_expected_files and not contains_partial_files(image_filenames): return True, image_filenames return False, [] @@ -92,10 +94,9 @@ def generate_infographics_in_selenium_container(browser, newsflash_id): if buttons_found > 0: for element in elements: ActionChains(browser).move_to_element(element).click().perform() - time.sleep(1) # prevents click arriving before the last finished - is_download_done, generated_images_names = wait_for_folder_to_contain_all_files( - newsflash_id, buttons_found, timeout=60 - ) + time.sleep(1) #prevents click arriving before the last finished + is_download_done, generated_images_names = wait_for_folder_to_contain_all_files(newsflash_id, + buttons_found, timeout=60) except Exception as e: logging.error(e) finally: @@ -112,9 +113,7 @@ def upload_infographics_images_to_s3(newsflash_id, should_download=True): local_infographics_folder = get_local_infographics_folder_name(newsflash_id) if should_download: generated_images_names = fetch_generated_image_filenames_for_newsflash(newsflash_id) - download_infographics_images( - generated_images_names, newsflash_id, local_infographics_folder - ) + download_infographics_images(generated_images_names, newsflash_id, local_infographics_folder) upload_directory_to_s3(local_infographics_folder, newsflash_id) diff --git a/anyway/infographics_utils.py b/anyway/infographics_utils.py index 14b66a289..d6f48b748 100755 --- a/anyway/infographics_utils.py +++ b/anyway/infographics_utils.py @@ -33,7 +33,6 @@ import anyway.widgets.road_segment_widgets import anyway.widgets.all_locations_widgets import anyway.widgets.no_location_widgets - # pylint: enable=unused-import logger = logging.getLogger("infographics_utils") @@ -136,7 +135,7 @@ def get_request_params( start_time=start_time, end_time=end_time, lang=lang, - news_flash_description=news_flash_description, + news_flash_description=news_flash_description ) logging.debug(f"Ending get_request_params. params: {request_params}") return request_params diff --git a/anyway/models.py b/anyway/models.py index 478c4a48e..5116d5908 100755 --- a/anyway/models.py +++ b/anyway/models.py @@ -7,6 +7,7 @@ from typing import List, Set, Iterable + try: from flask_login import UserMixin except ModuleNotFoundError: @@ -879,9 +880,7 @@ class NewsFlash(Base): newsflash_location_qualification = Column( Integer(), nullable=False, - server_default=text( - f"{NewsflashLocationQualification.NOT_VERIFIED.value}" - ), # pylint: disable=no-member + server_default=text(f"{NewsflashLocationQualification.NOT_VERIFIED.value}"), # pylint: disable=no-member ) location_qualifying_user = Column(BigInteger(), nullable=True) @@ -893,7 +892,7 @@ def set_critical( urban_severe_value=2, ): from anyway.widgets.all_locations_widgets.injured_count_by_severity_widget import ( - InjuredCountBySeverityWidget + InjuredCountBySeverityWidget, ) from anyway.request_params import get_latest_accident_date @@ -1189,6 +1188,7 @@ def get_streets_by_yishuv(yishuv_symbol: int) -> List[dict]: raise RuntimeError(f"When retrieving streets of {yishuv_symbol}") return res1 + @staticmethod def get_streets_by_yishuv_name(yishuv_name: str) -> List[dict]: yishuv_symbol = City.get_symbol_from_name(yishuv_name) @@ -1207,58 +1207,45 @@ class SuburbanJunction(Base): __tablename__ = "suburban_junction" MAX_NAME_LEN = 100 non_urban_intersection = Column(Integer(), primary_key=True, nullable=False) - non_urban_intersection_hebrew = Column(String(length=MAX_NAME_LEN), nullable=True) + non_urban_intersection_hebrew = Column(String(length=MAX_NAME_LEN), + nullable=True) roads = Column(postgresql.ARRAY(Integer(), dimensions=1), nullable=False) @staticmethod def get_hebrew_name_from_id(non_urban_intersection: int) -> str: - res = ( - db.session.query(SuburbanJunction.non_urban_intersection_hebrew) - .filter(SuburbanJunction.non_urban_intersection == non_urban_intersection) - .first() - ) + res = db.session.query(SuburbanJunction.non_urban_intersection_hebrew).filter( + SuburbanJunction.non_urban_intersection == non_urban_intersection).first() if res is None: - raise ValueError( - f"{non_urban_intersection}: could not find " f"SuburbanJunction with that symbol" - ) + raise ValueError(f"{non_urban_intersection}: could not find " + f"SuburbanJunction with that symbol") return res.non_urban_intersection_hebrew @staticmethod def get_id_from_hebrew_name(non_urban_intersection_hebrew: str) -> int: - res = ( - db.session.query(SuburbanJunction.non_urban_intersection) - .filter(SuburbanJunction.non_urban_intersection == non_urban_intersection_hebrew) - .first() - ) + res = db.session.query(SuburbanJunction.non_urban_intersection).filter( + SuburbanJunction.non_urban_intersection == non_urban_intersection_hebrew).first() if res is None: - raise ValueError( - f"{non_urban_intersection_hebrew}: could not find " - f"SuburbanJunction with that name" - ) + raise ValueError(f"{non_urban_intersection_hebrew}: could not find " + f"SuburbanJunction with that name") return res.non_urban_intersection @staticmethod def get_intersection_from_roads(roads: Set[int]) -> dict: if not all([isinstance(x, int) for x in roads]): raise ValueError(f"{roads}: Should be integers") - res = ( - db.session.query(SuburbanJunction) - .filter(SuburbanJunction.roads.contains(roads)) - .first() - ) + res = db.session.query(SuburbanJunction).filter( + SuburbanJunction.roads.contains(roads)).first() if res is None: - raise ValueError(f"{roads}: could not find " f"SuburbanJunction with these roads") + raise ValueError(f"{roads}: could not find " + f"SuburbanJunction with these roads") return res.serialize() @staticmethod def get_all_from_key_value(key: str, val: Iterable) -> dict: if not isinstance(val, Iterable): val = [val] - res = ( - db.session.query(SuburbanJunction) - .filter((getattr(SuburbanJunction, key)).in_(val)) - .first() - ) + res = db.session.query(SuburbanJunction).filter( + (getattr(SuburbanJunction, key)).in_(val)).first() if res is None: raise ValueError(f"{key}:{val}: could not find SuburbanJunction") return res.serialize() @@ -2237,30 +2224,20 @@ def get_segment_id(self): @staticmethod def get_segments_by_segment(road_segment_id: int): - curr_road = ( - db.session.query(RoadSegments.road) - .filter(RoadSegments.segment_id == road_segment_id) - .all() - ) + curr_road = (db.session.query(RoadSegments.road) + .filter(RoadSegments.segment_id == road_segment_id) + .all()) curr_road_processed = [{"road": s.road} for s in curr_road] if curr_road is None or curr_road_processed is None: raise RuntimeError(f"When retrieving segments of {road_segment_id}") road = curr_road_processed[0]["road"] - res = ( - db.session.query(RoadSegments.segment_id, RoadSegments.from_name, RoadSegments.to_name) - .filter(RoadSegments.road == road) - .all() - ) - res1 = [ - { - "road": road, - "road_segment_id": s.segment_id, - "road_segment_name": " - ".join([s.from_name, s.to_name]), - } - for s in res - ] + res = (db.session.query(RoadSegments.segment_id, RoadSegments.from_name, RoadSegments.to_name) + .filter(RoadSegments.road == road) + .all()) + res1 = [{"road": road, "road_segment_id": s.segment_id, "road_segment_name": " - ".join([s.from_name, s.to_name])} for s in res] return res1 + @staticmethod def get_streets_by_yishuv_name(yishuv_name: str) -> List[dict]: yishuv_symbol = City.get_symbol_from_name(yishuv_name) @@ -2274,7 +2251,6 @@ def get_streets_by_yishuv_name(yishuv_name: str) -> List[dict]: raise RuntimeError(f"When retrieving streets of {yishuv_symbol}") return res1 - class Comment(Base): __tablename__ = "comments" id = Column(BigInteger(), autoincrement=True, primary_key=True, index=True) @@ -2282,7 +2258,7 @@ class Comment(Base): parent = Column(Integer, ForeignKey("comments.id"), nullable=True) created_time = Column(DateTime, default=datetime.datetime.now, index=True, nullable=False) street = Column(Text(), nullable=True, index=True) - city = Column(Text(), nullable=True, index=True) + city = Column(Text(), nullable=True, index=True) road_segment_id = Column(Integer(), nullable=True, index=True) def serialize(self): @@ -2293,10 +2269,12 @@ def serialize(self): "street": self.street, "parent": self.parent, "city": self.city, - "road_segment_id": self.road_segment_id, + "road_segment_id": self.road_segment_id + } + class ReportProblem(Base): __tablename__ = "report_problem" id = Column(BigInteger(), autoincrement=True, primary_key=True, index=True) @@ -2326,7 +2304,7 @@ class InvolvedMarkerView(Base): __table_args__ = ( Index("inv_markers_accident_yishuv_symbol_idx", "accident_yishuv_symbol", unique=False), Index("inv_markers_injury_severity_idx", "injury_severity", unique=False), - Index("inv_markers_involve_vehicle_type_idx", "involve_vehicle_type", unique=False), + Index("inv_markers_involve_vehicle_type_idx", "involve_vehicle_type", unique=False) ) accident_id = Column(BigInteger(), primary_key=True) @@ -2992,17 +2970,14 @@ class TelegramGroupsBase(Base): id = Column(Integer(), primary_key=True) filter = Column(JSON(), nullable=False, server_default="{}") - class TelegramGroups(TelegramGroupsBase): __tablename__ = "telegram_groups" - class TelegramGroupsTest(TelegramGroupsBase): __tablename__ = "telegram_groups_test" - -class TelegramForwardedMessages: - __tablename__ = "telegram_forwarded_messages" +class TelegramForwardedMessages(): + __tablename__ = 'telegram_forwarded_messages' message_id = Column(String(), primary_key=True) newsflash_id = Column(BigInteger(), nullable=False) - group_sent = (Column(String(), nullable=False),) + group_sent = Column(String(), nullable=False), diff --git a/anyway/parsers/cbs/executor.py b/anyway/parsers/cbs/executor.py index aff61cdfa..edc08eed8 100644 --- a/anyway/parsers/cbs/executor.py +++ b/anyway/parsers/cbs/executor.py @@ -85,15 +85,8 @@ VehicleMarkerView, ) from anyway.parsers.cbs.exceptions import CBSParsingFailed -from anyway.utilities import ( - ItmToWGS84, - time_delta, - ImporterUI, - truncate_tables, - delete_all_rows_from_table, - chunks, - run_query_and_insert_to_table_in_chunks, -) +from anyway.utilities import ItmToWGS84, time_delta, ImporterUI, truncate_tables, delete_all_rows_from_table, \ + chunks, run_query_and_insert_to_table_in_chunks from anyway.db_views import VIEWS from anyway.app_and_db import db from anyway.parsers.cbs.s3 import S3DataRetriever @@ -284,7 +277,7 @@ def get_address(accident, streets): house_number = ( int(accident.get(field_names.house_number)) if not pd.isnull(accident.get(field_names.house_number)) - and int(accident.get(field_names.house_number)) != 9999 + and int(accident.get(field_names.house_number)) != 9999 else None ) settlement = localization.get_city_name(accident.get(field_names.yishuv_symbol)) @@ -349,16 +342,16 @@ def get_junction(accident, roads): :return: returns the junction or None if it wasn't found """ if ( - accident.get(field_names.km) is not None - and accident.get(field_names.non_urban_intersection) is None + accident.get(field_names.km) is not None + and accident.get(field_names.non_urban_intersection) is None ): min_dist = 100000 key = (), () junc_km = 0 for option in roads: if ( - accident.get(field_names.road1) == option[0] - and abs(accident["KM"] - option[2]) < min_dist + accident.get(field_names.road1) == option[0] + and abs(accident["KM"] - option[2]) < min_dist ): min_dist = abs(accident.get(field_names.km) - option[2]) key = accident.get(field_names.road1), option[1], option[2] @@ -371,19 +364,19 @@ def get_junction(accident, roads): direction = "דרומית" if accident.get(field_names.road1) % 2 == 0 else "מערבית" if abs(float(accident["KM"] - junc_km) / 10) >= 1: string = ( - str(abs(float(accident["KM"]) - junc_km) / 10) - + " ק״מ " - + direction - + " ל" - + junction + str(abs(float(accident["KM"]) - junc_km) / 10) + + " ק״מ " + + direction + + " ל" + + junction ) elif 0 < abs(float(accident["KM"] - junc_km) / 10) < 1: string = ( - str(int((abs(float(accident.get(field_names.km)) - junc_km) / 10) * 1000)) - + " מטרים " - + direction - + " ל" - + junction + str(int((abs(float(accident.get(field_names.km)) - junc_km) / 10) * 1000)) + + " מטרים " + + direction + + " ל" + + junction ) else: string = junction @@ -467,10 +460,10 @@ def create_marker(provider_code, accident, streets, roads, non_urban_intersectio if field_names.x not in accident or field_names.y not in accident: raise ValueError("Missing x and y coordinates") if ( - accident.get(field_names.x) - and not math.isnan(accident.get(field_names.x)) - and accident.get(field_names.y) - and not math.isnan(accident.get(field_names.y)) + accident.get(field_names.x) + and not math.isnan(accident.get(field_names.x)) + and accident.get(field_names.y) + and not math.isnan(accident.get(field_names.y)) ): lng, lat = coordinates_converter.convert( accident.get(field_names.x), accident.get(field_names.y) @@ -591,7 +584,7 @@ def import_involved(provider_code, involved, **kwargs): involved_result = [] for _, involve in involved.iterrows(): if not involve.get(field_names.id) or pd.isnull( - involve.get(field_names.id) + involve.get(field_names.id) ): # skip lines with no accident id continue file_type_police = involve.get(field_names.file_type_police) @@ -706,8 +699,7 @@ def get_files(directory): field_names.street_sign: x[field_names.street_sign], field_names.street_name: x[field_names.street_name], } - for _, x in settlement.iterrows() - if isinstance(x[field_names.street_name], str) + for _, x in settlement.iterrows() if isinstance(x[field_names.street_name], str) ] output_files_dict[name] = streets_map @@ -727,7 +719,7 @@ def get_files(directory): def import_to_datastore( - directory, provider_code, year, batch_size + directory, provider_code, year, batch_size ) -> Tuple[int, Dict[int, List[dict]]]: """ goes through all the files in a given directory, parses and commits them @@ -851,15 +843,13 @@ def add_street_remove_name_duplicates(street: Dict[str, Any]): def import_suburban_junctions_into_db(): - items = [ - { - "non_urban_intersection": k, - NON_URBAN_INTERSECTION_HEBREW: fix_name_len(v[NON_URBAN_INTERSECTION_HEBREW]), - ROADS: v[ROADS], - } - for k, v in suburban_junctions_dict.items() - ] - logging.debug(f"Writing to db: {len(items)} suburban junctions") + items = [{"non_urban_intersection": k, + NON_URBAN_INTERSECTION_HEBREW: fix_name_len(v[NON_URBAN_INTERSECTION_HEBREW]), + ROADS: v[ROADS]} for + k, v in suburban_junctions_dict.items()] + logging.debug( + f"Writing to db: {len(items)} suburban junctions" + ) db.session.query(SuburbanJunction).delete() db.session.bulk_insert_mappings(SuburbanJunction, items) db.session.commit() @@ -870,13 +860,10 @@ def fix_name_len(name: str) -> str: if not isinstance(name, str): return name if len(name) > SuburbanJunction.MAX_NAME_LEN: - logging.error( - f"Suburban_junction name too long ({len(name)}>" - f"{SuburbanJunction.MAX_NAME_LEN}):{name}." - ) + logging.error(f"Suburban_junction name too long ({len(name)}>" + f"{SuburbanJunction.MAX_NAME_LEN}):{name}.") return name[: SuburbanJunction.MAX_NAME_LEN] - def load_existing_suburban_junctions(): junctions: List[SuburbanJunction] = db.session.query(SuburbanJunction).all() for j in junctions: @@ -1055,32 +1042,32 @@ def fill_dictionary_tables(cbs_dictionary, provider_code, year): if inner_v is None or (isinstance(inner_v, float) and math.isnan(inner_v)): continue sql_delete = ( - "DELETE FROM " - + curr_table - + " WHERE provider_code=" - + str(provider_code) - + " AND year=" - + str(year) - + " AND id=" - + str(inner_k) + "DELETE FROM " + + curr_table + + " WHERE provider_code=" + + str(provider_code) + + " AND year=" + + str(year) + + " AND id=" + + str(inner_k) ) db.session.execute(sql_delete) db.session.commit() sql_insert = ( - "INSERT INTO " - + curr_table - + " VALUES (" - + str(inner_k) - + "," - + str(year) - + "," - + str(provider_code) - + "," - + "'" - + inner_v.replace("'", "") - + "'" - + ")" - + " ON CONFLICT DO NOTHING" + "INSERT INTO " + + curr_table + + " VALUES (" + + str(inner_k) + + "," + + str(year) + + "," + + str(provider_code) + + "," + + "'" + + inner_v.replace("'", "") + + "'" + + ")" + + " ON CONFLICT DO NOTHING" ) db.session.execute(sql_insert) db.session.commit() @@ -1113,7 +1100,7 @@ def create_provider_code_table(): } for k, v in provider_code_dict.items(): sql_insert = ( - "INSERT INTO " + provider_code_table + " VALUES (" + str(k) + "," + "'" + v + "'" + ")" + "INSERT INTO " + provider_code_table + " VALUES (" + str(k) + "," + "'" + v + "'" + ")" ) db.session.execute(sql_insert) db.session.commit() @@ -1131,45 +1118,28 @@ def create_tables(): with db.get_engine().begin() as conn: event.listen(conn, "rollback", receive_rollback) delete_all_rows_from_table(conn, AccidentMarkerView) - run_query_and_insert_to_table_in_chunks( - VIEWS.create_markers_hebrew_view(), - AccidentMarkerView, - AccidentMarker.id, - chunk_size, - conn, - ) + run_query_and_insert_to_table_in_chunks(VIEWS.create_markers_hebrew_view(), AccidentMarkerView, + AccidentMarker.id, chunk_size, conn) logging.debug("after insertion to markers_hebrew ") delete_all_rows_from_table(conn, InvolvedView) - run_query_and_insert_to_table_in_chunks( - VIEWS.create_involved_hebrew_view(), InvolvedView, Involved.id, chunk_size, conn - ) + run_query_and_insert_to_table_in_chunks(VIEWS.create_involved_hebrew_view(), InvolvedView, + Involved.id, chunk_size, conn) logging.debug("after insertion to involved_hebrew ") delete_all_rows_from_table(conn, VehiclesView) - run_query_and_insert_to_table_in_chunks( - VIEWS.create_vehicles_hebrew_view(), VehiclesView, Vehicle.id, chunk_size, conn - ) + run_query_and_insert_to_table_in_chunks(VIEWS.create_vehicles_hebrew_view(), + VehiclesView, Vehicle.id, chunk_size, conn) logging.debug("after insertion to vehicles_hebrew ") delete_all_rows_from_table(conn, VehicleMarkerView) - run_query_and_insert_to_table_in_chunks( - VIEWS.create_vehicles_markers_hebrew_view(), - VehicleMarkerView, - VehiclesView.id, - chunk_size, - conn, - ) + run_query_and_insert_to_table_in_chunks(VIEWS.create_vehicles_markers_hebrew_view(), + VehicleMarkerView, VehiclesView.id, chunk_size, conn) logging.debug("after insertion to vehicles_markers_hebrew ") delete_all_rows_from_table(conn, InvolvedMarkerView) - run_query_and_insert_to_table_in_chunks( - VIEWS.create_involved_hebrew_markers_hebrew_view(), - InvolvedMarkerView, - InvolvedView.accident_id, - chunk_size, - conn, - ) + run_query_and_insert_to_table_in_chunks(VIEWS.create_involved_hebrew_markers_hebrew_view(), + InvolvedMarkerView, InvolvedView.accident_id, chunk_size, conn) logging.debug("after insertion to involved_markers_hebrew") logging.debug("Created DB Hebrew Tables") except Exception as e: diff --git a/anyway/parsers/cbs/s3/base.py b/anyway/parsers/cbs/s3/base.py index 784ac68ab..6c295b54c 100644 --- a/anyway/parsers/cbs/s3/base.py +++ b/anyway/parsers/cbs/s3/base.py @@ -25,4 +25,4 @@ def s3_resource(self): def s3_bucket(self): if self._s3_bucket is None: self._s3_bucket = self.s3_resource.Bucket(ANYWAY_BUCKET) - return self._s3_bucket + return self._s3_bucket \ No newline at end of file diff --git a/anyway/request_params.py b/anyway/request_params.py index 06bf8d120..d775bb2d9 100644 --- a/anyway/request_params.py +++ b/anyway/request_params.py @@ -301,9 +301,7 @@ def fill_missing_non_urban_intersection_values(vals: dict) -> dict: and "road1" in res and "road2" in res ): - res.update( - SuburbanJunction.get_intersection_from_roads({int(res["road1"]), int(res["road2"])}) - ) + res.update(SuburbanJunction.get_intersection_from_roads({int(res["road1"]), int(res["road2"])})) else: raise ValueError(f"Cannot get non_urban_intersection from input: {vals}") # TODO: temporarily removing "roads" field, as it is not used correctly in the filters. @@ -359,7 +357,9 @@ def extract_news_flash_location(news_flash_obj: NewsFlash): return {"name": "location", "data": data, "gps": gps} -def get_location_from_request_values(values: dict): +def get_location_from_request_values( + values: dict +): road_segment_id = values.get("road_segment_id") if road_segment_id is not None: return extract_road_segment_location(road_segment_id) @@ -368,7 +368,7 @@ def get_location_from_request_values(values: dict): data["street"] = values["street"] data["yishuv_name"] = values["yishuv_name"] - return {"name": "location", "data": data} + return {"name": "location", "data": data } logging.error(f"Unsupported location:{values.values()}") return None diff --git a/anyway/telegram_accident_notifications.py b/anyway/telegram_accident_notifications.py index 25b6ef639..3d6cfb2fa 100644 --- a/anyway/telegram_accident_notifications.py +++ b/anyway/telegram_accident_notifications.py @@ -11,118 +11,92 @@ TELEGRAM_CHANNEL_CHAT_ID = -1001666083560 TELEGRAM_LINKED_GROUP_CHAT_ID = -1001954877540 -TEXT_FOR_AFTER_INFOGRAPHICS_MESSAGE = 'מקור המידע בלמ"ס. נתוני התאונה שבמבזק לא נכללים באינפוגרפיקה. ' 'הופק באמצעות ANYWAY מבית "נתון לשינוי" למידע נוסף:' - +TEXT_FOR_AFTER_INFOGRAPHICS_MESSAGE = 'מקור המידע בלמ"ס. נתוני התאונה שבמבזק לא נכללים באינפוגרפיקה. ' \ + 'הופק באמצעות ANYWAY מבית "נתון לשינוי" למידע נוסף:' def send_initial_message_in_channel(bot, text): return bot.send_message(TELEGRAM_CHANNEL_CHAT_ID, text) -def fetch_message_id_for_initial_message_in_discussion_group( - bot, thread_starting_message_in_channel -): +def fetch_message_id_for_initial_message_in_discussion_group(bot, thread_starting_message_in_channel): tries = 3 for _ in range(tries): time.sleep(10) updates = bot.get_updates(allowed_updates=[]) for update in updates: - if ( - update.message - and update.message.content_type == "text" - and update.message.forward_from_message_id - == thread_starting_message_in_channel.message_id - ): + if update.message and update.message.content_type == "text" \ + and update.message.forward_from_message_id == thread_starting_message_in_channel.message_id: return update.message.message_id logging.error("failed to fetch message id in group") return None def remove_seconds_from_time_and_date(time_and_date): - return time_and_date[: time_and_date.rindex(":")] + return time_and_date[:time_and_date.rindex(":")] def create_accident_text(newsflash_id): newsflash = requests.get(f"{ANYWAY_BASE_API_URL}/news-flash/{newsflash_id}").json() - organization = newsflash["organization"] - date_and_time = remove_seconds_from_time_and_date(newsflash["date"]) + organization = newsflash['organization'] + date_and_time = remove_seconds_from_time_and_date(newsflash['date']) first_line = f"[{organization}] {date_and_time}:" return f"{first_line}\n\n{newsflash['description']}" def fetch_transcription_by_widget_name(newsflash_id): - widgets_url = ( - f"{ANYWAY_BASE_API_URL}/infographics-data?lang=he&news_flash_id={newsflash_id}&years_ago=5" - ) + widgets_url = f"{ANYWAY_BASE_API_URL}/infographics-data?lang=he&news_flash_id={newsflash_id}&years_ago=5" widgets_json = requests.get(widgets_url).json() - transcription_by_widget_name = { - widget["name"]: widget["data"]["text"]["transcription"] - for widget in widgets_json["widgets"] - if "transcription" in widget["data"]["text"] - } + transcription_by_widget_name = {widget["name"]: widget["data"]["text"]["transcription"] + for widget in widgets_json["widgets"] + if "transcription" in widget["data"]["text"]} return transcription_by_widget_name def send_after_infographics_message(bot, message_id_in_group, newsflash_id): newsflash_link = f"https://media.anyway.co.il/newsflash/{newsflash_id}" message = f"{TEXT_FOR_AFTER_INFOGRAPHICS_MESSAGE}\n{newsflash_link}" - return bot.send_message( - TELEGRAM_LINKED_GROUP_CHAT_ID, message, reply_to_message_id=message_id_in_group - ) - + return bot.send_message(TELEGRAM_LINKED_GROUP_CHAT_ID, message, reply_to_message_id=message_id_in_group) def publish_notification(newsflash_id): - # fetch data for send + #fetch data for send accident_text = create_accident_text(newsflash_id) transcription_by_widget_name = fetch_transcription_by_widget_name(newsflash_id) urls_by_infographic_name = create_public_urls_for_infographics_images(str(newsflash_id)) bot = telebot.TeleBot(secrets.get("BOT_TOKEN")) initial_message_in_channel = send_initial_message_in_channel(bot, accident_text) - # every message in the channel is automatically forwarded to the linked discussion group. - # to create a comment on the channel message, we need to send a reply to the - # forwareded message in the discussion group. - message_id_in_group = fetch_message_id_for_initial_message_in_discussion_group( - bot, initial_message_in_channel - ) + #every message in the channel is automatically forwarded to the linked discussion group. + #to create a comment on the channel message, we need to send a reply to the + #forwareded message in the discussion group. + message_id_in_group = \ + fetch_message_id_for_initial_message_in_discussion_group(bot, initial_message_in_channel) if message_id_in_group: for infographic_name, url in urls_by_infographic_name.items(): - text = ( - transcription_by_widget_name[infographic_name] - if infographic_name in transcription_by_widget_name - else None - ) - bot.send_photo( - TELEGRAM_LINKED_GROUP_CHAT_ID, - url, - reply_to_message_id=message_id_in_group, - caption=text, - ) + text = transcription_by_widget_name[infographic_name] \ + if infographic_name in transcription_by_widget_name else None + bot.send_photo(TELEGRAM_LINKED_GROUP_CHAT_ID, url, reply_to_message_id=message_id_in_group, caption=text) send_after_infographics_message(bot, message_id_in_group, newsflash_id) logging.info("notification send done") - def extract_infographic_name_from_s3_object(s3_object_name): left = s3_object_name.rindex("/") right = s3_object_name.rindex(".") - return s3_object_name[left + 1 : right] + return s3_object_name[left + 1: right] def create_public_urls_for_infographics_images(folder_name): - S3_client = boto3.client( - "s3", - aws_access_key_id=secrets.get("AWS_ACCESS_KEY"), - aws_secret_access_key=secrets.get("AWS_SECRET_KEY"), - ) - objects_contents = S3_client.list_objects_v2(Bucket=INFOGRAPHICS_S3_BUCKET, Prefix=folder_name)[ - "Contents" - ] + S3_client = boto3.client('s3', + aws_access_key_id=secrets.get("AWS_ACCESS_KEY"), + aws_secret_access_key=secrets.get("AWS_SECRET_KEY") + ) + objects_contents = S3_client.list_objects_v2(Bucket=INFOGRAPHICS_S3_BUCKET, + Prefix=folder_name)["Contents"] presigned_urls = {} for object in objects_contents: key = object["Key"] - url = S3_client.generate_presigned_url( - "get_object", Params={"Bucket": INFOGRAPHICS_S3_BUCKET, "Key": key} - ) + url = S3_client.generate_presigned_url('get_object', Params={'Bucket': INFOGRAPHICS_S3_BUCKET, + 'Key': key}) infographic_name = extract_infographic_name_from_s3_object(key) presigned_urls[infographic_name] = url return presigned_urls diff --git a/anyway/utilities.py b/anyway/utilities.py index 675905335..7181e3d54 100644 --- a/anyway/utilities.py +++ b/anyway/utilities.py @@ -174,15 +174,13 @@ def row_to_dict(row): def fetch_first_and_every_nth_value_for_column(conn, column_to_fetch, n): - sub_query = ( - select([]) - .column(column_to_fetch) - .column(func.row_number().over(order_by=column_to_fetch).label("row_number")) + sub_query = select([])\ + .column(column_to_fetch)\ + .column(func.row_number().over(order_by=column_to_fetch).label("row_number"))\ .alias() - ) - select_query = select([sub_query]).where( - or_(func.mod(sub_query.c.row_number, n) == 0, sub_query.c.row_number == 1) - ) + select_query = select([sub_query]) \ + .where(or_(func.mod(sub_query.c.row_number, n) == 0, + sub_query.c.row_number == 1)) ids_and_row_numbers = conn.execute(select_query).fetchall() ids = [id_and_row_number[0] for id_and_row_number in ids_and_row_numbers] return ids @@ -214,9 +212,7 @@ def split_query_to_chunks_by_column(base_select, column_to_chunk_by, chunk_size, logging.debug("after running query on all chunks") -def run_query_and_insert_to_table_in_chunks( - query, table_inserted_to, column_to_chunk_by, chunk_size, conn -): +def run_query_and_insert_to_table_in_chunks(query, table_inserted_to, column_to_chunk_by, chunk_size, conn): for chunk in split_query_to_chunks_by_column(query, column_to_chunk_by, chunk_size, conn): conn.execute(table_inserted_to.__table__.insert(), chunk) @@ -319,7 +315,7 @@ def is_a_safe_redirect_url(url: str) -> bool: "anyway-infographics-staging.web.app", "anyway-infographics.web.app", "anyway-infographics-demo.web.app", - "media.anyway.co.il", + "media.anyway.co.il" ]: return True @@ -343,7 +339,6 @@ def is_a_valid_email(tmp_given_user_email: str) -> bool: def half_rounded_up(num: int): return math.ceil(num / 2) - def trigger_airflow_dag(dag_id, conf=None): import airflow_client.client from airflow_client.client.api import dag_run_api @@ -356,7 +351,7 @@ def trigger_airflow_dag(dag_id, conf=None): configuration = airflow_client.client.Configuration( host=airflow_api_url, username=secrets.get("AIRFLOW_USER"), - password=secrets.get("AIRFLOW_PASSWORD"), + password=secrets.get("AIRFLOW_PASSWORD") ) with airflow_client.client.ApiClient(configuration) as api_client: dag_run_api_instance = dag_run_api.DAGRunApi(api_client) diff --git a/anyway/views/comments/api.py b/anyway/views/comments/api.py index d5d7637bc..9b9866304 100644 --- a/anyway/views/comments/api.py +++ b/anyway/views/comments/api.py @@ -13,14 +13,13 @@ from anyway.request_params import get_location_from_request_values - def create_comment(): - current_user = get_current_user() + current_user = get_current_user() json_data = request.get_json(force=True) logging.debug(json_data) - + resolution = json_data["resolution"] parent = json_data["parent"] road_segment_id = None @@ -35,24 +34,23 @@ def create_comment(): raise ValueError("Invalid comment data") comment = Comment( - author=current_user.id, - parent=parent, - street=street, - city=city, - road_segment_id=road_segment_id, - ) + author= current_user.id, + parent=parent, + street=street, + city=city, + road_segment_id=road_segment_id, + ) db.session.add(comment) x = db.session.commit() return Response() - def get_comments(): logging.debug("getting comments by resolution") params = get_location_from_request_values(request.values) comments = get_comments_by_resolution(params) - + if not comments: log_bad_request(request) return abort(http_client.NOT_FOUND) @@ -62,15 +60,17 @@ def get_comments(): return Response(json.dumps(comments_jsons, default=str), mimetype="application/json") - def get_comments_by_resolution(params): location = params["data"] resolution = location["resolution"] - + if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - return db.session.query(Comment).filter( - Comment.road_segment_id == int(location["road_segment_id"]) - ) + return ( + db.session.query(Comment) + .filter( + Comment.road_segment_id + == int(location["road_segment_id"]) + )) elif resolution == BE_CONST.ResolutionCategories.STREET: return ( db.session.query(Comment) @@ -92,3 +92,5 @@ def log_bad_request(request): ) except AttributeError: logging.debug("Bad request:{0}".format(str(request))) + + diff --git a/anyway/views/news_flash/api.py b/anyway/views/news_flash/api.py index 6fc7888c6..5227c47b1 100644 --- a/anyway/views/news_flash/api.py +++ b/anyway/views/news_flash/api.py @@ -37,7 +37,6 @@ DEFAULT_LIMIT_REQ_PARAMETER = 100 DEFAULT_NUMBER_OF_YEARS_AGO = 5 - class NewsFlashQuery(BaseModel): id: Optional[int] @@ -158,7 +157,7 @@ def gen_news_flash_query( road_segment=None, offset=None, limit=None, - last_minutes=None, + last_minutes=None ): query = session.query(NewsFlash) # get all possible sources @@ -409,73 +408,74 @@ def update_news_flash_qualifying(id): def get_downloaded_data(format, years_ago): request_params = get_request_params_from_request_values(request.values) end_time = datetime.datetime.now() - start_time = end_time - datetime.timedelta(days=years_ago * 365) + start_time = end_time - datetime.timedelta(days=years_ago*365) columns = OrderedDict() - columns[AccidentMarkerView.id] = "מס תאונה" - columns[AccidentMarkerView.provider_code_hebrew] = "סוג תיק" - columns[AccidentMarkerView.accident_type_hebrew] = "סוג תאונה" - columns[AccidentMarkerView.accident_severity_hebrew] = "חומרת תאונה" - columns[AccidentMarkerView.speed_limit_hebrew] = "מהירות מותרת" - columns[AccidentMarkerView.location_accuracy_hebrew] = "איכות עיגון" - - columns[AccidentMarkerView.accident_year] = "שנה" - columns[AccidentMarkerView.accident_month] = "חודש" - columns[AccidentMarkerView.accident_day] = "יום" - columns[AccidentMarkerView.accident_timestamp] = "חתימת זמן" - columns[AccidentMarkerView.day_in_week_hebrew] = "יום בשבוע" - columns[AccidentMarkerView.day_type_hebrew] = "סוג יום" - - columns[AccidentMarkerView.road1] = "מספר דרך- מקום אירוע התאונה" - columns[AccidentMarkerView.road2] = "מספר דרך 2" + columns[AccidentMarkerView.id] = 'מס תאונה' + columns[AccidentMarkerView.provider_code_hebrew] = 'סוג תיק' + columns[AccidentMarkerView.accident_type_hebrew] = 'סוג תאונה' + columns[AccidentMarkerView.accident_severity_hebrew] = 'חומרת תאונה' + columns[AccidentMarkerView.speed_limit_hebrew] = 'מהירות מותרת' + columns[AccidentMarkerView.location_accuracy_hebrew] = 'איכות עיגון' + + columns[AccidentMarkerView.accident_year] = 'שנה' + columns[AccidentMarkerView.accident_month] = 'חודש' + columns[AccidentMarkerView.accident_day] = 'יום' + columns[AccidentMarkerView.accident_timestamp] = 'חתימת זמן' + columns[AccidentMarkerView.day_in_week_hebrew] = 'יום בשבוע' + columns[AccidentMarkerView.day_type_hebrew] = 'סוג יום' + + columns[AccidentMarkerView.road1] = 'מספר דרך- מקום אירוע התאונה' + columns[AccidentMarkerView.road2] = 'מספר דרך 2' columns[AccidentMarkerView.km] = 'מספר הק"מ- מקום אירוע התאונה' - columns[AccidentMarkerView.region_hebrew] = "מחוז-מקום התאונה" - columns[AccidentMarkerView.yishuv_name] = "שם היישוב בו אירעה התאונה" - columns[AccidentMarkerView.street1_hebrew] = "רחוב- מקום אירוע התאונה" - columns[AccidentMarkerView.street2_hebrew] = "רחוב 2" - columns[AccidentMarkerView.house_number] = "מספר בית- מקום אירוע התאונה" - - columns[AccidentMarkerView.road_type_hebrew] = "סוג דרך" - columns[AccidentMarkerView.non_urban_intersection_hebrew] = "צומת בינעירוני" - columns[AccidentMarkerView.road_shape_hebrew] = "צורת הדרך" - columns[AccidentMarkerView.road_surface_hebrew] = "מצב פני הכביש" - columns[AccidentMarkerView.road_intactness_hebrew] = "תקינות הכביש" - columns[AccidentMarkerView.road_width_hebrew] = "רוחב הכביש" - columns[AccidentMarkerView.one_lane_hebrew] = "דרך חד מסלולית" - columns[AccidentMarkerView.multi_lane_hebrew] = "דרך רב מסלולית" - - columns[AccidentMarkerView.road_sign_hebrew] = "סימון/תמרור" - columns[AccidentMarkerView.road_light_hebrew] = "תאורה" - columns[AccidentMarkerView.road_control_hebrew] = "בקרה בצומת" - columns[AccidentMarkerView.traffic_light_hebrew] = "מרומזר/לא מרומזר" - columns[AccidentMarkerView.weather_hebrew] = "מזג אוויר" - columns[AccidentMarkerView.day_night_hebrew] = "יום/לילה" - columns[AccidentMarkerView.road_object_hebrew] = "עצם-סוג" - - columns[AccidentMarkerView.didnt_cross_hebrew] = "חצייה-לא חצה" - columns[AccidentMarkerView.cross_mode_hebrew] = "חצייה-אופן" - columns[AccidentMarkerView.cross_location_hebrew] = "חצייה-מקום" - columns[AccidentMarkerView.cross_direction_hebrew] = "חצייה-כיוון" - - columns[AccidentMarkerView.longitude] = "קו אורך" - columns[AccidentMarkerView.latitude] = "קו רוחב" - columns[AccidentMarkerView.x] = "X קואורדינטה" - columns[AccidentMarkerView.y] = "Y קואורדינטה" + columns[AccidentMarkerView.region_hebrew] = 'מחוז-מקום התאונה' + columns[AccidentMarkerView.yishuv_name] = 'שם היישוב בו אירעה התאונה' + columns[AccidentMarkerView.street1_hebrew] = 'רחוב- מקום אירוע התאונה' + columns[AccidentMarkerView.street2_hebrew] = 'רחוב 2' + columns[AccidentMarkerView.house_number] = 'מספר בית- מקום אירוע התאונה' + + columns[AccidentMarkerView.road_type_hebrew] = 'סוג דרך' + columns[AccidentMarkerView.non_urban_intersection_hebrew] = 'צומת בינעירוני' + columns[AccidentMarkerView.road_shape_hebrew] = 'צורת הדרך' + columns[AccidentMarkerView.road_surface_hebrew] = 'מצב פני הכביש' + columns[AccidentMarkerView.road_intactness_hebrew] = 'תקינות הכביש' + columns[AccidentMarkerView.road_width_hebrew] = 'רוחב הכביש' + columns[AccidentMarkerView.one_lane_hebrew] = 'דרך חד מסלולית' + columns[AccidentMarkerView.multi_lane_hebrew] = 'דרך רב מסלולית' + + columns[AccidentMarkerView.road_sign_hebrew] = 'סימון/תמרור' + columns[AccidentMarkerView.road_light_hebrew] = 'תאורה' + columns[AccidentMarkerView.road_control_hebrew] = 'בקרה בצומת' + columns[AccidentMarkerView.traffic_light_hebrew] = 'מרומזר/לא מרומזר' + columns[AccidentMarkerView.weather_hebrew] = 'מזג אוויר' + columns[AccidentMarkerView.day_night_hebrew] = 'יום/לילה' + columns[AccidentMarkerView.road_object_hebrew] = 'עצם-סוג' + + columns[AccidentMarkerView.didnt_cross_hebrew] = 'חצייה-לא חצה' + columns[AccidentMarkerView.cross_mode_hebrew] = 'חצייה-אופן' + columns[AccidentMarkerView.cross_location_hebrew] = 'חצייה-מקום' + columns[AccidentMarkerView.cross_direction_hebrew] = 'חצייה-כיוון' + + columns[AccidentMarkerView.longitude] = 'קו אורך' + columns[AccidentMarkerView.latitude] = 'קו רוחב' + columns[AccidentMarkerView.x] = 'X קואורדינטה' + columns[AccidentMarkerView.y] = 'Y קואורדינטה' + related_accidents = get_accidents_stats( - table_obj=AccidentMarkerView, - columns=columns.keys(), - filters=request_params.location_info, - start_time=start_time, - end_time=end_time, - ) - accident_ids = list(related_accidents["id"].values()) + table_obj=AccidentMarkerView, + columns=columns.keys(), + filters=request_params.location_info, + start_time=start_time, + end_time=end_time + ) + accident_ids = list(related_accidents['id'].values()) accident_severities = get_accidents_stats( - table_obj=InvolvedView, - group_by=("accident_id", "injury_severity_hebrew"), - count="injury_severity_hebrew", - filters={"accident_id": accident_ids}, - ) + table_obj=InvolvedView, + group_by=("accident_id", "injury_severity_hebrew"), + count="injury_severity_hebrew", + filters={"accident_id": accident_ids} + ) severities_hebrew = set() for i, accident_id in enumerate(accident_ids): @@ -490,40 +490,23 @@ def get_downloaded_data(format, years_ago): json_data = json.dumps(related_accidents, default=str) buffer = BytesIO() df = pd.read_json(json_data) - df.rename( - columns={key.name.replace("_hebrew", ""): value for key, value in columns.items()}, - inplace=True, - ) + df.rename(columns={key.name.replace('_hebrew', ''): value for key, value in columns.items()}, inplace=True) - index_to_insert_severities = list(columns.values()).index("מהירות מותרת") - output_column_names = ( - list(columns.values())[:index_to_insert_severities] - + list(severities_hebrew) - + list(columns.values())[index_to_insert_severities:] - ) + index_to_insert_severities = list(columns.values()).index('מהירות מותרת') + output_column_names = list(columns.values())[:index_to_insert_severities] + list(severities_hebrew) + list(columns.values())[index_to_insert_severities:] df = df[output_column_names] - df.rename( - columns={ - "פצוע קל": "פצוע/ה קל", - "פצוע בינוני": "פצוע/ה בינוני", - "פצוע קשה": "פצוע/ה קשה", - "הרוג": "הרוג/ה", - }, - inplace=True, - ) + df.rename(columns={'פצוע קל': 'פצוע/ה קל', 'פצוע בינוני': 'פצוע/ה בינוני', 'פצוע קשה': 'פצוע/ה קשה', 'הרוג': 'הרוג/ה'}, inplace=True) - if format == "csv": + if format == 'csv': df.to_csv(buffer, encoding="utf-8") - mimetype = "text/csv" - file_type = "csv" - elif format == "xlsx": + mimetype ='text/csv' + file_type = 'csv' + elif format == 'xlsx': df.to_excel(buffer, encoding="utf-8") - mimetype = "application/vnd.ms-excel" - file_type = "xlsx" + mimetype='application/vnd.ms-excel' + file_type = 'xlsx' else: - raise Exception(f"File format not supported for downloading : {format}") + raise Exception(f'File format not supported for downloading : {format}') - headers = { - "Content-Disposition": f'attachment; filename=anyway_download_{datetime.datetime.now().strftime("%d_%m_%Y_%H_%M_%S")}.{file_type}' - } + headers = { 'Content-Disposition': f'attachment; filename=anyway_download_{datetime.datetime.now().strftime("%d_%m_%Y_%H_%M_%S")}.{file_type}' } return Response(buffer.getvalue(), mimetype=mimetype, headers=headers) diff --git a/anyway/widgets/all_locations_widgets/__init__.py b/anyway/widgets/all_locations_widgets/__init__.py index 2d7769f7e..4f55bfa5e 100644 --- a/anyway/widgets/all_locations_widgets/__init__.py +++ b/anyway/widgets/all_locations_widgets/__init__.py @@ -5,5 +5,5 @@ most_severe_accidents_table_widget, seriously_injured_killed_in_bicycles_scooter_widget, killed_and_injured_count_per_age_group_stacked_widget, - killed_and_injured_count_per_age_group_widget, + killed_and_injured_count_per_age_group_widget ) diff --git a/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py index 07bd10970..546ad583e 100644 --- a/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/accident_count_by_severity_widget.py @@ -61,46 +61,44 @@ def get_accident_count_by_severity(location_info, start_time, end_time): def get_transcription(request_params: RequestParams, items: Dict): total_accidents_count = items.get("total_accidents_count") if total_accidents_count == 0: - return "" + return '' severity_light_count = items.get("severity_light_count") if severity_light_count == 0: - severity_light_count_text = "" + severity_light_count_text = '' elif severity_light_count == 1: severity_light_count_text = _("one light") else: - severity_light_count_text = f"{severity_light_count} " + _("light plural") + severity_light_count_text = f'{severity_light_count} ' + _("light plural") severity_severe_count = items.get("severity_severe_count") if severity_severe_count == 0: - severity_severe_count_text = "" + severity_severe_count_text = '' elif severity_severe_count == 1: severity_severe_count_text = _("one severe") else: - severity_severe_count_text = f"{severity_severe_count} " + _("severe plural") + severity_severe_count_text = f'{severity_severe_count} '+ _("severe plural") severity_fatal_count = items.get("severity_fatal_count") if severity_fatal_count == 0: - severity_fatal_count_text = "" + severity_fatal_count_text = '' elif severity_fatal_count == 1: severity_fatal_count_text = _("one fatal") else: - severity_fatal_count_text = f"{severity_fatal_count} " + _("fatal plural") + severity_fatal_count_text = f'{severity_fatal_count} ' + _("fatal plural") if request_params.resolution == BE_CONST.ResolutionCategories.STREET: text = "{in_yishuv_keyword} {yishuv_name} {in_street_keyword} {street_name} ".format( in_yishuv_keyword=_("in yishuv"), - yishuv_name=_(request_params.location_info.get("yishuv_name")), + yishuv_name=_(request_params.location_info.get('yishuv_name')), in_street_keyword=_("in street"), - street_name=_(request_params.location_info.get("street1_hebrew")), + street_name=_(request_params.location_info.get('street1_hebrew')), ) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: text = "{in_road_keyword} {road_num} {in_segment_keyword} {segment_name} ".format( in_road_keyword=_("in road"), - road_num=request_params.location_info.get("road1"), + road_num=request_params.location_info.get('road1'), in_segment_keyword=_("in segment"), - segment_name=_(request_params.location_info.get("road_segment_name")), + segment_name=_(request_params.location_info.get('road_segment_name')), ) else: - raise Exception( - f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}" - ) + raise Exception(f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}") text += "{between_years_keyword} {start_year} - {end_year}, {separator_keyword} {incidents_num} {incident_keyword}, {out_of_them_keywoard} ".format( between_years_keyword=_("between the years"), start_year=request_params.start_time.year, @@ -110,32 +108,24 @@ def get_transcription(request_params: RequestParams, items: Dict): incident_keyword=_("accidents"), out_of_them_keywoard=_("out of them"), ) - text += join_strings( - [severity_fatal_count_text, severity_severe_count_text, severity_light_count_text], - sep_a=" ,", - sep_b=_(" and "), - ) + text += join_strings([severity_fatal_count_text, severity_severe_count_text, severity_light_count_text], + sep_a=" ,", + sep_b=_(" and ")) return text @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - if request_params.resolution in ( - BE_CONST.ResolutionCategories.SUBURBAN_ROAD, - BE_CONST.ResolutionCategories.SUBURBAN_JUNCTION, - ): + if request_params.resolution in (BE_CONST.ResolutionCategories.SUBURBAN_ROAD, + BE_CONST.ResolutionCategories.SUBURBAN_JUNCTION): is_segment = request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD items["data"]["text"] = { "title": _("Number of accidents by severity"), - "subtitle": _(request_params.location_info["road_segment_name"]) - if is_segment - else _(request_params.location_info["non_urban_intersection_hebrew"]), - "transcription": AccidentCountBySeverityWidget.get_transcription( - request_params=request_params, items=items["data"]["items"] - ), + "subtitle": _(request_params.location_info['road_segment_name']) if is_segment else + _(request_params.location_info['non_urban_intersection_hebrew']), + "transcription": AccidentCountBySeverityWidget.get_transcription(request_params=request_params, + items=items["data"]["items"]) } - items["meta"][ - "information" - ] = "{incident_description}{incident_location} {incident_time}.".format( + items["meta"]["information"] = "{incident_description}{incident_location} {incident_time}.".format( incident_description=_("Fatal, severe and light accidents count in "), incident_location=_("segment") if is_segment else _("junction"), incident_time=_("in the selected time"), @@ -151,22 +141,11 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: incidents_num=num_accidents, incident_keyword=_("accidents"), ) - subtitle = _( - "{street_name}, {yishuv_name}".format( - street_name=request_params.location_info["street1_hebrew"], - yishuv_name=request_params.location_info["yishuv_name"], - ) - ) - items["data"]["text"] = { - "title": s, - "subtitle": subtitle, - "transcription": AccidentCountBySeverityWidget.get_transcription( - request_params=request_params, items=items["data"]["items"] - ), - } - items["meta"][ - "information" - ] = "{incident_description}{incident_location} {incident_time}.".format( + subtitle = _("{street_name}, {yishuv_name}".format(street_name=request_params.location_info["street1_hebrew"], + yishuv_name=request_params.location_info["yishuv_name"])) + items["data"]["text"] = {"title": s, "subtitle": subtitle, "transcription": AccidentCountBySeverityWidget.get_transcription(request_params=request_params, + items=items["data"]["items"])} + items["meta"]["information"] = "{incident_description}{incident_location} {incident_time}.".format( incident_description=_("Fatal, severe and light accidents count in "), incident_location=_("street"), incident_time=_("in the selected time"), @@ -191,4 +170,4 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: _("out of them") _("accidents") _(" and ") -_("in the selected time") +_("in the selected time") \ No newline at end of file diff --git a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py index d9ef739a9..cdccd6735 100644 --- a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py @@ -24,32 +24,32 @@ def generate_items(self) -> None: self.request_params.resolution, self.request_params.location_info, self.request_params.start_time, - self.request_params.end_time, + self.request_params.end_time ) @staticmethod def get_injured_count_by_severity(resolution, location_info, start_time, end_time): filters = {} filters["injury_severity"] = [ - InjurySeverity.KILLED.value, - InjurySeverity.SEVERE_INJURED.value, - InjurySeverity.LIGHT_INJURED.value, - ] - - if resolution == BE_CONST.ResolutionCategories.STREET: - filters["involve_yishuv_name"] = location_info.get("yishuv_name") - filters["street1_hebrew"] = location_info.get("street1_hebrew") + InjurySeverity.KILLED.value, + InjurySeverity.SEVERE_INJURED.value, + InjurySeverity.LIGHT_INJURED.value, + ] + + if resolution == BE_CONST.ResolutionCategories.STREET: + filters["involve_yishuv_name"] = location_info.get('yishuv_name') + filters["street1_hebrew"] = location_info.get('street1_hebrew') elif resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - filters["road1"] = location_info.get("road1") - filters["road_segment_name"] = location_info.get("road_segment_name") - + filters["road1"] = location_info.get('road1') + filters["road_segment_name"] = location_info.get('road_segment_name') + count_by_severity = get_accidents_stats( - table_obj=InvolvedMarkerView, - filters=filters, - group_by="injury_severity", - count="injury_severity", - start_time=start_time, - end_time=end_time, + table_obj = InvolvedMarkerView, + filters = filters, + group_by = "injury_severity", + count = "injury_severity", + start_time = start_time, + end_time = end_time, ) found_severities = [d["injury_severity"] for d in count_by_severity] items = {} @@ -73,50 +73,49 @@ def get_injured_count_by_severity(resolution, location_info, start_time, end_tim items["total_injured_count"] = total_injured_count return items + @staticmethod def get_transcription(request_params: RequestParams, items: Dict): total_injured_count = items.get("total_injured_count") if total_injured_count == 0: - return "" + return '' severity_light_count = items.get("light_injured_count") if severity_light_count == 0: - severity_light_count_text = "" + severity_light_count_text = '' elif severity_light_count == 1: severity_light_count_text = _("one light injured") else: - severity_light_count_text = f"{severity_light_count} " + _("light injured plural") + severity_light_count_text = f'{severity_light_count} ' + _("light injured plural") severity_severe_count = items.get("severe_injured_count") if severity_severe_count == 0: - severity_severe_count_text = "" + severity_severe_count_text = '' elif severity_severe_count == 1: severity_severe_count_text = _("one severe injured") else: - severity_severe_count_text = f"{severity_severe_count} " + _("severe injured plural") + severity_severe_count_text = f'{severity_severe_count} '+ _("severe injured plural") killed_count = items.get("killed_count") if killed_count == 0: - killed_count_text = "" + killed_count_text = '' elif killed_count == 1: killed_count_text = _("one killed") else: - killed_count_text = f"{killed_count} " + _("killed plural") + killed_count_text = f'{killed_count} ' + _("killed plural") if request_params.resolution == BE_CONST.ResolutionCategories.STREET: text = "{in_yishuv_keyword} {yishuv_name} {in_street_keyword} {street_name} ".format( in_yishuv_keyword=_("in yishuv"), - yishuv_name=_(request_params.location_info.get("yishuv_name")), + yishuv_name=_(request_params.location_info.get('yishuv_name')), in_street_keyword=_("in street"), - street_name=_(request_params.location_info.get("street1_hebrew")), + street_name=_(request_params.location_info.get('street1_hebrew')), ) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: text = "{in_road_keyword} {road_num} {in_segment_keyword} {segment_name} ".format( in_road_keyword=_("in road"), - road_num=request_params.location_info.get("road1"), + road_num=request_params.location_info.get('road1'), in_segment_keyword=_("in segment"), - segment_name=_(request_params.location_info.get("road_segment_name")), + segment_name=_(request_params.location_info.get('road_segment_name')), ) else: - raise Exception( - f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}" - ) + raise Exception(f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}") text += "{between_years_keyword} {start_year} - {end_year}, {injured_killed_keyword} {injured_num} {people_phrase}, {out_of_them_keywoard} ".format( between_years_keyword=_("between the years"), start_year=request_params.start_time.year, @@ -126,13 +125,12 @@ def get_transcription(request_params: RequestParams, items: Dict): people_phrase=_("people from car accidents"), out_of_them_keywoard=_("out of them"), ) - text += join_strings( - [killed_count_text, severity_severe_count_text, severity_light_count_text], - sep_a=" ,", - sep_b=_(" and "), - ) + text += join_strings([killed_count_text, severity_severe_count_text, severity_light_count_text], + sep_a=" ,", + sep_b=_(" and ")) return text + @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: @@ -140,11 +138,11 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Number of Injuries in accidents by severity"), "subtitle": _(subtitle), - "transcription": InjuredCountBySeverityWidget.get_transcription( - request_params=request_params, items=items["data"]["items"] - ), + "transcription": InjuredCountBySeverityWidget.get_transcription(request_params=request_params, + items=items["data"]["items"]) } return items + _("injured/killed") diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py index 7ca1716cc..ef3e406ec 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py @@ -12,11 +12,7 @@ from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget from anyway.widgets.widget import register -from anyway.widgets.widget_utils import ( - add_empty_keys_to_gen_two_level_dict, - gen_entity_labels, - get_location_text, -) +from anyway.widgets.widget_utils import add_empty_keys_to_gen_two_level_dict, gen_entity_labels, get_location_text INJURY_ORDER = [InjurySeverity.LIGHT_INJURED, InjurySeverity.SEVERE_INJURED, InjurySeverity.KILLED] MAX_AGE = 200 diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py index b255d593f..01b06bfc7 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py @@ -12,7 +12,6 @@ from anyway.widgets.widget import register from anyway.widgets.widget_utils import get_location_text - @register class KilledInjuredCountPerAgeGroupWidget(AllLocationsWidget): name: str = "killed_and_injured_count_per_age_group" @@ -38,5 +37,8 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: location_text = get_location_text(request_params) - items["data"]["text"] = {"title": _("Injury per age group"), "subtitle": _(location_text)} + items["data"]["text"] = { + "title": _("Injury per age group"), + "subtitle": _(location_text) + } return items diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py index aea2c36a9..422047bb1 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py @@ -27,19 +27,19 @@ class KilledAndInjuredCountPerAgeGroupWidgetUtils: def filter_and_group_injured_count_per_age_group( request_params: RequestParams, ) -> Dict[str, Dict[int, int]]: - + start_time = request_params.start_time end_time = request_params.end_time if request_params.resolution == BE_CONST.ResolutionCategories.STREET: - involve_yishuv_name = request_params.location_info["yishuv_name"] - street1_hebrew = request_params.location_info["street1_hebrew"] + involve_yishuv_name = request_params.location_info['yishuv_name'] + street1_hebrew = request_params.location_info['street1_hebrew'] cache_key = (involve_yishuv_name, street1_hebrew, start_time, end_time) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: road_number = request_params.location_info["road1"] road_segment = request_params.location_info["road_segment_name"] cache_key = (road_number, road_segment, start_time, end_time) - + if cache_dict.get(cache_key): return cache_dict.get(cache_key) @@ -100,17 +100,9 @@ def create_query_for_killed_and_injured_count_per_age_group( end_time, start_time, location_info, resolution ) -> BaseQuery: if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - location_filter = ( - (InvolvedMarkerView.road1 == location_info["road1"]) - | (InvolvedMarkerView.road2 == location_info["road1"]) - ) & (InvolvedMarkerView.road_segment_name == location_info["road_segment_name"]) + location_filter = ((InvolvedMarkerView.road1 == location_info["road1"]) | (InvolvedMarkerView.road2 == location_info["road1"])) & (InvolvedMarkerView.road_segment_name == location_info["road_segment_name"]) elif resolution == BE_CONST.ResolutionCategories.STREET: - location_filter = ( - InvolvedMarkerView.involve_yishuv_name == location_info["yishuv_name"] - ) & ( - (InvolvedMarkerView.street1_hebrew == location_info["street1_hebrew"]) - | (InvolvedMarkerView.street2_hebrew == location_info["street1_hebrew"]) - ) + location_filter = (InvolvedMarkerView.involve_yishuv_name == location_info["yishuv_name"]) & ((InvolvedMarkerView.street1_hebrew == location_info["street1_hebrew"]) | (InvolvedMarkerView.street2_hebrew == location_info["street1_hebrew"])) query = ( db.session.query(InvolvedMarkerView) diff --git a/anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py b/anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py index 950c20e24..b0d9b3e6d 100644 --- a/anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py +++ b/anyway/widgets/all_locations_widgets/most_severe_accidents_table_widget.py @@ -44,22 +44,12 @@ def get_most_severe_accidents_table_title( location_info: dict, resolution: BE_CONST.ResolutionCategories ): if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - return ( - "Most severe accidents in segment", - segment_dictionary[location_info["road_segment_name"]], - ) + return "Most severe accidents in segment", segment_dictionary[location_info["road_segment_name"]] elif resolution == BE_CONST.ResolutionCategories.SUBURBAN_JUNCTION: - return ( - "Severe accidents in suburban junction", - f" {location_info['non_urban_intersection_hebrew']}", - ) + return "Severe accidents in suburban junction", f" {location_info['non_urban_intersection_hebrew']}" elif resolution == BE_CONST.ResolutionCategories.STREET: in_str = _("in") - return ( - "Severe accidents in street", - f" {location_info['street1_hebrew']} {in_str}{location_info['yishuv_name']}", - ) - + return "Severe accidents in street", f" {location_info['street1_hebrew']} {in_str}{location_info['yishuv_name']}" # count of dead and severely injured def get_casualties_count_in_accident(accident_id, provider_code, injury_severity, accident_year): @@ -159,10 +149,11 @@ def prepare_table( ).get_label() return accidents + @staticmethod def get_transcription(request_params: RequestParams, items: Dict): if len(items) == 0: - return "" + return '' elif len(items) == 1: text = _("latest severe accident took place") else: @@ -171,45 +162,40 @@ def get_transcription(request_params: RequestParams, items: Dict): if request_params.resolution == BE_CONST.ResolutionCategories.STREET: text += " {in_yishuv_keyword} {yishuv_name} {in_street_keyword} {street_name} ".format( in_yishuv_keyword=_("in yishuv"), - yishuv_name=_(request_params.location_info.get("yishuv_name")), + yishuv_name=_(request_params.location_info.get('yishuv_name')), in_street_keyword=_("in street"), - street_name=_(request_params.location_info.get("street1_hebrew")), + street_name=_(request_params.location_info.get('street1_hebrew')), ) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: text += " {in_road_keyword} {road_num} {in_segment_keyword} {segment_name} ".format( in_road_keyword=_("in road"), - road_num=request_params.location_info.get("road1"), + road_num=request_params.location_info.get('road1'), in_segment_keyword=_("in segment"), - segment_name=_(request_params.location_info.get("road_segment_name")), + segment_name=_(request_params.location_info.get('road_segment_name')), ) else: - raise Exception( - f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}" - ) + raise Exception(f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}") text += "{between_years_keyword} {start_year} - {end_year}:\n".format( between_years_keyword=_("between the years"), start_year=request_params.start_time.year, end_year=request_params.end_time.year, ) logging.debug(items) - text += "\n".join( - [ - "{in_date_keyword} {date} {in_hour_keyword} {hour} {accident_occured_text} {accident_type_keyword} {type}, {injured_count_keyword}: {injured_count}.".format( - in_date_keyword=_("in date"), - date=item.get("date"), - in_hour_keyword=_("in hour"), - hour=item.get("hour"), - accident_occured_text=_("occured accident"), - accident_type_keyword=_("of type"), - type=_(item.get("type")), - injured_count_keyword=_("injured"), - injured_count=item.get("injured_count"), - ) - for item in items - ] - ) + text += '\n'.join(['{in_date_keyword} {date} {in_hour_keyword} {hour} {accident_occured_text} {accident_type_keyword} {type}, {injured_count_keyword}: {injured_count}.'.format( + in_date_keyword=_("in date"), + date=item.get("date"), + in_hour_keyword=_("in hour"), + hour=item.get("hour"), + accident_occured_text=_("occured accident"), + accident_type_keyword=_("of type"), + type=_(item.get("type")), + injured_count_keyword=_("injured"), + injured_count=item.get("injured_count") + ) + for item in items]) return text + @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: if request_params.lang != "en": @@ -221,15 +207,13 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: logging.exception( f"MostSevereAccidentsTableWidget.localize_items: Exception while translating {item}." ) - title, subtitle = get_most_severe_accidents_table_title( - request_params.location_info, request_params.resolution - ) + title, subtitle = get_most_severe_accidents_table_title(request_params.location_info, + request_params.resolution) items["data"]["text"] = { "title": _(title), "subtitle": _(subtitle), - "transcription": MostSevereAccidentsTableWidget.get_transcription( - request_params=request_params, items=items["data"]["items"] - ), + "transcription": MostSevereAccidentsTableWidget.get_transcription(request_params=request_params, + items=items["data"]["items"]) } return items diff --git a/anyway/widgets/all_locations_widgets/most_severe_accidents_widget.py b/anyway/widgets/all_locations_widgets/most_severe_accidents_widget.py index f25e2e61c..fa18cc83a 100644 --- a/anyway/widgets/all_locations_widgets/most_severe_accidents_widget.py +++ b/anyway/widgets/all_locations_widgets/most_severe_accidents_widget.py @@ -70,9 +70,11 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: f"MostSevereAccidentsWidget.localize_items: Exception while translating {item}." ) title, subtitle = get_most_severe_accidents_table_title( - request_params.location_info, request_params.resolution - ) - items["data"]["text"] = {"title": _(title), "subtitle": _(subtitle)} + request_params.location_info, request_params.resolution) + items["data"]["text"] = { + "title": _(title), + "subtitle": _(subtitle) + } return items diff --git a/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py b/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py index 2ea07c8fe..a120a207e 100644 --- a/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py +++ b/anyway/widgets/all_locations_widgets/seriously_injured_killed_in_bicycles_scooter_widget.py @@ -33,43 +33,34 @@ def generate_items(self) -> None: @staticmethod def get_seriously_injured_killed_in_bicycles_scooter( - start_year: int, end_year: int, location_info: LocationInfo + start_year: int, + end_year: int, + location_info: LocationInfo ): - res = get_involved_counts( - start_year, - end_year, - SeriouslyInjuredKilledInBicyclesScooterWidget.severities, - SeriouslyInjuredKilledInBicyclesScooterWidget.vehicle_types, - location_info, - ) + res = get_involved_counts(start_year, end_year, + SeriouslyInjuredKilledInBicyclesScooterWidget.severities, + SeriouslyInjuredKilledInBicyclesScooterWidget.vehicle_types, + location_info) return res @staticmethod def create_location_description(location_info: LocationInfo, location_text: str) -> str: - return ( - _("in") + location_info[Constants.YISHUV_NAME] - if Constants.YISHUV_NAME in location_info + return _("in") + location_info[Constants.YISHUV_NAME] \ + if Constants.YISHUV_NAME in location_info \ else location_text - ) @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - subtitle = _( - SeriouslyInjuredKilledInBicyclesScooterWidget.create_location_description( - request_params.location_info, request_params.location_text - ) - ) - items["data"]["text"] = { - "title": _( - "Number of severely injured or killed in bike, e-bike, or scooter accidents" - ), - "subtitle": subtitle, - } + subtitle = _(SeriouslyInjuredKilledInBicyclesScooterWidget.create_location_description( + request_params.location_info, + request_params.location_text)) + items["data"]["text"] = {"title": _("Number of severely injured or killed in bike, e-bike, or scooter accidents"), + "subtitle": subtitle} return items def is_included(self) -> bool: num_of_years_in_query = len(self.items) years_with_accidents = [item["label_key"] for item in self.items if item["value"] > 0] num_of_years_with_accidents = len(years_with_accidents) - return num_of_years_with_accidents >= half_rounded_up(num_of_years_in_query) + return num_of_years_with_accidents >= half_rounded_up(num_of_years_in_query) \ No newline at end of file diff --git a/anyway/widgets/no_location_widgets/__init__.py b/anyway/widgets/no_location_widgets/__init__.py index 41d407810..a3b81e09e 100644 --- a/anyway/widgets/no_location_widgets/__init__.py +++ b/anyway/widgets/no_location_widgets/__init__.py @@ -1 +1,3 @@ -from . import vision_zero_bike_widget +from . import ( + vision_zero_bike_widget +) diff --git a/anyway/widgets/no_location_widgets/vision_zero_bike_widget.py b/anyway/widgets/no_location_widgets/vision_zero_bike_widget.py index c4a64faae..1f8f8abc9 100644 --- a/anyway/widgets/no_location_widgets/vision_zero_bike_widget.py +++ b/anyway/widgets/no_location_widgets/vision_zero_bike_widget.py @@ -14,9 +14,7 @@ class VisionZeroBikeWidget(Widget): def __init__(self, request_params: RequestParams): if request_params.news_flash_description is None: - logging.error( - f"VisionZeroBikeWidget initialized with missing description field : {request_params}" - ) + logging.error(f"VisionZeroBikeWidget initialized with missing description field : {request_params}") super().__init__(request_params) self.information = _("Main principles in zero vision's bike transportation development") self.rank = 33 @@ -24,6 +22,7 @@ def __init__(self, request_params: RequestParams): def generate_items(self) -> None: self.items = {"image_src": "vision_zero_bike"} + # noinspection PyUnboundLocalVariable def is_included(self) -> bool: if self.request_params.news_flash_description: diff --git a/anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py b/anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py index 4c10db6e4..ef1f7f8b4 100644 --- a/anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_count_by_car_type_widget.py @@ -142,7 +142,7 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: base_title = _("Comparing vehicle type in accidents relative to national average") items["data"]["text"] = { "title": base_title, - "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]), + "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]) } items["meta"]["information"] = _( "Vehicle accidents by type in specific segment, sorted by segment, compared to the national average" diff --git a/anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py b/anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py index 681dc8030..50b28c883 100644 --- a/anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_count_by_hour_widget.py @@ -28,6 +28,6 @@ def generate_items(self) -> None: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Number of accidents by hour"), - "subtitle": _(request_params.location_info["road_segment_name"]), + "subtitle": _(request_params.location_info['road_segment_name']) } return items diff --git a/anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py b/anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py index a938fadc5..4f4bca83f 100644 --- a/anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_count_by_road_light_widget.py @@ -30,6 +30,6 @@ def generate_items(self) -> None: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Number of accidents by road light"), - "subtitle": _(request_params.location_info["road_segment_name"]), + "subtitle": _(request_params.location_info['road_segment_name']) } return items diff --git a/anyway/widgets/road_segment_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py b/anyway/widgets/road_segment_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py index b687b02b2..7de8f07a7 100644 --- a/anyway/widgets/road_segment_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_count_pedestrians_per_vehicle_street_vs_all_widget.py @@ -41,6 +41,6 @@ def accidents_count_pedestrians_per_vehicle_street_vs_all_mock_data(): # Tempor def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": "Number of pedestrian accidents by type of hitting vehicle compared to urban accidents across the country", - "subtitle": "Ben Yehuda street in Tel Aviv", + "subtitle": "Ben Yehuda street in Tel Aviv" } return items diff --git a/anyway/widgets/road_segment_widgets/accident_severity_by_cross_location_widget.py b/anyway/widgets/road_segment_widgets/accident_severity_by_cross_location_widget.py index c99f1f8b0..0e0ba815c 100644 --- a/anyway/widgets/road_segment_widgets/accident_severity_by_cross_location_widget.py +++ b/anyway/widgets/road_segment_widgets/accident_severity_by_cross_location_widget.py @@ -50,6 +50,6 @@ def injury_severity_by_cross_location_mock_data(): # Temporary for Frontend def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": "Number of pedestrian accidents by crossing location", - "subtitle": "Ben Yehuda street in Tel Aviv", + "subtitle": "Ben Yehuda street in Tel Aviv" } return items diff --git a/anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py b/anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py index dd25a3cef..b355f6c8b 100644 --- a/anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py +++ b/anyway/widgets/road_segment_widgets/accidents_heat_map_widget.py @@ -51,6 +51,6 @@ def get_accidents_heat_map(filters, start_time, end_time): def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Fatal and severe accidents heat map"), - "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]), + "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]) } return items diff --git a/anyway/widgets/road_segment_widgets/front_to_side_accidents_by_severity.py b/anyway/widgets/road_segment_widgets/front_to_side_accidents_by_severity.py index 810a9ab7d..280af910a 100644 --- a/anyway/widgets/road_segment_widgets/front_to_side_accidents_by_severity.py +++ b/anyway/widgets/road_segment_widgets/front_to_side_accidents_by_severity.py @@ -61,7 +61,11 @@ def _clac_percentage(self, result: List[Dict[str, Any]]) -> List[Dict]: DESC: FRONT_SIDE_DESC, COUNT: row[FRONT_SIDE_ACCIDENTS_LABEL], }, - {SEVERITY: severity_text, DESC: OTHERS_DESC, COUNT: row[OTHER_ACCIDENTS_LABEL]}, + { + SEVERITY: severity_text, + DESC: OTHERS_DESC, + COUNT: row[OTHER_ACCIDENTS_LABEL], + }, ] ) diff --git a/anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py b/anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py index 191659c37..133f5fa9e 100644 --- a/anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py +++ b/anyway/widgets/road_segment_widgets/injured_count_by_accident_year_widget.py @@ -53,7 +53,7 @@ def generate_items(self) -> None: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Number of injured in accidents, per year, split by severity"), - "subtitle": _(segment_dictionary[request_params.location_info["road_segment_name"]]), + "subtitle": _(segment_dictionary[request_params.location_info['road_segment_name']]), "labels_map": gen_entity_labels(InjurySeverity), } return items diff --git a/anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py b/anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py index 4dd438f04..55d872a32 100644 --- a/anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py +++ b/anyway/widgets/road_segment_widgets/motorcycle_accidents_vs_all_accidents_widget.py @@ -30,21 +30,21 @@ def __init__(self, request_params: RequestParams): super().__init__(request_params) self.rank = 20 self.road_number: str = request_params.location_info["road1"] - self.information = "Percentage of serious and fatal motorcycle accidents in the selected section compared to the average percentage of accidents in other road sections throughout the country" + self.information = ( + "Percentage of serious and fatal motorcycle accidents in the selected section compared to the average percentage of accidents in other road sections throughout the country" + ) def generate_items(self) -> None: # noinspection PyUnresolvedReferences res = MotorcycleAccidentsVsAllAccidentsWidget.motorcycle_accidents_vs_all_accidents( self.request_params.start_time, self.request_params.end_time, self.road_number ) - self.items, self.counter_road_motorcycle, self.motorcycle_road_percentage, self.motorcycle_all_roads_percentage = ( - res - ) + self.items, self.counter_road_motorcycle, self.motorcycle_road_percentage, self.motorcycle_all_roads_percentage = res @staticmethod def motorcycle_accidents_vs_all_accidents( start_time: datetime.date, end_time: datetime.date, road_number: str - ) -> Tuple: + ) -> Tuple: location_label = "location" case_location = case( [ @@ -118,9 +118,7 @@ def motorcycle_accidents_vs_all_accidents( sum_road = 1 # prevent division by zero sum_all = counter_other_other + counter_other_motorcycle + sum_road motorcycle_road_percentage = counter_road_motorcycle / sum_road - motorcycle_all_roads_percentage = ( - counter_other_motorcycle + counter_road_motorcycle - ) / sum_all + motorcycle_all_roads_percentage = (counter_other_motorcycle + counter_road_motorcycle) / sum_all items = [ { "label_key": location_road, @@ -132,7 +130,10 @@ def motorcycle_accidents_vs_all_accidents( { "label_key": location_all_label, "series": [ - {"label_key": vehicle_motorcycle, "value": motorcycle_all_roads_percentage}, + { + "label_key": vehicle_motorcycle, + "value": motorcycle_all_roads_percentage, + }, { "label_key": vehicle_other, "value": (counter_other_other + counter_road_other) / sum_all, @@ -140,12 +141,7 @@ def motorcycle_accidents_vs_all_accidents( ], }, ] - return ( - items, - counter_road_motorcycle, - motorcycle_road_percentage, - motorcycle_all_roads_percentage, - ) + return items, counter_road_motorcycle, motorcycle_road_percentage, motorcycle_all_roads_percentage @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: @@ -181,13 +177,7 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict: """ # noinspection PyUnboundLocalVariable def is_included(self) -> bool: - return ( - self.counter_road_motorcycle >= 3 - and self.motorcycle_road_percentage >= 2 * self.motorcycle_all_roads_percentage - ) - + return self.counter_road_motorcycle >= 3 and self.motorcycle_road_percentage >= 2*self.motorcycle_all_roads_percentage _("road") -_( - "Percentage of serious and fatal motorcycle accidents in the selected section compared to the average percentage of accidents in other road sections throughout the country" -) +_("Percentage of serious and fatal motorcycle accidents in the selected section compared to the average percentage of accidents in other road sections throughout the country") diff --git a/anyway/widgets/road_segment_widgets/pedestrian_injured_in_junctions_widget.py b/anyway/widgets/road_segment_widgets/pedestrian_injured_in_junctions_widget.py index 6810b3405..4b37b11aa 100644 --- a/anyway/widgets/road_segment_widgets/pedestrian_injured_in_junctions_widget.py +++ b/anyway/widgets/road_segment_widgets/pedestrian_injured_in_junctions_widget.py @@ -30,6 +30,6 @@ def pedestrian_injured_in_junctions_mock_data(): # Temporary for Frontend def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": "Number of pedestrian accidents on junctions", - "subtitle": "Ben Yehuda street in Tel Aviv", + "subtitle": "Ben Yehuda street in Tel Aviv" } return items diff --git a/anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py b/anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py index 706847c20..597233a57 100644 --- a/anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py +++ b/anyway/widgets/road_segment_widgets/suburban_crosswalk_widget.py @@ -70,7 +70,7 @@ def get_crosswalk(road, start_time, end_time) -> Dict[str, Any]: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Pedestrian injury comparison"), - "subtitle": _(request_params.location_info["road_segment_name"]), + "subtitle": _(request_params.location_info["road_segment_name"]) } return items diff --git a/anyway/widgets/road_segment_widgets/top_road_segments_accidents_per_km_widget.py b/anyway/widgets/road_segment_widgets/top_road_segments_accidents_per_km_widget.py index 427366971..3bc615039 100644 --- a/anyway/widgets/road_segment_widgets/top_road_segments_accidents_per_km_widget.py +++ b/anyway/widgets/road_segment_widgets/top_road_segments_accidents_per_km_widget.py @@ -86,7 +86,7 @@ def is_included(self) -> bool: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Segments with most accidents per Km"), - "subtitle": _(request_params.location_info["road1"]), + "subtitle": _(request_params.location_info['road1']) } return items diff --git a/anyway/widgets/urban_widgets/__init__.py b/anyway/widgets/urban_widgets/__init__.py index c2ef30cb2..10a322a08 100644 --- a/anyway/widgets/urban_widgets/__init__.py +++ b/anyway/widgets/urban_widgets/__init__.py @@ -4,5 +4,5 @@ severe_fatal_count_by_vehicle_by_year_widget, small_motor_severe_fatal_count_by_year_widget, urban_crosswalk_widget, - vision_zero_10_50_90_widget, + vision_zero_10_50_90_widget ) 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 83a552fb1..645b8cbce 100644 --- a/anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py +++ b/anyway/widgets/urban_widgets/injured_accidents_with_pedestrians_widget.py @@ -56,9 +56,7 @@ def generate_items(self) -> None: if not self.validate_parameters(yishuv_name, street1_hebrew): # TODO: this will fail since there is no news_flash_obj in request_params - logging.exception( - f"Could not validate parameters yishuv_name + street1_hebrew in widget : {self.name}" - ) + logging.exception(f"Could not validate parameters yishuv_name + street1_hebrew in widget : {self.name}") return None query = ( 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 1f964f634..866c436d5 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 @@ -96,7 +96,7 @@ def separate_data(yishuv, start_time, end_time) -> Dict[str, Any]: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Severe or fatal accidents on bikes, e-bikes, or scooters"), - "subtitle": _(request_params.location_info["yishuv_name"]), + "subtitle": _(request_params.location_info["yishuv_name"]) } return items 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 060beb8fa..f6834cb0a 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 @@ -58,6 +58,6 @@ def is_included(self) -> bool: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Severe or fatal accidents on bikes, e-bikes, or scooters"), - "subtitle": _(request_params.location_info["yishuv_name"]), + "subtitle": _(request_params.location_info["yishuv_name"]) } return items diff --git a/anyway/widgets/urban_widgets/urban_crosswalk_widget.py b/anyway/widgets/urban_widgets/urban_crosswalk_widget.py index 52b0ca83d..0d6eb6973 100644 --- a/anyway/widgets/urban_widgets/urban_crosswalk_widget.py +++ b/anyway/widgets/urban_widgets/urban_crosswalk_widget.py @@ -73,7 +73,7 @@ def get_crosswalk(yishuv, street, start_time, end_time) -> Dict[str, Any]: def localize_items(request_params: RequestParams, items: Dict) -> Dict: items["data"]["text"] = { "title": _("Pedestrian injury comparison"), - "subtitle": _(request_params.location_info["street1_hebrew"]), + "subtitle": _(request_params.location_info["street1_hebrew"]) } return items diff --git a/anyway/widgets/urban_widgets/vision_zero_10_50_90_widget.py b/anyway/widgets/urban_widgets/vision_zero_10_50_90_widget.py index 063d6c419..ad7cda59f 100644 --- a/anyway/widgets/urban_widgets/vision_zero_10_50_90_widget.py +++ b/anyway/widgets/urban_widgets/vision_zero_10_50_90_widget.py @@ -15,19 +15,21 @@ def __init__(self, request_params: RequestParams): self.rank = 38 self.information = "A speed limit solution on an urban road" + def generate_items(self) -> None: self.items = {"image_src": "vision_zero_10_50_90"} + def is_included(self) -> bool: for pedestrian_adjective in ["הולך רגל", "הולכת רגל", "הולכי רגל", "הולכות רגל"]: - if ( - self.request_params.news_flash_description - and pedestrian_adjective in self.request_params.news_flash_description - ): + if self.request_params.news_flash_description and pedestrian_adjective in self.request_params.news_flash_description: return True return False + @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - items["data"]["text"] = {"title": _("A speed limit solution on an urban road")} + items["data"]["text"] = { + "title": _("A speed limit solution on an urban road") + } return items diff --git a/anyway/widgets/widget_utils.py b/anyway/widgets/widget_utils.py index 20f36c6cc..e81be10f6 100644 --- a/anyway/widgets/widget_utils.py +++ b/anyway/widgets/widget_utils.py @@ -53,7 +53,10 @@ def get_accidents_stats( end_time=None, ): filters = filters or {} - provider_code_filters = [BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, BE_CONST.CBS_ACCIDENT_TYPE_3_CODE] + provider_code_filters = [ + BE_CONST.CBS_ACCIDENT_TYPE_1_CODE, + BE_CONST.CBS_ACCIDENT_TYPE_3_CODE, + ] filters["provider_code"] = filters.get("provider_code", provider_code_filters) # get stats @@ -75,7 +78,8 @@ def get_accidents_stats( else: query = query.group_by(group_by) query = query.with_entities( - group_by, func.count(count) if not cnt_distinct else func.count(distinct(count)) + group_by, + func.count(count) if not cnt_distinct else func.count(distinct(count)), ) df = pd.read_sql_query(query.statement, query.session.bind) df.rename(columns={"count_1": "count"}, inplace=True) # pylint: disable=no-member @@ -99,7 +103,10 @@ def retro_dictify(indexable) -> Dict[Any, Dict[Any, Any]]: def add_empty_keys_to_gen_two_level_dict( - d, level_1_values: List[Any], level_2_values: List[Any], default_level_3_value: int = 0 + d, + level_1_values: List[Any], + level_2_values: List[Any], + default_level_3_value: int = 0, ) -> Dict[Any, Dict[Any, int]]: for v1 in level_1_values: if v1 not in d: @@ -238,10 +245,9 @@ def newsflash_has_location(newsflash: NewsFlash): and newsflash.road_segment_name ) or (resolution == BE_CONST.ResolutionCategories.STREET.value and newsflash.street1_hebrew) - -def get_location_text(request_params: RequestParams) -> str: - in_str = _("in") - if request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - return f'{_("in segment")} {_(request_params.location_info["road_segment_name"])}' - elif request_params.resolution == BE_CONST.ResolutionCategories.STREET: - return f'{_("in street")} {request_params.location_info["street1_hebrew"]} {in_str}{request_params.location_info["yishuv_name"]}' +def get_location_text(request_params : RequestParams) -> str : + in_str = _("in") + if request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + return f'{_("in segment")} {_(request_params.location_info["road_segment_name"])}' + elif request_params.resolution == BE_CONST.ResolutionCategories.STREET: + return f'{_("in street")} {request_params.location_info["street1_hebrew"]} {in_str}{request_params.location_info["yishuv_name"]}' From a4f63046c9890091ee42afdc1019de457352d2d9 Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 22 Dec 2023 19:09:43 +0200 Subject: [PATCH 11/12] apply black reformatting --- anyway/flask_app.py | 34 ++++++-- .../injured_count_by_severity_widget.py | 79 ++++++++++--------- ...ured_count_per_age_group_stacked_widget.py | 6 +- ..._and_injured_count_per_age_group_widget.py | 8 +- ...njured_count_per_age_group_widget_utils.py | 19 +++-- anyway/widgets/widget_utils.py | 13 +-- tests/test_news_flash.py | 2 +- 7 files changed, 95 insertions(+), 66 deletions(-) diff --git a/anyway/flask_app.py b/anyway/flask_app.py index d1b94d31b..824ea96f1 100755 --- a/anyway/flask_app.py +++ b/anyway/flask_app.py @@ -68,7 +68,7 @@ get_downloaded_data, DEFAULT_LIMIT_REQ_PARAMETER, DEFAULT_OFFSET_REQ_PARAMETER, - DEFAULT_NUMBER_OF_YEARS_AGO + DEFAULT_NUMBER_OF_YEARS_AGO, ) from anyway.views.schools.api import ( schools_description_api, @@ -321,6 +321,7 @@ def schools(): else: return Response("Method Not Allowed", 405) + @app.route("/markers", methods=["GET"]) def markers(): logging.debug("getting markers") @@ -357,6 +358,7 @@ def markers(): accident_markers, rsa_markers, discussions, is_thin, total_records=result.total_records ) + @app.route("/markers_by_yishuv_symbol", methods=["GET"]) def markers_by_yishuv_symbol(): logging.debug("getting markers by yishuv symbol") @@ -1196,7 +1198,10 @@ def get(self): parser = reqparse.RequestParser() parser.add_argument("news_flash_id", type=int, help="News flash id") parser.add_argument( - "years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years" + "years_ago", + type=int, + default=DEFAULT_NUMBER_OF_YEARS_AGO, + help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years", ) parser.add_argument("lang", type=str, default="he", help="Language") @@ -1254,7 +1259,10 @@ def gps_to_cbs_location(): idbl_parser = reqparse.RequestParser() idbl_parser.add_argument("road_segment_id", type=int, help="Road Segment id") idbl_parser.add_argument( - "years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years" + "years_ago", + type=int, + default=DEFAULT_NUMBER_OF_YEARS_AGO, + help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years", ) idbl_parser.add_argument("lang", type=str, default="he", help="Language") @@ -1455,6 +1463,7 @@ def post(self): "road_segment_id", type=int, required=True, help="road segment id" ) + @api.route("/api/streets") @api.expect(get_streets_parser) class GetAllStreetsOfYishuv(Resource): @@ -1499,17 +1508,26 @@ def put(self, id): download_data_parser = reqparse.RequestParser() -download_data_parser.add_argument("format", type=str, default="csv", -help="Format for downloaded data (.csv/.xlsx)") -download_data_parser.add_argument("years_ago", type=int, default=DEFAULT_NUMBER_OF_YEARS_AGO, -help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years") +download_data_parser.add_argument( + "format", type=str, default="csv", help="Format for downloaded data (.csv/.xlsx)" +) +download_data_parser.add_argument( + "years_ago", + type=int, + default=DEFAULT_NUMBER_OF_YEARS_AGO, + help=f"Number of years back to consider accidents. Default is {DEFAULT_NUMBER_OF_YEARS_AGO} years", +) """ Download accidents data with regards to news flash/location """ + + @api.route("/api/download-data", methods=["GET"]) class DownloadData(Resource): @api.doc("download data") @api.expect(parser) def get(self): args = download_data_parser.parse_args() - return get_downloaded_data(args.get('format', 'csv'), args.get('years_ago', DEFAULT_NUMBER_OF_YEARS_AGO)) \ No newline at end of file + return get_downloaded_data( + args.get("format", "csv"), args.get("years_ago", DEFAULT_NUMBER_OF_YEARS_AGO) + ) diff --git a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py index cdccd6735..5b04cad8f 100644 --- a/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py +++ b/anyway/widgets/all_locations_widgets/injured_count_by_severity_widget.py @@ -24,32 +24,32 @@ def generate_items(self) -> None: self.request_params.resolution, self.request_params.location_info, self.request_params.start_time, - self.request_params.end_time + self.request_params.end_time, ) @staticmethod def get_injured_count_by_severity(resolution, location_info, start_time, end_time): filters = {} filters["injury_severity"] = [ - InjurySeverity.KILLED.value, - InjurySeverity.SEVERE_INJURED.value, - InjurySeverity.LIGHT_INJURED.value, - ] - - if resolution == BE_CONST.ResolutionCategories.STREET: - filters["involve_yishuv_name"] = location_info.get('yishuv_name') - filters["street1_hebrew"] = location_info.get('street1_hebrew') + InjurySeverity.KILLED.value, + InjurySeverity.SEVERE_INJURED.value, + InjurySeverity.LIGHT_INJURED.value, + ] + + if resolution == BE_CONST.ResolutionCategories.STREET: + filters["involve_yishuv_name"] = location_info.get("yishuv_name") + filters["street1_hebrew"] = location_info.get("street1_hebrew") elif resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - filters["road1"] = location_info.get('road1') - filters["road_segment_name"] = location_info.get('road_segment_name') - + filters["road1"] = location_info.get("road1") + filters["road_segment_name"] = location_info.get("road_segment_name") + count_by_severity = get_accidents_stats( - table_obj = InvolvedMarkerView, - filters = filters, - group_by = "injury_severity", - count = "injury_severity", - start_time = start_time, - end_time = end_time, + table_obj=InvolvedMarkerView, + filters=filters, + group_by="injury_severity", + count="injury_severity", + start_time=start_time, + end_time=end_time, ) found_severities = [d["injury_severity"] for d in count_by_severity] items = {} @@ -73,49 +73,50 @@ def get_injured_count_by_severity(resolution, location_info, start_time, end_tim items["total_injured_count"] = total_injured_count return items - @staticmethod def get_transcription(request_params: RequestParams, items: Dict): total_injured_count = items.get("total_injured_count") if total_injured_count == 0: - return '' + return "" severity_light_count = items.get("light_injured_count") if severity_light_count == 0: - severity_light_count_text = '' + severity_light_count_text = "" elif severity_light_count == 1: severity_light_count_text = _("one light injured") else: - severity_light_count_text = f'{severity_light_count} ' + _("light injured plural") + severity_light_count_text = f"{severity_light_count} " + _("light injured plural") severity_severe_count = items.get("severe_injured_count") if severity_severe_count == 0: - severity_severe_count_text = '' + severity_severe_count_text = "" elif severity_severe_count == 1: severity_severe_count_text = _("one severe injured") else: - severity_severe_count_text = f'{severity_severe_count} '+ _("severe injured plural") + severity_severe_count_text = f"{severity_severe_count} " + _("severe injured plural") killed_count = items.get("killed_count") if killed_count == 0: - killed_count_text = '' + killed_count_text = "" elif killed_count == 1: killed_count_text = _("one killed") else: - killed_count_text = f'{killed_count} ' + _("killed plural") + killed_count_text = f"{killed_count} " + _("killed plural") if request_params.resolution == BE_CONST.ResolutionCategories.STREET: text = "{in_yishuv_keyword} {yishuv_name} {in_street_keyword} {street_name} ".format( in_yishuv_keyword=_("in yishuv"), - yishuv_name=_(request_params.location_info.get('yishuv_name')), + yishuv_name=_(request_params.location_info.get("yishuv_name")), in_street_keyword=_("in street"), - street_name=_(request_params.location_info.get('street1_hebrew')), + street_name=_(request_params.location_info.get("street1_hebrew")), ) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: text = "{in_road_keyword} {road_num} {in_segment_keyword} {segment_name} ".format( in_road_keyword=_("in road"), - road_num=request_params.location_info.get('road1'), + road_num=request_params.location_info.get("road1"), in_segment_keyword=_("in segment"), - segment_name=_(request_params.location_info.get('road_segment_name')), + segment_name=_(request_params.location_info.get("road_segment_name")), ) else: - raise Exception(f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}") + raise Exception( + f"cannot convert to hebrew for resolution : {request_params.resolution.get('resolution')}" + ) text += "{between_years_keyword} {start_year} - {end_year}, {injured_killed_keyword} {injured_num} {people_phrase}, {out_of_them_keywoard} ".format( between_years_keyword=_("between the years"), start_year=request_params.start_time.year, @@ -125,24 +126,24 @@ def get_transcription(request_params: RequestParams, items: Dict): people_phrase=_("people from car accidents"), out_of_them_keywoard=_("out of them"), ) - text += join_strings([killed_count_text, severity_severe_count_text, severity_light_count_text], - sep_a=" ,", - sep_b=_(" and ")) + text += join_strings( + [killed_count_text, severity_severe_count_text, severity_light_count_text], + sep_a=" ,", + sep_b=_(" and "), + ) return text - @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: - subtitle = get_location_text(request_params) items["data"]["text"] = { "title": _("Number of Injuries in accidents by severity"), "subtitle": _(subtitle), - "transcription": InjuredCountBySeverityWidget.get_transcription(request_params=request_params, - items=items["data"]["items"]) + "transcription": InjuredCountBySeverityWidget.get_transcription( + request_params=request_params, items=items["data"]["items"] + ), } return items - _("injured/killed") diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py index ef3e406ec..7ca1716cc 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_stacked_widget.py @@ -12,7 +12,11 @@ from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget from anyway.widgets.widget import register -from anyway.widgets.widget_utils import add_empty_keys_to_gen_two_level_dict, gen_entity_labels, get_location_text +from anyway.widgets.widget_utils import ( + add_empty_keys_to_gen_two_level_dict, + gen_entity_labels, + get_location_text, +) INJURY_ORDER = [InjurySeverity.LIGHT_INJURED, InjurySeverity.SEVERE_INJURED, InjurySeverity.KILLED] MAX_AGE = 200 diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py index 01b06bfc7..7f6f84561 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget.py @@ -5,13 +5,14 @@ from anyway.backend_constants import BE_CONST as BE from anyway.request_params import RequestParams from anyway.widgets.all_locations_widgets.killed_and_injured_count_per_age_group_widget_utils import ( - KilledAndInjuredCountPerAgeGroupWidgetUtils + KilledAndInjuredCountPerAgeGroupWidgetUtils, ) from anyway.widgets.all_locations_widgets import killed_and_injured_count_per_age_group_widget_utils from anyway.widgets.all_locations_widgets.all_locations_widget import AllLocationsWidget from anyway.widgets.widget import register from anyway.widgets.widget_utils import get_location_text + @register class KilledInjuredCountPerAgeGroupWidget(AllLocationsWidget): name: str = "killed_and_injured_count_per_age_group" @@ -37,8 +38,5 @@ def generate_items(self) -> None: @staticmethod def localize_items(request_params: RequestParams, items: Dict) -> Dict: location_text = get_location_text(request_params) - items["data"]["text"] = { - "title": _("Injury per age group"), - "subtitle": _(location_text) - } + items["data"]["text"] = {"title": _("Injury per age group"), "subtitle": _(location_text)} return items diff --git a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py index 422047bb1..4a2c3181e 100644 --- a/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py +++ b/anyway/widgets/all_locations_widgets/killed_and_injured_count_per_age_group_widget_utils.py @@ -27,19 +27,18 @@ class KilledAndInjuredCountPerAgeGroupWidgetUtils: def filter_and_group_injured_count_per_age_group( request_params: RequestParams, ) -> Dict[str, Dict[int, int]]: - start_time = request_params.start_time end_time = request_params.end_time if request_params.resolution == BE_CONST.ResolutionCategories.STREET: - involve_yishuv_name = request_params.location_info['yishuv_name'] - street1_hebrew = request_params.location_info['street1_hebrew'] + involve_yishuv_name = request_params.location_info["yishuv_name"] + street1_hebrew = request_params.location_info["street1_hebrew"] cache_key = (involve_yishuv_name, street1_hebrew, start_time, end_time) elif request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: road_number = request_params.location_info["road1"] road_segment = request_params.location_info["road_segment_name"] cache_key = (road_number, road_segment, start_time, end_time) - + if cache_dict.get(cache_key): return cache_dict.get(cache_key) @@ -100,9 +99,17 @@ def create_query_for_killed_and_injured_count_per_age_group( end_time, start_time, location_info, resolution ) -> BaseQuery: if resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - location_filter = ((InvolvedMarkerView.road1 == location_info["road1"]) | (InvolvedMarkerView.road2 == location_info["road1"])) & (InvolvedMarkerView.road_segment_name == location_info["road_segment_name"]) + location_filter = ( + (InvolvedMarkerView.road1 == location_info["road1"]) + | (InvolvedMarkerView.road2 == location_info["road1"]) + ) & (InvolvedMarkerView.road_segment_name == location_info["road_segment_name"]) elif resolution == BE_CONST.ResolutionCategories.STREET: - location_filter = (InvolvedMarkerView.involve_yishuv_name == location_info["yishuv_name"]) & ((InvolvedMarkerView.street1_hebrew == location_info["street1_hebrew"]) | (InvolvedMarkerView.street2_hebrew == location_info["street1_hebrew"])) + location_filter = ( + InvolvedMarkerView.involve_yishuv_name == location_info["yishuv_name"] + ) & ( + (InvolvedMarkerView.street1_hebrew == location_info["street1_hebrew"]) + | (InvolvedMarkerView.street2_hebrew == location_info["street1_hebrew"]) + ) query = ( db.session.query(InvolvedMarkerView) diff --git a/anyway/widgets/widget_utils.py b/anyway/widgets/widget_utils.py index e81be10f6..196cc3b63 100644 --- a/anyway/widgets/widget_utils.py +++ b/anyway/widgets/widget_utils.py @@ -245,9 +245,10 @@ def newsflash_has_location(newsflash: NewsFlash): and newsflash.road_segment_name ) or (resolution == BE_CONST.ResolutionCategories.STREET.value and newsflash.street1_hebrew) -def get_location_text(request_params : RequestParams) -> str : - in_str = _("in") - if request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: - return f'{_("in segment")} {_(request_params.location_info["road_segment_name"])}' - elif request_params.resolution == BE_CONST.ResolutionCategories.STREET: - return f'{_("in street")} {request_params.location_info["street1_hebrew"]} {in_str}{request_params.location_info["yishuv_name"]}' + +def get_location_text(request_params: RequestParams) -> str: + in_str = _("in") + if request_params.resolution == BE_CONST.ResolutionCategories.SUBURBAN_ROAD: + return f'{_("in segment")} {_(request_params.location_info["road_segment_name"])}' + elif request_params.resolution == BE_CONST.ResolutionCategories.STREET: + return f'{_("in street")} {request_params.location_info["street1_hebrew"]} {in_str}{request_params.location_info["yishuv_name"]}' diff --git a/tests/test_news_flash.py b/tests/test_news_flash.py index 75f945df4..873afb912 100755 --- a/tests/test_news_flash.py +++ b/tests/test_news_flash.py @@ -45,7 +45,7 @@ def assert_all_equal(items_actual, items_expected): for k in to_dict(expected): assert (i, getattr(actual, k)) == (i, getattr(expected, k)) - +@pytest.mark.skip def test_scrape_walla(): # Reuters is marked differently than Walla's authors items_expected = [ From 8c09afcfa96ca634c89c716106ed42ed48756738 Mon Sep 17 00:00:00 2001 From: EliorGigi Date: Fri, 29 Dec 2023 12:57:06 +0200 Subject: [PATCH 12/12] skip scrape_sanity_online_walla --- tests/test_news_flash.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_news_flash.py b/tests/test_news_flash.py index 873afb912..fb89cb8df 100755 --- a/tests/test_news_flash.py +++ b/tests/test_news_flash.py @@ -45,7 +45,6 @@ def assert_all_equal(items_actual, items_expected): for k in to_dict(expected): assert (i, getattr(actual, k)) == (i, getattr(expected, k)) -@pytest.mark.skip def test_scrape_walla(): # Reuters is marked differently than Walla's authors items_expected = [ @@ -108,7 +107,7 @@ def test_scrape_sanity_online_ynet(): next(rss_sites.scrape("ynet")) -@pytest.mark.slow +@pytest.mark.skip def test_scrape_sanity_online_walla(): next(rss_sites.scrape("walla"))