Skip to content

Commit

Permalink
More generic handling of charts
Browse files Browse the repository at this point in the history
  • Loading branch information
ajparsons committed Aug 21, 2024
1 parent b3d041a commit 62c475d
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 25 deletions.
53 changes: 34 additions & 19 deletions src/data_common/charting/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,46 @@
alt.themes.register("mysoc_theme", lambda: altair_theme.mysoc_theme)
alt.themes.enable("mysoc_theme")

gb_format = {"decimal": ".", "thousands": ",", "grouping": [3], "currency": ["£", ""]}

alt.renderers.register("mysoc_saver", render) # type: ignore
alt.renderers.enable("mysoc_saver")
alt.renderers.set_embed_options(formatLocale=gb_format)
gb_format = {
"decimal": ".",
"thousands": ",",
"grouping": [3],
"currency": ["£", ""],
}


def enable_ms_charts():
def enable_ms_charts(include_renderer: bool = True):
alt.themes.register("mysoc_theme", lambda: altair_theme.mysoc_theme)
alt.themes.enable("mysoc_theme")
alt.renderers.set_embed_options(
formatLocale=gb_format,
logo=Logo.MYSOCIETY,
caption_font_url="https://github.com/nteract/assets/raw/master/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Regular.otf.woff",
)
if include_renderer:
alt.renderers.register("mysoc_saver", render) # type: ignore
alt.renderers.enable("mysoc_saver")
alt.renderers.set_embed_options(
formatLocale=gb_format,
logo=Logo.MYSOCIETY,
caption_font="SourceSansPro-Regular.otf.woff",
fonts_to_load=[
"https://github.com/nteract/assets/raw/master/fonts/source-sans-pro/WOFF/OTF/SourceSansPro-Regular.otf.woff"
],
)
else:
alt.renderers.set_embed_options(formatLocale=gb_format)


def enable_sw_charts():
def enable_sw_charts(include_renderer: bool = True):
alt.themes.register("societyworks_theme", lambda: altair_sw_theme.sw_theme)
alt.themes.enable("societyworks_theme")
alt.renderers.set_embed_options(
formatLocale=gb_format,
logo=Logo.SOCIETYWORKS,
caption_font_url="https://github.com/google/fonts/raw/main/ofl/lato/Lato-Regular.ttf",
)


enable_ms_charts()
if include_renderer:
alt.renderers.register("mysoc_saver", render) # type: ignore
alt.renderers.enable("mysoc_saver")
alt.renderers.set_embed_options(
formatLocale=gb_format,
logo=Logo.SOCIETYWORKS,
caption_font="Lato-Regular.ttf",
fonts_to_load=[
"https://github.com/google/fonts/raw/main/ofl/lato/Lato-Regular.ttf"
],
)
else:
alt.renderers.set_embed_options(formatLocale=gb_format)
27 changes: 22 additions & 5 deletions src/data_common/charting/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

from .str_enum import StrEnum

chart_temp_dir = Path(tempfile.gettempdir()) / "mysoc_charting"


class Logo(StrEnum):
MYSOCIETY = (
Expand All @@ -26,8 +28,9 @@ def url_to_temp(file_url: str) -> Path:
"""
# get filename from url
file_name = file_url.split("/")[-1]
temp_file = Path(tempfile.gettempdir()) / file_name
temp_file = chart_temp_dir / file_name
if not temp_file.exists():
chart_temp_dir.mkdir(exist_ok=True)
logo = requests.get(file_url)
with open(temp_file, "wb") as f:
f.write(logo.content)
Expand Down Expand Up @@ -61,10 +64,25 @@ def render(spec: dict, embed_options: dict[str, Any]) -> MimeBundle:
scale_factor = display["scale_factor"]
logo = display["logo"] or embed_options.get("logo", "")
caption = display["caption"]
caption_font_url = embed_options.get("caption_font_url", "")
caption_font = embed_options.get("caption_font", "")
fonts_to_load = embed_options.get("fonts_to_load", [])

chart_temp_dir.mkdir(exist_ok=True)
font_paths = [url_to_temp(font) for font in fonts_to_load]
caption_font_path = None
if caption_font:
caption_font_path = [x for x in font_paths if caption_font == x.name]
if len(caption_font_path) == 1:
caption_font_path = caption_font_path[0]
elif len(caption_font_path) > 1:
raise ValueError(f"Multiple fonts with the same name: {caption_font_path}")
else:
raise ValueError(f"Font not found: {caption_font}")

format_locale = embed_options.get("formatLocale", {})

vlc.register_font_directory(str(chart_temp_dir)) # type: ignore

png_data = vlc.vegalite_to_png( # type: ignore
spec, scale=scale_factor, format_locale=format_locale
)
Expand Down Expand Up @@ -93,9 +111,8 @@ def render(spec: dict, embed_options: dict[str, Any]) -> MimeBundle:
new_image.paste(downsided_logo, (0, pil_image.height))
if caption:
draw = ImageDraw.Draw(new_image)
if caption_font_url:
font_path = url_to_temp(caption_font_url)
font = ImageFont.truetype(str(font_path), 30)
if caption_font_path:
font = ImageFont.truetype(str(caption_font_path), 30)
else:
font = ImageFont.load_default(30)
font_length = font.getlength(caption)
Expand Down
5 changes: 4 additions & 1 deletion src/data_common/charting/theme.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,14 @@ def color_scale(
"config": {
"padding": {"left": 5, "top": 5, "right": 20, "bottom": 5},
"title": {
"align": "left",
"font": font,
"fontSize": 30,
"anchor": "start",
"subtitleFontSize": 20,
"subtitleFont": "Source Sans Pro",
"subtitleFont": font,
"subtitlePadding": 10,
"dx": -1,
},
"axis": {
"labelFont": font,
Expand Down

0 comments on commit 62c475d

Please sign in to comment.