Files
Copies/utils.py
T
2026-07-09 15:54:36 +02:00

134 lines
4.4 KiB
Python

import re
from pathlib import Path
def natural_key(text):
return [int(c) if c.isdigit() else c.lower() for c in re.split(r'(\d+)', str(text))]
def read_all_labels(base_dir):
return list(filter(None, (Path(base_dir) / "labels").read_text().splitlines()))
def enonce_total(base_dir):
text_dir = Path(base_dir) / 'Text'
if not text_dir.is_dir():
return ""
files = [f for f in text_dir.iterdir() if f.is_file() and f.suffix not in [".pdf", ".tex"]]
files.sort(key=lambda f: natural_key(f.name))
output = []
for filepath in files:
content = filepath.read_text(encoding='utf-8')
output.append(f"{filepath.name}\n{content}\n\n\n")
return "".join(output)
import os
def pdf_image_of_enonce(root_dir, label):
pdf_path = os.path.join(root_dir, "Text2", f"{label}.pdf")
if os.path.exists(pdf_path):
return pdf_path
def pdf_image_of_solution(root_dir, label):
pdf_path = os.path.join(root_dir, "Sol2", f"{label}.pdf")
if os.path.exists(pdf_path):
return pdf_path
def get_exam_file_content(folder_path, mode, label):
"""
Retrieves content from the Text or Sol directory for a specific label.
Checks for exact filename matches or grouped 'prefix[a,b,c]' filenames.
"""
target_dir = Path(folder_path) / mode
if not target_dir.is_dir():
return None
# Sanitize label (consistent with the script's saving logic)
safe_label = label.replace("/", "_")
# 1. Try exact filename match
direct_file = target_dir / safe_label
if direct_file.is_file():
return direct_file.read_text(encoding="utf-8")
# 2. Search for grouped files: prefix[suffix1,suffix2,...]
for file_path in target_dir.glob("*[*]"):
name = file_path.name
if "[" in name and name.endswith("]"):
# Split 'prefix[suffixes]' -> 'prefix', 'suffixes'
prefix, rest = name.split("[", 1)
suffixes = rest[:-1].split(",") # Remove trailing ']' and split
# Check if any reconstructed label matches
for s in suffixes:
if (prefix + s) == safe_label:
return file_path.read_text(encoding="utf-8")
return None
def get_label_text_content(folder, label):
return get_exam_file_content(folder, "Text", label)
def get_label_sol_content(folder, label):
return get_exam_file_content(folder, "Sol", label)
def get_label_persp_content(folder, label):
return get_exam_file_content(folder, "Persp", label)
import tempfile
import shutil
import subprocess
def compile_to_pdf(text, output_pdf_path): # 21 cm + 3.8 (dimension de la marge de gauche)
"""Wraps text in a standalone template and compiles it to PDF."""
latex_template = f"""\\documentclass[varwidth=24.8cm,margin=0.4cm]{{standalone}}
\\usepackage[utf8]{{inputenc}}
\\usepackage[T1]{{fontenc}}
\\usepackage{{lmodern}}
\\usepackage{{amsmath, amssymb}}
\\usepackage{{commands}}
\\usepackage{{minted}}
\\usepackage{{graphicx}}
\\usepackage{{enumitem}}
\\begin{{document}}
\\begin{{minipage}}{{24.8cm}}
{text}
\\end{{minipage}}
\\end{{document}}
"""
with tempfile.TemporaryDirectory() as temp_dir:
tex_filename = 'text.tex'
pdf_filename = 'text.pdf'
tex_path = os.path.join(temp_dir, tex_filename)
with open(tex_path, 'w', encoding='utf-8') as f:
f.write(latex_template)
# Set TEXINPUTS so pdflatex can find commands.sty if it's in the current dir
# env = os.environ.copy()
# current_dir = os.getcwd()
# env['TEXINPUTS'] = f".:{current_dir}:"
try:
subprocess.run(
['pdflatex', '-interaction=nonstopmode', tex_filename],
cwd=temp_dir,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False
)
if "minted" in text:
subprocess.run(
['pdflatex', '-interaction=nonstopmode', tex_filename],
cwd=temp_dir,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False)
generated_pdf = os.path.join(temp_dir, pdf_filename)
if os.path.exists(generated_pdf):
shutil.move(generated_pdf, output_pdf_path)
except Exception as e:
print(f"Compilation error for {output_pdf_path}: {e}")