Leon4gr45 commited on
Commit
b6dfd6f
·
verified ·
1 Parent(s): 5eb209a

Delete browser_use/browser_use/dom/markdown_extractor.py with huggingface_hub

Browse files
browser_use/browser_use/dom/markdown_extractor.py DELETED
@@ -1,170 +0,0 @@
1
- """
2
- Shared markdown extraction utilities for browser content processing.
3
-
4
- This module provides a unified interface for extracting clean markdown from browser content,
5
- used by both the tools service and page actor.
6
- """
7
-
8
- import re
9
- from typing import TYPE_CHECKING, Any
10
-
11
- from browser_use.dom.serializer.html_serializer import HTMLSerializer
12
- from browser_use.dom.service import DomService
13
-
14
- if TYPE_CHECKING:
15
- from browser_use.browser.session import BrowserSession
16
- from browser_use.browser.watchdogs.dom_watchdog import DOMWatchdog
17
-
18
-
19
- async def extract_clean_markdown(
20
- browser_session: 'BrowserSession | None' = None,
21
- dom_service: DomService | None = None,
22
- target_id: str | None = None,
23
- extract_links: bool = False,
24
- ) -> tuple[str, dict[str, Any]]:
25
- """Extract clean markdown from browser content using enhanced DOM tree.
26
-
27
- This unified function can extract markdown using either a browser session (for tools service)
28
- or a DOM service with target ID (for page actor).
29
-
30
- Args:
31
- browser_session: Browser session to extract content from (tools service path)
32
- dom_service: DOM service instance (page actor path)
33
- target_id: Target ID for the page (required when using dom_service)
34
- extract_links: Whether to preserve links in markdown
35
-
36
- Returns:
37
- tuple: (clean_markdown_content, content_statistics)
38
-
39
- Raises:
40
- ValueError: If neither browser_session nor (dom_service + target_id) are provided
41
- """
42
- # Validate input parameters
43
- if browser_session is not None:
44
- if dom_service is not None or target_id is not None:
45
- raise ValueError('Cannot specify both browser_session and dom_service/target_id')
46
- # Browser session path (tools service)
47
- enhanced_dom_tree = await _get_enhanced_dom_tree_from_browser_session(browser_session)
48
- current_url = await browser_session.get_current_page_url()
49
- method = 'enhanced_dom_tree'
50
- elif dom_service is not None and target_id is not None:
51
- # DOM service path (page actor)
52
- # Lazy fetch all_frames inside get_dom_tree if needed (for cross-origin iframes)
53
- enhanced_dom_tree, _ = await dom_service.get_dom_tree(target_id=target_id, all_frames=None)
54
- current_url = None # Not available via DOM service
55
- method = 'dom_service'
56
- else:
57
- raise ValueError('Must provide either browser_session or both dom_service and target_id')
58
-
59
- # Use the HTML serializer with the enhanced DOM tree
60
- html_serializer = HTMLSerializer(extract_links=extract_links)
61
- page_html = html_serializer.serialize(enhanced_dom_tree)
62
-
63
- original_html_length = len(page_html)
64
-
65
- # Use markdownify for clean markdown conversion
66
- from markdownify import markdownify as md
67
-
68
- content = md(
69
- page_html,
70
- heading_style='ATX', # Use # style headings
71
- strip=['script', 'style'], # Remove these tags
72
- bullets='-', # Use - for unordered lists
73
- code_language='', # Don't add language to code blocks
74
- escape_asterisks=False, # Don't escape asterisks (cleaner output)
75
- escape_underscores=False, # Don't escape underscores (cleaner output)
76
- escape_misc=False, # Don't escape other characters (cleaner output)
77
- autolinks=False, # Don't convert URLs to <> format
78
- default_title=False, # Don't add default title attributes
79
- keep_inline_images_in=[], # Don't keep inline images in any tags (we already filter base64 in HTML)
80
- )
81
-
82
- initial_markdown_length = len(content)
83
-
84
- # Minimal cleanup - markdownify already does most of the work
85
- content = re.sub(r'%[0-9A-Fa-f]{2}', '', content) # Remove any remaining URL encoding
86
-
87
- # Apply light preprocessing to clean up excessive whitespace
88
- content, chars_filtered = _preprocess_markdown_content(content)
89
-
90
- final_filtered_length = len(content)
91
-
92
- # Content statistics
93
- stats = {
94
- 'method': method,
95
- 'original_html_chars': original_html_length,
96
- 'initial_markdown_chars': initial_markdown_length,
97
- 'filtered_chars_removed': chars_filtered,
98
- 'final_filtered_chars': final_filtered_length,
99
- }
100
-
101
- # Add URL to stats if available
102
- if current_url:
103
- stats['url'] = current_url
104
-
105
- return content, stats
106
-
107
-
108
- async def _get_enhanced_dom_tree_from_browser_session(browser_session: 'BrowserSession'):
109
- """Get enhanced DOM tree from browser session via DOMWatchdog."""
110
- # Get the enhanced DOM tree from DOMWatchdog
111
- # This captures the current state of the page including dynamic content, shadow roots, etc.
112
- dom_watchdog: DOMWatchdog | None = browser_session._dom_watchdog
113
- assert dom_watchdog is not None, 'DOMWatchdog not available'
114
-
115
- # Use cached enhanced DOM tree if available, otherwise build it
116
- if dom_watchdog.enhanced_dom_tree is not None:
117
- return dom_watchdog.enhanced_dom_tree
118
-
119
- # Build the enhanced DOM tree if not cached
120
- await dom_watchdog._build_dom_tree_without_highlights()
121
- enhanced_dom_tree = dom_watchdog.enhanced_dom_tree
122
- assert enhanced_dom_tree is not None, 'Enhanced DOM tree not available'
123
-
124
- return enhanced_dom_tree
125
-
126
-
127
- # Legacy aliases removed - all code now uses the unified extract_clean_markdown function
128
-
129
-
130
- def _preprocess_markdown_content(content: str, max_newlines: int = 3) -> tuple[str, int]:
131
- """
132
- Light preprocessing of markdown output - minimal cleanup with JSON blob removal.
133
-
134
- Args:
135
- content: Markdown content to lightly filter
136
- max_newlines: Maximum consecutive newlines to allow
137
-
138
- Returns:
139
- tuple: (filtered_content, chars_filtered)
140
- """
141
- original_length = len(content)
142
-
143
- # Remove JSON blobs (common in SPAs like LinkedIn, Facebook, etc.)
144
- # These are often embedded as `{"key":"value",...}` and can be massive
145
- # Match JSON objects/arrays that are at least 100 chars long
146
- # This catches SPA state/config data without removing small inline JSON
147
- content = re.sub(r'`\{["\w].*?\}`', '', content, flags=re.DOTALL) # Remove JSON in code blocks
148
- content = re.sub(r'\{"\$type":[^}]{100,}\}', '', content) # Remove JSON with $type fields (common pattern)
149
- content = re.sub(r'\{"[^"]{5,}":\{[^}]{100,}\}', '', content) # Remove nested JSON objects
150
-
151
- # Compress consecutive newlines (4+ newlines become max_newlines)
152
- content = re.sub(r'\n{4,}', '\n' * max_newlines, content)
153
-
154
- # Remove lines that are only whitespace or very short (likely artifacts)
155
- lines = content.split('\n')
156
- filtered_lines = []
157
- for line in lines:
158
- stripped = line.strip()
159
- # Keep lines with substantial content
160
- if len(stripped) > 2:
161
- # Skip lines that look like JSON (start with { or [ and are very long)
162
- if (stripped.startswith('{') or stripped.startswith('[')) and len(stripped) > 100:
163
- continue
164
- filtered_lines.append(line)
165
-
166
- content = '\n'.join(filtered_lines)
167
- content = content.strip()
168
-
169
- chars_filtered = original_length - len(content)
170
- return content, chars_filtered