Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature 2373- move widgets to all locations #2511

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion anyway/flask_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down
5 changes: 4 additions & 1 deletion anyway/widgets/all_locations_widgets/__init__.py
Original file line number Diff line number Diff line change
@@ -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
)
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
from typing import Dict

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.widgets.widget_utils import get_accidents_stats, join_strings, get_location_text
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__]

Expand All @@ -22,29 +21,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 = {}
Expand Down Expand Up @@ -128,13 +133,16 @@ def get_transcription(request_params: RequestParams, items: Dict):

@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": _(request_params.location_info['road_segment_name']),
"subtitle": _(subtitle),
"transcription": InjuredCountBySeverityWidget.get_transcription(request_params=request_params,
items=items["data"]["items"])
}
return items



_("injured/killed")
Expand All @@ -144,4 +152,4 @@ def localize_items(request_params: RequestParams, items: Dict) -> Dict:
_("one severe injured")
_("severe injured plural")
_("one light injured")
_("light injured plural")
_("light injured plural")
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@

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
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


@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__]

Expand Down Expand Up @@ -48,9 +48,10 @@ 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": _("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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@

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
from anyway.widgets.widget_utils import get_location_text

@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__]

Expand All @@ -35,8 +36,9 @@ 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": f'{_("in segment")} {_(request_params.location_info["road_segment_name"])}',
"subtitle": _(location_text)
}
return items
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand All @@ -122,4 +132,4 @@ def create_query_for_killed_and_injured_count_per_age_group(
)
.order_by(asc(InvolvedMarkerView.age_group))
)
return query
return query
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 0 additions & 3 deletions anyway/widgets/road_segment_widgets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
)
8 changes: 8 additions & 0 deletions anyway/widgets/widget_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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"]}'
Loading
Loading