Spaces:
Paused
Paused
Deploy Poster Scorer
Browse files- .gitattributes +1 -0
- README.md +28 -6
- app.py +126 -0
- artifacts/poster_scorer_model.zip +3 -0
- examples/balanced.png +0 -0
- examples/graphic_heavy.png +0 -0
- examples/text_heavy.png +3 -0
- features.py +155 -0
- packages.txt +2 -0
- poster_inference.py +108 -0
- requirements.txt +10 -0
- score_feedback.py +189 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
examples/text_heavy.png filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,10 +1,32 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk:
|
|
|
|
|
|
|
|
|
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Poster Scorer
|
| 3 |
+
emoji: 🖼️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: yellow
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.28.0
|
| 8 |
+
python_version: "3.12"
|
| 9 |
+
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# Poster Scorer
|
| 14 |
+
|
| 15 |
+
Upload a poster to predict its overall design score on the PosterIQ 1 to 10 scale and get one suggested layout change. The app measures text and layout with Tesseract OCR and background-color analysis, scores those 14 measurements with an AutoGluon regression model, and asks the same model which tested change would raise its score most.
|
| 16 |
+
|
| 17 |
+
**Model inputs:** the 14 numeric features in `features.py`, such as `char_count`, `text_area_frac`, `graphic_area_frac`, `text_share`, and text height.
|
| 18 |
+
|
| 19 |
+
**Results (219 posters, 153/33/33 split):**
|
| 20 |
+
|
| 21 |
+
| Split | Model RMSE | Mean baseline RMSE | Model R² |
|
| 22 |
+
|---|---|---|---|
|
| 23 |
+
| Validation | 1.36 | 1.48 | 0.14 |
|
| 24 |
+
| Test | 1.12 | 1.46 | 0.41 |
|
| 25 |
+
|
| 26 |
+
**Feedback:** the suggestion comes from testing training-data values of text area, graphic area, word count, and text size against the score model. It is a model estimate, not a proven cause of the score or a guaranteed improvement, and it is not trained on human feedback labels.
|
| 27 |
+
|
| 28 |
+
**Scope:** the score predicts overall design quality from text and layout measurements only. It does not judge color, content, or typography. OCR and graphic masks are estimates.
|
| 29 |
+
|
| 30 |
+
**Data:** [creative-graphic-design/PosterIQ](https://huggingface.co/datasets/creative-graphic-design/PosterIQ), `overall_rating` subset, listed for non-commercial research use. Code and data pipeline: [github.com/jackstev-edu/PosterScorer](https://github.com/jackstev-edu/PosterScorer).
|
| 31 |
+
|
| 32 |
+
**AI assistance:** code was developed with help from Claude (Anthropic).
|
app.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Poster Scorer: Gradio app that scores an uploaded poster and suggests one change.
|
| 2 |
+
|
| 3 |
+
Pipeline: poster image -> OCR + pixel analysis (features.py) -> 14 numeric
|
| 4 |
+
features -> trained AutoGluon regressor -> PosterIQ design score on its 1-10
|
| 5 |
+
scale, plus one model-estimated feedback sentence (poster_inference.py).
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from threading import Lock
|
| 10 |
+
|
| 11 |
+
import gradio as gr
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import pytesseract
|
| 14 |
+
from PIL import Image
|
| 15 |
+
|
| 16 |
+
from features import FEATURE_COLUMNS, MIN_SIDE_PX, extract_features
|
| 17 |
+
from poster_inference import PosterScorer
|
| 18 |
+
|
| 19 |
+
EXAMPLES_DIR = Path(__file__).resolve().parent / "examples"
|
| 20 |
+
LOWER_QUARTILE = 4.0 # Dataset quartiles of overall_design_score
|
| 21 |
+
UPPER_QUARTILE = 5.9
|
| 22 |
+
MIN_CONTENT_FRAC = 0.01 # Below this the poster is treated as blank
|
| 23 |
+
MAX_PIXELS = 40_000_000 # Same upload limit as api.py
|
| 24 |
+
|
| 25 |
+
# Load once per process; a broken bundle should fail startup, never fall back to a heuristic
|
| 26 |
+
SCORER = PosterScorer()
|
| 27 |
+
MODEL_SOURCE = f"Trained model: {SCORER.predictor.model_best}"
|
| 28 |
+
SCORING_LOCK = Lock() # OCR runs in parallel, model calls one at a time as in api.py
|
| 29 |
+
|
| 30 |
+
SCOPE_NOTE = (
|
| 31 |
+
"The model predicts PosterIQ overall design quality from text and layout measurements. "
|
| 32 |
+
"The feedback is the change the model estimates would raise its score most, "
|
| 33 |
+
"not a proven cause or a guaranteed improvement."
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def design_band(score):
|
| 38 |
+
"""Map a 1-10 predicted design score to its dataset quartile band."""
|
| 39 |
+
if score < LOWER_QUARTILE:
|
| 40 |
+
return "Below typical"
|
| 41 |
+
if score < UPPER_QUARTILE:
|
| 42 |
+
return "Typical"
|
| 43 |
+
return "Above typical"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def lean_note(row):
|
| 47 |
+
"""Describe which side dominates, straight from the measurements."""
|
| 48 |
+
if row["word_count"] == 0:
|
| 49 |
+
return "No readable text was detected."
|
| 50 |
+
if row["text_share"] > 0.6:
|
| 51 |
+
return "Leans text-heavy."
|
| 52 |
+
if row["text_share"] < 0.2:
|
| 53 |
+
return "Leans graphic-heavy."
|
| 54 |
+
return "Text and graphics are roughly comparable in area."
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def empty_outputs(message):
|
| 58 |
+
"""Every early exit returns the same six outputs as a success."""
|
| 59 |
+
return None, "", "", pd.DataFrame(columns=["feature", "value"]), None, message
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def score_poster(image):
|
| 63 |
+
"""Callback: poster image in, score + verdict + feedback + features + overlay + status out."""
|
| 64 |
+
if image is None:
|
| 65 |
+
return empty_outputs("Upload a poster image, then select Score poster.")
|
| 66 |
+
if not isinstance(image, Image.Image):
|
| 67 |
+
return empty_outputs("Use a PNG, JPG, or WEBP image file.")
|
| 68 |
+
if min(image.size) < MIN_SIDE_PX:
|
| 69 |
+
return empty_outputs(f"Image is too small; use at least {MIN_SIDE_PX}px on the shortest side.")
|
| 70 |
+
if image.width * image.height > MAX_PIXELS:
|
| 71 |
+
return empty_outputs("Image is too large; use at most 40 million pixels.")
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
row, overlay = extract_features(image) # OCR once; the scorer reuses these measurements
|
| 75 |
+
except pytesseract.TesseractNotFoundError:
|
| 76 |
+
return empty_outputs("OCR engine not found. Install Tesseract or set TESSERACT_CMD.")
|
| 77 |
+
|
| 78 |
+
# Long format table reads better than one very wide row
|
| 79 |
+
table = pd.DataFrame({"feature": FEATURE_COLUMNS, "value": [round(float(row[c]), 4) for c in FEATURE_COLUMNS]})
|
| 80 |
+
if row["text_area_frac"] + row["graphic_area_frac"] < MIN_CONTENT_FRAC:
|
| 81 |
+
# Nearly blank input: a score here would be meaningless
|
| 82 |
+
return None, "", "", table, overlay, "Almost no text or graphics were detected. Check that the image is a poster."
|
| 83 |
+
|
| 84 |
+
with SCORING_LOCK:
|
| 85 |
+
result = SCORER.score_features(row)
|
| 86 |
+
score = round(result["score"], 1) # Already clipped to 1..10; round before banding so both agree
|
| 87 |
+
status = f"{lean_note(row)} Source: {MODEL_SOURCE}. {SCOPE_NOTE}"
|
| 88 |
+
return score, design_band(score), result["feedback_sentence"], table, overlay, status
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
with gr.Blocks(title="Poster Scorer") as demo:
|
| 92 |
+
gr.Markdown(
|
| 93 |
+
"# Poster Scorer\n"
|
| 94 |
+
"Upload a poster to predict its PosterIQ overall design score on a 1 to 10 scale "
|
| 95 |
+
"and get one suggested layout change from the model. "
|
| 96 |
+
"The overlay shows what was measured: **orange boxes** are detected text, "
|
| 97 |
+
"**blue tint** is graphic area."
|
| 98 |
+
)
|
| 99 |
+
with gr.Row():
|
| 100 |
+
with gr.Column():
|
| 101 |
+
image_in = gr.Image(type="pil", sources=["upload", "clipboard"], label="Poster")
|
| 102 |
+
score_btn = gr.Button("Score poster", variant="primary")
|
| 103 |
+
with gr.Column():
|
| 104 |
+
score_out = gr.Number(label="Predicted design score (1-10)", precision=1, interactive=False)
|
| 105 |
+
band_out = gr.Textbox(label="Verdict", interactive=False)
|
| 106 |
+
feedback_out = gr.Textbox(label="Model feedback", interactive=False, lines=2)
|
| 107 |
+
status_out = gr.Textbox(label="Interpretation", interactive=False, lines=3)
|
| 108 |
+
with gr.Row():
|
| 109 |
+
overlay_out = gr.Image(label="What the model measured", interactive=False)
|
| 110 |
+
table_out = gr.Dataframe(label="Extracted features (model input)", interactive=False)
|
| 111 |
+
|
| 112 |
+
outputs = [score_out, band_out, feedback_out, table_out, overlay_out, status_out]
|
| 113 |
+
score_btn.click(score_poster, image_in, outputs, api_name="score_poster", concurrency_limit=2)
|
| 114 |
+
# Clearing the input also clears stale results
|
| 115 |
+
image_in.clear(lambda: empty_outputs("Upload another poster."), outputs=outputs, api_name="clear_poster")
|
| 116 |
+
|
| 117 |
+
example_paths = sorted(p for p in EXAMPLES_DIR.glob("*") if p.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"})
|
| 118 |
+
if example_paths:
|
| 119 |
+
gr.Examples(
|
| 120 |
+
examples=[[str(p)] for p in example_paths], inputs=image_in, outputs=outputs,
|
| 121 |
+
fn=score_poster, run_on_click=True, cache_examples=False,
|
| 122 |
+
label="Click an example to score it",
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
demo.queue().launch()
|
artifacts/poster_scorer_model.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7f253f8a1eeeef1cb653e8292ab11d31c54240596c148d0c79180151e2d0872e
|
| 3 |
+
size 1594888
|
examples/balanced.png
ADDED
|
examples/graphic_heavy.png
ADDED
|
examples/text_heavy.png
ADDED
|
Git LFS Details
|
features.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Poster feature extraction shared by training and the Gradio app.
|
| 2 |
+
|
| 3 |
+
Training and inference must call the same function, otherwise the model
|
| 4 |
+
sees differently computed columns at serving time (train/serve skew).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytesseract
|
| 11 |
+
from PIL import Image, ImageDraw, ImageFilter, ImageOps
|
| 12 |
+
|
| 13 |
+
# Allow a custom Tesseract path on Windows without editing code
|
| 14 |
+
if os.environ.get("TESSERACT_CMD"):
|
| 15 |
+
pytesseract.pytesseract.tesseract_cmd = os.environ["TESSERACT_CMD"]
|
| 16 |
+
|
| 17 |
+
# Column order is the model contract; training must use this exact list
|
| 18 |
+
FEATURE_COLUMNS = [
|
| 19 |
+
"img_width_px",
|
| 20 |
+
"img_height_px",
|
| 21 |
+
"aspect_ratio",
|
| 22 |
+
"word_count",
|
| 23 |
+
"char_count",
|
| 24 |
+
"text_block_count",
|
| 25 |
+
"text_area_frac",
|
| 26 |
+
"graphic_area_frac",
|
| 27 |
+
"background_area_frac",
|
| 28 |
+
"text_share",
|
| 29 |
+
"text_to_graphic_ratio",
|
| 30 |
+
"mean_text_height_frac",
|
| 31 |
+
"max_text_height_frac",
|
| 32 |
+
"text_height_std_frac",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
MAX_SIDE_PX = 1600 # Normalize scale so OCR speed and noise stay consistent
|
| 36 |
+
MIN_SIDE_PX = 200 # Below this OCR output is unreliable, so reject
|
| 37 |
+
MIN_WORD_CONF = 60 # Tesseract confidence floor for keeping a word
|
| 38 |
+
BOX_PAD_PX = 3 # Small pad so anti-aliased glyph edges count as text
|
| 39 |
+
BG_DIST_THRESHOLD = 40.0 # RGB distance separating content from background
|
| 40 |
+
BORDER_FRAC = 0.03 # Border strip width used to estimate background color
|
| 41 |
+
RATIO_EPS = 1e-3 # Caps text_to_graphic_ratio when no graphics are found
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def prepare_image(image):
|
| 45 |
+
"""Apply EXIF rotation, force RGB, and downscale large posters."""
|
| 46 |
+
image = ImageOps.exif_transpose(image).convert("RGB") # Phone photos often carry rotation tags
|
| 47 |
+
scale = MAX_SIDE_PX / max(image.size) # Only shrink, never upscale small images
|
| 48 |
+
if scale < 1:
|
| 49 |
+
new_size = (round(image.width * scale), round(image.height * scale))
|
| 50 |
+
image = image.resize(new_size, Image.LANCZOS) # Lanczos keeps small text edges sharp
|
| 51 |
+
return image
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _ocr_words(image):
|
| 55 |
+
"""Run Tesseract and keep confident, non-empty word boxes."""
|
| 56 |
+
# PSM 11 finds sparse text anywhere, which suits poster layouts
|
| 57 |
+
gray = ImageOps.grayscale(image) # Color shapes confuse Tesseract layout analysis
|
| 58 |
+
data = pytesseract.image_to_data(
|
| 59 |
+
gray, config="--psm 11", output_type=pytesseract.Output.DICT
|
| 60 |
+
)
|
| 61 |
+
words = []
|
| 62 |
+
for i, text in enumerate(data["text"]):
|
| 63 |
+
text = text.strip()
|
| 64 |
+
conf = float(data["conf"][i]) # Tesseract returns -1 for non-word rows
|
| 65 |
+
n_alnum = sum(c.isalnum() for c in text)
|
| 66 |
+
if conf < MIN_WORD_CONF or (n_alnum < 2 and not text.isdigit()):
|
| 67 |
+
continue # Single glyphs on shapes are the most common false positive
|
| 68 |
+
words.append({
|
| 69 |
+
"text": text,
|
| 70 |
+
"left": data["left"][i],
|
| 71 |
+
"top": data["top"][i],
|
| 72 |
+
"width": data["width"][i],
|
| 73 |
+
"height": data["height"][i],
|
| 74 |
+
"block": (data["page_num"][i], data["block_num"][i]), # Unique block id
|
| 75 |
+
})
|
| 76 |
+
return words
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _background_color(rgb):
|
| 80 |
+
"""Estimate background as the median color of the border strip."""
|
| 81 |
+
h, w, _ = rgb.shape
|
| 82 |
+
b = max(1, int(min(h, w) * BORDER_FRAC)) # Strip width scales with poster size
|
| 83 |
+
border = np.concatenate([
|
| 84 |
+
rgb[:b].reshape(-1, 3), rgb[-b:].reshape(-1, 3),
|
| 85 |
+
rgb[:, :b].reshape(-1, 3), rgb[:, -b:].reshape(-1, 3),
|
| 86 |
+
])
|
| 87 |
+
return np.median(border, axis=0) # Median resists logos touching the edge
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def extract_features(image):
|
| 91 |
+
"""Return (feature dict, overlay image) for one poster.
|
| 92 |
+
|
| 93 |
+
The overlay shades detected graphics blue and outlines text in orange
|
| 94 |
+
so a user can check what the numbers were computed from.
|
| 95 |
+
"""
|
| 96 |
+
original_w, original_h = image.size # Report true size, not the resized one
|
| 97 |
+
img = prepare_image(image)
|
| 98 |
+
w, h = img.size
|
| 99 |
+
|
| 100 |
+
words = _ocr_words(img)
|
| 101 |
+
|
| 102 |
+
# Text mask: union of padded word boxes
|
| 103 |
+
text_mask = np.zeros((h, w), dtype=bool)
|
| 104 |
+
for wd in words:
|
| 105 |
+
x0 = max(0, wd["left"] - BOX_PAD_PX)
|
| 106 |
+
y0 = max(0, wd["top"] - BOX_PAD_PX)
|
| 107 |
+
x1 = min(w, wd["left"] + wd["width"] + BOX_PAD_PX)
|
| 108 |
+
y1 = min(h, wd["top"] + wd["height"] + BOX_PAD_PX)
|
| 109 |
+
text_mask[y0:y1, x0:x1] = True
|
| 110 |
+
|
| 111 |
+
# Content mask: pixels far from the background color after denoising
|
| 112 |
+
smooth = np.asarray(img.filter(ImageFilter.MedianFilter(5)), dtype=np.float32)
|
| 113 |
+
bg = _background_color(smooth)
|
| 114 |
+
dist = np.linalg.norm(smooth - bg, axis=2) # Per-pixel RGB distance to background
|
| 115 |
+
content_mask = dist > BG_DIST_THRESHOLD
|
| 116 |
+
|
| 117 |
+
# Graphics are content that is not inside a text box
|
| 118 |
+
graphic_mask = content_mask & ~text_mask
|
| 119 |
+
|
| 120 |
+
text_frac = float(text_mask.mean())
|
| 121 |
+
graphic_frac = float(graphic_mask.mean())
|
| 122 |
+
heights = np.array([wd["height"] / h for wd in words]) if words else np.zeros(1)
|
| 123 |
+
|
| 124 |
+
row = {
|
| 125 |
+
"img_width_px": original_w,
|
| 126 |
+
"img_height_px": original_h,
|
| 127 |
+
"aspect_ratio": original_w / original_h,
|
| 128 |
+
"word_count": len(words),
|
| 129 |
+
"char_count": sum(len(wd["text"]) for wd in words),
|
| 130 |
+
"text_block_count": len({wd["block"] for wd in words}),
|
| 131 |
+
"text_area_frac": text_frac,
|
| 132 |
+
"graphic_area_frac": graphic_frac,
|
| 133 |
+
"background_area_frac": max(0.0, 1.0 - text_frac - graphic_frac),
|
| 134 |
+
# Bounded 0..1 share is easier for models than an unbounded ratio
|
| 135 |
+
"text_share": text_frac / (text_frac + graphic_frac) if (text_frac + graphic_frac) > 0 else 0.0,
|
| 136 |
+
"text_to_graphic_ratio": text_frac / max(graphic_frac, RATIO_EPS),
|
| 137 |
+
"mean_text_height_frac": float(heights.mean()),
|
| 138 |
+
"max_text_height_frac": float(heights.max()),
|
| 139 |
+
"text_height_std_frac": float(heights.std()),
|
| 140 |
+
}
|
| 141 |
+
assert list(row) == FEATURE_COLUMNS, "Feature dict drifted from FEATURE_COLUMNS."
|
| 142 |
+
return row, _draw_overlay(img, graphic_mask, words)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _draw_overlay(img, graphic_mask, words):
|
| 146 |
+
"""Tint graphic pixels blue and outline each OCR word box."""
|
| 147 |
+
base = np.asarray(img, dtype=np.float32)
|
| 148 |
+
tint = np.array([40, 110, 255], dtype=np.float32)
|
| 149 |
+
base[graphic_mask] = 0.55 * base[graphic_mask] + 0.45 * tint # Semi-transparent blend
|
| 150 |
+
overlay = Image.fromarray(base.astype(np.uint8))
|
| 151 |
+
draw = ImageDraw.Draw(overlay)
|
| 152 |
+
for wd in words:
|
| 153 |
+
box = [wd["left"], wd["top"], wd["left"] + wd["width"], wd["top"] + wd["height"]]
|
| 154 |
+
draw.rectangle(box, outline=(255, 140, 0), width=3) # Orange reads on most palettes
|
| 155 |
+
return overlay
|
packages.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tesseract-ocr
|
| 2 |
+
libgomp1
|
poster_inference.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable GUI interface to the bundled poster score model and feedback recipe."""
|
| 2 |
+
import hashlib
|
| 3 |
+
from importlib.metadata import version
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path, PurePosixPath
|
| 6 |
+
import shutil
|
| 7 |
+
import stat
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
import zipfile
|
| 11 |
+
|
| 12 |
+
ROOT = Path(__file__).resolve().parent
|
| 13 |
+
DEFAULT_BUNDLE = ROOT / "artifacts/poster_scorer_model.zip"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _validate_manifest(manifest, columns):
|
| 17 |
+
if manifest.get("schema_version") != 1:
|
| 18 |
+
raise ValueError("Unsupported model bundle schema")
|
| 19 |
+
if manifest.get("target") != "overall_design_score":
|
| 20 |
+
raise ValueError("Bundle target is not overall_design_score")
|
| 21 |
+
if manifest.get("feature_columns") != columns:
|
| 22 |
+
raise ValueError("Model bundle feature contract does not match features.py")
|
| 23 |
+
extractor_hash = hashlib.sha256((ROOT / "features.py").read_bytes()).hexdigest()
|
| 24 |
+
if manifest.get("extractor_sha256") != extractor_hash:
|
| 25 |
+
raise ValueError("Feature extractor differs from the version used to train this model")
|
| 26 |
+
if manifest.get("autogluon_version") != version("autogluon.tabular"):
|
| 27 |
+
raise ValueError("Install the AutoGluon version specified in the model manifest")
|
| 28 |
+
expected_python = manifest.get("python_version")
|
| 29 |
+
if expected_python and expected_python.split(".")[:2] != [str(sys.version_info.major), str(sys.version_info.minor)]:
|
| 30 |
+
raise ValueError(f"This model bundle requires Python {expected_python}")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _extract_bundle(bundle_path, cache_dir):
|
| 34 |
+
"""Unpack a content-addressed bundle, rejecting path traversal and symlinks."""
|
| 35 |
+
bundle_path, cache_dir = Path(bundle_path).resolve(), Path(cache_dir).resolve()
|
| 36 |
+
if not bundle_path.is_file():
|
| 37 |
+
raise FileNotFoundError(f"Model bundle not found: {bundle_path}")
|
| 38 |
+
digest = hashlib.sha256(bundle_path.read_bytes()).hexdigest()
|
| 39 |
+
destination = cache_dir / digest
|
| 40 |
+
marker = destination / ".bundle_sha256"
|
| 41 |
+
if marker.is_file() and marker.read_text().strip() == digest:
|
| 42 |
+
return destination
|
| 43 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 44 |
+
temporary = Path(tempfile.mkdtemp(prefix="unpack-", dir=cache_dir))
|
| 45 |
+
try:
|
| 46 |
+
with zipfile.ZipFile(bundle_path) as archive:
|
| 47 |
+
entries = archive.infolist()
|
| 48 |
+
if len(entries) > 10000 or sum(item.file_size for item in entries) > 2_000_000_000:
|
| 49 |
+
raise ValueError("Model bundle exceeds extraction limits")
|
| 50 |
+
names = [item.filename for item in entries]
|
| 51 |
+
if len(names) != len(set(names)):
|
| 52 |
+
raise ValueError("Duplicate archive entries are not allowed")
|
| 53 |
+
required = {"metrics.json", "feedback_recipe.json", "model_manifest.json", "model/predictor.pkl"}
|
| 54 |
+
if not required.issubset(names):
|
| 55 |
+
raise ValueError("Model bundle is missing required artifacts")
|
| 56 |
+
for item in entries:
|
| 57 |
+
name = item.filename
|
| 58 |
+
path = PurePosixPath(name)
|
| 59 |
+
mode = item.external_attr >> 16
|
| 60 |
+
if (path.is_absolute() or ".." in path.parts or "\\" in name or ":" in name
|
| 61 |
+
or stat.S_ISLNK(mode) or not (temporary / name).resolve().is_relative_to(temporary)):
|
| 62 |
+
raise ValueError(f"Unsafe model bundle entry: {name}")
|
| 63 |
+
archive.extractall(temporary)
|
| 64 |
+
(temporary / ".bundle_sha256").write_text(digest + "\n")
|
| 65 |
+
try:
|
| 66 |
+
temporary.rename(destination)
|
| 67 |
+
except FileExistsError:
|
| 68 |
+
if not marker.is_file() or marker.read_text().strip() != digest:
|
| 69 |
+
raise ValueError("Incomplete model cache; remove the indicated cache directory")
|
| 70 |
+
return destination
|
| 71 |
+
finally:
|
| 72 |
+
if temporary.exists():
|
| 73 |
+
shutil.rmtree(temporary)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class PosterScorer:
|
| 77 |
+
"""Load once per GUI process, then score any number of posters."""
|
| 78 |
+
|
| 79 |
+
def __init__(self, bundle_path=None, cache_dir=None):
|
| 80 |
+
from features import FEATURE_COLUMNS
|
| 81 |
+
from autogluon.tabular import TabularPredictor
|
| 82 |
+
from score_feedback import ScoreOptimizer
|
| 83 |
+
|
| 84 |
+
self.bundle_dir = _extract_bundle(bundle_path or DEFAULT_BUNDLE, cache_dir or ROOT / "models/gui-cache")
|
| 85 |
+
self.manifest = json.loads((self.bundle_dir / "model_manifest.json").read_text())
|
| 86 |
+
_validate_manifest(self.manifest, FEATURE_COLUMNS)
|
| 87 |
+
metrics = json.loads((self.bundle_dir / "metrics.json").read_text())
|
| 88 |
+
if metrics.get("feature_columns") != FEATURE_COLUMNS or metrics.get("target") != self.manifest["target"]:
|
| 89 |
+
raise ValueError("Metrics and manifest feature/target contracts differ")
|
| 90 |
+
self.predictor = TabularPredictor.load(str(self.bundle_dir / "model"))
|
| 91 |
+
self.optimizer = ScoreOptimizer.load_recipe(self.predictor, self.bundle_dir / "feedback_recipe.json")
|
| 92 |
+
if self.optimizer.feature_names != FEATURE_COLUMNS:
|
| 93 |
+
raise ValueError("Feedback recipe and extractor feature contracts differ")
|
| 94 |
+
|
| 95 |
+
def score_features(self, features):
|
| 96 |
+
"""Return score, raw_score, one feedback sentence and ranked changes."""
|
| 97 |
+
result = self.optimizer.analyze(features)
|
| 98 |
+
result["raw_score"] = result["score"]
|
| 99 |
+
result["score"] = min(10.0, max(1.0, result["raw_score"]))
|
| 100 |
+
return result
|
| 101 |
+
|
| 102 |
+
def score_image(self, image):
|
| 103 |
+
"""Accept a PIL image and return the score result, features and PIL overlay."""
|
| 104 |
+
from features import extract_features
|
| 105 |
+
features, overlay = extract_features(image)
|
| 106 |
+
result = self.score_features(features)
|
| 107 |
+
result.update(features=features, overlay=overlay)
|
| 108 |
+
return result
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Gradio Space runtime; versions match the trained bundle (requirements-inference.txt, artifacts/model_manifest.json)
|
| 2 |
+
autogluon.tabular[lightgbm]==1.5.0
|
| 3 |
+
numpy==2.3.5
|
| 4 |
+
pandas==2.3.3
|
| 5 |
+
scipy==1.16.3
|
| 6 |
+
scikit-learn==1.7.2
|
| 7 |
+
lightgbm==4.6.0
|
| 8 |
+
Pillow==12.3.0
|
| 9 |
+
pytesseract==0.3.13
|
| 10 |
+
typing-extensions>=4.10,<5
|
score_feedback.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Continuous score feedback adapted from the supplied temp.py ScoreOptimizer.
|
| 2 |
+
|
| 3 |
+
This searches training quantiles using an already-trained predictor; it does not
|
| 4 |
+
train a second model or identify causal feature harm. Text/graphic area, text-count and text-height groups are actionable.
|
| 5 |
+
Geometry stays fixed; related measurements are updated as coherent groups.
|
| 6 |
+
Count/height edits assume text area scales proportionally; this is a model
|
| 7 |
+
probe, not an image edit or a guarantee of realizable design improvement.
|
| 8 |
+
"""
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
AREA_FEATURES = ("text_area_frac", "graphic_area_frac")
|
| 17 |
+
GROUPS = {"word_count": ("word_count", "char_count", "text_block_count"),
|
| 18 |
+
"mean_text_height_frac": ("mean_text_height_frac", "max_text_height_frac", "text_height_std_frac")}
|
| 19 |
+
DERIVED = ("background_area_frac", "text_share", "text_to_graphic_ratio")
|
| 20 |
+
RATIO_EPS = 1e-3 # Same definition as features.extract_features.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class ScoreOptimizer:
|
| 24 |
+
"""Attach to a fitted predictor and learn candidate values from TRAIN only."""
|
| 25 |
+
|
| 26 |
+
def __init__(self, predictor, train_features, feature_names=None, training_ids=None):
|
| 27 |
+
self.predictor = predictor
|
| 28 |
+
self.feature_names = list(feature_names or train_features.columns)
|
| 29 |
+
train = self._validate(train_features)
|
| 30 |
+
if train.empty:
|
| 31 |
+
raise ValueError("Training features cannot be empty")
|
| 32 |
+
self.actionable = list(AREA_FEATURES) + [name for name, group in GROUPS.items()
|
| 33 |
+
if set(group).issubset(self.feature_names)]
|
| 34 |
+
self.quantiles = {
|
| 35 |
+
name: np.unique(train[name].quantile(np.linspace(0.05, 0.95, 19))).tolist()
|
| 36 |
+
for name in self.actionable
|
| 37 |
+
}
|
| 38 |
+
self.recipe = {
|
| 39 |
+
"version": 1, "method": "training_quantile_group_counterfactuals", "fit_split": "train",
|
| 40 |
+
"training_rows": len(train), "feature_columns": self.feature_names,
|
| 41 |
+
"actionable_features": self.actionable, "quantiles": self.quantiles,
|
| 42 |
+
"coupled_groups": {name: list(group) + ["text_area_frac"] + list(DERIVED)
|
| 43 |
+
for name, group in GROUPS.items() if name in self.actionable},
|
| 44 |
+
"immutable_features": [c for c in self.feature_names if c not in AREA_FEATURES + DERIVED + tuple(x for group in GROUPS.values() for x in group)],
|
| 45 |
+
"interpretation": "Model-estimated layout changes, not causal attribution or feedback labels.",
|
| 46 |
+
}
|
| 47 |
+
if training_ids is not None:
|
| 48 |
+
ids = sorted(str(value) for value in training_ids)
|
| 49 |
+
if len(ids) != len(train) or len(set(ids)) != len(ids):
|
| 50 |
+
raise ValueError("Training IDs must uniquely match training rows")
|
| 51 |
+
self.recipe["training_ids_sha256"] = hashlib.sha256("\n".join(ids).encode()).hexdigest()
|
| 52 |
+
|
| 53 |
+
def save_recipe(self, path):
|
| 54 |
+
Path(path).write_text(json.dumps(self.recipe, indent=2, allow_nan=False) + "\n")
|
| 55 |
+
|
| 56 |
+
@classmethod
|
| 57 |
+
def load_recipe(cls, predictor, path):
|
| 58 |
+
"""Reuse fitted candidate metadata without reading any dataset splits."""
|
| 59 |
+
recipe = json.loads(Path(path).read_text())
|
| 60 |
+
if recipe.get("fit_split") != "train" or recipe.get("version") != 1:
|
| 61 |
+
raise ValueError("Expected a version 1 recipe fitted on train")
|
| 62 |
+
obj = cls.__new__(cls)
|
| 63 |
+
obj.predictor = predictor
|
| 64 |
+
obj.recipe = recipe
|
| 65 |
+
obj.feature_names = recipe["feature_columns"]
|
| 66 |
+
obj.actionable = recipe["actionable_features"]
|
| 67 |
+
obj.quantiles = recipe["quantiles"]
|
| 68 |
+
if not set(obj.actionable).issubset(set(AREA_FEATURES) | set(GROUPS)):
|
| 69 |
+
raise ValueError("Unknown actionable feature in recipe")
|
| 70 |
+
for name in obj.actionable:
|
| 71 |
+
values = np.asarray(obj.quantiles[name], dtype=float)
|
| 72 |
+
if not len(values) or not np.isfinite(values).all() or (values < 0).any():
|
| 73 |
+
raise ValueError("Invalid candidate values in feedback recipe")
|
| 74 |
+
return obj
|
| 75 |
+
|
| 76 |
+
def _validate(self, frame):
|
| 77 |
+
missing = set(self.feature_names) - set(frame.columns)
|
| 78 |
+
if missing:
|
| 79 |
+
raise ValueError(f"Missing required features: {sorted(missing)}")
|
| 80 |
+
required_areas = set(AREA_FEATURES + DERIVED)
|
| 81 |
+
if not required_areas.issubset(self.feature_names):
|
| 82 |
+
raise ValueError("Feedback requires the five shared area features")
|
| 83 |
+
values = frame[self.feature_names].apply(pd.to_numeric, errors="raise").astype(float)
|
| 84 |
+
if not np.isfinite(values.to_numpy()).all():
|
| 85 |
+
raise ValueError("Feedback requires finite, non-missing feature values")
|
| 86 |
+
for column in values:
|
| 87 |
+
if (values[column] < 0).any():
|
| 88 |
+
raise ValueError(f"{column} cannot be negative")
|
| 89 |
+
if (column.endswith("_frac") or column == "text_share") and (values[column] > 1).any():
|
| 90 |
+
raise ValueError(f"{column} must be between 0 and 1")
|
| 91 |
+
text, graphic = values[AREA_FEATURES[0]], values[AREA_FEATURES[1]]
|
| 92 |
+
if (text + graphic > 1 + 1e-8).any():
|
| 93 |
+
raise ValueError("Text and graphic areas cannot exceed the image area")
|
| 94 |
+
expected = {
|
| 95 |
+
"background_area_frac": np.maximum(0, 1 - text - graphic),
|
| 96 |
+
"text_share": np.divide(text, text + graphic, out=np.zeros(len(text)), where=(text + graphic) > 0),
|
| 97 |
+
"text_to_graphic_ratio": text / np.maximum(graphic, RATIO_EPS),
|
| 98 |
+
}
|
| 99 |
+
for column, expected_values in expected.items():
|
| 100 |
+
if not np.allclose(values[column], expected_values, rtol=1e-5, atol=1e-7):
|
| 101 |
+
raise ValueError(f"Inconsistent derived feature: {column}")
|
| 102 |
+
return values.reset_index(drop=True)
|
| 103 |
+
|
| 104 |
+
def candidate_rows(self, features):
|
| 105 |
+
"""Return feasible rows and (feature, old value, new value) descriptions."""
|
| 106 |
+
base = self._validate(pd.DataFrame([features])).iloc[0]
|
| 107 |
+
rows, descriptions = [], []
|
| 108 |
+
for feature in self.actionable:
|
| 109 |
+
if feature != "graphic_area_frac" and (base["text_area_frac"] == 0 or base.get("word_count", 1) == 0):
|
| 110 |
+
continue
|
| 111 |
+
for value in self.quantiles[feature]:
|
| 112 |
+
if feature == "word_count":
|
| 113 |
+
value = float(round(value))
|
| 114 |
+
if np.isclose(value, base[feature]):
|
| 115 |
+
continue
|
| 116 |
+
row = base.copy()
|
| 117 |
+
row[feature] = value
|
| 118 |
+
if feature in GROUPS:
|
| 119 |
+
if value <= 0 or base[feature] <= 0:
|
| 120 |
+
continue
|
| 121 |
+
factor = value / base[feature]
|
| 122 |
+
if feature == "word_count":
|
| 123 |
+
row["char_count"] = max(value, round(base["char_count"] * factor))
|
| 124 |
+
row["text_block_count"] = min(value, max(1, round(base["text_block_count"] * factor)))
|
| 125 |
+
else:
|
| 126 |
+
row["max_text_height_frac"] = base["max_text_height_frac"] * factor
|
| 127 |
+
row["text_height_std_frac"] = base["text_height_std_frac"] * factor
|
| 128 |
+
if row["max_text_height_frac"] > 1 or row["text_height_std_frac"] > row["max_text_height_frac"] / 2 + 1e-8:
|
| 129 |
+
continue
|
| 130 |
+
row["text_area_frac"] = base["text_area_frac"] * factor
|
| 131 |
+
text, graphic = row["text_area_frac"], row["graphic_area_frac"]
|
| 132 |
+
if text < 0 or graphic < 0 or text + graphic > 1 or (text == 0 and base.get("word_count", 0) > 0):
|
| 133 |
+
continue
|
| 134 |
+
row["background_area_frac"] = max(0.0, 1 - text - graphic)
|
| 135 |
+
row["text_share"] = text / (text + graphic) if text + graphic > 0 else 0.0
|
| 136 |
+
row["text_to_graphic_ratio"] = text / max(graphic, RATIO_EPS)
|
| 137 |
+
changes = {name: float(row[name]) for name in self.feature_names if not np.isclose(row[name], base[name])}
|
| 138 |
+
rows.append(row)
|
| 139 |
+
descriptions.append((feature, float(base[feature]), float(value), changes))
|
| 140 |
+
return pd.DataFrame(rows, columns=self.feature_names), descriptions
|
| 141 |
+
|
| 142 |
+
def analyze_many(self, features, top_k=3, min_improvement=1e-6):
|
| 143 |
+
"""Score every input and all feasible candidates in one prediction batch."""
|
| 144 |
+
if top_k < 1 or min_improvement < 0:
|
| 145 |
+
raise ValueError("top_k must be positive and min_improvement nonnegative")
|
| 146 |
+
base = self._validate(features)
|
| 147 |
+
if base.empty:
|
| 148 |
+
return []
|
| 149 |
+
parts, metadata = [base], []
|
| 150 |
+
for index, row in base.iterrows():
|
| 151 |
+
candidates, descriptions = self.candidate_rows(row.to_dict())
|
| 152 |
+
parts.append(candidates)
|
| 153 |
+
metadata.extend((index, *description) for description in descriptions)
|
| 154 |
+
scores = np.asarray(self.predictor.predict(pd.concat(parts, ignore_index=True)), dtype=float)
|
| 155 |
+
if len(scores) != sum(len(part) for part in parts) or not np.isfinite(scores).all():
|
| 156 |
+
raise ValueError("Predictor returned invalid scores")
|
| 157 |
+
results = [{"score": float(score), "ranked_changes": [], "best_recommendation": None,
|
| 158 |
+
"best_feature": None, "best_gain": None, "best_direction": None,
|
| 159 |
+
"supported_features": self.actionable,
|
| 160 |
+
"feedback_sentence": "The model found no tested layout change likely to improve this poster’s score.",
|
| 161 |
+
"message": "No tested feature-group change improved the model's predicted score."}
|
| 162 |
+
for score in scores[:len(base)]]
|
| 163 |
+
best_by_row = [{} for _ in range(len(base))]
|
| 164 |
+
for (index, feature, old, new, changes), score in zip(metadata, scores[len(base):]):
|
| 165 |
+
change = {"feature": feature, "current_value": old, "suggested_value": new,
|
| 166 |
+
"direction": "increase" if new > old else "decrease", "coupled_feature_updates": changes,
|
| 167 |
+
"predicted_score": float(score), "gain": float(score - results[index]["score"])}
|
| 168 |
+
previous = best_by_row[index].get(feature)
|
| 169 |
+
if previous is None or change["gain"] > previous["gain"]:
|
| 170 |
+
best_by_row[index][feature] = change
|
| 171 |
+
for result, best in zip(results, best_by_row):
|
| 172 |
+
ranked = sorted(best.values(), key=lambda item: item["gain"], reverse=True)[:top_k]
|
| 173 |
+
result["ranked_changes"] = ranked # Signed gains include zero/negative outcomes.
|
| 174 |
+
if ranked and ranked[0]["gain"] > min_improvement:
|
| 175 |
+
recommendation = ranked[0]
|
| 176 |
+
result.update(best_recommendation=recommendation, best_feature=recommendation["feature"],
|
| 177 |
+
best_gain=recommendation["gain"], best_direction=recommendation["direction"],
|
| 178 |
+
message="Largest estimated gain among tested feature-group changes; not a causal diagnosis.")
|
| 179 |
+
labels = {"text_area_frac": "text coverage", "graphic_area_frac": "graphic coverage",
|
| 180 |
+
"word_count": "the amount of text", "mean_text_height_frac": "text size"}
|
| 181 |
+
action = "increasing" if recommendation["direction"] == "increase" else "decreasing"
|
| 182 |
+
result["feedback_sentence"] = (
|
| 183 |
+
f"The model suggests {action} {labels[recommendation['feature']]} "
|
| 184 |
+
"as the most promising change for this poster."
|
| 185 |
+
)
|
| 186 |
+
return results
|
| 187 |
+
|
| 188 |
+
def analyze(self, features, **kwargs):
|
| 189 |
+
return self.analyze_many(pd.DataFrame([features]), **kwargs)[0]
|