HaanIlango commited on
Commit
1eea8dd
·
verified ·
1 Parent(s): 499ad5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -13
app.py CHANGED
@@ -6,6 +6,10 @@ import tensorflow as tf
6
  import keras
7
  from huggingface_hub import snapshot_download
8
  import pytesseract
 
 
 
 
9
 
10
  _msi_model = None
11
 
@@ -103,8 +107,11 @@ def compute_attention_scores(saliency_map):
103
  return {"focus_score": round(focus_score, 1), "spread_score": round(spread_score, 1)}
104
 
105
 
106
- def compute_overall_grade(focus_score, spread_score, read):
107
- readability_score = max(0, 100 - read['contrast_issues'] * 15 - read['small_text_issues'] * 10)
 
 
 
108
  total = round(0.55 * focus_score + 0.20 * spread_score + 0.25 * readability_score)
109
  total = max(0, min(100, total))
110
  if total >= 75:
@@ -116,6 +123,57 @@ def compute_overall_grade(focus_score, spread_score, read):
116
  return total, grade
117
 
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  def generate_recommendations(saliency_map, scores, read, img_h, img_w):
120
  tips = []
121
  bottom_band = saliency_map[int(img_h * 0.85):, :]
@@ -128,9 +186,6 @@ def generate_recommendations(saliency_map, scores, read, img_h, img_w):
128
  elif scores['focus_score'] > 90:
129
  tips.append("Attention is very narrowly focused on one spot - double check other important elements (logo, CTA) are not being ignored.")
130
 
131
- if scores['spread_score'] < 3:
132
- tips.append("Very little of the design pulls attention beyond the main hotspot. Secondary elements may go unnoticed by viewers.")
133
-
134
  if read['contrast_issues'] > 0:
135
  if read['contrast_issues'] > 5:
136
  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.")
@@ -244,12 +299,12 @@ def analyze_readability(pil_img):
244
  contrast_issues += 1
245
  if len(issue_lines) < 5:
246
  severity = contrast_severity_label(ratio)
247
- issue_lines.append(f"- \"{word}\" is {severity} ({ratio:.1f}:1, needs 4.5:1 minimum)")
248
  issue_boxes.append({"box": (x, y, w, h), "label": "Low contrast"})
249
  if size_pct < 1.2:
250
  small_text_issues += 1
251
  if len(issue_lines) < 5:
252
- issue_lines.append(f"- Small text \"{word}\" ({size_pct:.1f}% of image height)")
253
  issue_boxes.append({"box": (x, y, w, h), "label": "Small text"})
254
  return {"words_checked": words_checked, "contrast_issues": contrast_issues,
255
  "small_text_issues": small_text_issues, "issue_lines": issue_lines, "issue_boxes": issue_boxes}
@@ -286,7 +341,7 @@ def draw_zone_labels(overlay_bgr, zones):
286
 
287
  def analyze(pil_image, overlay_strength):
288
  if pil_image is None:
289
- return None, "Upload an image first."
290
  pil_rgb = pil_image.convert("RGB")
291
  img_bgr = cv2.cvtColor(np.array(pil_rgb), cv2.COLOR_RGB2BGR)
292
  h, w = img_bgr.shape[:2]
@@ -297,14 +352,18 @@ def analyze(pil_image, overlay_strength):
297
  scores = compute_attention_scores(saliency_map)
298
  zones = identify_hotspots(saliency_map, h, w)
299
  read = analyze_readability(pil_rgb)
300
- total_score, grade = compute_overall_grade(scores['focus_score'], scores['spread_score'], read)
 
 
301
  tips = generate_recommendations(saliency_map, scores, read, h, w)
 
302
 
303
  overlay_bgr = draw_zone_labels(overlay_bgr, zones)
304
  overlay_bgr = draw_issue_markers(overlay_bgr, read.get("issue_boxes", []))
305
  overlay_rgb = cv2.cvtColor(overlay_bgr, cv2.COLOR_BGR2RGB)
306
 
307
- summary = f"## Grade: {grade} — {total_score}/100\n\n"
 
308
 
309
  summary += "**Where Attention Goes First:** *(numbers match the image above)*\n"
310
  if zones:
@@ -316,7 +375,7 @@ def analyze(pil_image, overlay_strength):
316
  summary += (
317
  f"\n**Scores:**\n"
318
  f"- Clear Focal Point: {scores['focus_score']}/100 (how strongly attention lands on one main spot, vs scattered everywhere)\n"
319
- f"- Attention Coverage: {scores['spread_score']}/100 (how much of the whole design draws some interest, not just one hotspot)\n"
320
  f"- Readability: "
321
  )
322
  if read['words_checked'] == 0:
@@ -350,7 +409,7 @@ def analyze(pil_image, overlay_strength):
350
  "not a substitute for live user testing."
351
  )
352
 
353
- return Image.fromarray(overlay_rgb), summary
354
 
355
 
356
  with gr.Blocks(title="Design Analyzer") as demo:
@@ -363,7 +422,8 @@ with gr.Blocks(title="Design Analyzer") as demo:
363
  analyze_btn = gr.Button("Analyze", variant="primary")
364
  with gr.Column():
365
  image_output = gr.Image(label="Heatmap result")
 
366
  text_output = gr.Markdown()
367
- analyze_btn.click(fn=analyze, inputs=[image_input, strength_slider], outputs=[image_output, text_output])
368
 
369
  demo.launch()
 
6
  import keras
7
  from huggingface_hub import snapshot_download
8
  import pytesseract
9
+ import io
10
+ import matplotlib
11
+ matplotlib.use("Agg")
12
+ import matplotlib.pyplot as plt
13
 
14
  _msi_model = None
15
 
 
107
  return {"focus_score": round(focus_score, 1), "spread_score": round(spread_score, 1)}
108
 
109
 
110
+ def compute_readability_score(read):
111
+ return max(0, 100 - read['contrast_issues'] * 15 - read['small_text_issues'] * 10)
112
+
113
+
114
+ def compute_overall_grade(focus_score, spread_score, readability_score):
115
  total = round(0.55 * focus_score + 0.20 * spread_score + 0.25 * readability_score)
116
  total = max(0, min(100, total))
117
  if total >= 75:
 
123
  return total, grade
124
 
125
 
126
+ def explain_grade(focus_score, readability_score, read):
127
+ total_issues = read['contrast_issues'] + read['small_text_issues']
128
+ weighted_focus_deficit = 0.55 * max(0, 100 - focus_score)
129
+ weighted_read_deficit = 0.25 * max(0, 100 - readability_score)
130
+
131
+ if weighted_read_deficit >= weighted_focus_deficit and total_issues > 0:
132
+ return "mainly due to text readability - some text is harder to read than ideal"
133
+ elif focus_score < 50:
134
+ return "mainly because attention is spread out, without one clear focal point"
135
+ elif focus_score > 90:
136
+ return "attention is very tightly focused on one spot - worth checking other key elements (logo, CTA) aren't being missed"
137
+ else:
138
+ return "a mix of small readability and focus factors - see details below"
139
+
140
+
141
+ def coverage_description(spread_score):
142
+ if spread_score < 15:
143
+ return "concentrated on one clear focal point - that's usually a good sign, not a problem"
144
+ elif spread_score < 40:
145
+ return "landing mostly in a couple of areas, which is fairly typical"
146
+ else:
147
+ return "spread fairly widely across the design"
148
+
149
+
150
+ def create_score_chart(focus_score, spread_score, readability_score):
151
+ labels = ["Clear Focal\nPoint", "Attention\nCoverage", "Readability"]
152
+ values = [focus_score, spread_score, readability_score]
153
+ colors = []
154
+ for v in values:
155
+ if v >= 75:
156
+ colors.append("#4CAF50")
157
+ elif v >= 50:
158
+ colors.append("#FFC107")
159
+ else:
160
+ colors.append("#F44336")
161
+ fig, ax = plt.subplots(figsize=(5, 3), dpi=100)
162
+ bars = ax.barh(labels, values, color=colors)
163
+ ax.set_xlim(0, 100)
164
+ ax.set_xlabel("Score out of 100")
165
+ ax.invert_yaxis()
166
+ for bar, v in zip(bars, values):
167
+ ax.text(min(v + 2, 92), bar.get_y() + bar.get_height() / 2, f"{v:.0f}", va="center", fontsize=10)
168
+ ax.set_title("Scores at a Glance")
169
+ fig.tight_layout()
170
+ buf = io.BytesIO()
171
+ fig.savefig(buf, format="png")
172
+ plt.close(fig)
173
+ buf.seek(0)
174
+ return Image.open(buf).convert("RGB")
175
+
176
+
177
  def generate_recommendations(saliency_map, scores, read, img_h, img_w):
178
  tips = []
179
  bottom_band = saliency_map[int(img_h * 0.85):, :]
 
186
  elif scores['focus_score'] > 90:
187
  tips.append("Attention is very narrowly focused on one spot - double check other important elements (logo, CTA) are not being ignored.")
188
 
 
 
 
189
  if read['contrast_issues'] > 0:
190
  if read['contrast_issues'] > 5:
191
  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.")
 
299
  contrast_issues += 1
300
  if len(issue_lines) < 5:
301
  severity = contrast_severity_label(ratio)
302
+ issue_lines.append(f"- \"{word}\" {severity} against its background")
303
  issue_boxes.append({"box": (x, y, w, h), "label": "Low contrast"})
304
  if size_pct < 1.2:
305
  small_text_issues += 1
306
  if len(issue_lines) < 5:
307
+ issue_lines.append(f"- \"{word}\" is a bit small to read comfortably")
308
  issue_boxes.append({"box": (x, y, w, h), "label": "Small text"})
309
  return {"words_checked": words_checked, "contrast_issues": contrast_issues,
310
  "small_text_issues": small_text_issues, "issue_lines": issue_lines, "issue_boxes": issue_boxes}
 
341
 
342
  def analyze(pil_image, overlay_strength):
343
  if pil_image is None:
344
+ return None, None, "Upload an image first."
345
  pil_rgb = pil_image.convert("RGB")
346
  img_bgr = cv2.cvtColor(np.array(pil_rgb), cv2.COLOR_RGB2BGR)
347
  h, w = img_bgr.shape[:2]
 
352
  scores = compute_attention_scores(saliency_map)
353
  zones = identify_hotspots(saliency_map, h, w)
354
  read = analyze_readability(pil_rgb)
355
+ readability_score = compute_readability_score(read)
356
+ total_score, grade = compute_overall_grade(scores['focus_score'], scores['spread_score'], readability_score)
357
+ grade_reason = explain_grade(scores['focus_score'], readability_score, read)
358
  tips = generate_recommendations(saliency_map, scores, read, h, w)
359
+ chart_image = create_score_chart(scores['focus_score'], scores['spread_score'], readability_score)
360
 
361
  overlay_bgr = draw_zone_labels(overlay_bgr, zones)
362
  overlay_bgr = draw_issue_markers(overlay_bgr, read.get("issue_boxes", []))
363
  overlay_rgb = cv2.cvtColor(overlay_bgr, cv2.COLOR_BGR2RGB)
364
 
365
+ summary = f"## Grade: {grade} — {total_score}/100\n"
366
+ summary += f"*Why: {grade_reason}*\n\n"
367
 
368
  summary += "**Where Attention Goes First:** *(numbers match the image above)*\n"
369
  if zones:
 
375
  summary += (
376
  f"\n**Scores:**\n"
377
  f"- Clear Focal Point: {scores['focus_score']}/100 (how strongly attention lands on one main spot, vs scattered everywhere)\n"
378
+ f"- Attention Coverage: {scores['spread_score']}/100 - {coverage_description(scores['spread_score'])}\n"
379
  f"- Readability: "
380
  )
381
  if read['words_checked'] == 0:
 
409
  "not a substitute for live user testing."
410
  )
411
 
412
+ return Image.fromarray(overlay_rgb), chart_image, summary
413
 
414
 
415
  with gr.Blocks(title="Design Analyzer") as demo:
 
422
  analyze_btn = gr.Button("Analyze", variant="primary")
423
  with gr.Column():
424
  image_output = gr.Image(label="Heatmap result")
425
+ chart_output = gr.Image(label="Scores at a glance")
426
  text_output = gr.Markdown()
427
+ analyze_btn.click(fn=analyze, inputs=[image_input, strength_slider], outputs=[image_output, chart_output, text_output])
428
 
429
  demo.launch()