Repository: data-for-change/anyway

Issue:
Modify most_severe_accidents_table Widget
Relevant file: anyway/infographics_utils.py
Widget name: most_severe_accidents_table
Relevant function: get_most_severe_accidents_table
1. Separate severe (severity 2) and light injured (severity 3) to two different fields in the API: severe_injured_count and light_injured_count. 
For now keep the injured_count field in the API for compatibility
2. After FE will adjust to this change, remove the injured_count field


Discussion:

Resolving patch:
diff --git a/anyway/infographics_utils.py b/anyway/infographics_utils.py
--- a/anyway/infographics_utils.py
+++ b/anyway/infographics_utils.py
@@ -58,11 +58,11 @@ def serialize(self):
 def extract_news_flash_location(news_flash_id):
     news_flash_obj = db.session.query(NewsFlash).filter(NewsFlash.id == news_flash_id).first()
     if not news_flash_obj:
-        logging.warn("could not find news flash id {}".format(news_flash_id))
+        logging.warning(f"could not find news flash id {str(news_flash_id)}")
         return None
     resolution = news_flash_obj.resolution if news_flash_obj.resolution else None
     if not news_flash_obj or not resolution or resolution not in resolution_dict:
-        logging.warn("could not find valid resolution for news flash id {}".format(news_flash_id))
+        logging.warning(f"could not find valid resolution for news flash id {str(news_flash_id)}")
         return None
     data = {"resolution": resolution}
     for field in resolution_dict[resolution]:
@@ -110,7 +110,7 @@ def get_accident_count_by_accident_type(location_info, start_time, end_time):
 
 
 def get_top_road_segments_accidents_per_km(
-    resolution, location_info, start_time=None, end_time=None, limit=5
+        resolution, location_info, start_time=None, end_time=None, limit=5
 ):
     if resolution != "כביש בינעירוני":  # relevent for non urban roads only
         return {}
@@ -126,19 +126,19 @@ def get_top_road_segments_accidents_per_km(
             (RoadSegments.to_km - RoadSegments.from_km).label("segment_length"),
             cast(
                 (
-                    func.count(AccidentMarkerView.road_segment_name)
-                    / (RoadSegments.to_km - RoadSegments.from_km)
+                        func.count(AccidentMarkerView.road_segment_name)
+                        / (RoadSegments.to_km - RoadSegments.from_km)
                 ),
                 Numeric(10, 4),
             ).label("accidents_per_km"),
         )
-        .filter(AccidentMarkerView.road1 == RoadSegments.road)
-        .filter(AccidentMarkerView.road_segment_number == RoadSegments.segment)
-        .filter(AccidentMarkerView.road1 == location_info["road1"])
-        .filter(AccidentMarkerView.road_segment_name is not None)
-        .group_by(AccidentMarkerView.road_segment_name, RoadSegments.from_km, RoadSegments.to_km)
-        .order_by(desc("accidents_per_km"))
-        .limit(limit)
+            .filter(AccidentMarkerView.road1 == RoadSegments.road)
+            .filter(AccidentMarkerView.road_segment_number == RoadSegments.segment)
+            .filter(AccidentMarkerView.road1 == location_info["road1"])
+            .filter(AccidentMarkerView.road_segment_name is not None)
+            .group_by(AccidentMarkerView.road_segment_name, RoadSegments.from_km, RoadSegments.to_km)
+            .order_by(desc("accidents_per_km"))
+            .limit(limit)
     )
 
     result = pd.read_sql_query(query.statement, query.session.bind)
@@ -146,7 +146,7 @@ def get_top_road_segments_accidents_per_km(
 
 
 def get_accidents_stats(
-    table_obj, filters=None, group_by=None, count=None, start_time=None, end_time=None
+        table_obj, filters=None, group_by=None, count=None, start_time=None, end_time=None
 ):
     filters = filters or {}
     filters["provider_code"] = [
@@ -179,7 +179,7 @@ def get_injured_filters(location_info):
 
 
 def get_most_severe_accidents_with_entities(
-    table_obj, filters, entities, start_time, end_time, limit=10
+        table_obj, filters, entities, start_time, end_time, limit=10
 ):
     filters = filters or {}
     filters["provider_code"] = [
@@ -255,8 +255,8 @@ def filter_and_group_injured_count_per_age_group(data_of_ages):
         for item in range_dict.items():
             item_min_range, item_max_range = item
             if (
-                item_min_range <= min_age <= item_max_range
-                and item_min_range <= max_age <= item_max_range
+                    item_min_range <= min_age <= item_max_range
+                    and item_min_range <= max_age <= item_max_range
             ):
                 string_age_range = f"{item_min_range:02}-{item_max_range:02}"
                 dict_by_required_age_group[string_age_range] += count
@@ -319,14 +319,19 @@ def get_most_severe_accidents_table(location_info, start_time, end_time):
         dt = accident["accident_timestamp"].to_pydatetime()
         accident["date"] = dt.strftime("%d/%m/%y")
         accident["hour"] = dt.strftime("%H:%M")
-        num = get_casualties_count_in_accident(
+        accident["killed_count"] = get_casualties_count_in_accident(
             accident["id"], accident["provider_code"], 1, accident["accident_year"]
         )
-        accident["killed_count"] = num
-        num = get_casualties_count_in_accident(
-            accident["id"], accident["provider_code"], [2, 3], accident["accident_year"]
+        accident["severe_injured_count"] = get_casualties_count_in_accident(
+            accident["id"], accident["provider_code"], 2, accident["accident_year"]
+        )
+        accident["light_injured_count"] = get_casualties_count_in_accident(
+            accident["id"], accident["provider_code"], 3, accident["accident_year"]
+        )
+        # TODO: remove injured_count after FE adaptation to light and severe counts
+        accident["injured_count"] = (
+                accident["severe_injured_count"] + accident["light_injured_count"]
         )
-        accident["injured_count"] = num
         del (
             accident["accident_timestamp"],
             accident["accident_type"],
@@ -345,8 +350,8 @@ def count_accidents_by_driver_type(data):
         elif vehicle_type in BE_CONST.PRIVATE_DRIVER_VEHICLE_TYPES:
             driver_types[driver_type_hebrew_dict["private_vehicle_driver"]] += count
         elif (
-            vehicle_type in BE_CONST.LIGHT_ELECTRIC_VEHICLE_TYPES
-            or vehicle_type in BE_CONST.OTHER_VEHICLES_TYPES
+                vehicle_type in BE_CONST.LIGHT_ELECTRIC_VEHICLE_TYPES
+                or vehicle_type in BE_CONST.OTHER_VEHICLES_TYPES
         ):
             driver_types[driver_type_hebrew_dict["other_driver"]] += count
     output = []
@@ -528,13 +533,21 @@ def percentage_accidents_by_car_type_national_data_cache(start_time, end_time):
     return percentage_accidents_by_car_type(involved_by_vehicle_type_data)
 
 
-def stats_accidents_by_car_type_with_national_data(involved_by_vehicle_type_data, start_time, end_time):
+def stats_accidents_by_car_type_with_national_data(
+        involved_by_vehicle_type_data, start_time, end_time
+):
     out = []
     data_by_segment = percentage_accidents_by_car_type(involved_by_vehicle_type_data)
     national_data = percentage_accidents_by_car_type_national_data_cache(start_time, end_time)
 
     for k, v in national_data.items():  # pylint: disable=W0612
-        out.append({'car_type': k, 'percentage_segment': data_by_segment[k], 'percentage_country': national_data[k]})
+        out.append(
+            {
+                "car_type": k,
+                "percentage_segment": data_by_segment[k],
+                "percentage_country": national_data[k],
+            }
+        )
 
     return out
 
@@ -776,7 +789,9 @@ def create_infographics_data(news_flash_id, number_of_years_ago):
     accident_count_by_car_type = Widget(
         name="accident_count_by_car_type",
         rank=17,
-        items=stats_accidents_by_car_type_with_national_data(involved_by_vehicle_type_data, start_time, end_time),
+        items=stats_accidents_by_car_type_with_national_data(
+            involved_by_vehicle_type_data, start_time, end_time
+        ),
     )
     output["widgets"].append(accident_count_by_car_type.serialize())
 


Test patch: