189 lines
7.7 KiB
Python
189 lines
7.7 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
main.py
|
|
Service HTTP series-studio pour la génération unifiée de séries d'exercices (PDF et DOCX).
|
|
Fournit l'API interne : GET /themes, POST /validate, POST /render, GET /jobs/<id>/pdf,
|
|
GET /jobs/<id>/docx, POST /jobs/<id>/rerender.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import time
|
|
import uuid
|
|
from typing import Optional
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from fastapi.responses import FileResponse, JSONResponse
|
|
from pydantic import BaseModel
|
|
|
|
import themes
|
|
import validator
|
|
import figures
|
|
import renderer_docx
|
|
import renderer_typst
|
|
|
|
app = FastAPI(title="series-studio", version="1.0.0")
|
|
|
|
JOBS_DIR = os.getenv("SERIES_STUDIO_JOBS_DIR", "/app/jobs")
|
|
DATA_DIR = os.getenv("SERIES_STUDIO_DATA_DIR", "/app/data")
|
|
REF_DIR = os.getenv("SERIES_STUDIO_REF_DIR", "/app/ref")
|
|
|
|
os.makedirs(JOBS_DIR, exist_ok=True)
|
|
os.makedirs(DATA_DIR, exist_ok=True)
|
|
|
|
class ValidateRequest(BaseModel):
|
|
source: dict
|
|
|
|
class RenderRequest(BaseModel):
|
|
source: dict
|
|
theme: Optional[str] = "classique"
|
|
|
|
class RerenderRequest(BaseModel):
|
|
theme: str
|
|
|
|
@app.get("/themes")
|
|
def get_themes():
|
|
"""Renvoie la liste des thèmes disponibles."""
|
|
all_themes = themes.list_themes()
|
|
return {"themes": all_themes}
|
|
|
|
@app.post("/validate")
|
|
def validate_endpoint(req: ValidateRequest):
|
|
"""Valide une source JSON et renvoie des erreurs précises et localisées."""
|
|
res = validator.validate_source(req.source)
|
|
return res
|
|
|
|
def _execute_render_pipeline(source: dict, theme_name: str, job_id: str) -> str:
|
|
"""Exécute le pipeline de rendu complet PDF et DOCX sans aucun modèle."""
|
|
# 1. Vérification du thème
|
|
try:
|
|
theme_tokens = themes.get_theme(theme_name)
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
# 2. Validation de la source
|
|
val_res = validator.validate_source(source)
|
|
if not val_res["valid"]:
|
|
raise HTTPException(status_code=400, detail={"message": "Source JSON invalide", "errors": val_res["errors"]})
|
|
|
|
job_dir = os.path.join(JOBS_DIR, job_id)
|
|
figures_dir = os.path.join(job_dir, "figures")
|
|
os.makedirs(figures_dir, exist_ok=True)
|
|
|
|
# 3. Sauvegarde de la source et des métadonnées du job
|
|
with open(os.path.join(job_dir, "source.json"), "w", encoding="utf-8") as f:
|
|
json.dump(source, f, ensure_ascii=False, indent=2)
|
|
|
|
with open(os.path.join(job_dir, "theme.json"), "w", encoding="utf-8") as f:
|
|
json.dump(theme_tokens, f, ensure_ascii=False, indent=2)
|
|
|
|
journal_lines = [
|
|
f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Démarrage job {job_id} — Thème: {theme_name}"
|
|
]
|
|
|
|
# 4. Résolution et tracé des figures (déclaratives ou existantes)
|
|
figures_map = {}
|
|
|
|
# Résolution des figures déclarées dans source["figures"]
|
|
for fig_spec in source.get("figures", []):
|
|
f_id = fig_spec.get("id")
|
|
kind = fig_spec.get("kind", "declarative")
|
|
out_name = f"{f_id}.png"
|
|
out_path = os.path.join(figures_dir, out_name)
|
|
if kind == "declarative":
|
|
figures.render_declarative_figure(fig_spec, out_path)
|
|
figures_map[f_id] = out_path
|
|
figures_map[out_name] = out_path
|
|
journal_lines.append(f"Figure déclarative tracée à 300 dpi : {out_name}")
|
|
elif kind == "file":
|
|
img_file = fig_spec.get("file", f_id)
|
|
resolved = figures.resolve_figure_file(img_file, figures_dir, [REF_DIR, os.path.join(REF_DIR, "serie06-reference")])
|
|
figures_map[f_id] = resolved
|
|
figures_map[os.path.basename(resolved)] = resolved
|
|
journal_lines.append(f"Image résolue : {resolved}")
|
|
|
|
# Résolution des images dans l'annexe
|
|
annexe = source.get("annexe")
|
|
if annexe:
|
|
for col in annexe.get("colonnes", []):
|
|
img_name = col.get("image") or col.get("figure_id")
|
|
if img_name and img_name not in figures_map:
|
|
try:
|
|
resolved = figures.resolve_figure_file(img_name, figures_dir, [REF_DIR, os.path.join(REF_DIR, "serie06-reference")])
|
|
figures_map[img_name] = resolved
|
|
figures_map[os.path.basename(img_name)] = resolved
|
|
journal_lines.append(f"Image d'annexe résolue : {resolved}")
|
|
except Exception as e:
|
|
journal_lines.append(f"Avertissement image annexe : {e}")
|
|
|
|
# 5. Rendu PDF avec Typst (génère le PDF et extrait le texte de référence)
|
|
output_pdf_path = os.path.join(job_dir, "output.pdf")
|
|
pdf_text = None
|
|
try:
|
|
pdf_meta = renderer_typst.render_typst(source, theme_tokens, output_pdf_path, figures_map=figures_map)
|
|
pdf_text = pdf_meta.get("texte")
|
|
journal_lines.append(f"PDF rendu avec succès : {pdf_meta['pages']} page(s) calibrée(s)")
|
|
except Exception as e:
|
|
journal_lines.append(f"ERREUR rendu PDF : {e}")
|
|
with open(os.path.join(job_dir, "journal.log"), "w", encoding="utf-8") as f:
|
|
f.write("\n".join(journal_lines))
|
|
raise HTTPException(status_code=500, detail=f"Erreur rendu PDF : {e}")
|
|
|
|
# 6. Rendu DOCX avec OMML natif
|
|
output_docx_path = os.path.join(job_dir, "output.docx")
|
|
try:
|
|
docx_meta = renderer_docx.render_docx(source, theme_tokens, output_docx_path, figures_map, pdf_text=pdf_text)
|
|
journal_lines.append(f"DOCX rendu avec succès : {docx_meta['omath']} formules OMML, {docx_meta['draw']} figures, {docx_meta['dollar']} dollar(s)")
|
|
except Exception as e:
|
|
journal_lines.append(f"ERREUR rendu DOCX : {e}")
|
|
with open(os.path.join(job_dir, "journal.log"), "w", encoding="utf-8") as f:
|
|
f.write("\n".join(journal_lines))
|
|
raise HTTPException(status_code=500, detail=f"Erreur rendu DOCX : {e}")
|
|
|
|
journal_lines.append(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Fin normale du job {job_id}")
|
|
with open(os.path.join(job_dir, "journal.log"), "w", encoding="utf-8") as f:
|
|
f.write("\n".join(journal_lines))
|
|
|
|
return job_id
|
|
|
|
@app.post("/render")
|
|
def render_endpoint(req: RenderRequest):
|
|
"""Point d'entrée principal pour générer le PDF et le DOCX d'une série."""
|
|
job_id = f"job_{time.strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
|
|
_execute_render_pipeline(req.source, req.theme or "classique", job_id)
|
|
return {"job_id": job_id}
|
|
|
|
@app.get("/jobs/{job_id}/pdf")
|
|
def get_job_pdf(job_id: str):
|
|
"""Télécharge le fichier PDF produit par un job."""
|
|
path = os.path.join(JOBS_DIR, job_id, "output.pdf")
|
|
if not os.path.exists(path):
|
|
raise HTTPException(status_code=404, detail="Fichier PDF introuvable pour ce job")
|
|
return FileResponse(path, media_type="application/pdf", filename=f"{job_id}.pdf")
|
|
|
|
@app.get("/jobs/{job_id}/docx")
|
|
def get_job_docx(job_id: str):
|
|
"""Télécharge le fichier DOCX produit par un job."""
|
|
path = os.path.join(JOBS_DIR, job_id, "output.docx")
|
|
if not os.path.exists(path):
|
|
raise HTTPException(status_code=404, detail="Fichier DOCX introuvable pour ce job")
|
|
return FileResponse(
|
|
path,
|
|
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
filename=f"{job_id}.docx"
|
|
)
|
|
|
|
@app.post("/jobs/{job_id}/rerender")
|
|
def rerender_endpoint(job_id: str, req: RerenderRequest):
|
|
"""Re-rend une série existante dans un autre thème sans repasser par un modèle."""
|
|
source_path = os.path.join(JOBS_DIR, job_id, "source.json")
|
|
if not os.path.exists(source_path):
|
|
raise HTTPException(status_code=404, detail="Job source introuvable")
|
|
|
|
with open(source_path, "r", encoding="utf-8") as f:
|
|
source = json.load(f)
|
|
|
|
new_job_id = f"job_{time.strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
|
|
_execute_render_pipeline(source, req.theme, new_job_id)
|
|
return {"job_id": new_job_id}
|