Start removing texenv and use pytex

Work with feed and compile for time being.
Nothing for correction or pdfjam
This commit is contained in:
Benjamin Bertrand 2017-04-16 18:46:14 +03:00
parent bb18addd86
commit 68cdb62f4c
3 changed files with 96 additions and 106 deletions

View File

@ -4,10 +4,6 @@
__version__ = "0.1"
from .texenv import texenv
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -1,25 +1,10 @@
#!/usr/bin/env python
# encoding: utf-8
import os
import jinja2
"""
Custom filter for Bopytex
"""
__all__ = ["texenv"]
# Definition of jinja syntax for latex
texenv = jinja2.Environment(
block_start_string='\Block{',
block_end_string='}',
variable_start_string='\Var{',
variable_end_string='}',
line_statement_prefix='%-',
line_comment_prefix='%#',
loader=jinja2.FileSystemLoader(os.path.abspath('.')),
extensions=['jinja2.ext.do']
)
# Filters
def do_calculus(steps, name="A", sep="=", end="", joining=" \\\\ \n"):
"""Display properly the calculus
@ -40,13 +25,6 @@ def do_calculus(steps, name="A", sep="=", end="", joining=" \\\\ \n"):
return ans
texenv.filters['calculus'] = do_calculus
from random import shuffle
texenv.filters['shuffle'] = shuffle
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -6,110 +6,124 @@ Producing then compiling templates
"""
import os
import csv
import math as m
import logging
import optparse
import random as rd
import sys
from path import Path
from pymath.calculus.polynomDeg2 import Polynom_deg2
from pymath import Dataset
from pymath import Equation
from pymath import Expression
from pymath import Fraction
from pymath import Polynom
from pymath import random_pythagore
from pymath import random_str
from pymath import WeightedDataset
from .texenv import texenv
import pytex
import pymath
EXPORT_DICT = {}
EXPORT_DICT.update(m.__dict__)
EXPORT_DICT.update(rd.__dict__)
EXPORT_DICT.update(__builtins__)
EXPORT_DICT.update({
"Expression": Expression,
"Polynom": Polynom,
"Polynom_deg2": Polynom_deg2,
"Fraction": Fraction,
"Equation": Equation,
"random_str": random_str,
"random_pythagore": random_pythagore,
"Dataset": Dataset,
"WeightedDataset": WeightedDataset,
})
formatter = logging.Formatter('%(name)s :: %(levelname)s :: %(message)s')
steam_handler = logging.StreamHandler()
steam_handler.setLevel(logging.DEBUG)
steam_handler.setFormatter(formatter)
# création de l'objet logger qui va nous servir à écrire dans les logs
# logger = logging.getLogger("opytex")
# on met le niveau du logger à DEBUG, comme ça il écrit tout
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(steam_handler)
MAPYTEX_TOOLS = {
"Expression": pymath.Expression,
"Polynom": pymath.Polynom,
"Fraction": pymath.Fraction,
"Equation": pymath.Equation,
"random_str": pymath.random_str,
"random_pythagore": pymath.random_pythagore,
"Dataset": pymath.Dataset,
"WeightedDataset": pymath.WeightedDataset,
}
pytex.update_export_dict(MAPYTEX_TOOLS)
def produce_and_compile(options):
""" Produce and compile subjects
"""
# template = report_renderer.get_template(options.template)
template = texenv.get_template(options.template)
# template = texenv.get_template(options.template)
template = Path(options.template)
logger.debug(f"Template will be {template}")
if options.output_dir:
output_dir = Path(options.output_dir)
else:
output_dir = template.dirname()
logger.debug(f"The output directory will be {output_dir}")
# Saving place
cwd = Path("./").abspath()
# cwd = Path("./").abspath()
template_file = Path(options.template)
# template_file = Path(options.template)
output = Path(template_file.dirname()) / Path(template_file.name[3:])
if not options.csv_file:
# {:02:0f} means that we want a 2 digits number
list_infos = [
{"num": "{:02.0f}".format(i+1)}
{"num": f"{i+1:02d}"}
for i in range(options.num_subj)
]
else:
with open(options.csv_file, 'r', encoding='ISO-8859-1') as csv_file:
list_infos = list(csv.DictReader(csv_file, delimiter=";"))
for (i, info) in enumerate(list_infos):
info['num'] = "{:02.0f}".format(i+1)
if output.dirname() != "":
output.dirname().cd()
# if output.dirname() != "":
# output.dirname().cd()
output = output.name
# output = output.name
if options.only_corr:
options.corr = True
else:
tmp_pdf = []
tex_files = []
for infos in list_infos:
# print("_______" + str(infos))
dest = Path(str(infos['num']) + output)
tmp_pdf.append(dest.namebase + ".pdf")
with open(dest, 'w') as output_file:
output_file.write(
template.render(
infos=infos,
**EXPORT_DICT
# dest = Path(str(infos['num']) + output)
dest = (
output_dir
/ Path(template.replace("tpl", infos["num"]))
)
logger.debug(f"Feeding template toward {dest}")
tex_files.append(dest)
pytex.feed(
template,
{"infos": infos},
output=dest,
force=1
)
logger.debug(f"{dest} fed")
# with open(dest, 'w') as output_file:
# output_file.write(
# template.render(
# infos=infos,
# **EXPORT_DICT
# )
# )
if not options.no_compil:
os.system("pdflatex " + dest)
pdf_files = []
for texfile in tex_files:
logger.debug(f"Start compiling {texfile}")
pytex.pdflatex(texfile)
logger.debug(f"End compiling {texfile}")
pdf_files.append(str(texfile[:-4] + ".pdf"))
logger.debug(f"Compiled files : {pdf_files}")
if not options.dirty:
os.system("rm *.aux *.log")
pytex.clean(output_dir)
if not options.no_join:
print(Path("./").abspath())
print(
"pdfjam "
+ " ".join(tmp_pdf)
+ " ".join(pdf_files)
+ " -o all"
+ Path(output).namebase
+ Path(output_dir).namebase
+ ".pdf"
)
os.system(
"pdfjam "
+ " ".join(tmp_pdf)
+ " ".join(pdf_files)
+ " -o all"
+ Path(output).namebase
+ Path(output_dir).namebase
+ ".pdf"
)
# os.system("pdfjam *.pdf -o all" + Path(output).namebase + ".pdf")
print("rm " + " ".join(tmp_pdf))
os.system("rm " + " ".join(tmp_pdf))
print("rm " + " ".join(pdf_files))
os.system("rm " + " ".join(pdf_files))
if options.corr:
find_subj_tex_files = "find ./ -iname '[0-9]*_*.tex' "
@ -135,17 +149,17 @@ def produce_and_compile(options):
print(Path("./").abspath())
print(
"pdfjam `find ./ -iname '[0-9]*.pdf'` -o corr"
+ Path(output).namebase + ".pdf"
+ Path(output_dir).namebase + ".pdf"
)
os.system(
"pdfjam `find ./ -iname '[0-9]*.pdf'` -o corr"
+ Path(output).namebase + ".pdf"
+ Path(output_dir).namebase + ".pdf"
)
# os.system("pdfjam *.pdf -o all" + Path(output).namebase + ".pdf")
print(r"find ./ -iname '[0-9]*.pdf' -exec rm -f {} \;")
os.system(r"find ./ -iname '[0-9]*.pdf' -exec rm -f {} \;")
cwd.cd()
# cwd.cd()
def main():
@ -159,12 +173,12 @@ def main():
help="File with the template. The name should have the following form tpl_... ."
)
parser.add_option(
"-C",
"--csv",
"-o",
"--output-dir",
action="store",
type="string",
dest="csv_file",
help="Filename of the csv file where informations on subjects are stored"
dest="output_dir",
help="Where fed templates and compiled files will be placed"
)
parser.add_option(
"-N",
@ -197,7 +211,7 @@ def main():
help="Do not join pdf and clean single pdf"
)
parser.add_option(
"-o",
"-O",
"--only-corr",
action="store_true",
dest="only_corr",
@ -213,6 +227,8 @@ def main():
(options, _) = parser.parse_args()
logger.debug(f"CI parser gets {options}")
if not options.template:
print("I need a template!")
sys.exit(0)