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" __version__ = "0.1"
from .texenv import texenv
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -1,25 +1,10 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8 # 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"): def do_calculus(steps, name="A", sep="=", end="", joining=" \\\\ \n"):
"""Display properly the calculus """Display properly the calculus
@ -40,13 +25,6 @@ def do_calculus(steps, name="A", sep="=", end="", joining=" \\\\ \n"):
return ans return ans
texenv.filters['calculus'] = do_calculus
from random import shuffle
texenv.filters['shuffle'] = shuffle
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

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