finish rendering.py

This commit is contained in:
Sina Atalay 2023-09-12 19:41:56 +02:00
parent 2b571a9892
commit 2f22ffd9fa
3 changed files with 122 additions and 76 deletions

View File

@ -12,7 +12,7 @@ from jinja2 import Environment, FileSystemLoader
from ruamel.yaml import YAML from ruamel.yaml import YAML
from rendercv.data_model import RenderCVDataModel from rendercv.data_model import RenderCVDataModel
from rendercv.tinytex import run_latex from rendercv.rendering import render_template, run_latex
# logging config: # logging config:
logging.basicConfig( logging.basicConfig(
@ -20,85 +20,20 @@ logging.basicConfig(
format="%(name)s - %(levelname)s - %(message)s", format="%(name)s - %(levelname)s - %(message)s",
) )
input_name = "personal"
workspace = os.path.dirname(os.path.dirname(__file__)) workspace = os.path.dirname(os.path.dirname(__file__))
templateName = "classic"
templatePath = os.path.join(workspace, "rendercv", "templates", templateName)
environment = Environment(
loader=FileSystemLoader(templatePath),
trim_blocks=True,
lstrip_blocks=True,
)
environment.globals.update(str=str)
def markdown_to_latex(value: str) -> str: input_file_path = os.path.join(workspace, "tests", "inputs", f"{input_name}.yaml")
"""
Convert a markdown string to LaTeX.
:param value: The markdown string to convert.
:type value: str
:return: The LaTeX string.
:rtype: str
"""
if not isinstance(value, str):
raise ValueError("markdown_to_latex should only be used on strings!")
# convert links
link = re.search(r"\[(.*)\]\((.*?)\)", value)
if link is not None:
link = link.groups()
oldLinkString = "[" + link[0] + "](" + link[1] + ")"
newLinkString = "\\hrefExternal{" + link[1] + "}{" + link[0] + "}"
value = value.replace(oldLinkString, newLinkString)
return value
def markdown_url_to_url(value: str) -> bool:
"""
Convert a markdown link to a URL.
:param value: The markdown link to convert.
:type value: str
:return: The URL.
:rtype: str
"""
if not isinstance(value, str):
raise ValueError("markdown_to_latex should only be used on strings!")
link = re.search(r"\[(.*)\]\((.*?)\)", value)
if link is not None:
url = link.groups()[1]
return url
else:
raise ValueError(
"markdown_url_to_url should only be used on markdown links!"
)
environment.filters["markdown_to_latex"] = markdown_to_latex
environment.filters["markdown_url_to_url"] = markdown_url_to_url
environment.block_start_string = "((*"
environment.block_end_string = "*))"
environment.variable_start_string = "<<"
environment.variable_end_string = ">>"
environment.comment_start_string = "((#"
environment.comment_end_string = "#))"
template = environment.get_template(f"{templateName}.tex.j2")
inpur_name = "personal"
input_file_path = os.path.join(workspace, "tests", "inputs", f"{inpur_name}.yaml")
with open(input_file_path) as file: with open(input_file_path) as file:
yaml = YAML() yaml = YAML()
raw_json = yaml.load(file) raw_json = yaml.load(file)
data = RenderCVDataModel(**raw_json) data = RenderCVDataModel(**raw_json)
output_latex_file = template.render(design=data.design.options, cv=data.cv) output_latex_file = render_template(data=data)
# Create an output file and write the rendered LaTeX code to it: # Create an output file and write the rendered LaTeX code to it:
output_file_path = os.path.join(workspace, "tests", "outputs", f"{inpur_name}.tex") output_file_path = os.path.join(workspace, "tests", "outputs", f"{input_name}.tex")
os.makedirs(os.path.dirname(output_file_path), exist_ok=True) os.makedirs(os.path.dirname(output_file_path), exist_ok=True)
with open(output_file_path, "w") as file: with open(output_file_path, "w") as file:
file.write(output_latex_file) file.write(output_latex_file)

View File

@ -3,8 +3,122 @@
import os import os
import subprocess import subprocess
def render_template(template, data): import os
pass import json
import logging
import re
from jinja2 import Environment, FileSystemLoader, PackageLoader
import rendercv.templates
def markdown_to_latex(markdown_string: str) -> str:
"""Convert a markdown string to LaTeX.
Example:
>>> markdown_to_latex("This is a **bold** text with an [*italic link*](https://google.com).")
"This is a \\textbf{bold} text with a \\hrefExternal{https://google.com}{\\textit{link}}."
Args:
value (str): The markdown string to convert.
Returns:
str: The LaTeX string.
"""
if not isinstance(markdown_string, str):
raise ValueError("markdown_to_latex should only be used on strings!")
# convert links
links = re.findall(r"\[([^\]\[]*)\]\((.*?)\)", markdown_string)
if links is not None:
for link in links:
link_text = link[0]
link_url = link[1]
old_link_string = f"[{link_text}]({link_url})"
new_link_string = "\\hrefExternal{" + link_url + "}{" + link_text + "}"
markdown_string = markdown_string.replace(old_link_string, new_link_string)
# convert bold
bolds = re.findall(r"\*\*([^\*]*)\*\*", markdown_string)
if bolds is not None:
for bold_text in bolds:
old_bold_text = f"**{bold_text}**"
new_bold_text = "\\textbf{" + bold_text + "}"
markdown_string = markdown_string.replace(old_bold_text, new_bold_text)
# convert italic
italics = re.findall(r"\*([^\*]*)\*", markdown_string)
if italics is not None:
for italic_text in italics:
old_italic_text = f"*{italic_text}*"
new_italic_text = "\\textit{" + italic_text + "}"
markdown_string = markdown_string.replace(old_italic_text, new_italic_text)
latex_string = markdown_string
return latex_string
def markdown_url_to_url(value: str) -> bool:
"""Convert a markdown link to a normal string URL.
Example:
>>> markdown_url_to_url("[Google](https://google.com)")
"https://google.com"
Args:
value (str): The markdown link to convert.
Returns:
str: The URL as a string.
"""
if not isinstance(value, str):
raise ValueError("markdown_to_latex should only be used on strings!")
link = re.search(r"\[(.*)\]\((.*?)\)", value)
if link is not None:
url = link.groups()[1]
return url
else:
raise ValueError("markdown_url_to_url should only be used on markdown links!")
def render_template(data):
# templates_directory = os.path.dirname(os.path.dirname())
# create a Jinja2 environment:
environment = Environment(
loader=PackageLoader("rendercv", "templates"),
trim_blocks=True,
lstrip_blocks=True,
)
# add new functions to the environment:
environment.globals.update(str=str)
# set custom delimiters for LaTeX templating:
environment.block_start_string = "((*"
environment.block_end_string = "*))"
environment.variable_start_string = "<<"
environment.variable_end_string = ">>"
environment.comment_start_string = "((#"
environment.comment_end_string = "#))"
# load the template:
theme = data.design.theme
template = environment.get_template(f"{theme}.tex.j2")
# add custom filters:
environment.filters["markdown_to_latex"] = markdown_to_latex
environment.filters["markdown_url_to_url"] = markdown_url_to_url
return template.render(design=data.design.options, cv=data.cv)
def run_latex(latexFilePath): def run_latex(latexFilePath):
""" """
@ -24,7 +138,7 @@ def run_latex(latexFilePath):
if file.endswith(".tex"): if file.endswith(".tex"):
continue continue
os.remove(os.path.join(os.path.dirname(latexFilePath), file)) os.remove(os.path.join(os.path.dirname(latexFilePath), file))
tinytexPath = os.path.join( tinytexPath = os.path.join(
os.path.dirname(__file__), os.path.dirname(__file__),
"vendor", "vendor",

View File

@ -1,3 +0,0 @@
"""
This module implements a handler for TinyTeX.
"""