Skip to content

Commit

Permalink
- added support for specifying latex auxiliary file
Browse files Browse the repository at this point in the history
- parameters.yaml
	- new settings "latex"
- gift_wrapper
	- question.py
		- a couple of type hintings modified to actually honor the Python >=3.6 requirement
  • Loading branch information
manuvazquez committed May 6, 2020
1 parent f610ca0 commit 1a6843c
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 15 deletions.
22 changes: 21 additions & 1 deletion gift_wrapper/core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import argparse
import pathlib
import collections
import sys

import yaml
import tqdm
Expand Down Expand Up @@ -78,6 +79,14 @@ def wrap(parameters_file: str, questions_file: str, local_run: bool, no_checks:
# to keep track of files already compiled/transferred
history = {'already compiled': set(), 'already transferred': set()}

latex_auxiliary_file = pathlib.Path(parameters['latex']['auxiliary file'])

# if latex checks are enabled and the given auxiliary file already exists...
if (not no_checks) and latex_auxiliary_file.exists():

print(f'{colors.error}latex auxiliary file {colors.reset}"{latex_auxiliary_file}"{colors.error} exists')
sys.exit(1)

with open(output_file, 'w') as f:

# for every category...
Expand Down Expand Up @@ -112,9 +121,12 @@ def wrap(parameters_file: str, questions_file: str, local_run: bool, no_checks:
# the class is removed from the dictionary so that it doesn't get passed to the initializer
del q['class']

# whether or not latex formulas should be checked
# whether or not latex formulas should be checked...
q['check_latex_formulas'] = not no_checks

# ...if so, this auxiliary file will be used (created)
q['latex_auxiliary_file'] = latex_auxiliary_file

# "history" is passed
q['history'] = history

Expand All @@ -128,3 +140,11 @@ def wrap(parameters_file: str, questions_file: str, local_run: bool, no_checks:
f.write(f'{q.gift}\n\n')

print(f'{colors.info}file "{colors.reset}{output_file}{colors.info}" created')

# if latex checks are enabled...
if not no_checks:

# latex auxiliary files are deleted
for suffix in ['.tex', '.aux', '.log']:

latex_auxiliary_file.with_suffix(suffix).unlink()
8 changes: 6 additions & 2 deletions gift_wrapper/gift.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import re
import pathlib
from typing import Union

from . import latex

Expand Down Expand Up @@ -118,14 +120,16 @@ def from_feedback(text: str) -> str:
return '#'*4 + text


def process_latex(text: str, check_compliance: bool = True) -> str:
def process_latex(text: str, latex_auxiliary_file: Union[str, pathlib.Path], check_compliance: bool = True) -> str:
"""
Adapts every occurrence of $$ to GIFT.
Parameters
----------
text : str
Input text.
latex_auxiliary_file: str or pathlib.Path
(Auxiliary) TeX file that is created to check the formula.
check_compliance: bool
Whether or not to check if the formula can be compiled.
Expand All @@ -142,7 +146,7 @@ def replacement(m: re.Match) -> str:

if check_compliance:

if not latex.formula_can_be_compiled(latex_source):
if not latex.formula_can_be_compiled(latex_source, auxiliary_file=latex_auxiliary_file):

raise NotCompliantLatexFormula(latex_source)

Expand Down
4 changes: 2 additions & 2 deletions gift_wrapper/latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,15 @@ def compile_tex(
''')


def formula_can_be_compiled(formula: str, auxiliary_file: str = '__latex_check.tex') -> bool:
def formula_can_be_compiled(formula: str, auxiliary_file: Union[str, pathlib.Path]) -> bool:
"""
Checks whether a latex formula can be compiled with the above template, `latex_template`.
Parameters
----------
formula : str
Latex formula.
auxiliary_file : str
auxiliary_file : str or pathlib.Path
(Auxiliary) TeX file that is created to check the formula.
Returns
Expand Down
23 changes: 15 additions & 8 deletions gift_wrapper/question.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from . import remote
from . import colors

# regular expression to extract a percentage
re_percentage = re.compile('(\d*\.\d+|\d+)\s*%')


Expand All @@ -20,7 +21,7 @@ class HtmlQuestion(metaclass=abc.ABCMeta):

def __init__(
self, name: str, statement: str, images_settings: dict, history: dict, check_latex_formulas: bool,
feedback: Optional[str] = None):
latex_auxiliary_file: Union[str, pathlib.Path], feedback: Optional[str] = None):
"""
Initializer.
Expand Down Expand Up @@ -48,7 +49,8 @@ def __init__(

self.processing_functions = [
functools.partial(gift.process_url_images, width=self.images_width, height=self.images_height),
gift.process_new_lines, functools.partial(gift.process_latex, check_compliance=check_latex_formulas)
gift.process_new_lines, functools.partial(
gift.process_latex, latex_auxiliary_file=latex_auxiliary_file, check_compliance=check_latex_formulas)
]

# this might be tampered with by subclasses/decorator
Expand Down Expand Up @@ -139,9 +141,10 @@ class Numerical(HtmlQuestion):

def __init__(
self, name: str, statement: str, images_settings: dict, history: dict, check_latex_formulas: bool,
solution: dict, feedback: Optional[str] = None):
latex_auxiliary_file: Union[str, pathlib.Path], solution: dict, feedback: Optional[str] = None):

super().__init__(name, statement, images_settings, history, check_latex_formulas, feedback)
super().__init__(
name, statement, images_settings, history, check_latex_formulas, latex_auxiliary_file, feedback)

assert ('value' in solution), '"value" missing in "solution"'

Expand Down Expand Up @@ -193,9 +196,10 @@ class MultipleChoice(HtmlQuestion):

def __init__(
self, name: str, statement: str, images_settings: dict, history: dict, check_latex_formulas: bool,
answers: dict, feedback: Optional[str] = None):
latex_auxiliary_file: Union[str, pathlib.Path], answers: dict, feedback: Optional[str] = None):

super().__init__(name, statement, images_settings, history, check_latex_formulas, feedback)
super().__init__(
name, statement, images_settings, history, check_latex_formulas, latex_auxiliary_file, feedback)

self.answers = answers

Expand Down Expand Up @@ -266,10 +270,12 @@ def __setattr__(self, key, value):
# ...is relayed to the decorated object
setattr(self._decorated, key, value)

# TODO: when minimum Python version is forwarded to 3.8, `[re.Match]` should replace `...` as the the signature
# of the `Callable` in the type hinting for `replacement`
@staticmethod
def transform_files(
text: str, pattern: str, process_match: Callable[[str], None],
replacement: Union[str, Callable[[re.Match], str]]):
replacement: Union[str, Callable[..., str]]):
"""
It searches in a text for strings corresponding to files (maybe including a path), replaces them by another
string according to some function and, additionally, processes each file according to another function.
Expand Down Expand Up @@ -352,7 +358,8 @@ def __init__(
# assembled remote path
remote_subdirectory = pathlib.Path(public_filesystem_root).joinpath(pictures_base_directory)

def replacement_function(m: re.Match) -> str:
# TODO: when minimum Python version is forwarded to 3.8, `re.Match` should be the type hinting for `m`
def replacement_function(m) -> str:

file = pathlib.Path(m.group(0))

Expand Down
7 changes: 6 additions & 1 deletion parameters.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,9 @@ images hosting:
public filesystem root: ./public_html

# public address from which the images will hang
public URL: http://www.tsc.uc3m.es/~mvazquez/
public URL: http://www.tsc.uc3m.es/~mvazquez/

latex:

# auxiliary TeX file that will be created to check that formulas can be compiled
auxiliary file: __latex_check.tex
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name="gift-wrapper", # Replace with your own username
version="1.2.4",
version="1.2.5",
author="Manuel A. Vázquez",
author_email="[email protected]",
description="Build GIFT (Moodle compatible) files easily",
Expand Down

0 comments on commit 1a6843c

Please sign in to comment.