Add some color to scoring

master
Sébastien Miquel 2026-02-25 20:38:44 +01:00
parent 6215b2aad2
commit cbae1473ac
1 changed files with 52 additions and 5 deletions

View File

@ -214,6 +214,57 @@ def render_latex_text(text, width_px, bg_color=(255, 255, 255, 255), max_lines=N
final_img.alpha_composite(img)
return final_img
def render_score_text(label, score, error, width_px, fontsize=18,
bg_color=(255, 255, 255, 255)):
# 1. Calculate Color Gradient (0.0=DarkRed -> 4.0=Green)
# Clamp score between 0 and 4
t = max(0.0, min(1.0, float(score) / 4.0))
# Dark Red (139, 0, 0) to Green (0, 128, 0)
red = 139 * (1 - t)
green = 128 * t
hex_color = mcolors.to_hex((red/255, green/255, 0))
# 2. Build Text with Mathtext Color
# We use \color{hex} to color specific parts in Matplotlib
score_str = f"{label} ; Note : \\color{{{hex_color}}}{{{score}}}"
if error and error != "null":
score_str += f" | Error: {error}"
# 3. Wrap Text (using your existing heuristic)
dpi = 100
fig_width = width_px / dpi
chars_per_line = int(fig_width * 10) # Heuristic from your snippet
# Use your existing wrapper
wrapped_text = wrap_latex_text(score_str, chars_per_line)
# 4. Render (Standard Matplotlib boilerplate)
num_lines = wrapped_text.count('\n') + 1
fig_height = num_lines * 0.4 + 0.2 # Slight padding adjustment
fig = plt.figure(figsize=(fig_width, fig_height), dpi=dpi)
plt.text(0.01, 0.95, wrapped_text, fontsize=fontsize,
verticalalignment='top', horizontalalignment='left',
wrap=False) # wrap=False because wrap_latex_text handled it
plt.axis('off')
buf = io.BytesIO()
plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0.1, transparent=True)
plt.close(fig)
buf.seek(0)
img = Image.open(buf).convert("RGBA")
# Apply background
final_img = Image.new("RGBA", img.size, bg_color)
final_img.alpha_composite(img)
return final_img
def compose_label_image(base_img, label, result, hmin,
render_fn=render_latex_text,
draw_callback=None):
@ -243,11 +294,7 @@ def compose_label_image(base_img, label, result, hmin,
# 1. Prepare Headers
header_elements = []
# Score
score_text = f"{label} ; Note : {score}"
if error and error != "null": score_text += f" | Error: {error}"
img_score = render_fn(score_text, base_img.width // 2, fontsize=18)
img_score = render_score_text(label, score, error, base_img.width // 2, fontsize=18)
header_elements.append({"type": "score", "img": img_score, "data": result})
# Global Feedbacks