HaanIlango commited on
Commit
3339ef7
·
verified ·
1 Parent(s): c511841

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -283
app.py CHANGED
@@ -35,286 +35,4 @@ def get_target_shape(original_shape):
35
  def preprocess_input(input_image, target_shape):
36
  t = tf.expand_dims(input_image, axis=0)
37
  t = tf.image.resize(t, target_shape, preserve_aspect_ratio=True)
38
- vp = target_shape[0] - t.shape[1]
39
- hp = target_shape[1] - t.shape[2]
40
- v1, v2 = vp // 2, vp - vp // 2
41
- h1, h2 = hp // 2, hp - hp // 2
42
- t = tf.pad(t, [[0, 0], [v1, v2], [h1, h2], [0, 0]])
43
- return t, [v1, v2], [h1, h2]
44
-
45
-
46
- def postprocess_output(output_tensor, vp, hp, original_shape):
47
- output_tensor = output_tensor[:, vp[0]:output_tensor.shape[1] - vp[1], hp[0]:output_tensor.shape[2] - hp[1], :]
48
- output_tensor = tf.image.resize(output_tensor, original_shape)
49
- return output_tensor.numpy().squeeze()
50
-
51
-
52
- def compute_text_boost_map(pil_img):
53
- """
54
- Large legible text reliably draws real human attention (confirmed by
55
- eye-tracking research), but MSI-Net (a bottom-up model) can underweight
56
- it relative to small high-contrast graphics. This adds a modest,
57
- size-proportional boost to detected text regions to correct that.
58
- """
59
- img_arr = np.array(pil_img.convert("RGB"))
60
- h, w = img_arr.shape[:2]
61
- data = pytesseract.image_to_data(img_arr, config="--psm 11", output_type=pytesseract.Output.DICT)
62
- text_map = np.zeros((h, w), dtype=np.float32)
63
- for i in range(len(data['text'])):
64
- word = data['text'][i].strip()
65
- tw_, th_ = data['width'][i], data['height'][i]
66
- if not word or th_ < 8 or tw_ < 5:
67
- continue
68
- x, y = data['left'][i], data['top'][i]
69
- weight = min(1.0, (th_ / h) * 6)
70
- pad = int(th_ * 0.15)
71
- y0, y1 = max(0, y - pad), min(h, y + th_ + pad)
72
- x0, x1 = max(0, x - pad), min(w, x + tw_ + pad)
73
- text_map[y0:y1, x0:x1] = np.maximum(text_map[y0:y1, x0:x1], weight)
74
- return text_map
75
-
76
-
77
- def compute_saliency_map(pil_image):
78
- model = load_msi_net()
79
- input_image = np.array(pil_image.convert("RGB"), dtype=np.float32)
80
- original_shape = input_image.shape[:2]
81
- target_shape = get_target_shape(original_shape)
82
- input_tensor, v_pad, h_pad = preprocess_input(input_image, target_shape)
83
- raw_output = model(input_tensor)
84
- output_tensor = list(raw_output.values())[0] if isinstance(raw_output, dict) else raw_output
85
- msi_saliency = postprocess_output(output_tensor, v_pad, h_pad, original_shape)
86
- msi_saliency = msi_saliency.astype(np.float32)
87
- msi_saliency -= msi_saliency.min()
88
- if msi_saliency.max() > 0:
89
- msi_saliency /= msi_saliency.max()
90
-
91
- text_boost = compute_text_boost_map(pil_image)
92
- combined = 0.7 * msi_saliency + 0.3 * text_boost
93
- combined -= combined.min()
94
- if combined.max() > 0:
95
- combined /= combined.max()
96
- return combined
97
-
98
-
99
- def render_heatmap_overlay(img_bgr, saliency_map, alpha=0.45):
100
- heat_u8 = (saliency_map * 255).astype(np.uint8)
101
- heat_color = cv2.applyColorMap(heat_u8, cv2.COLORMAP_JET)
102
- return cv2.addWeighted(heat_color, alpha, img_bgr, 1 - alpha, 0)
103
-
104
-
105
- def compute_attention_scores(saliency_map):
106
- flat = np.sort(saliency_map.flatten())
107
- n = len(flat)
108
- cum = np.cumsum(flat)
109
- gini = (n + 1 - 2 * np.sum(cum) / (cum[-1] + 1e-8)) / n
110
- focus_score = float(gini) * 100
111
- spread_score = float((saliency_map >= 0.5).mean()) * 100
112
- return {"focus_score": round(focus_score, 1), "spread_score": round(spread_score, 1)}
113
-
114
-
115
- def compute_overall_grade(focus_score, spread_score, read):
116
- readability_score = max(0, 100 - read['contrast_issues'] * 15 - read['small_text_issues'] * 10)
117
- total = round(0.55 * focus_score + 0.20 * spread_score + 0.25 * readability_score)
118
- total = max(0, min(100, total))
119
- if total >= 75:
120
- grade = "Good"
121
- elif total >= 50:
122
- grade = "Fair"
123
- else:
124
- grade = "Needs Work"
125
- return total, grade
126
-
127
-
128
- def generate_recommendations(saliency_map, scores, read, img_h, img_w):
129
- tips = []
130
- bottom_band = saliency_map[int(img_h * 0.85):, :]
131
- bottom_avg = bottom_band.mean()
132
- if bottom_avg < 0.25:
133
- tips.append("Your bottom section (often where CTAs or contact info sit) is getting low attention. Consider bolder color contrast or larger text there.")
134
-
135
- if scores['focus_score'] < 40:
136
- tips.append("Attention is scattered with no clear focal point. Consider making one element (headline, product, or offer) visually dominant.")
137
- elif scores['focus_score'] > 90:
138
- tips.append("Attention is very narrowly focused on one spot - double check other important elements (logo, CTA) are not being ignored.")
139
-
140
- if scores['spread_score'] < 3:
141
- tips.append("Very little of the design pulls attention beyond the main hotspot. Secondary elements may go unnoticed by viewers.")
142
-
143
- if read['contrast_issues'] > 0:
144
- tips.append(f"Fix contrast on {read['contrast_issues']} text element(s) - darken text or lighten its background to reach 4.5:1 minimum.")
145
- if read['small_text_issues'] > 0:
146
- tips.append(f"Increase size on {read['small_text_issues']} text element(s) - text under ~1.2% of image height risks being unreadable.")
147
-
148
- if not tips:
149
- tips.append("No major issues detected - this design is in solid shape.")
150
-
151
- return tips
152
-
153
-
154
- def identify_hotspots(saliency_map, img_h, img_w, top_n=4):
155
- threshold = np.percentile(saliency_map, 85)
156
- binary = (saliency_map >= threshold).astype(np.uint8)
157
- kernel = np.ones((25, 25), np.uint8)
158
- binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
159
- num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary, connectivity=8)
160
- zones = []
161
- for i in range(1, num_labels):
162
- area = stats[i, cv2.CC_STAT_AREA]
163
- if area < (img_h * img_w * 0.005):
164
- continue
165
- cx, cy = centroids[i]
166
- h_pos = "top" if cy < img_h * 0.33 else ("bottom" if cy > img_h * 0.66 else "middle")
167
- w_pos = "left" if cx < img_w * 0.33 else ("right" if cx > img_w * 0.66 else "center")
168
- avg_intensity = float(saliency_map[labels == i].mean())
169
- zones.append({"position": f"{h_pos}-{w_pos}", "area_pct": round(float(area / (img_h * img_w)) * 100, 1),
170
- "intensity": round(avg_intensity * 100, 1)})
171
- zones.sort(key=lambda z: -z["intensity"])
172
- return zones[:top_n]
173
-
174
-
175
- def relative_luminance(rgb):
176
- def chan(c):
177
- c = c / 255.0
178
- return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
179
- r, g, b = rgb
180
- return 0.2126 * chan(r) + 0.7152 * chan(g) + 0.0722 * chan(b)
181
-
182
-
183
- def contrast_ratio(rgb1, rgb2):
184
- l1 = relative_luminance(rgb1)
185
- l2 = relative_luminance(rgb2)
186
- lighter, darker = max(l1, l2), min(l1, l2)
187
- return (lighter + 0.05) / (darker + 0.05)
188
-
189
-
190
- def sample_text_and_bg_color(img_arr, x, y, w, h):
191
- pad = max(2, int(h * 0.3))
192
- y0, y1 = max(0, y - pad), min(img_arr.shape[0], y + h + pad)
193
- x0, x1 = max(0, x - pad), min(img_arr.shape[1], x + w + pad)
194
- region = img_arr[y0:y1, x0:x1]
195
- gray = cv2.cvtColor(region, cv2.COLOR_RGB2GRAY)
196
- thresh = np.median(gray)
197
- dark_mask = gray < thresh
198
- light_mask = ~dark_mask
199
- dark_px = region[dark_mask]
200
- light_px = region[light_mask]
201
- if len(dark_px) == 0 or len(light_px) == 0:
202
- return None, None
203
- text_color = tuple(np.median(dark_px, axis=0).astype(int))
204
- bg_color = tuple(np.median(light_px, axis=0).astype(int))
205
- return text_color, bg_color
206
-
207
-
208
- def analyze_readability(pil_img):
209
- img_arr = np.array(pil_img.convert("RGB"))
210
- img_h = img_arr.shape[0]
211
- ocr_data = pytesseract.image_to_data(img_arr, output_type=pytesseract.Output.DICT)
212
- words_checked = 0
213
- contrast_issues = 0
214
- small_text_issues = 0
215
- issue_lines = []
216
- for i in range(len(ocr_data['text'])):
217
- word = ocr_data['text'][i].strip()
218
- conf = int(ocr_data['conf'][i])
219
- if not word or conf < 60 or len(word) < 2:
220
- continue
221
- x, y, w, h = ocr_data['left'][i], ocr_data['top'][i], ocr_data['width'][i], ocr_data['height'][i]
222
- if w < 3 or h < 3:
223
- continue
224
- words_checked += 1
225
- text_color, bg_color = sample_text_and_bg_color(img_arr, x, y, w, h)
226
- if text_color is None:
227
- continue
228
- ratio = contrast_ratio(text_color, bg_color)
229
- size_pct = (h / img_h) * 100
230
- if ratio < 4.5:
231
- contrast_issues += 1
232
- if len(issue_lines) < 5:
233
- issue_lines.append(f"- Low contrast on \"{word}\" ({ratio:.1f}:1, needs 4.5:1 minimum)")
234
- if size_pct < 1.2:
235
- small_text_issues += 1
236
- if len(issue_lines) < 5:
237
- issue_lines.append(f"- Small text \"{word}\" ({size_pct:.1f}% of image height)")
238
- return {"words_checked": words_checked, "contrast_issues": contrast_issues,
239
- "small_text_issues": small_text_issues, "issue_lines": issue_lines}
240
-
241
-
242
- def analyze(pil_image, overlay_strength):
243
- if pil_image is None:
244
- return None, "Upload an image first."
245
- pil_rgb = pil_image.convert("RGB")
246
- img_bgr = cv2.cvtColor(np.array(pil_rgb), cv2.COLOR_RGB2BGR)
247
- h, w = img_bgr.shape[:2]
248
-
249
- saliency_map = compute_saliency_map(pil_rgb)
250
- overlay_bgr = render_heatmap_overlay(img_bgr, saliency_map, alpha=overlay_strength)
251
- overlay_rgb = cv2.cvtColor(overlay_bgr, cv2.COLOR_BGR2RGB)
252
-
253
- scores = compute_attention_scores(saliency_map)
254
- zones = identify_hotspots(saliency_map, h, w)
255
- read = analyze_readability(pil_rgb)
256
- total_score, grade = compute_overall_grade(scores['focus_score'], scores['spread_score'], read)
257
- tips = generate_recommendations(saliency_map, scores, read, h, w)
258
-
259
- summary = f"## Grade: {grade} — {total_score}/100\n\n"
260
-
261
- summary += "**Where Attention Goes First:**\n"
262
- if zones:
263
- for z in zones:
264
- summary += f"- {z['position'].replace('-', ' ').title()} ({z['intensity']}/100 intensity, {z['area_pct']}% of design)\n"
265
- else:
266
- summary += "- Attention is fairly even across the design, no strong single hotspot.\n"
267
-
268
- summary += (
269
- f"\n**Scores:**\n"
270
- f"- Clear Focal Point: {scores['focus_score']}/100 (how strongly attention lands on one main spot, vs scattered everywhere)\n"
271
- f"- Attention Coverage: {scores['spread_score']}/100 (how much of the whole design draws some interest, not just one hotspot)\n"
272
- f"- Readability: "
273
- )
274
- if read['words_checked'] == 0:
275
- summary += "no text detected\n"
276
- elif read['contrast_issues'] == 0 and read['small_text_issues'] == 0:
277
- summary += "clean (0 issues)\n"
278
- else:
279
- summary += f"{read['contrast_issues'] + read['small_text_issues']} issue(s) found\n"
280
-
281
- if read['issue_lines']:
282
- summary += "\n**Readability details:**\n" + "\n".join(read['issue_lines']) + "\n"
283
- summary += (
284
- "\n*Note: contrast is estimated automatically and can misread text sitting on "
285
- "busy or gradient backgrounds. If a flagged item looks clearly readable to your "
286
- "eye, treat it as a false positive.*\n"
287
- )
288
-
289
- summary += "\n**How to Improve:**\n"
290
- for tip in tips:
291
- summary += f"- {tip}\n"
292
-
293
- summary += (
294
- "\n---\n"
295
- "**Methodology:** Attention prediction combines MSI-Net, a peer-reviewed saliency model "
296
- "(Kroner et al., *Neural Networks*, 2020, "
297
- "[DOI: 10.1016/j.neunet.2020.05.004](https://doi.org/10.1016/j.neunet.2020.05.004)), "
298
- "with a size-proportional boost for legible text - since eye-tracking research confirms "
299
- "large headline text reliably draws attention, which pure bottom-up saliency models can "
300
- "underweight relative to small high-contrast graphics. This is a data-informed prediction, "
301
- "not a substitute for live user testing."
302
- )
303
-
304
- return Image.fromarray(overlay_rgb), summary
305
-
306
-
307
- with gr.Blocks(title="Design Analyzer") as demo:
308
- gr.Markdown("# Design Analyzer")
309
- gr.Markdown("Upload a design to check where attention is drawn, plus text contrast and readability.")
310
- with gr.Row():
311
- with gr.Column():
312
- image_input = gr.Image(type="pil", label="Upload design")
313
- strength_slider = gr.Slider(0.1, 0.8, value=0.45, step=0.05, label="Heatmap overlay strength")
314
- analyze_btn = gr.Button("Analyze", variant="primary")
315
- with gr.Column():
316
- image_output = gr.Image(label="Heatmap result")
317
- text_output = gr.Markdown()
318
- analyze_btn.click(fn=analyze, inputs=[image_input, strength_slider], outputs=[image_output, text_output])
319
-
320
- demo.launch()
 
35
  def preprocess_input(input_image, target_shape):
36
  t = tf.expand_dims(input_image, axis=0)
37
  t = tf.image.resize(t, target_shape, preserve_aspect_ratio=True)
38
+ vp