Skip to content

Commit

Permalink
Finalised unit tests for HTML report and create TemplateHTML class
Browse files Browse the repository at this point in the history
  • Loading branch information
CBROWN-ONS committed Aug 11, 2023
1 parent 1df791f commit fba1a60
Show file tree
Hide file tree
Showing 6 changed files with 409 additions and 202 deletions.
128 changes: 128 additions & 0 deletions src/transport_performance/gtfs/report/report_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""Utils to assist in the creation of a HTML report for GTFS."""
from typing import Union
import pathlib
import shutil
import os

from transport_performance.utils.defence import (
_bool_defence,
_string_defence,
_is_path_like,
)


class TemplateHTML:
"""A class for inserting HTML string into a docstring."""

def __init__(self, path: Union[str, pathlib.Path]) -> None:
"""Initialise the TemplateHTML object.
Parameters
----------
path : Union[str, pathlib.Path]
The file path of the html template
Returns
-------
None
"""
_is_path_like(path, "path")
with open(path, "r", encoding="utf8") as f:
self.template = f.read()
return None

def insert(
self, placeholder: str, value: str, replace_multiple: bool = False
) -> None:
"""Insert values into the html template.
Parameters
----------
placeholder : str
The placeholder name in the template.
This is a string. In the template it
should be surrounded by sqsuare brackets.
value : str
The value to place in the placeholder
location.
replace_multiple : bool, optional
Whether or not to replace multiple
placeholders that share the same
placeholder value,
by default False
Returns
-------
None
"""
_string_defence(placeholder, "placeholder")
_string_defence(value, "value")
_bool_defence(replace_multiple, "replace_multiple")
occurences = len(self.template.split(f"[{placeholder}]")) - 1
if occurences > 1 and not replace_multiple:
raise ValueError(
"You have selected not to replace multiple"
"placeholders of the same value, however"
"placeholders occur more than once. \n"
"If you would like to allow this, set the"
"replace_multiple param to True"
)

self.template = self.template.replace(f"[{placeholder}]", value)

def get_template(self) -> str:
"""Get the template attribute of the TemplateHTML object.
Returns
-------
str
The template attribute
"""
return self.template


def set_up_report_dir(
path: Union[str, pathlib.Path] = "outputs", overwrite: bool = False
) -> None:
"""Set up the directory that will hold the report.
Parameters
----------
path : Union[str, pathlib.Path], optional
The path to the directory,
by default "outputs"
overwrite : bool, optional
Whether or not to overwrite any current reports,
by default False
Returns
-------
None
"""
# defences
if not os.path.exists(path):
raise FileNotFoundError(
"The specified path does not exist. " f"Path passed: {str(path)}"
)

if os.path.exists(f"{path}/gtfs_report") and not overwrite:
raise FileExistsError(
"Report already exists at path: "
f"[{path}]."
"Consider setting overwrite=True"
"if you'd like to overwrite this."
)

try:
os.mkdir(f"{path}/gtfs_report")
except FileExistsError:
pass
shutil.copy(
src="src/transport_performance/gtfs/report/css_styles/styles.css",
dst=f"{path}/gtfs_report",
)
return None
125 changes: 0 additions & 125 deletions src/transport_performance/gtfs/report/utils.py

This file was deleted.

66 changes: 25 additions & 41 deletions src/transport_performance/gtfs/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@
_dict_defence,
_string_and_nonetype_defence,
)
from transport_performance.gtfs.report.utils import (
read_html_template,
insert_into_template,
from transport_performance.gtfs.report.report_utils import (
TemplateHTML,
set_up_report_dir,
)
from transport_performance.gtfs.utils import convert_pandas_to_plotly
Expand Down Expand Up @@ -1051,26 +1050,23 @@ def html_report(
# feed evaluation
self.clean_feed()
validation_dataframe = self.is_valid()
eval_temp = read_html_template(
location=(
eval_temp = TemplateHTML(
path=(
"src/transport_performance/gtfs/report/"
"html_templates/evaluation_template.html"
)
)
eval_temp = insert_into_template(
eval_temp,
eval_temp.insert(
"eval_placeholder_1",
convert_pandas_to_plotly(validation_dataframe, True),
)
eval_temp = insert_into_template(
eval_temp, "eval_title_1", "GTFS Feed Evalulation"
)
eval_temp = insert_into_template(eval_temp, "date", date)
eval_temp.insert("eval_title_1", "GTFS Feed Evalulation")
eval_temp.insert("date", date)

with open(
f"{report_dir}/gtfs_report/index.html", "w", encoding="utf8"
) as eval_f:
eval_f.writelines(eval_temp)
eval_f.writelines(eval_temp.get_template())

# stops
self.viz_stops(out_pth=f"{report_dir}/gtfs_report/stop_locations.html")
Expand All @@ -1079,29 +1075,23 @@ def html_report(
geoms="hull",
geom_crs=27700,
)
stops_temp = read_html_template(
stops_temp = TemplateHTML(
(
"src/transport_performance/gtfs/report/"
"html_templates/stops_template.html"
)
)
stops_temp = insert_into_template(
stops_temp, "stops_placeholder_1", "stop_locations.html"
)
stops_temp = insert_into_template(
stops_temp, "stops_placeholder_2", "convex_hull.html"
)
stops_temp = insert_into_template(
stops_temp, "stops_title_1", "Stops from GTFS data"
stops_temp.insert("stops_placeholder_1", "stop_locations.html")
stops_temp.insert("stops_placeholder_2", "convex_hull.html")
stops_temp.insert("stops_title_1", "Stops from GTFS data")
stops_temp.insert(
"stops_title_2", "Convex Hull Generated from GTFS Data"
)
stops_temp = insert_into_template(
stops_temp, "stops_title_2", "Convex Hull Generated from GTFS Data"
)
stops_temp = insert_into_template(stops_temp, "date", date)
stops_temp.insert("date", date)
with open(
f"{report_dir}/gtfs_report/stops.html", "w", encoding="utf8"
) as stops_f:
stops_f.writelines(stops_temp)
stops_f.writelines(stops_temp.get_template())

# summaries
self.summarise_routes()
Expand All @@ -1122,36 +1112,30 @@ def html_report(
xlabel="Trip Count",
ylabel="Day",
)
summ_temp = read_html_template(
location=(
summ_temp = TemplateHTML(
path=(
"src/transport_performance/gtfs/report/"
"html_templates/summary_template.html"
)
)
summ_temp = insert_into_template(
summ_temp, "plotly_placeholder_1", route_html
)
summ_temp = insert_into_template(
summ_temp,
summ_temp.insert("plotly_placeholder_1", route_html)
summ_temp.insert(
"plotly_title_1",
f"Route Summary by Day and Route Type ({summary_type})",
)
summ_temp = insert_into_template(
summ_temp, "plotly_placeholder_2", trip_html
)
summ_temp = insert_into_template(
summ_temp,
summ_temp.insert("plotly_placeholder_2", trip_html)
summ_temp.insert(
"plotly_title_2",
f"Trip Summary by Day and Route Type ({summary_type})",
)
summ_temp = insert_into_template(summ_temp, "date", date)
summ_temp.insert("date", date)
with open(
f"{report_dir}/gtfs_report/summaries.html", "w", encoding="utf8"
) as summ_f:
summ_f.writelines(summ_temp)
summ_f.writelines(summ_temp.get_template())

print(
f"GTFS Report Created at {report_dir}"
f"GTFS Report Created at {report_dir}\n"
f"View your report here: {report_dir}/gtfs_report"
)

Expand Down
Loading

0 comments on commit fba1a60

Please sign in to comment.