Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines6789101191 unmodified lines1031041051061071081091105 unmodified lines1161171181191201216 unmodified lines128129130131132133134135136107 unmodified lines24424524624724824925025125225325425530 unmodified lines2862872882892902912924 unmodified lines2972982993003013023033043053063073083093105 unmodified lines31631731831932032132227 unmodified lines3503513523533543553566 unmodified lines3633643653663673683695 unmodified linesimport kerasfrom huggingface_hub import snapshot_downloadimport pytesseract_msi_model = None91 unmodified linesreturn {"focus_score": round(focus_score, 1), "spread_score": round(spread_score, 1)}def compute_overall_grade(focus_score, spread_score, read):readability_score = max(0, 100 - read['contrast_issues'] * 15 - read['small_text_issues'] * 10)total = round(0.55 * focus_score + 0.20 * spread_score + 0.25 * readability_score)total = max(0, min(100, total))if total >= 75:5 unmodified linesreturn total, gradedef generate_recommendations(saliency_map, scores, read, img_h, img_w):tips = []bottom_band = saliency_map[int(img_h * 0.85):, :]6 unmodified lineselif scores['focus_score'] > 90:tips.append("Attention is very narrowly focused on one spot - double check other important elements (logo, CTA) are not being ignored.")if scores['spread_score'] < 3:tips.append("Very little of the design pulls attention beyond the main hotspot. Secondary elements may go unnoticed by viewers.")if read['contrast_issues'] > 0:if read['contrast_issues'] > 5:tips.append(f"A quick win: {read['contrast_issues']} text elements could read more clearly. The good news - the pattern (see white boxes marked \"Low contrast\" on the image) suggests one color choice affects most of them, so a single tweak will likely fix most at once.")107 unmodified linescontrast_issues += 1if len(issue_lines) < 5:severity = contrast_severity_label(ratio)issue_lines.append(f"- \"{word}\" is {severity} ({ratio:.1f}:1, needs 4.5:1 minimum)")issue_boxes.append({"box": (x, y, w, h), "label": "Low contrast"})if size_pct < 1.2:small_text_issues += 1if len(issue_lines) < 5:issue_lines.append(f"- Small text \"{word}\" ({size_pct:.1f}% of image height)")issue_boxes.append({"box": (x, y, w, h), "label": "Small text"})return {"words_checked": words_checked, "contrast_issues": contrast_issues,"small_text_issues": small_text_issues, "issue_lines": issue_lines, "issue_boxes": issue_boxes}30 unmodified linesdef analyze(pil_image, overlay_strength):if pil_image is None:return None, "Upload an image first."pil_rgb = pil_image.convert("RGB")img_bgr = cv2.cvtColor(np.array(pil_rgb), cv2.COLOR_RGB2BGR)h, w = img_bgr.shape[:2]4 unmodified linesscores = compute_attention_scores(saliency_map)zones = identify_hotspots(saliency_map, h, w)read = analyze_readability(pil_rgb)total_score, grade = compute_overall_grade(scores['focus_score'], scores['spread_score'], read)tips = generate_recommendations(saliency_map, scores, read, h, w)overlay_bgr = draw_zone_labels(overlay_bgr, zones)overlay_bgr = draw_issue_markers(overlay_bgr, read.get("issue_boxes", []))overlay_rgb = cv2.cvtColor(overlay_bgr, cv2.COLOR_BGR2RGB)summary = f"## Grade: {grade} — {total_score}/100\n\n"summary += "**Where Attention Goes First:** *(numbers match the image above)*\n"if zones:5 unmodified linessummary += (f"\n**Scores:**\n"f"- Clear Focal Point: {scores['focus_score']}/100 (how strongly attention lands on one main spot, vs scattered everywhere)\n"f"- Attention Coverage: {scores['spread_score']}/100 (how much of the whole design draws some interest, not just one hotspot)\n"f"- Readability: ")if read['words_checked'] == 0:27 unmodified lines"not a substitute for live user testing.")return Image.fromarray(overlay_rgb), summarywith gr.Blocks(title="Design Analyzer") as demo:6 unmodified linesanalyze_btn = gr.Button("Analyze", variant="primary")with gr.Column():image_output = gr.Image(label="Heatmap result")text_output = gr.Markdown()analyze_btn.click(fn=analyze, inputs=[image_input, strength_slider], outputs=[image_output, text_output])demo.launch()5 unmodified lines678910111213141591 unmodified lines1071081091101111121131141151161175 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781796 unmodified lines186187188189190191107 unmodified lines29930030130230330430530630730830931030 unmodified lines3413423433443453463474 unmodified lines3523533543553563573583593603613623633643653663673683695 unmodified lines37537637737837938038127 unmodified lines4094104114124134144156 unmodified lines4224234244254264274284295 unmodified linesimport kerasfrom huggingface_hub import snapshot_downloadimport pytesseractimport ioimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as plt_msi_model = None91 unmodified linesreturn {"focus_score": round(focus_score, 1), "spread_score": round(spread_score, 1)}def compute_readability_score(read):return max(0, 100 - read['contrast_issues'] * 15 - read['small_text_issues'] * 10)def compute_overall_grade(focus_score, spread_score, readability_score):total = round(0.55 * focus_score + 0.20 * spread_score + 0.25 * readability_score)total = max(0, min(100, total))if total >= 75:5 unmodified linesreturn total, gradedef explain_grade(focus_score, readability_score, read):total_issues = read['contrast_issues'] + read['small_text_issues']weighted_focus_deficit = 0.55 * max(0, 100 - focus_score)weighted_read_deficit = 0.25 * max(0, 100 - readability_score)if weighted_read_deficit >= weighted_focus_deficit and total_issues > 0:return "mainly due to text readability - some text is harder to read than ideal"elif focus_score < 50:return "mainly because attention is spread out, without one clear focal point"elif focus_score > 90:return "attention is very tightly focused on one spot - worth checking other key elements (logo, CTA) aren't being missed"else:return "a mix of small readability and focus factors - see details below"def coverage_description(spread_score):if spread_score < 15:return "concentrated on one clear focal point - that's usually a good sign, not a problem"elif spread_score < 40:return "landing mostly in a couple of areas, which is fairly typical"else:return "spread fairly widely across the design"def create_score_chart(focus_score, spread_score, readability_score):labels = ["Clear Focal\nPoint", "Attention\nCoverage", "Readability"]values = [focus_score, spread_score, readability_score]colors = []for v in values:if v >= 75:colors.append("#4CAF50")elif v >= 50:colors.append("#FFC107")else:colors.append("#F44336")fig, ax = plt.subplots(figsize=(5, 3), dpi=100)bars = ax.barh(labels, values, color=colors)ax.set_xlim(0, 100)ax.set_xlabel("Score out of 100")ax.invert_yaxis()for bar, v in zip(bars, values):ax.text(min(v + 2, 92), bar.get_y() + bar.get_height() / 2, f"{v:.0f}", va="center", fontsize=10)ax.set_title("Scores at a Glance")fig.tight_layout()buf = io.BytesIO()fig.savefig(buf, format="png")plt.close(fig)buf.seek(0)return Image.open(buf).convert("RGB")def generate_recommendations(saliency_map, scores, read, img_h, img_w):tips = []bottom_band = saliency_map[int(img_h * 0.85):, :]6 unmodified lineselif scores['focus_score'] > 90:tips.append("Attention is very narrowly focused on one spot - double check other important elements (logo, CTA) are not being ignored.")if read['contrast_issues'] > 0:if read['contrast_issues'] > 5:tips.append(f"A quick win: {read['contrast_issues']} text elements could read more clearly. The good news - the pattern (see white boxes marked \"Low contrast\" on the image) suggests one color choice affects most of them, so a single tweak will likely fix most at once.")107 unmodified linescontrast_issues += 1if len(issue_lines) < 5:severity = contrast_severity_label(ratio)issue_lines.append(f"- \"{word}\" {severity} against its background")issue_boxes.append({"box": (x, y, w, h), "label": "Low contrast"})if size_pct < 1.2:small_text_issues += 1if len(issue_lines) < 5:issue_lines.append(f"- \"{word}\" is a bit small to read comfortably")issue_boxes.append({"box": (x, y, w, h), "label": "Small text"})return {"words_checked": words_checked, "contrast_issues": contrast_issues,"small_text_issues": small_text_issues, "issue_lines": issue_lines, "issue_boxes": issue_boxes}30 unmodified linesdef analyze(pil_image, overlay_strength):if pil_image is None:return None, None, "Upload an image first."pil_rgb = pil_image.convert("RGB")img_bgr = cv2.cvtColor(np.array(pil_rgb), cv2.COLOR_RGB2BGR)h, w = img_bgr.shape[:2]4 unmodified linesscores = compute_attention_scores(saliency_map)zones = identify_hotspots(saliency_map, h, w)read = analyze_readability(pil_rgb)readability_score = compute_readability_score(read)total_score, grade = compute_overall_grade(scores['focus_score'], scores['spread_score'], readability_score)grade_reason = explain_grade(scores['focus_score'], readability_score, read)tips = generate_recommendations(saliency_map, scores, read, h, w)chart_image = create_score_chart(scores['focus_score'], scores['spread_score'], readability_score)overlay_bgr = draw_zone_labels(overlay_bgr, zones)overlay_bgr = draw_issue_markers(overlay_bgr, read.get("issue_boxes", []))overlay_rgb = cv2.cvtColor(overlay_bgr, cv2.COLOR_BGR2RGB)summary = f"## Grade: {grade} — {total_score}/100\n"summary += f"*Why: {grade_reason}*\n\n"summary += "**Where Attention Goes First:** *(numbers match the image above)*\n"if zones:5 unmodified linessummary += (f"\n**Scores:**\n"f"- Clear Focal Point: {scores['focus_score']}/100 (how strongly attention lands on one main spot, vs scattered everywhere)\n"f"- Attention Coverage: {scores['spread_score']}/100 - {coverage_description(scores['spread_score'])}\n"f"- Readability: ")if read['words_checked'] == 0:27 unmodified lines"not a substitute for live user testing.")return Image.fromarray(overlay_rgb), chart_image, summarywith gr.Blocks(title="Design Analyzer") as demo:6 unmodified linesanalyze_btn = gr.Button("Analyze", variant="primary")with gr.Column():image_output = gr.Image(label="Heatmap result")chart_output = gr.Image(label="Scores at a glance")text_output = gr.Markdown()analyze_btn.click(fn=analyze, inputs=[image_input, strength_slider], outputs=[image_output, chart_output, text_output])demo.launch()
app.py+73-13