Spaces:
Sleeping
Sleeping
Update app.py
Browse files34 unmodified lines353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932034 unmodified linesdef preprocess_input(input_image, target_shape):t = tf.expand_dims(input_image, axis=0)t = tf.image.resize(t, target_shape, preserve_aspect_ratio=True)vp = target_shape[0] - t.shape[1]hp = target_shape[1] - t.shape[2]v1, v2 = vp // 2, vp - vp // 2h1, h2 = hp // 2, hp - hp // 2t = tf.pad(t, [[0, 0], [v1, v2], [h1, h2], [0, 0]])return t, [v1, v2], [h1, h2]def postprocess_output(output_tensor, vp, hp, original_shape):output_tensor = output_tensor[:, vp[0]:output_tensor.shape[1] - vp[1], hp[0]:output_tensor.shape[2] - hp[1], :]output_tensor = tf.image.resize(output_tensor, original_shape)return output_tensor.numpy().squeeze()def compute_text_boost_map(pil_img):"""Large legible text reliably draws real human attention (confirmed byeye-tracking research), but MSI-Net (a bottom-up model) can underweightit relative to small high-contrast graphics. This adds a modest,size-proportional boost to detected text regions to correct that."""img_arr = np.array(pil_img.convert("RGB"))h, w = img_arr.shape[:2]data = pytesseract.image_to_data(img_arr, config="--psm 11", output_type=pytesseract.Output.DICT)text_map = np.zeros((h, w), dtype=np.float32)for i in range(len(data['text'])):word = data['text'][i].strip()tw_, th_ = data['width'][i], data['height'][i]if not word or th_ < 8 or tw_ < 5:continuex, y = data['left'][i], data['top'][i]weight = min(1.0, (th_ / h) * 6)pad = int(th_ * 0.15)y0, y1 = max(0, y - pad), min(h, y + th_ + pad)x0, x1 = max(0, x - pad), min(w, x + tw_ + pad)text_map[y0:y1, x0:x1] = np.maximum(text_map[y0:y1, x0:x1], weight)return text_mapdef compute_saliency_map(pil_image):model = load_msi_net()input_image = np.array(pil_image.convert("RGB"), dtype=np.float32)original_shape = input_image.shape[:2]target_shape = get_target_shape(original_shape)input_tensor, v_pad, h_pad = preprocess_input(input_image, target_shape)raw_output = model(input_tensor)output_tensor = list(raw_output.values())[0] if isinstance(raw_output, dict) else raw_outputmsi_saliency = postprocess_output(output_tensor, v_pad, h_pad, original_shape)msi_saliency = msi_saliency.astype(np.float32)msi_saliency -= msi_saliency.min()if msi_saliency.max() > 0:msi_saliency /= msi_saliency.max()text_boost = compute_text_boost_map(pil_image)combined = 0.7 * msi_saliency + 0.3 * text_boostcombined -= combined.min()if combined.max() > 0:combined /= combined.max()return combineddef render_heatmap_overlay(img_bgr, saliency_map, alpha=0.45):heat_u8 = (saliency_map * 255).astype(np.uint8)heat_color = cv2.applyColorMap(heat_u8, cv2.COLORMAP_JET)return cv2.addWeighted(heat_color, alpha, img_bgr, 1 - alpha, 0)def compute_attention_scores(saliency_map):flat = np.sort(saliency_map.flatten())n = len(flat)cum = np.cumsum(flat)gini = (n + 1 - 2 * np.sum(cum) / (cum[-1] + 1e-8)) / nfocus_score = float(gini) * 100spread_score = float((saliency_map >= 0.5).mean()) * 100return {"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:grade = "Good"elif total >= 50:grade = "Fair"else:grade = "Needs Work"return total, gradedef generate_recommendations(saliency_map, scores, read, img_h, img_w):tips = []bottom_band = saliency_map[int(img_h * 0.85):, :]bottom_avg = bottom_band.mean()if bottom_avg < 0.25:tips.append("Your bottom section (often where CTAs or contact info sit) is getting low attention. Consider bolder color contrast or larger text there.")if scores['focus_score'] < 40:tips.append("Attention is scattered with no clear focal point. Consider making one element (headline, product, or offer) visually dominant.")elif 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:tips.append(f"Fix contrast on {read['contrast_issues']} text element(s) - darken text or lighten its background to reach 4.5:1 minimum.")if read['small_text_issues'] > 0:tips.append(f"Increase size on {read['small_text_issues']} text element(s) - text under ~1.2% of image height risks being unreadable.")if not tips:tips.append("No major issues detected - this design is in solid shape.")return tipsdef identify_hotspots(saliency_map, img_h, img_w, top_n=4):threshold = np.percentile(saliency_map, 85)binary = (saliency_map >= threshold).astype(np.uint8)kernel = np.ones((25, 25), np.uint8)binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary, connectivity=8)zones = []for i in range(1, num_labels):area = stats[i, cv2.CC_STAT_AREA]if area < (img_h * img_w * 0.005):continuecx, cy = centroids[i]h_pos = "top" if cy < img_h * 0.33 else ("bottom" if cy > img_h * 0.66 else "middle")w_pos = "left" if cx < img_w * 0.33 else ("right" if cx > img_w * 0.66 else "center")avg_intensity = float(saliency_map[labels == i].mean())zones.append({"position": f"{h_pos}-{w_pos}", "area_pct": round(float(area / (img_h * img_w)) * 100, 1),"intensity": round(avg_intensity * 100, 1)})zones.sort(key=lambda z: -z["intensity"])return zones[:top_n]def relative_luminance(rgb):def chan(c):c = c / 255.0return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4r, g, b = rgbreturn 0.2126 * chan(r) + 0.7152 * chan(g) + 0.0722 * chan(b)def contrast_ratio(rgb1, rgb2):l1 = relative_luminance(rgb1)l2 = relative_luminance(rgb2)lighter, darker = max(l1, l2), min(l1, l2)return (lighter + 0.05) / (darker + 0.05)def sample_text_and_bg_color(img_arr, x, y, w, h):pad = max(2, int(h * 0.3))y0, y1 = max(0, y - pad), min(img_arr.shape[0], y + h + pad)x0, x1 = max(0, x - pad), min(img_arr.shape[1], x + w + pad)region = img_arr[y0:y1, x0:x1]gray = cv2.cvtColor(region, cv2.COLOR_RGB2GRAY)thresh = np.median(gray)dark_mask = gray < threshlight_mask = ~dark_maskdark_px = region[dark_mask]light_px = region[light_mask]if len(dark_px) == 0 or len(light_px) == 0:return None, Nonetext_color = tuple(np.median(dark_px, axis=0).astype(int))bg_color = tuple(np.median(light_px, axis=0).astype(int))return text_color, bg_colordef analyze_readability(pil_img):img_arr = np.array(pil_img.convert("RGB"))img_h = img_arr.shape[0]ocr_data = pytesseract.image_to_data(img_arr, output_type=pytesseract.Output.DICT)words_checked = 0contrast_issues = 0small_text_issues = 0issue_lines = []for i in range(len(ocr_data['text'])):word = ocr_data['text'][i].strip()conf = int(ocr_data['conf'][i])if not word or conf < 60 or len(word) < 2:continuex, y, w, h = ocr_data['left'][i], ocr_data['top'][i], ocr_data['width'][i], ocr_data['height'][i]if w < 3 or h < 3:continuewords_checked += 1text_color, bg_color = sample_text_and_bg_color(img_arr, x, y, w, h)if text_color is None:continueratio = contrast_ratio(text_color, bg_color)size_pct = (h / img_h) * 100if ratio < 4.5:contrast_issues += 1if len(issue_lines) < 5:issue_lines.append(f"- Low contrast on \"{word}\" ({ratio:.1f}:1, needs 4.5:1 minimum)")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)")return {"words_checked": words_checked, "contrast_issues": contrast_issues,"small_text_issues": small_text_issues, "issue_lines": issue_lines}def 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]saliency_map = compute_saliency_map(pil_rgb)overlay_bgr = render_heatmap_overlay(img_bgr, saliency_map, alpha=overlay_strength)overlay_rgb = cv2.cvtColor(overlay_bgr, cv2.COLOR_BGR2RGB)scores = 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)summary = f"## Grade: {grade} — {total_score}/100\n\n"summary += "**Where Attention Goes First:**\n"if zones:for z in zones:summary += f"- {z['position'].replace('-', ' ').title()} ({z['intensity']}/100 intensity, {z['area_pct']}% of design)\n"else:summary += "- Attention is fairly even across the design, no strong single hotspot.\n"summary += (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:summary += "no text detected\n"elif read['contrast_issues'] == 0 and read['small_text_issues'] == 0:summary += "clean (0 issues)\n"else:summary += f"{read['contrast_issues'] + read['small_text_issues']} issue(s) found\n"if read['issue_lines']:summary += "\n**Readability details:**\n" + "\n".join(read['issue_lines']) + "\n"summary += ("\n*Note: contrast is estimated automatically and can misread text sitting on ""busy or gradient backgrounds. If a flagged item looks clearly readable to your ""eye, treat it as a false positive.*\n")summary += "\n**How to Improve:**\n"for tip in tips:summary += f"- {tip}\n"summary += ("\n---\n""**Methodology:** Attention prediction combines MSI-Net, a peer-reviewed saliency model ""(Kroner et al., *Neural Networks*, 2020, ""[DOI: 10.1016/j.neunet.2020.05.004](https://doi.org/10.1016/j.neunet.2020.05.004)), ""with a size-proportional boost for legible text - since eye-tracking research confirms ""large headline text reliably draws attention, which pure bottom-up saliency models can ""underweight relative to small high-contrast graphics. This is a data-informed prediction, ""not a substitute for live user testing.")return Image.fromarray(overlay_rgb), summarywith gr.Blocks(title="Design Analyzer") as demo:gr.Markdown("# Design Analyzer")gr.Markdown("Upload a design to check where attention is drawn, plus text contrast and readability.")with gr.Row():with gr.Column():image_input = gr.Image(type="pil", label="Upload design")strength_slider = gr.Slider(0.1, 0.8, value=0.45, step=0.05, label="Heatmap overlay strength")analyze_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()34 unmodified lines3536373834 unmodified linesdef preprocess_input(input_image, target_shape):t = tf.expand_dims(input_image, axis=0)t = tf.image.resize(t, target_shape, preserve_aspect_ratio=True)vp
app.py+1-283