Source code for hlsfactory.jinja_frontend
import hashlib
import json
import time
from pathlib import Path
from typing import Any
from jinja2 import Template
from hlsfactory.framework import Design, Frontend
from hlsfactory.utils import (
ExecutionDataStatus,
update_execution_data_with_flow_results,
)
[docs]
class JinjaFrontend(Frontend):
name = "JinjaFrontend"
def __init__(
self,
work_dir: Path,
jinja_configs: list[dict[str, Any]],
log_execution_time: bool = True,
) -> None:
self.work_dir = work_dir
self.log_execution_time = log_execution_time
self.jinja_configs = jinja_configs
[docs]
def load_configs_from_jsonl(self, fp_jsonl: Path):
configs = []
txt_config = fp_jsonl.read_text()
lines = txt_config.splitlines()
for line in lines:
config = json.loads(line.strip())
configs.append(config)
self.jinja_configs = configs
return self.jinja_configs
[docs]
def load_configs_from_json(self, fp_json: Path):
txt_json = fp_json.read_text()
config_list = json.loads(txt_json)
if not isinstance(config_list, list):
raise ValueError("Configs must be a list of dicts")
for list_item_key, list_item_value in config_list.items():
if not isinstance(list_item_key, str):
raise ValueError("List item keys must be strings")
if not isinstance(list_item_value, dict):
raise ValueError("List item values must be dicts")
self.jinja_configs.append(list_item_value)
return self.jinja_configs
[docs]
def execute(self, design: Design, _timeout: float | None = None) -> list[Design]:
t_0 = time.perf_counter()
new_designs = []
for jinja_config in self.jinja_configs:
config_hash = hashlib.md5( # noqa: S324
string=str(jinja_config).encode(),
).hexdigest()
new_design = design.copy_and_rename_to_new_parent_dir(
f"{design.name}__jinja_{config_hash}",
design.dir.parent,
)
new_designs.append(new_design)
jinja_files = sorted(new_design.dir.rglob("*.jinja"))
for jinja_file in jinja_files:
t: Template = Template(
jinja_file.read_text(),
)
# write the rendered template to the file without the .jinja extension
new_file = jinja_file.with_suffix("")
new_file.write_text(
t.render(
**jinja_config,
),
)
# remove the .jinja file
jinja_file.unlink()
t_1 = time.perf_counter()
update_execution_data_with_flow_results(
new_design.dir, self.name, ExecutionDataStatus.SUCCESS, t_0, t_1
)
update_execution_data_with_flow_results(
design.dir, self.name, ExecutionDataStatus.SUCCESS, t_0, t_1
)
return new_designs