Spaces:
No application file
No application file
File size: 31,385 Bytes
78e0552 16a46a4 78e0552 16a46a4 78e0552 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 16a46a4 75538a9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 |
# type: ignore
from agents import Agent, AsyncOpenAI, Runner, function_tool, RunContextWrapper
from model import get_model
import os
import time
import json
import base64
import asyncio
from PIL import Image
from datetime import datetime
from typing import Optional, List, Literal
from urllib.parse import urlparse
from pydantic import BaseModel, Field, conint
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from browser_use import Agent as AgentBrowser, ChatGoogle, ChatOpenAI as ChatOpenAIBrowserUse, Tools, ActionResult
from browser_use.browser import BrowserSession, BrowserProfile
from utils.chrome_playwright import start_chrome_with_debug_port, connect_playwright_to_cdp
from browser_use.actor.element import Element as Element_
from browser_use.dom.serializer.serializer import DOMTreeSerializer
import re
# Model definitions for browser interaction
class PageVisited(BaseModel):
url: str
title: str
extracted_text: str
class WebsiteInfo(BaseModel):
url: str
title: str
pages_visited: List[PageVisited]
class ContentInfo(BaseModel):
query: Optional[str] # can be None if no query provided
summary: str
full_text: str
class Colors(BaseModel):
primary: Optional[str] # hex code or None
secondary: Optional[str]
palette: List[str]
class Typography(BaseModel):
fonts: List[str]
weights: List[str]
styles: List[str]
class ButtonStyles(BaseModel):
styles: List[str]
examples: Optional[str]
class HeadingStyles(BaseModel):
styles: List[str]
examples: Optional[str]
class Components(BaseModel):
buttons: Optional[ButtonStyles]
headings: Optional[HeadingStyles]
logos: List[str]
icons: List[str]
class DesignSystem(BaseModel):
colors: Colors
typography: Typography
components: Components
class Screenshot(BaseModel):
component: str
filename: str
path: str
class BrowserAgentOutput(BaseModel):
website: WebsiteInfo
content: ContentInfo
design_system: DesignSystem
screenshots: List[Screenshot]
# Create instance of Tools
tools = Tools()
# Param schemas for all custom actions
class ElementScreenshotParams(BaseModel):
selectors: List[str] = Field(..., description="A list of CSS selectors to try for locating the element(s). The first valid selector will be used.")
filename: str = Field(default="element_screenshot.png", description="Output filename for the screenshot.")
highlight: bool = Field(default=True, description="If True, draw a red border around the element before taking the screenshot.")
padding: conint(ge=0) = Field(default=10, description="Padding (in pixels) to add around the element in the screenshot.")
scroll_if_needed: bool = Field(default=True, description="If True, scroll the element into view before taking the screenshot.")
fallback_to_full_page: bool = Field(default=True, description="If no element is found, fallback to taking a full page screenshot.")
class FindElementByPromptParams(BaseModel):
query: str = Field(..., description="A detailed natural language description of the element to find, including its visual appearance, position, and any visible text it contains (e.g., 'the login button with the text Sign In').")
class HighlightElementParams(BaseModel):
selector: Optional[str] = Field(None, description="CSS selector for the element to highlight.")
remove: Optional[bool] = Field(False, description="If True, remove the highlight.")
class GetBoundingBoxParams(BaseModel):
selector: str = Field(..., description="CSS selector for the element to get bounding box.")
class ElementScreenshotClipParams(BaseModel):
clip: dict = Field(..., description="Clipping region with keys: x, y, width, height.")
filename: str = Field('element_clip.png', description="Name of the output file.")
class VerifyElementVisualParams(BaseModel):
query: str = Field(..., description="Natural language description of the element to find and verify.")
screenshot_path: str = Field(..., description="Path to the screenshot file to verify.")
tolerance: int = Field(20, description="Maximum allowed difference in pixels between element and screenshot dimensions.")
class ColorElementHint(BaseModel):
text: str = Field(description="Text content of element (e.g., 'Get Started', 'Sign Up', 'Main heading text'). Can be empty for background elements.")
tags: List[str] = Field(description="Possible HTML tags (e.g., ['button', 'a'] for brand colors, ['body', 'header'] for backgrounds, ['h1', 'p'] for text)")
priority: Literal["primary", "secondary", "accent", "background", "text-heading", "text-body", "text-subtle"] = Field(
description="Color category: primary/secondary/accent for brand colors, background for page background, text-heading/text-body/text-subtle for text hierarchy"
)
class PossibleColorThemeData(BaseModel):
elements_to_find: List[ColorElementHint] = Field(
description="List of elements identified by agent that likely have brand colors"
)
additional_tag_patterns: Optional[List[str]] = Field(
default=None,
description="Additional tags agent thinks should be checked (e.g., ['span', 'div'])"
)
def rgb_to_hex(rgb_string):
"""Convert rgb(r, g, b) or rgba(r, g, b, a) to hex"""
if not rgb_string or rgb_string in ['transparent', 'none']:
return None
# Extract numbers from rgb/rgba string
match = re.findall(r'\d+', rgb_string)
if not match or len(match) < 3:
return None
r, g, b = int(match[0]), int(match[1]), int(match[2])
# Skip fully transparent or white/black extremes that aren't real brand colors
if len(match) > 3: # rgba
alpha = float(match[3]) if '.' in rgb_string else int(match[3]) / 255
if alpha < 0.1: # Nearly transparent
return None
return f'#{r:02x}{g:02x}{b:02x}'
def extract_colors_from_computed_style(computed_style_array):
"""Extract color values from CDP computedStyle response"""
color_properties = {
'color': 3,
'background-color': 5,
'border-color': 2,
'border-top-color': 2,
'border-bottom-color': 2,
'border-left-color': 2,
'border-right-color': 2,
'fill': 4,
'stroke': 2,
}
extracted = {}
for prop in computed_style_array:
prop_name = prop.get('name', '')
prop_value = prop.get('value', '')
if prop_name in color_properties:
hex_color = rgb_to_hex(prop_value)
if hex_color and hex_color not in ['#000000', '#ffffff']: # Skip pure black/white
extracted[prop_name] = {
'hex': hex_color,
'weight': color_properties[prop_name]
}
return extracted
def colors_similar(hex1, hex2, threshold=15):
"""Check if two hex colors are similar within RGB threshold"""
r1, g1, b1 = int(hex1[1:3], 16), int(hex1[3:5], 16), int(hex1[5:7], 16)
r2, g2, b2 = int(hex2[1:3], 16), int(hex2[3:5], 16), int(hex2[5:7], 16)
return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
def build_search_strategy(params: PossibleColorThemeData):
"""
Convert agent params into search strategy
"""
# Base hardcoded selectors (always search)
BASE_SELECTORS = [
# Interactive elements (brand colors)
{'tag': 'a', 'role': None, 'hierarchy': None},
{'tag': 'button', 'role': None, 'hierarchy': None},
{'tag': 'div', 'role': 'button', 'hierarchy': None},
{'tag': 'span', 'role': 'button', 'hierarchy': None},
{'tag': 'input', 'role': 'submit', 'hierarchy': None},
# Text hierarchy
{'tag': 'h1', 'role': None, 'hierarchy': 'heading-primary'},
{'tag': 'h2', 'role': None, 'hierarchy': 'heading-secondary'},
{'tag': 'h3', 'role': None, 'hierarchy': 'heading-tertiary'},
{'tag': 'h4', 'role': None, 'hierarchy': 'heading-tertiary'},
{'tag': 'h5', 'role': None, 'hierarchy': 'heading-tertiary'},
{'tag': 'h6', 'role': None, 'hierarchy': 'heading-tertiary'},
{'tag': 'p', 'role': None, 'hierarchy': 'body-text'},
{'tag': 'span', 'role': None, 'hierarchy': 'subtle-text'},
{'tag': 'small', 'role': None, 'hierarchy': 'subtle-text'},
# Background detection
{'tag': 'body', 'role': None, 'hierarchy': 'background'},
{'tag': 'header', 'role': None, 'hierarchy': 'background'},
{'tag': 'footer', 'role': None, 'hierarchy': 'background'},
{'tag': 'nav', 'role': None, 'hierarchy': 'background'},
{'tag': 'main', 'role': None, 'hierarchy': 'background'},
{'tag': 'section', 'role': None, 'hierarchy': 'background'},
{'tag': 'div', 'role': None, 'hierarchy': None},
]
# Extract from params
search_strategy = {
'base_selectors': BASE_SELECTORS,
'text_matches': [
elem.text for elem in params.elements_to_find
],
'priority_map': {
elem.text: elem.priority
for elem in params.elements_to_find
},
'agent_tags': list(set(
tag
for elem in params.elements_to_find
for tag in elem.tags
))
}
# Add additional tags if provided
if params.additional_tag_patterns:
search_strategy['agent_tags'].extend(params.additional_tag_patterns)
return search_strategy
@tools.action(
description="""Extracts the complete color system from the current webpage for brand guidelines.
This action identifies and extracts brand colors by analyzing interactive elements
(buttons, links, CTAs) and their styling. It combines hardcoded element patterns
with AI-identified color hints to find primary, secondary, and accent brand colors,
along with background colors (light/dark) and text hierarchy colors.
Process:
1. Takes agent-provided hints about elements with brand colors (text + tags)
2. Searches DOM using both base selectors and agent hints
3. Extracts computed colors from matching elements
4. Scores and ranks colors by prominence, relevance, and hierarchy
5. Categorizes colors into brand, background, and text hierarchy groups
Args:
params (AgentColorThemeData): Contains:
- elements_to_find: List of elements agent identified (text, tags, priority)
- additional_tag_patterns: Extra tags to search (optional)
browser_session (BrowserSession): The active browser session
Returns:
ActionResult with extracted_content containing:
{
"primary": {"hex": "#...", "score": float, "examples": [...]},
"secondary": {"hex": "#...", "score": float, "examples": [...]},
"accent": {"hex": "#...", "score": float, "examples": [...]},
"background": {"hex": "#...", "score": float, "example": "...", "source": "agent-hint|auto-detected"},
"text_hierarchy": {
"heading": {"hex": "#...", "score": float, "hierarchy_level": "...", "source": "agent-hint|auto-detected"},
"body": {"hex": "#...", "score": float, "hierarchy_level": "...", "source": "agent-hint|auto-detected"},
"subtle": {"hex": "#...", "score": float, "hierarchy_level": "...", "source": "agent-hint|auto-detected"}
},
"all_colors": [...], # Top 10 ranked colors
"error": None or error message
} """,
param_model=PossibleColorThemeData,
)
async def extract_color_system(params,browser_session: BrowserSession):
print("Extracting color system from the website...--------------------")
print(params)
page = await browser_session.get_current_page()
await page._ensure_session()
await page._client.send.CSS.enable(session_id=page._session_id)
await page._client.send.DOM.getDocument(
params={'depth': 1}, # depth: 1 is usually enough to get the root document
session_id=page._session_id
)
dom_service = page.dom_service
enhanced_dom_tree = await dom_service.get_dom_tree(target_id=page._target_id)
serialized_dom_state, _ = DOMTreeSerializer(
enhanced_dom_tree, None, paint_order_filtering=True
).serialize_accessible_elements()
llm_representation = serialized_dom_state.llm_representation()
# print(llm_representation)
search_strategy = build_search_strategy(params)
print(search_strategy)
# Parse and match
matching_indices = []
lines = llm_representation.split('\n')
lines = [line.strip(" \t\r\n\f\v") for line in lines if line.strip(" \t\r\n\f\v")]
print(lines)
for i, line in enumerate(lines):
# Extract [index]<tag attributes>
match = re.match(r'\s*\[(\d+)\]<(\w+)([^>]*)>', line)
if not match:
continue
element_index = int(match.group(1))
tag = match.group(2)
attributes = match.group(3)
# Get text content from next line
text_content = ''
if i + 1 < len(lines):
next_line = lines[i + 1].strip()
if not next_line.startswith('['):
text_content = next_line
# Match Strategy 1: Base selectors
for base in search_strategy['base_selectors']:
if tag == base['tag']:
role_match = base['role'] is None or f'role="{base["role"]}"' in attributes
if role_match:
matching_indices.append({
'index': element_index,
'tag': tag,
'text': text_content,
'source': 'base',
'priority': None,
'hierarchy': base.get('hierarchy') # β¨ NEW
})
break
# Match Strategy 2: Agent text matches (higher priority)
for text_match in search_strategy['text_matches']:
if text_match.lower() in text_content.lower():
priority = search_strategy['priority_map'].get(text_match)
matching_indices.append({
'index': element_index,
'tag': tag,
'text': text_content,
'source': 'agent',
'priority': priority,
'matched_text': text_match,
'hierarchy': None # β¨ NEW (agent matches override hierarchy)
})
break
print(matching_indices )
# await page.dom_service.get_dom_tree(target_id=page._target_id)
# await page._ensure_session()
color_data = []
# β οΈ Limit to first 800 matches to avoid processing too many elements
matches_to_process = matching_indices[:800]
if len(matching_indices) > 800:
print(f"β οΈ Found {len(matching_indices)} matches, limiting to 800 for performance")
for match in matches_to_process:
element_index = match['index']
# Get element using selector_map (as you discovered!)
if element_index not in serialized_dom_state.selector_map:
continue
element_info = serialized_dom_state.selector_map[element_index]
try:
pushed_nodes = await page._client.send.DOM.pushNodesByBackendIdsToFrontend(
params={
'backendNodeIds': [element_info.backend_node_id], # Pass a list
},
session_id=page._session_id
)
# 2. Extract the live NodeId from the response list
working_node_ids = pushed_nodes.get('nodeIds', [])
if working_node_ids and working_node_ids[0] != 0:
working_node_id = working_node_ids[0]
print(f"β
Successfully resolved live NodeId: {working_node_id}")
tasksToRun = [
page._client.send.CSS.getComputedStyleForNode(
params={'nodeId': working_node_id},
session_id=page._session_id
),
page._client.send.DOM.getBoxModel(
params={'nodeId': working_node_id},
session_id=page._session_id
),
]
results = await asyncio.gather(*tasksToRun, return_exceptions=True)
computedStyle = results[0] if not isinstance(results[0], Exception) else None
boxModel = results[1] if not isinstance(results[1], Exception) else None
if not computedStyle:
print(f"β οΈ Could not get computed style for node {working_node_id}")
continue
# Extract colors from computed style
colors = extract_colors_from_computed_style(computedStyle.get('computedStyle', []))
if not colors:
continue # No colors found for this element
# Get element size and position from box model
element_size = 0
element_position = 0
if boxModel and 'model' in boxModel:
content = boxModel['model'].get('content', [])
if len(content) >= 4:
# content is [x1, y1, x2, y2, x3, y3, x4, y4]
width = abs(content[4] - content[0])
height = abs(content[5] - content[1])
element_size = width * height
element_position = content[1] # top Y position
# Build color entries
for prop_name, color_info in colors.items():
color_data.append({
'hex': color_info['hex'],
'property': prop_name,
'property_weight': color_info['weight'],
'element_text': match.get('text', ''),
'element_tag': match.get('tag', ''),
'element_size': element_size,
'element_position': element_position,
'agent_priority': match.get('priority'), # 'primary', 'secondary', 'accent', or None
'agent_matched': match.get('source') == 'agent',
'hierarchy': match.get('hierarchy'), # β¨ NEW: 'heading-primary', 'body-text', etc.
})
print(f"β
Extracted {len(colors)} colors from {match.get('tag', 'unknown')} element")
else:
print(f"β ERROR: Node with BackendNodeId {element_info.backend_node_id} could not be found in the current DOM tree.")
continue # Move to the next matched element
except Exception as e:
print(f"β ERROR during CDP call for node {element_index}: {e}")
continue
# ====== SCORING AND RANKING ======
print(f"\nπ Scoring {len(color_data)} color entries...")
# Score each color
for entry in color_data:
score = 0
# Agent priority match (highest weight)
if entry['agent_matched']:
priority_scores = {
'primary': 20,
'secondary': 15,
'accent': 10,
'background': 12,
'text-heading': 8,
'text-body': 6,
'text-subtle': 4
}
score += priority_scores.get(entry['agent_priority'], 5)
# Property type weight (base weight only, no background boost)
score += entry['property_weight']
# Text hierarchy boost (for text colors only)
if entry['property'] == 'color' and entry['hierarchy']:
hierarchy_boost = {
'heading-primary': 6,
'heading-secondary': 5,
'heading-tertiary': 4,
'body-text': 3,
'subtle-text': 2
}
score += hierarchy_boost.get(entry['hierarchy'], 0)
# Size weight (larger elements = more prominent)
size_score = min(entry['element_size'] / 1000, 10) # Cap at 10
score += size_score
# Position weight (above fold = more important)
if entry['element_position'] < 800: # Approximate viewport height
score += 5
entry['score'] = score
# Sort by score descending
color_data.sort(key=lambda x: x['score'], reverse=True)
# ====== DEDUPLICATION ======
print(f"π Deduplicating similar colors...")
unique_colors = []
seen_colors = []
for entry in color_data:
is_duplicate = False
for seen in seen_colors:
if colors_similar(entry['hex'], seen['hex']):
is_duplicate = True
break
if not is_duplicate:
unique_colors.append(entry)
seen_colors.append(entry)
print(f"β
Reduced to {len(unique_colors)} unique colors")
# ====== CATEGORIZATION ======
# Separate colors by agent priority hints
brand_colors = [] # primary, secondary, accent
background_hints = [] # background
text_hints = {'heading': [], 'body': [], 'subtle': []} # text-heading, text-body, text-subtle
unassigned_colors = [] # No agent hint
for c in unique_colors:
if c['agent_matched']:
priority = c['agent_priority']
if priority in ['primary', 'secondary', 'accent']:
brand_colors.append(c)
elif priority == 'background':
background_hints.append(c)
elif priority == 'text-heading':
text_hints['heading'].append(c)
elif priority == 'text-body':
text_hints['body'].append(c)
elif priority == 'text-subtle':
text_hints['subtle'].append(c)
else:
unassigned_colors.append(c)
print(f"π¨ Brand colors (agent hints): {len(brand_colors)}")
print(f"π Background hints: {len(background_hints)}")
print(f"π Text hints: heading={len(text_hints['heading'])}, body={len(text_hints['body'])}, subtle={len(text_hints['subtle'])}")
print(f"β Unassigned colors (auto-detect): {len(unassigned_colors)}")
# If no brand color hints, fallback to filtering layout backgrounds
if not brand_colors:
layout_backgrounds = ['body', 'header', 'main', 'nav', 'footer', 'section']
brand_colors = [
c for c in unassigned_colors
if not (c['property'] == 'background-color' and c['element_tag'] in layout_backgrounds)
]
print(f"β οΈ No brand hints - auto-detected {len(brand_colors)} brand colors")
result = {
'primary': None,
'secondary': None,
'accent': None,
'background': None,
'text_hierarchy': {},
'all_colors': [],
'error': None
}
# Extract PRIMARY/SECONDARY/ACCENT from brand colors only
if len(brand_colors) >= 1:
top = brand_colors[0]
result['primary'] = {
'hex': top['hex'],
'score': top['score'],
'examples': [f"{top['element_tag']}[{top['element_text'][:30]}]"],
'property': top['property'] # For verification
}
if len(brand_colors) >= 2:
second = brand_colors[1]
result['secondary'] = {
'hex': second['hex'],
'score': second['score'],
'examples': [f"{second['element_tag']}[{second['element_text'][:30]}]"],
'property': second['property']
}
if len(brand_colors) >= 3:
third = brand_colors[2]
result['accent'] = {
'hex': third['hex'],
'score': third['score'],
'examples': [f"{third['element_tag']}[{third['element_text'][:30]}]"],
'property': third['property']
}
# β¨ Extract background (use agent hint if provided, otherwise auto-detect)
if background_hints:
bg = background_hints[0]
result['background'] = {
'hex': bg['hex'],
'score': bg['score'],
'example': f"{bg['element_tag']}[{bg['element_text'][:30]}]",
'source': 'agent-hint'
}
else:
# Auto-detect background from unassigned colors
background_colors = [c for c in unassigned_colors if c['property'] == 'background-color']
if background_colors:
bg = background_colors[0]
result['background'] = {
'hex': bg['hex'],
'score': bg['score'],
'example': f"{bg['element_tag']}[{bg['element_text'][:30]}]",
'source': 'auto-detected'
}
# β¨ Extract text hierarchy (use agent hints first, fallback to hierarchy field)
# Define text_colors once for auto-detection fallback
text_colors = [c for c in unassigned_colors if c['property'] == 'color']
# Heading text
if text_hints['heading']:
tc = text_hints['heading'][0]
result['text_hierarchy']['heading'] = {
'hex': tc['hex'],
'score': tc['score'],
'example': f"{tc['element_tag']}[{tc['element_text'][:30]}]",
'source': 'agent-hint'
}
else:
# Auto-detect from heading hierarchy
for tc in text_colors:
if tc.get('hierarchy') in ['heading-primary', 'heading-secondary', 'heading-tertiary']:
result['text_hierarchy']['heading'] = {
'hex': tc['hex'],
'score': tc['score'],
'example': f"{tc['element_tag']}[{tc['element_text'][:30]}]",
'hierarchy_level': tc['hierarchy'],
'source': 'auto-detected'
}
break
# Body text
if text_hints['body']:
tc = text_hints['body'][0]
result['text_hierarchy']['body'] = {
'hex': tc['hex'],
'score': tc['score'],
'example': f"{tc['element_tag']}[{tc['element_text'][:30]}]",
'source': 'agent-hint'
}
else:
# Auto-detect from body hierarchy
for tc in text_colors:
if tc.get('hierarchy') == 'body-text':
result['text_hierarchy']['body'] = {
'hex': tc['hex'],
'score': tc['score'],
'example': f"{tc['element_tag']}[{tc['element_text'][:30]}]",
'hierarchy_level': tc['hierarchy'],
'source': 'auto-detected'
}
break
# Subtle text
if text_hints['subtle']:
tc = text_hints['subtle'][0]
result['text_hierarchy']['subtle'] = {
'hex': tc['hex'],
'score': tc['score'],
'example': f"{tc['element_tag']}[{tc['element_text'][:30]}]",
'source': 'agent-hint'
}
else:
# Auto-detect from subtle hierarchy
for tc in text_colors:
if tc.get('hierarchy') == 'subtle-text':
result['text_hierarchy']['subtle'] = {
'hex': tc['hex'],
'score': tc['score'],
'example': f"{tc['element_tag']}[{tc['element_text'][:30]}]",
'hierarchy_level': tc['hierarchy'],
'source': 'auto-detected'
}
break
# Top 10 palette
result['all_colors'] = [
{'hex': c['hex'], 'score': c['score'], 'property': c['property']}
for c in unique_colors[:10]
]
print(f"\nπ¨ Color System Extracted:")
print(f" Primary: {result['primary']['hex'] if result['primary'] else 'N/A'}")
print(f" Secondary: {result['secondary']['hex'] if result['secondary'] else 'N/A'}")
print(f" Accent: {result['accent']['hex'] if result['accent'] else 'N/A'}")
print(f" Background: {result['background']['hex'] if result['background'] else 'N/A'}")
print(f" Text (Heading): {result['text_hierarchy'].get('heading', {}).get('hex', 'N/A')}")
print(f" Text (Body): {result['text_hierarchy'].get('body', {}).get('hex', 'N/A')}")
print(f" Text (Subtle): {result['text_hierarchy'].get('subtle', {}).get('hex', 'N/A')}")
return ActionResult(
extracted_content=f"""
β
Color System Successfully Extracted
BRAND COLORS (from interactive elements):
ββββββββββββββββββββββββββββββββββββββββββ
Primary: {result['primary']['hex'] if result['primary'] else 'N/A'} (score: {result['primary']['score'] if result['primary'] else 0:.1f})
Source: {result['primary']['property'] if result['primary'] else 'N/A'}
Example: {result['primary']['examples'][0] if result['primary'] else 'N/A'}
Secondary: {result['secondary']['hex'] if result['secondary'] else 'N/A'} (score: {result['secondary']['score'] if result['secondary'] else 0:.1f})
Source: {result['secondary']['property'] if result['secondary'] else 'N/A'}
Example: {result['secondary']['examples'][0] if result['secondary'] else 'N/A'}
Accent: {result['accent']['hex'] if result['accent'] else 'N/A'} (score: {result['accent']['score'] if result['accent'] else 0:.1f})
Source: {result['accent']['property'] if result['accent'] else 'N/A'}
Example: {result['accent']['examples'][0] if result['accent'] else 'N/A'}
BACKGROUND COLOR:
ββββββββββββββββββββββββββββββββββββββββββ
Background: {result['background']['hex'] if result['background'] else 'N/A'}
{f"Source: {result['background']['source']}" if result['background'] else ''}
TEXT HIERARCHY:
ββββββββββββββββββββββββββββββββββββββββββ
Heading: {result['text_hierarchy'].get('heading', {}).get('hex', 'N/A')}
Body: {result['text_hierarchy'].get('body', {}).get('hex', 'N/A')}
Subtle: {result['text_hierarchy'].get('subtle', {}).get('hex', 'N/A')}
VERIFICATION NOTES:
ββββββββββββββββββββββββββββββββββββββββββ
β Primary color is from: {result['primary']['property'] if result['primary'] else 'unknown'} property
β Colors ranked by prominence, agent hints, and visual hierarchy
β Layout backgrounds excluded from brand color ranking
β Total unique colors found: {len(brand_colors)} brand colors, {len([c for c in unique_colors if c['property'] == 'background-color'])} backgrounds
FULL PALETTE (Top 10):
{chr(10).join(f" {i+1}. {c['hex']} ({c['property']}, score: {c['score']:.1f})" for i, c in enumerate(unique_colors[:10]))}
""",
include_in_memory=True
) |