Files
series-studio/figures.py
T

176 lines
6.8 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
figures.py
Génération déclarative de figures géométriques et tracés mathématiques en matplotlib 300 dpi,
ou résolution d'images existantes.
"""
import os
os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib")
import shutil
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as patches
plt.rcParams['font.family'] = 'DejaVu Sans'
plt.rcParams['mathtext.fontset'] = 'cm'
def render_declarative_figure(spec: dict, output_path: str):
"""Génère une figure matplotlib 300 dpi à partir d'une description déclarative JSON."""
figsize = tuple(spec.get("figsize", [5.0, 4.5]))
fig, ax = plt.subplots(figsize=figsize, dpi=300)
xlim = spec.get("xlim", [-2.0, 4.0])
ylim = spec.get("ylim", [-2.0, 4.0])
ax.set_xlim(xlim[0], xlim[1])
ax.set_ylim(ylim[0], ylim[1])
if spec.get("aspect") == "equal":
ax.set_aspect('equal')
# Masquer spines
for spine in ax.spines.values():
spine.set_visible(False)
ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)
# Grille fine
grid_cfg = spec.get("grid")
if grid_cfg:
xs = grid_cfg.get("x_step", 0.5)
ys = grid_cfg.get("y_step", 0.5)
ax.set_xticks(np.arange(xlim[0], xlim[1] + xs, xs))
ax.set_yticks(np.arange(ylim[0], ylim[1] + ys, ys))
ax.grid(True, which='both', linestyle=':', color='#e2e8f0', alpha=0.6, linewidth=0.6)
# Axes
if spec.get("axes", True):
ax.axhline(0, color='#0f172a', linewidth=1.2)
ax.axvline(0, color='#0f172a', linewidth=1.2)
ax.annotate('', xy=(xlim[1] - 0.05, 0), xytext=(xlim[1] - 0.2, 0),
arrowprops=dict(arrowstyle="->", color='#0f172a', lw=1.2))
ax.annotate('', xy=(0, ylim[1] - 0.05), xytext=(0, ylim[1] - 0.2),
arrowprops=dict(arrowstyle="->", color='#0f172a', lw=1.2))
# Éléments
for el in spec.get("elements", []):
kind = el.get("kind")
if kind == "circle":
c = el.get("center", [0, 0])
r = el.get("radius", 1.0)
edge = el.get("stroke", "#1e3a8a")
face = el.get("fill", "none")
lw = el.get("lw", 1.8)
ls = el.get("linestyle", "-")
circle = patches.Circle((c[0], c[1]), r, edgecolor=edge, facecolor=face, linewidth=lw, linestyle=ls)
ax.add_patch(circle)
elif kind == "vector":
fr = el.get("from", [0, 0])
to = el.get("to", [1, 0])
col = el.get("color", "#0f172a")
lw = el.get("lw", 1.8)
mut = el.get("mutation_scale", 12)
ax.annotate('', xy=(to[0], to[1]), xytext=(fr[0], fr[1]),
arrowprops=dict(arrowstyle="-|>", color=col, lw=lw, mutation_scale=mut))
elif kind == "point":
x = el.get("x", 0)
y = el.get("y", 0)
col = el.get("color", "#b91c1c")
size = el.get("size", 5.5)
ax.plot([x], [y], 'o', color=col, markersize=size)
lbl = el.get("label")
if lbl:
ox = el.get("offset_x", 0.12)
oy = el.get("offset_y", -0.15)
ax.text(x + ox, y + oy, lbl, fontsize=el.get("fontsize", 11),
fontweight='bold', color=col,
ha=el.get("ha", "left"), va=el.get("va", "center"))
elif kind == "line":
xs = el.get("x", [])
ys = el.get("y", [])
col = el.get("color", "#0f172a")
lw = el.get("lw", 1.5)
ls = el.get("linestyle", "-")
ax.plot(xs, ys, color=col, linewidth=lw, linestyle=ls)
elif kind == "polygon":
xs = el.get("x", [])
ys = el.get("y", [])
col = el.get("color", "#3b82f6")
edge = el.get("stroke", "#1d4ed8")
alpha = el.get("alpha", 0.15)
lw = el.get("lw", 1.8)
ax.fill(xs, ys, color=col, alpha=alpha)
ax.plot(xs, ys, color=edge, linewidth=lw)
elif kind == "text":
x = el.get("x", 0)
y = el.get("y", 0)
t = el.get("text", "")
fs = el.get("fontsize", 11)
col = el.get("color", "#0f172a")
ax.text(x, y, t, fontsize=fs, fontweight='bold', color=col,
ha=el.get("ha", "center"), va=el.get("va", "center"))
elif kind == "function":
expr = el.get("expr", "x")
f_xmin = el.get("xmin", xlim[0])
f_xmax = el.get("xmax", xlim[1])
col = el.get("color", "#2563eb")
lw = el.get("lw", 1.8)
x_vals = np.linspace(f_xmin, f_xmax, 200)
try:
# Évaluation sécurisée avec numpy
y_vals = eval(expr, {"np": np, "x": x_vals, "sin": np.sin, "cos": np.cos, "exp": np.exp, "sqrt": np.sqrt})
ax.plot(x_vals, y_vals, color=col, linewidth=lw)
except Exception as e:
print(f"Erreur tracé fonction {expr}: {e}")
# Cartouche de titre interne éventuel
t_box = spec.get("title_box")
if t_box:
boxstyle = dict(boxstyle='round,pad=0.35', facecolor='#f8fafc', edgecolor='#94a3b8', linewidth=0.8)
ax.text(t_box.get("x", 0.3), t_box.get("y", ylim[1] - 0.2), t_box.get("text", ""),
fontsize=9, fontweight='bold', color='#1e293b',
ha=t_box.get("ha", "center"), va=t_box.get("va", "top"), bbox=boxstyle)
plt.tight_layout()
os.makedirs(os.path.dirname(output_path), exist_ok=True)
plt.savefig(output_path, dpi=300, bbox_inches='tight')
plt.close()
return output_path
def resolve_figure_file(img_name: str, target_dir: str, ref_dirs=None) -> str:
"""Cherche une image par son nom et la copie dans target_dir si nécessaire."""
target_path = os.path.join(target_dir, os.path.basename(img_name))
if os.path.exists(target_path):
return target_path
if os.path.isabs(img_name) and os.path.exists(img_name):
shutil.copy2(img_name, target_path)
return target_path
search_dirs = (ref_dirs or []) + [
"/app/ref/serie05-reference",
"/app/ref/serie06-reference",
"/app/ref",
"/app/data",
os.path.join(os.path.dirname(__file__), "ref", "serie05-reference"),
os.path.join(os.path.dirname(__file__), "ref", "serie06-reference"),
"/workspace/heykel-ref-20261109/serie06-reference",
"/workspace/heykel-ref-20261109/moteur"
]
for d in search_dirs:
candidate = os.path.join(d, os.path.basename(img_name))
if os.path.exists(candidate):
os.makedirs(target_dir, exist_ok=True)
shutil.copy2(candidate, target_path)
return target_path
raise FileNotFoundError(f"Image introuvable : '{img_name}'")