Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Matistjati committed Aug 18, 2024
1 parent cdd1804 commit 194c7b1
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 32 deletions.
16 changes: 9 additions & 7 deletions problemtools/md2html.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import html
import os.path
import string
import argparse
Expand All @@ -12,9 +11,9 @@

FOOTNOTES_STRING = '<section class="footnotes" role="doc-endnotes">'

def convert(problem: str, options: argparse.Namespace) -> None:
def convert(problem: str, options: argparse.Namespace) -> bool:
"""Convert a Markdown statement to HTML
Args:
problem: path to problem directory
options: command-line arguments. See problem2html.py
Expand All @@ -34,7 +33,8 @@ def convert(problem: str, options: argparse.Namespace) -> None:
_copy_images(statement_path,
lambda img_name: handle_image(os.path.join(problem, "problem_statement", img_name)))
command = ["pandoc", statement_path, "-t" , "html"]
statement_html = subprocess.run(command, capture_output=True, text=True, shell=False).stdout
statement_html = subprocess.run(command, capture_output=True, text=True,
shell=False, check=True).stdout

templatepaths = [os.path.join(os.path.dirname(__file__), 'templates/markdown'),
os.path.join(os.path.dirname(__file__), '../templates/markdown'),
Expand Down Expand Up @@ -66,11 +66,13 @@ def convert(problem: str, options: argparse.Namespace) -> None:
with open("problem.css", "w") as output_file:
with open(os.path.join(templatepath, "problem.css"), "r") as input_file:
output_file.write(input_file.read())

return True


def handle_image(src: str) -> None:
"""This is called for every image in the statement
Copies the image from the statement to the output directory
Copies the image from the statement to the output directory
Args:
src: full file path to the image
Expand Down Expand Up @@ -103,7 +105,8 @@ def json_dfs(data, callback) -> None:

def _copy_images(statement_path, callback):
command = ["pandoc", statement_path, "-t" , "json"]
statement_json = subprocess.run(command, capture_output=True, text=True, shell=False).stdout
statement_json = subprocess.run(command, capture_output=True,
text=True, shell=False, check=True).stdout
json_dfs(json.loads(statement_json), callback)


Expand Down Expand Up @@ -135,4 +138,3 @@ def _substitute_template(templatepath: str, templatefile: str, **params) -> str:
with open(os.path.join(templatepath, templatefile), "r", encoding="utf-8") as template_file:
html_template = template_file.read() % params
return html_template

18 changes: 9 additions & 9 deletions problemtools/problem2pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def convert(options: argparse.Namespace) -> bool:

if not os.path.isfile(statement_path):
raise Exception(f"Error! {statement_path} is not a file")

templatepaths = [os.path.join(os.path.dirname(__file__), 'templates/markdown_pdf'),
os.path.join(os.path.dirname(__file__), '../templates/markdown_pdf'),
'/usr/lib/problemtools/templates/markdown_pdf']
Expand All @@ -30,20 +30,20 @@ def convert(options: argparse.Namespace) -> bool:
table_fix_path = os.path.join(templatepath, "fix_tables.md")
if not os.path.isfile(table_fix_path):
raise Exception("Could not find markdown pdf template")
with open(table_fix_path, "r") as f:
table_fix = f.read()

with open(table_fix_path, "r") as file:
table_fix = file.read()

statement_dir = os.path.join(problem_root, "problem_statement")
with open(statement_path, "r") as f:
statement_md = f.read()
with open(statement_path, "r") as file:
statement_md = file.read()

problem_name = statement_common.get_problem_name(problem_root, options.language)

# Add code that adds vertical and horizontal lines to all tables
statement_md = r'\centerline{\huge %s}' % problem_name + statement_md
statement_md = table_fix + statement_md

# Hacky: html samples -> md. Then we append to the markdown document
samples = "\n".join(statement_common.format_samples(problem_root, to_pdf=True))

Expand All @@ -54,7 +54,7 @@ def convert(options: argparse.Namespace) -> bool:
temp_file.write(statement_md)
temp_file.flush()
command = ["pandoc", temp_file.name, "-o", f"{problembase}.pdf", f"--resource-path={statement_dir}"]
subprocess.run(command, capture_output=True, text=True, shell=False)
return subprocess.run(command, capture_output=True, text=True, shell=False, check=True)

else:
# Set up template if necessary
Expand Down
16 changes: 8 additions & 8 deletions problemtools/statement_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def find_statement(problem_root: str, extension: str, language: Optional[str]) -

def find_statement_extension(problem_root: str, language: Optional[str]) -> str:
"""Given a language, find whether the extension is tex or md
Args:
problem_root: path to problem root
"""
Expand All @@ -51,7 +51,7 @@ def get_problem_name(problem: str, language: Optional[str]) -> Optional[str]:
with verifyproblem.Problem(problem) as prob:
config = verifyproblem.ProblemConfig(prob)
if not config.check(None):
raise Exception(f"Invalid problem.yaml")
raise Exception("Invalid problem.yaml")
names = config.get("name")
# If there is only one language, per the spec that is the one we want
if len(names) == 1:
Expand All @@ -64,7 +64,7 @@ def get_problem_name(problem: str, language: Optional[str]) -> Optional[str]:

def format_samples(problem_root: str, to_pdf: bool = False) -> List[str]:
"""Read all samples from the problem directory and convert them to pandoc-valid markdown
Args:
problem_root: path to root of problem
to_pdf: whether the outputted samples should be valid for for html or pdf
Expand All @@ -73,7 +73,7 @@ def format_samples(problem_root: str, to_pdf: bool = False) -> List[str]:
List[str]: All samples, converted to a format appropriate to be pasted into
a markdown file. Ordered lexicographically by file names
"""

sample_path = os.path.join(problem_root, "data", "sample")
if not os.path.isdir(sample_path):
print("WARNING!! no sample folder")
Expand All @@ -95,7 +95,7 @@ def format_samples(problem_root: str, to_pdf: bool = False) -> List[str]:
<th style="text-align:right; width:33%;">Write</th>
</tr>
</table>"""

with open(os.path.join(sample_path, sample), "r", encoding="utf-8") as infile:
sample_interaction = infile.readlines()
lines = []
Expand Down Expand Up @@ -159,16 +159,16 @@ def format_samples(problem_root: str, to_pdf: bool = False) -> List[str]:
</tbody>
</table>"""
% ({"case": casenum, "input": html.escape(sample_input), "output": html.escape(sample_output)}))

if to_pdf:
# If pdf, convert to markdown
with tempfile.NamedTemporaryFile(mode='w', suffix=".html") as temp_file:
temp_file.write(samples[-1])
temp_file.flush()
command = ["pandoc", temp_file.name, "-t" , "markdown"]
samples[-1] = subprocess.run(command, capture_output=True, text=True, shell=False).stdout
samples[-1] = subprocess.run(command, capture_output=True, text=True,
shell=False, check=True).stdout

casenum += 1

return samples

13 changes: 5 additions & 8 deletions problemtools/templates/markdown/problem.css
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ table:not(.sample) td {
/*Style sample in its own way*/
.sample {
font-family: Arial, Helvetica, sans-serif;
}

.sample {
width: 100%;
}

Expand Down Expand Up @@ -94,20 +91,20 @@ div.sampleinteractionread {
border: 1px solid black;
width: 60%;
float: left;
margin: 3px 0px 3px 0px;
margin: 3px 0px;
}

.sampleinteractionread pre {
margin: 1px 5px 1px 5px;
margin: 1px 5px;
}

div.sampleinteractionwrite {
border: 1px solid black;
width: 60%;
float: right;
margin: 3px 0px 3px 0px;
margin: 3px 0px;
}

.sampleinteractionwrite pre {
margin: 1px 5px 1px 5px;
}
margin: 1px 5px;
}

0 comments on commit 194c7b1

Please sign in to comment.