sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
unclecode/crawl4ai:docs/examples/nst_proxy/api_proxy_example.py
""" NSTProxy Integration Examples for crawl4ai ------------------------------------------ NSTProxy is a premium residential proxy provider. ๐Ÿ‘‰ Purchase Proxies: https://nstproxy.com ๐Ÿ’ฐ Use coupon code "crawl4ai" for 10% off your plan. """ import asyncio, requests from crawl4ai import AsyncWebCrawler, BrowserConfig async def main(): """ Example: Dynamically fetch a proxy from NSTProxy API before crawling. """ NST_TOKEN = "YOUR_NST_PROXY_TOKEN" # Get from https://app.nstproxy.com/profile CHANNEL_ID = "YOUR_NST_PROXY_CHANNEL_ID" # Your NSTProxy Channel ID country = "ANY" # e.g. "ANY", "US", "DE" # Fetch proxy from NSTProxy API api_url = ( f"https://api.nstproxy.com/api/v1/generate/apiproxies" f"?fType=2&channelId={CHANNEL_ID}&country={country}" f"&protocol=http&sessionDuration=10&count=1&token={NST_TOKEN}" ) response = requests.get(api_url, timeout=10).json() proxy = response[0] ip = proxy.get("ip") port = proxy.get("port") username = proxy.get("username", "") password = proxy.get("password", "") browser_config = BrowserConfig(proxy_config={ "server": f"http://{ip}:{port}", "username": username, "password": password, }) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun(url="https://example.com") print("[API Proxy] Status:", result.status_code) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/nst_proxy/api_proxy_example.py", "license": "Apache License 2.0", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/nst_proxy/auth_proxy_example.py
""" NSTProxy Integration Examples for crawl4ai ------------------------------------------ NSTProxy is a premium residential proxy provider. ๐Ÿ‘‰ Purchase Proxies: https://nstproxy.com ๐Ÿ’ฐ Use coupon code "crawl4ai" for 10% off your plan. """ import asyncio from crawl4ai import AsyncWebCrawler, BrowserConfig async def main(): """ Example: Use NSTProxy with manual username/password authentication. """ browser_config = BrowserConfig(proxy_config={ "server": "http://gate.nstproxy.io:24125", "username": "your_username", "password": "your_password", }) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun(url="https://example.com") print("[Auth Proxy] Status:", result.status_code) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/nst_proxy/auth_proxy_example.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
unclecode/crawl4ai:docs/examples/nst_proxy/basic_proxy_example.py
""" NSTProxy Integration Examples for crawl4ai ------------------------------------------ NSTProxy is a premium residential proxy provider. ๐Ÿ‘‰ Purchase Proxies: https://nstproxy.com ๐Ÿ’ฐ Use coupon code "crawl4ai" for 10% off your plan. """ import asyncio from crawl4ai import AsyncWebCrawler, BrowserConfig async def main(): # Using HTTP proxy browser_config = BrowserConfig(proxy_config={"server": "http://gate.nstproxy.io:24125"}) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun(url="https://example.com") print("[HTTP Proxy] Status:", result.status_code) # Using SOCKS proxy browser_config = BrowserConfig(proxy_config={"server": "socks5://gate.nstproxy.io:24125"}) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun(url="https://example.com") print("[SOCKS5 Proxy] Status:", result.status_code) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/nst_proxy/basic_proxy_example.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/nst_proxy/nstproxy_example.py
""" NSTProxy Integration Examples for crawl4ai ------------------------------------------ NSTProxy is a premium residential proxy provider. ๐Ÿ‘‰ Purchase Proxies: https://nstproxy.com ๐Ÿ’ฐ Use coupon code "crawl4ai" for 10% off your plan. """ import asyncio from crawl4ai import AsyncWebCrawler, BrowserConfig async def main(): """ Example: Using NSTProxy with AsyncWebCrawler. """ NST_TOKEN = "YOUR_NST_PROXY_TOKEN" # Get from https://app.nstproxy.com/profile CHANNEL_ID = "YOUR_NST_PROXY_CHANNEL_ID" # Your NSTProxy Channel ID browser_config = BrowserConfig() browser_config.set_nstproxy( token=NST_TOKEN, channel_id=CHANNEL_ID, country="ANY", # e.g. "US", "JP", or "ANY" state="", # optional, leave empty if not needed city="", # optional, leave empty if not needed session_duration=0 # Session duration in minutes,0 = rotate on every request ) # === Run crawler === async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun(url="https://example.com") print("[Nstproxy] Status:", result.status_code) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/nst_proxy/nstproxy_example.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/releases_review/demo_v0.7.7.py
#!/usr/bin/env python3 """ Crawl4AI v0.7.7 Release Demo ============================ This demo showcases the major feature in v0.7.7: **Self-Hosting with Real-time Monitoring Dashboard** Features Demonstrated: 1. System health monitoring with live metrics 2. Real-time request tracking (active & completed) 3. Browser pool management (permanent/hot/cold pools) 4. Monitor API endpoints for programmatic access 5. WebSocket streaming for real-time updates 6. Control actions (kill browser, cleanup, restart) 7. Production metrics (efficiency, reuse rates, memory) Prerequisites: - Crawl4AI Docker container running on localhost:11235 - Python packages: pip install httpx websockets Usage: python docs/releases_review/demo_v0.7.7.py """ import asyncio import httpx import json import time from datetime import datetime from typing import Dict, Any # Configuration CRAWL4AI_BASE_URL = "http://localhost:11235" MONITOR_DASHBOARD_URL = f"{CRAWL4AI_BASE_URL}/dashboard" def print_section(title: str, description: str = ""): """Print a formatted section header""" print(f"\n{'=' * 70}") print(f"๐Ÿ“Š {title}") if description: print(f"{description}") print(f"{'=' * 70}\n") def print_subsection(title: str): """Print a formatted subsection header""" print(f"\n{'-' * 70}") print(f"{title}") print(f"{'-' * 70}") async def check_server_health(): """Check if Crawl4AI server is running""" try: async with httpx.AsyncClient(timeout=5.0) as client: response = await client.get(f"{CRAWL4AI_BASE_URL}/health") return response.status_code == 200 except: return False async def demo_1_system_health_overview(): """Demo 1: System Health Overview - Live metrics and pool status""" print_section( "Demo 1: System Health Overview", "Real-time monitoring of system resources and browser pool" ) async with httpx.AsyncClient(timeout=30.0) as client: print("๐Ÿ” Fetching system health metrics...") try: response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/health") health = response.json() print("\nโœ… System Health Report:") print(f"\n๐Ÿ–ฅ๏ธ Container Metrics:") print(f" โ€ข CPU Usage: {health['container']['cpu_percent']:.1f}%") print(f" โ€ข Memory Usage: {health['container']['memory_percent']:.1f}% " f"({health['container']['memory_mb']:.0f} MB)") print(f" โ€ข Network RX: {health['container']['network_rx_mb']:.2f} MB") print(f" โ€ข Network TX: {health['container']['network_tx_mb']:.2f} MB") print(f" โ€ข Uptime: {health['container']['uptime_seconds']:.0f}s") print(f"\n๐ŸŒ Browser Pool Status:") print(f" Permanent Browser:") print(f" โ€ข Active: {health['pool']['permanent']['active']}") print(f" โ€ข Total Requests: {health['pool']['permanent']['total_requests']}") print(f" Hot Pool (Frequently Used Configs):") print(f" โ€ข Count: {health['pool']['hot']['count']}") print(f" โ€ข Total Requests: {health['pool']['hot']['total_requests']}") print(f" Cold Pool (On-Demand Configs):") print(f" โ€ข Count: {health['pool']['cold']['count']}") print(f" โ€ข Total Requests: {health['pool']['cold']['total_requests']}") print(f"\n๐Ÿ“ˆ Overall Statistics:") print(f" โ€ข Total Requests: {health['stats']['total_requests']}") print(f" โ€ข Success Rate: {health['stats']['success_rate_percent']:.1f}%") print(f" โ€ข Avg Latency: {health['stats']['avg_latency_ms']:.0f}ms") print(f"\n๐Ÿ’ก Dashboard URL: {MONITOR_DASHBOARD_URL}") except Exception as e: print(f"โŒ Error fetching health: {e}") async def demo_2_request_tracking(): """Demo 2: Real-time Request Tracking - Generate and monitor requests""" print_section( "Demo 2: Real-time Request Tracking", "Submit crawl jobs and watch them in real-time" ) async with httpx.AsyncClient(timeout=60.0) as client: print("๐Ÿš€ Submitting crawl requests...") # Submit multiple requests urls_to_crawl = [ "https://httpbin.org/html", "https://httpbin.org/json", "https://example.com" ] tasks = [] for url in urls_to_crawl: task = client.post( f"{CRAWL4AI_BASE_URL}/crawl", json={"urls": [url], "crawler_config": {}} ) tasks.append(task) print(f" โ€ข Submitting {len(urls_to_crawl)} requests in parallel...") results = await asyncio.gather(*tasks, return_exceptions=True) successful = sum(1 for r in results if not isinstance(r, Exception) and r.status_code == 200) print(f" โœ… {successful}/{len(urls_to_crawl)} requests submitted") # Check request tracking print("\n๐Ÿ“Š Checking request tracking...") await asyncio.sleep(2) # Wait for requests to process response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/requests") requests_data = response.json() print(f"\n๐Ÿ“‹ Request Status:") print(f" โ€ข Active Requests: {len(requests_data['active'])}") print(f" โ€ข Completed Requests: {len(requests_data['completed'])}") if requests_data['completed']: print(f"\n๐Ÿ“ Recent Completed Requests:") for req in requests_data['completed'][:3]: status_icon = "โœ…" if req['success'] else "โŒ" print(f" {status_icon} {req['endpoint']} - {req['latency_ms']:.0f}ms") async def demo_3_browser_pool_management(): """Demo 3: Browser Pool Management - 3-tier architecture in action""" print_section( "Demo 3: Browser Pool Management", "Understanding permanent, hot, and cold browser pools" ) async with httpx.AsyncClient(timeout=60.0) as client: print("๐ŸŒŠ Testing browser pool with different configurations...") # Test 1: Default config (permanent browser) print("\n๐Ÿ”ฅ Test 1: Default Config โ†’ Permanent Browser") for i in range(3): await client.post( f"{CRAWL4AI_BASE_URL}/crawl", json={"urls": [f"https://httpbin.org/html?req={i}"], "crawler_config": {}} ) print(f" โ€ข Request {i+1}/3 sent (should use permanent browser)") await asyncio.sleep(2) # Test 2: Custom viewport (cold โ†’ hot promotion after 3 uses) print("\nโ™จ๏ธ Test 2: Custom Viewport โ†’ Cold Pool (promoting to Hot)") viewport_config = {"viewport": {"width": 1280, "height": 720}} for i in range(4): await client.post( f"{CRAWL4AI_BASE_URL}/crawl", json={ "urls": [f"https://httpbin.org/json?viewport={i}"], "browser_config": viewport_config, "crawler_config": {} } ) print(f" โ€ข Request {i+1}/4 sent (coldโ†’hot promotion after 3rd use)") await asyncio.sleep(2) # Check browser pool status print("\n๐Ÿ“Š Browser Pool Report:") response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/browsers") browsers = response.json() print(f"\n๐ŸŽฏ Pool Summary:") print(f" โ€ข Total Browsers: {browsers['summary']['total_count']}") print(f" โ€ข Total Memory: {browsers['summary']['total_memory_mb']} MB") print(f" โ€ข Reuse Rate: {browsers['summary']['reuse_rate_percent']:.1f}%") print(f"\n๐Ÿ“‹ Browser Pool Details:") if browsers['permanent']: for browser in browsers['permanent']: print(f" ๐Ÿ”ฅ Permanent: {browser['browser_id'][:8]}... | " f"Requests: {browser['request_count']} | " f"Memory: {browser['memory_mb']:.0f} MB") if browsers['hot']: for browser in browsers['hot']: print(f" โ™จ๏ธ Hot: {browser['browser_id'][:8]}... | " f"Requests: {browser['request_count']} | " f"Memory: {browser['memory_mb']:.0f} MB") if browsers['cold']: for browser in browsers['cold']: print(f" โ„๏ธ Cold: {browser['browser_id'][:8]}... | " f"Requests: {browser['request_count']} | " f"Memory: {browser['memory_mb']:.0f} MB") async def demo_4_monitor_api_endpoints(): """Demo 4: Monitor API Endpoints - Complete API surface""" print_section( "Demo 4: Monitor API Endpoints", "Programmatic access to all monitoring data" ) async with httpx.AsyncClient(timeout=30.0) as client: print("๐Ÿ”Œ Testing Monitor API endpoints...") # Endpoint performance statistics print_subsection("Endpoint Performance Statistics") response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/endpoints/stats") endpoint_stats = response.json() print("\n๐Ÿ“Š Per-Endpoint Analytics:") for endpoint, stats in endpoint_stats.items(): print(f" {endpoint}:") print(f" โ€ข Requests: {stats['count']}") print(f" โ€ข Avg Latency: {stats['avg_latency_ms']:.0f}ms") print(f" โ€ข Success Rate: {stats['success_rate_percent']:.1f}%") # Timeline data for charts print_subsection("Timeline Data (for Charts)") response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/timeline?minutes=5") timeline = response.json() print(f"\n๐Ÿ“ˆ Timeline Metrics (last 5 minutes):") print(f" โ€ข Data Points: {len(timeline['memory'])}") if timeline['memory']: latest = timeline['memory'][-1] print(f" โ€ข Latest Memory: {latest['value']:.1f}%") print(f" โ€ข Timestamp: {latest['timestamp']}") # Janitor logs print_subsection("Janitor Cleanup Events") response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/logs/janitor?limit=3") janitor_logs = response.json() print(f"\n๐Ÿงน Recent Cleanup Activities:") if janitor_logs: for log in janitor_logs[:3]: print(f" โ€ข {log['timestamp']}: {log['message']}") else: print(" (No cleanup events yet - janitor runs periodically)") # Error logs print_subsection("Error Monitoring") response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/logs/errors?limit=3") error_logs = response.json() print(f"\nโŒ Recent Errors:") if error_logs: for log in error_logs[:3]: print(f" โ€ข {log['timestamp']}: {log['error_type']}") print(f" {log['message'][:100]}...") else: print(" โœ… No recent errors!") async def demo_5_websocket_streaming(): """Demo 5: WebSocket Streaming - Real-time updates""" print_section( "Demo 5: WebSocket Streaming", "Live monitoring with 2-second update intervals" ) print("โšก WebSocket Streaming Demo") print("\n๐Ÿ’ก The monitoring dashboard uses WebSocket for real-time updates") print(f" โ€ข Connection: ws://localhost:11235/monitor/ws") print(f" โ€ข Update Interval: 2 seconds") print(f" โ€ข Data: Health, requests, browsers, memory, errors") print("\n๐Ÿ“ Sample WebSocket Integration Code:") print(""" import websockets import json async def monitor_realtime(): uri = "ws://localhost:11235/monitor/ws" async with websockets.connect(uri) as websocket: while True: data = await websocket.recv() update = json.loads(data) print(f"Memory: {update['health']['container']['memory_percent']:.1f}%") print(f"Active Requests: {len(update['requests']['active'])}") print(f"Browser Pool: {update['health']['pool']['permanent']['active']}") """) print("\n๐ŸŒ Open the dashboard to see WebSocket in action:") print(f" {MONITOR_DASHBOARD_URL}") async def demo_6_control_actions(): """Demo 6: Control Actions - Manual browser management""" print_section( "Demo 6: Control Actions", "Manual control over browser pool and cleanup" ) async with httpx.AsyncClient(timeout=30.0) as client: print("๐ŸŽฎ Testing control actions...") # Force cleanup print_subsection("Force Immediate Cleanup") print("๐Ÿงน Triggering manual cleanup...") try: response = await client.post(f"{CRAWL4AI_BASE_URL}/monitor/actions/cleanup") if response.status_code == 200: result = response.json() print(f" โœ… Cleanup completed") print(f" โ€ข Browsers cleaned: {result.get('cleaned_count', 0)}") print(f" โ€ข Memory freed: {result.get('memory_freed_mb', 0):.1f} MB") else: print(f" โš ๏ธ Response: {response.status_code}") except Exception as e: print(f" โ„น๏ธ Cleanup action: {e}") # Get browser list for potential kill/restart print_subsection("Browser Management") response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/browsers") browsers = response.json() cold_browsers = browsers.get('cold', []) if cold_browsers: browser_id = cold_browsers[0]['browser_id'] print(f"\n๐ŸŽฏ Example: Kill specific browser") print(f" POST /monitor/actions/kill_browser") print(f" JSON: {{'browser_id': '{browser_id[:16]}...'}}") print(f" โ†’ Kills the browser and frees resources") print(f"\n๐Ÿ”„ Example: Restart browser") print(f" POST /monitor/actions/restart_browser") print(f" JSON: {{'browser_id': 'browser_id_here'}}") print(f" โ†’ Restart a specific browser instance") # Reset statistics print_subsection("Reset Statistics") print("๐Ÿ“Š Statistics can be reset for fresh monitoring:") print(f" POST /monitor/stats/reset") print(f" โ†’ Clears all accumulated statistics") async def demo_7_production_metrics(): """Demo 7: Production Metrics - Key indicators for operations""" print_section( "Demo 7: Production Metrics", "Critical metrics for production monitoring" ) async with httpx.AsyncClient(timeout=30.0) as client: print("๐Ÿ“Š Key Production Metrics:") # Overall health response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/health") health = response.json() # Browser efficiency response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/browsers") browsers = response.json() print("\n๐ŸŽฏ Critical Metrics to Track:") print(f"\n1๏ธโƒฃ Memory Usage Trends") print(f" โ€ข Current: {health['container']['memory_percent']:.1f}%") print(f" โ€ข Alert if: >80%") print(f" โ€ข Action: Trigger cleanup or scale") print(f"\n2๏ธโƒฃ Request Success Rate") print(f" โ€ข Current: {health['stats']['success_rate_percent']:.1f}%") print(f" โ€ข Target: >95%") print(f" โ€ข Alert if: <90%") print(f"\n3๏ธโƒฃ Average Latency") print(f" โ€ข Current: {health['stats']['avg_latency_ms']:.0f}ms") print(f" โ€ข Target: <2000ms") print(f" โ€ข Alert if: >5000ms") print(f"\n4๏ธโƒฃ Browser Pool Efficiency") print(f" โ€ข Reuse Rate: {browsers['summary']['reuse_rate_percent']:.1f}%") print(f" โ€ข Target: >80%") print(f" โ€ข Indicates: Effective browser pooling") print(f"\n5๏ธโƒฃ Total Browsers") print(f" โ€ข Current: {browsers['summary']['total_count']}") print(f" โ€ข Alert if: >20 (possible leak)") print(f" โ€ข Check: Janitor is running correctly") print(f"\n6๏ธโƒฃ Error Frequency") response = await client.get(f"{CRAWL4AI_BASE_URL}/monitor/logs/errors?limit=10") errors = response.json() print(f" โ€ข Recent Errors: {len(errors)}") print(f" โ€ข Alert if: >10 in last hour") print(f" โ€ข Action: Review error patterns") print("\n๐Ÿ’ก Integration Examples:") print(" โ€ข Prometheus: Scrape /monitor/health") print(" โ€ข Alerting: Monitor memory, success rate, latency") print(" โ€ข Dashboards: WebSocket streaming to custom UI") print(" โ€ข Log Aggregation: Collect /monitor/logs/* endpoints") async def demo_8_self_hosting_value(): """Demo 8: Self-Hosting Value Proposition""" print_section( "Demo 8: Why Self-Host Crawl4AI?", "The value proposition of owning your infrastructure" ) print("๐ŸŽฏ Self-Hosting Benefits:\n") print("๐Ÿ”’ Data Privacy & Security") print(" โ€ข Your data never leaves your infrastructure") print(" โ€ข No third-party access to crawled content") print(" โ€ข Keep sensitive workflows behind your firewall") print("\n๐Ÿ’ฐ Cost Control") print(" โ€ข No per-request pricing or rate limits") print(" โ€ข Predictable infrastructure costs") print(" โ€ข Scale based on your actual needs") print("\n๐ŸŽฏ Full Customization") print(" โ€ข Complete control over browser configs") print(" โ€ข Custom hooks and strategies") print(" โ€ข Tailored monitoring and alerting") print("\n๐Ÿ“Š Complete Transparency") print(" โ€ข Real-time monitoring dashboard") print(" โ€ข Full visibility into system performance") print(" โ€ข Detailed request and error tracking") print("\nโšก Performance & Flexibility") print(" โ€ข Direct access, no network overhead") print(" โ€ข Integrate with existing infrastructure") print(" โ€ข Custom resource allocation") print("\n๐Ÿ›ก๏ธ Enterprise-Grade Operations") print(" โ€ข Prometheus integration ready") print(" โ€ข WebSocket for real-time dashboards") print(" โ€ข Full API for automation") print(" โ€ข Manual controls for troubleshooting") print(f"\n๐ŸŒ Get Started:") print(f" docker pull unclecode/crawl4ai:0.7.7") print(f" docker run -d -p 11235:11235 --shm-size=1g unclecode/crawl4ai:0.7.7") print(f" # Visit: {MONITOR_DASHBOARD_URL}") def print_summary(): """Print comprehensive demo summary""" print("\n" + "=" * 70) print("๐Ÿ“Š DEMO SUMMARY - Crawl4AI v0.7.7") print("=" * 70) print("\nโœจ Features Demonstrated:") print("=" * 70) print("โœ… System Health Overview") print(" โ†’ Real-time CPU, memory, network, and uptime monitoring") print("\nโœ… Request Tracking") print(" โ†’ Active and completed request monitoring with full details") print("\nโœ… Browser Pool Management") print(" โ†’ 3-tier architecture: Permanent, Hot, and Cold pools") print(" โ†’ Automatic promotion and cleanup") print("\nโœ… Monitor API Endpoints") print(" โ†’ Complete REST API for programmatic access") print(" โ†’ Health, requests, browsers, timeline, logs, errors") print("\nโœ… WebSocket Streaming") print(" โ†’ Real-time updates every 2 seconds") print(" โ†’ Build custom dashboards with live data") print("\nโœ… Control Actions") print(" โ†’ Manual browser management (kill, restart)") print(" โ†’ Force cleanup and statistics reset") print("\nโœ… Production Metrics") print(" โ†’ 6 critical metrics for operational excellence") print(" โ†’ Prometheus integration patterns") print("\nโœ… Self-Hosting Value") print(" โ†’ Data privacy, cost control, full customization") print(" โ†’ Enterprise-grade transparency and control") print("\n" + "=" * 70) print("๐ŸŽฏ What's New in v0.7.7?") print("=" * 70) print("โ€ข ๐Ÿ“Š Complete Real-time Monitoring System") print("โ€ข ๐ŸŒ Interactive Web Dashboard (/dashboard)") print("โ€ข ๐Ÿ”Œ Comprehensive Monitor API") print("โ€ข โšก WebSocket Streaming (2-second updates)") print("โ€ข ๐ŸŽฎ Manual Control Actions") print("โ€ข ๐Ÿ“ˆ Production Integration Examples") print("โ€ข ๐Ÿญ Prometheus, Alerting, Log Aggregation") print("โ€ข ๐Ÿ”ฅ Smart Browser Pool (Permanent/Hot/Cold)") print("โ€ข ๐Ÿงน Automatic Janitor Cleanup") print("โ€ข ๐Ÿ“‹ Full Request & Error Tracking") print("\n" + "=" * 70) print("๐Ÿ’ก Why This Matters") print("=" * 70) print("Before v0.7.7: Docker was just a containerized crawler") print("After v0.7.7: Complete self-hosting platform with enterprise monitoring") print("\nYou now have:") print(" โ€ข Full visibility into what's happening inside") print(" โ€ข Real-time operational dashboards") print(" โ€ข Complete control over browser resources") print(" โ€ข Production-ready observability") print(" โ€ข Zero external dependencies") print("\n" + "=" * 70) print("๐Ÿ“š Next Steps") print("=" * 70) print(f"1. Open the dashboard: {MONITOR_DASHBOARD_URL}") print("2. Read the docs: https://docs.crawl4ai.com/basic/self-hosting/") print("3. Try the Monitor API endpoints yourself") print("4. Set up Prometheus integration for production") print("5. Build custom dashboards with WebSocket streaming") print("\n" + "=" * 70) print("๐Ÿ”— Resources") print("=" * 70) print(f"โ€ข Dashboard: {MONITOR_DASHBOARD_URL}") print(f"โ€ข Health API: {CRAWL4AI_BASE_URL}/monitor/health") print(f"โ€ข Documentation: https://docs.crawl4ai.com/") print(f"โ€ข GitHub: https://github.com/unclecode/crawl4ai") print("\n" + "=" * 70) print("๐ŸŽ‰ You're now in control of your web crawling destiny!") print("=" * 70) async def main(): """Run all demos""" print("\n" + "=" * 70) print("๐Ÿš€ Crawl4AI v0.7.7 Release Demo") print("=" * 70) print("Feature: Self-Hosting with Real-time Monitoring Dashboard") print("=" * 70) # Check if server is running print("\n๐Ÿ” Checking Crawl4AI server...") server_running = await check_server_health() if not server_running: print(f"โŒ Cannot connect to Crawl4AI at {CRAWL4AI_BASE_URL}") print("\nPlease start the Docker container:") print(" docker pull unclecode/crawl4ai:0.7.7") print(" docker run -d -p 11235:11235 --shm-size=1g unclecode/crawl4ai:0.7.7") print("\nThen re-run this demo.") return print(f"โœ… Crawl4AI server is running!") print(f"๐Ÿ“Š Dashboard available at: {MONITOR_DASHBOARD_URL}") # Run all demos demos = [ demo_1_system_health_overview, demo_2_request_tracking, demo_3_browser_pool_management, demo_4_monitor_api_endpoints, demo_5_websocket_streaming, demo_6_control_actions, demo_7_production_metrics, demo_8_self_hosting_value, ] for i, demo_func in enumerate(demos, 1): try: await demo_func() if i < len(demos): await asyncio.sleep(2) # Brief pause between demos except KeyboardInterrupt: print(f"\n\nโš ๏ธ Demo interrupted by user") return except Exception as e: print(f"\nโŒ Demo {i} error: {e}") print("Continuing to next demo...\n") continue # Print comprehensive summary print_summary() print("\n" + "=" * 70) print("โœ… Demo completed!") print("=" * 70) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: print("\n\n๐Ÿ‘‹ Demo stopped by user. Thanks for trying Crawl4AI v0.7.7!") except Exception as e: print(f"\n\nโŒ Demo failed: {e}") print("Make sure the Docker container is running:") print(" docker run -d -p 11235:11235 --shm-size=1g unclecode/crawl4ai:0.7.7")
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/releases_review/demo_v0.7.7.py", "license": "Apache License 2.0", "lines": 505, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:tests/test_llm_extraction_parallel_issue_1055.py
""" Final verification test for Issue #1055 fix This test demonstrates that LLM extraction now runs in parallel when using arun_many with multiple URLs. """ import os import sys import time import asyncio grandparent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(grandparent_dir) from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode, LLMExtractionStrategy, LLMConfig, ) from pydantic import BaseModel class SimpleData(BaseModel): title: str summary: str def print_section(title): print("\n" + "=" * 80) print(title) print("=" * 80 + "\n") async def test_without_llm(): """Baseline: Test crawling without LLM extraction""" print_section("TEST 1: Crawling WITHOUT LLM Extraction") config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, ) browser_config = BrowserConfig(headless=True, verbose=False) urls = [ "https://www.example.com", "https://www.iana.org", "https://www.wikipedia.org", ] print(f"Crawling {len(urls)} URLs without LLM extraction...") print("Expected: Fast and parallel\n") start_time = time.time() async with AsyncWebCrawler(config=browser_config) as crawler: results = await crawler.arun_many(urls=urls, config=config) duration = time.time() - start_time print(f"\nโœ… Completed in {duration:.2f}s") print(f" Successful: {sum(1 for r in results if r.success)}/{len(urls)}") print(f" Average: {duration/len(urls):.2f}s per URL") return duration async def test_with_llm_before_fix(): """Demonstrate the problem: Sequential execution with LLM""" print_section("TEST 2: What Issue #1055 Reported (LLM Sequential Behavior)") print("The issue reported that with LLM extraction, URLs would crawl") print("one after another instead of in parallel.") print("\nWithout our fix, this would show:") print(" - URL 1 fetches โ†’ extracts โ†’ completes") print(" - URL 2 fetches โ†’ extracts โ†’ completes") print(" - URL 3 fetches โ†’ extracts โ†’ completes") print("\nTotal time would be approximately sum of all individual times.") async def test_with_llm_after_fix(): """Demonstrate the fix: Parallel execution with LLM""" print_section("TEST 3: After Fix - LLM Extraction in Parallel") config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, extraction_strategy=LLMExtractionStrategy( llm_config=LLMConfig(provider="openai/gpt-4o-mini"), schema=SimpleData.model_json_schema(), extraction_type="schema", instruction="Extract title and summary", ) ) browser_config = BrowserConfig(headless=True, verbose=False) urls = [ "https://www.example.com", "https://www.iana.org", "https://www.wikipedia.org", ] print(f"Crawling {len(urls)} URLs WITH LLM extraction...") print("Expected: Parallel execution with our fix\n") completion_times = {} start_time = time.time() async with AsyncWebCrawler(config=browser_config) as crawler: results = await crawler.arun_many(urls=urls, config=config) for result in results: elapsed = time.time() - start_time completion_times[result.url] = elapsed print(f" [{elapsed:5.2f}s] โœ“ {result.url[:50]}") duration = time.time() - start_time print(f"\nโœ… Total time: {duration:.2f}s") print(f" Successful: {sum(1 for url in urls if url in completion_times)}/{len(urls)}") # Analyze parallelism times = list(completion_times.values()) if len(times) >= 2: # If parallel, completion times should be staggered, not evenly spaced time_diffs = [times[i+1] - times[i] for i in range(len(times)-1)] avg_diff = sum(time_diffs) / len(time_diffs) print(f"\nParallelism Analysis:") print(f" Completion time differences: {[f'{d:.2f}s' for d in time_diffs]}") print(f" Average difference: {avg_diff:.2f}s") # In parallel mode, some tasks complete close together # In sequential mode, they're evenly spaced (avg ~2-3s apart) if avg_diff < duration / len(urls): print(f" โœ… PARALLEL: Tasks completed with overlapping execution") else: print(f" โš ๏ธ SEQUENTIAL: Tasks completed one after another") return duration async def test_multiple_arun_calls(): """Test multiple individual arun() calls in parallel""" print_section("TEST 4: Multiple arun() Calls with asyncio.gather") config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, extraction_strategy=LLMExtractionStrategy( llm_config=LLMConfig(provider="openai/gpt-4o-mini"), schema=SimpleData.model_json_schema(), extraction_type="schema", instruction="Extract title and summary", ) ) browser_config = BrowserConfig(headless=True, verbose=False) urls = [ "https://www.example.com", "https://www.iana.org", "https://www.wikipedia.org", ] print(f"Running {len(urls)} arun() calls with asyncio.gather()...") print("Expected: True parallel execution\n") start_time = time.time() async with AsyncWebCrawler(config=browser_config) as crawler: tasks = [crawler.arun(url, config=config) for url in urls] results = await asyncio.gather(*tasks) duration = time.time() - start_time print(f"\nโœ… Completed in {duration:.2f}s") print(f" Successful: {sum(1 for r in results if r.success)}/{len(urls)}") print(f" This proves the async LLM extraction works correctly") return duration async def main(): print("\n" + "๐Ÿš€" * 40) print("ISSUE #1055 FIX VERIFICATION") print("Testing: Sequential โ†’ Parallel LLM Extraction") print("๐Ÿš€" * 40) # Run tests await test_without_llm() await test_with_llm_before_fix() time_with_llm = await test_with_llm_after_fix() time_gather = await test_multiple_arun_calls() # Final summary print_section("FINAL VERDICT") print("โœ… Fix Verified!") print("\nWhat changed:") print(" โ€ข Created aperform_completion_with_backoff() using litellm.acompletion") print(" โ€ข Added arun() method to ExtractionStrategy base class") print(" โ€ข Implemented parallel arun() in LLMExtractionStrategy") print(" โ€ข Updated AsyncWebCrawler to use arun() when available") print("\nResult:") print(" โ€ข LLM extraction now runs in parallel across multiple URLs") print(" โ€ข Backward compatible - existing strategies still work") print(" โ€ข No breaking changes to the API") print("\nโœจ Issue #1055 is RESOLVED!") print("\n" + "=" * 80 + "\n") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_llm_extraction_parallel_issue_1055.py", "license": "Apache License 2.0", "lines": 161, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_pyopenssl_security_fix.py
""" Lightweight test to verify pyOpenSSL security fix (Issue #1545). This test verifies the security requirements are met: 1. pyOpenSSL >= 25.3.0 is installed 2. cryptography >= 45.0.7 is installed (above vulnerable range) 3. SSL/TLS functionality works correctly This test can run without full crawl4ai dependencies installed. """ import sys from packaging import version def test_package_versions(): """Test that package versions meet security requirements.""" print("=" * 70) print("TEST: Package Version Security Requirements (Issue #1545)") print("=" * 70) all_passed = True # Test pyOpenSSL version try: import OpenSSL pyopenssl_version = OpenSSL.__version__ print(f"\nโœ“ pyOpenSSL is installed: {pyopenssl_version}") if version.parse(pyopenssl_version) >= version.parse("25.3.0"): print(f" โœ“ PASS: pyOpenSSL {pyopenssl_version} >= 25.3.0 (required)") else: print(f" โœ— FAIL: pyOpenSSL {pyopenssl_version} < 25.3.0 (required)") all_passed = False except ImportError as e: print(f"\nโœ— FAIL: pyOpenSSL not installed - {e}") all_passed = False # Test cryptography version try: import cryptography crypto_version = cryptography.__version__ print(f"\nโœ“ cryptography is installed: {crypto_version}") # The vulnerable range is >=37.0.0 & <43.0.1 # We need >= 45.0.7 to be safe if version.parse(crypto_version) >= version.parse("45.0.7"): print(f" โœ“ PASS: cryptography {crypto_version} >= 45.0.7 (secure)") print(f" โœ“ NOT in vulnerable range (37.0.0 to 43.0.0)") elif version.parse(crypto_version) >= version.parse("37.0.0") and version.parse(crypto_version) < version.parse("43.0.1"): print(f" โœ— FAIL: cryptography {crypto_version} is VULNERABLE") print(f" โœ— Version is in vulnerable range (>=37.0.0 & <43.0.1)") all_passed = False else: print(f" โš  WARNING: cryptography {crypto_version} < 45.0.7") print(f" โš  May not meet security requirements") except ImportError as e: print(f"\nโœ— FAIL: cryptography not installed - {e}") all_passed = False return all_passed def test_ssl_basic_functionality(): """Test that SSL/TLS basic functionality works.""" print("\n" + "=" * 70) print("TEST: SSL/TLS Basic Functionality") print("=" * 70) try: import OpenSSL.SSL # Create a basic SSL context to verify functionality context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) print("\nโœ“ SSL Context created successfully") print(" โœ“ PASS: SSL/TLS functionality is working") return True except Exception as e: print(f"\nโœ— FAIL: SSL functionality test failed - {e}") return False def test_pyopenssl_crypto_integration(): """Test that pyOpenSSL and cryptography integration works.""" print("\n" + "=" * 70) print("TEST: pyOpenSSL <-> cryptography Integration") print("=" * 70) try: from OpenSSL import crypto # Generate a simple key pair to test integration key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) print("\nโœ“ Generated RSA key pair successfully") print(" โœ“ PASS: pyOpenSSL and cryptography are properly integrated") return True except Exception as e: print(f"\nโœ— FAIL: Integration test failed - {e}") import traceback traceback.print_exc() return False def main(): """Run all security tests.""" print("\n") print("โ•”" + "=" * 68 + "โ•—") print("โ•‘ pyOpenSSL Security Fix Verification - Issue #1545 โ•‘") print("โ•š" + "=" * 68 + "โ•") print("\nVerifying that the pyOpenSSL update resolves the security vulnerability") print("in the cryptography package (CVE: versions >=37.0.0 & <43.0.1)\n") results = [] # Test 1: Package versions results.append(("Package Versions", test_package_versions())) # Test 2: SSL functionality results.append(("SSL Functionality", test_ssl_basic_functionality())) # Test 3: Integration results.append(("pyOpenSSL-crypto Integration", test_pyopenssl_crypto_integration())) # Summary print("\n" + "=" * 70) print("TEST SUMMARY") print("=" * 70) all_passed = True for test_name, passed in results: status = "โœ“ PASS" if passed else "โœ— FAIL" print(f"{status}: {test_name}") all_passed = all_passed and passed print("=" * 70) if all_passed: print("\nโœ“โœ“โœ“ ALL TESTS PASSED โœ“โœ“โœ“") print("โœ“ Security vulnerability is resolved") print("โœ“ pyOpenSSL >= 25.3.0 is working correctly") print("โœ“ cryptography >= 45.0.7 (not vulnerable)") print("\nThe dependency update is safe to merge.\n") return True else: print("\nโœ—โœ—โœ— SOME TESTS FAILED โœ—โœ—โœ—") print("โœ— Security requirements not met") print("\nDo NOT merge until all tests pass.\n") return False if __name__ == "__main__": try: success = main() sys.exit(0 if success else 1) except KeyboardInterrupt: print("\n\nTest interrupted by user") sys.exit(1) except Exception as e: print(f"\nโœ— Unexpected error: {e}") import traceback traceback.print_exc() sys.exit(1)
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_pyopenssl_security_fix.py", "license": "Apache License 2.0", "lines": 132, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_pyopenssl_update.py
""" Test script to verify pyOpenSSL update doesn't break crawl4ai functionality. This test verifies: 1. pyOpenSSL and cryptography versions are correct and secure 2. Basic crawling functionality still works 3. HTTPS/SSL connections work properly 4. Stealth mode integration works (uses playwright-stealth internally) Issue: #1545 - Security vulnerability in cryptography package Fix: Updated pyOpenSSL from >=24.3.0 to >=25.3.0 Expected: cryptography package should be >=45.0.7 (above vulnerable range) """ import asyncio import sys from packaging import version def check_versions(): """Verify pyOpenSSL and cryptography versions meet security requirements.""" print("=" * 60) print("STEP 1: Checking Package Versions") print("=" * 60) try: import OpenSSL pyopenssl_version = OpenSSL.__version__ print(f"โœ“ pyOpenSSL version: {pyopenssl_version}") # Check pyOpenSSL >= 25.3.0 if version.parse(pyopenssl_version) >= version.parse("25.3.0"): print(f" โœ“ Version check passed: {pyopenssl_version} >= 25.3.0") else: print(f" โœ— Version check FAILED: {pyopenssl_version} < 25.3.0") return False except ImportError as e: print(f"โœ— Failed to import pyOpenSSL: {e}") return False try: import cryptography crypto_version = cryptography.__version__ print(f"โœ“ cryptography version: {crypto_version}") # Check cryptography >= 45.0.7 (above vulnerable range) if version.parse(crypto_version) >= version.parse("45.0.7"): print(f" โœ“ Security check passed: {crypto_version} >= 45.0.7 (not vulnerable)") else: print(f" โœ— Security check FAILED: {crypto_version} < 45.0.7 (potentially vulnerable)") return False except ImportError as e: print(f"โœ— Failed to import cryptography: {e}") return False print("\nโœ“ All version checks passed!\n") return True async def test_basic_crawl(): """Test basic crawling functionality with HTTPS site.""" print("=" * 60) print("STEP 2: Testing Basic HTTPS Crawling") print("=" * 60) try: from crawl4ai import AsyncWebCrawler async with AsyncWebCrawler(verbose=True) as crawler: # Test with a simple HTTPS site (requires SSL/TLS) print("Crawling example.com (HTTPS)...") result = await crawler.arun( url="https://www.example.com", bypass_cache=True ) if result.success: print(f"โœ“ Crawl successful!") print(f" - Status code: {result.status_code}") print(f" - Content length: {len(result.html)} bytes") print(f" - SSL/TLS connection: โœ“ Working") return True else: print(f"โœ— Crawl failed: {result.error_message}") return False except Exception as e: print(f"โœ— Test failed with error: {e}") import traceback traceback.print_exc() return False async def test_stealth_mode(): """Test stealth mode functionality (depends on playwright-stealth).""" print("\n" + "=" * 60) print("STEP 3: Testing Stealth Mode Integration") print("=" * 60) try: from crawl4ai import AsyncWebCrawler, BrowserConfig # Create browser config with stealth mode browser_config = BrowserConfig( headless=True, verbose=False ) async with AsyncWebCrawler(config=browser_config, verbose=True) as crawler: print("Crawling with stealth mode enabled...") result = await crawler.arun( url="https://www.example.com", bypass_cache=True ) if result.success: print(f"โœ“ Stealth crawl successful!") print(f" - Stealth mode: โœ“ Working") return True else: print(f"โœ— Stealth crawl failed: {result.error_message}") return False except Exception as e: print(f"โœ— Stealth test failed with error: {e}") import traceback traceback.print_exc() return False async def main(): """Run all tests.""" print("\n") print("โ•”" + "=" * 58 + "โ•—") print("โ•‘ pyOpenSSL Security Update Verification Test (Issue #1545) โ•‘") print("โ•š" + "=" * 58 + "โ•") print("\n") # Step 1: Check versions versions_ok = check_versions() if not versions_ok: print("\nโœ— FAILED: Version requirements not met") return False # Step 2: Test basic crawling crawl_ok = await test_basic_crawl() if not crawl_ok: print("\nโœ— FAILED: Basic crawling test failed") return False # Step 3: Test stealth mode stealth_ok = await test_stealth_mode() if not stealth_ok: print("\nโœ— FAILED: Stealth mode test failed") return False # All tests passed print("\n" + "=" * 60) print("FINAL RESULT") print("=" * 60) print("โœ“ All tests passed successfully!") print("โœ“ pyOpenSSL update is working correctly") print("โœ“ No breaking changes detected") print("โœ“ Security vulnerability resolved") print("=" * 60) print("\n") return True if __name__ == "__main__": try: success = asyncio.run(main()) sys.exit(0 if success else 1) except KeyboardInterrupt: print("\n\nTest interrupted by user") sys.exit(1) except Exception as e: print(f"\nโœ— Unexpected error: {e}") import traceback traceback.print_exc() sys.exit(1)
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_pyopenssl_update.py", "license": "Apache License 2.0", "lines": 150, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/unit/test_sitemap_namespace_parsing.py
import sys from types import SimpleNamespace import pytest # Provide a lightweight stub for rank_bm25 before importing the seeder to avoid # optional dependency issues (e.g., incompatible wheels in CI). class _FakeBM25: def __init__(self, corpus): self._scores = [1.0] * len(corpus) def get_scores(self, tokens): return self._scores sys.modules.setdefault("rank_bm25", SimpleNamespace(BM25Okapi=_FakeBM25)) from crawl4ai.async_url_seeder import AsyncUrlSeeder class DummyResponse: def __init__(self, request_url: str, text: str): self.status_code = 200 self._content = text.encode("utf-8") self.url = request_url def raise_for_status(self): return None @property def content(self): return self._content @property def text(self): return self._content.decode("utf-8") class DummyAsyncClient: def __init__(self, response_map): self._responses = response_map async def get(self, url, **kwargs): payload = self._responses[url] if callable(payload): payload = payload() return DummyResponse(url, payload) @pytest.mark.asyncio async def test_iter_sitemap_handles_namespace_less_sitemaps(): xml = """<?xml version="1.0"?> <urlset> <url><loc>https://example.com/a</loc></url> <url><loc>https://example.com/b</loc></url> </urlset> """ seeder = AsyncUrlSeeder(client=DummyAsyncClient({"https://example.com/sitemap.xml": xml})) urls = [] async for u in seeder._iter_sitemap("https://example.com/sitemap.xml"): urls.append(u) assert urls == ["https://example.com/a", "https://example.com/b"] @pytest.mark.asyncio async def test_iter_sitemap_handles_custom_namespace(): xml = """<?xml version="1.0"?> <urlset xmlns="https://custom.namespace/schema"> <url><loc>https://example.com/ns</loc></url> </urlset> """ seeder = AsyncUrlSeeder(client=DummyAsyncClient({"https://example.com/ns-sitemap.xml": xml})) urls = [] async for u in seeder._iter_sitemap("https://example.com/ns-sitemap.xml"): urls.append(u) assert urls == ["https://example.com/ns"] @pytest.mark.asyncio async def test_iter_sitemap_handles_namespace_index_and_children(): index_xml = """<?xml version="1.0"?> <sitemapindex xmlns="http://another.example/ns"> <sitemap> <loc>https://example.com/child-1.xml</loc> </sitemap> <sitemap> <loc>https://example.com/child-2.xml</loc> </sitemap> </sitemapindex> """ child_xml = """<?xml version="1.0"?> <urlset xmlns="http://irrelevant"> <url><loc>https://example.com/page-{n}</loc></url> </urlset> """ responses = { "https://example.com/index.xml": index_xml, "https://example.com/child-1.xml": child_xml.format(n=1), "https://example.com/child-2.xml": child_xml.format(n=2), } seeder = AsyncUrlSeeder(client=DummyAsyncClient(responses)) urls = [] async for u in seeder._iter_sitemap("https://example.com/index.xml"): urls.append(u) assert sorted(urls) == [ "https://example.com/page-1", "https://example.com/page-2", ] @pytest.mark.asyncio async def test_iter_sitemap_normalizes_relative_locations(): xml = """<?xml version="1.0"?> <urlset> <url><loc>/relative-path</loc></url> <url><loc>https://example.com/absolute</loc></url> </urlset> """ seeder = AsyncUrlSeeder(client=DummyAsyncClient({"https://example.com/sitemap.xml": xml})) urls = [] async for u in seeder._iter_sitemap("https://example.com/sitemap.xml"): urls.append(u) assert urls == [ "https://example.com/relative-path", "https://example.com/absolute", ]
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/unit/test_sitemap_namespace_parsing.py", "license": "Apache License 2.0", "lines": 104, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_aws_waf.py
import asyncio import capsolver from crawl4ai import * # TODO: set your config # Docs: https://docs.capsolver.com/guide/captcha/awsWaf/ api_key = "CAP-xxxxxxxxxxxxxxxxxxxxx" # your api key of capsolver site_url = "https://nft.porsche.com/onboarding@6" # page url of your target site cookie_domain = ".nft.porsche.com" # the domain name to which you want to apply the cookie captcha_type = "AntiAwsWafTaskProxyLess" # type of your target captcha capsolver.api_key = api_key async def main(): browser_config = BrowserConfig( verbose=True, headless=False, use_persistent_context=True, ) async with AsyncWebCrawler(config=browser_config) as crawler: await crawler.arun( url=site_url, cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) # get aws waf cookie using capsolver sdk solution = capsolver.solve({ "type": captcha_type, "websiteURL": site_url, }) cookie = solution["cookie"] print("aws waf cookie:", cookie) js_code = """ document.cookie = \'aws-waf-token=""" + cookie + """;domain=""" + cookie_domain + """;path=/\'; location.reload(); """ wait_condition = """() => { return document.title === \'Join Porscheโ€™s journey into Web3\'; }""" run_config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, session_id="session_captcha_test", js_code=js_code, js_only=True, wait_for=f"js:{wait_condition}" ) result_next = await crawler.arun( url=site_url, config=run_config, ) print(result_next.markdown) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_aws_waf.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_cloudflare_challenge.py
import asyncio import capsolver from crawl4ai import * # TODO: set your config # Docs: https://docs.capsolver.com/guide/captcha/cloudflare_challenge/ api_key = "CAP-xxxxxxxxxxxxxxxxxxxxx" # your api key of capsolver site_url = "https://gitlab.com/users/sign_in" # page url of your target site captcha_type = "AntiCloudflareTask" # type of your target captcha # your http proxy to solve cloudflare challenge proxy_server = "proxy.example.com:8080" proxy_username = "myuser" proxy_password = "mypass" capsolver.api_key = api_key async def main(): # get challenge cookie using capsolver sdk solution = capsolver.solve({ "type": captcha_type, "websiteURL": site_url, "proxy": f"{proxy_server}:{proxy_username}:{proxy_password}", }) cookies = solution["cookies"] user_agent = solution["userAgent"] print("challenge cookies:", cookies) cookies_list = [] for name, value in cookies.items(): cookies_list.append({ "name": name, "value": value, "url": site_url, }) browser_config = BrowserConfig( verbose=True, headless=False, use_persistent_context=True, user_agent=user_agent, cookies=cookies_list, proxy_config={ "server": f"http://{proxy_server}", "username": proxy_username, "password": proxy_password, }, ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun( url=site_url, cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) print(result.markdown) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_cloudflare_challenge.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_cloudflare_turnstile.py
import asyncio import capsolver from crawl4ai import * # TODO: set your config # Docs: https://docs.capsolver.com/guide/captcha/cloudflare_turnstile/ api_key = "CAP-xxxxxxxxxxxxxxxxxxxxx" # your api key of capsolver site_key = "0x4AAAAAAAGlwMzq_9z6S9Mh" # site key of your target site site_url = "https://clifford.io/demo/cloudflare-turnstile" # page url of your target site captcha_type = "AntiTurnstileTaskProxyLess" # type of your target captcha capsolver.api_key = api_key async def main(): browser_config = BrowserConfig( verbose=True, headless=False, use_persistent_context=True, ) async with AsyncWebCrawler(config=browser_config) as crawler: await crawler.arun( url=site_url, cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) # get turnstile token using capsolver sdk solution = capsolver.solve({ "type": captcha_type, "websiteURL": site_url, "websiteKey": site_key, }) token = solution["token"] print("turnstile token:", token) js_code = """ document.querySelector(\'input[name="cf-turnstile-response"]\').value = \'"""+token+"""\'; document.querySelector(\'button[type="submit"]\').click(); """ wait_condition = """() => { const items = document.querySelectorAll(\'h1\'); return items.length === 0; }""" run_config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, session_id="session_captcha_test", js_code=js_code, js_only=True, wait_for=f"js:{wait_condition}" ) result_next = await crawler.arun( url=site_url, config=run_config, ) print(result_next.markdown) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_cloudflare_turnstile.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_recaptcha_v2.py
import asyncio import capsolver from crawl4ai import * # TODO: set your config # Docs: https://docs.capsolver.com/guide/captcha/ReCaptchaV2/ api_key = "CAP-xxxxxxxxxxxxxxxxxxxxx" # your api key of capsolver site_key = "6LfW6wATAAAAAHLqO2pb8bDBahxlMxNdo9g947u9" # site key of your target site site_url = "https://recaptcha-demo.appspot.com/recaptcha-v2-checkbox.php" # page url of your target site captcha_type = "ReCaptchaV2TaskProxyLess" # type of your target captcha capsolver.api_key = api_key async def main(): browser_config = BrowserConfig( verbose=True, headless=False, use_persistent_context=True, ) async with AsyncWebCrawler(config=browser_config) as crawler: await crawler.arun( url=site_url, cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) # get recaptcha token using capsolver sdk solution = capsolver.solve({ "type": captcha_type, "websiteURL": site_url, "websiteKey": site_key, }) token = solution["gRecaptchaResponse"] print("recaptcha token:", token) js_code = """ const textarea = document.getElementById(\'g-recaptcha-response\'); if (textarea) { textarea.value = \"""" + token + """\"; document.querySelector(\'button.form-field[type="submit"]\').click(); } """ wait_condition = """() => { const items = document.querySelectorAll(\'h2\'); return items.length > 1; }""" run_config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, session_id="session_captcha_test", js_code=js_code, js_only=True, wait_for=f"js:{wait_condition}" ) result_next = await crawler.arun( url=site_url, config=run_config, ) print(result_next.markdown) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_recaptcha_v2.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_recaptcha_v3.py
import asyncio import capsolver from crawl4ai import * # TODO: set your config # Docs: https://docs.capsolver.com/guide/captcha/ReCaptchaV3/ api_key = "CAP-xxxxxxxxxxxxxxxxxxxxx" # your api key of capsolver site_key = "6LdKlZEpAAAAAAOQjzC2v_d36tWxCl6dWsozdSy9" # site key of your target site site_url = "https://recaptcha-demo.appspot.com/recaptcha-v3-request-scores.php" # page url of your target site page_action = "examples/v3scores" # page action of your target site captcha_type = "ReCaptchaV3TaskProxyLess" # type of your target captcha capsolver.api_key = api_key async def main(): browser_config = BrowserConfig( verbose=True, headless=False, use_persistent_context=True, ) # get recaptcha token using capsolver sdk solution = capsolver.solve({ "type": captcha_type, "websiteURL": site_url, "websiteKey": site_key, "pageAction": page_action, }) token = solution["gRecaptchaResponse"] print("recaptcha token:", token) async with AsyncWebCrawler(config=browser_config) as crawler: await crawler.arun( url=site_url, cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) js_code = """ const originalFetch = window.fetch; window.fetch = function(...args) { if (typeof args[0] === 'string' && args[0].includes('/recaptcha-v3-verify.php')) { const url = new URL(args[0], window.location.origin); url.searchParams.set('action', '""" + token + """'); args[0] = url.toString(); document.querySelector('.token').innerHTML = "fetch('/recaptcha-v3-verify.php?action=examples/v3scores&token=""" + token + """')"; console.log('Fetch URL hooked:', args[0]); } return originalFetch.apply(this, args); }; """ wait_condition = """() => { return document.querySelector('.step3:not(.hidden)'); }""" run_config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, session_id="session_captcha_test", js_code=js_code, js_only=True, wait_for=f"js:{wait_condition}" ) result_next = await crawler.arun( url=site_url, config=run_config, ) print(result_next.markdown) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_api_integration/solve_recaptcha_v3.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_aws_waf.py
import time import asyncio from crawl4ai import * # TODO: the user data directory that includes the capsolver extension user_data_dir = "/browser-profile/Default1" """ The capsolver extension supports more features, such as: - Telling the extension when to start solving captcha. - Calling functions to check whether the captcha has been solved, etc. Reference blog: https://docs.capsolver.com/guide/automation-tool-integration/ """ browser_config = BrowserConfig( verbose=True, headless=False, user_data_dir=user_data_dir, use_persistent_context=True, ) async def main(): async with AsyncWebCrawler(config=browser_config) as crawler: result_initial = await crawler.arun( url="https://nft.porsche.com/onboarding@6", cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) # do something later time.sleep(300) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_aws_waf.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_cloudflare_challenge.py
import time import asyncio from crawl4ai import * # TODO: the user data directory that includes the capsolver extension user_data_dir = "/browser-profile/Default1" """ The capsolver extension supports more features, such as: - Telling the extension when to start solving captcha. - Calling functions to check whether the captcha has been solved, etc. Reference blog: https://docs.capsolver.com/guide/automation-tool-integration/ """ browser_config = BrowserConfig( verbose=True, headless=False, user_data_dir=user_data_dir, use_persistent_context=True, ) async def main(): async with AsyncWebCrawler(config=browser_config) as crawler: result_initial = await crawler.arun( url="https://gitlab.com/users/sign_in", cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) # do something later time.sleep(300) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_cloudflare_challenge.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_cloudflare_turnstile.py
import time import asyncio from crawl4ai import * # TODO: the user data directory that includes the capsolver extension user_data_dir = "/browser-profile/Default1" """ The capsolver extension supports more features, such as: - Telling the extension when to start solving captcha. - Calling functions to check whether the captcha has been solved, etc. Reference blog: https://docs.capsolver.com/guide/automation-tool-integration/ """ browser_config = BrowserConfig( verbose=True, headless=False, user_data_dir=user_data_dir, use_persistent_context=True, ) async def main(): async with AsyncWebCrawler(config=browser_config) as crawler: result_initial = await crawler.arun( url="https://clifford.io/demo/cloudflare-turnstile", cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) # do something later time.sleep(300) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_cloudflare_turnstile.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_recaptcha_v2.py
import time import asyncio from crawl4ai import * # TODO: the user data directory that includes the capsolver extension user_data_dir = "/browser-profile/Default1" """ The capsolver extension supports more features, such as: - Telling the extension when to start solving captcha. - Calling functions to check whether the captcha has been solved, etc. Reference blog: https://docs.capsolver.com/guide/automation-tool-integration/ """ browser_config = BrowserConfig( verbose=True, headless=False, user_data_dir=user_data_dir, use_persistent_context=True, ) async def main(): async with AsyncWebCrawler(config=browser_config) as crawler: result_initial = await crawler.arun( url="https://recaptcha-demo.appspot.com/recaptcha-v2-checkbox.php", cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) # do something later time.sleep(300) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_recaptcha_v2.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_recaptcha_v3.py
import time import asyncio from crawl4ai import * # TODO: the user data directory that includes the capsolver extension user_data_dir = "/browser-profile/Default1" """ The capsolver extension supports more features, such as: - Telling the extension when to start solving captcha. - Calling functions to check whether the captcha has been solved, etc. Reference blog: https://docs.capsolver.com/guide/automation-tool-integration/ """ browser_config = BrowserConfig( verbose=True, headless=False, user_data_dir=user_data_dir, use_persistent_context=True, ) async def main(): async with AsyncWebCrawler(config=browser_config) as crawler: result_initial = await crawler.arun( url="https://recaptcha-demo.appspot.com/recaptcha-v3-request-scores.php", cache_mode=CacheMode.BYPASS, session_id="session_captcha_test" ) # do something later time.sleep(300) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/capsolver_captcha_solver/capsolver_extension_integration/solve_recaptcha_v3.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/releases_review/demo_v0.7.6.py
#!/usr/bin/env python3 """ Crawl4AI v0.7.6 Release Demo ============================ This demo showcases the major feature in v0.7.6: **Webhook Support for Docker Job Queue API** Features Demonstrated: 1. Asynchronous job processing with webhook notifications 2. Webhook support for /crawl/job endpoint 3. Webhook support for /llm/job endpoint 4. Notification-only vs data-in-payload modes 5. Custom webhook headers for authentication 6. Structured extraction with JSON schemas 7. Exponential backoff retry for reliable delivery Prerequisites: - Crawl4AI Docker container running on localhost:11235 - Flask installed: pip install flask requests - LLM API key configured (for LLM examples) Usage: python docs/releases_review/demo_v0.7.6.py """ import requests import json import time from flask import Flask, request, jsonify from threading import Thread # Configuration CRAWL4AI_BASE_URL = "http://localhost:11235" WEBHOOK_BASE_URL = "http://localhost:8080" # Flask app for webhook receiver app = Flask(__name__) received_webhooks = [] @app.route('/webhook', methods=['POST']) def webhook_handler(): """Universal webhook handler for both crawl and LLM extraction jobs.""" payload = request.json task_id = payload['task_id'] task_type = payload['task_type'] status = payload['status'] print(f"\n{'='*70}") print(f"๐Ÿ“ฌ Webhook Received!") print(f" Task ID: {task_id}") print(f" Task Type: {task_type}") print(f" Status: {status}") print(f" Timestamp: {payload['timestamp']}") if status == 'completed': if 'data' in payload: print(f" โœ… Data included in webhook") if task_type == 'crawl': results = payload['data'].get('results', []) print(f" ๐Ÿ“Š Crawled {len(results)} URL(s)") elif task_type == 'llm_extraction': extracted = payload['data'].get('extracted_content', {}) print(f" ๐Ÿค– Extracted: {json.dumps(extracted, indent=6)}") else: print(f" ๐Ÿ“ฅ Notification only (fetch data separately)") elif status == 'failed': print(f" โŒ Error: {payload.get('error', 'Unknown')}") print(f"{'='*70}\n") received_webhooks.append(payload) return jsonify({"status": "received"}), 200 def start_webhook_server(): """Start Flask webhook server in background.""" app.run(host='0.0.0.0', port=8080, debug=False, use_reloader=False) def demo_1_crawl_webhook_notification_only(): """Demo 1: Crawl job with webhook notification (data fetched separately).""" print("\n" + "="*70) print("DEMO 1: Crawl Job - Webhook Notification Only") print("="*70) print("Submitting crawl job with webhook notification...") payload = { "urls": ["https://example.com"], "browser_config": {"headless": True}, "crawler_config": {"cache_mode": "bypass"}, "webhook_config": { "webhook_url": f"{WEBHOOK_BASE_URL}/webhook", "webhook_data_in_payload": False, "webhook_headers": { "X-Demo": "v0.7.6", "X-Type": "crawl" } } } response = requests.post(f"{CRAWL4AI_BASE_URL}/crawl/job", json=payload) if response.ok: task_id = response.json()['task_id'] print(f"โœ… Job submitted: {task_id}") print("โณ Webhook will notify when complete...") return task_id else: print(f"โŒ Failed: {response.text}") return None def demo_2_crawl_webhook_with_data(): """Demo 2: Crawl job with full data in webhook payload.""" print("\n" + "="*70) print("DEMO 2: Crawl Job - Webhook with Full Data") print("="*70) print("Submitting crawl job with data included in webhook...") payload = { "urls": ["https://www.python.org"], "browser_config": {"headless": True}, "crawler_config": {"cache_mode": "bypass"}, "webhook_config": { "webhook_url": f"{WEBHOOK_BASE_URL}/webhook", "webhook_data_in_payload": True, "webhook_headers": { "X-Demo": "v0.7.6", "X-Type": "crawl-with-data" } } } response = requests.post(f"{CRAWL4AI_BASE_URL}/crawl/job", json=payload) if response.ok: task_id = response.json()['task_id'] print(f"โœ… Job submitted: {task_id}") print("โณ Webhook will include full results...") return task_id else: print(f"โŒ Failed: {response.text}") return None def demo_3_llm_webhook_notification_only(): """Demo 3: LLM extraction with webhook notification (NEW in v0.7.6!).""" print("\n" + "="*70) print("DEMO 3: LLM Extraction - Webhook Notification Only (NEW!)") print("="*70) print("Submitting LLM extraction job with webhook notification...") payload = { "url": "https://www.example.com", "q": "Extract the main heading and description from this page", "provider": "openai/gpt-4o-mini", "cache": False, "webhook_config": { "webhook_url": f"{WEBHOOK_BASE_URL}/webhook", "webhook_data_in_payload": False, "webhook_headers": { "X-Demo": "v0.7.6", "X-Type": "llm" } } } response = requests.post(f"{CRAWL4AI_BASE_URL}/llm/job", json=payload) if response.ok: task_id = response.json()['task_id'] print(f"โœ… Job submitted: {task_id}") print("โณ Webhook will notify when LLM extraction completes...") return task_id else: print(f"โŒ Failed: {response.text}") return None def demo_4_llm_webhook_with_schema(): """Demo 4: LLM extraction with JSON schema and data in webhook (NEW in v0.7.6!).""" print("\n" + "="*70) print("DEMO 4: LLM Extraction - Schema + Full Data in Webhook (NEW!)") print("="*70) print("Submitting LLM extraction with JSON schema...") schema = { "type": "object", "properties": { "title": {"type": "string", "description": "Page title"}, "description": {"type": "string", "description": "Page description"}, "main_topics": { "type": "array", "items": {"type": "string"}, "description": "Main topics covered" } }, "required": ["title"] } payload = { "url": "https://www.python.org", "q": "Extract the title, description, and main topics from this website", "schema": json.dumps(schema), "provider": "openai/gpt-4o-mini", "cache": False, "webhook_config": { "webhook_url": f"{WEBHOOK_BASE_URL}/webhook", "webhook_data_in_payload": True, "webhook_headers": { "X-Demo": "v0.7.6", "X-Type": "llm-with-schema" } } } response = requests.post(f"{CRAWL4AI_BASE_URL}/llm/job", json=payload) if response.ok: task_id = response.json()['task_id'] print(f"โœ… Job submitted: {task_id}") print("โณ Webhook will include structured extraction results...") return task_id else: print(f"โŒ Failed: {response.text}") return None def demo_5_global_webhook_config(): """Demo 5: Using global webhook configuration from config.yml.""" print("\n" + "="*70) print("DEMO 5: Global Webhook Configuration") print("="*70) print("๐Ÿ’ก You can configure a default webhook URL in config.yml:") print(""" webhooks: enabled: true default_url: "https://myapp.com/webhooks/default" data_in_payload: false retry: max_attempts: 5 initial_delay_ms: 1000 max_delay_ms: 32000 timeout_ms: 30000 """) print("Then submit jobs WITHOUT webhook_config - they'll use the default!") print("This is useful for consistent webhook handling across all jobs.") def demo_6_webhook_retry_logic(): """Demo 6: Webhook retry mechanism with exponential backoff.""" print("\n" + "="*70) print("DEMO 6: Webhook Retry Logic") print("="*70) print("๐Ÿ”„ Webhook delivery uses exponential backoff retry:") print(" โ€ข Max attempts: 5") print(" โ€ข Delays: 1s โ†’ 2s โ†’ 4s โ†’ 8s โ†’ 16s") print(" โ€ข Timeout: 30s per attempt") print(" โ€ข Retries on: 5xx errors, network errors, timeouts") print(" โ€ข No retry on: 4xx client errors") print("\nThis ensures reliable webhook delivery even with temporary failures!") def print_summary(): """Print demo summary and results.""" print("\n" + "="*70) print("๐Ÿ“Š DEMO SUMMARY") print("="*70) print(f"Total webhooks received: {len(received_webhooks)}") crawl_webhooks = [w for w in received_webhooks if w['task_type'] == 'crawl'] llm_webhooks = [w for w in received_webhooks if w['task_type'] == 'llm_extraction'] print(f"\nBreakdown:") print(f" ๐Ÿ•ท๏ธ Crawl jobs: {len(crawl_webhooks)}") print(f" ๐Ÿค– LLM extraction jobs: {len(llm_webhooks)}") print(f"\nDetails:") for i, webhook in enumerate(received_webhooks, 1): icon = "๐Ÿ•ท๏ธ" if webhook['task_type'] == 'crawl' else "๐Ÿค–" print(f" {i}. {icon} {webhook['task_id']}: {webhook['status']}") print("\n" + "="*70) print("โœจ v0.7.6 KEY FEATURES DEMONSTRATED:") print("="*70) print("โœ… Webhook support for /crawl/job") print("โœ… Webhook support for /llm/job (NEW!)") print("โœ… Notification-only mode (fetch data separately)") print("โœ… Data-in-payload mode (get full results in webhook)") print("โœ… Custom headers for authentication") print("โœ… JSON schema for structured LLM extraction") print("โœ… Exponential backoff retry for reliable delivery") print("โœ… Global webhook configuration support") print("โœ… Universal webhook handler for both job types") print("\n๐Ÿ’ก Benefits:") print(" โ€ข No more polling - get instant notifications") print(" โ€ข Better resource utilization") print(" โ€ข Reliable delivery with automatic retries") print(" โ€ข Consistent API across crawl and LLM jobs") print(" โ€ข Production-ready webhook infrastructure") def main(): """Run all demos.""" print("\n" + "="*70) print("๐Ÿš€ Crawl4AI v0.7.6 Release Demo") print("="*70) print("Feature: Webhook Support for Docker Job Queue API") print("="*70) # Check if server is running try: health = requests.get(f"{CRAWL4AI_BASE_URL}/health", timeout=5) print(f"โœ… Crawl4AI server is running") except: print(f"โŒ Cannot connect to Crawl4AI at {CRAWL4AI_BASE_URL}") print("Please start Docker container:") print(" docker run -d -p 11235:11235 --env-file .llm.env unclecode/crawl4ai:0.7.6") return # Start webhook server print(f"\n๐ŸŒ Starting webhook server at {WEBHOOK_BASE_URL}...") webhook_thread = Thread(target=start_webhook_server, daemon=True) webhook_thread.start() time.sleep(2) # Run demos demo_1_crawl_webhook_notification_only() time.sleep(5) demo_2_crawl_webhook_with_data() time.sleep(5) demo_3_llm_webhook_notification_only() time.sleep(5) demo_4_llm_webhook_with_schema() time.sleep(5) demo_5_global_webhook_config() demo_6_webhook_retry_logic() # Wait for webhooks print("\nโณ Waiting for all webhooks to arrive...") time.sleep(30) # Print summary print_summary() print("\n" + "="*70) print("โœ… Demo completed!") print("="*70) print("\n๐Ÿ“š Documentation:") print(" โ€ข deploy/docker/WEBHOOK_EXAMPLES.md") print(" โ€ข docs/examples/docker_webhook_example.py") print("\n๐Ÿ”— Upgrade:") print(" docker pull unclecode/crawl4ai:0.7.6") if __name__ == "__main__": main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/releases_review/demo_v0.7.6.py", "license": "Apache License 2.0", "lines": 303, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:deploy/docker/hook_manager.py
""" Hook Manager for User-Provided Hook Functions Handles validation, compilation, and safe execution of user-provided hook code """ import ast import asyncio import traceback from typing import Dict, Callable, Optional, Tuple, List, Any import logging logger = logging.getLogger(__name__) class UserHookManager: """Manages user-provided hook functions with error isolation""" # Expected signatures for each hook point HOOK_SIGNATURES = { "on_browser_created": ["browser"], "on_page_context_created": ["page", "context"], "before_goto": ["page", "context", "url"], "after_goto": ["page", "context", "url", "response"], "on_user_agent_updated": ["page", "context", "user_agent"], "on_execution_started": ["page", "context"], "before_retrieve_html": ["page", "context"], "before_return_html": ["page", "context", "html"] } # Default timeout for hook execution (in seconds) DEFAULT_TIMEOUT = 30 def __init__(self, timeout: int = DEFAULT_TIMEOUT): self.timeout = timeout self.errors: List[Dict[str, Any]] = [] self.compiled_hooks: Dict[str, Callable] = {} self.execution_log: List[Dict[str, Any]] = [] def validate_hook_structure(self, hook_code: str, hook_point: str) -> Tuple[bool, str]: """ Validate the structure of user-provided hook code Args: hook_code: The Python code string containing the hook function hook_point: The hook point name (e.g., 'on_page_context_created') Returns: Tuple of (is_valid, error_message) """ try: # Parse the code tree = ast.parse(hook_code) # Check if it's empty if not tree.body: return False, "Hook code is empty" # Find the function definition func_def = None for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): func_def = node break if not func_def: return False, "Hook must contain a function definition (def or async def)" # Check if it's async (all hooks should be async) if not isinstance(func_def, ast.AsyncFunctionDef): return False, f"Hook function must be async (use 'async def' instead of 'def')" # Get function name for better error messages func_name = func_def.name # Validate parameters expected_params = self.HOOK_SIGNATURES.get(hook_point, []) if not expected_params: return False, f"Unknown hook point: {hook_point}" func_params = [arg.arg for arg in func_def.args.args] # Check if it has **kwargs for flexibility has_kwargs = func_def.args.kwarg is not None # Must have at least the expected parameters missing_params = [] for expected in expected_params: if expected not in func_params: missing_params.append(expected) if missing_params and not has_kwargs: return False, f"Hook function '{func_name}' must accept parameters: {', '.join(expected_params)} (missing: {', '.join(missing_params)})" # Check if it returns something (should return page or browser) has_return = any(isinstance(node, ast.Return) for node in ast.walk(func_def)) if not has_return: # Warning, not error - we'll handle this logger.warning(f"Hook function '{func_name}' should return the {expected_params[0]} object") return True, "Valid" except SyntaxError as e: return False, f"Syntax error at line {e.lineno}: {str(e)}" except Exception as e: return False, f"Failed to parse hook code: {str(e)}" def compile_hook(self, hook_code: str, hook_point: str) -> Optional[Callable]: """ Compile user-provided hook code into a callable function Args: hook_code: The Python code string hook_point: The hook point name Returns: Compiled function or None if compilation failed """ try: # Create a safe namespace for the hook # SECURITY: No __import__ to prevent arbitrary module imports (RCE risk) import builtins safe_builtins = {} # Add safe built-in functions (no __import__ for security) allowed_builtins = [ 'print', 'len', 'str', 'int', 'float', 'bool', 'list', 'dict', 'set', 'tuple', 'range', 'enumerate', 'zip', 'map', 'filter', 'any', 'all', 'sum', 'min', 'max', 'sorted', 'reversed', 'abs', 'round', 'isinstance', 'type', 'getattr', 'hasattr', 'setattr', 'callable', 'iter', 'next', '__build_class__' # Required for class definitions in exec ] for name in allowed_builtins: if hasattr(builtins, name): safe_builtins[name] = getattr(builtins, name) namespace = { '__name__': f'user_hook_{hook_point}', '__builtins__': safe_builtins } # Add commonly needed imports exec("import asyncio", namespace) exec("import json", namespace) exec("import re", namespace) exec("from typing import Dict, List, Optional", namespace) # Execute the code to define the function exec(hook_code, namespace) # Find the async function in the namespace for name, obj in namespace.items(): if callable(obj) and not name.startswith('_') and asyncio.iscoroutinefunction(obj): return obj # If no async function found, look for any function for name, obj in namespace.items(): if callable(obj) and not name.startswith('_'): logger.warning(f"Found non-async function '{name}' - wrapping it") # Wrap sync function in async async def async_wrapper(*args, **kwargs): return obj(*args, **kwargs) return async_wrapper raise ValueError("No callable function found in hook code") except Exception as e: error = { 'hook_point': hook_point, 'error': f"Failed to compile hook: {str(e)}", 'type': 'compilation_error', 'traceback': traceback.format_exc() } self.errors.append(error) logger.error(f"Hook compilation failed for {hook_point}: {str(e)}") return None async def execute_hook_safely( self, hook_func: Callable, hook_point: str, *args, **kwargs ) -> Tuple[Any, Optional[Dict]]: """ Execute a user hook with error isolation and timeout Args: hook_func: The compiled hook function hook_point: The hook point name *args, **kwargs: Arguments to pass to the hook Returns: Tuple of (result, error_dict) """ start_time = asyncio.get_event_loop().time() try: # Add timeout to prevent infinite loops result = await asyncio.wait_for( hook_func(*args, **kwargs), timeout=self.timeout ) # Log successful execution execution_time = asyncio.get_event_loop().time() - start_time self.execution_log.append({ 'hook_point': hook_point, 'status': 'success', 'execution_time': execution_time, 'timestamp': start_time }) return result, None except asyncio.TimeoutError: error = { 'hook_point': hook_point, 'error': f'Hook execution timed out ({self.timeout}s limit)', 'type': 'timeout', 'execution_time': self.timeout } self.errors.append(error) self.execution_log.append({ 'hook_point': hook_point, 'status': 'timeout', 'error': error['error'], 'execution_time': self.timeout, 'timestamp': start_time }) # Return the first argument (usually page/browser) to continue return args[0] if args else None, error except Exception as e: execution_time = asyncio.get_event_loop().time() - start_time error = { 'hook_point': hook_point, 'error': str(e), 'type': type(e).__name__, 'traceback': traceback.format_exc(), 'execution_time': execution_time } self.errors.append(error) self.execution_log.append({ 'hook_point': hook_point, 'status': 'failed', 'error': str(e), 'error_type': type(e).__name__, 'execution_time': execution_time, 'timestamp': start_time }) # Return the first argument (usually page/browser) to continue return args[0] if args else None, error def get_summary(self) -> Dict[str, Any]: """Get a summary of hook execution""" total_hooks = len(self.execution_log) successful = sum(1 for log in self.execution_log if log['status'] == 'success') failed = sum(1 for log in self.execution_log if log['status'] == 'failed') timed_out = sum(1 for log in self.execution_log if log['status'] == 'timeout') return { 'total_executions': total_hooks, 'successful': successful, 'failed': failed, 'timed_out': timed_out, 'success_rate': (successful / total_hooks * 100) if total_hooks > 0 else 0, 'total_errors': len(self.errors) } class IsolatedHookWrapper: """Wraps user hooks with error isolation and reporting""" def __init__(self, hook_manager: UserHookManager): self.hook_manager = hook_manager def create_hook_wrapper(self, user_hook: Callable, hook_point: str) -> Callable: """ Create a wrapper that isolates hook errors from main process Args: user_hook: The compiled user hook function hook_point: The hook point name Returns: Wrapped async function that handles errors gracefully """ async def wrapped_hook(*args, **kwargs): """Wrapped hook with error isolation""" # Get the main return object (page/browser) # This ensures we always have something to return return_obj = None if args: return_obj = args[0] elif 'page' in kwargs: return_obj = kwargs['page'] elif 'browser' in kwargs: return_obj = kwargs['browser'] try: # Execute user hook with safety result, error = await self.hook_manager.execute_hook_safely( user_hook, hook_point, *args, **kwargs ) if error: # Hook failed but we continue with original object logger.warning(f"User hook failed at {hook_point}: {error['error']}") return return_obj # Hook succeeded - return its result or the original object if result is None: logger.debug(f"Hook at {hook_point} returned None, using original object") return return_obj return result except Exception as e: # This should rarely happen due to execute_hook_safely logger.error(f"Unexpected error in hook wrapper for {hook_point}: {e}") return return_obj # Set function name for debugging wrapped_hook.__name__ = f"wrapped_{hook_point}" return wrapped_hook async def process_user_hooks( hooks_input: Dict[str, str], timeout: int = 30 ) -> Tuple[Dict[str, Callable], List[Dict], UserHookManager]: """ Process and compile user-provided hook functions Args: hooks_input: Dictionary mapping hook points to code strings timeout: Timeout for each hook execution Returns: Tuple of (compiled_hooks, validation_errors, hook_manager) """ hook_manager = UserHookManager(timeout=timeout) wrapper = IsolatedHookWrapper(hook_manager) compiled_hooks = {} validation_errors = [] for hook_point, hook_code in hooks_input.items(): # Skip empty hooks if not hook_code or not hook_code.strip(): continue # Validate hook point if hook_point not in UserHookManager.HOOK_SIGNATURES: validation_errors.append({ 'hook_point': hook_point, 'error': f'Unknown hook point. Valid points: {", ".join(UserHookManager.HOOK_SIGNATURES.keys())}', 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code }) continue # Validate structure is_valid, message = hook_manager.validate_hook_structure(hook_code, hook_point) if not is_valid: validation_errors.append({ 'hook_point': hook_point, 'error': message, 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code }) continue # Compile the hook hook_func = hook_manager.compile_hook(hook_code, hook_point) if hook_func: # Wrap with error isolation wrapped_hook = wrapper.create_hook_wrapper(hook_func, hook_point) compiled_hooks[hook_point] = wrapped_hook logger.info(f"Successfully compiled hook for {hook_point}") else: validation_errors.append({ 'hook_point': hook_point, 'error': 'Failed to compile hook function - check syntax and structure', 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code }) return compiled_hooks, validation_errors, hook_manager async def process_user_hooks_with_manager( hooks_input: Dict[str, str], hook_manager: UserHookManager ) -> Tuple[Dict[str, Callable], List[Dict]]: """ Process and compile user-provided hook functions with existing manager Args: hooks_input: Dictionary mapping hook points to code strings hook_manager: Existing UserHookManager instance Returns: Tuple of (compiled_hooks, validation_errors) """ wrapper = IsolatedHookWrapper(hook_manager) compiled_hooks = {} validation_errors = [] for hook_point, hook_code in hooks_input.items(): # Skip empty hooks if not hook_code or not hook_code.strip(): continue # Validate hook point if hook_point not in UserHookManager.HOOK_SIGNATURES: validation_errors.append({ 'hook_point': hook_point, 'error': f'Unknown hook point. Valid points: {", ".join(UserHookManager.HOOK_SIGNATURES.keys())}', 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code }) continue # Validate structure is_valid, message = hook_manager.validate_hook_structure(hook_code, hook_point) if not is_valid: validation_errors.append({ 'hook_point': hook_point, 'error': message, 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code }) continue # Compile the hook hook_func = hook_manager.compile_hook(hook_code, hook_point) if hook_func: # Wrap with error isolation wrapped_hook = wrapper.create_hook_wrapper(hook_func, hook_point) compiled_hooks[hook_point] = wrapped_hook logger.info(f"Successfully compiled hook for {hook_point}") else: validation_errors.append({ 'hook_point': hook_point, 'error': 'Failed to compile hook function - check syntax and structure', 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code }) return compiled_hooks, validation_errors async def attach_user_hooks_to_crawler( crawler, # AsyncWebCrawler instance user_hooks: Dict[str, str], timeout: int = 30, hook_manager: Optional[UserHookManager] = None ) -> Tuple[Dict[str, Any], UserHookManager]: """ Attach user-provided hooks to crawler with full error reporting Args: crawler: AsyncWebCrawler instance user_hooks: Dictionary mapping hook points to code strings timeout: Timeout for each hook execution hook_manager: Optional existing UserHookManager instance Returns: Tuple of (status_dict, hook_manager) """ # Use provided hook_manager or create a new one if hook_manager is None: hook_manager = UserHookManager(timeout=timeout) # Process hooks with the hook_manager compiled_hooks, validation_errors = await process_user_hooks_with_manager( user_hooks, hook_manager ) # Log validation errors if validation_errors: logger.warning(f"Hook validation errors: {validation_errors}") # Attach successfully compiled hooks attached_hooks = [] for hook_point, wrapped_hook in compiled_hooks.items(): try: crawler.crawler_strategy.set_hook(hook_point, wrapped_hook) attached_hooks.append(hook_point) logger.info(f"Attached hook to {hook_point}") except Exception as e: logger.error(f"Failed to attach hook to {hook_point}: {e}") validation_errors.append({ 'hook_point': hook_point, 'error': f'Failed to attach hook: {str(e)}' }) status = 'success' if not validation_errors else ('partial' if attached_hooks else 'failed') status_dict = { 'status': status, 'attached_hooks': attached_hooks, 'validation_errors': validation_errors, 'total_hooks_provided': len(user_hooks), 'successfully_attached': len(attached_hooks), 'failed_validation': len(validation_errors) } return status_dict, hook_manager
{ "repo_id": "unclecode/crawl4ai", "file_path": "deploy/docker/hook_manager.py", "license": "Apache License 2.0", "lines": 423, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:deploy/docker/webhook.py
""" Webhook delivery service for Crawl4AI. This module provides webhook notification functionality with exponential backoff retry logic. """ import asyncio import httpx import logging from typing import Dict, Optional from datetime import datetime, timezone logger = logging.getLogger(__name__) class WebhookDeliveryService: """Handles webhook delivery with exponential backoff retry logic.""" def __init__(self, config: Dict): """ Initialize the webhook delivery service. Args: config: Application configuration dictionary containing webhook settings """ self.config = config.get("webhooks", {}) self.max_attempts = self.config.get("retry", {}).get("max_attempts", 5) self.initial_delay = self.config.get("retry", {}).get("initial_delay_ms", 1000) / 1000 self.max_delay = self.config.get("retry", {}).get("max_delay_ms", 32000) / 1000 self.timeout = self.config.get("retry", {}).get("timeout_ms", 30000) / 1000 async def send_webhook( self, webhook_url: str, payload: Dict, headers: Optional[Dict[str, str]] = None ) -> bool: """ Send webhook with exponential backoff retry logic. Args: webhook_url: The URL to send the webhook to payload: The JSON payload to send headers: Optional custom headers Returns: bool: True if delivered successfully, False otherwise """ default_headers = self.config.get("headers", {}) merged_headers = {**default_headers, **(headers or {})} merged_headers["Content-Type"] = "application/json" async with httpx.AsyncClient(timeout=self.timeout) as client: for attempt in range(self.max_attempts): try: logger.info( f"Sending webhook (attempt {attempt + 1}/{self.max_attempts}) to {webhook_url}" ) response = await client.post( webhook_url, json=payload, headers=merged_headers ) # Success or client error (don't retry client errors) if response.status_code < 500: if 200 <= response.status_code < 300: logger.info(f"Webhook delivered successfully to {webhook_url}") return True else: logger.warning( f"Webhook rejected with status {response.status_code}: {response.text[:200]}" ) return False # Client error - don't retry # Server error - retry with backoff logger.warning( f"Webhook failed with status {response.status_code}, will retry" ) except httpx.TimeoutException as exc: logger.error(f"Webhook timeout (attempt {attempt + 1}): {exc}") except httpx.RequestError as exc: logger.error(f"Webhook request error (attempt {attempt + 1}): {exc}") except Exception as exc: logger.error(f"Webhook delivery error (attempt {attempt + 1}): {exc}") # Calculate exponential backoff delay if attempt < self.max_attempts - 1: delay = min(self.initial_delay * (2 ** attempt), self.max_delay) logger.info(f"Retrying in {delay}s...") await asyncio.sleep(delay) logger.error( f"Webhook delivery failed after {self.max_attempts} attempts to {webhook_url}" ) return False async def notify_job_completion( self, task_id: str, task_type: str, status: str, urls: list, webhook_config: Optional[Dict], result: Optional[Dict] = None, error: Optional[str] = None ): """ Notify webhook of job completion. Args: task_id: The task identifier task_type: Type of task (e.g., "crawl", "llm_extraction") status: Task status ("completed" or "failed") urls: List of URLs that were crawled webhook_config: Webhook configuration from the job request result: Optional crawl result data error: Optional error message if failed """ # Determine webhook URL webhook_url = None data_in_payload = self.config.get("data_in_payload", False) custom_headers = None if webhook_config: webhook_url = webhook_config.get("webhook_url") data_in_payload = webhook_config.get("webhook_data_in_payload", data_in_payload) custom_headers = webhook_config.get("webhook_headers") if not webhook_url: webhook_url = self.config.get("default_url") if not webhook_url: logger.debug("No webhook URL configured, skipping notification") return # Check if webhooks are enabled if not self.config.get("enabled", True): logger.debug("Webhooks are disabled, skipping notification") return # Build payload payload = { "task_id": task_id, "task_type": task_type, "status": status, "timestamp": datetime.now(timezone.utc).isoformat(), "urls": urls } if error: payload["error"] = error if data_in_payload and result: payload["data"] = result # Send webhook (fire and forget - don't block on completion) await self.send_webhook(webhook_url, payload, custom_headers)
{ "repo_id": "unclecode/crawl4ai", "file_path": "deploy/docker/webhook.py", "license": "Apache License 2.0", "lines": 133, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/adaptive_crawling/llm_config_example.py
import asyncio import os from crawl4ai import AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig, LLMConfig async def test_configuration(name: str, config: AdaptiveConfig, url: str, query: str): """Test a specific configuration""" print(f"\n{'='*60}") print(f"Configuration: {name}") print(f"{'='*60}") async with AsyncWebCrawler(verbose=False) as crawler: adaptive = AdaptiveCrawler(crawler, config) result = await adaptive.digest(start_url=url, query=query) print("\n" + "="*50) print("CRAWL STATISTICS") print("="*50) adaptive.print_stats(detailed=False) # Get the most relevant content found print("\n" + "="*50) print("MOST RELEVANT PAGES") print("="*50) relevant_pages = adaptive.get_relevant_content(top_k=5) for i, page in enumerate(relevant_pages, 1): print(f"\n{i}. {page['url']}") print(f" Relevance Score: {page['score']:.2%}") # Show a snippet of the content content = page['content'] or "" if content: snippet = content[:200].replace('\n', ' ') if len(content) > 200: snippet += "..." print(f" Preview: {snippet}") print(f"\n{'='*50}") print(f"Pages crawled: {len(result.crawled_urls)}") print(f"Final confidence: {adaptive.confidence:.1%}") print(f"Stopped reason: {result.metrics.get('stopped_reason', 'max_pages')}") if result.metrics.get('is_irrelevant', False): print("โš ๏ธ Query detected as irrelevant!") return result async def llm_embedding(): """Demonstrate various embedding configurations""" print("EMBEDDING STRATEGY CONFIGURATION EXAMPLES") print("=" * 60) # Base URL and query for testing test_url = "https://docs.python.org/3/library/asyncio.html" openai_llm_config = LLMConfig( provider='openai/text-embedding-3-small', api_token=os.getenv('OPENAI_API_KEY'), temperature=0.7, max_tokens=2000 ) config_openai = AdaptiveConfig( strategy="embedding", max_pages=10, # Use OpenAI embeddings embedding_llm_config=openai_llm_config, # embedding_llm_config={ # 'provider': 'openai/text-embedding-3-small', # 'api_token': os.getenv('OPENAI_API_KEY') # }, # OpenAI embeddings are high quality, can be stricter embedding_k_exp=4.0, n_query_variations=12 ) await test_configuration( "OpenAI Embeddings", config_openai, test_url, # "event-driven architecture patterns" "async await context managers coroutines" ) return async def basic_adaptive_crawling(): """Basic adaptive crawling example""" # Initialize the crawler async with AsyncWebCrawler(verbose=True) as crawler: # Create an adaptive crawler with default settings (statistical strategy) adaptive = AdaptiveCrawler(crawler) # Note: You can also use embedding strategy for semantic understanding: # from crawl4ai import AdaptiveConfig # config = AdaptiveConfig(strategy="embedding") # adaptive = AdaptiveCrawler(crawler, config) # Start adaptive crawling print("Starting adaptive crawl for Python async programming information...") result = await adaptive.digest( start_url="https://docs.python.org/3/library/asyncio.html", query="async await context managers coroutines" ) # Display crawl statistics print("\n" + "="*50) print("CRAWL STATISTICS") print("="*50) adaptive.print_stats(detailed=False) # Get the most relevant content found print("\n" + "="*50) print("MOST RELEVANT PAGES") print("="*50) relevant_pages = adaptive.get_relevant_content(top_k=5) for i, page in enumerate(relevant_pages, 1): print(f"\n{i}. {page['url']}") print(f" Relevance Score: {page['score']:.2%}") # Show a snippet of the content content = page['content'] or "" if content: snippet = content[:200].replace('\n', ' ') if len(content) > 200: snippet += "..." print(f" Preview: {snippet}") # Show final confidence print(f"\n{'='*50}") print(f"Final Confidence: {adaptive.confidence:.2%}") print(f"Total Pages Crawled: {len(result.crawled_urls)}") print(f"Knowledge Base Size: {len(adaptive.state.knowledge_base)} documents") if adaptive.confidence >= 0.8: print("โœ“ High confidence - can answer detailed questions about async Python") elif adaptive.confidence >= 0.6: print("~ Moderate confidence - can answer basic questions") else: print("โœ— Low confidence - need more information") if __name__ == "__main__": asyncio.run(llm_embedding()) # asyncio.run(basic_adaptive_crawling())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/adaptive_crawling/llm_config_example.py", "license": "Apache License 2.0", "lines": 120, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/docker_client_hooks_example.py
#!/usr/bin/env python3 """ Comprehensive hooks examples using Docker Client with function objects. This approach is recommended because: - Write hooks as regular Python functions - Full IDE support (autocomplete, type checking) - Automatic conversion to API format - Reusable and testable code - Clean, readable syntax """ import asyncio from crawl4ai import Crawl4aiDockerClient # API_BASE_URL = "http://localhost:11235" API_BASE_URL = "http://localhost:11234" # ============================================================================ # Hook Function Definitions # ============================================================================ # --- All Hooks Demo --- async def browser_created_hook(browser, **kwargs): """Called after browser is created""" print("[HOOK] Browser created and ready") return browser async def page_context_hook(page, context, **kwargs): """Setup page environment""" print("[HOOK] Setting up page environment") # Set viewport await page.set_viewport_size({"width": 1920, "height": 1080}) # Add cookies await context.add_cookies([{ "name": "test_session", "value": "abc123xyz", "domain": ".httpbin.org", "path": "/" }]) # Block resources await context.route("**/*.{png,jpg,jpeg,gif}", lambda route: route.abort()) await context.route("**/analytics/*", lambda route: route.abort()) print("[HOOK] Environment configured") return page async def user_agent_hook(page, context, user_agent, **kwargs): """Called when user agent is updated""" print(f"[HOOK] User agent: {user_agent[:50]}...") return page async def before_goto_hook(page, context, url, **kwargs): """Called before navigating to URL""" print(f"[HOOK] Navigating to: {url}") await page.set_extra_http_headers({ "X-Custom-Header": "crawl4ai-test", "Accept-Language": "en-US" }) return page async def after_goto_hook(page, context, url, response, **kwargs): """Called after page loads""" print(f"[HOOK] Page loaded: {url}") await page.wait_for_timeout(1000) try: await page.wait_for_selector("body", timeout=2000) print("[HOOK] Body element ready") except: print("[HOOK] Timeout, continuing") return page async def execution_started_hook(page, context, **kwargs): """Called when custom JS execution starts""" print("[HOOK] JS execution started") await page.evaluate("console.log('[HOOK] Custom JS');") return page async def before_retrieve_hook(page, context, **kwargs): """Called before retrieving HTML""" print("[HOOK] Preparing HTML retrieval") # Scroll for lazy content await page.evaluate("window.scrollTo(0, document.body.scrollHeight);") await page.wait_for_timeout(500) await page.evaluate("window.scrollTo(0, 0);") print("[HOOK] Scrolling complete") return page async def before_return_hook(page, context, html, **kwargs): """Called before returning HTML""" print(f"[HOOK] HTML ready: {len(html)} chars") metrics = await page.evaluate('''() => ({ images: document.images.length, links: document.links.length, scripts: document.scripts.length })''') print(f"[HOOK] Metrics - Images: {metrics['images']}, Links: {metrics['links']}") return page # --- Authentication Hooks --- async def auth_context_hook(page, context, **kwargs): """Setup authentication context""" print("[HOOK] Setting up authentication") # Add auth cookies await context.add_cookies([{ "name": "auth_token", "value": "fake_jwt_token", "domain": ".httpbin.org", "path": "/", "httpOnly": True }]) # Set localStorage await page.evaluate(''' localStorage.setItem('user_id', '12345'); localStorage.setItem('auth_time', new Date().toISOString()); ''') print("[HOOK] Auth context ready") return page async def auth_headers_hook(page, context, url, **kwargs): """Add authentication headers""" print(f"[HOOK] Adding auth headers for {url}") import base64 credentials = base64.b64encode(b"user:passwd").decode('ascii') await page.set_extra_http_headers({ 'Authorization': f'Basic {credentials}', 'X-API-Key': 'test-key-123' }) return page # --- Performance Optimization Hooks --- async def performance_hook(page, context, **kwargs): """Optimize page for performance""" print("[HOOK] Optimizing for performance") # Block resource-heavy content await context.route("**/*.{png,jpg,jpeg,gif,webp,svg}", lambda r: r.abort()) await context.route("**/*.{woff,woff2,ttf}", lambda r: r.abort()) await context.route("**/*.{mp4,webm,ogg}", lambda r: r.abort()) await context.route("**/googletagmanager.com/*", lambda r: r.abort()) await context.route("**/google-analytics.com/*", lambda r: r.abort()) await context.route("**/facebook.com/*", lambda r: r.abort()) # Disable animations await page.add_style_tag(content=''' *, *::before, *::after { animation-duration: 0s !important; transition-duration: 0s !important; } ''') print("[HOOK] Optimizations applied") return page async def cleanup_hook(page, context, **kwargs): """Clean page before extraction""" print("[HOOK] Cleaning page") await page.evaluate('''() => { const selectors = [ '.ad', '.ads', '.advertisement', '.popup', '.modal', '.overlay', '.cookie-banner', '.newsletter' ]; selectors.forEach(sel => { document.querySelectorAll(sel).forEach(el => el.remove()); }); document.querySelectorAll('script, style').forEach(el => el.remove()); }''') print("[HOOK] Page cleaned") return page # --- Content Extraction Hooks --- async def wait_dynamic_content_hook(page, context, url, response, **kwargs): """Wait for dynamic content to load""" print(f"[HOOK] Waiting for dynamic content on {url}") await page.wait_for_timeout(2000) # Click "Load More" if exists try: load_more = await page.query_selector('[class*="load-more"], button:has-text("Load More")') if load_more: await load_more.click() await page.wait_for_timeout(1000) print("[HOOK] Clicked 'Load More'") except: pass return page async def extract_metadata_hook(page, context, **kwargs): """Extract page metadata""" print("[HOOK] Extracting metadata") metadata = await page.evaluate('''() => { const getMeta = (name) => { const el = document.querySelector(`meta[name="${name}"], meta[property="${name}"]`); return el ? el.getAttribute('content') : null; }; return { title: document.title, description: getMeta('description'), author: getMeta('author'), keywords: getMeta('keywords'), }; }''') print(f"[HOOK] Metadata: {metadata}") # Infinite scroll for i in range(3): await page.evaluate("window.scrollTo(0, document.body.scrollHeight);") await page.wait_for_timeout(1000) print(f"[HOOK] Scroll {i+1}/3") return page # --- Multi-URL Hooks --- async def url_specific_hook(page, context, url, **kwargs): """Apply URL-specific logic""" print(f"[HOOK] Processing URL: {url}") # URL-specific headers if 'html' in url: await page.set_extra_http_headers({"X-Type": "HTML"}) elif 'json' in url: await page.set_extra_http_headers({"X-Type": "JSON"}) return page async def track_progress_hook(page, context, url, response, **kwargs): """Track crawl progress""" status = response.status if response else 'unknown' print(f"[HOOK] Loaded {url} - Status: {status}") return page # ============================================================================ # Test Functions # ============================================================================ async def test_all_hooks_comprehensive(): """Test all 8 hook types""" print("=" * 70) print("Test 1: All Hooks Comprehensive Demo (Docker Client)") print("=" * 70) async with Crawl4aiDockerClient(base_url=API_BASE_URL, verbose=False) as client: print("\nCrawling with all 8 hooks...") # Define hooks with function objects hooks = { "on_browser_created": browser_created_hook, "on_page_context_created": page_context_hook, "on_user_agent_updated": user_agent_hook, "before_goto": before_goto_hook, "after_goto": after_goto_hook, "on_execution_started": execution_started_hook, "before_retrieve_html": before_retrieve_hook, "before_return_html": before_return_hook } result = await client.crawl( ["https://httpbin.org/html"], hooks=hooks, hooks_timeout=30 ) print("\nโœ… Success!") print(f" URL: {result.url}") print(f" Success: {result.success}") print(f" HTML: {len(result.html)} chars") async def test_authentication_workflow(): """Test authentication with hooks""" print("\n" + "=" * 70) print("Test 2: Authentication Workflow (Docker Client)") print("=" * 70) async with Crawl4aiDockerClient(base_url=API_BASE_URL, verbose=False) as client: print("\nTesting authentication...") hooks = { "on_page_context_created": auth_context_hook, "before_goto": auth_headers_hook } result = await client.crawl( ["https://httpbin.org/basic-auth/user/passwd"], hooks=hooks, hooks_timeout=15 ) print("\nโœ… Authentication completed") if result.success: if '"authenticated"' in result.html and 'true' in result.html: print(" โœ… Basic auth successful!") else: print(" โš ๏ธ Auth status unclear") else: print(f" โŒ Failed: {result.error_message}") async def test_performance_optimization(): """Test performance optimization""" print("\n" + "=" * 70) print("Test 3: Performance Optimization (Docker Client)") print("=" * 70) async with Crawl4aiDockerClient(base_url=API_BASE_URL, verbose=False) as client: print("\nTesting performance hooks...") hooks = { "on_page_context_created": performance_hook, "before_retrieve_html": cleanup_hook } result = await client.crawl( ["https://httpbin.org/html"], hooks=hooks, hooks_timeout=10 ) print("\nโœ… Optimization completed") print(f" HTML size: {len(result.html):,} chars") print(" Resources blocked, ads removed") async def test_content_extraction(): """Test content extraction""" print("\n" + "=" * 70) print("Test 4: Content Extraction (Docker Client)") print("=" * 70) async with Crawl4aiDockerClient(base_url=API_BASE_URL, verbose=False) as client: print("\nTesting extraction hooks...") hooks = { "after_goto": wait_dynamic_content_hook, "before_retrieve_html": extract_metadata_hook } result = await client.crawl( ["https://www.kidocode.com/"], hooks=hooks, hooks_timeout=20 ) print("\nโœ… Extraction completed") print(f" URL: {result.url}") print(f" Success: {result.success}") print(f" Metadata: {result.metadata}") async def test_multi_url_crawl(): """Test hooks with multiple URLs""" print("\n" + "=" * 70) print("Test 5: Multi-URL Crawl (Docker Client)") print("=" * 70) async with Crawl4aiDockerClient(base_url=API_BASE_URL, verbose=False) as client: print("\nCrawling multiple URLs...") hooks = { "before_goto": url_specific_hook, "after_goto": track_progress_hook } results = await client.crawl( [ "https://httpbin.org/html", "https://httpbin.org/json", "https://httpbin.org/xml" ], hooks=hooks, hooks_timeout=15 ) print("\nโœ… Multi-URL crawl completed") print(f"\n Crawled {len(results)} URLs:") for i, result in enumerate(results, 1): status = "โœ…" if result.success else "โŒ" print(f" {status} {i}. {result.url}") async def test_reusable_hook_library(): """Test using reusable hook library""" print("\n" + "=" * 70) print("Test 6: Reusable Hook Library (Docker Client)") print("=" * 70) # Create a library of reusable hooks class HookLibrary: @staticmethod async def block_images(page, context, **kwargs): """Block all images""" await context.route("**/*.{png,jpg,jpeg,gif}", lambda r: r.abort()) print("[LIBRARY] Images blocked") return page @staticmethod async def block_analytics(page, context, **kwargs): """Block analytics""" await context.route("**/analytics/*", lambda r: r.abort()) await context.route("**/google-analytics.com/*", lambda r: r.abort()) print("[LIBRARY] Analytics blocked") return page @staticmethod async def scroll_infinite(page, context, **kwargs): """Handle infinite scroll""" for i in range(5): prev = await page.evaluate("document.body.scrollHeight") await page.evaluate("window.scrollTo(0, document.body.scrollHeight);") await page.wait_for_timeout(1000) curr = await page.evaluate("document.body.scrollHeight") if curr == prev: break print("[LIBRARY] Infinite scroll complete") return page async with Crawl4aiDockerClient(base_url=API_BASE_URL, verbose=False) as client: print("\nUsing hook library...") hooks = { "on_page_context_created": HookLibrary.block_images, "before_retrieve_html": HookLibrary.scroll_infinite } result = await client.crawl( ["https://www.kidocode.com/"], hooks=hooks, hooks_timeout=20 ) print("\nโœ… Library hooks completed") print(f" Success: {result.success}") # ============================================================================ # Main # ============================================================================ async def main(): """Run all Docker client hook examples""" print("๐Ÿ”ง Crawl4AI Docker Client - Hooks Examples (Function-Based)") print("Using Python function objects with automatic conversion") print("=" * 70) tests = [ ("All Hooks Demo", test_all_hooks_comprehensive), ("Authentication", test_authentication_workflow), ("Performance", test_performance_optimization), ("Extraction", test_content_extraction), ("Multi-URL", test_multi_url_crawl), ("Hook Library", test_reusable_hook_library) ] for i, (name, test_func) in enumerate(tests, 1): try: await test_func() print(f"\nโœ… Test {i}/{len(tests)}: {name} completed\n") except Exception as e: print(f"\nโŒ Test {i}/{len(tests)}: {name} failed: {e}\n") import traceback traceback.print_exc() print("=" * 70) print("๐ŸŽ‰ All Docker client hook examples completed!") print("\n๐Ÿ’ก Key Benefits of Function-Based Hooks:") print(" โ€ข Write as regular Python functions") print(" โ€ข Full IDE support (autocomplete, types)") print(" โ€ข Automatic conversion to API format") print(" โ€ข Reusable across projects") print(" โ€ข Clean, readable code") print(" โ€ข Easy to test and debug") print("=" * 70) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/docker_client_hooks_example.py", "license": "Apache License 2.0", "lines": 401, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/docker_hooks_examples.py
#!/usr/bin/env python3 """ ๐Ÿš€ Crawl4AI Docker Hooks System - Complete Examples ==================================================== This file demonstrates the Docker Hooks System with three different approaches: 1. String-based hooks for REST API 2. hooks_to_string() utility to convert functions 3. Docker Client with automatic conversion (most convenient) Requirements: - Docker container running: docker run -p 11235:11235 unclecode/crawl4ai:latest - crawl4ai installed: pip install crawl4ai """ import asyncio import requests import json import time from typing import Dict, Any # Import Crawl4AI components from crawl4ai import hooks_to_string from crawl4ai.docker_client import Crawl4aiDockerClient # Configuration DOCKER_URL = "http://localhost:11235" TEST_URLS = [ "https://www.kidocode.com", "https://quotes.toscrape.com", "https://httpbin.org/html", ] def print_section(title: str, description: str = ""): """Print a formatted section header""" print("\n" + "=" * 70) print(f" {title}") if description: print(f" {description}") print("=" * 70 + "\n") def check_docker_service() -> bool: """Check if Docker service is running""" try: response = requests.get(f"{DOCKER_URL}/health", timeout=3) return response.status_code == 200 except: return False # ============================================================================ # REUSABLE HOOK LIBRARY # ============================================================================ async def performance_optimization_hook(page, context, **kwargs): """ Performance Hook: Block unnecessary resources to speed up crawling """ print(" [Hook] ๐Ÿš€ Optimizing performance - blocking images and ads...") # Block images await context.route( "**/*.{png,jpg,jpeg,gif,webp,svg,ico}", lambda route: route.abort() ) # Block ads and analytics await context.route("**/analytics/*", lambda route: route.abort()) await context.route("**/ads/*", lambda route: route.abort()) await context.route("**/google-analytics.com/*", lambda route: route.abort()) print(" [Hook] โœ“ Performance optimization applied") return page async def viewport_setup_hook(page, context, **kwargs): """ Viewport Hook: Set consistent viewport size for rendering """ print(" [Hook] ๐Ÿ–ฅ๏ธ Setting viewport to 1920x1080...") await page.set_viewport_size({"width": 1920, "height": 1080}) print(" [Hook] โœ“ Viewport configured") return page async def authentication_headers_hook(page, context, url, **kwargs): """ Headers Hook: Add custom authentication and tracking headers """ print(f" [Hook] ๐Ÿ” Adding custom headers for {url[:50]}...") await page.set_extra_http_headers({ 'X-Crawl4AI': 'docker-hooks', 'X-Custom-Hook': 'function-based', 'Accept-Language': 'en-US,en;q=0.9', }) print(" [Hook] โœ“ Custom headers added") return page async def lazy_loading_handler_hook(page, context, **kwargs): """ Content Hook: Handle lazy-loaded content by scrolling """ print(" [Hook] ๐Ÿ“œ Scrolling to load lazy content...") # Scroll to bottom await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await page.wait_for_timeout(1000) # Scroll to middle await page.evaluate("window.scrollTo(0, document.body.scrollHeight / 2)") await page.wait_for_timeout(500) # Scroll back to top await page.evaluate("window.scrollTo(0, 0)") await page.wait_for_timeout(500) print(" [Hook] โœ“ Lazy content loaded") return page async def page_analytics_hook(page, context, **kwargs): """ Analytics Hook: Log page metrics before extraction """ print(" [Hook] ๐Ÿ“Š Collecting page analytics...") metrics = await page.evaluate(''' () => ({ title: document.title, images: document.images.length, links: document.links.length, scripts: document.scripts.length, headings: document.querySelectorAll('h1, h2, h3').length, paragraphs: document.querySelectorAll('p').length }) ''') print(f" [Hook] ๐Ÿ“ˆ Page: {metrics['title'][:50]}...") print(f" Links: {metrics['links']}, Images: {metrics['images']}, " f"Headings: {metrics['headings']}, Paragraphs: {metrics['paragraphs']}") return page # ============================================================================ # APPROACH 1: String-Based Hooks (REST API) # ============================================================================ def example_1_string_based_hooks(): """ Demonstrate string-based hooks with REST API Use this when working with REST API directly or non-Python clients """ print_section( "APPROACH 1: String-Based Hooks (REST API)", "Define hooks as strings for REST API requests" ) # Define hooks as strings hooks_config = { "on_page_context_created": """ async def hook(page, context, **kwargs): print(" [String Hook] Setting up page context...") # Block images for performance await context.route("**/*.{png,jpg,jpeg,gif,webp}", lambda route: route.abort()) await page.set_viewport_size({"width": 1920, "height": 1080}) return page """, "before_goto": """ async def hook(page, context, url, **kwargs): print(f" [String Hook] Navigating to {url[:50]}...") await page.set_extra_http_headers({ 'X-Crawl4AI': 'string-based-hooks', }) return page """, "before_retrieve_html": """ async def hook(page, context, **kwargs): print(" [String Hook] Scrolling page...") await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await page.wait_for_timeout(1000) return page """ } # Prepare request payload payload = { "urls": [TEST_URLS[2]], # httpbin.org "hooks": { "code": hooks_config, "timeout": 30 }, "crawler_config": { "cache_mode": "bypass" } } print(f"๐ŸŽฏ Target URL: {TEST_URLS[2]}") print(f"๐Ÿ”ง Configured {len(hooks_config)} string-based hooks") print(f"๐Ÿ“ก Sending request to Docker API...\n") try: start_time = time.time() response = requests.post(f"{DOCKER_URL}/crawl", json=payload, timeout=60) execution_time = time.time() - start_time if response.status_code == 200: result = response.json() print(f"\nโœ… Request successful! (took {execution_time:.2f}s)") # Display results if result.get('results') and result['results'][0].get('success'): crawl_result = result['results'][0] html_length = len(crawl_result.get('html', '')) markdown_length = len(crawl_result.get('markdown', '')) print(f"\n๐Ÿ“Š Results:") print(f" โ€ข HTML length: {html_length:,} characters") print(f" โ€ข Markdown length: {markdown_length:,} characters") print(f" โ€ข URL: {crawl_result.get('url')}") # Check hooks execution if 'hooks' in result: hooks_info = result['hooks'] print(f"\n๐ŸŽฃ Hooks Execution:") print(f" โ€ข Status: {hooks_info['status']['status']}") print(f" โ€ข Attached hooks: {len(hooks_info['status']['attached_hooks'])}") if 'summary' in hooks_info: summary = hooks_info['summary'] print(f" โ€ข Total executions: {summary['total_executions']}") print(f" โ€ข Successful: {summary['successful']}") print(f" โ€ข Success rate: {summary['success_rate']:.1f}%") else: print(f"โš ๏ธ Crawl completed but no results") else: print(f"โŒ Request failed with status {response.status_code}") print(f" Error: {response.text[:200]}") except requests.exceptions.Timeout: print("โฐ Request timed out after 60 seconds") except Exception as e: print(f"โŒ Error: {str(e)}") print("\n" + "โ”€" * 70) print("โœ“ String-based hooks example complete\n") # ============================================================================ # APPROACH 2: Function-Based Hooks with hooks_to_string() Utility # ============================================================================ def example_2_hooks_to_string_utility(): """ Demonstrate the hooks_to_string() utility for converting functions Use this when you want to write hooks as functions but use REST API """ print_section( "APPROACH 2: hooks_to_string() Utility", "Convert Python functions to strings for REST API" ) print("๐Ÿ“ฆ Creating hook functions...") print(" โ€ข performance_optimization_hook") print(" โ€ข authentication_headers_hook") print(" โ€ข lazy_loading_handler_hook") # Convert function objects to strings using the utility print("\n๐Ÿ”„ Converting functions to strings with hooks_to_string()...") hooks_dict = { "on_page_context_created": performance_optimization_hook, "before_goto": authentication_headers_hook, "before_retrieve_html": lazy_loading_handler_hook, } hooks_as_strings = hooks_to_string(hooks_dict) print(f"โœ… Successfully converted {len(hooks_as_strings)} functions to strings") # Show a preview print("\n๐Ÿ“ Sample converted hook (first 200 characters):") print("โ”€" * 70) sample_hook = list(hooks_as_strings.values())[0] print(sample_hook[:200] + "...") print("โ”€" * 70) # Use the converted hooks with REST API print("\n๐Ÿ“ก Using converted hooks with REST API...") payload = { "urls": [TEST_URLS[2]], "hooks": { "code": hooks_as_strings, "timeout": 30 } } try: start_time = time.time() response = requests.post(f"{DOCKER_URL}/crawl", json=payload, timeout=60) execution_time = time.time() - start_time if response.status_code == 200: result = response.json() print(f"\nโœ… Request successful! (took {execution_time:.2f}s)") if result.get('results') and result['results'][0].get('success'): crawl_result = result['results'][0] print(f" โ€ข HTML length: {len(crawl_result.get('html', '')):,} characters") print(f" โ€ข Hooks executed successfully!") else: print(f"โŒ Request failed: {response.status_code}") except Exception as e: print(f"โŒ Error: {str(e)}") print("\n๐Ÿ’ก Benefits of hooks_to_string():") print(" โœ“ Write hooks as regular Python functions") print(" โœ“ Full IDE support (autocomplete, syntax highlighting)") print(" โœ“ Type checking and linting") print(" โœ“ Easy to test and debug") print(" โœ“ Reusable across projects") print(" โœ“ Works with any REST API client") print("\n" + "โ”€" * 70) print("โœ“ hooks_to_string() utility example complete\n") # ============================================================================ # APPROACH 3: Docker Client with Automatic Conversion (RECOMMENDED) # ============================================================================ async def example_3_docker_client_auto_conversion(): """ Demonstrate Docker Client with automatic hook conversion (RECOMMENDED) Use this for the best developer experience with Python """ print_section( "APPROACH 3: Docker Client with Auto-Conversion (RECOMMENDED)", "Pass function objects directly - conversion happens automatically!" ) print("๐Ÿณ Initializing Crawl4AI Docker Client...") client = Crawl4aiDockerClient(base_url=DOCKER_URL) print("โœ… Client ready!\n") # Use our reusable hook library - just pass the function objects! print("๐Ÿ“š Using reusable hook library:") print(" โ€ข performance_optimization_hook") print(" โ€ข authentication_headers_hook") print(" โ€ข lazy_loading_handler_hook") print(" โ€ข page_analytics_hook") print("\n๐ŸŽฏ Target URL: " + TEST_URLS[0]) print("๐Ÿš€ Starting crawl with automatic hook conversion...\n") try: start_time = time.time() # Pass function objects directly - NO manual conversion needed! โœจ results = await client.crawl( urls=[TEST_URLS[0]], hooks={ "on_page_context_created": performance_optimization_hook, "before_goto": authentication_headers_hook, "before_retrieve_html": lazy_loading_handler_hook, "before_return_html": page_analytics_hook, }, hooks_timeout=30 ) execution_time = time.time() - start_time print(f"\nโœ… Crawl completed! (took {execution_time:.2f}s)\n") # Display results if results and results.success: result = results print(f"๐Ÿ“Š Results:") print(f" โ€ข URL: {result.url}") print(f" โ€ข Success: {result.success}") print(f" โ€ข HTML length: {len(result.html):,} characters") print(f" โ€ข Markdown length: {len(result.markdown):,} characters") # Show metadata if result.metadata: print(f"\n๐Ÿ“‹ Metadata:") print(f" โ€ข Title: {result.metadata.get('title', 'N/A')[:50]}...") # Show links if result.links: internal_count = len(result.links.get('internal', [])) external_count = len(result.links.get('external', [])) print(f"\n๐Ÿ”— Links Found:") print(f" โ€ข Internal: {internal_count}") print(f" โ€ข External: {external_count}") else: print(f"โš ๏ธ Crawl completed but no successful results") if results: print(f" Error: {results.error_message}") except Exception as e: print(f"โŒ Error: {str(e)}") import traceback traceback.print_exc() print("\n๐ŸŒŸ Why Docker Client is RECOMMENDED:") print(" โœ“ Automatic function-to-string conversion") print(" โœ“ No manual hooks_to_string() calls needed") print(" โœ“ Cleaner, more Pythonic code") print(" โœ“ Full type hints and IDE support") print(" โœ“ Built-in error handling") print(" โœ“ Async/await support") print("\n" + "โ”€" * 70) print("โœ“ Docker Client auto-conversion example complete\n") # ============================================================================ # APPROACH 4: Authentication Example # ============================================================================ def example_4_authentication_flow(): """ Demonstrate authentication flow with multiple hooks """ print_section( "EXAMPLE 4: Authentication Flow", "Using hooks for authentication with cookies and headers" ) hooks_code = { "on_page_context_created": """ async def hook(page, context, **kwargs): print("[HOOK] Setting up authentication context") # Add authentication cookies await context.add_cookies([ { "name": "auth_token", "value": "fake_jwt_token_here", "domain": ".httpbin.org", "path": "/", "httpOnly": True, "secure": True } ]) return page """, "before_goto": """ async def hook(page, context, url, **kwargs): print(f"[HOOK] Adding auth headers for {url}") # Add Authorization header import base64 credentials = base64.b64encode(b"user:passwd").decode('ascii') await page.set_extra_http_headers({ 'Authorization': f'Basic {credentials}', 'X-API-Key': 'test-api-key-123' }) return page """ } payload = { "urls": ["https://httpbin.org/basic-auth/user/passwd"], "hooks": { "code": hooks_code, "timeout": 15 } } print("\nTesting authentication with httpbin endpoints...") response = requests.post(f"{DOCKER_URL}/crawl", json=payload) if response.status_code == 200: data = response.json() print("โœ… Authentication test completed") if 'results' in data: for i, result in enumerate(data['results']): print(f"\n URL {i+1}: {result['url']}") if result.get('success'): # Check for authentication success indicators html_content = result.get('html', '') if '"authenticated"' in html_content and 'true' in html_content: print(" โœ… Authentication successful! Basic auth worked.") else: print(" โš ๏ธ Page loaded but auth status unclear") else: print(f" โŒ Failed: {result.get('error_message', 'Unknown error')}") else: print(f"โŒ Error: {response.status_code}") print("\n" + "โ”€" * 70) print("โœ“ Authentication example complete\n") # ============================================================================ # MAIN EXECUTION # ============================================================================ async def main(): """ Run all example demonstrations """ print("\n" + "=" * 70) print(" ๐Ÿš€ Crawl4AI - Docker Hooks System Examples") print("=" * 70) # Check Docker service print("\n๐Ÿ” Checking Docker service status...") if not check_docker_service(): print("โŒ Docker service is not running!") print("\n๐Ÿ“‹ To start the Docker service:") print(" docker run -p 11235:11235 unclecode/crawl4ai:latest") print("\nPlease start the service and run this example again.") return print("โœ… Docker service is running!\n") # Run all examples examples = [ ("String-Based Hooks (REST API)", example_1_string_based_hooks, False), ("hooks_to_string() Utility", example_2_hooks_to_string_utility, False), ("Docker Client Auto-Conversion (Recommended)", example_3_docker_client_auto_conversion, True), ("Authentication Flow", example_4_authentication_flow, False), ] for i, (name, example_func, is_async) in enumerate(examples, 1): print(f"\n{'๐Ÿ”ท' * 35}") print(f"Example {i}/{len(examples)}: {name}") print(f"{'๐Ÿ”ท' * 35}\n") try: if is_async: await example_func() else: example_func() print(f"โœ… Example {i} completed successfully!") # Pause between examples (except the last one) if i < len(examples): print("\nโธ๏ธ Press Enter to continue to next example...") input() except KeyboardInterrupt: print(f"\nโน๏ธ Examples interrupted by user") break except Exception as e: print(f"\nโŒ Example {i} failed: {str(e)}") import traceback traceback.print_exc() print("\nContinuing to next example...\n") continue # Final summary print("\n" + "=" * 70) print(" ๐ŸŽ‰ All Examples Complete!") print("=" * 70) print("\n๐Ÿ“Š Summary - Three Approaches to Docker Hooks:") print("\nโœจ 1. String-Based Hooks:") print(" โ€ข Write hooks as strings directly in JSON") print(" โ€ข Best for: REST API, non-Python clients, simple use cases") print(" โ€ข Cons: No IDE support, harder to debug") print("\nโœจ 2. hooks_to_string() Utility:") print(" โ€ข Write hooks as Python functions, convert to strings") print(" โ€ข Best for: Python with REST API, reusable hook libraries") print(" โ€ข Pros: IDE support, type checking, easy debugging") print("\nโœจ 3. Docker Client (RECOMMENDED):") print(" โ€ข Pass function objects directly, automatic conversion") print(" โ€ข Best for: Python applications, best developer experience") print(" โ€ข Pros: All benefits of #2 + cleaner code, no manual conversion") print("\n๐Ÿ’ก Recommendation:") print(" Use Docker Client (#3) for Python applications") print(" Use hooks_to_string() (#2) when you need REST API flexibility") print(" Use string-based (#1) for non-Python clients or simple scripts") print("\n๐ŸŽฏ 8 Hook Points Available:") print(" โ€ข on_browser_created, on_page_context_created") print(" โ€ข on_user_agent_updated, before_goto, after_goto") print(" โ€ข on_execution_started, before_retrieve_html, before_return_html") print("\n๐Ÿ“š Resources:") print(" โ€ข Docs: https://docs.crawl4ai.com/core/docker-deployment") print(" โ€ข GitHub: https://github.com/unclecode/crawl4ai") print(" โ€ข Discord: https://discord.gg/jP8KfhDhyN") print("\n" + "=" * 70) print(" Happy Crawling! ๐Ÿ•ท๏ธ") print("=" * 70 + "\n") if __name__ == "__main__": print("\n๐ŸŽฌ Starting Crawl4AI Docker Hooks Examples...") print("Press Ctrl+C anytime to exit\n") try: asyncio.run(main()) except KeyboardInterrupt: print("\n\n๐Ÿ‘‹ Examples stopped by user. Thanks for exploring Crawl4AI!") except Exception as e: print(f"\n\nโŒ Error: {str(e)}") import traceback traceback.print_exc()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/docker_hooks_examples.py", "license": "Apache License 2.0", "lines": 504, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/docker_webhook_example.py
""" Docker Webhook Example for Crawl4AI This example demonstrates how to use webhooks with the Crawl4AI job queue API. Instead of polling for results, webhooks notify your application when jobs complete. Supports both: - /crawl/job - Raw crawling with markdown extraction - /llm/job - LLM-powered content extraction Prerequisites: 1. Crawl4AI Docker container running on localhost:11235 2. Flask installed: pip install flask requests 3. LLM API key configured in .llm.env (for LLM extraction examples) Usage: 1. Run this script: python docker_webhook_example.py 2. The webhook server will start on http://localhost:8080 3. Jobs will be submitted and webhooks will be received automatically """ import requests import json import time from flask import Flask, request, jsonify from threading import Thread # Configuration CRAWL4AI_BASE_URL = "http://localhost:11235" WEBHOOK_BASE_URL = "http://localhost:8080" # Your webhook receiver URL # Initialize Flask app for webhook receiver app = Flask(__name__) # Store received webhook data for demonstration received_webhooks = [] @app.route('/webhooks/crawl-complete', methods=['POST']) def handle_crawl_webhook(): """ Webhook handler that receives notifications when crawl jobs complete. Payload structure: { "task_id": "crawl_abc123", "task_type": "crawl", "status": "completed" or "failed", "timestamp": "2025-10-21T10:30:00.000000+00:00", "urls": ["https://example.com"], "error": "error message" (only if failed), "data": {...} (only if webhook_data_in_payload=True) } """ payload = request.json print(f"\n{'='*60}") print(f"๐Ÿ“ฌ Webhook received for task: {payload['task_id']}") print(f" Status: {payload['status']}") print(f" Timestamp: {payload['timestamp']}") print(f" URLs: {payload['urls']}") if payload['status'] == 'completed': # If data is in payload, process it directly if 'data' in payload: print(f" โœ… Data included in webhook") data = payload['data'] # Process the crawl results here for result in data.get('results', []): print(f" - Crawled: {result.get('url')}") print(f" - Markdown length: {len(result.get('markdown', ''))}") else: # Fetch results from API if not included print(f" ๐Ÿ“ฅ Fetching results from API...") task_id = payload['task_id'] result_response = requests.get(f"{CRAWL4AI_BASE_URL}/crawl/job/{task_id}") if result_response.ok: data = result_response.json() print(f" โœ… Results fetched successfully") # Process the crawl results here for result in data['result'].get('results', []): print(f" - Crawled: {result.get('url')}") print(f" - Markdown length: {len(result.get('markdown', ''))}") elif payload['status'] == 'failed': print(f" โŒ Job failed: {payload.get('error', 'Unknown error')}") print(f"{'='*60}\n") # Store webhook for demonstration received_webhooks.append(payload) # Return 200 OK to acknowledge receipt return jsonify({"status": "received"}), 200 @app.route('/webhooks/llm-complete', methods=['POST']) def handle_llm_webhook(): """ Webhook handler that receives notifications when LLM extraction jobs complete. Payload structure: { "task_id": "llm_1698765432_12345", "task_type": "llm_extraction", "status": "completed" or "failed", "timestamp": "2025-10-21T10:30:00.000000+00:00", "urls": ["https://example.com/article"], "error": "error message" (only if failed), "data": {"extracted_content": {...}} (only if webhook_data_in_payload=True) } """ payload = request.json print(f"\n{'='*60}") print(f"๐Ÿค– LLM Webhook received for task: {payload['task_id']}") print(f" Task Type: {payload['task_type']}") print(f" Status: {payload['status']}") print(f" Timestamp: {payload['timestamp']}") print(f" URL: {payload['urls'][0]}") if payload['status'] == 'completed': # If data is in payload, process it directly if 'data' in payload: print(f" โœ… Data included in webhook") data = payload['data'] # Webhook wraps extracted content in 'extracted_content' field extracted = data.get('extracted_content', {}) print(f" - Extracted content:") print(f" {json.dumps(extracted, indent=8)}") else: # Fetch results from API if not included print(f" ๐Ÿ“ฅ Fetching results from API...") task_id = payload['task_id'] result_response = requests.get(f"{CRAWL4AI_BASE_URL}/llm/job/{task_id}") if result_response.ok: data = result_response.json() print(f" โœ… Results fetched successfully") # API returns unwrapped content in 'result' field extracted = data['result'] print(f" - Extracted content:") print(f" {json.dumps(extracted, indent=8)}") elif payload['status'] == 'failed': print(f" โŒ Job failed: {payload.get('error', 'Unknown error')}") print(f"{'='*60}\n") # Store webhook for demonstration received_webhooks.append(payload) # Return 200 OK to acknowledge receipt return jsonify({"status": "received"}), 200 def start_webhook_server(): """Start the Flask webhook server in a separate thread""" app.run(host='0.0.0.0', port=8080, debug=False, use_reloader=False) def submit_crawl_job_with_webhook(urls, webhook_url, include_data=False): """ Submit a crawl job with webhook notification. Args: urls: List of URLs to crawl webhook_url: URL to receive webhook notifications include_data: Whether to include full results in webhook payload Returns: task_id: The job's task identifier """ payload = { "urls": urls, "browser_config": {"headless": True}, "crawler_config": {"cache_mode": "bypass"}, "webhook_config": { "webhook_url": webhook_url, "webhook_data_in_payload": include_data, # Optional: Add custom headers for authentication # "webhook_headers": { # "X-Webhook-Secret": "your-secret-token" # } } } print(f"\n๐Ÿš€ Submitting crawl job...") print(f" URLs: {urls}") print(f" Webhook: {webhook_url}") print(f" Include data: {include_data}") response = requests.post( f"{CRAWL4AI_BASE_URL}/crawl/job", json=payload, headers={"Content-Type": "application/json"} ) if response.ok: data = response.json() task_id = data['task_id'] print(f" โœ… Job submitted successfully") print(f" Task ID: {task_id}") return task_id else: print(f" โŒ Failed to submit job: {response.text}") return None def submit_llm_job_with_webhook(url, query, webhook_url, include_data=False, schema=None, provider=None): """ Submit an LLM extraction job with webhook notification. Args: url: URL to extract content from query: Instruction for the LLM (e.g., "Extract article title and author") webhook_url: URL to receive webhook notifications include_data: Whether to include full results in webhook payload schema: Optional JSON schema for structured extraction provider: Optional LLM provider (e.g., "openai/gpt-4o-mini") Returns: task_id: The job's task identifier """ payload = { "url": url, "q": query, "cache": False, "webhook_config": { "webhook_url": webhook_url, "webhook_data_in_payload": include_data, # Optional: Add custom headers for authentication # "webhook_headers": { # "X-Webhook-Secret": "your-secret-token" # } } } if schema: payload["schema"] = schema if provider: payload["provider"] = provider print(f"\n๐Ÿค– Submitting LLM extraction job...") print(f" URL: {url}") print(f" Query: {query}") print(f" Webhook: {webhook_url}") print(f" Include data: {include_data}") if provider: print(f" Provider: {provider}") response = requests.post( f"{CRAWL4AI_BASE_URL}/llm/job", json=payload, headers={"Content-Type": "application/json"} ) if response.ok: data = response.json() task_id = data['task_id'] print(f" โœ… Job submitted successfully") print(f" Task ID: {task_id}") return task_id else: print(f" โŒ Failed to submit job: {response.text}") return None def submit_job_without_webhook(urls): """ Submit a job without webhook (traditional polling approach). Args: urls: List of URLs to crawl Returns: task_id: The job's task identifier """ payload = { "urls": urls, "browser_config": {"headless": True}, "crawler_config": {"cache_mode": "bypass"} } print(f"\n๐Ÿš€ Submitting crawl job (without webhook)...") print(f" URLs: {urls}") response = requests.post( f"{CRAWL4AI_BASE_URL}/crawl/job", json=payload ) if response.ok: data = response.json() task_id = data['task_id'] print(f" โœ… Job submitted successfully") print(f" Task ID: {task_id}") return task_id else: print(f" โŒ Failed to submit job: {response.text}") return None def poll_job_status(task_id, timeout=60): """ Poll for job status (used when webhook is not configured). Args: task_id: The job's task identifier timeout: Maximum time to wait in seconds """ print(f"\nโณ Polling for job status...") start_time = time.time() while time.time() - start_time < timeout: response = requests.get(f"{CRAWL4AI_BASE_URL}/crawl/job/{task_id}") if response.ok: data = response.json() status = data.get('status', 'unknown') if status == 'completed': print(f" โœ… Job completed!") return data elif status == 'failed': print(f" โŒ Job failed: {data.get('error', 'Unknown error')}") return data else: print(f" โณ Status: {status}, waiting...") time.sleep(2) else: print(f" โŒ Failed to get status: {response.text}") return None print(f" โฐ Timeout reached") return None def main(): """Run the webhook demonstration""" # Check if Crawl4AI is running try: health = requests.get(f"{CRAWL4AI_BASE_URL}/health", timeout=5) print(f"โœ… Crawl4AI is running: {health.json()}") except: print(f"โŒ Cannot connect to Crawl4AI at {CRAWL4AI_BASE_URL}") print(" Please make sure Docker container is running:") print(" docker run -d -p 11235:11235 --name crawl4ai unclecode/crawl4ai:latest") return # Start webhook server in background thread print(f"\n๐ŸŒ Starting webhook server at {WEBHOOK_BASE_URL}...") webhook_thread = Thread(target=start_webhook_server, daemon=True) webhook_thread.start() time.sleep(2) # Give server time to start # Example 1: Job with webhook (notification only, fetch data separately) print(f"\n{'='*60}") print("Example 1: Webhook Notification Only") print(f"{'='*60}") task_id_1 = submit_crawl_job_with_webhook( urls=["https://example.com"], webhook_url=f"{WEBHOOK_BASE_URL}/webhooks/crawl-complete", include_data=False ) # Example 2: Job with webhook (data included in payload) time.sleep(5) # Wait a bit between requests print(f"\n{'='*60}") print("Example 2: Webhook with Full Data") print(f"{'='*60}") task_id_2 = submit_crawl_job_with_webhook( urls=["https://www.python.org"], webhook_url=f"{WEBHOOK_BASE_URL}/webhooks/crawl-complete", include_data=True ) # Example 3: LLM extraction with webhook (notification only) time.sleep(5) # Wait a bit between requests print(f"\n{'='*60}") print("Example 3: LLM Extraction with Webhook (Notification Only)") print(f"{'='*60}") task_id_3 = submit_llm_job_with_webhook( url="https://www.example.com", query="Extract the main heading and description from this page.", webhook_url=f"{WEBHOOK_BASE_URL}/webhooks/llm-complete", include_data=False, provider="openai/gpt-4o-mini" ) # Example 4: LLM extraction with webhook (data included + schema) time.sleep(5) # Wait a bit between requests print(f"\n{'='*60}") print("Example 4: LLM Extraction with Schema and Full Data") print(f"{'='*60}") # Define a schema for structured extraction schema = json.dumps({ "type": "object", "properties": { "title": {"type": "string", "description": "Page title"}, "description": {"type": "string", "description": "Page description"} }, "required": ["title"] }) task_id_4 = submit_llm_job_with_webhook( url="https://www.python.org", query="Extract the title and description of this website", webhook_url=f"{WEBHOOK_BASE_URL}/webhooks/llm-complete", include_data=True, schema=schema, provider="openai/gpt-4o-mini" ) # Example 5: Traditional polling (no webhook) time.sleep(5) # Wait a bit between requests print(f"\n{'='*60}") print("Example 5: Traditional Polling (No Webhook)") print(f"{'='*60}") task_id_5 = submit_job_without_webhook( urls=["https://github.com"] ) if task_id_5: result = poll_job_status(task_id_5) if result and result.get('status') == 'completed': print(f" โœ… Results retrieved via polling") # Wait for webhooks to arrive print(f"\nโณ Waiting for webhooks to be received...") time.sleep(30) # Give jobs time to complete and webhooks to arrive (longer for LLM) # Summary print(f"\n{'='*60}") print("Summary") print(f"{'='*60}") print(f"Total webhooks received: {len(received_webhooks)}") crawl_webhooks = [w for w in received_webhooks if w['task_type'] == 'crawl'] llm_webhooks = [w for w in received_webhooks if w['task_type'] == 'llm_extraction'] print(f"\n๐Ÿ“Š Breakdown:") print(f" - Crawl webhooks: {len(crawl_webhooks)}") print(f" - LLM extraction webhooks: {len(llm_webhooks)}") print(f"\n๐Ÿ“‹ Details:") for i, webhook in enumerate(received_webhooks, 1): task_type = webhook['task_type'] icon = "๐Ÿ•ท๏ธ" if task_type == "crawl" else "๐Ÿค–" print(f"{i}. {icon} Task {webhook['task_id']}: {webhook['status']} ({task_type})") print(f"\nโœ… Demo completed!") print(f"\n๐Ÿ’ก Pro tips:") print(f" - In production, your webhook URL should be publicly accessible") print(f" (e.g., https://myapp.com/webhooks) or use ngrok for testing") print(f" - Both /crawl/job and /llm/job support the same webhook configuration") print(f" - Use webhook_data_in_payload=true to get results directly in the webhook") print(f" - LLM jobs may take longer, adjust timeouts accordingly") if __name__ == "__main__": main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/docker_webhook_example.py", "license": "Apache License 2.0", "lines": 386, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/website-to-api/api_server.py
from fastapi import FastAPI, HTTPException from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse from pydantic import BaseModel, HttpUrl from typing import Dict, Any, Optional, Union, List import uvicorn import asyncio import os import json from datetime import datetime from web_scraper_lib import WebScraperAgent, scrape_website app = FastAPI( title="Web Scraper API", description="Convert any website into a structured data API. Provide a URL and tell AI what data you need in plain English.", version="1.0.0" ) # Mount static files if os.path.exists("static"): app.mount("/static", StaticFiles(directory="static"), name="static") # Mount assets directory if os.path.exists("assets"): app.mount("/assets", StaticFiles(directory="assets"), name="assets") # Initialize the scraper agent scraper_agent = WebScraperAgent() # Create directory for saved API requests os.makedirs("saved_requests", exist_ok=True) class ScrapeRequest(BaseModel): url: HttpUrl query: str model_name: Optional[str] = None class ModelConfigRequest(BaseModel): model_name: str provider: str api_token: str class ScrapeResponse(BaseModel): success: bool url: str query: str extracted_data: Union[Dict[str, Any], list] schema_used: Optional[Dict[str, Any]] = None timestamp: Optional[str] = None error: Optional[str] = None class SavedApiRequest(BaseModel): id: str endpoint: str method: str headers: Dict[str, str] body: Dict[str, Any] timestamp: str response: Optional[Dict[str, Any]] = None def save_api_request(endpoint: str, method: str, headers: Dict[str, str], body: Dict[str, Any], response: Optional[Dict[str, Any]] = None) -> str: """Save an API request to a JSON file.""" # Check for duplicate requests (same URL and query) if endpoint in ["/scrape", "/scrape-with-llm"] and "url" in body and "query" in body: existing_requests = get_saved_requests() for existing_request in existing_requests: if (existing_request.endpoint == endpoint and existing_request.body.get("url") == body["url"] and existing_request.body.get("query") == body["query"]): print(f"Duplicate request found for URL: {body['url']} and query: {body['query']}") return existing_request.id # Return existing request ID instead of creating new one request_id = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3] saved_request = SavedApiRequest( id=request_id, endpoint=endpoint, method=method, headers=headers, body=body, timestamp=datetime.now().isoformat(), response=response ) file_path = os.path.join("saved_requests", f"{request_id}.json") with open(file_path, "w") as f: json.dump(saved_request.dict(), f, indent=2) return request_id def get_saved_requests() -> List[SavedApiRequest]: """Get all saved API requests.""" requests = [] if os.path.exists("saved_requests"): for filename in os.listdir("saved_requests"): if filename.endswith('.json'): file_path = os.path.join("saved_requests", filename) try: with open(file_path, "r") as f: data = json.load(f) requests.append(SavedApiRequest(**data)) except Exception as e: print(f"Error loading saved request {filename}: {e}") # Sort by timestamp (newest first) requests.sort(key=lambda x: x.timestamp, reverse=True) return requests @app.get("/") async def root(): """Serve the frontend interface.""" if os.path.exists("static/index.html"): return FileResponse("static/index.html") else: return { "message": "Web Scraper API", "description": "Convert any website into structured data with AI", "endpoints": { "/scrape": "POST - Scrape data from a website", "/schemas": "GET - List cached schemas", "/clear-cache": "POST - Clear schema cache", "/models": "GET - List saved model configurations", "/models": "POST - Save a new model configuration", "/models/{model_name}": "DELETE - Delete a model configuration", "/saved-requests": "GET - List saved API requests" } } @app.post("/scrape", response_model=ScrapeResponse) async def scrape_website_endpoint(request: ScrapeRequest): """ Scrape structured data from any website. This endpoint: 1. Takes a URL and plain English query 2. Generates a custom scraper using AI 3. Returns structured data """ try: # Save the API request headers = {"Content-Type": "application/json"} body = { "url": str(request.url), "query": request.query, "model_name": request.model_name } result = await scraper_agent.scrape_data( url=str(request.url), query=request.query, model_name=request.model_name ) response_data = ScrapeResponse( success=True, url=result["url"], query=result["query"], extracted_data=result["extracted_data"], schema_used=result["schema_used"], timestamp=result["timestamp"] ) # Save the request with response save_api_request( endpoint="/scrape", method="POST", headers=headers, body=body, response=response_data.dict() ) return response_data except Exception as e: # Save the failed request headers = {"Content-Type": "application/json"} body = { "url": str(request.url), "query": request.query, "model_name": request.model_name } save_api_request( endpoint="/scrape", method="POST", headers=headers, body=body, response={"error": str(e)} ) raise HTTPException(status_code=500, detail=f"Scraping failed: {str(e)}") @app.post("/scrape-with-llm", response_model=ScrapeResponse) async def scrape_website_endpoint_with_llm(request: ScrapeRequest): """ Scrape structured data from any website using a custom LLM model. """ try: # Save the API request headers = {"Content-Type": "application/json"} body = { "url": str(request.url), "query": request.query, "model_name": request.model_name } result = await scraper_agent.scrape_data_with_llm( url=str(request.url), query=request.query, model_name=request.model_name ) response_data = ScrapeResponse( success=True, url=result["url"], query=result["query"], extracted_data=result["extracted_data"], timestamp=result["timestamp"] ) # Save the request with response save_api_request( endpoint="/scrape-with-llm", method="POST", headers=headers, body=body, response=response_data.dict() ) return response_data except Exception as e: # Save the failed request headers = {"Content-Type": "application/json"} body = { "url": str(request.url), "query": request.query, "model_name": request.model_name } save_api_request( endpoint="/scrape-with-llm", method="POST", headers=headers, body=body, response={"error": str(e)} ) raise HTTPException(status_code=500, detail=f"Scraping failed: {str(e)}") @app.get("/saved-requests") async def list_saved_requests(): """List all saved API requests.""" try: requests = get_saved_requests() return { "success": True, "requests": [req.dict() for req in requests], "count": len(requests) } except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to list saved requests: {str(e)}") @app.delete("/saved-requests/{request_id}") async def delete_saved_request(request_id: str): """Delete a saved API request.""" try: file_path = os.path.join("saved_requests", f"{request_id}.json") if os.path.exists(file_path): os.remove(file_path) return { "success": True, "message": f"Saved request '{request_id}' deleted successfully" } else: raise HTTPException(status_code=404, detail=f"Saved request '{request_id}' not found") except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to delete saved request: {str(e)}") @app.get("/schemas") async def list_cached_schemas(): """List all cached schemas.""" try: schemas = await scraper_agent.get_cached_schemas() return { "success": True, "cached_schemas": schemas, "count": len(schemas) } except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to list schemas: {str(e)}") @app.post("/clear-cache") async def clear_schema_cache(): """Clear all cached schemas.""" try: scraper_agent.clear_cache() return { "success": True, "message": "Schema cache cleared successfully" } except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to clear cache: {str(e)}") @app.get("/models") async def list_models(): """List all saved model configurations.""" try: models = scraper_agent.list_saved_models() return { "success": True, "models": models, "count": len(models) } except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to list models: {str(e)}") @app.post("/models") async def save_model_config(request: ModelConfigRequest): """Save a new model configuration.""" try: success = scraper_agent.save_model_config( model_name=request.model_name, provider=request.provider, api_token=request.api_token ) if success: return { "success": True, "message": f"Model configuration '{request.model_name}' saved successfully" } else: raise HTTPException(status_code=500, detail="Failed to save model configuration") except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to save model: {str(e)}") @app.delete("/models/{model_name}") async def delete_model_config(model_name: str): """Delete a model configuration.""" try: success = scraper_agent.delete_model_config(model_name) if success: return { "success": True, "message": f"Model configuration '{model_name}' deleted successfully" } else: raise HTTPException(status_code=404, detail=f"Model configuration '{model_name}' not found") except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to delete model: {str(e)}") @app.get("/health") async def health_check(): """Health check endpoint.""" return {"status": "healthy", "service": "web-scraper-api"} if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/website-to-api/api_server.py", "license": "Apache License 2.0", "lines": 315, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/website-to-api/app.py
#!/usr/bin/env python3 """ Startup script for the Web Scraper API with frontend interface. """ import os import sys import uvicorn from pathlib import Path def main(): # Check if static directory exists static_dir = Path("static") if not static_dir.exists(): print("โŒ Static directory not found!") print("Please make sure the 'static' directory exists with the frontend files.") sys.exit(1) # Check if required frontend files exist required_files = ["index.html", "styles.css", "script.js"] missing_files = [] for file in required_files: if not (static_dir / file).exists(): missing_files.append(file) if missing_files: print(f"โŒ Missing frontend files: {', '.join(missing_files)}") print("Please make sure all frontend files are present in the static directory.") sys.exit(1) print("๐Ÿš€ Starting Web Scraper API with Frontend Interface") print("=" * 50) print("๐Ÿ“ Static files found and ready to serve") print("๐ŸŒ Frontend will be available at: http://localhost:8000") print("๐Ÿ”Œ API endpoints available at: http://localhost:8000/docs") print("=" * 50) # Start the server uvicorn.run( "api_server:app", host="0.0.0.0", port=8000, reload=True, log_level="info" ) if __name__ == "__main__": main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/website-to-api/app.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/website-to-api/test_api.py
import asyncio from web_scraper_lib import scrape_website import os async def test_library(): """Test the mini library directly.""" print("=== Testing Mini Library ===") # Test 1: Scrape with a custom model url = "https://marketplace.mainstreet.co.in/collections/adidas-yeezy/products/adidas-yeezy-boost-350-v2-yecheil-non-reflective" query = "Extract the following data: Product name, Product price, Product description, Product size. DO NOT EXTRACT ANYTHING ELSE." if os.path.exists("models"): model_name = os.listdir("models")[0].split(".")[0] else: raise Exception("No models found in models directory") print(f"Scraping: {url}") print(f"Query: {query}") try: result = await scrape_website(url, query, model_name) print("โœ… Library test successful!") print(f"Extracted data: {result['extracted_data']}") except Exception as e: print(f"โŒ Library test failed: {e}") if __name__ == "__main__": asyncio.run(test_library())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/website-to-api/test_api.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:docs/examples/website-to-api/test_models.py
#!/usr/bin/env python3 """ Test script for the new model management functionality. This script demonstrates how to save and use custom model configurations. """ import asyncio import requests import json # API base URL BASE_URL = "http://localhost:8000" def test_model_management(): """Test the model management endpoints.""" print("=== Testing Model Management ===") # 1. List current models print("\n1. Listing current models:") response = requests.get(f"{BASE_URL}/models") print(f"Status: {response.status_code}") print(f"Response: {json.dumps(response.json(), indent=2)}") # 2. Save another model configuration (OpenAI example) print("\n2. Saving OpenAI model configuration:") openai_config = { "model_name": "my-openai", "provider": "openai", "api_token": "your-openai-api-key-here" } response = requests.post(f"{BASE_URL}/models", json=openai_config) print(f"Status: {response.status_code}") print(f"Response: {json.dumps(response.json(), indent=2)}") # 3. List models again to see the new ones print("\n3. Listing models after adding new ones:") response = requests.get(f"{BASE_URL}/models") print(f"Status: {response.status_code}") print(f"Response: {json.dumps(response.json(), indent=2)}") # 4. Delete a model configuration print("\n4. Deleting a model configuration:") response = requests.delete(f"{BASE_URL}/models/my-openai") print(f"Status: {response.status_code}") print(f"Response: {json.dumps(response.json(), indent=2)}") # 5. Final list of models print("\n5. Final list of models:") response = requests.get(f"{BASE_URL}/models") print(f"Status: {response.status_code}") print(f"Response: {json.dumps(response.json(), indent=2)}") if __name__ == "__main__": print("Model Management Test Script") print("Make sure the API server is running on http://localhost:8000") print("=" * 50) try: test_model_management() except requests.exceptions.ConnectionError: print("Error: Could not connect to the API server.") print("Make sure the server is running with: python api_server.py") except Exception as e: print(f"Error: {e}")
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/website-to-api/test_models.py", "license": "Apache License 2.0", "lines": 54, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:docs/examples/website-to-api/web_scraper_lib.py
from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CacheMode, CrawlerRunConfig, LLMConfig, JsonCssExtractionStrategy, LLMExtractionStrategy ) import os import json import hashlib from typing import Dict, Any, Optional, List from litellm import completion class ModelConfig: """Configuration for LLM models.""" def __init__(self, provider: str, api_token: str): self.provider = provider self.api_token = api_token def to_dict(self) -> Dict[str, Any]: return { "provider": self.provider, "api_token": self.api_token } @classmethod def from_dict(cls, data: Dict[str, Any]) -> 'ModelConfig': return cls( provider=data["provider"], api_token=data["api_token"] ) class WebScraperAgent: """ A mini library that converts any website into a structured data API. Features: 1. Provide a URL and tell AI what data you need in plain English 2. Generate: Agent reverse-engineers the site and deploys custom scraper 3. Integrate: Use private API endpoint to get structured data 4. Support for custom LLM models and API keys """ def __init__(self, schemas_dir: str = "schemas", models_dir: str = "models"): self.schemas_dir = schemas_dir self.models_dir = models_dir os.makedirs(self.schemas_dir, exist_ok=True) os.makedirs(self.models_dir, exist_ok=True) def _generate_schema_key(self, url: str, query: str) -> str: """Generate a unique key for schema caching based on URL and query.""" content = f"{url}:{query}" return hashlib.md5(content.encode()).hexdigest() def save_model_config(self, model_name: str, provider: str, api_token: str) -> bool: """ Save a model configuration for later use. Args: model_name: User-friendly name for the model provider: LLM provider (e.g., 'gemini', 'openai', 'anthropic') api_token: API token for the provider Returns: True if saved successfully """ try: model_config = ModelConfig(provider, api_token) config_path = os.path.join(self.models_dir, f"{model_name}.json") with open(config_path, "w") as f: json.dump(model_config.to_dict(), f, indent=2) print(f"Model configuration saved: {model_name}") return True except Exception as e: print(f"Failed to save model configuration: {e}") return False def load_model_config(self, model_name: str) -> Optional[ModelConfig]: """ Load a saved model configuration. Args: model_name: Name of the saved model configuration Returns: ModelConfig object or None if not found """ try: config_path = os.path.join(self.models_dir, f"{model_name}.json") if not os.path.exists(config_path): return None with open(config_path, "r") as f: data = json.load(f) return ModelConfig.from_dict(data) except Exception as e: print(f"Failed to load model configuration: {e}") return None def list_saved_models(self) -> List[str]: """List all saved model configurations.""" models = [] for filename in os.listdir(self.models_dir): if filename.endswith('.json'): models.append(filename[:-5]) # Remove .json extension return models def delete_model_config(self, model_name: str) -> bool: """ Delete a saved model configuration. Args: model_name: Name of the model configuration to delete Returns: True if deleted successfully """ try: config_path = os.path.join(self.models_dir, f"{model_name}.json") if os.path.exists(config_path): os.remove(config_path) print(f"Model configuration deleted: {model_name}") return True return False except Exception as e: print(f"Failed to delete model configuration: {e}") return False async def _load_or_generate_schema(self, url: str, query: str, session_id: str = "schema_generator", model_name: Optional[str] = None) -> Dict[str, Any]: """ Loads schema from cache if exists, otherwise generates using AI. This is the "Generate" step - our agent reverse-engineers the site. Args: url: URL to scrape query: Query for data extraction session_id: Session identifier model_name: Name of saved model configuration to use """ schema_key = self._generate_schema_key(url, query) schema_path = os.path.join(self.schemas_dir, f"{schema_key}.json") if os.path.exists(schema_path): print(f"Schema found in cache for {url}") with open(schema_path, "r") as f: return json.load(f) print(f"Generating new schema for {url}") print(f"Query: {query}") query += """ IMPORTANT: GENERATE THE SCHEMA WITH ONLY THE FIELDS MENTIONED IN THE QUERY. MAKE SURE THE NUMBER OF FIELDS IN THE SCHEME MATCH THE NUMBER OF FIELDS IN THE QUERY. """ # Step 1: Fetch the page HTML async with AsyncWebCrawler(config=BrowserConfig(headless=True)) as crawler: result = await crawler.arun( url=url, config=CrawlerRunConfig( cache_mode=CacheMode.BYPASS, session_id=session_id, simulate_user=True, remove_overlay_elements=True, delay_before_return_html=5, ) ) html = result.fit_html # Step 2: Generate schema using AI with custom model if specified print("AI is analyzing the page structure...") # Use custom model configuration if provided if model_name: model_config = self.load_model_config(model_name) if model_config: llm_config = LLMConfig( provider=model_config.provider, api_token=model_config.api_token ) print(f"Using custom model: {model_name}") else: raise ValueError(f"Model configuration '{model_name}' not found. Please add it from the Models page.") else: # Require a model to be specified raise ValueError("No model specified. Please select a model from the dropdown or add one from the Models page.") schema = JsonCssExtractionStrategy.generate_schema( html=html, llm_config=llm_config, query=query ) # Step 3: Cache the generated schema print(f"Schema generated and cached: {json.dumps(schema, indent=2)}") with open(schema_path, "w") as f: json.dump(schema, f, indent=2) return schema def _generate_llm_schema(self, query: str, llm_config: LLMConfig) -> Dict[str, Any]: """ Generate a schema for a given query using a custom LLM model. Args: query: Plain English description of what data to extract model_config: Model configuration to use """ # ask the model to generate a schema for the given query in the form of a json. prompt = f""" IDENTIFY THE FIELDS FOR EXTRACTION MENTIONED IN THE QUERY and GENERATE A JSON SCHEMA FOR THE FIELDS. eg. {{ "name": "str", "age": "str", "email": "str", "product_name": "str", "product_price": "str", "product_description": "str", "product_image": "str", "product_url": "str", "product_rating": "str", "product_reviews": "str", }} Here is the query: {query} IMPORTANT: THE RESULT SHOULD BE A JSON OBJECT. MAKE SURE THE NUMBER OF FIELDS IN THE RESULT MATCH THE NUMBER OF FIELDS IN THE QUERY. THE RESULT SHOULD BE A JSON OBJECT. """ response = completion( model=llm_config.provider, messages=[{"role": "user", "content": prompt}], api_key=llm_config.api_token, result_type="json" ) return response.json()["choices"][0]["message"]["content"] async def scrape_data_with_llm(self, url: str, query: str, model_name: Optional[str] = None) -> Dict[str, Any]: """ Scrape structured data from any website using a custom LLM model. Args: url: The website URL to scrape query: Plain English description of what data to extract model_name: Name of saved model configuration to use """ if model_name: model_config = self.load_model_config(model_name) if model_config: llm_config = LLMConfig( provider=model_config.provider, api_token=model_config.api_token ) print(f"Using custom model: {model_name}") else: raise ValueError(f"Model configuration '{model_name}' not found. Please add it from the Models page.") else: # Require a model to be specified raise ValueError("No model specified. Please select a model from the dropdown or add one from the Models page.") query += """\n IMPORTANT: THE RESULT SHOULD BE A JSON OBJECT WITH THE ONLY THE FIELDS MENTIONED IN THE QUERY. MAKE SURE THE NUMBER OF FIELDS IN THE RESULT MATCH THE NUMBER OF FIELDS IN THE QUERY. THE RESULT SHOULD BE A JSON OBJECT. """ schema = self._generate_llm_schema(query, llm_config) print(f"Schema: {schema}") llm_extraction_strategy = LLMExtractionStrategy( llm_config=llm_config, instruction=query, result_type="json", schema=schema ) async with AsyncWebCrawler() as crawler: result = await crawler.arun( url=url, config=CrawlerRunConfig( cache_mode=CacheMode.BYPASS, simulate_user=True, extraction_strategy=llm_extraction_strategy, ) ) extracted_data = result.extracted_content if isinstance(extracted_data, str): try: extracted_data = json.loads(extracted_data) except json.JSONDecodeError: # If it's not valid JSON, keep it as string pass return { "url": url, "query": query, "extracted_data": extracted_data, "timestamp": result.timestamp if hasattr(result, 'timestamp') else None } async def scrape_data(self, url: str, query: str, model_name: Optional[str] = None) -> Dict[str, Any]: """ Main method to scrape structured data from any website. Args: url: The website URL to scrape query: Plain English description of what data to extract model_name: Name of saved model configuration to use Returns: Structured data extracted from the website """ # Step 1: Generate or load schema (reverse-engineer the site) schema = await self._load_or_generate_schema(url=url, query=query, model_name=model_name) # Step 2: Deploy custom high-speed scraper print(f"Deploying custom scraper for {url}") browser_config = BrowserConfig(headless=True) async with AsyncWebCrawler(config=browser_config) as crawler: run_config = CrawlerRunConfig( extraction_strategy=JsonCssExtractionStrategy(schema=schema), ) result = await crawler.arun(url=url, config=run_config) # Step 3: Return structured data # Parse extracted_content if it's a JSON string extracted_data = result.extracted_content if isinstance(extracted_data, str): try: extracted_data = json.loads(extracted_data) except json.JSONDecodeError: # If it's not valid JSON, keep it as string pass return { "url": url, "query": query, "extracted_data": extracted_data, "schema_used": schema, "timestamp": result.timestamp if hasattr(result, 'timestamp') else None } async def get_cached_schemas(self) -> Dict[str, str]: """Get list of cached schemas.""" schemas = {} for filename in os.listdir(self.schemas_dir): if filename.endswith('.json'): schema_key = filename[:-5] # Remove .json extension schemas[schema_key] = filename return schemas def clear_cache(self): """Clear all cached schemas.""" import shutil if os.path.exists(self.schemas_dir): shutil.rmtree(self.schemas_dir) os.makedirs(self.schemas_dir, exist_ok=True) print("Schema cache cleared") # Convenience function for simple usage async def scrape_website(url: str, query: str, model_name: Optional[str] = None) -> Dict[str, Any]: """ Simple function to scrape any website with plain English instructions. Args: url: Website URL query: Plain English description of what data to extract model_name: Name of saved model configuration to use Returns: Extracted structured data """ agent = WebScraperAgent() return await agent.scrape_data(url, query, model_name) async def scrape_website_with_llm(url: str, query: str, model_name: Optional[str] = None): """ Scrape structured data from any website using a custom LLM model. Args: url: The website URL to scrape query: Plain English description of what data to extract model_name: Name of saved model configuration to use """ agent = WebScraperAgent() return await agent.scrape_data_with_llm(url, query, model_name)
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/website-to-api/web_scraper_lib.py", "license": "Apache License 2.0", "lines": 340, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/md_v2/marketplace/backend/config.py
""" Marketplace Configuration - Loads from .env file """ import os import sys import hashlib from pathlib import Path from dotenv import load_dotenv # Load .env file env_path = Path(__file__).parent / '.env' if not env_path.exists(): print("\nโŒ ERROR: No .env file found!") print("Please copy .env.example to .env and update with your values:") print(f" cp {Path(__file__).parent}/.env.example {Path(__file__).parent}/.env") print("\nThen edit .env with your secure values.") sys.exit(1) load_dotenv(env_path) # Required environment variables required_vars = ['MARKETPLACE_ADMIN_PASSWORD', 'MARKETPLACE_JWT_SECRET'] missing_vars = [var for var in required_vars if not os.getenv(var)] if missing_vars: print(f"\nโŒ ERROR: Missing required environment variables: {', '.join(missing_vars)}") print("Please check your .env file and ensure all required variables are set.") sys.exit(1) class Config: """Configuration loaded from environment variables""" # Admin authentication - hashed from password in .env ADMIN_PASSWORD_HASH = hashlib.sha256( os.getenv('MARKETPLACE_ADMIN_PASSWORD').encode() ).hexdigest() # JWT secret for token generation JWT_SECRET_KEY = os.getenv('MARKETPLACE_JWT_SECRET') # Database path DATABASE_PATH = os.getenv('MARKETPLACE_DB_PATH', './marketplace.db') # Token expiry in hours TOKEN_EXPIRY_HOURS = int(os.getenv('MARKETPLACE_TOKEN_EXPIRY', '4')) # CORS origins - hardcoded as they don't contain secrets ALLOWED_ORIGINS = [ "http://localhost:8000", "http://localhost:8080", "http://localhost:8100", "http://127.0.0.1:8000", "http://127.0.0.1:8080", "http://127.0.0.1:8100", "https://crawl4ai.com", "https://www.crawl4ai.com", "https://docs.crawl4ai.com", "https://market.crawl4ai.com" ]
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/md_v2/marketplace/backend/config.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/md_v2/marketplace/backend/database.py
import sqlite3 import yaml import json from pathlib import Path from typing import Dict, List, Any class DatabaseManager: def __init__(self, db_path=None, schema_path='schema.yaml'): self.schema = self._load_schema(schema_path) # Use provided path or fallback to schema default self.db_path = db_path or self.schema['database']['name'] self.conn = None self._init_database() def _load_schema(self, path: str) -> Dict: with open(path, 'r') as f: return yaml.safe_load(f) def _init_database(self): """Auto-create/migrate database from schema""" self.conn = sqlite3.connect(self.db_path, check_same_thread=False) self.conn.row_factory = sqlite3.Row for table_name, table_def in self.schema['tables'].items(): self._create_or_update_table(table_name, table_def['columns']) def _create_or_update_table(self, table_name: str, columns: Dict): cursor = self.conn.cursor() # Check if table exists cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,)) table_exists = cursor.fetchone() is not None if not table_exists: # Create table col_defs = [] for col_name, col_spec in columns.items(): col_def = f"{col_name} {col_spec['type']}" if col_spec.get('primary'): col_def += " PRIMARY KEY" if col_spec.get('autoincrement'): col_def += " AUTOINCREMENT" if col_spec.get('unique'): col_def += " UNIQUE" if col_spec.get('required'): col_def += " NOT NULL" if 'default' in col_spec: default = col_spec['default'] if default == 'CURRENT_TIMESTAMP': col_def += f" DEFAULT {default}" elif isinstance(default, str): col_def += f" DEFAULT '{default}'" else: col_def += f" DEFAULT {default}" col_defs.append(col_def) create_sql = f"CREATE TABLE {table_name} ({', '.join(col_defs)})" cursor.execute(create_sql) else: # Check for new columns and add them cursor.execute(f"PRAGMA table_info({table_name})") existing_columns = {row[1] for row in cursor.fetchall()} for col_name, col_spec in columns.items(): if col_name not in existing_columns: col_def = f"{col_spec['type']}" if 'default' in col_spec: default = col_spec['default'] if default == 'CURRENT_TIMESTAMP': col_def += f" DEFAULT {default}" elif isinstance(default, str): col_def += f" DEFAULT '{default}'" else: col_def += f" DEFAULT {default}" cursor.execute(f"ALTER TABLE {table_name} ADD COLUMN {col_name} {col_def}") self.conn.commit() def get_all(self, table: str, limit: int = 100, offset: int = 0, where: str = None) -> List[Dict]: cursor = self.conn.cursor() query = f"SELECT * FROM {table}" if where: query += f" WHERE {where}" query += f" LIMIT {limit} OFFSET {offset}" cursor.execute(query) rows = cursor.fetchall() return [dict(row) for row in rows] def search(self, query: str, tables: List[str] = None) -> Dict[str, List[Dict]]: if not tables: tables = list(self.schema['tables'].keys()) results = {} cursor = self.conn.cursor() for table in tables: # Search in text columns columns = self.schema['tables'][table]['columns'] text_cols = [col for col, spec in columns.items() if spec['type'] == 'TEXT' and col != 'id'] if text_cols: where_clause = ' OR '.join([f"{col} LIKE ?" for col in text_cols]) params = [f'%{query}%'] * len(text_cols) cursor.execute(f"SELECT * FROM {table} WHERE {where_clause} LIMIT 10", params) rows = cursor.fetchall() if rows: results[table] = [dict(row) for row in rows] return results def close(self): if self.conn: self.conn.close()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/md_v2/marketplace/backend/database.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/md_v2/marketplace/backend/dummy_data.py
import sqlite3 import json import random from datetime import datetime, timedelta from database import DatabaseManager def generate_slug(text): return text.lower().replace(' ', '-').replace('&', 'and') def generate_dummy_data(): db = DatabaseManager() conn = db.conn cursor = conn.cursor() # Clear existing data for table in ['apps', 'articles', 'categories', 'sponsors']: cursor.execute(f"DELETE FROM {table}") # Categories categories = [ ("Browser Automation", "โš™", "Tools for browser automation and control"), ("Proxy Services", "๐Ÿ”’", "Proxy providers and rotation services"), ("LLM Integration", "๐Ÿค–", "AI/LLM tools and integrations"), ("Data Processing", "๐Ÿ“Š", "Data extraction and processing tools"), ("Cloud Infrastructure", "โ˜", "Cloud browser and computing services"), ("Developer Tools", "๐Ÿ› ", "Development and testing utilities") ] for i, (name, icon, desc) in enumerate(categories): cursor.execute(""" INSERT INTO categories (name, slug, icon, description, order_index) VALUES (?, ?, ?, ?, ?) """, (name, generate_slug(name), icon, desc, i)) # Apps with real Unsplash images apps_data = [ # Browser Automation ("Playwright Cloud", "Browser Automation", "Paid", True, True, "Scalable browser automation in the cloud with Playwright", "https://playwright.cloud", None, "$99/month starter", 4.8, 12500, "https://images.unsplash.com/photo-1633356122544-f134324a6cee?w=800&h=400&fit=crop"), ("Selenium Grid Hub", "Browser Automation", "Freemium", False, False, "Distributed Selenium grid for parallel testing", "https://seleniumhub.io", "https://github.com/seleniumhub/grid", "Free - $299/month", 4.2, 8400, "https://images.unsplash.com/photo-1555066931-4365d14bab8c?w=800&h=400&fit=crop"), ("Puppeteer Extra", "Browser Automation", "Open Source", True, False, "Enhanced Puppeteer with stealth plugins and more", "https://puppeteer-extra.dev", "https://github.com/berstend/puppeteer-extra", "Free", 4.6, 15200, "https://images.unsplash.com/photo-1461749280684-dccba630e2f6?w=800&h=400&fit=crop"), # Proxy Services ("BrightData", "Proxy Services", "Paid", True, True, "Premium proxy network with 72M+ IPs worldwide", "https://brightdata.com", None, "Starting $500/month", 4.7, 9800, "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=800&h=400&fit=crop"), ("SmartProxy", "Proxy Services", "Paid", False, True, "Residential and datacenter proxies with rotation", "https://smartproxy.com", None, "Starting $75/month", 4.3, 7600, "https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=800&h=400&fit=crop"), ("ProxyMesh", "Proxy Services", "Freemium", False, False, "Rotating proxy servers with sticky sessions", "https://proxymesh.com", None, "$10-$50/month", 4.0, 4200, "https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=800&h=400&fit=crop"), # LLM Integration ("LangChain Crawl", "LLM Integration", "Open Source", True, False, "LangChain integration for Crawl4AI workflows", "https://langchain-crawl.dev", "https://github.com/langchain/crawl", "Free", 4.5, 18900, "https://images.unsplash.com/photo-1677442136019-21780ecad995?w=800&h=400&fit=crop"), ("GPT Scraper", "LLM Integration", "Freemium", False, False, "Extract structured data using GPT models", "https://gptscraper.ai", None, "Free - $99/month", 4.1, 5600, "https://images.unsplash.com/photo-1655720828018-edd2daec9349?w=800&h=400&fit=crop"), ("Claude Extract", "LLM Integration", "Paid", True, True, "Professional extraction using Claude AI", "https://claude-extract.com", None, "$199/month", 4.9, 3200, "https://images.unsplash.com/photo-1686191128892-3b09ad503b4f?w=800&h=400&fit=crop"), # Data Processing ("DataMiner Pro", "Data Processing", "Paid", False, False, "Advanced data extraction and transformation", "https://dataminer.pro", None, "$149/month", 4.2, 6700, "https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&h=400&fit=crop"), ("ScraperAPI", "Data Processing", "Freemium", True, True, "Simple API for web scraping with proxy rotation", "https://scraperapi.com", None, "Free - $299/month", 4.6, 22300, "https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=800&h=400&fit=crop"), ("Apify", "Data Processing", "Freemium", False, False, "Web scraping and automation platform", "https://apify.com", None, "$49-$499/month", 4.4, 14500, "https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=800&h=400&fit=crop"), # Cloud Infrastructure ("BrowserCloud", "Cloud Infrastructure", "Paid", True, True, "Managed headless browsers in the cloud", "https://browsercloud.io", None, "$199/month", 4.5, 8900, "https://images.unsplash.com/photo-1667372393119-3d4c48d07fc9?w=800&h=400&fit=crop"), ("LambdaTest", "Cloud Infrastructure", "Freemium", False, False, "Cross-browser testing on cloud", "https://lambdatest.com", None, "Free - $99/month", 4.1, 11200, "https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=800&h=400&fit=crop"), ("Browserless", "Cloud Infrastructure", "Freemium", True, False, "Headless browser automation API", "https://browserless.io", None, "$50-$500/month", 4.7, 19800, "https://images.unsplash.com/photo-1639762681485-074b7f938ba0?w=800&h=400&fit=crop"), # Developer Tools ("Crawl4AI VSCode", "Developer Tools", "Open Source", True, False, "VSCode extension for Crawl4AI development", "https://marketplace.visualstudio.com", "https://github.com/crawl4ai/vscode", "Free", 4.8, 34500, "https://images.unsplash.com/photo-1629654297299-c8506221ca97?w=800&h=400&fit=crop"), ("Postman Collection", "Developer Tools", "Open Source", False, False, "Postman collection for Crawl4AI API testing", "https://postman.com/crawl4ai", "https://github.com/crawl4ai/postman", "Free", 4.3, 7800, "https://images.unsplash.com/photo-1599507593499-a3f7d7d97667?w=800&h=400&fit=crop"), ("Debug Toolkit", "Developer Tools", "Open Source", False, False, "Debugging tools for crawler development", "https://debug.crawl4ai.com", "https://github.com/crawl4ai/debug", "Free", 4.0, 4300, "https://images.unsplash.com/photo-1515879218367-8466d910aaa4?w=800&h=400&fit=crop"), ] for name, category, type_, featured, sponsored, desc, url, github, pricing, rating, downloads, image in apps_data: screenshots = json.dumps([ f"https://images.unsplash.com/photo-{random.randint(1500000000000, 1700000000000)}-{random.randint(1000000000000, 9999999999999)}?w=800&h=600&fit=crop", f"https://images.unsplash.com/photo-{random.randint(1500000000000, 1700000000000)}-{random.randint(1000000000000, 9999999999999)}?w=800&h=600&fit=crop" ]) cursor.execute(""" INSERT INTO apps (name, slug, description, category, type, featured, sponsored, website_url, github_url, pricing, rating, downloads, image, screenshots, logo_url, integration_guide, contact_email, views) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (name, generate_slug(name), desc, category, type_, featured, sponsored, url, github, pricing, rating, downloads, image, screenshots, f"https://ui-avatars.com/api/?name={name}&background=50ffff&color=070708&size=128", f"# {name} Integration\n\n```python\nfrom crawl4ai import AsyncWebCrawler\n# Integration code coming soon...\n```", f"contact@{generate_slug(name)}.com", random.randint(100, 5000))) # Articles with real images articles_data = [ ("Browser Automation Showdown: Playwright vs Puppeteer vs Selenium", "Review", "John Doe", ["Playwright Cloud", "Puppeteer Extra"], ["browser-automation", "comparison", "2024"], "https://images.unsplash.com/photo-1587620962725-abab7fe55159?w=1200&h=630&fit=crop"), ("Top 5 Proxy Services for Web Scraping in 2024", "Comparison", "Jane Smith", ["BrightData", "SmartProxy", "ProxyMesh"], ["proxy", "web-scraping", "guide"], "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=1200&h=630&fit=crop"), ("Integrating LLMs with Crawl4AI: A Complete Guide", "Tutorial", "Crawl4AI Team", ["LangChain Crawl", "GPT Scraper", "Claude Extract"], ["llm", "integration", "tutorial"], "https://images.unsplash.com/photo-1677442136019-21780ecad995?w=1200&h=630&fit=crop"), ("Building Scalable Crawlers with Cloud Infrastructure", "Tutorial", "Mike Johnson", ["BrowserCloud", "Browserless"], ["cloud", "scalability", "architecture"], "https://images.unsplash.com/photo-1667372393119-3d4c48d07fc9?w=1200&h=630&fit=crop"), ("What's New in Crawl4AI Marketplace", "News", "Crawl4AI Team", [], ["marketplace", "announcement", "news"], "https://images.unsplash.com/photo-1556075798-4825dfaaf498?w=1200&h=630&fit=crop"), ("Cost Analysis: Self-Hosted vs Cloud Browser Solutions", "Comparison", "Sarah Chen", ["BrowserCloud", "LambdaTest", "Browserless"], ["cost", "cloud", "comparison"], "https://images.unsplash.com/photo-1554224155-8d04cb21cd6c?w=1200&h=630&fit=crop"), ("Getting Started with Browser Automation", "Tutorial", "Crawl4AI Team", ["Playwright Cloud", "Selenium Grid Hub"], ["beginner", "tutorial", "automation"], "https://images.unsplash.com/photo-1498050108023-c5249f4df085?w=1200&h=630&fit=crop"), ("The Future of Web Scraping: AI-Powered Extraction", "News", "Dr. Alan Turing", ["Claude Extract", "GPT Scraper"], ["ai", "future", "trends"], "https://images.unsplash.com/photo-1593720213428-28a5b9e94613?w=1200&h=630&fit=crop") ] for title, category, author, related_apps, tags, image in articles_data: # Get app IDs for related apps related_ids = [] for app_name in related_apps: cursor.execute("SELECT id FROM apps WHERE name = ?", (app_name,)) result = cursor.fetchone() if result: related_ids.append(result[0]) content = f"""# {title} By {author} | {datetime.now().strftime('%B %d, %Y')} ## Introduction This is a comprehensive article about {title.lower()}. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ## Key Points - Important point about the topic - Another crucial insight - Technical details and specifications - Performance comparisons ## Conclusion In summary, this article explored various aspects of the topic. Stay tuned for more updates! """ cursor.execute(""" INSERT INTO articles (title, slug, content, author, category, related_apps, featured_image, tags, views) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) """, (title, generate_slug(title), content, author, category, json.dumps(related_ids), image, json.dumps(tags), random.randint(200, 10000))) # Sponsors sponsors_data = [ ("BrightData", "Gold", "https://brightdata.com", "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=728&h=90&fit=crop"), ("ScraperAPI", "Gold", "https://scraperapi.com", "https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=728&h=90&fit=crop"), ("BrowserCloud", "Silver", "https://browsercloud.io", "https://images.unsplash.com/photo-1667372393119-3d4c48d07fc9?w=728&h=90&fit=crop"), ("Claude Extract", "Silver", "https://claude-extract.com", "https://images.unsplash.com/photo-1686191128892-3b09ad503b4f?w=728&h=90&fit=crop"), ("SmartProxy", "Bronze", "https://smartproxy.com", "https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=728&h=90&fit=crop") ] for company, tier, landing_url, banner in sponsors_data: start_date = datetime.now() - timedelta(days=random.randint(1, 30)) end_date = datetime.now() + timedelta(days=random.randint(30, 180)) cursor.execute(""" INSERT INTO sponsors (company_name, logo_url, tier, banner_url, landing_url, active, start_date, end_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, (company, f"https://ui-avatars.com/api/?name={company}&background=09b5a5&color=fff&size=200", tier, banner, landing_url, 1, start_date.isoformat(), end_date.isoformat())) conn.commit() print("โœ“ Dummy data generated successfully!") print(f" - {len(categories)} categories") print(f" - {len(apps_data)} apps") print(f" - {len(articles_data)} articles") print(f" - {len(sponsors_data)} sponsors") if __name__ == "__main__": generate_dummy_data()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/md_v2/marketplace/backend/dummy_data.py", "license": "Apache License 2.0", "lines": 220, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/releases_review/demo_v0.7.5.py
""" ๐Ÿš€ Crawl4AI v0.7.5 Release Demo - Working Examples ================================================== This demo showcases key features introduced in v0.7.5 with real, executable examples. Featured Demos: 1. โœ… Docker Hooks System - Real API calls with custom hooks (string & function-based) 2. โœ… Enhanced LLM Integration - Working LLM configurations 3. โœ… HTTPS Preservation - Live crawling with HTTPS maintenance Requirements: - crawl4ai v0.7.5 installed - Docker running with crawl4ai image (optional for Docker demos) - Valid API keys for LLM demos (optional) """ import asyncio import requests import time import sys from crawl4ai import (AsyncWebCrawler, CrawlerRunConfig, BrowserConfig, CacheMode, FilterChain, URLPatternFilter, BFSDeepCrawlStrategy, hooks_to_string) from crawl4ai.docker_client import Crawl4aiDockerClient def print_section(title: str, description: str = ""): """Print a section header""" print(f"\n{'=' * 60}") print(f"{title}") if description: print(f"{description}") print(f"{'=' * 60}\n") async def demo_1_docker_hooks_system(): """Demo 1: Docker Hooks System - Real API calls with custom hooks""" print_section( "Demo 1: Docker Hooks System", "Testing both string-based and function-based hooks (NEW in v0.7.5!)" ) # Check Docker service availability def check_docker_service(): try: response = requests.get("http://localhost:11235/", timeout=3) return response.status_code == 200 except: return False print("Checking Docker service...") docker_running = check_docker_service() if not docker_running: print("โš ๏ธ Docker service not running on localhost:11235") print("To test Docker hooks:") print("1. Run: docker run -p 11235:11235 unclecode/crawl4ai:latest") print("2. Wait for service to start") print("3. Re-run this demo\n") return print("โœ“ Docker service detected!") # ============================================================================ # PART 1: Traditional String-Based Hooks (Works with REST API) # ============================================================================ print("\n" + "โ”€" * 60) print("Part 1: String-Based Hooks (REST API)") print("โ”€" * 60) hooks_config_string = { "on_page_context_created": """ async def hook(page, context, **kwargs): print("[String Hook] Setting up page context") await context.route("**/*.{png,jpg,jpeg,gif,webp}", lambda route: route.abort()) return page """, "before_retrieve_html": """ async def hook(page, context, **kwargs): print("[String Hook] Before retrieving HTML") await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await page.wait_for_timeout(1000) return page """ } payload = { "urls": ["https://httpbin.org/html"], "hooks": { "code": hooks_config_string, "timeout": 30 } } print("๐Ÿ”ง Using string-based hooks for REST API...") try: start_time = time.time() response = requests.post("http://localhost:11235/crawl", json=payload, timeout=60) execution_time = time.time() - start_time if response.status_code == 200: result = response.json() print(f"โœ… String-based hooks executed in {execution_time:.2f}s") if result.get('results') and result['results'][0].get('success'): html_length = len(result['results'][0].get('html', '')) print(f" ๐Ÿ“„ HTML length: {html_length} characters") else: print(f"โŒ Request failed: {response.status_code}") except Exception as e: print(f"โŒ Error: {str(e)}") # ============================================================================ # PART 2: NEW Function-Based Hooks with Docker Client (v0.7.5) # ============================================================================ print("\n" + "โ”€" * 60) print("Part 2: Function-Based Hooks with Docker Client (โœจ NEW!)") print("โ”€" * 60) # Define hooks as regular Python functions async def on_page_context_created_func(page, context, **kwargs): """Block images to speed up crawling""" print("[Function Hook] Setting up page context") await context.route("**/*.{png,jpg,jpeg,gif,webp}", lambda route: route.abort()) await page.set_viewport_size({"width": 1920, "height": 1080}) return page async def before_goto_func(page, context, url, **kwargs): """Add custom headers before navigation""" print(f"[Function Hook] About to navigate to {url}") await page.set_extra_http_headers({ 'X-Crawl4AI': 'v0.7.5-function-hooks', 'X-Test-Header': 'demo' }) return page async def before_retrieve_html_func(page, context, **kwargs): """Scroll to load lazy content""" print("[Function Hook] Scrolling page for lazy-loaded content") await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await page.wait_for_timeout(500) await page.evaluate("window.scrollTo(0, 0)") return page # Use the hooks_to_string utility (can be used standalone) print("\n๐Ÿ“ฆ Converting functions to strings with hooks_to_string()...") hooks_as_strings = hooks_to_string({ "on_page_context_created": on_page_context_created_func, "before_goto": before_goto_func, "before_retrieve_html": before_retrieve_html_func }) print(f" โœ“ Converted {len(hooks_as_strings)} hooks to string format") # OR use Docker Client which does conversion automatically! print("\n๐Ÿณ Using Docker Client with automatic conversion...") try: client = Crawl4aiDockerClient(base_url="http://localhost:11235") # Pass function objects directly - conversion happens automatically! results = await client.crawl( urls=["https://httpbin.org/html"], hooks={ "on_page_context_created": on_page_context_created_func, "before_goto": before_goto_func, "before_retrieve_html": before_retrieve_html_func }, hooks_timeout=30 ) if results and results.success: print(f"โœ… Function-based hooks executed successfully!") print(f" ๐Ÿ“„ HTML length: {len(results.html)} characters") print(f" ๐ŸŽฏ URL: {results.url}") else: print("โš ๏ธ Crawl completed but may have warnings") except Exception as e: print(f"โŒ Docker client error: {str(e)}") # Show the benefits print("\n" + "=" * 60) print("โœจ Benefits of Function-Based Hooks:") print("=" * 60) print("โœ“ Full IDE support (autocomplete, syntax highlighting)") print("โœ“ Type checking and linting") print("โœ“ Easier to test and debug") print("โœ“ Reusable across projects") print("โœ“ Automatic conversion in Docker client") print("=" * 60) async def demo_2_enhanced_llm_integration(): """Demo 2: Enhanced LLM Integration - Working LLM configurations""" print_section( "Demo 2: Enhanced LLM Integration", "Testing custom LLM providers and configurations" ) print("๐Ÿค– Testing Enhanced LLM Integration Features") provider = "gemini/gemini-2.5-flash-lite" payload = { "url": "https://example.com", "f": "llm", "q": "Summarize this page in one sentence.", "provider": provider, # Explicitly set provider "temperature": 0.7 } try: response = requests.post( "http://localhost:11235/md", json=payload, timeout=60 ) if response.status_code == 200: result = response.json() print(f"โœ“ Request successful with provider: {provider}") print(f" - Response keys: {list(result.keys())}") print(f" - Content length: {len(result.get('markdown', ''))} characters") print(f" - Note: Actual LLM call may fail without valid API key") else: print(f"โŒ Request failed: {response.status_code}") print(f" - Response: {response.text[:500]}") except Exception as e: print(f"[red]Error: {e}[/]") async def demo_3_https_preservation(): """Demo 3: HTTPS Preservation - Live crawling with HTTPS maintenance""" print_section( "Demo 3: HTTPS Preservation", "Testing HTTPS preservation for internal links" ) print("๐Ÿ”’ Testing HTTPS Preservation Feature") # Test with HTTPS preservation enabled print("\nTest 1: HTTPS Preservation ENABLED") url_filter = URLPatternFilter( patterns=["^(https:\/\/)?quotes\.toscrape\.com(\/.*)?$"] ) config = CrawlerRunConfig( exclude_external_links=True, stream=True, verbose=False, preserve_https_for_internal_links=True, deep_crawl_strategy=BFSDeepCrawlStrategy( max_depth=2, max_pages=5, filter_chain=FilterChain([url_filter]) ) ) test_url = "https://quotes.toscrape.com" print(f"๐ŸŽฏ Testing URL: {test_url}") async with AsyncWebCrawler() as crawler: async for result in await crawler.arun(url=test_url, config=config): print("โœ“ HTTPS Preservation Test Completed") internal_links = [i['href'] for i in result.links['internal']] for link in internal_links: print(f" โ†’ {link}") async def main(): """Run all demos""" print("\n" + "=" * 60) print("๐Ÿš€ Crawl4AI v0.7.5 Working Demo") print("=" * 60) # Check system requirements print("๐Ÿ” System Requirements Check:") print(f" - Python version: {sys.version.split()[0]} {'โœ“' if sys.version_info >= (3, 10) else 'โŒ (3.10+ required)'}") try: import requests print(f" - Requests library: โœ“") except ImportError: print(f" - Requests library: โŒ") print() demos = [ ("Docker Hooks System", demo_1_docker_hooks_system), ("Enhanced LLM Integration", demo_2_enhanced_llm_integration), ("HTTPS Preservation", demo_3_https_preservation), ] for i, (name, demo_func) in enumerate(demos, 1): try: print(f"\n๐Ÿ“ Starting Demo {i}/{len(demos)}: {name}") await demo_func() if i < len(demos): print(f"\nโœจ Demo {i} complete! Press Enter for next demo...") input() except KeyboardInterrupt: print(f"\nโน๏ธ Demo interrupted by user") break except Exception as e: print(f"โŒ Demo {i} error: {str(e)}") print("Continuing to next demo...") continue print("\n" + "=" * 60) print("๐ŸŽ‰ Demo Complete!") print("=" * 60) print("You've experienced the power of Crawl4AI v0.7.5!") print("") print("Key Features Demonstrated:") print("๐Ÿ”ง Docker Hooks - String-based & function-based (NEW!)") print(" โ€ข hooks_to_string() utility for function conversion") print(" โ€ข Docker client with automatic conversion") print(" โ€ข Full IDE support and type checking") print("๐Ÿค– Enhanced LLM - Better AI integration") print("๐Ÿ”’ HTTPS Preservation - Secure link handling") print("") print("Ready to build something amazing? ๐Ÿš€") print("") print("๐Ÿ“– Docs: https://docs.crawl4ai.com/") print("๐Ÿ™ GitHub: https://github.com/unclecode/crawl4ai") print("=" * 60) if __name__ == "__main__": print("๐Ÿš€ Crawl4AI v0.7.5 Live Demo Starting...") print("Press Ctrl+C anytime to exit\n") try: asyncio.run(main()) except KeyboardInterrupt: print("\n๐Ÿ‘‹ Demo stopped by user. Thanks for trying Crawl4AI v0.7.5!") except Exception as e: print(f"\nโŒ Demo error: {str(e)}") print("Make sure you have the required dependencies installed.")
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/releases_review/demo_v0.7.5.py", "license": "Apache License 2.0", "lines": 286, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/releases_review/v0.7.5_docker_hooks_demo.py
#!/usr/bin/env python3 """ ๐Ÿš€ Crawl4AI v0.7.5 - Docker Hooks System Complete Demonstration ================================================================ This file demonstrates the NEW Docker Hooks System introduced in v0.7.5. The Docker Hooks System is a completely NEW feature that provides pipeline customization through user-provided Python functions. It offers three approaches: 1. String-based hooks for REST API 2. hooks_to_string() utility to convert functions 3. Docker Client with automatic conversion (most convenient) All three approaches are part of this NEW v0.7.5 feature! Perfect for video recording and demonstration purposes. Requirements: - Docker container running: docker run -p 11235:11235 unclecode/crawl4ai:latest - crawl4ai v0.7.5 installed: pip install crawl4ai==0.7.5 """ import asyncio import requests import json import time from typing import Dict, Any # Import Crawl4AI components from crawl4ai import hooks_to_string from crawl4ai.docker_client import Crawl4aiDockerClient # Configuration DOCKER_URL = "http://localhost:11235" # DOCKER_URL = "http://localhost:11234" TEST_URLS = [ # "https://httpbin.org/html", "https://www.kidocode.com", "https://quotes.toscrape.com", ] def print_section(title: str, description: str = ""): """Print a formatted section header""" print("\n" + "=" * 70) print(f" {title}") if description: print(f" {description}") print("=" * 70 + "\n") def check_docker_service() -> bool: """Check if Docker service is running""" try: response = requests.get(f"{DOCKER_URL}/health", timeout=3) return response.status_code == 200 except: return False # ============================================================================ # REUSABLE HOOK LIBRARY (NEW in v0.7.5) # ============================================================================ async def performance_optimization_hook(page, context, **kwargs): """ Performance Hook: Block unnecessary resources to speed up crawling """ print(" [Hook] ๐Ÿš€ Optimizing performance - blocking images and ads...") # Block images await context.route( "**/*.{png,jpg,jpeg,gif,webp,svg,ico}", lambda route: route.abort() ) # Block ads and analytics await context.route("**/analytics/*", lambda route: route.abort()) await context.route("**/ads/*", lambda route: route.abort()) await context.route("**/google-analytics.com/*", lambda route: route.abort()) print(" [Hook] โœ“ Performance optimization applied") return page async def viewport_setup_hook(page, context, **kwargs): """ Viewport Hook: Set consistent viewport size for rendering """ print(" [Hook] ๐Ÿ–ฅ๏ธ Setting viewport to 1920x1080...") await page.set_viewport_size({"width": 1920, "height": 1080}) print(" [Hook] โœ“ Viewport configured") return page async def authentication_headers_hook(page, context, url, **kwargs): """ Headers Hook: Add custom authentication and tracking headers """ print(f" [Hook] ๐Ÿ” Adding custom headers for {url[:50]}...") await page.set_extra_http_headers({ 'X-Crawl4AI-Version': '0.7.5', 'X-Custom-Hook': 'function-based-demo', 'Accept-Language': 'en-US,en;q=0.9', 'User-Agent': 'Crawl4AI/0.7.5 (Educational Demo)' }) print(" [Hook] โœ“ Custom headers added") return page async def lazy_loading_handler_hook(page, context, **kwargs): """ Content Hook: Handle lazy-loaded content by scrolling """ print(" [Hook] ๐Ÿ“œ Scrolling to load lazy content...") # Scroll to bottom await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await page.wait_for_timeout(1000) # Scroll to middle await page.evaluate("window.scrollTo(0, document.body.scrollHeight / 2)") await page.wait_for_timeout(500) # Scroll back to top await page.evaluate("window.scrollTo(0, 0)") await page.wait_for_timeout(500) print(" [Hook] โœ“ Lazy content loaded") return page async def page_analytics_hook(page, context, **kwargs): """ Analytics Hook: Log page metrics before extraction """ print(" [Hook] ๐Ÿ“Š Collecting page analytics...") metrics = await page.evaluate(''' () => ({ title: document.title, images: document.images.length, links: document.links.length, scripts: document.scripts.length, headings: document.querySelectorAll('h1, h2, h3').length, paragraphs: document.querySelectorAll('p').length }) ''') print(f" [Hook] ๐Ÿ“ˆ Page: {metrics['title'][:50]}...") print(f" Links: {metrics['links']}, Images: {metrics['images']}, " f"Headings: {metrics['headings']}, Paragraphs: {metrics['paragraphs']}") return page # ============================================================================ # DEMO 1: String-Based Hooks (NEW Docker Hooks System) # ============================================================================ def demo_1_string_based_hooks(): """ Demonstrate string-based hooks with REST API (part of NEW Docker Hooks System) """ print_section( "DEMO 1: String-Based Hooks (REST API)", "Part of the NEW Docker Hooks System - hooks as strings" ) # Define hooks as strings hooks_config = { "on_page_context_created": """ async def hook(page, context, **kwargs): print(" [String Hook] Setting up page context...") # Block images for performance await context.route("**/*.{png,jpg,jpeg,gif,webp}", lambda route: route.abort()) await page.set_viewport_size({"width": 1920, "height": 1080}) return page """, "before_goto": """ async def hook(page, context, url, **kwargs): print(f" [String Hook] Navigating to {url[:50]}...") await page.set_extra_http_headers({ 'X-Crawl4AI': 'string-based-hooks', 'X-Demo': 'v0.7.5' }) return page """, "before_retrieve_html": """ async def hook(page, context, **kwargs): print(" [String Hook] Scrolling page...") await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await page.wait_for_timeout(1000) return page """ } # Prepare request payload payload = { "urls": [TEST_URLS[0]], "hooks": { "code": hooks_config, "timeout": 30 }, "crawler_config": { "cache_mode": "bypass" } } print(f"๐ŸŽฏ Target URL: {TEST_URLS[0]}") print(f"๐Ÿ”ง Configured {len(hooks_config)} string-based hooks") print(f"๐Ÿ“ก Sending request to Docker API...\n") try: start_time = time.time() response = requests.post(f"{DOCKER_URL}/crawl", json=payload, timeout=60) execution_time = time.time() - start_time if response.status_code == 200: result = response.json() print(f"\nโœ… Request successful! (took {execution_time:.2f}s)") # Display results if result.get('results') and result['results'][0].get('success'): crawl_result = result['results'][0] html_length = len(crawl_result.get('html', '')) markdown_length = len(crawl_result.get('markdown', '')) print(f"\n๐Ÿ“Š Results:") print(f" โ€ข HTML length: {html_length:,} characters") print(f" โ€ข Markdown length: {markdown_length:,} characters") print(f" โ€ข URL: {crawl_result.get('url')}") # Check hooks execution if 'hooks' in result: hooks_info = result['hooks'] print(f"\n๐ŸŽฃ Hooks Execution:") print(f" โ€ข Status: {hooks_info['status']['status']}") print(f" โ€ข Attached hooks: {len(hooks_info['status']['attached_hooks'])}") if 'summary' in hooks_info: summary = hooks_info['summary'] print(f" โ€ข Total executions: {summary['total_executions']}") print(f" โ€ข Successful: {summary['successful']}") print(f" โ€ข Success rate: {summary['success_rate']:.1f}%") else: print(f"โš ๏ธ Crawl completed but no results") else: print(f"โŒ Request failed with status {response.status_code}") print(f" Error: {response.text[:200]}") except requests.exceptions.Timeout: print("โฐ Request timed out after 60 seconds") except Exception as e: print(f"โŒ Error: {str(e)}") print("\n" + "โ”€" * 70) print("โœ“ String-based hooks demo complete\n") # ============================================================================ # DEMO 2: Function-Based Hooks with hooks_to_string() Utility # ============================================================================ def demo_2_hooks_to_string_utility(): """ Demonstrate the new hooks_to_string() utility for converting functions """ print_section( "DEMO 2: hooks_to_string() Utility (NEW! โœจ)", "Convert Python functions to strings for REST API" ) print("๐Ÿ“ฆ Creating hook functions...") print(" โ€ข performance_optimization_hook") print(" โ€ข viewport_setup_hook") print(" โ€ข authentication_headers_hook") print(" โ€ข lazy_loading_handler_hook") # Convert function objects to strings using the NEW utility print("\n๐Ÿ”„ Converting functions to strings with hooks_to_string()...") hooks_dict = { "on_page_context_created": performance_optimization_hook, "before_goto": authentication_headers_hook, "before_retrieve_html": lazy_loading_handler_hook, } hooks_as_strings = hooks_to_string(hooks_dict) print(f"โœ… Successfully converted {len(hooks_as_strings)} functions to strings") # Show a preview print("\n๐Ÿ“ Sample converted hook (first 250 characters):") print("โ”€" * 70) sample_hook = list(hooks_as_strings.values())[0] print(sample_hook[:250] + "...") print("โ”€" * 70) # Use the converted hooks with REST API print("\n๐Ÿ“ก Using converted hooks with REST API...") payload = { "urls": [TEST_URLS[0]], "hooks": { "code": hooks_as_strings, "timeout": 30 } } try: start_time = time.time() response = requests.post(f"{DOCKER_URL}/crawl", json=payload, timeout=60) execution_time = time.time() - start_time if response.status_code == 200: result = response.json() print(f"\nโœ… Request successful! (took {execution_time:.2f}s)") if result.get('results') and result['results'][0].get('success'): crawl_result = result['results'][0] print(f" โ€ข HTML length: {len(crawl_result.get('html', '')):,} characters") print(f" โ€ข Hooks executed successfully!") else: print(f"โŒ Request failed: {response.status_code}") except Exception as e: print(f"โŒ Error: {str(e)}") print("\n๐Ÿ’ก Benefits of hooks_to_string():") print(" โœ“ Write hooks as regular Python functions") print(" โœ“ Full IDE support (autocomplete, syntax highlighting)") print(" โœ“ Type checking and linting") print(" โœ“ Easy to test and debug") print(" โœ“ Reusable across projects") print(" โœ“ Works with any REST API client") print("\n" + "โ”€" * 70) print("โœ“ hooks_to_string() utility demo complete\n") # ============================================================================ # DEMO 3: Docker Client with Automatic Conversion (RECOMMENDED! ๐ŸŒŸ) # ============================================================================ async def demo_3_docker_client_auto_conversion(): """ Demonstrate Docker Client with automatic hook conversion (RECOMMENDED) """ print_section( "DEMO 3: Docker Client with Auto-Conversion (RECOMMENDED! ๐ŸŒŸ)", "Pass function objects directly - conversion happens automatically!" ) print("๐Ÿณ Initializing Crawl4AI Docker Client...") client = Crawl4aiDockerClient(base_url=DOCKER_URL) print("โœ… Client ready!\n") # Use our reusable hook library - just pass the function objects! print("๐Ÿ“š Using reusable hook library:") print(" โ€ข performance_optimization_hook") print(" โ€ข viewport_setup_hook") print(" โ€ข authentication_headers_hook") print(" โ€ข lazy_loading_handler_hook") print(" โ€ข page_analytics_hook") print("\n๐ŸŽฏ Target URL: " + TEST_URLS[1]) print("๐Ÿš€ Starting crawl with automatic hook conversion...\n") try: start_time = time.time() # Pass function objects directly - NO manual conversion needed! โœจ results = await client.crawl( urls=[TEST_URLS[0]], hooks={ "on_page_context_created": performance_optimization_hook, "before_goto": authentication_headers_hook, "before_retrieve_html": lazy_loading_handler_hook, "before_return_html": page_analytics_hook, }, hooks_timeout=30 ) execution_time = time.time() - start_time print(f"\nโœ… Crawl completed! (took {execution_time:.2f}s)\n") # Display results if results and results.success: result = results print(f"๐Ÿ“Š Results:") print(f" โ€ข URL: {result.url}") print(f" โ€ข Success: {result.success}") print(f" โ€ข HTML length: {len(result.html):,} characters") print(f" โ€ข Markdown length: {len(result.markdown):,} characters") # Show metadata if result.metadata: print(f"\n๐Ÿ“‹ Metadata:") print(f" โ€ข Title: {result.metadata.get('title', 'N/A')}") print(f" โ€ข Description: {result.metadata.get('description', 'N/A')}") # Show links if result.links: internal_count = len(result.links.get('internal', [])) external_count = len(result.links.get('external', [])) print(f"\n๐Ÿ”— Links Found:") print(f" โ€ข Internal: {internal_count}") print(f" โ€ข External: {external_count}") else: print(f"โš ๏ธ Crawl completed but no successful results") if results: print(f" Error: {results.error_message}") except Exception as e: print(f"โŒ Error: {str(e)}") import traceback traceback.print_exc() print("\n๐ŸŒŸ Why Docker Client is RECOMMENDED:") print(" โœ“ Automatic function-to-string conversion") print(" โœ“ No manual hooks_to_string() calls needed") print(" โœ“ Cleaner, more Pythonic code") print(" โœ“ Full type hints and IDE support") print(" โœ“ Built-in error handling") print(" โœ“ Async/await support") print("\n" + "โ”€" * 70) print("โœ“ Docker Client auto-conversion demo complete\n") # ============================================================================ # DEMO 4: Advanced Use Case - Complete Hook Pipeline # ============================================================================ async def demo_4_complete_hook_pipeline(): """ Demonstrate a complete hook pipeline using all 8 hook points """ print_section( "DEMO 4: Complete Hook Pipeline", "Using all 8 available hook points for comprehensive control" ) # Define all 8 hooks async def on_browser_created_hook(browser, **kwargs): """Hook 1: Called after browser is created""" print(" [Pipeline] 1/8 Browser created") return browser async def on_page_context_created_hook(page, context, **kwargs): """Hook 2: Called after page context is created""" print(" [Pipeline] 2/8 Page context created - setting up...") await page.set_viewport_size({"width": 1920, "height": 1080}) return page async def on_user_agent_updated_hook(page, context, user_agent, **kwargs): """Hook 3: Called when user agent is updated""" print(f" [Pipeline] 3/8 User agent updated: {user_agent[:50]}...") return page async def before_goto_hook(page, context, url, **kwargs): """Hook 4: Called before navigating to URL""" print(f" [Pipeline] 4/8 Before navigation to: {url[:60]}...") return page async def after_goto_hook(page, context, url, response, **kwargs): """Hook 5: Called after navigation completes""" print(f" [Pipeline] 5/8 After navigation - Status: {response.status if response else 'N/A'}") await page.wait_for_timeout(1000) return page async def on_execution_started_hook(page, context, **kwargs): """Hook 6: Called when JavaScript execution starts""" print(" [Pipeline] 6/8 JavaScript execution started") return page async def before_retrieve_html_hook(page, context, **kwargs): """Hook 7: Called before retrieving HTML""" print(" [Pipeline] 7/8 Before HTML retrieval - scrolling...") await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") return page async def before_return_html_hook(page, context, html, **kwargs): """Hook 8: Called before returning HTML""" print(f" [Pipeline] 8/8 Before return - HTML length: {len(html):,} chars") return page print("๐ŸŽฏ Target URL: " + TEST_URLS[0]) print("๐Ÿ”ง Configured ALL 8 hook points for complete pipeline control\n") client = Crawl4aiDockerClient(base_url=DOCKER_URL) try: print("๐Ÿš€ Starting complete pipeline crawl...\n") start_time = time.time() results = await client.crawl( urls=[TEST_URLS[0]], hooks={ "on_browser_created": on_browser_created_hook, "on_page_context_created": on_page_context_created_hook, "on_user_agent_updated": on_user_agent_updated_hook, "before_goto": before_goto_hook, "after_goto": after_goto_hook, "on_execution_started": on_execution_started_hook, "before_retrieve_html": before_retrieve_html_hook, "before_return_html": before_return_html_hook, }, hooks_timeout=45 ) execution_time = time.time() - start_time if results and results.success: print(f"\nโœ… Complete pipeline executed successfully! (took {execution_time:.2f}s)") print(f" โ€ข All 8 hooks executed in sequence") print(f" โ€ข HTML length: {len(results.html):,} characters") else: print(f"โš ๏ธ Pipeline completed with warnings") except Exception as e: print(f"โŒ Error: {str(e)}") print("\n๐Ÿ“š Available Hook Points:") print(" 1. on_browser_created - Browser initialization") print(" 2. on_page_context_created - Page context setup") print(" 3. on_user_agent_updated - User agent configuration") print(" 4. before_goto - Pre-navigation setup") print(" 5. after_goto - Post-navigation processing") print(" 6. on_execution_started - JavaScript execution start") print(" 7. before_retrieve_html - Pre-extraction processing") print(" 8. before_return_html - Final HTML processing") print("\n" + "โ”€" * 70) print("โœ“ Complete hook pipeline demo complete\n") # ============================================================================ # MAIN EXECUTION # ============================================================================ async def main(): """ Run all demonstrations """ print("\n" + "=" * 70) print(" ๐Ÿš€ Crawl4AI v0.7.5 - Docker Hooks Complete Demonstration") print("=" * 70) # Check Docker service print("\n๐Ÿ” Checking Docker service status...") if not check_docker_service(): print("โŒ Docker service is not running!") print("\n๐Ÿ“‹ To start the Docker service:") print(" docker run -p 11235:11235 unclecode/crawl4ai:latest") print("\nPlease start the service and run this demo again.") return print("โœ… Docker service is running!\n") # Run all demos demos = [ ("String-Based Hooks (REST API)", demo_1_string_based_hooks, False), ("hooks_to_string() Utility", demo_2_hooks_to_string_utility, False), ("Docker Client Auto-Conversion", demo_3_docker_client_auto_conversion, True), # ("Complete Hook Pipeline", demo_4_complete_hook_pipeline, True), ] for i, (name, demo_func, is_async) in enumerate(demos, 1): print(f"\n{'๐Ÿ”ท' * 35}") print(f"Starting Demo {i}/{len(demos)}: {name}") print(f"{'๐Ÿ”ท' * 35}\n") try: if is_async: await demo_func() else: demo_func() print(f"โœ… Demo {i} completed successfully!") # Pause between demos (except the last one) if i < len(demos): print("\nโธ๏ธ Press Enter to continue to next demo...") # input() except KeyboardInterrupt: print(f"\nโน๏ธ Demo interrupted by user") break except Exception as e: print(f"\nโŒ Demo {i} failed: {str(e)}") import traceback traceback.print_exc() print("\nContinuing to next demo...\n") continue # Final summary print("\n" + "=" * 70) print(" ๐ŸŽ‰ All Demonstrations Complete!") print("=" * 70) print("\n๐Ÿ“Š Summary of v0.7.5 Docker Hooks System:") print("\n๐Ÿ†• COMPLETELY NEW FEATURE in v0.7.5:") print(" The Docker Hooks System lets you customize the crawling pipeline") print(" with user-provided Python functions at 8 strategic points.") print("\nโœจ Three Ways to Use Docker Hooks (All NEW!):") print(" 1. String-based - Write hooks as strings for REST API") print(" 2. hooks_to_string() - Convert Python functions to strings") print(" 3. Docker Client - Automatic conversion (RECOMMENDED)") print("\n๐Ÿ’ก Key Benefits:") print(" โœ“ Full IDE support (autocomplete, syntax highlighting)") print(" โœ“ Type checking and linting") print(" โœ“ Easy to test and debug") print(" โœ“ Reusable across projects") print(" โœ“ Complete pipeline control") print("\n๐ŸŽฏ 8 Hook Points Available:") print(" โ€ข on_browser_created, on_page_context_created") print(" โ€ข on_user_agent_updated, before_goto, after_goto") print(" โ€ข on_execution_started, before_retrieve_html, before_return_html") print("\n๐Ÿ“š Resources:") print(" โ€ข Docs: https://docs.crawl4ai.com") print(" โ€ข GitHub: https://github.com/unclecode/crawl4ai") print(" โ€ข Discord: https://discord.gg/jP8KfhDhyN") print("\n" + "=" * 70) print(" Happy Crawling with v0.7.5! ๐Ÿ•ท๏ธ") print("=" * 70 + "\n") if __name__ == "__main__": print("\n๐ŸŽฌ Starting Crawl4AI v0.7.5 Docker Hooks Demonstration...") print("Press Ctrl+C anytime to exit\n") try: asyncio.run(main()) except KeyboardInterrupt: print("\n\n๐Ÿ‘‹ Demo stopped by user. Thanks for exploring Crawl4AI v0.7.5!") except Exception as e: print(f"\n\nโŒ Demo error: {str(e)}") import traceback traceback.print_exc()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/releases_review/v0.7.5_docker_hooks_demo.py", "license": "Apache License 2.0", "lines": 526, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:test_llm_webhook_feature.py
#!/usr/bin/env python3 """ Test script to validate webhook implementation for /llm/job endpoint. This tests that the /llm/job endpoint now supports webhooks following the same pattern as /crawl/job. """ import sys import os # Add deploy/docker to path sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'deploy', 'docker')) def test_llm_job_payload_model(): """Test that LlmJobPayload includes webhook_config field""" print("=" * 60) print("TEST 1: LlmJobPayload Model") print("=" * 60) try: from job import LlmJobPayload from schemas import WebhookConfig from pydantic import ValidationError # Test with webhook_config payload_dict = { "url": "https://example.com", "q": "Extract main content", "schema": None, "cache": False, "provider": None, "webhook_config": { "webhook_url": "https://myapp.com/webhook", "webhook_data_in_payload": True, "webhook_headers": {"X-Secret": "token"} } } payload = LlmJobPayload(**payload_dict) print(f"โœ… LlmJobPayload accepts webhook_config") print(f" - URL: {payload.url}") print(f" - Query: {payload.q}") print(f" - Webhook URL: {payload.webhook_config.webhook_url}") print(f" - Data in payload: {payload.webhook_config.webhook_data_in_payload}") # Test without webhook_config (should be optional) minimal_payload = { "url": "https://example.com", "q": "Extract content" } payload2 = LlmJobPayload(**minimal_payload) assert payload2.webhook_config is None, "webhook_config should be optional" print(f"โœ… LlmJobPayload works without webhook_config (optional)") return True except Exception as e: print(f"โŒ Failed: {e}") import traceback traceback.print_exc() return False def test_handle_llm_request_signature(): """Test that handle_llm_request accepts webhook_config parameter""" print("\n" + "=" * 60) print("TEST 2: handle_llm_request Function Signature") print("=" * 60) try: from api import handle_llm_request import inspect sig = inspect.signature(handle_llm_request) params = list(sig.parameters.keys()) print(f"Function parameters: {params}") if 'webhook_config' in params: print(f"โœ… handle_llm_request has webhook_config parameter") # Check that it's optional with default None webhook_param = sig.parameters['webhook_config'] if webhook_param.default is None or webhook_param.default == inspect.Parameter.empty: print(f"โœ… webhook_config is optional (default: {webhook_param.default})") else: print(f"โš ๏ธ webhook_config default is: {webhook_param.default}") return True else: print(f"โŒ handle_llm_request missing webhook_config parameter") return False except Exception as e: print(f"โŒ Failed: {e}") import traceback traceback.print_exc() return False def test_process_llm_extraction_signature(): """Test that process_llm_extraction accepts webhook_config parameter""" print("\n" + "=" * 60) print("TEST 3: process_llm_extraction Function Signature") print("=" * 60) try: from api import process_llm_extraction import inspect sig = inspect.signature(process_llm_extraction) params = list(sig.parameters.keys()) print(f"Function parameters: {params}") if 'webhook_config' in params: print(f"โœ… process_llm_extraction has webhook_config parameter") webhook_param = sig.parameters['webhook_config'] if webhook_param.default is None or webhook_param.default == inspect.Parameter.empty: print(f"โœ… webhook_config is optional (default: {webhook_param.default})") else: print(f"โš ๏ธ webhook_config default is: {webhook_param.default}") return True else: print(f"โŒ process_llm_extraction missing webhook_config parameter") return False except Exception as e: print(f"โŒ Failed: {e}") import traceback traceback.print_exc() return False def test_webhook_integration_in_api(): """Test that api.py properly integrates webhook notifications""" print("\n" + "=" * 60) print("TEST 4: Webhook Integration in process_llm_extraction") print("=" * 60) try: api_file = os.path.join(os.path.dirname(__file__), 'deploy', 'docker', 'api.py') with open(api_file, 'r') as f: api_content = f.read() # Check for WebhookDeliveryService initialization if 'webhook_service = WebhookDeliveryService(config)' in api_content: print("โœ… process_llm_extraction initializes WebhookDeliveryService") else: print("โŒ Missing WebhookDeliveryService initialization in process_llm_extraction") return False # Check for notify_job_completion calls with llm_extraction if 'task_type="llm_extraction"' in api_content: print("โœ… Uses correct task_type='llm_extraction' for notifications") else: print("โŒ Missing task_type='llm_extraction' in webhook notifications") return False # Count webhook notification calls (should have at least 3: success + 2 failure paths) notification_count = api_content.count('await webhook_service.notify_job_completion') # Find only in process_llm_extraction function llm_func_start = api_content.find('async def process_llm_extraction') llm_func_end = api_content.find('\nasync def ', llm_func_start + 1) if llm_func_end == -1: llm_func_end = len(api_content) llm_func_content = api_content[llm_func_start:llm_func_end] llm_notification_count = llm_func_content.count('await webhook_service.notify_job_completion') print(f"โœ… Found {llm_notification_count} webhook notification calls in process_llm_extraction") if llm_notification_count >= 3: print(f"โœ… Sufficient notification points (success + failure paths)") else: print(f"โš ๏ธ Expected at least 3 notification calls, found {llm_notification_count}") return True except Exception as e: print(f"โŒ Failed: {e}") import traceback traceback.print_exc() return False def test_job_endpoint_integration(): """Test that /llm/job endpoint extracts and passes webhook_config""" print("\n" + "=" * 60) print("TEST 5: /llm/job Endpoint Integration") print("=" * 60) try: job_file = os.path.join(os.path.dirname(__file__), 'deploy', 'docker', 'job.py') with open(job_file, 'r') as f: job_content = f.read() # Find the llm_job_enqueue function llm_job_start = job_content.find('async def llm_job_enqueue') llm_job_end = job_content.find('\n\n@router', llm_job_start + 1) if llm_job_end == -1: llm_job_end = job_content.find('\n\nasync def', llm_job_start + 1) llm_job_func = job_content[llm_job_start:llm_job_end] # Check for webhook_config extraction if 'webhook_config = None' in llm_job_func: print("โœ… llm_job_enqueue initializes webhook_config variable") else: print("โŒ Missing webhook_config initialization") return False if 'if payload.webhook_config:' in llm_job_func: print("โœ… llm_job_enqueue checks for payload.webhook_config") else: print("โŒ Missing webhook_config check") return False if 'webhook_config = payload.webhook_config.model_dump(mode=\'json\')' in llm_job_func: print("โœ… llm_job_enqueue converts webhook_config to dict") else: print("โŒ Missing webhook_config.model_dump conversion") return False if 'webhook_config=webhook_config' in llm_job_func: print("โœ… llm_job_enqueue passes webhook_config to handle_llm_request") else: print("โŒ Missing webhook_config parameter in handle_llm_request call") return False return True except Exception as e: print(f"โŒ Failed: {e}") import traceback traceback.print_exc() return False def test_create_new_task_integration(): """Test that create_new_task stores webhook_config in Redis""" print("\n" + "=" * 60) print("TEST 6: create_new_task Webhook Storage") print("=" * 60) try: api_file = os.path.join(os.path.dirname(__file__), 'deploy', 'docker', 'api.py') with open(api_file, 'r') as f: api_content = f.read() # Find create_new_task function create_task_start = api_content.find('async def create_new_task') create_task_end = api_content.find('\nasync def ', create_task_start + 1) if create_task_end == -1: create_task_end = len(api_content) create_task_func = api_content[create_task_start:create_task_end] # Check for webhook_config storage if 'if webhook_config:' in create_task_func: print("โœ… create_new_task checks for webhook_config") else: print("โŒ Missing webhook_config check in create_new_task") return False if 'task_data["webhook_config"] = json.dumps(webhook_config)' in create_task_func: print("โœ… create_new_task stores webhook_config in Redis task data") else: print("โŒ Missing webhook_config storage in task_data") return False # Check that webhook_config is passed to process_llm_extraction if 'webhook_config' in create_task_func and 'background_tasks.add_task' in create_task_func: print("โœ… create_new_task passes webhook_config to background task") else: print("โš ๏ธ Could not verify webhook_config passed to background task") return True except Exception as e: print(f"โŒ Failed: {e}") import traceback traceback.print_exc() return False def test_pattern_consistency(): """Test that /llm/job follows the same pattern as /crawl/job""" print("\n" + "=" * 60) print("TEST 7: Pattern Consistency with /crawl/job") print("=" * 60) try: api_file = os.path.join(os.path.dirname(__file__), 'deploy', 'docker', 'api.py') with open(api_file, 'r') as f: api_content = f.read() # Find handle_crawl_job to compare pattern crawl_job_start = api_content.find('async def handle_crawl_job') crawl_job_end = api_content.find('\nasync def ', crawl_job_start + 1) if crawl_job_end == -1: crawl_job_end = len(api_content) crawl_job_func = api_content[crawl_job_start:crawl_job_end] # Find process_llm_extraction llm_extract_start = api_content.find('async def process_llm_extraction') llm_extract_end = api_content.find('\nasync def ', llm_extract_start + 1) if llm_extract_end == -1: llm_extract_end = len(api_content) llm_extract_func = api_content[llm_extract_start:llm_extract_end] print("Checking pattern consistency...") # Both should initialize WebhookDeliveryService crawl_has_service = 'webhook_service = WebhookDeliveryService(config)' in crawl_job_func llm_has_service = 'webhook_service = WebhookDeliveryService(config)' in llm_extract_func if crawl_has_service and llm_has_service: print("โœ… Both initialize WebhookDeliveryService") else: print(f"โŒ Service initialization mismatch (crawl: {crawl_has_service}, llm: {llm_has_service})") return False # Both should call notify_job_completion on success crawl_notifies_success = 'status="completed"' in crawl_job_func and 'notify_job_completion' in crawl_job_func llm_notifies_success = 'status="completed"' in llm_extract_func and 'notify_job_completion' in llm_extract_func if crawl_notifies_success and llm_notifies_success: print("โœ… Both notify on success") else: print(f"โŒ Success notification mismatch (crawl: {crawl_notifies_success}, llm: {llm_notifies_success})") return False # Both should call notify_job_completion on failure crawl_notifies_failure = 'status="failed"' in crawl_job_func and 'error=' in crawl_job_func llm_notifies_failure = 'status="failed"' in llm_extract_func and 'error=' in llm_extract_func if crawl_notifies_failure and llm_notifies_failure: print("โœ… Both notify on failure") else: print(f"โŒ Failure notification mismatch (crawl: {crawl_notifies_failure}, llm: {llm_notifies_failure})") return False print("โœ… /llm/job follows the same pattern as /crawl/job") return True except Exception as e: print(f"โŒ Failed: {e}") import traceback traceback.print_exc() return False def main(): """Run all tests""" print("\n๐Ÿงช LLM Job Webhook Feature Validation") print("=" * 60) print("Testing that /llm/job now supports webhooks like /crawl/job") print("=" * 60 + "\n") results = [] # Run all tests results.append(("LlmJobPayload Model", test_llm_job_payload_model())) results.append(("handle_llm_request Signature", test_handle_llm_request_signature())) results.append(("process_llm_extraction Signature", test_process_llm_extraction_signature())) results.append(("Webhook Integration", test_webhook_integration_in_api())) results.append(("/llm/job Endpoint", test_job_endpoint_integration())) results.append(("create_new_task Storage", test_create_new_task_integration())) results.append(("Pattern Consistency", test_pattern_consistency())) # Print summary print("\n" + "=" * 60) print("TEST SUMMARY") print("=" * 60) passed = sum(1 for _, result in results if result) total = len(results) for test_name, result in results: status = "โœ… PASS" if result else "โŒ FAIL" print(f"{status} - {test_name}") print(f"\n{'=' * 60}") print(f"Results: {passed}/{total} tests passed") print(f"{'=' * 60}") if passed == total: print("\n๐ŸŽ‰ All tests passed! /llm/job webhook feature is correctly implemented.") print("\n๐Ÿ“ Summary of changes:") print(" 1. LlmJobPayload model includes webhook_config field") print(" 2. /llm/job endpoint extracts and passes webhook_config") print(" 3. handle_llm_request accepts webhook_config parameter") print(" 4. create_new_task stores webhook_config in Redis") print(" 5. process_llm_extraction sends webhook notifications") print(" 6. Follows the same pattern as /crawl/job") return 0 else: print(f"\nโš ๏ธ {total - passed} test(s) failed. Please review the output above.") return 1 if __name__ == "__main__": exit(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "test_llm_webhook_feature.py", "license": "Apache License 2.0", "lines": 322, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:test_webhook_implementation.py
""" Simple test script to validate webhook implementation without running full server. This script tests: 1. Webhook module imports and syntax 2. WebhookDeliveryService initialization 3. Payload construction logic 4. Configuration parsing """ import sys import os import json from datetime import datetime, timezone # Add deploy/docker to path to import modules # sys.path.insert(0, '/home/user/crawl4ai/deploy/docker') sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'deploy', 'docker')) def test_imports(): """Test that all webhook-related modules can be imported""" print("=" * 60) print("TEST 1: Module Imports") print("=" * 60) try: from webhook import WebhookDeliveryService print("โœ… webhook.WebhookDeliveryService imported successfully") except Exception as e: print(f"โŒ Failed to import webhook module: {e}") return False try: from schemas import WebhookConfig, WebhookPayload print("โœ… schemas.WebhookConfig imported successfully") print("โœ… schemas.WebhookPayload imported successfully") except Exception as e: print(f"โŒ Failed to import schemas: {e}") return False return True def test_webhook_service_init(): """Test WebhookDeliveryService initialization""" print("\n" + "=" * 60) print("TEST 2: WebhookDeliveryService Initialization") print("=" * 60) try: from webhook import WebhookDeliveryService # Test with default config config = { "webhooks": { "enabled": True, "default_url": None, "data_in_payload": False, "retry": { "max_attempts": 5, "initial_delay_ms": 1000, "max_delay_ms": 32000, "timeout_ms": 30000 }, "headers": { "User-Agent": "Crawl4AI-Webhook/1.0" } } } service = WebhookDeliveryService(config) print(f"โœ… Service initialized successfully") print(f" - Max attempts: {service.max_attempts}") print(f" - Initial delay: {service.initial_delay}s") print(f" - Max delay: {service.max_delay}s") print(f" - Timeout: {service.timeout}s") # Verify calculations assert service.max_attempts == 5, "Max attempts should be 5" assert service.initial_delay == 1.0, "Initial delay should be 1.0s" assert service.max_delay == 32.0, "Max delay should be 32.0s" assert service.timeout == 30.0, "Timeout should be 30.0s" print("โœ… All configuration values correct") return True except Exception as e: print(f"โŒ Service initialization failed: {e}") import traceback traceback.print_exc() return False def test_webhook_config_model(): """Test WebhookConfig Pydantic model""" print("\n" + "=" * 60) print("TEST 3: WebhookConfig Model Validation") print("=" * 60) try: from schemas import WebhookConfig from pydantic import ValidationError # Test valid config valid_config = { "webhook_url": "https://example.com/webhook", "webhook_data_in_payload": True, "webhook_headers": {"X-Secret": "token123"} } config = WebhookConfig(**valid_config) print(f"โœ… Valid config accepted:") print(f" - URL: {config.webhook_url}") print(f" - Data in payload: {config.webhook_data_in_payload}") print(f" - Headers: {config.webhook_headers}") # Test minimal config minimal_config = { "webhook_url": "https://example.com/webhook" } config2 = WebhookConfig(**minimal_config) print(f"โœ… Minimal config accepted (defaults applied):") print(f" - URL: {config2.webhook_url}") print(f" - Data in payload: {config2.webhook_data_in_payload}") print(f" - Headers: {config2.webhook_headers}") # Test invalid URL try: invalid_config = { "webhook_url": "not-a-url" } config3 = WebhookConfig(**invalid_config) print(f"โŒ Invalid URL should have been rejected") return False except ValidationError as e: print(f"โœ… Invalid URL correctly rejected") return True except Exception as e: print(f"โŒ Model validation test failed: {e}") import traceback traceback.print_exc() return False def test_payload_construction(): """Test webhook payload construction logic""" print("\n" + "=" * 60) print("TEST 4: Payload Construction") print("=" * 60) try: # Simulate payload construction from notify_job_completion task_id = "crawl_abc123" task_type = "crawl" status = "completed" urls = ["https://example.com"] payload = { "task_id": task_id, "task_type": task_type, "status": status, "timestamp": datetime.now(timezone.utc).isoformat(), "urls": urls } print(f"โœ… Basic payload constructed:") print(json.dumps(payload, indent=2)) # Test with error error_payload = { "task_id": "crawl_xyz789", "task_type": "crawl", "status": "failed", "timestamp": datetime.now(timezone.utc).isoformat(), "urls": ["https://example.com"], "error": "Connection timeout" } print(f"\nโœ… Error payload constructed:") print(json.dumps(error_payload, indent=2)) # Test with data data_payload = { "task_id": "crawl_def456", "task_type": "crawl", "status": "completed", "timestamp": datetime.now(timezone.utc).isoformat(), "urls": ["https://example.com"], "data": { "results": [ {"url": "https://example.com", "markdown": "# Example"} ] } } print(f"\nโœ… Data payload constructed:") print(json.dumps(data_payload, indent=2)) return True except Exception as e: print(f"โŒ Payload construction failed: {e}") import traceback traceback.print_exc() return False def test_exponential_backoff(): """Test exponential backoff calculation""" print("\n" + "=" * 60) print("TEST 5: Exponential Backoff Calculation") print("=" * 60) try: initial_delay = 1.0 # 1 second max_delay = 32.0 # 32 seconds print("Backoff delays for 5 attempts:") for attempt in range(5): delay = min(initial_delay * (2 ** attempt), max_delay) print(f" Attempt {attempt + 1}: {delay}s") # Verify the sequence: 1s, 2s, 4s, 8s, 16s expected = [1.0, 2.0, 4.0, 8.0, 16.0] actual = [min(initial_delay * (2 ** i), max_delay) for i in range(5)] assert actual == expected, f"Expected {expected}, got {actual}" print("โœ… Exponential backoff sequence correct") return True except Exception as e: print(f"โŒ Backoff calculation failed: {e}") return False def test_api_integration(): """Test that api.py imports webhook module correctly""" print("\n" + "=" * 60) print("TEST 6: API Integration") print("=" * 60) try: # Check if api.py can import webhook module api_path = os.path.join(os.path.dirname(__file__), 'deploy', 'docker', 'api.py') with open(api_path, 'r') as f: api_content = f.read() if 'from webhook import WebhookDeliveryService' in api_content: print("โœ… api.py imports WebhookDeliveryService") else: print("โŒ api.py missing webhook import") return False if 'WebhookDeliveryService(config)' in api_content: print("โœ… api.py initializes WebhookDeliveryService") else: print("โŒ api.py doesn't initialize WebhookDeliveryService") return False if 'notify_job_completion' in api_content: print("โœ… api.py calls notify_job_completion") else: print("โŒ api.py doesn't call notify_job_completion") return False return True except Exception as e: print(f"โŒ API integration check failed: {e}") return False def main(): """Run all tests""" print("\n๐Ÿงช Webhook Implementation Validation Tests") print("=" * 60) results = [] # Run tests results.append(("Module Imports", test_imports())) results.append(("Service Initialization", test_webhook_service_init())) results.append(("Config Model", test_webhook_config_model())) results.append(("Payload Construction", test_payload_construction())) results.append(("Exponential Backoff", test_exponential_backoff())) results.append(("API Integration", test_api_integration())) # Print summary print("\n" + "=" * 60) print("TEST SUMMARY") print("=" * 60) passed = sum(1 for _, result in results if result) total = len(results) for test_name, result in results: status = "โœ… PASS" if result else "โŒ FAIL" print(f"{status} - {test_name}") print(f"\n{'=' * 60}") print(f"Results: {passed}/{total} tests passed") print(f"{'=' * 60}") if passed == total: print("\n๐ŸŽ‰ All tests passed! Webhook implementation is valid.") return 0 else: print(f"\nโš ๏ธ {total - passed} test(s) failed. Please review the output above.") return 1 if __name__ == "__main__": exit(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "test_webhook_implementation.py", "license": "Apache License 2.0", "lines": 254, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:tests/docker/test_filter_deep_crawl.py
""" Test the complete fix for both the filter serialization and JSON serialization issues. """ import os import traceback from typing import Any import asyncio import httpx from crawl4ai import BrowserConfig, CacheMode, CrawlerRunConfig from crawl4ai.deep_crawling import ( BFSDeepCrawlStrategy, ContentRelevanceFilter, FilterChain, URLFilter, URLPatternFilter, ) CRAWL4AI_DOCKER_PORT = os.environ.get("CRAWL4AI_DOCKER_PORT", "11234") try: BASE_PORT = int(CRAWL4AI_DOCKER_PORT) except TypeError: BASE_PORT = 11234 BASE_URL = f"http://localhost:{BASE_PORT}/" # Adjust port as needed async def test_with_docker_client(filter_chain: list[URLFilter], max_pages: int = 20, timeout: int = 30) -> bool: """Test using the Docker client (same as 1419.py).""" from crawl4ai.docker_client import Crawl4aiDockerClient print("=" * 60) print("Testing with Docker Client") print("=" * 60) try: async with Crawl4aiDockerClient( base_url=BASE_URL, verbose=True, ) as client: crawler_config = CrawlerRunConfig( deep_crawl_strategy=BFSDeepCrawlStrategy( max_depth=2, # Keep it shallow for testing max_pages=max_pages, # Limit pages for testing filter_chain=FilterChain(filter_chain) ), cache_mode=CacheMode.BYPASS, ) print("\n1. Testing crawl with filters...") results = await client.crawl( ["https://docs.crawl4ai.com"], # Simple test page browser_config=BrowserConfig(headless=True), crawler_config=crawler_config, hooks_timeout=timeout, ) if results: print(f"โœ… Crawl succeeded! Type: {type(results)}") if hasattr(results, 'success'): print(f"โœ… Results success: {results.success}") # Test that we can iterate results without JSON errors if hasattr(results, '__iter__'): for i, result in enumerate(results): if hasattr(result, 'url'): print(f" Result {i}: {result.url[:50]}...") else: print(f" Result {i}: {str(result)[:50]}...") else: # Handle list of results print(f"โœ… Got {len(results)} results") for i, result in enumerate(results[:3]): # Show first 3 print(f" Result {i}: {result.url[:50]}...") else: print("โŒ Crawl failed - no results returned") return False print("\nโœ… Docker client test completed successfully!") return True except Exception as e: print(f"โŒ Docker client test failed: {e}") traceback.print_exc() return False async def test_with_rest_api(filters: list[dict[str, Any]], max_pages: int = 20, timeout: int = 30) -> bool: """Test using REST API directly.""" print("\n" + "=" * 60) print("Testing with REST API") print("=" * 60) # Create filter configuration deep_crawl_strategy_payload = { "type": "BFSDeepCrawlStrategy", "params": { "max_depth": 2, "max_pages": max_pages, "filter_chain": { "type": "FilterChain", "params": { "filters": filters } } } } crawl_payload = { "urls": ["https://docs.crawl4ai.com"], "browser_config": {"type": "BrowserConfig", "params": {"headless": True}}, "crawler_config": { "type": "CrawlerRunConfig", "params": { "deep_crawl_strategy": deep_crawl_strategy_payload, "cache_mode": "bypass" } } } try: async with httpx.AsyncClient() as client: print("\n1. Sending crawl request to REST API...") response = await client.post( f"{BASE_URL}crawl", json=crawl_payload, timeout=timeout, ) if response.status_code == 200: print(f"โœ… REST API returned 200 OK") data = response.json() if data.get("success"): results = data.get("results", []) print(f"โœ… Got {len(results)} results") for i, result in enumerate(results[:3]): print(f" Result {i}: {result.get('url', 'unknown')[:50]}...") else: print(f"โŒ Crawl not successful: {data}") return False else: print(f"โŒ REST API returned {response.status_code}") print(f" Response: {response.text[:500]}") return False print("\nโœ… REST API test completed successfully!") return True except Exception as e: print(f"โŒ REST API test failed: {e}") traceback.print_exc() return False async def main(): """Run all tests.""" print("\n๐Ÿงช TESTING COMPLETE FIX FOR DOCKER FILTER AND JSON ISSUES") print("=" * 60) print("Make sure the server is running with the updated code!") print("=" * 60) results = [] # Test 1: Docker client max_pages_ = [20, 5] timeouts = [30, 60] filter_chain_test_cases = [ [ URLPatternFilter( # patterns=["*about*", "*privacy*", "*terms*"], patterns=["*advanced*"], reverse=True ), ], [ ContentRelevanceFilter( query="about faq", threshold=0.2, ), ], ] for idx, (filter_chain, max_pages, timeout) in enumerate(zip(filter_chain_test_cases, max_pages_, timeouts)): docker_passed = await test_with_docker_client(filter_chain=filter_chain, max_pages=max_pages, timeout=timeout) results.append((f"Docker Client w/ filter chain {idx}", docker_passed)) # Test 2: REST API max_pages_ = [20, 5, 5] timeouts = [30, 60, 60] filters_test_cases = [ [ { "type": "URLPatternFilter", "params": { "patterns": ["*advanced*"], "reverse": True } } ], [ { "type": "ContentRelevanceFilter", "params": { "query": "about faq", "threshold": 0.2, } } ], [ { "type": "ContentRelevanceFilter", "params": { "query": ["about", "faq"], "threshold": 0.2, } } ], ] for idx, (filters, max_pages, timeout) in enumerate(zip(filters_test_cases, max_pages_, timeouts)): rest_passed = await test_with_rest_api(filters=filters, max_pages=max_pages, timeout=timeout) results.append((f"REST API w/ filters {idx}", rest_passed)) # Summary print("\n" + "=" * 60) print("FINAL TEST SUMMARY") print("=" * 60) all_passed = True for test_name, passed in results: status = "โœ… PASSED" if passed else "โŒ FAILED" print(f"{test_name:20} {status}") if not passed: all_passed = False print("=" * 60) if all_passed: print("๐ŸŽ‰ ALL TESTS PASSED!") else: print("โš ๏ธ Some tests failed. Please check the server logs for details.") return 0 if all_passed else 1 if __name__ == "__main__": import sys sys.exit(asyncio.run(main()))
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/docker/test_filter_deep_crawl.py", "license": "Apache License 2.0", "lines": 214, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/docker/test_hooks_client.py
#!/usr/bin/env python3 """ Test client for demonstrating user-provided hooks in Crawl4AI Docker API """ import requests import json from typing import Dict, Any API_BASE_URL = "http://localhost:11234" # Adjust if needed def test_hooks_info(): """Get information about available hooks""" print("=" * 70) print("Testing: GET /hooks/info") print("=" * 70) response = requests.get(f"{API_BASE_URL}/hooks/info") if response.status_code == 200: data = response.json() print("Available Hook Points:") for hook, info in data['available_hooks'].items(): print(f"\n{hook}:") print(f" Parameters: {', '.join(info['parameters'])}") print(f" Description: {info['description']}") else: print(f"Error: {response.status_code}") print(response.text) def test_basic_crawl_with_hooks(): """Test basic crawling with user-provided hooks""" print("\n" + "=" * 70) print("Testing: POST /crawl with hooks") print("=" * 70) # Define hooks as Python code strings hooks_code = { "on_page_context_created": """ async def hook(page, context, **kwargs): print("Hook: Setting up page context") # Block images to speed up crawling await context.route("**/*.{png,jpg,jpeg,gif,webp}", lambda route: route.abort()) print("Hook: Images blocked") return page """, "before_retrieve_html": """ async def hook(page, context, **kwargs): print("Hook: Before retrieving HTML") # Scroll to bottom to load lazy content await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await page.wait_for_timeout(1000) print("Hook: Scrolled to bottom") return page """, "before_goto": """ async def hook(page, context, url, **kwargs): print(f"Hook: About to navigate to {url}") # Add custom headers await page.set_extra_http_headers({ 'X-Test-Header': 'crawl4ai-hooks-test' }) return page """ } # Create request payload payload = { "urls": ["https://httpbin.org/html"], "hooks": { "code": hooks_code, "timeout": 30 } } print("Sending request with hooks...") response = requests.post(f"{API_BASE_URL}/crawl", json=payload) if response.status_code == 200: data = response.json() print("\nโœ… Crawl successful!") # Check hooks status if 'hooks' in data: hooks_info = data['hooks'] print("\nHooks Execution Summary:") print(f" Status: {hooks_info['status']['status']}") print(f" Attached hooks: {', '.join(hooks_info['status']['attached_hooks'])}") if hooks_info['status']['validation_errors']: print("\nโš ๏ธ Validation Errors:") for error in hooks_info['status']['validation_errors']: print(f" - {error['hook_point']}: {error['error']}") if 'summary' in hooks_info: summary = hooks_info['summary'] print(f"\nExecution Statistics:") print(f" Total executions: {summary['total_executions']}") print(f" Successful: {summary['successful']}") print(f" Failed: {summary['failed']}") print(f" Timed out: {summary['timed_out']}") print(f" Success rate: {summary['success_rate']:.1f}%") if hooks_info['execution_log']: print("\nExecution Log:") for log_entry in hooks_info['execution_log']: status_icon = "โœ…" if log_entry['status'] == 'success' else "โŒ" print(f" {status_icon} {log_entry['hook_point']}: {log_entry['status']} ({log_entry.get('execution_time', 0):.2f}s)") if hooks_info['errors']: print("\nโŒ Hook Errors:") for error in hooks_info['errors']: print(f" - {error['hook_point']}: {error['error']}") # Show crawl results if 'results' in data: print(f"\nCrawled {len(data['results'])} URL(s)") for result in data['results']: print(f" - {result['url']}: {'โœ…' if result['success'] else 'โŒ'}") else: print(f"โŒ Error: {response.status_code}") print(response.text) def test_invalid_hook(): """Test with an invalid hook to see error handling""" print("\n" + "=" * 70) print("Testing: Invalid hook handling") print("=" * 70) # Intentionally broken hook hooks_code = { "on_page_context_created": """ def hook(page, context): # Missing async! return page """, "before_retrieve_html": """ async def hook(page, context, **kwargs): # This will cause an error await page.non_existent_method() return page """ } payload = { "urls": ["https://httpbin.org/html"], "hooks": { "code": hooks_code, "timeout": 5 } } print("Sending request with invalid hooks...") response = requests.post(f"{API_BASE_URL}/crawl", json=payload) if response.status_code == 200: data = response.json() if 'hooks' in data: hooks_info = data['hooks'] print(f"\nHooks Status: {hooks_info['status']['status']}") if hooks_info['status']['validation_errors']: print("\nโœ… Validation caught errors (as expected):") for error in hooks_info['status']['validation_errors']: print(f" - {error['hook_point']}: {error['error']}") if hooks_info['errors']: print("\nโœ… Runtime errors handled gracefully:") for error in hooks_info['errors']: print(f" - {error['hook_point']}: {error['error']}") # The crawl should still succeed despite hook errors if data.get('success'): print("\nโœ… Crawl succeeded despite hook errors (error isolation working!)") else: print(f"Error: {response.status_code}") print(response.text) def test_authentication_hook(): """Test authentication using hooks""" print("\n" + "=" * 70) print("Testing: Authentication with hooks") print("=" * 70) hooks_code = { "before_goto": """ async def hook(page, context, url, **kwargs): # For httpbin.org basic auth test, set Authorization header import base64 # httpbin.org/basic-auth/user/passwd expects username="user" and password="passwd" credentials = base64.b64encode(b"user:passwd").decode('ascii') await page.set_extra_http_headers({ 'Authorization': f'Basic {credentials}' }) print(f"Hook: Set Authorization header for {url}") return page """, "on_page_context_created": """ async def hook(page, context, **kwargs): # Example: Add cookies for session tracking await context.add_cookies([ { 'name': 'session_id', 'value': 'test_session_123', 'domain': '.httpbin.org', 'path': '/', 'httpOnly': True, 'secure': True } ]) print("Hook: Added session cookie") return page """ } payload = { "urls": ["https://httpbin.org/basic-auth/user/passwd"], "hooks": { "code": hooks_code, "timeout": 30 } } print("Sending request with authentication hook...") response = requests.post(f"{API_BASE_URL}/crawl", json=payload) if response.status_code == 200: data = response.json() if data.get('success'): print("โœ… Crawl with authentication hook successful") # Check if hooks executed if 'hooks' in data: hooks_info = data['hooks'] if hooks_info.get('summary', {}).get('successful', 0) > 0: print(f"โœ… Authentication hooks executed: {hooks_info['summary']['successful']} successful") # Check for any hook errors if hooks_info.get('errors'): print("โš ๏ธ Hook errors:") for error in hooks_info['errors']: print(f" - {error}") # Check if authentication worked by looking at the result if 'results' in data and len(data['results']) > 0: result = data['results'][0] if result.get('success'): print("โœ… Page crawled successfully (authentication worked!)") # httpbin.org/basic-auth returns JSON with authenticated=true when successful if 'authenticated' in str(result.get('html', '')): print("โœ… Authentication confirmed in response content") else: print(f"โŒ Crawl failed: {result.get('error_message', 'Unknown error')}") else: print("โŒ Request failed") print(f"Response: {json.dumps(data, indent=2)}") else: print(f"โŒ Error: {response.status_code}") try: error_data = response.json() print(f"Error details: {json.dumps(error_data, indent=2)}") except: print(f"Error text: {response.text[:500]}") def test_streaming_with_hooks(): """Test streaming endpoint with hooks""" print("\n" + "=" * 70) print("Testing: POST /crawl/stream with hooks") print("=" * 70) hooks_code = { "before_retrieve_html": """ async def hook(page, context, **kwargs): await page.evaluate("document.querySelectorAll('img').forEach(img => img.remove())") return page """ } payload = { "urls": ["https://httpbin.org/html", "https://httpbin.org/json"], "hooks": { "code": hooks_code, "timeout": 10 } } print("Sending streaming request with hooks...") with requests.post(f"{API_BASE_URL}/crawl/stream", json=payload, stream=True) as response: if response.status_code == 200: # Check headers for hooks status hooks_status = response.headers.get('X-Hooks-Status') if hooks_status: print(f"Hooks Status (from header): {hooks_status}") print("\nStreaming results:") for line in response.iter_lines(): if line: try: result = json.loads(line) if 'url' in result: print(f" Received: {result['url']}") elif 'status' in result: print(f" Stream status: {result['status']}") except json.JSONDecodeError: print(f" Raw: {line.decode()}") else: print(f"Error: {response.status_code}") def test_basic_without_hooks(): """Test basic crawl without hooks""" print("\n" + "=" * 70) print("Testing: POST /crawl with no hooks") print("=" * 70) payload = { "urls": ["https://httpbin.org/html", "https://httpbin.org/json"] } response = requests.post(f"{API_BASE_URL}/crawl", json=payload) if response.status_code == 200: data = response.json() print(f"Response: {json.dumps(data, indent=2)}") else: print(f"Error: {response.status_code}") def main(): """Run all tests""" print("๐Ÿ”ง Crawl4AI Docker API - Hooks Testing") print("=" * 70) # Test 1: Get hooks information # test_hooks_info() # Test 2: Basic crawl with hooks # test_basic_crawl_with_hooks() # Test 3: Invalid hooks (error handling) test_invalid_hook() # # Test 4: Authentication hook # test_authentication_hook() # # Test 5: Streaming with hooks # test_streaming_with_hooks() # # Test 6: Basic crawl without hooks # test_basic_without_hooks() print("\n" + "=" * 70) print("โœ… All tests completed!") print("=" * 70) if __name__ == "__main__": main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/docker/test_hooks_client.py", "license": "Apache License 2.0", "lines": 304, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/docker/test_hooks_comprehensive.py
#!/usr/bin/env python3 """ Comprehensive test demonstrating all hook types from hooks_example.py adapted for the Docker API with real URLs """ import requests import json import time from typing import Dict, Optional API_BASE_URL = "http://localhost:11235" # Global token storage _auth_token: Optional[str] = None def get_auth_token(email: str = "test@gmail.com") -> str: """ Get a JWT token from the /token endpoint. The email domain must have valid MX records. """ global _auth_token if _auth_token: return _auth_token print(f"๐Ÿ” Requesting JWT token for {email}...") response = requests.post( f"{API_BASE_URL}/token", json={"email": email} ) if response.status_code == 200: data = response.json() _auth_token = data["access_token"] print(f"โœ… Token obtained successfully") return _auth_token else: raise Exception(f"Failed to get token: {response.status_code} - {response.text}") def get_auth_headers() -> Dict[str, str]: """Get headers with JWT Bearer token.""" token = get_auth_token() return { "Authorization": f"Bearer {token}", "Content-Type": "application/json" } def test_all_hooks_demo(): """Demonstrate all 8 hook types with practical examples""" print("=" * 70) print("Testing: All Hooks Comprehensive Demo") print("=" * 70) hooks_code = { "on_browser_created": """ async def hook(browser, **kwargs): # Hook called after browser is created print("[HOOK] on_browser_created - Browser is ready!") # Browser-level configurations would go here return browser """, "on_page_context_created": """ async def hook(page, context, **kwargs): # Hook called after a new page and context are created print("[HOOK] on_page_context_created - New page created!") # Set viewport size for consistent rendering await page.set_viewport_size({"width": 1920, "height": 1080}) # Add cookies for the session (using httpbin.org domain) await context.add_cookies([ { "name": "test_session", "value": "abc123xyz", "domain": ".httpbin.org", "path": "/", "httpOnly": True, "secure": True } ]) # Block ads and tracking scripts to speed up crawling await context.route("**/*.{png,jpg,jpeg,gif,webp,svg}", lambda route: route.abort()) await context.route("**/analytics/*", lambda route: route.abort()) await context.route("**/ads/*", lambda route: route.abort()) print("[HOOK] Viewport set, cookies added, and ads blocked") return page """, "on_user_agent_updated": """ async def hook(page, context, user_agent, **kwargs): # Hook called when user agent is updated print(f"[HOOK] on_user_agent_updated - User agent: {user_agent[:50]}...") return page """, "before_goto": """ async def hook(page, context, url, **kwargs): # Hook called before navigating to each URL print(f"[HOOK] before_goto - About to visit: {url}") # Add custom headers for the request await page.set_extra_http_headers({ "X-Custom-Header": "crawl4ai-test", "Accept-Language": "en-US,en;q=0.9", "DNT": "1" }) return page """, "after_goto": """ async def hook(page, context, url, response, **kwargs): # Hook called after navigating to each URL print(f"[HOOK] after_goto - Successfully loaded: {url}") # Wait a moment for dynamic content to load await page.wait_for_timeout(1000) # Check if specific elements exist (with error handling) try: # For httpbin.org, wait for body element await page.wait_for_selector("body", timeout=2000) print("[HOOK] Body element found and loaded") except: print("[HOOK] Timeout waiting for body, continuing anyway") return page """, "on_execution_started": """ async def hook(page, context, **kwargs): # Hook called after custom JavaScript execution print("[HOOK] on_execution_started - Custom JS executed!") # You could inject additional JavaScript here if needed await page.evaluate("console.log('[INJECTED] Hook JS running');") return page """, "before_retrieve_html": """ async def hook(page, context, **kwargs): # Hook called before retrieving the HTML content print("[HOOK] before_retrieve_html - Preparing to get HTML") # Scroll to bottom to trigger lazy loading await page.evaluate("window.scrollTo(0, document.body.scrollHeight);") await page.wait_for_timeout(500) # Scroll back to top await page.evaluate("window.scrollTo(0, 0);") await page.wait_for_timeout(500) # One more scroll to middle for good measure await page.evaluate("window.scrollTo(0, document.body.scrollHeight / 2);") print("[HOOK] Scrolling completed for lazy-loaded content") return page """, "before_return_html": """ async def hook(page, context, html, **kwargs): # Hook called before returning the HTML content print(f"[HOOK] before_return_html - HTML length: {len(html)} characters") # Log some page metrics metrics = await page.evaluate('''() => { return { images: document.images.length, links: document.links.length, scripts: document.scripts.length } }''') print(f"[HOOK] Page metrics - Images: {metrics['images']}, Links: {metrics['links']}, Scripts: {metrics['scripts']}") return page """ } # Create request payload payload = { "urls": ["https://httpbin.org/html"], "hooks": { "code": hooks_code, "timeout": 30 }, "crawler_config": { "js_code": "window.scrollTo(0, document.body.scrollHeight);", "wait_for": "body", "cache_mode": "bypass" } } print("\nSending request with all 8 hooks...") start_time = time.time() response = requests.post(f"{API_BASE_URL}/crawl", json=payload, headers=get_auth_headers()) elapsed_time = time.time() - start_time print(f"Request completed in {elapsed_time:.2f} seconds") if response.status_code == 200: data = response.json() print("\nโœ… Request successful!") # Check hooks execution if 'hooks' in data: hooks_info = data['hooks'] print("\n๐Ÿ“Š Hooks Execution Summary:") print(f" Status: {hooks_info['status']['status']}") print(f" Attached hooks: {len(hooks_info['status']['attached_hooks'])}") for hook_name in hooks_info['status']['attached_hooks']: print(f" โœ“ {hook_name}") if 'summary' in hooks_info: summary = hooks_info['summary'] print(f"\n๐Ÿ“ˆ Execution Statistics:") print(f" Total executions: {summary['total_executions']}") print(f" Successful: {summary['successful']}") print(f" Failed: {summary['failed']}") print(f" Timed out: {summary['timed_out']}") print(f" Success rate: {summary['success_rate']:.1f}%") if hooks_info.get('execution_log'): print(f"\n๐Ÿ“ Execution Log:") for log_entry in hooks_info['execution_log']: status_icon = "โœ…" if log_entry['status'] == 'success' else "โŒ" exec_time = log_entry.get('execution_time', 0) print(f" {status_icon} {log_entry['hook_point']}: {exec_time:.3f}s") # Check crawl results if 'results' in data and len(data['results']) > 0: print(f"\n๐Ÿ“„ Crawl Results:") for result in data['results']: print(f" URL: {result['url']}") print(f" Success: {result.get('success', False)}") if result.get('html'): print(f" HTML length: {len(result['html'])} characters") else: print(f"โŒ Error: {response.status_code}") try: error_data = response.json() print(f"Error details: {json.dumps(error_data, indent=2)}") except: print(f"Error text: {response.text[:500]}") def test_authentication_flow(): """Test a complete authentication flow with multiple hooks""" print("\n" + "=" * 70) print("Testing: Authentication Flow with Multiple Hooks") print("=" * 70) hooks_code = { "on_page_context_created": """ async def hook(page, context, **kwargs): print("[HOOK] Setting up authentication context") # Add authentication cookies await context.add_cookies([ { "name": "auth_token", "value": "fake_jwt_token_here", "domain": ".httpbin.org", "path": "/", "httpOnly": True, "secure": True } ]) # Set localStorage items (for SPA authentication) await page.evaluate(''' localStorage.setItem('user_id', '12345'); localStorage.setItem('auth_time', new Date().toISOString()); ''') return page """, "before_goto": """ async def hook(page, context, url, **kwargs): print(f"[HOOK] Adding auth headers for {url}") # Add Authorization header import base64 credentials = base64.b64encode(b"user:passwd").decode('ascii') await page.set_extra_http_headers({ 'Authorization': f'Basic {credentials}', 'X-API-Key': 'test-api-key-123' }) return page """ } payload = { "urls": [ "https://httpbin.org/basic-auth/user/passwd" ], "hooks": { "code": hooks_code, "timeout": 15 } } print("\nTesting authentication with httpbin endpoints...") response = requests.post(f"{API_BASE_URL}/crawl", json=payload, headers=get_auth_headers()) if response.status_code == 200: data = response.json() print("โœ… Authentication test completed") if 'results' in data: for i, result in enumerate(data['results']): print(f"\n URL {i+1}: {result['url']}") if result.get('success'): # Check for authentication success indicators html_content = result.get('html', '') if '"authenticated"' in html_content and 'true' in html_content: print(" โœ… Authentication successful! Basic auth worked.") else: print(" โš ๏ธ Page loaded but auth status unclear") else: print(f" โŒ Failed: {result.get('error_message', 'Unknown error')}") else: print(f"โŒ Error: {response.status_code}") def test_performance_optimization_hooks(): """Test hooks for performance optimization""" print("\n" + "=" * 70) print("Testing: Performance Optimization Hooks") print("=" * 70) hooks_code = { "on_page_context_created": """ async def hook(page, context, **kwargs): print("[HOOK] Optimizing page for performance") # Block resource-heavy content await context.route("**/*.{png,jpg,jpeg,gif,webp,svg,ico}", lambda route: route.abort()) await context.route("**/*.{woff,woff2,ttf,otf}", lambda route: route.abort()) await context.route("**/*.{mp4,webm,ogg,mp3,wav}", lambda route: route.abort()) await context.route("**/googletagmanager.com/*", lambda route: route.abort()) await context.route("**/google-analytics.com/*", lambda route: route.abort()) await context.route("**/doubleclick.net/*", lambda route: route.abort()) await context.route("**/facebook.com/*", lambda route: route.abort()) # Disable animations and transitions await page.add_style_tag(content=''' *, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; transition-duration: 0s !important; transition-delay: 0s !important; } ''') print("[HOOK] Performance optimizations applied") return page """, "before_retrieve_html": """ async def hook(page, context, **kwargs): print("[HOOK] Removing unnecessary elements before extraction") # Remove ads, popups, and other unnecessary elements await page.evaluate('''() => { // Remove common ad containers const adSelectors = [ '.ad', '.ads', '.advertisement', '[id*="ad-"]', '[class*="ad-"]', '.popup', '.modal', '.overlay', '.cookie-banner', '.newsletter-signup' ]; adSelectors.forEach(selector => { document.querySelectorAll(selector).forEach(el => el.remove()); }); // Remove script tags to clean up HTML document.querySelectorAll('script').forEach(el => el.remove()); // Remove style tags we don't need document.querySelectorAll('style').forEach(el => el.remove()); }''') return page """ } payload = { "urls": ["https://httpbin.org/html"], "hooks": { "code": hooks_code, "timeout": 10 } } print("\nTesting performance optimization hooks...") start_time = time.time() response = requests.post(f"{API_BASE_URL}/crawl", json=payload, headers=get_auth_headers()) elapsed_time = time.time() - start_time print(f"Request completed in {elapsed_time:.2f} seconds") if response.status_code == 200: data = response.json() print("โœ… Performance optimization test completed") if 'results' in data and len(data['results']) > 0: result = data['results'][0] if result.get('html'): print(f" HTML size: {len(result['html'])} characters") print(" Resources blocked, ads removed, animations disabled") else: print(f"โŒ Error: {response.status_code}") def test_content_extraction_hooks(): """Test hooks for intelligent content extraction""" print("\n" + "=" * 70) print("Testing: Content Extraction Hooks") print("=" * 70) hooks_code = { "after_goto": """ async def hook(page, context, url, response, **kwargs): print(f"[HOOK] Waiting for dynamic content on {url}") # Wait for any lazy-loaded content await page.wait_for_timeout(2000) # Trigger any "Load More" buttons try: load_more = await page.query_selector('[class*="load-more"], [class*="show-more"], button:has-text("Load More")') if load_more: await load_more.click() await page.wait_for_timeout(1000) print("[HOOK] Clicked 'Load More' button") except: pass return page """, "before_retrieve_html": """ async def hook(page, context, **kwargs): print("[HOOK] Extracting structured data") # Extract metadata metadata = await page.evaluate('''() => { const getMeta = (name) => { const element = document.querySelector(`meta[name="${name}"], meta[property="${name}"]`); return element ? element.getAttribute('content') : null; }; return { title: document.title, description: getMeta('description') || getMeta('og:description'), author: getMeta('author'), keywords: getMeta('keywords'), ogTitle: getMeta('og:title'), ogImage: getMeta('og:image'), canonical: document.querySelector('link[rel="canonical"]')?.href, jsonLd: Array.from(document.querySelectorAll('script[type="application/ld+json"]')) .map(el => el.textContent).filter(Boolean) }; }''') print(f"[HOOK] Extracted metadata: {json.dumps(metadata, indent=2)}") # Infinite scroll handling for i in range(3): await page.evaluate("window.scrollTo(0, document.body.scrollHeight);") await page.wait_for_timeout(1000) print(f"[HOOK] Scroll iteration {i+1}/3") return page """ } payload = { "urls": ["https://httpbin.org/html", "https://httpbin.org/json"], "hooks": { "code": hooks_code, "timeout": 20 } } print("\nTesting content extraction hooks...") response = requests.post(f"{API_BASE_URL}/crawl", json=payload, headers=get_auth_headers()) if response.status_code == 200: data = response.json() print("โœ… Content extraction test completed") if 'hooks' in data and 'summary' in data['hooks']: summary = data['hooks']['summary'] print(f" Hooks executed: {summary['successful']}/{summary['total_executions']}") if 'results' in data: for result in data['results']: print(f"\n URL: {result['url']}") print(f" Success: {result.get('success', False)}") else: print(f"โŒ Error: {response.status_code}") def main(): """Run comprehensive hook tests""" print("๐Ÿ”ง Crawl4AI Docker API - Comprehensive Hooks Testing") print("Based on docs/examples/hooks_example.py") print("=" * 70) # Get JWT token first (required when jwt_enabled=true) try: get_auth_token() print("=" * 70) except Exception as e: print(f"โŒ Failed to authenticate: {e}") print("Make sure the server is running and jwt_enabled is configured correctly.") return tests = [ ("All Hooks Demo", test_all_hooks_demo), ("Authentication Flow", test_authentication_flow), ("Performance Optimization", test_performance_optimization_hooks), ("Content Extraction", test_content_extraction_hooks), ] for i, (name, test_func) in enumerate(tests, 1): print(f"\n๐Ÿ“Œ Test {i}/{len(tests)}: {name}") try: test_func() print(f"โœ… {name} completed") except Exception as e: print(f"โŒ {name} failed: {e}") import traceback traceback.print_exc() print("\n" + "=" * 70) print("๐ŸŽ‰ All comprehensive hook tests completed!") print("=" * 70) if __name__ == "__main__": main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/docker/test_hooks_comprehensive.py", "license": "Apache License 2.0", "lines": 452, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/docker/test_hooks_utility.py
""" Test script demonstrating the hooks_to_string utility and Docker client integration. """ import asyncio from crawl4ai import Crawl4aiDockerClient, hooks_to_string # Define hook functions as regular Python functions async def auth_hook(page, context, **kwargs): """Add authentication cookies.""" await context.add_cookies([{ 'name': 'test_cookie', 'value': 'test_value', 'domain': '.httpbin.org', 'path': '/' }]) return page async def scroll_hook(page, context, **kwargs): """Scroll to load lazy content.""" await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await page.wait_for_timeout(1000) return page async def viewport_hook(page, context, **kwargs): """Set custom viewport.""" await page.set_viewport_size({"width": 1920, "height": 1080}) return page async def test_hooks_utility(): """Test the hooks_to_string utility function.""" print("=" * 60) print("Testing hooks_to_string utility") print("=" * 60) # Create hooks dictionary with function objects hooks_dict = { "on_page_context_created": auth_hook, "before_retrieve_html": scroll_hook } # Convert to string format hooks_string = hooks_to_string(hooks_dict) print("\nโœ“ Successfully converted function objects to strings") print(f"\nโœ“ Converted {len(hooks_string)} hooks:") for hook_name in hooks_string.keys(): print(f" - {hook_name}") print("\nโœ“ Preview of converted hook:") print("-" * 60) print(hooks_string["on_page_context_created"][:200] + "...") print("-" * 60) return hooks_string async def test_docker_client_with_functions(): """Test Docker client with function objects (automatic conversion).""" print("\n" + "=" * 60) print("Testing Docker Client with Function Objects") print("=" * 60) # Note: This requires a running Crawl4AI Docker server # Uncomment the following to test with actual server: async with Crawl4aiDockerClient(base_url="http://localhost:11234", verbose=True) as client: # Pass function objects directly - they'll be converted automatically result = await client.crawl( ["https://httpbin.org/html"], hooks={ "on_page_context_created": auth_hook, "before_retrieve_html": scroll_hook }, hooks_timeout=30 ) print(f"\nโœ“ Crawl successful: {result.success}") print(f"โœ“ URL: {result.url}") print("\nโœ“ Docker client accepts function objects directly") print("โœ“ Automatic conversion happens internally") print("โœ“ No manual string formatting needed!") async def test_docker_client_with_strings(): """Test Docker client with pre-converted strings.""" print("\n" + "=" * 60) print("Testing Docker Client with String Hooks") print("=" * 60) # Convert hooks to strings first hooks_dict = { "on_page_context_created": viewport_hook, "before_retrieve_html": scroll_hook } hooks_string = hooks_to_string(hooks_dict) # Note: This requires a running Crawl4AI Docker server # Uncomment the following to test with actual server: async with Crawl4aiDockerClient(base_url="http://localhost:11234", verbose=True) as client: # Pass string hooks - they'll be used as-is result = await client.crawl( ["https://httpbin.org/html"], hooks=hooks_string, hooks_timeout=30 ) print(f"\nโœ“ Crawl successful: {result.success}") print("\nโœ“ Docker client also accepts pre-converted strings") print("โœ“ Backward compatible with existing code") async def show_usage_patterns(): """Show different usage patterns.""" print("\n" + "=" * 60) print("Usage Patterns") print("=" * 60) print("\n1. Direct function usage (simplest):") print("-" * 60) print(""" async def my_hook(page, context, **kwargs): await page.set_viewport_size({"width": 1920, "height": 1080}) return page result = await client.crawl( ["https://example.com"], hooks={"on_page_context_created": my_hook} ) """) print("\n2. Convert then use:") print("-" * 60) print(""" hooks_dict = {"on_page_context_created": my_hook} hooks_string = hooks_to_string(hooks_dict) result = await client.crawl( ["https://example.com"], hooks=hooks_string ) """) print("\n3. Manual string (backward compatible):") print("-" * 60) print(""" hooks_string = { "on_page_context_created": ''' async def hook(page, context, **kwargs): await page.set_viewport_size({"width": 1920, "height": 1080}) return page ''' } result = await client.crawl( ["https://example.com"], hooks=hooks_string ) """) async def main(): """Run all tests.""" print("\n๐Ÿš€ Crawl4AI Hooks Utility Test Suite\n") # Test the utility function # await test_hooks_utility() # Show usage with Docker client # await test_docker_client_with_functions() await test_docker_client_with_strings() # Show different patterns # await show_usage_patterns() # print("\n" + "=" * 60) # print("โœ“ All tests completed successfully!") # print("=" * 60) # print("\nKey Benefits:") # print(" โ€ข Write hooks as regular Python functions") # print(" โ€ข IDE support with autocomplete and type checking") # print(" โ€ข Automatic conversion to API format") # print(" โ€ข Backward compatible with string hooks") # print(" โ€ข Same utility used everywhere") # print("\n") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/docker/test_hooks_utility.py", "license": "Apache License 2.0", "lines": 153, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/docker/test_llm_params.py
#!/usr/bin/env python3 """ Test script for LLM temperature and base_url parameters in Crawl4AI Docker API. This demonstrates the new hierarchical configuration system: 1. Request-level parameters (highest priority) 2. Provider-specific environment variables 3. Global environment variables 4. System defaults (lowest priority) """ import asyncio import httpx import json import os from rich.console import Console from rich.panel import Panel from rich.syntax import Syntax from rich.table import Table console = Console() # Configuration BASE_URL = "http://localhost:11235" # Docker API endpoint TEST_URL = "https://httpbin.org/html" # Simple test page # --- Helper Functions --- async def check_server_health(client: httpx.AsyncClient) -> bool: """Check if the server is healthy.""" console.print("[bold cyan]Checking server health...[/]", end="") try: response = await client.get("/health", timeout=10.0) response.raise_for_status() console.print(" [bold green]โœ“ Server is healthy![/]") return True except Exception as e: console.print(f"\n[bold red]โœ— Server health check failed: {e}[/]") console.print(f"Is the server running at {BASE_URL}?") return False def print_request(endpoint: str, payload: dict, title: str = "Request"): """Pretty print the request.""" syntax = Syntax(json.dumps(payload, indent=2), "json", theme="monokai") console.print(Panel.fit( f"[cyan]POST {endpoint}[/cyan]\n{syntax}", title=f"[bold blue]{title}[/]", border_style="blue" )) def print_response(response: dict, title: str = "Response"): """Pretty print relevant parts of the response.""" # Extract only the relevant parts relevant = {} if "markdown" in response: relevant["markdown"] = response["markdown"][:200] + "..." if len(response.get("markdown", "")) > 200 else response.get("markdown", "") if "success" in response: relevant["success"] = response["success"] if "url" in response: relevant["url"] = response["url"] if "filter" in response: relevant["filter"] = response["filter"] console.print(Panel.fit( Syntax(json.dumps(relevant, indent=2), "json", theme="monokai"), title=f"[bold green]{title}[/]", border_style="green" )) # --- Test Functions --- async def test_default_no_params(client: httpx.AsyncClient): """Test 1: No temperature or base_url specified - uses defaults""" console.rule("[bold yellow]Test 1: Default Configuration (No Parameters)[/]") payload = { "url": TEST_URL, "f": "llm", "q": "What is the main heading of this page? Answer in exactly 5 words." } print_request("/md", payload, "Request without temperature/base_url") try: response = await client.post("/md", json=payload, timeout=30.0) response.raise_for_status() data = response.json() print_response(data, "Response (using system defaults)") console.print("[dim]โ†’ This used system defaults or environment variables if set[/]") except Exception as e: console.print(f"[red]Error: {e}[/]") async def test_request_temperature(client: httpx.AsyncClient): """Test 2: Request-level temperature (highest priority)""" console.rule("[bold yellow]Test 2: Request-Level Temperature[/]") # Test with low temperature (more focused) payload_low = { "url": TEST_URL, "f": "llm", "q": "What is the main heading? Be creative and poetic.", "temperature": 0.1 # Very low - should be less creative } print_request("/md", payload_low, "Low Temperature (0.1)") try: response = await client.post("/md", json=payload_low, timeout=30.0) response.raise_for_status() data_low = response.json() print_response(data_low, "Response with Low Temperature") console.print("[dim]โ†’ Low temperature (0.1) should produce focused, less creative output[/]") except Exception as e: console.print(f"[red]Error: {e}[/]") console.print() # Test with high temperature (more creative) payload_high = { "url": TEST_URL, "f": "llm", "q": "What is the main heading? Be creative and poetic.", "temperature": 1.5 # High - should be more creative } print_request("/md", payload_high, "High Temperature (1.5)") try: response = await client.post("/md", json=payload_high, timeout=30.0) response.raise_for_status() data_high = response.json() print_response(data_high, "Response with High Temperature") console.print("[dim]โ†’ High temperature (1.5) should produce more creative, varied output[/]") except Exception as e: console.print(f"[red]Error: {e}[/]") async def test_provider_override(client: httpx.AsyncClient): """Test 3: Provider override with temperature""" console.rule("[bold yellow]Test 3: Provider Override with Temperature[/]") provider = "gemini/gemini-2.5-flash-lite" payload = { "url": TEST_URL, "f": "llm", "q": "Summarize this page in one sentence.", "provider": provider, # Explicitly set provider "temperature": 0.7 } print_request("/md", payload, "Provider + Temperature Override") try: response = await client.post("/md", json=payload, timeout=30.0) response.raise_for_status() data = response.json() print_response(data, "Response with Provider Override") console.print(f"[dim]โ†’ This explicitly uses {provider} with temperature 0.7[/]") except Exception as e: console.print(f"[red]Error: {e}[/]") async def test_base_url_custom(client: httpx.AsyncClient): """Test 4: Custom base_url (will fail unless you have a custom endpoint)""" console.rule("[bold yellow]Test 4: Custom Base URL (Demo Only)[/]") payload = { "url": TEST_URL, "f": "llm", "q": "What is this page about?", "base_url": "https://api.custom-endpoint.com/v1", # Custom endpoint "temperature": 0.5 } print_request("/md", payload, "Custom Base URL Request") console.print("[yellow]Note: This will fail unless you have a custom endpoint set up[/]") try: response = await client.post("/md", json=payload, timeout=10.0) response.raise_for_status() data = response.json() print_response(data, "Response from Custom Endpoint") except httpx.HTTPStatusError as e: console.print(f"[yellow]Expected failure (no custom endpoint): Status {e.response.status_code}[/]") except Exception as e: console.print(f"[yellow]Expected error: {e}[/]") async def test_llm_job_endpoint(client: httpx.AsyncClient): """Test 5: Test the /llm/job endpoint with temperature and base_url""" console.rule("[bold yellow]Test 5: LLM Job Endpoint with Parameters[/]") payload = { "url": TEST_URL, "q": "Extract the main title and any key information", "temperature": 0.3, # "base_url": "https://api.openai.com/v1" # Optional } print_request("/llm/job", payload, "LLM Job with Temperature") try: # Submit the job response = await client.post("/llm/job", json=payload, timeout=30.0) response.raise_for_status() job_data = response.json() if "task_id" in job_data: task_id = job_data["task_id"] console.print(f"[green]Job created with task_id: {task_id}[/]") # Poll for result (simplified - in production use proper polling) await asyncio.sleep(3) status_response = await client.get(f"/llm/job/{task_id}") status_data = status_response.json() if status_data.get("status") == "completed": console.print("[green]Job completed successfully![/]") if "result" in status_data: console.print(Panel.fit( Syntax(json.dumps(status_data["result"], indent=2), "json", theme="monokai"), title="Extraction Result", border_style="green" )) else: console.print(f"[yellow]Job status: {status_data.get('status', 'unknown')}[/]") else: console.print(f"[red]Unexpected response: {job_data}[/]") except Exception as e: console.print(f"[red]Error: {e}[/]") async def test_llm_endpoint(client: httpx.AsyncClient): """ Quick QA round-trip with /llm. Asks a trivial question against SIMPLE_URL just to show wiring. """ import time import urllib.parse page_url = "https://kidocode.com" question = "What is the title of this page?" enc = urllib.parse.quote_plus(page_url, safe="") console.print(f"GET /llm/{enc}?q={question}") try: t0 = time.time() resp = await client.get(f"/llm/{enc}", params={"q": question}) dt = time.time() - t0 console.print( f"Response Status: [bold {'green' if resp.is_success else 'red'}]{resp.status_code}[/] (took {dt:.2f}s)") resp.raise_for_status() answer = resp.json().get("answer", "") console.print(Panel(answer or "No answer returned", title="LLM answer", border_style="magenta", expand=False)) except Exception as e: console.print(f"[bold red]Error hitting /llm:[/] {e}") async def show_environment_info(): """Display current environment configuration""" console.rule("[bold cyan]Current Environment Configuration[/]") table = Table(title="LLM Environment Variables", show_header=True, header_style="bold magenta") table.add_column("Variable", style="cyan", width=30) table.add_column("Value", style="yellow") table.add_column("Description", style="dim") env_vars = [ ("LLM_PROVIDER", "Global default provider"), ("LLM_TEMPERATURE", "Global default temperature"), ("LLM_BASE_URL", "Global custom API endpoint"), ("OPENAI_API_KEY", "OpenAI API key"), ("OPENAI_TEMPERATURE", "OpenAI-specific temperature"), ("OPENAI_BASE_URL", "OpenAI-specific endpoint"), ("ANTHROPIC_API_KEY", "Anthropic API key"), ("ANTHROPIC_TEMPERATURE", "Anthropic-specific temperature"), ("GROQ_API_KEY", "Groq API key"), ("GROQ_TEMPERATURE", "Groq-specific temperature"), ] for var, desc in env_vars: value = os.environ.get(var, "[not set]") if "API_KEY" in var and value != "[not set]": # Mask API keys for security value = value[:10] + "..." if len(value) > 10 else "***" table.add_row(var, value, desc) console.print(table) console.print() # --- Main Test Runner --- async def main(): """Run all tests""" console.print(Panel.fit( "[bold cyan]Crawl4AI LLM Parameters Test Suite[/]\n" + "Testing temperature and base_url configuration hierarchy", border_style="cyan" )) # Show current environment # await show_environment_info() # Create HTTP client async with httpx.AsyncClient(base_url=BASE_URL, timeout=60.0) as client: # Check server health if not await check_server_health(client): console.print("[red]Server is not available. Please ensure the Docker container is running.[/]") return # Run tests tests = [ ("Default Configuration", test_default_no_params), ("Request Temperature", test_request_temperature), ("Provider Override", test_provider_override), ("Custom Base URL", test_base_url_custom), ("LLM Job Endpoint", test_llm_job_endpoint), ("LLM Endpoint", test_llm_endpoint), ] for i, (name, test_func) in enumerate(tests, 1): if i > 1: console.print() # Add spacing between tests try: await test_func(client) except Exception as e: console.print(f"[red]Test '{name}' failed with error: {e}[/]") console.print_exception(show_locals=False) console.rule("[bold green]All Tests Complete![/]", style="green") # Summary console.print("\n[bold cyan]Configuration Hierarchy Summary:[/]") console.print("1. [yellow]Request parameters[/] - Highest priority (temperature, base_url in API call)") console.print("2. [yellow]Provider-specific env[/] - e.g., OPENAI_TEMPERATURE, GROQ_BASE_URL") console.print("3. [yellow]Global env variables[/] - LLM_TEMPERATURE, LLM_BASE_URL") console.print("4. [yellow]System defaults[/] - Lowest priority (provider/litellm defaults)") console.print() if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: console.print("\n[yellow]Tests interrupted by user.[/]") except Exception as e: console.print(f"\n[bold red]An error occurred:[/]") console.print_exception(show_locals=False)
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/docker/test_llm_params.py", "license": "Apache License 2.0", "lines": 289, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/general/test_bff_scoring.py
#!/usr/bin/env python3 """ Simple test to verify BestFirstCrawlingStrategy fixes. This test crawls a real website and shows that: 1. Higher-scoring pages are crawled first (priority queue fix) 2. Links are scored before truncation (link discovery fix) """ import asyncio from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig from crawl4ai.deep_crawling import BestFirstCrawlingStrategy from crawl4ai.deep_crawling.scorers import KeywordRelevanceScorer async def test_best_first_strategy(): """Test BestFirstCrawlingStrategy with keyword scoring""" print("=" * 70) print("Testing BestFirstCrawlingStrategy with Real URL") print("=" * 70) print("\nThis test will:") print("1. Crawl Python.org documentation") print("2. Score pages based on keywords: 'tutorial', 'guide', 'reference'") print("3. Show that higher-scoring pages are crawled first") print("-" * 70) # Create a keyword scorer that prioritizes tutorial/guide pages scorer = KeywordRelevanceScorer( keywords=["tutorial", "guide", "reference", "documentation"], weight=1.0, case_sensitive=False ) # Create the strategy with scoring strategy = BestFirstCrawlingStrategy( max_depth=2, # Crawl 2 levels deep max_pages=10, # Limit to 10 pages total url_scorer=scorer, # Use keyword scoring include_external=False # Only internal links ) # Configure browser and crawler browser_config = BrowserConfig( headless=True, # Run in background verbose=False # Reduce output noise ) crawler_config = CrawlerRunConfig( deep_crawl_strategy=strategy, verbose=False ) print("\nStarting crawl of https://docs.python.org/3/") print("Looking for pages with keywords: tutorial, guide, reference, documentation") print("-" * 70) crawled_urls = [] async with AsyncWebCrawler(config=browser_config) as crawler: # Crawl and collect results results = await crawler.arun( url="https://docs.python.org/3/", config=crawler_config ) # Process results if isinstance(results, list): for result in results: score = result.metadata.get('score', 0) if result.metadata else 0 depth = result.metadata.get('depth', 0) if result.metadata else 0 crawled_urls.append({ 'url': result.url, 'score': score, 'depth': depth, 'success': result.success }) print("\n" + "=" * 70) print("CRAWL RESULTS (in order of crawling)") print("=" * 70) for i, item in enumerate(crawled_urls, 1): status = "โœ“" if item['success'] else "โœ—" # Highlight high-scoring pages if item['score'] > 0.5: print(f"{i:2}. [{status}] Score: {item['score']:.2f} | Depth: {item['depth']} | {item['url']}") print(f" ^ HIGH SCORE - Contains keywords!") else: print(f"{i:2}. [{status}] Score: {item['score']:.2f} | Depth: {item['depth']} | {item['url']}") print("\n" + "=" * 70) print("ANALYSIS") print("=" * 70) # Check if higher scores appear early in the crawl scores = [item['score'] for item in crawled_urls[1:]] # Skip initial URL high_score_indices = [i for i, s in enumerate(scores) if s > 0.3] if high_score_indices and high_score_indices[0] < len(scores) / 2: print("โœ… SUCCESS: Higher-scoring pages (with keywords) were crawled early!") print(" This confirms the priority queue fix is working.") else: print("โš ๏ธ Check the crawl order above - higher scores should appear early") # Show score distribution print(f"\nScore Statistics:") print(f" - Total pages crawled: {len(crawled_urls)}") print(f" - Average score: {sum(item['score'] for item in crawled_urls) / len(crawled_urls):.2f}") print(f" - Max score: {max(item['score'] for item in crawled_urls):.2f}") print(f" - Pages with keywords: {sum(1 for item in crawled_urls if item['score'] > 0.3)}") print("\n" + "=" * 70) print("TEST COMPLETE") print("=" * 70) if __name__ == "__main__": print("\n๐Ÿ” BestFirstCrawlingStrategy Simple Test\n") asyncio.run(test_best_first_strategy())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/general/test_bff_scoring.py", "license": "Apache License 2.0", "lines": 98, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/proxy/test_proxy_deprecation.py
import warnings import pytest from crawl4ai.async_configs import BrowserConfig, ProxyConfig def test_browser_config_proxy_string_emits_deprecation_and_autoconverts(): warnings.simplefilter("always", DeprecationWarning) proxy_str = "23.95.150.145:6114:username:password" with warnings.catch_warnings(record=True) as caught: cfg = BrowserConfig(proxy=proxy_str, headless=True) dep_warnings = [w for w in caught if issubclass(w.category, DeprecationWarning)] assert dep_warnings, "Expected DeprecationWarning when using BrowserConfig(proxy=...)" assert cfg.proxy is None, "cfg.proxy should be None after auto-conversion" assert isinstance(cfg.proxy_config, ProxyConfig), "cfg.proxy_config should be ProxyConfig instance" assert cfg.proxy_config.username == "username" assert cfg.proxy_config.password == "password" assert cfg.proxy_config.server.startswith("http://") assert cfg.proxy_config.server.endswith(":6114") def test_browser_config_with_proxy_config_emits_no_deprecation(): warnings.simplefilter("always", DeprecationWarning) with warnings.catch_warnings(record=True) as caught: cfg = BrowserConfig( headless=True, proxy_config={ "server": "http://127.0.0.1:8080", "username": "u", "password": "p", }, ) dep_warnings = [w for w in caught if issubclass(w.category, DeprecationWarning)] assert not dep_warnings, "Did not expect DeprecationWarning when using proxy_config" assert cfg.proxy is None assert isinstance(cfg.proxy_config, ProxyConfig)
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/proxy/test_proxy_deprecation.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_preserve_https_for_internal_links.py
#!/usr/bin/env python3 """ Final test and demo for HTTPS preservation feature (Issue #1410) This demonstrates how the preserve_https_for_internal_links flag prevents HTTPS downgrade when servers redirect to HTTP. """ import sys import os from urllib.parse import urljoin, urlparse def demonstrate_issue(): """Show the problem: HTTPS -> HTTP redirect causes HTTP links""" print("=" * 60) print("DEMONSTRATING THE ISSUE") print("=" * 60) # Simulate what happens during crawling original_url = "https://quotes.toscrape.com/tag/deep-thoughts" redirected_url = "http://quotes.toscrape.com/tag/deep-thoughts/" # Server redirects to HTTP # Extract a relative link relative_link = "/author/Albert-Einstein" # Standard URL joining uses the redirected (HTTP) base resolved_url = urljoin(redirected_url, relative_link) print(f"Original URL: {original_url}") print(f"Redirected to: {redirected_url}") print(f"Relative link: {relative_link}") print(f"Resolved link: {resolved_url}") print(f"\nโŒ Problem: Link is now HTTP instead of HTTPS!") return resolved_url def demonstrate_solution(): """Show the solution: preserve HTTPS for internal links""" print("\n" + "=" * 60) print("DEMONSTRATING THE SOLUTION") print("=" * 60) # Our normalize_url with HTTPS preservation def normalize_url_with_preservation(href, base_url, preserve_https=False, original_scheme=None): """Normalize URL with optional HTTPS preservation""" # Standard resolution full_url = urljoin(base_url, href.strip()) # Preserve HTTPS if requested if preserve_https and original_scheme == 'https': parsed_full = urlparse(full_url) parsed_base = urlparse(base_url) # Only for same-domain links if parsed_full.scheme == 'http' and parsed_full.netloc == parsed_base.netloc: full_url = full_url.replace('http://', 'https://', 1) print(f" โ†’ Preserved HTTPS for {parsed_full.netloc}") return full_url # Same scenario as before original_url = "https://quotes.toscrape.com/tag/deep-thoughts" redirected_url = "http://quotes.toscrape.com/tag/deep-thoughts/" relative_link = "/author/Albert-Einstein" # Without preservation (current behavior) resolved_without = normalize_url_with_preservation( relative_link, redirected_url, preserve_https=False, original_scheme='https' ) print(f"\nWithout preservation:") print(f" Result: {resolved_without}") # With preservation (new feature) resolved_with = normalize_url_with_preservation( relative_link, redirected_url, preserve_https=True, original_scheme='https' ) print(f"\nWith preservation (preserve_https_for_internal_links=True):") print(f" Result: {resolved_with}") print(f"\nโœ… Solution: Internal link stays HTTPS!") return resolved_with def test_edge_cases(): """Test important edge cases""" print("\n" + "=" * 60) print("EDGE CASES") print("=" * 60) from urllib.parse import urljoin, urlparse def preserve_https(href, base_url, original_scheme): """Helper to test preservation logic""" full_url = urljoin(base_url, href) if original_scheme == 'https': parsed_full = urlparse(full_url) parsed_base = urlparse(base_url) # Fixed: check for protocol-relative URLs if (parsed_full.scheme == 'http' and parsed_full.netloc == parsed_base.netloc and not href.strip().startswith('//')): full_url = full_url.replace('http://', 'https://', 1) return full_url test_cases = [ # (description, href, base_url, original_scheme, should_be_https) ("External link", "http://other.com/page", "http://example.com", "https", False), ("Already HTTPS", "/page", "https://example.com", "https", True), ("No original HTTPS", "/page", "http://example.com", "http", False), ("Subdomain", "/page", "http://sub.example.com", "https", True), ("Protocol-relative", "//example.com/page", "http://example.com", "https", False), ] for desc, href, base_url, orig_scheme, should_be_https in test_cases: result = preserve_https(href, base_url, orig_scheme) is_https = result.startswith('https://') status = "โœ…" if is_https == should_be_https else "โŒ" print(f"\n{status} {desc}:") print(f" Input: {href} + {base_url}") print(f" Result: {result}") print(f" Expected HTTPS: {should_be_https}, Got: {is_https}") def usage_example(): """Show how to use the feature in crawl4ai""" print("\n" + "=" * 60) print("USAGE IN CRAWL4AI") print("=" * 60) print(""" To enable HTTPS preservation in your crawl4ai code: ```python from crawl4ai import AsyncWebCrawler, CrawlerRunConfig async with AsyncWebCrawler() as crawler: config = CrawlerRunConfig( preserve_https_for_internal_links=True # Enable HTTPS preservation ) result = await crawler.arun( url="https://example.com", config=config ) # All internal links will maintain HTTPS even if # the server redirects to HTTP ``` This is especially useful for: - Sites that redirect HTTPS to HTTP but still support HTTPS - Security-conscious crawling where you want to stay on HTTPS - Avoiding mixed content issues in downstream processing """) if __name__ == "__main__": # Run all demonstrations demonstrate_issue() demonstrate_solution() test_edge_cases() usage_example() print("\n" + "=" * 60) print("โœ… All tests complete!") print("=" * 60)
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_preserve_https_for_internal_links.py", "license": "Apache License 2.0", "lines": 134, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:crawl4ai/table_extraction.py
""" Table extraction strategies for Crawl4AI. This module provides various strategies for detecting and extracting tables from HTML content. The strategy pattern allows for flexible table extraction methods while maintaining a consistent interface. """ from abc import ABC, abstractmethod from typing import Dict, List, Optional, Any, Union, Tuple from lxml import etree import re import json from .types import LLMConfig, create_llm_config from .utils import perform_completion_with_backoff, sanitize_html import os from concurrent.futures import ThreadPoolExecutor, as_completed import time import tiktoken class TableExtractionStrategy(ABC): """ Abstract base class for all table extraction strategies. This class defines the interface that all table extraction strategies must implement. It provides a consistent way to detect and extract tables from HTML content. """ def __init__(self, **kwargs): """ Initialize the table extraction strategy. Args: **kwargs: Additional keyword arguments for specific strategies """ self.verbose = kwargs.get("verbose", False) self.logger = kwargs.get("logger", None) @abstractmethod def extract_tables(self, element: etree.Element, **kwargs) -> List[Dict[str, Any]]: """ Extract tables from the given HTML element. Args: element: The HTML element (typically the body or a container element) **kwargs: Additional parameters for extraction Returns: List of dictionaries containing table data, each with: - headers: List of column headers - rows: List of row data (each row is a list) - caption: Table caption if present - summary: Table summary attribute if present - metadata: Additional metadata about the table """ pass def _log(self, level: str, message: str, tag: str = "TABLE", **kwargs): """Helper method to safely use logger.""" if self.logger: log_method = getattr(self.logger, level, None) if log_method: log_method(message=message, tag=tag, **kwargs) class DefaultTableExtraction(TableExtractionStrategy): """ Default table extraction strategy that implements the current Crawl4AI table extraction logic. This strategy uses a scoring system to identify data tables (vs layout tables) and extracts structured data including headers, rows, captions, and summaries. It handles colspan and rowspan attributes to preserve table structure. """ def __init__(self, **kwargs): """ Initialize the default table extraction strategy. Args: table_score_threshold (int): Minimum score for a table to be considered a data table (default: 7) min_rows (int): Minimum number of rows for a valid table (default: 0) min_cols (int): Minimum number of columns for a valid table (default: 0) **kwargs: Additional parameters passed to parent class """ super().__init__(**kwargs) self.table_score_threshold = kwargs.get("table_score_threshold", 7) self.min_rows = kwargs.get("min_rows", 0) self.min_cols = kwargs.get("min_cols", 0) def extract_tables(self, element: etree.Element, **kwargs) -> List[Dict[str, Any]]: """ Extract all data tables from the HTML element. Args: element: The HTML element to search for tables **kwargs: Additional parameters (can override instance settings) Returns: List of dictionaries containing extracted table data """ tables_data = [] # Allow kwargs to override instance settings score_threshold = kwargs.get("table_score_threshold", self.table_score_threshold) # Find all table elements tables = element.xpath(".//table") for table in tables: # Check if this is a data table (not a layout table) if self.is_data_table(table, table_score_threshold=score_threshold): try: table_data = self.extract_table_data(table) # Apply minimum size filters if specified if self.min_rows > 0 and len(table_data.get("rows", [])) < self.min_rows: continue if self.min_cols > 0: col_count = len(table_data.get("headers", [])) or ( max(len(row) for row in table_data.get("rows", [])) if table_data.get("rows") else 0 ) if col_count < self.min_cols: continue tables_data.append(table_data) except Exception as e: self._log("error", f"Error extracting table data: {str(e)}", "TABLE_EXTRACT") continue return tables_data def is_data_table(self, table: etree.Element, **kwargs) -> bool: """ Determine if a table is a data table (vs. layout table) using a scoring system. Args: table: The table element to evaluate **kwargs: Additional parameters (e.g., table_score_threshold) Returns: True if the table scores above the threshold, False otherwise """ score = 0 # Check for thead and tbody has_thead = len(table.xpath(".//thead")) > 0 has_tbody = len(table.xpath(".//tbody")) > 0 if has_thead: score += 2 if has_tbody: score += 1 # Check for th elements th_count = len(table.xpath(".//th")) if th_count > 0: score += 2 if has_thead or table.xpath(".//tr[1]/th"): score += 1 # Check for nested tables (negative indicator) if len(table.xpath(".//table")) > 0: score -= 3 # Role attribute check role = table.get("role", "").lower() if role in {"presentation", "none"}: score -= 3 # Column consistency rows = table.xpath(".//tr") if not rows: return False col_counts = [len(row.xpath(".//td|.//th")) for row in rows] if col_counts: avg_cols = sum(col_counts) / len(col_counts) variance = sum((c - avg_cols)**2 for c in col_counts) / len(col_counts) if variance < 1: score += 2 # Caption and summary if table.xpath(".//caption"): score += 2 if table.get("summary"): score += 1 # Text density total_text = sum( len(''.join(cell.itertext()).strip()) for row in rows for cell in row.xpath(".//td|.//th") ) total_tags = sum(1 for _ in table.iterdescendants()) text_ratio = total_text / (total_tags + 1e-5) if text_ratio > 20: score += 3 elif text_ratio > 10: score += 2 # Data attributes data_attrs = sum(1 for attr in table.attrib if attr.startswith('data-')) score += data_attrs * 0.5 # Size check if col_counts and len(rows) >= 2: avg_cols = sum(col_counts) / len(col_counts) if avg_cols >= 2: score += 2 threshold = kwargs.get("table_score_threshold", self.table_score_threshold) return score >= threshold def extract_table_data(self, table: etree.Element) -> Dict[str, Any]: """ Extract structured data from a table element. Args: table: The table element to extract data from Returns: Dictionary containing: - headers: List of column headers - rows: List of row data (each row is a list) - caption: Table caption if present - summary: Table summary attribute if present - metadata: Additional metadata about the table """ # Extract caption and summary caption = table.xpath(".//caption/text()") caption = caption[0].strip() if caption else "" summary = table.get("summary", "").strip() # Extract headers with colspan handling headers = [] thead_rows = table.xpath(".//thead/tr") if thead_rows: header_cells = thead_rows[0].xpath(".//th") for cell in header_cells: text = cell.text_content().strip() colspan = int(cell.get("colspan", 1)) headers.extend([text] * colspan) else: # Check first row for headers first_row = table.xpath(".//tr[1]") if first_row: for cell in first_row[0].xpath(".//th|.//td"): text = cell.text_content().strip() colspan = int(cell.get("colspan", 1)) headers.extend([text] * colspan) # Extract rows with colspan handling rows = [] for row in table.xpath(".//tr[not(ancestor::thead)]"): row_data = [] for cell in row.xpath(".//td"): text = cell.text_content().strip() colspan = int(cell.get("colspan", 1)) row_data.extend([text] * colspan) if row_data: rows.append(row_data) # Align rows with headers max_columns = len(headers) if headers else ( max(len(row) for row in rows) if rows else 0 ) aligned_rows = [] for row in rows: aligned = row[:max_columns] + [''] * (max_columns - len(row)) aligned_rows.append(aligned) # Generate default headers if none found if not headers and max_columns > 0: headers = [f"Column {i+1}" for i in range(max_columns)] # Build metadata metadata = { "row_count": len(aligned_rows), "column_count": max_columns, "has_headers": bool(thead_rows) or bool(table.xpath(".//tr[1]/th")), "has_caption": bool(caption), "has_summary": bool(summary) } # Add table attributes that might be useful if table.get("id"): metadata["id"] = table.get("id") if table.get("class"): metadata["class"] = table.get("class") return { "headers": headers, "rows": aligned_rows, "caption": caption, "summary": summary, "metadata": metadata } class NoTableExtraction(TableExtractionStrategy): """ A strategy that does not extract any tables. This can be used to explicitly disable table extraction when needed. """ def extract_tables(self, element: etree.Element, **kwargs) -> List[Dict[str, Any]]: """ Return an empty list (no tables extracted). Args: element: The HTML element (ignored) **kwargs: Additional parameters (ignored) Returns: Empty list """ return [] class LLMTableExtraction(TableExtractionStrategy): """ LLM-based table extraction strategy that uses language models to intelligently extract and structure table data, handling complex cases like rowspan, colspan, and nested tables. This strategy uses an LLM to understand table structure semantically and convert it to structured data that can be easily consumed by pandas DataFrames. """ # System prompt for table extraction TABLE_EXTRACTION_PROMPT = """You are a specialized table extraction system that converts complex HTML tables into structured JSON data. Your primary goal is to handle difficult, irregular HTML tables that cannot be easily parsed by standard tools, transforming them into clean, tabulated data. ## Critical Requirements **IMPORTANT**: You must extract **EVERY SINGLE ROW** from the table, regardless of size. Tables often contain hundreds of rows, and omitting data is unacceptable. The reason we use an LLM for this task is because these tables have complex structures that standard parsers cannot handle properly. ## Output Format **Your response must be valid JSON**. The output must be properly formatted, parseable JSON with: - Proper escaping of quotes in strings - Valid JSON syntax (commas, brackets, etc.) - No trailing commas - Proper handling of special characters ## Table Structure Every table should be extracted as a JSON object with this structure: ```json { "headers": ["Column 1", "Column 2", ...], "rows": [ ["Row 1 Col 1", "Row 1 Col 2", ...], ["Row 2 Col 1", "Row 2 Col 2", ...], // ... continue for ALL rows ... ], "caption": "Table caption if present", "summary": "Table summary attribute if present", "metadata": { "row_count": <actual_number_of_rows>, "column_count": <number>, "has_headers": <boolean>, "has_merged_cells": <boolean>, "nested_tables": <boolean>, "table_type": "data|pivot|matrix|nested" } } ``` ## Handling Complex Structures ### Why This Matters Standard HTML parsers fail on tables with: - Complex colspan/rowspan arrangements - Nested tables - Irregular structures - Mixed header patterns Your job is to intelligently interpret these structures and produce clean, regular data. ### Colspan (Merged Columns) When a cell spans multiple columns, duplicate the value across all spanned columns to maintain rectangular data structure. Example HTML: ```html <tr> <td colspan="3">Quarterly Report</td> <td>Total</td> </tr> ``` Becomes: ["Quarterly Report", "Quarterly Report", "Quarterly Report", "Total"] ### Rowspan (Merged Rows) When a cell spans multiple rows, duplicate the value down all affected rows. Example with many rows: ```html <tr> <td rowspan="50">Category A</td> <td>Item 1</td> <td>$100</td> </tr> <tr> <td>Item 2</td> <td>$200</td> </tr> <!-- ... 48 more rows ... --> ``` Result structure (response must be valid JSON): ```json { "headers": ["Category", "Item", "Price"], "rows": [ ["Category A", "Item 1", "$100"], ["Category A", "Item 2", "$200"], ["Category A", "Item 3", "$300"], ["Category A", "Item 4", "$400"], ["Category A", "Item 5", "$500"], // ... ALL 50 rows must be included ... ["Category A", "Item 50", "$5000"] ], "metadata": { "row_count": 50, "column_count": 3, "has_headers": true, "has_merged_cells": true, "nested_tables": false, "table_type": "data" } } ``` ### Nested Tables For tables containing other tables: 1. Extract the outer table structure 2. Represent nested tables as a JSON string or structured representation 3. Ensure the data remains usable ## Complete Examples ### Example 1: Large Table with Complex Structure Input HTML (abbreviated for documentation): ```html <table> <thead> <tr> <th rowspan="2">Department</th> <th colspan="4">2024 Performance</th> </tr> <tr> <th>Q1</th> <th>Q2</th> <th>Q3</th> <th>Q4</th> </tr> </thead> <tbody> <tr> <td rowspan="15">Sales</td> <td>Region North</td> <td>$1.2M</td> <td>$1.5M</td> <td>$1.8M</td> </tr> <tr> <td>Region South</td> <td>$0.9M</td> <td>$1.1M</td> <td>$1.3M</td> </tr> <!-- ... 13 more regions ... --> <tr> <td rowspan="20">Engineering</td> <td>Team Alpha</td> <td>85%</td> <td>88%</td> <td>92%</td> </tr> <!-- ... 19 more teams ... --> <!-- ... continue for 200+ total rows ... --> </tbody> </table> ``` Output (showing structure with all rows) - must be valid JSON: ```json { "headers": ["Department", "Team/Region", "Q1", "Q2", "Q3", "Q4"], "rows": [ ["Sales", "Region North", "$1.2M", "$1.5M", "$1.8M"], ["Sales", "Region South", "$0.9M", "$1.1M", "$1.3M"], ["Sales", "Region East", "$1.1M", "$1.4M", "$1.6M"], ["Sales", "Region West", "$1.0M", "$1.2M", "$1.5M"], ["Sales", "Region Central", "$0.8M", "$1.0M", "$1.2M"], // ... ALL 15 Sales rows must be included ... ["Engineering", "Team Alpha", "85%", "88%", "92%"], ["Engineering", "Team Beta", "82%", "85%", "89%"], ["Engineering", "Team Gamma", "88%", "90%", "93%"], // ... ALL 20 Engineering rows must be included ... // ... Continue for EVERY row in the table ... ], "caption": "", "summary": "", "metadata": { "row_count": 235, "column_count": 6, "has_headers": true, "has_merged_cells": true, "nested_tables": false, "table_type": "data" } } ``` ### Example 2: Pivot Table with Hundreds of Rows Input structure: ```html <table> <tr> <th>Product ID</th> <th>Jan</th> <th>Feb</th> <!-- ... all 12 months ... --> </tr> <tr> <td>PROD-001</td> <td>1,234</td> <td>1,456</td> <!-- ... --> </tr> <!-- ... 500+ product rows ... --> </table> ``` Output must include ALL rows and be valid JSON: ```json { "headers": ["Product ID", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "rows": [ ["PROD-001", "1,234", "1,456", "1,789", "2,012", "2,234", "2,456", "2,678", "2,890", "3,123", "3,345", "3,567", "3,789"], ["PROD-002", "2,345", "2,567", "2,789", "3,012", "3,234", "3,456", "3,678", "3,890", "4,123", "4,345", "4,567", "4,789"], ["PROD-003", "3,456", "3,678", "3,890", "4,123", "4,345", "4,567", "4,789", "5,012", "5,234", "5,456", "5,678", "5,890"], // ... ALL 500+ rows MUST be included ... ["PROD-547", "9,876", "10,098", "10,321", "10,543", "10,765", "10,987", "11,210", "11,432", "11,654", "11,876", "12,098", "12,321"] ], "metadata": { "row_count": 547, "column_count": 13, "has_headers": true, "has_merged_cells": false, "nested_tables": false, "table_type": "pivot" } } ``` ## Critical Data Integrity Rules 1. **COMPLETENESS**: Extract EVERY row, no matter how many (10, 100, 1000+) 2. **ACCURACY**: Preserve exact values, including formatting 3. **STRUCTURE**: Maintain consistent column count across all rows 4. **VALIDATION**: Ensure output is valid JSON that can be parsed 5. **ESCAPING**: Properly escape quotes and special characters in cell values ## Special Handling Instructions ### Large Tables - Never abbreviate or summarize - Never use "..." to indicate omitted rows - Process every row even if it takes significant time - The metadata row_count must match actual extracted rows ### Complex Merged Cells - Track rowspan/colspan values carefully - Ensure proper cell duplication - Maintain data alignment across all rows ### Data Types - Keep numbers as strings to preserve formatting - Preserve currency symbols, percentages, etc. - Handle empty cells as empty strings "" ### Error Prevention - If a cell contains quotes, escape them properly - Handle newlines within cells appropriately - Ensure no JSON syntax errors ## Output Validation Before returning results: 1. Verify JSON is valid and parseable 2. Confirm row count matches actual data 3. Check that all rows have same column count 4. Ensure all data is preserved without truncation ## JSON Schema Definition Your output must conform to the following JSON schema (OpenAPI 3.0 format): { "components": { "schemas": { "ExtractedTable": { "type": "object", "required": [ "headers", "rows", "metadata" ], "properties": { "headers": { "type": "array", "description": "Column headers for the table", "items": { "type": "string" }, "minItems": 1 }, "rows": { "type": "array", "description": "All table rows - must include every single row", "items": { "type": "array", "items": { "type": "string" }, "minItems": 1 } }, "caption": { "type": "string", "description": "Table caption if present", "default": "" }, "summary": { "type": "string", "description": "Table summary attribute if present", "default": "" }, "metadata": { "type": "object", "required": [ "row_count", "column_count", "has_headers", "has_merged_cells", "nested_tables", "table_type" ], "properties": { "row_count": { "type": "integer", "description": "Actual count of rows extracted", "minimum": 0 }, "column_count": { "type": "integer", "description": "Number of columns in the table", "minimum": 1 }, "has_headers": { "type": "boolean", "description": "Whether table has identified headers" }, "has_merged_cells": { "type": "boolean", "description": "Whether table contains colspan or rowspan" }, "nested_tables": { "type": "boolean", "description": "Whether table contains nested tables" }, "table_type": { "type": "string", "enum": ["data", "pivot", "matrix", "nested"], "description": "Classification of table structure" } } } } } } } } **CRITICAL**: Your response must be a valid JSON object that conforms to this schema. The entire purpose of using an LLM for this task is to handle complex HTML tables that standard parsers cannot process correctly. Your value lies in intelligently interpreting complex structures and returning complete, clean, tabulated data in valid JSON format.""" def __init__(self, llm_config: Optional[LLMConfig] = None, css_selector: Optional[str] = None, max_tries: int = 3, enable_chunking: bool = True, chunk_token_threshold: int = 3000, min_rows_per_chunk: int = 10, max_parallel_chunks: int = 5, verbose: bool = False, **kwargs): """ Initialize the LLM-based table extraction strategy. Args: llm_config: LLM configuration for the extraction css_selector: Optional CSS selector to focus on specific page areas max_tries: Maximum number of retries if LLM fails to extract tables (default: 3) enable_chunking: Enable smart chunking for large tables (default: True) chunk_token_threshold: Token threshold for triggering chunking (default: 3000) min_rows_per_chunk: Minimum rows per chunk (default: 10) max_parallel_chunks: Maximum parallel chunk processing (default: 5) verbose: Enable verbose logging **kwargs: Additional parameters passed to parent class """ super().__init__(verbose=verbose, **kwargs) # Set up LLM configuration self.llm_config = llm_config if not self.llm_config: # Use default configuration if not provided self.llm_config = create_llm_config( provider=os.getenv("DEFAULT_PROVIDER", "openai/gpt-4o-mini"), api_token=os.getenv("OPENAI_API_KEY"), ) self.css_selector = css_selector self.max_tries = max(1, max_tries) # Ensure at least 1 try self.enable_chunking = enable_chunking self.chunk_token_threshold = chunk_token_threshold self.min_rows_per_chunk = max(5, min_rows_per_chunk) # At least 5 rows per chunk self.max_parallel_chunks = max(1, max_parallel_chunks) self.extra_args = kwargs.get("extra_args", {}) def extract_tables(self, element: etree.Element, **kwargs) -> List[Dict[str, Any]]: """ Extract tables from HTML using LLM. Args: element: The HTML element to search for tables **kwargs: Additional parameters Returns: List of dictionaries containing extracted table data """ # Allow CSS selector override via kwargs css_selector = kwargs.get("css_selector", self.css_selector) # Get the HTML content to process if css_selector: # Use XPath to convert CSS selector (basic conversion) # For more complex CSS selectors, we might need a proper CSS to XPath converter selected_elements = self._css_to_xpath_select(element, css_selector) if not selected_elements: self._log("warning", f"No elements found for CSS selector: {css_selector}") return [] html_content = ''.join(etree.tostring(elem, encoding='unicode') for elem in selected_elements) else: # Process entire element html_content = etree.tostring(element, encoding='unicode') # Check if there are any tables in the content if '<table' not in html_content.lower(): if self.verbose: self._log("info", f"No <table> tags found in HTML content") return [] if self.verbose: self._log("info", f"Found table tags in HTML, content length: {len(html_content)}") # Check if chunking is needed if self.enable_chunking and self._needs_chunking(html_content): if self.verbose: self._log("info", "Content exceeds token threshold, using chunked extraction") return self._extract_with_chunking(html_content) # Single extraction for small content # Prepare the prompt user_prompt = f"""GENERATE THE TABULATED DATA from the following HTML content: ```html {sanitize_html(html_content)} ``` Return only a JSON array of extracted tables following the specified format.""" # Try extraction with retries for attempt in range(1, self.max_tries + 1): try: if self.verbose and attempt > 1: self._log("info", f"Retry attempt {attempt}/{self.max_tries} for table extraction") # Call LLM with the extraction prompt response = perform_completion_with_backoff( provider=self.llm_config.provider, prompt_with_variables=self.TABLE_EXTRACTION_PROMPT + "\n\n" + user_prompt + "\n\n MAKE SURE TO EXTRACT ALL DATA, DO NOT LEAVE ANYTHING FOR BRAVITY, YOUR GOAL IS TO RETURN ALL, NO MATTER HOW LONG IS DATA", api_token=self.llm_config.api_token, base_url=self.llm_config.base_url, json_response=True, base_delay=self.llm_config.backoff_base_delay, max_attempts=self.llm_config.backoff_max_attempts, exponential_factor=self.llm_config.backoff_exponential_factor, extra_args=self.extra_args ) # Parse the response if response and response.choices: content = response.choices[0].message.content if self.verbose: self._log("debug", f"LLM response type: {type(content)}") if isinstance(content, str): self._log("debug", f"LLM response preview: {content[:200]}...") # Parse JSON response if isinstance(content, str): tables_data = json.loads(content) else: tables_data = content # Handle various response formats from LLM # Sometimes LLM wraps response in "result" or other keys if isinstance(tables_data, dict): # Check for common wrapper keys if 'result' in tables_data: tables_data = tables_data['result'] elif 'tables' in tables_data: tables_data = tables_data['tables'] elif 'data' in tables_data: tables_data = tables_data['data'] else: # If it's a single table dict, wrap in list tables_data = [tables_data] # Flatten nested lists if needed while isinstance(tables_data, list) and len(tables_data) == 1 and isinstance(tables_data[0], list): tables_data = tables_data[0] # Ensure we have a list if not isinstance(tables_data, list): tables_data = [tables_data] if self.verbose: self._log("debug", f"Parsed {len(tables_data)} table(s) from LLM response") # Validate and clean the extracted tables validated_tables = [] for table in tables_data: if self._validate_table_structure(table): validated_tables.append(self._ensure_table_format(table)) elif self.verbose: self._log("warning", f"Table failed validation: {table}") # Check if we got valid tables if validated_tables: if self.verbose: self._log("info", f"Successfully extracted {len(validated_tables)} tables using LLM on attempt {attempt}") return validated_tables # If no valid tables but we still have attempts left, retry if attempt < self.max_tries: if self.verbose: self._log("warning", f"No valid tables extracted on attempt {attempt}, retrying...") continue else: if self.verbose: self._log("warning", f"No valid tables extracted after {self.max_tries} attempts") return [] except json.JSONDecodeError as e: if self.verbose: self._log("error", f"JSON parsing error on attempt {attempt}: {str(e)}") if attempt < self.max_tries: continue else: return [] except Exception as e: if self.verbose: self._log("error", f"Error in LLM table extraction on attempt {attempt}: {str(e)}") if attempt == self.max_tries: import traceback self._log("debug", f"Traceback: {traceback.format_exc()}") # For unexpected errors, retry if we have attempts left if attempt < self.max_tries: # Add a small delay before retry for rate limiting import time time.sleep(1) continue else: return [] # Should not reach here, but return empty list as fallback return [] def _estimate_tokens(self, text: str) -> int: """ Estimate token count for text. Uses tiktoken for OpenAI models, simple approximation for others. """ try: # Try to use tiktoken for accurate counting if 'gpt' in self.llm_config.provider.lower(): encoding = tiktoken.encoding_for_model("gpt-3.5-turbo") return len(encoding.encode(text)) except: pass # Fallback: rough approximation (1 token โ‰ˆ 4 characters) return len(text) // 4 def _needs_chunking(self, html_content: str) -> bool: """ Check if table HTML needs chunking based on token count. """ if not self.enable_chunking: return False token_count = self._estimate_tokens(html_content) needs_chunk = token_count > self.chunk_token_threshold if self.verbose and needs_chunk: self._log("info", f"Table needs chunking: {token_count} tokens > {self.chunk_token_threshold} threshold") return needs_chunk def _extract_table_structure(self, html_content: str) -> Tuple[List[etree.Element], List[etree.Element], List[etree.Element], bool]: """ Extract headers, body rows, and footer from table HTML. Returns: Tuple of (header_rows, body_rows, footer_rows, has_headers) """ parser = etree.HTMLParser() tree = etree.fromstring(html_content, parser) # Find all tables tables = tree.xpath('.//table') if not tables: return [], [], [], False table = tables[0] # Process first table # Extract header rows (from thead or first rows with th) header_rows = [] thead = table.xpath('.//thead') if thead: header_rows = thead[0].xpath('.//tr') else: # Look for rows with th elements for row in table.xpath('.//tr'): if row.xpath('.//th'): header_rows.append(row) else: break # Track if we found headers has_headers = len(header_rows) > 0 # Extract footer rows footer_rows = [] tfoot = table.xpath('.//tfoot') if tfoot: footer_rows = tfoot[0].xpath('.//tr') # Extract body rows body_rows = [] tbody = table.xpath('.//tbody') if tbody: body_rows = tbody[0].xpath('.//tr') else: # Get all rows that aren't headers or footers all_rows = table.xpath('.//tr') header_count = len(header_rows) footer_count = len(footer_rows) if footer_count > 0: body_rows = all_rows[header_count:-footer_count] else: body_rows = all_rows[header_count:] # If no headers found and no tbody, all rows are body rows if not has_headers and not tbody: body_rows = tables[0].xpath('.//tr') return header_rows, body_rows, footer_rows, has_headers def _create_smart_chunks(self, html_content: str) -> Tuple[List[str], bool]: """ Create smart chunks of table HTML, preserving headers in each chunk. Returns: Tuple of (chunks, has_headers) """ if self.verbose: self._log("info", f"Creating smart chunks from {len(html_content)} characters of HTML") header_rows, body_rows, footer_rows, has_headers = self._extract_table_structure(html_content) if self.verbose: self._log("info", f"Table structure: {len(header_rows)} header rows, {len(body_rows)} body rows, {len(footer_rows)} footer rows") if not body_rows: if self.verbose: self._log("info", "No body rows to chunk, returning full content") return [html_content], has_headers # No rows to chunk # Create header HTML (to be included in every chunk) header_html = "" if header_rows: thead_element = etree.Element("thead") for row in header_rows: thead_element.append(row) header_html = etree.tostring(thead_element, encoding='unicode') # Calculate rows per chunk based on token estimates chunks = [] current_chunk_rows = [] current_token_count = self._estimate_tokens(header_html) for row in body_rows: row_html = etree.tostring(row, encoding='unicode') row_tokens = self._estimate_tokens(row_html) # Check if adding this row would exceed threshold if current_chunk_rows and (current_token_count + row_tokens > self.chunk_token_threshold): # Create chunk with current rows chunk_html = self._create_chunk_html(header_html, current_chunk_rows, None) chunks.append(chunk_html) # Start new chunk current_chunk_rows = [row_html] current_token_count = self._estimate_tokens(header_html) + row_tokens else: current_chunk_rows.append(row_html) current_token_count += row_tokens # Add remaining rows if current_chunk_rows: # Include footer only in the last chunk footer_html = None if footer_rows: tfoot_element = etree.Element("tfoot") for row in footer_rows: tfoot_element.append(row) footer_html = etree.tostring(tfoot_element, encoding='unicode') chunk_html = self._create_chunk_html(header_html, current_chunk_rows, footer_html) chunks.append(chunk_html) # Ensure minimum rows per chunk if len(chunks) > 1: chunks = self._rebalance_chunks(chunks, self.min_rows_per_chunk) if self.verbose: self._log("info", f"Created {len(chunks)} chunks for parallel processing") return chunks, has_headers def _create_chunk_html(self, header_html: str, body_rows: List[str], footer_html: Optional[str]) -> str: """ Create a complete table HTML chunk with headers, body rows, and optional footer. """ html_parts = ['<table>'] if header_html: html_parts.append(header_html) html_parts.append('<tbody>') html_parts.extend(body_rows) html_parts.append('</tbody>') if footer_html: html_parts.append(footer_html) html_parts.append('</table>') return ''.join(html_parts) def _rebalance_chunks(self, chunks: List[str], min_rows: int) -> List[str]: """ Rebalance chunks to ensure minimum rows per chunk. Merge small chunks if necessary. """ # This is a simplified implementation # In production, you'd want more sophisticated rebalancing return chunks def _process_chunk(self, chunk_html: str, chunk_index: int, total_chunks: int, has_headers: bool = True) -> Dict[str, Any]: """ Process a single chunk with the LLM. """ if self.verbose: self._log("info", f"Processing chunk {chunk_index + 1}/{total_chunks}") # Build context about headers header_context = "" if not has_headers: header_context = "\nIMPORTANT: This table has NO headers. Return an empty array for 'headers' field and extract all rows as data rows." # Add context about this being part of a larger table chunk_prompt = f"""Extract table data from this HTML chunk. This is part {chunk_index + 1} of {total_chunks} of a larger table. Focus on extracting the data rows accurately.{header_context} ```html {sanitize_html(chunk_html)} ``` Return only a JSON array of extracted tables following the specified format.""" for attempt in range(1, self.max_tries + 1): try: if self.verbose and attempt > 1: self._log("info", f"Retry attempt {attempt}/{self.max_tries} for chunk {chunk_index + 1}") response = perform_completion_with_backoff( provider=self.llm_config.provider, prompt_with_variables=self.TABLE_EXTRACTION_PROMPT + "\n\n" + chunk_prompt, api_token=self.llm_config.api_token, base_url=self.llm_config.base_url, json_response=True, base_delay=self.llm_config.backoff_base_delay, max_attempts=self.llm_config.backoff_max_attempts, exponential_factor=self.llm_config.backoff_exponential_factor, extra_args=self.extra_args ) if response and response.choices: content = response.choices[0].message.content # Parse JSON response if isinstance(content, str): tables_data = json.loads(content) else: tables_data = content # Handle various response formats if isinstance(tables_data, dict): if 'result' in tables_data: tables_data = tables_data['result'] elif 'tables' in tables_data: tables_data = tables_data['tables'] elif 'data' in tables_data: tables_data = tables_data['data'] else: tables_data = [tables_data] # Flatten nested lists while isinstance(tables_data, list) and len(tables_data) == 1 and isinstance(tables_data[0], list): tables_data = tables_data[0] if not isinstance(tables_data, list): tables_data = [tables_data] # Return first valid table (each chunk should have one table) for table in tables_data: if self._validate_table_structure(table): return { 'chunk_index': chunk_index, 'table': self._ensure_table_format(table) } # If no valid table, return empty result return {'chunk_index': chunk_index, 'table': None} except Exception as e: if self.verbose: self._log("error", f"Error processing chunk {chunk_index + 1}: {str(e)}") if attempt < self.max_tries: time.sleep(1) continue else: return {'chunk_index': chunk_index, 'table': None, 'error': str(e)} return {'chunk_index': chunk_index, 'table': None} def _merge_chunk_results(self, chunk_results: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """ Merge results from multiple chunks into a single table. """ # Sort by chunk index to maintain order chunk_results.sort(key=lambda x: x.get('chunk_index', 0)) # Filter out failed chunks valid_chunks = [r for r in chunk_results if r.get('table')] if not valid_chunks: return [] # Start with the first chunk's structure merged_table = valid_chunks[0]['table'].copy() # Concatenate rows from all chunks all_rows = [] for chunk_result in valid_chunks: table = chunk_result['table'] # Skip headers from non-first chunks (they're duplicates) rows = table.get('rows', []) all_rows.extend(rows) merged_table['rows'] = all_rows # Update metadata merged_table['metadata']['row_count'] = len(all_rows) merged_table['metadata']['chunked'] = True merged_table['metadata']['chunk_count'] = len(valid_chunks) if self.verbose: self._log("info", f"Merged {len(valid_chunks)} chunks into table with {len(all_rows)} rows") return [merged_table] def _extract_with_chunking(self, html_content: str) -> List[Dict[str, Any]]: """ Extract tables using chunking and parallel processing. """ if self.verbose: self._log("info", f"Starting chunked extraction for content with {len(html_content)} characters") # Create smart chunks chunks, has_headers = self._create_smart_chunks(html_content) if self.verbose: self._log("info", f"Created {len(chunks)} chunk(s) for processing") if len(chunks) == 1: # No need for parallel processing if self.verbose: self._log("info", "Processing as single chunk (no parallelization needed)") result = self._process_chunk(chunks[0], 0, 1, has_headers) return [result['table']] if result.get('table') else [] # Process chunks in parallel if self.verbose: self._log("info", f"Processing {len(chunks)} chunks in parallel (max workers: {self.max_parallel_chunks})") chunk_results = [] with ThreadPoolExecutor(max_workers=self.max_parallel_chunks) as executor: # Submit all chunks for processing futures = { executor.submit(self._process_chunk, chunk, i, len(chunks), has_headers): i for i, chunk in enumerate(chunks) } # Collect results as they complete for future in as_completed(futures): chunk_index = futures[future] try: result = future.result(timeout=60) # 60 second timeout per chunk if self.verbose: self._log("info", f"Chunk {chunk_index + 1}/{len(chunks)} completed successfully") chunk_results.append(result) except Exception as e: if self.verbose: self._log("error", f"Chunk {chunk_index + 1}/{len(chunks)} processing failed: {str(e)}") chunk_results.append({'chunk_index': chunk_index, 'table': None, 'error': str(e)}) if self.verbose: self._log("info", f"All chunks processed, merging results...") # Merge results return self._merge_chunk_results(chunk_results) def _css_to_xpath_select(self, element: etree.Element, css_selector: str) -> List[etree.Element]: """ Convert CSS selector to XPath and select elements. This is a basic implementation - for complex CSS selectors, consider using cssselect library. Args: element: Root element to search from css_selector: CSS selector string Returns: List of selected elements """ # Basic CSS to XPath conversion # This handles simple cases like "div", ".class", "#id", "div.class" xpath = css_selector # Handle ID selector if css_selector.startswith('#'): xpath = f".//*[@id='{css_selector[1:]}']" # Handle class selector elif css_selector.startswith('.'): xpath = f".//*[contains(@class, '{css_selector[1:]}')]" # Handle element with class elif '.' in css_selector: parts = css_selector.split('.') element_name = parts[0] class_name = parts[1] xpath = f".//{element_name}[contains(@class, '{class_name}')]" # Handle element with ID elif '#' in css_selector: parts = css_selector.split('#') element_name = parts[0] id_value = parts[1] xpath = f".//{element_name}[@id='{id_value}']" # Handle simple element selector else: xpath = f".//{css_selector}" try: return element.xpath(xpath) except Exception as e: self._log("warning", f"XPath conversion failed for selector '{css_selector}': {str(e)}") return [] def _validate_table_structure(self, table: Dict) -> bool: """ Validate that the table has the required structure. Args: table: Table dictionary to validate Returns: True if valid, False otherwise """ # Check required fields if not isinstance(table, dict): return False # Must have at least headers and rows if 'headers' not in table or 'rows' not in table: return False # Headers should be a list (but might be nested) headers = table.get('headers') if not isinstance(headers, list): return False # Flatten headers if nested while isinstance(headers, list) and len(headers) == 1 and isinstance(headers[0], list): table['headers'] = headers[0] headers = table['headers'] # Rows should be a list rows = table.get('rows') if not isinstance(rows, list): return False # Flatten rows if deeply nested cleaned_rows = [] for row in rows: # Handle multiple levels of nesting while isinstance(row, list) and len(row) == 1 and isinstance(row[0], list): row = row[0] cleaned_rows.append(row) table['rows'] = cleaned_rows # Each row should be a list for row in table.get('rows', []): if not isinstance(row, list): return False return True def _ensure_table_format(self, table: Dict) -> Dict[str, Any]: """ Ensure the table has all required fields with proper defaults. Args: table: Table dictionary to format Returns: Properly formatted table dictionary """ # Ensure all required fields exist formatted_table = { 'headers': table.get('headers', []), 'rows': table.get('rows', []), 'caption': table.get('caption', ''), 'summary': table.get('summary', ''), 'metadata': table.get('metadata', {}) } # Ensure metadata has basic fields if not formatted_table['metadata']: formatted_table['metadata'] = {} # Calculate metadata if not provided metadata = formatted_table['metadata'] if 'row_count' not in metadata: metadata['row_count'] = len(formatted_table['rows']) if 'column_count' not in metadata: metadata['column_count'] = len(formatted_table['headers']) if 'has_headers' not in metadata: metadata['has_headers'] = bool(formatted_table['headers']) # Ensure all rows have the same number of columns as headers col_count = len(formatted_table['headers']) if col_count > 0: for i, row in enumerate(formatted_table['rows']): if len(row) < col_count: # Pad with empty strings formatted_table['rows'][i] = row + [''] * (col_count - len(row)) elif len(row) > col_count: # Truncate extra columns formatted_table['rows'][i] = row[:col_count] return formatted_table
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/table_extraction.py", "license": "Apache License 2.0", "lines": 1181, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
unclecode/crawl4ai:docs/examples/llm_table_extraction_example.py
#!/usr/bin/env python3 """ Example demonstrating LLM-based table extraction in Crawl4AI. This example shows how to use the LLMTableExtraction strategy to extract complex tables from web pages, including handling rowspan, colspan, and nested tables. """ import os import sys # Get the grandparent directory grandparent_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(grandparent_dir) __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) import asyncio from crawl4ai import ( AsyncWebCrawler, CrawlerRunConfig, LLMConfig, LLMTableExtraction, CacheMode ) import pandas as pd # Example 1: Basic LLM Table Extraction async def basic_llm_extraction(): """Extract tables using LLM with default settings.""" print("\n=== Example 1: Basic LLM Table Extraction ===") # Configure LLM (using OpenAI GPT-4o-mini for cost efficiency) llm_config = LLMConfig( provider="openai/gpt-4.1-mini", api_token="env:OPENAI_API_KEY", # Uses environment variable temperature=0.1, # Low temperature for consistency max_tokens=32000 ) # Create LLM table extraction strategy table_strategy = LLMTableExtraction( llm_config=llm_config, verbose=True, # css_selector="div.mw-content-ltr", max_tries=2, enable_chunking=True, chunk_token_threshold=5000, # Lower threshold to force chunking min_rows_per_chunk=10, max_parallel_chunks=3 ) # Configure crawler with the strategy config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, table_extraction=table_strategy ) async with AsyncWebCrawler() as crawler: # Extract tables from a Wikipedia page result = await crawler.arun( url="https://en.wikipedia.org/wiki/List_of_chemical_elements", config=config ) if result.success: print(f"โœ“ Found {len(result.tables)} tables") # Display first table if result.tables: first_table = result.tables[0] print(f"\nFirst table:") print(f" Headers: {first_table['headers'][:5]}...") print(f" Rows: {len(first_table['rows'])}") # Convert to pandas DataFrame df = pd.DataFrame( first_table['rows'], columns=first_table['headers'] ) print(f"\nDataFrame shape: {df.shape}") print(df.head()) else: print(f"โœ— Extraction failed: {result.error}") # Example 2: Focused Extraction with CSS Selector async def focused_extraction(): """Extract tables from specific page sections using CSS selectors.""" print("\n=== Example 2: Focused Extraction with CSS Selector ===") # HTML with multiple tables test_html = """ <html> <body> <div class="sidebar"> <table role="presentation"> <tr><td>Navigation</td></tr> </table> </div> <div class="main-content"> <table id="data-table"> <caption>Quarterly Sales Report</caption> <thead> <tr> <th rowspan="2">Product</th> <th colspan="3">Q1 2024</th> </tr> <tr> <th>Jan</th> <th>Feb</th> <th>Mar</th> </tr> </thead> <tbody> <tr> <td>Widget A</td> <td>100</td> <td>120</td> <td>140</td> </tr> <tr> <td>Widget B</td> <td>200</td> <td>180</td> <td>220</td> </tr> </tbody> </table> </div> </body> </html> """ llm_config = LLMConfig( provider="openai/gpt-4.1-mini", api_token="env:OPENAI_API_KEY" ) # Focus only on main content area table_strategy = LLMTableExtraction( llm_config=llm_config, css_selector=".main-content", # Only extract from main content verbose=True ) config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, table_extraction=table_strategy ) async with AsyncWebCrawler() as crawler: result = await crawler.arun( url=f"raw:{test_html}", config=config ) if result.success and result.tables: table = result.tables[0] print(f"โœ“ Extracted table: {table.get('caption', 'No caption')}") print(f" Headers: {table['headers']}") print(f" Metadata: {table['metadata']}") # The LLM should have handled the rowspan/colspan correctly print("\nProcessed data (rowspan/colspan handled):") for i, row in enumerate(table['rows']): print(f" Row {i+1}: {row}") # Example 3: Comparing with Default Extraction async def compare_strategies(): """Compare LLM extraction with default extraction on complex tables.""" print("\n=== Example 3: Comparing LLM vs Default Extraction ===") # Complex table with nested structure complex_html = """ <html> <body> <table> <tr> <th rowspan="3">Category</th> <th colspan="2">2023</th> <th colspan="2">2024</th> </tr> <tr> <th>H1</th> <th>H2</th> <th>H1</th> <th>H2</th> </tr> <tr> <td colspan="4">All values in millions</td> </tr> <tr> <td>Revenue</td> <td>100</td> <td>120</td> <td>130</td> <td>145</td> </tr> <tr> <td>Profit</td> <td>20</td> <td>25</td> <td>28</td> <td>32</td> </tr> </table> </body> </html> """ async with AsyncWebCrawler() as crawler: # Test with default extraction from crawl4ai import DefaultTableExtraction default_strategy = DefaultTableExtraction( table_score_threshold=3, verbose=True ) config_default = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, table_extraction=default_strategy ) result_default = await crawler.arun( url=f"raw:{complex_html}", config=config_default ) # Test with LLM extraction llm_strategy = LLMTableExtraction( llm_config=LLMConfig( provider="openai/gpt-4.1-mini", api_token="env:OPENAI_API_KEY" ), verbose=True ) config_llm = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, table_extraction=llm_strategy ) result_llm = await crawler.arun( url=f"raw:{complex_html}", config=config_llm ) # Compare results print("\nDefault Extraction:") if result_default.tables: table = result_default.tables[0] print(f" Headers: {table.get('headers', [])}") print(f" Rows: {len(table.get('rows', []))}") for i, row in enumerate(table.get('rows', [])[:3]): print(f" Row {i+1}: {row}") print("\nLLM Extraction (handles complex structure better):") if result_llm.tables: table = result_llm.tables[0] print(f" Headers: {table.get('headers', [])}") print(f" Rows: {len(table.get('rows', []))}") for i, row in enumerate(table.get('rows', [])): print(f" Row {i+1}: {row}") print(f" Metadata: {table.get('metadata', {})}") # Example 4: Batch Processing Multiple Pages async def batch_extraction(): """Extract tables from multiple pages efficiently.""" print("\n=== Example 4: Batch Table Extraction ===") urls = [ "https://www.worldometers.info/geography/alphabetical-list-of-countries/", # "https://en.wikipedia.org/wiki/List_of_chemical_elements", ] llm_config = LLMConfig( provider="openai/gpt-4.1-mini", api_token="env:OPENAI_API_KEY", temperature=0.1, max_tokens=1500 ) table_strategy = LLMTableExtraction( llm_config=llm_config, css_selector="div.datatable-container", # Wikipedia data tables verbose=False, enable_chunking=True, chunk_token_threshold=5000, # Lower threshold to force chunking min_rows_per_chunk=10, max_parallel_chunks=3 ) config = CrawlerRunConfig( table_extraction=table_strategy, cache_mode=CacheMode.BYPASS ) all_tables = [] async with AsyncWebCrawler() as crawler: for url in urls: print(f"\nProcessing: {url.split('/')[-1][:50]}...") result = await crawler.arun(url=url, config=config) if result.success and result.tables: print(f" โœ“ Found {len(result.tables)} tables") # Store first table from each page if result.tables: all_tables.append({ 'url': url, 'table': result.tables[0] }) # Summary print(f"\n=== Summary ===") print(f"Extracted {len(all_tables)} tables from {len(urls)} pages") for item in all_tables: table = item['table'] print(f"\nFrom {item['url'].split('/')[-1][:30]}:") print(f" Columns: {len(table['headers'])}") print(f" Rows: {len(table['rows'])}") async def main(): """Run all examples.""" print("=" * 60) print("LLM TABLE EXTRACTION EXAMPLES") print("=" * 60) # Run examples (comment out ones you don't want to run) # Basic extraction await basic_llm_extraction() # # Focused extraction with CSS # await focused_extraction() # # Compare strategies # await compare_strategies() # # Batch processing # await batch_extraction() print("\n" + "=" * 60) print("ALL EXAMPLES COMPLETED") print("=" * 60) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/llm_table_extraction_example.py", "license": "Apache License 2.0", "lines": 300, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/table_extraction_example.py
""" Example: Using Table Extraction Strategies in Crawl4AI This example demonstrates how to use different table extraction strategies to extract tables from web pages. """ import asyncio import pandas as pd from crawl4ai import ( AsyncWebCrawler, CrawlerRunConfig, CacheMode, DefaultTableExtraction, NoTableExtraction, TableExtractionStrategy ) from typing import Dict, List, Any async def example_default_extraction(): """Example 1: Using default table extraction (automatic).""" print("\n" + "="*50) print("Example 1: Default Table Extraction") print("="*50) async with AsyncWebCrawler() as crawler: # No need to specify table_extraction - uses DefaultTableExtraction automatically config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, table_score_threshold=7 # Adjust sensitivity (default: 7) ) result = await crawler.arun( "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)", config=config ) if result.success and result.tables: print(f"Found {len(result.tables)} tables") # Convert first table to pandas DataFrame if result.tables: first_table = result.tables[0] df = pd.DataFrame( first_table['rows'], columns=first_table['headers'] if first_table['headers'] else None ) print(f"\nFirst table preview:") print(df.head()) print(f"Shape: {df.shape}") async def example_custom_configuration(): """Example 2: Custom table extraction configuration.""" print("\n" + "="*50) print("Example 2: Custom Table Configuration") print("="*50) async with AsyncWebCrawler() as crawler: # Create custom extraction strategy with specific settings table_strategy = DefaultTableExtraction( table_score_threshold=5, # Lower threshold for more permissive detection min_rows=3, # Only extract tables with at least 3 rows min_cols=2, # Only extract tables with at least 2 columns verbose=True ) config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, table_extraction=table_strategy, # Target specific tables using CSS selector css_selector="div.main-content" ) result = await crawler.arun( "https://example.com/data", config=config ) if result.success: print(f"Found {len(result.tables)} tables matching criteria") for i, table in enumerate(result.tables): print(f"\nTable {i+1}:") print(f" Caption: {table.get('caption', 'No caption')}") print(f" Size: {table['metadata']['row_count']} rows ร— {table['metadata']['column_count']} columns") print(f" Has headers: {table['metadata']['has_headers']}") async def example_disable_extraction(): """Example 3: Disable table extraction when not needed.""" print("\n" + "="*50) print("Example 3: Disable Table Extraction") print("="*50) async with AsyncWebCrawler() as crawler: # Use NoTableExtraction to skip table processing entirely config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, table_extraction=NoTableExtraction() # No tables will be extracted ) result = await crawler.arun( "https://example.com", config=config ) if result.success: print(f"Tables extracted: {len(result.tables)} (should be 0)") print("Table extraction disabled - better performance for non-table content") class FinancialTableExtraction(TableExtractionStrategy): """ Custom strategy for extracting financial tables with specific requirements. """ def __init__(self, currency_symbols=None, **kwargs): super().__init__(**kwargs) self.currency_symbols = currency_symbols or ['$', 'โ‚ฌ', 'ยฃ', 'ยฅ'] def extract_tables(self, element, **kwargs): """Extract only tables that appear to contain financial data.""" tables_data = [] for table in element.xpath(".//table"): # Check if table contains currency symbols table_text = ''.join(table.itertext()) has_currency = any(symbol in table_text for symbol in self.currency_symbols) if not has_currency: continue # Extract using base logic (could reuse DefaultTableExtraction logic) headers = [] rows = [] # Extract headers for th in table.xpath(".//thead//th | .//tr[1]//th"): headers.append(th.text_content().strip()) # Extract rows for tr in table.xpath(".//tbody//tr | .//tr[position()>1]"): row = [] for td in tr.xpath(".//td"): cell_text = td.text_content().strip() # Clean currency values for symbol in self.currency_symbols: cell_text = cell_text.replace(symbol, '') row.append(cell_text) if row: rows.append(row) if headers or rows: tables_data.append({ "headers": headers, "rows": rows, "caption": table.xpath(".//caption/text()")[0] if table.xpath(".//caption") else "", "summary": table.get("summary", ""), "metadata": { "type": "financial", "has_currency": True, "row_count": len(rows), "column_count": len(headers) if headers else len(rows[0]) if rows else 0 } }) return tables_data async def example_custom_strategy(): """Example 4: Custom table extraction strategy.""" print("\n" + "="*50) print("Example 4: Custom Financial Table Strategy") print("="*50) async with AsyncWebCrawler() as crawler: # Use custom strategy for financial tables config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, table_extraction=FinancialTableExtraction( currency_symbols=['$', 'โ‚ฌ'], verbose=True ) ) result = await crawler.arun( "https://finance.yahoo.com/", config=config ) if result.success: print(f"Found {len(result.tables)} financial tables") for table in result.tables: if table['metadata'].get('type') == 'financial': print(f" โœ“ Financial table with {table['metadata']['row_count']} rows") async def example_combined_extraction(): """Example 5: Combine table extraction with other strategies.""" print("\n" + "="*50) print("Example 5: Combined Extraction Strategies") print("="*50) from crawl4ai import LLMExtractionStrategy, LLMConfig async with AsyncWebCrawler() as crawler: # Define schema for structured extraction schema = { "type": "object", "properties": { "page_title": {"type": "string"}, "main_topic": {"type": "string"}, "key_figures": { "type": "array", "items": {"type": "string"} } } } config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, # Table extraction table_extraction=DefaultTableExtraction( table_score_threshold=6, min_rows=2 ), # LLM extraction for structured data extraction_strategy=LLMExtractionStrategy( llm_config=LLMConfig(provider="openai"), schema=schema ) ) result = await crawler.arun( "https://en.wikipedia.org/wiki/Economy_of_the_United_States", config=config ) if result.success: print(f"Tables found: {len(result.tables)}") # Tables are in result.tables if result.tables: print(f"First table has {len(result.tables[0]['rows'])} rows") # Structured data is in result.extracted_content if result.extracted_content: import json structured_data = json.loads(result.extracted_content) print(f"Page title: {structured_data.get('page_title', 'N/A')}") print(f"Main topic: {structured_data.get('main_topic', 'N/A')}") async def main(): """Run all examples.""" print("\n" + "="*60) print("CRAWL4AI TABLE EXTRACTION EXAMPLES") print("="*60) # Run examples await example_default_extraction() await example_custom_configuration() await example_disable_extraction() await example_custom_strategy() # await example_combined_extraction() # Requires OpenAI API key print("\n" + "="*60) print("EXAMPLES COMPLETED") print("="*60) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/table_extraction_example.py", "license": "Apache License 2.0", "lines": 224, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:tests/general/test_persistent_context.py
import asyncio import os from crawl4ai.async_webcrawler import AsyncWebCrawler from crawl4ai.async_configs import BrowserConfig, CrawlerRunConfig, CacheMode # Simple concurrency test for persistent context page creation # Usage: python scripts/test_persistent_context.py URLS = [ # "https://example.com", "https://httpbin.org/html", "https://www.python.org/", "https://www.rust-lang.org/", ] async def main(): profile_dir = os.path.join(os.path.expanduser("~"), ".crawl4ai", "profiles", "test-persistent-profile") os.makedirs(profile_dir, exist_ok=True) browser_config = BrowserConfig( browser_type="chromium", headless=True, use_persistent_context=True, user_data_dir=profile_dir, use_managed_browser=True, verbose=True, ) run_cfg = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, stream=False, verbose=True, ) async with AsyncWebCrawler(config=browser_config) as crawler: results = await crawler.arun_many(URLS, config=run_cfg) for r in results: print(r.url, r.success, len(r.markdown.raw_markdown) if r.markdown else 0) # r = await crawler.arun(url=URLS[0], config=run_cfg) # print(r.url, r.success, len(r.markdown.raw_markdown) if r.markdown else 0) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/general/test_persistent_context.py", "license": "Apache License 2.0", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/profiler/test_keyboard_handle.py
import sys import pytest import asyncio from unittest.mock import patch, MagicMock from crawl4ai.browser_profiler import BrowserProfiler @pytest.mark.asyncio @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific msvcrt test") async def test_keyboard_input_handling(): # Mock sequence of keystrokes: arrow key followed by 'q' mock_keys = [b'\x00K', b'q'] mock_kbhit = MagicMock(side_effect=[True, True, False]) mock_getch = MagicMock(side_effect=mock_keys) with patch('msvcrt.kbhit', mock_kbhit), patch('msvcrt.getch', mock_getch): # profiler = BrowserProfiler() user_done_event = asyncio.Event() # Create a local async function to simulate the keyboard input handling async def test_listen_for_quit_command(): if sys.platform == "win32": while True: try: if mock_kbhit(): raw = mock_getch() try: key = raw.decode("utf-8") except UnicodeDecodeError: continue if len(key) != 1 or not key.isprintable(): continue if key.lower() == "q": user_done_event.set() return await asyncio.sleep(0.1) except Exception as e: continue # Run the listener listener_task = asyncio.create_task(test_listen_for_quit_command()) # Wait for the event to be set try: await asyncio.wait_for(user_done_event.wait(), timeout=1.0) assert user_done_event.is_set() finally: if not listener_task.done(): listener_task.cancel() try: await listener_task except asyncio.CancelledError: pass
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/profiler/test_keyboard_handle.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/proxy/test_proxy_config.py
""" Comprehensive test suite for ProxyConfig in different forms: 1. String form (ip:port:username:password) 2. Dict form (dictionary with keys) 3. Object form (ProxyConfig instance) 4. Environment variable form (from env vars) Tests cover all possible scenarios and edge cases using pytest. """ import asyncio import os import pytest import tempfile from unittest.mock import patch from crawl4ai import AsyncWebCrawler, BrowserConfig from crawl4ai.async_configs import CrawlerRunConfig, ProxyConfig from crawl4ai.cache_context import CacheMode class TestProxyConfig: """Comprehensive test suite for ProxyConfig functionality.""" # Test data for different scenarios # get free proxy server from from webshare.io https://www.webshare.io/?referral_code=3sqog0y1fvsl TEST_PROXY_DATA = { "server": "", "username": "", "password": "", "ip": "" } def setup_method(self): """Setup for each test method.""" self.test_url = "https://httpbin.org/ip" # Use httpbin for testing # ==================== OBJECT FORM TESTS ==================== def test_proxy_config_object_creation_basic(self): """Test basic ProxyConfig object creation.""" proxy = ProxyConfig(server="127.0.0.1:8080") assert proxy.server == "127.0.0.1:8080" assert proxy.username is None assert proxy.password is None assert proxy.ip == "127.0.0.1" # Should auto-extract IP def test_proxy_config_object_creation_full(self): """Test ProxyConfig object creation with all parameters.""" proxy = ProxyConfig( server=f"http://{self.TEST_PROXY_DATA['server']}", username=self.TEST_PROXY_DATA['username'], password=self.TEST_PROXY_DATA['password'], ip=self.TEST_PROXY_DATA['ip'] ) assert proxy.server == f"http://{self.TEST_PROXY_DATA['server']}" assert proxy.username == self.TEST_PROXY_DATA['username'] assert proxy.password == self.TEST_PROXY_DATA['password'] assert proxy.ip == self.TEST_PROXY_DATA['ip'] def test_proxy_config_object_ip_extraction(self): """Test automatic IP extraction from server URL.""" test_cases = [ ("http://192.168.1.1:8080", "192.168.1.1"), ("https://10.0.0.1:3128", "10.0.0.1"), ("192.168.1.100:8080", "192.168.1.100"), ("proxy.example.com:8080", "proxy.example.com"), ] for server, expected_ip in test_cases: proxy = ProxyConfig(server=server) assert proxy.ip == expected_ip, f"Failed for server: {server}" def test_proxy_config_object_invalid_server(self): """Test ProxyConfig with invalid server formats.""" # Should not raise exception but may not extract IP properly proxy = ProxyConfig(server="invalid-format") assert proxy.server == "invalid-format" # IP extraction might fail but object should still be created # ==================== DICT FORM TESTS ==================== def test_proxy_config_from_dict_basic(self): """Test creating ProxyConfig from basic dictionary.""" proxy_dict = {"server": "127.0.0.1:8080"} proxy = ProxyConfig.from_dict(proxy_dict) assert proxy.server == "127.0.0.1:8080" assert proxy.username is None assert proxy.password is None def test_proxy_config_from_dict_full(self): """Test creating ProxyConfig from complete dictionary.""" proxy_dict = { "server": f"http://{self.TEST_PROXY_DATA['server']}", "username": self.TEST_PROXY_DATA['username'], "password": self.TEST_PROXY_DATA['password'], "ip": self.TEST_PROXY_DATA['ip'] } proxy = ProxyConfig.from_dict(proxy_dict) assert proxy.server == proxy_dict["server"] assert proxy.username == proxy_dict["username"] assert proxy.password == proxy_dict["password"] assert proxy.ip == proxy_dict["ip"] def test_proxy_config_from_dict_missing_keys(self): """Test creating ProxyConfig from dictionary with missing keys.""" proxy_dict = {"server": "127.0.0.1:8080", "username": "user"} proxy = ProxyConfig.from_dict(proxy_dict) assert proxy.server == "127.0.0.1:8080" assert proxy.username == "user" assert proxy.password is None assert proxy.ip == "127.0.0.1" # Should auto-extract def test_proxy_config_from_dict_empty(self): """Test creating ProxyConfig from empty dictionary.""" proxy_dict = {} proxy = ProxyConfig.from_dict(proxy_dict) assert proxy.server is None assert proxy.username is None assert proxy.password is None assert proxy.ip is None def test_proxy_config_from_dict_none_values(self): """Test creating ProxyConfig from dictionary with None values.""" proxy_dict = { "server": "127.0.0.1:8080", "username": None, "password": None, "ip": None } proxy = ProxyConfig.from_dict(proxy_dict) assert proxy.server == "127.0.0.1:8080" assert proxy.username is None assert proxy.password is None assert proxy.ip == "127.0.0.1" # Should auto-extract despite None # ==================== STRING FORM TESTS ==================== def test_proxy_config_from_string_full_format(self): """Test creating ProxyConfig from full string format (ip:port:username:password).""" proxy_str = f"{self.TEST_PROXY_DATA['ip']}:6114:{self.TEST_PROXY_DATA['username']}:{self.TEST_PROXY_DATA['password']}" proxy = ProxyConfig.from_string(proxy_str) assert proxy.server == f"http://{self.TEST_PROXY_DATA['ip']}:6114" assert proxy.username == self.TEST_PROXY_DATA['username'] assert proxy.password == self.TEST_PROXY_DATA['password'] assert proxy.ip == self.TEST_PROXY_DATA['ip'] def test_proxy_config_from_string_ip_port_only(self): """Test creating ProxyConfig from string with only ip:port.""" proxy_str = "192.168.1.1:8080" proxy = ProxyConfig.from_string(proxy_str) assert proxy.server == "http://192.168.1.1:8080" assert proxy.username is None assert proxy.password is None assert proxy.ip == "192.168.1.1" def test_proxy_config_from_string_invalid_format(self): """Test creating ProxyConfig from invalid string formats.""" invalid_formats = [ "invalid", "ip:port:user", # Missing password (3 parts) "ip:port:user:pass:extra", # Too many parts (5 parts) "", "::", # Empty parts but 3 total (invalid) "::::", # Empty parts but 5 total (invalid) ] for proxy_str in invalid_formats: with pytest.raises(ValueError, match="Invalid proxy string format"): ProxyConfig.from_string(proxy_str) def test_proxy_config_from_string_edge_cases_that_work(self): """Test string formats that should work but might be edge cases.""" # These cases actually work as valid formats edge_cases = [ (":", "http://:", ""), # ip:port format with empty values (":::", "http://:", ""), # ip:port:user:pass format with empty values ] for proxy_str, expected_server, expected_ip in edge_cases: proxy = ProxyConfig.from_string(proxy_str) assert proxy.server == expected_server assert proxy.ip == expected_ip def test_proxy_config_from_string_edge_cases(self): """Test string parsing edge cases.""" # Test with different port numbers proxy_str = "10.0.0.1:3128:user:pass" proxy = ProxyConfig.from_string(proxy_str) assert proxy.server == "http://10.0.0.1:3128" # Test with special characters in credentials proxy_str = "10.0.0.1:8080:user@domain:pass:word" with pytest.raises(ValueError): # Should fail due to extra colon in password ProxyConfig.from_string(proxy_str) # ==================== ENVIRONMENT VARIABLE TESTS ==================== def test_proxy_config_from_env_single_proxy(self): """Test loading single proxy from environment variable.""" proxy_str = f"{self.TEST_PROXY_DATA['ip']}:6114:{self.TEST_PROXY_DATA['username']}:{self.TEST_PROXY_DATA['password']}" with patch.dict(os.environ, {'TEST_PROXIES': proxy_str}): proxies = ProxyConfig.from_env('TEST_PROXIES') assert len(proxies) == 1 proxy = proxies[0] assert proxy.ip == self.TEST_PROXY_DATA['ip'] assert proxy.username == self.TEST_PROXY_DATA['username'] assert proxy.password == self.TEST_PROXY_DATA['password'] def test_proxy_config_from_env_multiple_proxies(self): """Test loading multiple proxies from environment variable.""" proxy_list = [ "192.168.1.1:8080:user1:pass1", "192.168.1.2:8080:user2:pass2", "10.0.0.1:3128" # No auth ] proxy_str = ",".join(proxy_list) with patch.dict(os.environ, {'TEST_PROXIES': proxy_str}): proxies = ProxyConfig.from_env('TEST_PROXIES') assert len(proxies) == 3 # Check first proxy assert proxies[0].ip == "192.168.1.1" assert proxies[0].username == "user1" assert proxies[0].password == "pass1" # Check second proxy assert proxies[1].ip == "192.168.1.2" assert proxies[1].username == "user2" assert proxies[1].password == "pass2" # Check third proxy (no auth) assert proxies[2].ip == "10.0.0.1" assert proxies[2].username is None assert proxies[2].password is None def test_proxy_config_from_env_empty_var(self): """Test loading from empty environment variable.""" with patch.dict(os.environ, {'TEST_PROXIES': ''}): proxies = ProxyConfig.from_env('TEST_PROXIES') assert len(proxies) == 0 def test_proxy_config_from_env_missing_var(self): """Test loading from missing environment variable.""" # Ensure the env var doesn't exist with patch.dict(os.environ, {}, clear=True): proxies = ProxyConfig.from_env('NON_EXISTENT_VAR') assert len(proxies) == 0 def test_proxy_config_from_env_with_empty_entries(self): """Test loading proxies with empty entries in the list.""" proxy_str = "192.168.1.1:8080:user:pass,,10.0.0.1:3128," with patch.dict(os.environ, {'TEST_PROXIES': proxy_str}): proxies = ProxyConfig.from_env('TEST_PROXIES') assert len(proxies) == 2 # Empty entries should be skipped assert proxies[0].ip == "192.168.1.1" assert proxies[1].ip == "10.0.0.1" def test_proxy_config_from_env_with_invalid_entries(self): """Test loading proxies with some invalid entries.""" proxy_str = "192.168.1.1:8080:user:pass,invalid_proxy,10.0.0.1:3128" with patch.dict(os.environ, {'TEST_PROXIES': proxy_str}): # Should handle errors gracefully and return valid proxies proxies = ProxyConfig.from_env('TEST_PROXIES') # Depending on implementation, might return partial list or empty # This tests error handling assert isinstance(proxies, list) # ==================== SERIALIZATION TESTS ==================== def test_proxy_config_to_dict(self): """Test converting ProxyConfig to dictionary.""" proxy = ProxyConfig( server=f"http://{self.TEST_PROXY_DATA['server']}", username=self.TEST_PROXY_DATA['username'], password=self.TEST_PROXY_DATA['password'], ip=self.TEST_PROXY_DATA['ip'] ) result_dict = proxy.to_dict() expected = { "server": f"http://{self.TEST_PROXY_DATA['server']}", "username": self.TEST_PROXY_DATA['username'], "password": self.TEST_PROXY_DATA['password'], "ip": self.TEST_PROXY_DATA['ip'] } assert result_dict == expected def test_proxy_config_clone(self): """Test cloning ProxyConfig with modifications.""" original = ProxyConfig( server="http://127.0.0.1:8080", username="user", password="pass" ) # Clone with modifications cloned = original.clone(username="new_user", password="new_pass") # Original should be unchanged assert original.username == "user" assert original.password == "pass" # Clone should have new values assert cloned.username == "new_user" assert cloned.password == "new_pass" assert cloned.server == original.server # Unchanged value def test_proxy_config_roundtrip_serialization(self): """Test that ProxyConfig can be serialized and deserialized without loss.""" original = ProxyConfig( server=f"http://{self.TEST_PROXY_DATA['server']}", username=self.TEST_PROXY_DATA['username'], password=self.TEST_PROXY_DATA['password'], ip=self.TEST_PROXY_DATA['ip'] ) # Serialize to dict and back serialized = original.to_dict() deserialized = ProxyConfig.from_dict(serialized) assert deserialized.server == original.server assert deserialized.username == original.username assert deserialized.password == original.password assert deserialized.ip == original.ip # ==================== INTEGRATION TESTS ==================== @pytest.mark.asyncio async def test_crawler_with_proxy_config_object(self): """Test AsyncWebCrawler with ProxyConfig object.""" proxy_config = ProxyConfig( server=f"http://{self.TEST_PROXY_DATA['server']}", username=self.TEST_PROXY_DATA['username'], password=self.TEST_PROXY_DATA['password'] ) browser_config = BrowserConfig(headless=True) # Test that the crawler accepts the ProxyConfig object without errors async with AsyncWebCrawler(config=browser_config) as crawler: try: # Note: This might fail due to actual proxy connection, but should not fail due to config issues result = await crawler.arun( url=self.test_url, config=CrawlerRunConfig( cache_mode=CacheMode.BYPASS, proxy_config=proxy_config, page_timeout=10000 # Short timeout for testing ) ) # If we get here, proxy config was accepted assert result is not None except Exception as e: # We expect connection errors with test proxies, but not config errors error_msg = str(e).lower() assert "attribute" not in error_msg, f"Config error: {e}" assert "proxy_config" not in error_msg, f"Proxy config error: {e}" @pytest.mark.asyncio async def test_crawler_with_proxy_config_dict(self): """Test AsyncWebCrawler with ProxyConfig from dictionary.""" proxy_dict = { "server": f"http://{self.TEST_PROXY_DATA['server']}", "username": self.TEST_PROXY_DATA['username'], "password": self.TEST_PROXY_DATA['password'] } proxy_config = ProxyConfig.from_dict(proxy_dict) browser_config = BrowserConfig(headless=True) async with AsyncWebCrawler(config=browser_config) as crawler: try: result = await crawler.arun( url=self.test_url, config=CrawlerRunConfig( cache_mode=CacheMode.BYPASS, proxy_config=proxy_config, page_timeout=10000 ) ) assert result is not None except Exception as e: error_msg = str(e).lower() assert "attribute" not in error_msg, f"Config error: {e}" @pytest.mark.asyncio async def test_crawler_with_proxy_config_from_string(self): """Test AsyncWebCrawler with ProxyConfig from string.""" proxy_str = f"{self.TEST_PROXY_DATA['ip']}:6114:{self.TEST_PROXY_DATA['username']}:{self.TEST_PROXY_DATA['password']}" proxy_config = ProxyConfig.from_string(proxy_str) browser_config = BrowserConfig(headless=True) async with AsyncWebCrawler(config=browser_config) as crawler: try: result = await crawler.arun( url=self.test_url, config=CrawlerRunConfig( cache_mode=CacheMode.BYPASS, proxy_config=proxy_config, page_timeout=10000 ) ) assert result is not None except Exception as e: error_msg = str(e).lower() assert "attribute" not in error_msg, f"Config error: {e}" # ==================== EDGE CASES AND ERROR HANDLING ==================== def test_proxy_config_with_none_server(self): """Test ProxyConfig behavior with None server.""" proxy = ProxyConfig(server=None) assert proxy.server is None assert proxy.ip is None # Should not crash def test_proxy_config_with_empty_string_server(self): """Test ProxyConfig behavior with empty string server.""" proxy = ProxyConfig(server="") assert proxy.server == "" assert proxy.ip is None or proxy.ip == "" def test_proxy_config_special_characters_in_credentials(self): """Test ProxyConfig with special characters in username/password.""" special_chars_tests = [ ("user@domain.com", "pass!@#$%"), ("user_123", "p@ssw0rd"), ("user-test", "pass-word"), ] for username, password in special_chars_tests: proxy = ProxyConfig( server="http://127.0.0.1:8080", username=username, password=password ) assert proxy.username == username assert proxy.password == password def test_proxy_config_unicode_handling(self): """Test ProxyConfig with unicode characters.""" proxy = ProxyConfig( server="http://127.0.0.1:8080", username="ใƒฆใƒผใ‚ถใƒผ", # Japanese characters password="ะฟะฐั€ะพะปัŒ" # Cyrillic characters ) assert proxy.username == "ใƒฆใƒผใ‚ถใƒผ" assert proxy.password == "ะฟะฐั€ะพะปัŒ" # ==================== PERFORMANCE TESTS ==================== def test_proxy_config_creation_performance(self): """Test that ProxyConfig creation is reasonably fast.""" import time start_time = time.time() for i in range(1000): proxy = ProxyConfig( server=f"http://192.168.1.{i % 255}:8080", username=f"user{i}", password=f"pass{i}" ) end_time = time.time() # Should be able to create 1000 configs in less than 1 second assert (end_time - start_time) < 1.0 def test_proxy_config_from_env_performance(self): """Test that loading many proxies from env is reasonably fast.""" import time # Create a large list of proxy strings proxy_list = [f"192.168.1.{i}:8080:user{i}:pass{i}" for i in range(100)] proxy_str = ",".join(proxy_list) with patch.dict(os.environ, {'PERF_TEST_PROXIES': proxy_str}): start_time = time.time() proxies = ProxyConfig.from_env('PERF_TEST_PROXIES') end_time = time.time() assert len(proxies) == 100 # Should be able to parse 100 proxies in less than 1 second assert (end_time - start_time) < 1.0 # ==================== STANDALONE TEST FUNCTIONS ==================== @pytest.mark.asyncio async def test_dict_proxy(): """Original test function for dict proxy - kept for backward compatibility.""" proxy_config = { "server": "23.95.150.145:6114", "username": "cfyswbwn", "password": "1gs266hoqysi" } proxy_config_obj = ProxyConfig.from_dict(proxy_config) browser_config = BrowserConfig(headless=True) async with AsyncWebCrawler(config=browser_config) as crawler: try: result = await crawler.arun(url="https://httpbin.org/ip", config=CrawlerRunConfig( stream=False, cache_mode=CacheMode.BYPASS, proxy_config=proxy_config_obj, page_timeout=10000 )) print("Dict proxy test passed!") print(result.markdown[:200] if result and result.markdown else "No result") except Exception as e: print(f"Dict proxy test error (expected): {e}") @pytest.mark.asyncio async def test_string_proxy(): """Test function for string proxy format.""" proxy_str = "23.95.150.145:6114:cfyswbwn:1gs266hoqysi" proxy_config_obj = ProxyConfig.from_string(proxy_str) browser_config = BrowserConfig(headless=True) async with AsyncWebCrawler(config=browser_config) as crawler: try: result = await crawler.arun(url="https://httpbin.org/ip", config=CrawlerRunConfig( stream=False, cache_mode=CacheMode.BYPASS, proxy_config=proxy_config_obj, page_timeout=10000 )) print("String proxy test passed!") print(result.markdown[:200] if result and result.markdown else "No result") except Exception as e: print(f"String proxy test error (expected): {e}") @pytest.mark.asyncio async def test_env_proxy(): """Test function for environment variable proxy.""" # Set environment variable os.environ['TEST_PROXIES'] = "23.95.150.145:6114:cfyswbwn:1gs266hoqysi" proxies = ProxyConfig.from_env('TEST_PROXIES') if proxies: proxy_config_obj = proxies[0] # Use first proxy browser_config = BrowserConfig(headless=True) async with AsyncWebCrawler(config=browser_config) as crawler: try: result = await crawler.arun(url="https://httpbin.org/ip", config=CrawlerRunConfig( stream=False, cache_mode=CacheMode.BYPASS, proxy_config=proxy_config_obj, page_timeout=10000 )) print("Environment proxy test passed!") print(result.markdown[:200] if result and result.markdown else "No result") except Exception as e: print(f"Environment proxy test error (expected): {e}") else: print("No proxies loaded from environment") if __name__ == "__main__": print("Running comprehensive ProxyConfig tests...") print("=" * 50) # Run the standalone test functions print("\n1. Testing dict proxy format...") asyncio.run(test_dict_proxy()) print("\n2. Testing string proxy format...") asyncio.run(test_string_proxy()) print("\n3. Testing environment variable proxy format...") asyncio.run(test_env_proxy()) print("\n" + "=" * 50) print("To run the full pytest suite, use: pytest " + __file__) print("=" * 50)
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/proxy/test_proxy_config.py", "license": "Apache License 2.0", "lines": 489, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_llm_simple_url.py
#!/usr/bin/env python3 """ Test LLMTableExtraction with controlled HTML """ import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import asyncio from crawl4ai import ( AsyncWebCrawler, CrawlerRunConfig, LLMConfig, LLMTableExtraction, DefaultTableExtraction, CacheMode ) async def test_controlled_html(): """Test with controlled HTML content.""" print("\n" + "=" * 60) print("LLM TABLE EXTRACTION TEST") print("=" * 60) url = "https://en.wikipedia.org/wiki/List_of_chemical_elements" # url = "https://en.wikipedia.org/wiki/List_of_prime_ministers_of_India" # Configure LLM llm_config = LLMConfig( # provider="openai/gpt-4.1-mini", # api_token=os.getenv("OPENAI_API_KEY"), provider="groq/llama-3.3-70b-versatile", api_token="GROQ_API_TOKEN", temperature=0.1, max_tokens=32000 ) print("\n1. Testing LLMTableExtraction:") # Create LLM extraction strategy llm_strategy = LLMTableExtraction( llm_config=llm_config, verbose=True, # css_selector="div.w3-example" css_selector="div.mw-content-ltr", # css_selector="table.wikitable", max_tries=2, enable_chunking=True, chunk_token_threshold=5000, # Lower threshold to force chunking min_rows_per_chunk=10, max_parallel_chunks=3 ) config_llm = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, table_extraction=llm_strategy ) async with AsyncWebCrawler() as crawler: # Test with LLM extraction result_llm = await crawler.arun( # url=f"raw:{test_html}", url=url, config=config_llm ) if result_llm.success: print(f"\n โœ“ LLM Extraction: Found {len(result_llm.tables)} table(s)") for i, table in enumerate(result_llm.tables, 1): print(f"\n Table {i}:") print(f" - Caption: {table.get('caption', 'No caption')}") print(f" - Headers: {table['headers']}") print(f" - Rows: {len(table['rows'])}") # Show how colspan/rowspan were handled print(f" - Sample rows:") for j, row in enumerate(table['rows'][:2], 1): print(f" Row {j}: {row}") metadata = table.get('metadata', {}) print(f" - Metadata:") print(f" โ€ข Has merged cells: {metadata.get('has_merged_cells', False)}") print(f" โ€ข Table type: {metadata.get('table_type', 'unknown')}") # # Compare with default extraction # print("\n2. Comparing with DefaultTableExtraction:") # default_strategy = DefaultTableExtraction( # table_score_threshold=3, # verbose=False # ) # config_default = CrawlerRunConfig( # cache_mode=CacheMode.BYPASS, # table_extraction=default_strategy # ) # result_default = await crawler.arun( # # url=f"raw:{test_html}", # url=url, # config=config_default # ) # if result_default.success: # print(f" โœ“ Default Extraction: Found {len(result_default.tables)} table(s)") # # Compare handling of complex structures # print("\n3. Comparison Summary:") # print(f" LLM found: {len(result_llm.tables)} tables") # print(f" Default found: {len(result_default.tables)} tables") # if result_llm.tables and result_default.tables: # llm_first = result_llm.tables[0] # default_first = result_default.tables[0] # print(f"\n First table comparison:") # print(f" LLM headers: {len(llm_first['headers'])} columns") # print(f" Default headers: {len(default_first['headers'])} columns") # # Check if LLM better handled the complex structure # if llm_first.get('metadata', {}).get('has_merged_cells'): # print(" โœ“ LLM correctly identified merged cells") # # Test pandas compatibility # try: # import pandas as pd # print("\n4. Testing Pandas compatibility:") # # Create DataFrame from LLM extraction # df_llm = pd.DataFrame( # llm_first['rows'], # columns=llm_first['headers'] # ) # print(f" โœ“ LLM table -> DataFrame: Shape {df_llm.shape}") # # Create DataFrame from default extraction # df_default = pd.DataFrame( # default_first['rows'], # columns=default_first['headers'] # ) # print(f" โœ“ Default table -> DataFrame: Shape {df_default.shape}") # print("\n LLM DataFrame preview:") # print(df_llm.head(2).to_string()) # except ImportError: # print("\n4. Pandas not installed, skipping DataFrame test") print("\nโœ… Test completed successfully!") async def main(): """Run the test.""" # Check for API key if not os.getenv("OPENAI_API_KEY"): print("โš ๏ธ OPENAI_API_KEY not set. Please set it to test LLM extraction.") print(" You can set it with: export OPENAI_API_KEY='your-key-here'") return await test_controlled_html() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_llm_simple_url.py", "license": "Apache License 2.0", "lines": 133, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:crawl4ai/async_crawler_strategy.back.py
from __future__ import annotations import asyncio import base64 import time from abc import ABC, abstractmethod from typing import Callable, Dict, Any, List, Union from typing import Optional, AsyncGenerator, Final import os from playwright.async_api import Page, Error from playwright.async_api import TimeoutError as PlaywrightTimeoutError from io import BytesIO from PIL import Image, ImageDraw, ImageFont import hashlib import uuid from .js_snippet import load_js_script from .models import AsyncCrawlResponse from .config import SCREENSHOT_HEIGHT_TRESHOLD from .async_configs import BrowserConfig, CrawlerRunConfig, HTTPCrawlerConfig from .async_logger import AsyncLogger from .ssl_certificate import SSLCertificate from .user_agent_generator import ValidUAGenerator from .browser_manager import BrowserManager import aiofiles import aiohttp import chardet from aiohttp.client import ClientTimeout from urllib.parse import urlparse from types import MappingProxyType import contextlib from functools import partial class AsyncCrawlerStrategy(ABC): """ Abstract base class for crawler strategies. Subclasses must implement the crawl method. """ @abstractmethod async def crawl(self, url: str, **kwargs) -> AsyncCrawlResponse: pass # 4 + 3 class AsyncPlaywrightCrawlerStrategy(AsyncCrawlerStrategy): """ Crawler strategy using Playwright. Attributes: browser_config (BrowserConfig): Configuration object containing browser settings. logger (AsyncLogger): Logger instance for recording events and errors. _downloaded_files (List[str]): List of downloaded file paths. hooks (Dict[str, Callable]): Dictionary of hooks for custom behavior. browser_manager (BrowserManager): Manager for browser creation and management. Methods: __init__(self, browser_config=None, logger=None, **kwargs): Initialize the AsyncPlaywrightCrawlerStrategy with a browser configuration. __aenter__(self): Start the browser and initialize the browser manager. __aexit__(self, exc_type, exc_val, exc_tb): Close the browser and clean up resources. start(self): Start the browser and initialize the browser manager. close(self): Close the browser and clean up resources. kill_session(self, session_id): Kill a browser session and clean up resources. crawl(self, url, **kwargs): Run the crawler for a single URL. """ def __init__( self, browser_config: BrowserConfig = None, logger: AsyncLogger = None, **kwargs ): """ Initialize the AsyncPlaywrightCrawlerStrategy with a browser configuration. Args: browser_config (BrowserConfig): Configuration object containing browser settings. If None, will be created from kwargs for backwards compatibility. logger: Logger instance for recording events and errors. **kwargs: Additional arguments for backwards compatibility and extending functionality. """ # Initialize browser config, either from provided object or kwargs self.browser_config = browser_config or BrowserConfig.from_kwargs(kwargs) self.logger = logger # Initialize session management self._downloaded_files = [] # Initialize hooks system self.hooks = { "on_browser_created": None, "on_page_context_created": None, "on_user_agent_updated": None, "on_execution_started": None, "on_execution_ended": None, "before_goto": None, "after_goto": None, "before_return_html": None, "before_retrieve_html": None, } # Initialize browser manager with config self.browser_manager = BrowserManager( browser_config=self.browser_config, logger=self.logger ) async def __aenter__(self): await self.start() return self async def __aexit__(self, exc_type, exc_val, exc_tb): await self.close() async def start(self): """ Start the browser and initialize the browser manager. """ await self.browser_manager.start() await self.execute_hook( "on_browser_created", self.browser_manager.browser, context=self.browser_manager.default_context, ) async def close(self): """ Close the browser and clean up resources. """ await self.browser_manager.close() # Explicitly reset the static Playwright instance BrowserManager._playwright_instance = None async def kill_session(self, session_id: str): """ Kill a browser session and clean up resources. Args: session_id (str): The ID of the session to kill. Returns: None """ # Log a warning message and no need kill session, in new version auto kill session self.logger.warning( message="Session auto-kill is enabled in the new version. No need to manually kill sessions.", tag="WARNING", ) await self.browser_manager.kill_session(session_id) def set_hook(self, hook_type: str, hook: Callable): """ Set a hook function for a specific hook type. Following are list of hook types: - on_browser_created: Called when a new browser instance is created. - on_page_context_created: Called when a new page context is created. - on_user_agent_updated: Called when the user agent is updated. - on_execution_started: Called when the execution starts. - before_goto: Called before a goto operation. - after_goto: Called after a goto operation. - before_return_html: Called before returning HTML content. - before_retrieve_html: Called before retrieving HTML content. All hooks except on_browser_created accepts a context and a page as arguments and **kwargs. However, on_browser_created accepts a browser and a context as arguments and **kwargs. Args: hook_type (str): The type of the hook. hook (Callable): The hook function to set. Returns: None """ if hook_type in self.hooks: self.hooks[hook_type] = hook else: raise ValueError(f"Invalid hook type: {hook_type}") async def execute_hook(self, hook_type: str, *args, **kwargs): """ Execute a hook function for a specific hook type. Args: hook_type (str): The type of the hook. *args: Variable length positional arguments. **kwargs: Keyword arguments. Returns: The return value of the hook function, if any. """ hook = self.hooks.get(hook_type) if hook: if asyncio.iscoroutinefunction(hook): return await hook(*args, **kwargs) else: return hook(*args, **kwargs) return args[0] if args else None def update_user_agent(self, user_agent: str): """ Update the user agent for the browser. Args: user_agent (str): The new user agent string. Returns: None """ self.user_agent = user_agent def set_custom_headers(self, headers: Dict[str, str]): """ Set custom headers for the browser. Args: headers (Dict[str, str]): A dictionary of headers to set. Returns: None """ self.headers = headers async def smart_wait(self, page: Page, wait_for: str, timeout: float = 30000): """ Wait for a condition in a smart way. This functions works as below: 1. If wait_for starts with 'js:', it assumes it's a JavaScript function and waits for it to return true. 2. If wait_for starts with 'css:', it assumes it's a CSS selector and waits for it to be present. 3. Otherwise, it tries to evaluate wait_for as a JavaScript function and waits for it to return true. 4. If it's not a JavaScript function, it assumes it's a CSS selector and waits for it to be present. This is a more advanced version of the wait_for parameter in CrawlerStrategy.crawl(). Args: page: Playwright page object wait_for (str): The condition to wait for. Can be a CSS selector, a JavaScript function, or explicitly prefixed with 'js:' or 'css:'. timeout (float): Maximum time to wait in milliseconds Returns: None """ wait_for = wait_for.strip() if wait_for.startswith("js:"): # Explicitly specified JavaScript js_code = wait_for[3:].strip() return await self.csp_compliant_wait(page, js_code, timeout) elif wait_for.startswith("css:"): # Explicitly specified CSS selector css_selector = wait_for[4:].strip() try: await page.wait_for_selector(css_selector, timeout=timeout) except Error as e: if "Timeout" in str(e): raise TimeoutError( f"Timeout after {timeout}ms waiting for selector '{css_selector}'" ) else: raise ValueError(f"Invalid CSS selector: '{css_selector}'") else: # Auto-detect based on content if wait_for.startswith("()") or wait_for.startswith("function"): # It's likely a JavaScript function return await self.csp_compliant_wait(page, wait_for, timeout) else: # Assume it's a CSS selector first try: await page.wait_for_selector(wait_for, timeout=timeout) except Error as e: if "Timeout" in str(e): raise TimeoutError( f"Timeout after {timeout}ms waiting for selector '{wait_for}'" ) else: # If it's not a timeout error, it might be an invalid selector # Let's try to evaluate it as a JavaScript function as a fallback try: return await self.csp_compliant_wait( page, f"() => {{{wait_for}}}", timeout ) except Error: raise ValueError( f"Invalid wait_for parameter: '{wait_for}'. " "It should be either a valid CSS selector, a JavaScript function, " "or explicitly prefixed with 'js:' or 'css:'." ) async def csp_compliant_wait( self, page: Page, user_wait_function: str, timeout: float = 30000 ): """ Wait for a condition in a CSP-compliant way. Args: page: Playwright page object user_wait_function: JavaScript function as string that returns boolean timeout: Maximum time to wait in milliseconds Returns: bool: True if condition was met, False if timed out Raises: RuntimeError: If there's an error evaluating the condition """ wrapper_js = f""" async () => {{ const userFunction = {user_wait_function}; const startTime = Date.now(); try {{ while (true) {{ if (await userFunction()) {{ return true; }} if (Date.now() - startTime > {timeout}) {{ return false; // Return false instead of throwing }} await new Promise(resolve => setTimeout(resolve, 100)); }} }} catch (error) {{ throw new Error(`Error evaluating condition: ${{error.message}}`); }} }} """ try: result = await page.evaluate(wrapper_js) return result except Exception as e: if "Error evaluating condition" in str(e): raise RuntimeError(f"Failed to evaluate wait condition: {str(e)}") # For timeout or other cases, just return False return False async def process_iframes(self, page): """ Process iframes on a page. This function will extract the content of each iframe and replace it with a div containing the extracted content. Args: page: Playwright page object Returns: Playwright page object """ # Find all iframes iframes = await page.query_selector_all("iframe") for i, iframe in enumerate(iframes): try: # Add a unique identifier to the iframe await iframe.evaluate(f'(element) => element.id = "iframe-{i}"') # Get the frame associated with this iframe frame = await iframe.content_frame() if frame: # Wait for the frame to load await frame.wait_for_load_state( "load", timeout=30000 ) # 30 seconds timeout # Extract the content of the iframe's body iframe_content = await frame.evaluate( "() => document.body.innerHTML" ) # Generate a unique class name for this iframe class_name = f"extracted-iframe-content-{i}" # Replace the iframe with a div containing the extracted content _iframe = iframe_content.replace("`", "\\`") await page.evaluate( f""" () => {{ const iframe = document.getElementById('iframe-{i}'); const div = document.createElement('div'); div.innerHTML = `{_iframe}`; div.className = '{class_name}'; iframe.replaceWith(div); }} """ ) else: self.logger.warning( message="Could not access content frame for iframe {index}", tag="SCRAPE", params={"index": i}, ) except Exception as e: self.logger.error( message="Error processing iframe {index}: {error}", tag="ERROR", params={"index": i, "error": str(e)}, ) # Return the page object return page async def create_session(self, **kwargs) -> str: """ Creates a new browser session and returns its ID. A browse session is a unique openned page can be reused for multiple crawls. This function is asynchronous and returns a string representing the session ID. Args: **kwargs: Optional keyword arguments to configure the session. Returns: str: The session ID. """ await self.start() session_id = kwargs.get("session_id") or str(uuid.uuid4()) user_agent = kwargs.get("user_agent", self.user_agent) # Use browser_manager to get a fresh page & context assigned to this session_id page, context = await self.browser_manager.get_page(CrawlerRunConfig( session_id=session_id, user_agent=user_agent, **kwargs, )) return session_id async def crawl( self, url: str, config: CrawlerRunConfig, **kwargs ) -> AsyncCrawlResponse: """ Crawls a given URL or processes raw HTML/local file content based on the URL prefix. Args: url (str): The URL to crawl. Supported prefixes: - 'http://' or 'https://': Web URL to crawl. - 'file://': Local file path to process. - 'raw://': Raw HTML content to process. **kwargs: Additional parameters: - 'screenshot' (bool): Whether to take a screenshot. - ... [other existing parameters] Returns: AsyncCrawlResponse: The response containing HTML, headers, status code, and optional screenshot. """ config = config or CrawlerRunConfig.from_kwargs(kwargs) response_headers = {} status_code = 200 # Default for local/raw HTML screenshot_data = None if url.startswith(("http://", "https://", "view-source:")): return await self._crawl_web(url, config) elif url.startswith("file://"): # initialize empty lists for console messages captured_console = [] # Process local file local_file_path = url[7:] # Remove 'file://' prefix if not os.path.exists(local_file_path): raise FileNotFoundError(f"Local file not found: {local_file_path}") with open(local_file_path, "r", encoding="utf-8") as f: html = f.read() if config.screenshot: screenshot_data = await self._generate_screenshot_from_html(html) if config.capture_console_messages: page, context = await self.browser_manager.get_page(crawlerRunConfig=config) captured_console = await self._capture_console_messages(page, url) return AsyncCrawlResponse( html=html, response_headers=response_headers, status_code=status_code, screenshot=screenshot_data, get_delayed_content=None, console_messages=captured_console, ) ##### # Since both "raw:" and "raw://" start with "raw:", the first condition is always true for both, so "raw://" will be sliced as "//...", which is incorrect. # Fix: Check for "raw://" first, then "raw:" # Also, the prefix "raw://" is actually 6 characters long, not 7, so it should be sliced accordingly: url[6:] ##### elif url.startswith("raw://") or url.startswith("raw:"): # Process raw HTML content # raw_html = url[4:] if url[:4] == "raw:" else url[7:] raw_html = url[6:] if url.startswith("raw://") else url[4:] html = raw_html if config.screenshot: screenshot_data = await self._generate_screenshot_from_html(html) return AsyncCrawlResponse( html=html, response_headers=response_headers, status_code=status_code, screenshot=screenshot_data, get_delayed_content=None, ) else: raise ValueError( "URL must start with 'http://', 'https://', 'file://', or 'raw:'" ) async def _crawl_web( self, url: str, config: CrawlerRunConfig ) -> AsyncCrawlResponse: """ Internal method to crawl web URLs with the specified configuration. Includes optional network and console capturing. Args: url (str): The web URL to crawl config (CrawlerRunConfig): Configuration object controlling the crawl behavior Returns: AsyncCrawlResponse: The response containing HTML, headers, status code, and optional data """ config.url = url response_headers = {} execution_result = None status_code = None redirected_url = url # Reset downloaded files list for new crawl self._downloaded_files = [] # Initialize capture lists captured_requests = [] captured_console = [] # Handle user agent with magic mode user_agent_to_override = config.user_agent if user_agent_to_override: self.browser_config.user_agent = user_agent_to_override elif config.magic or config.user_agent_mode == "random": self.browser_config.user_agent = ValidUAGenerator().generate( **(config.user_agent_generator_config or {}) ) # Get page for session page, context = await self.browser_manager.get_page(crawlerRunConfig=config) # await page.goto(URL) # Add default cookie # await context.add_cookies( # [{"name": "cookiesEnabled", "value": "true", "url": url}] # ) # Handle navigator overrides if config.override_navigator or config.simulate_user or config.magic: await context.add_init_script(load_js_script("navigator_overrider")) # Call hook after page creation await self.execute_hook("on_page_context_created", page, context=context, config=config) # Network Request Capturing if config.capture_network_requests: async def handle_request_capture(request): try: post_data_str = None try: # Be cautious with large post data post_data = request.post_data_buffer if post_data: # Attempt to decode, fallback to base64 or size indication try: post_data_str = post_data.decode('utf-8', errors='replace') except UnicodeDecodeError: post_data_str = f"[Binary data: {len(post_data)} bytes]" except Exception: post_data_str = "[Error retrieving post data]" captured_requests.append({ "event_type": "request", "url": request.url, "method": request.method, "headers": dict(request.headers), # Convert Header dict "post_data": post_data_str, "resource_type": request.resource_type, "is_navigation_request": request.is_navigation_request(), "timestamp": time.time() }) except Exception as e: if self.logger: self.logger.warning(f"Error capturing request details for {request.url}: {e}", tag="CAPTURE") captured_requests.append({"event_type": "request_capture_error", "url": request.url, "error": str(e), "timestamp": time.time()}) async def handle_response_capture(response): try: try: # body = await response.body() # json_body = await response.json() text_body = await response.text() except Exception as e: body = None # json_body = None # text_body = None captured_requests.append({ "event_type": "response", "url": response.url, "status": response.status, "status_text": response.status_text, "headers": dict(response.headers), # Convert Header dict "from_service_worker": response.from_service_worker, "request_timing": response.request.timing, # Detailed timing info "timestamp": time.time(), "body" : { # "raw": body, # "json": json_body, "text": text_body } }) except Exception as e: if self.logger: self.logger.warning(f"Error capturing response details for {response.url}: {e}", tag="CAPTURE") captured_requests.append({"event_type": "response_capture_error", "url": response.url, "error": str(e), "timestamp": time.time()}) async def handle_request_failed_capture(request): try: captured_requests.append({ "event_type": "request_failed", "url": request.url, "method": request.method, "resource_type": request.resource_type, "failure_text": str(request.failure) if request.failure else "Unknown failure", "timestamp": time.time() }) except Exception as e: if self.logger: self.logger.warning(f"Error capturing request failed details for {request.url}: {e}", tag="CAPTURE") captured_requests.append({"event_type": "request_failed_capture_error", "url": request.url, "error": str(e), "timestamp": time.time()}) page.on("request", handle_request_capture) page.on("response", handle_response_capture) page.on("requestfailed", handle_request_failed_capture) # Console Message Capturing if config.capture_console_messages: def handle_console_capture(msg): try: message_type = "unknown" try: message_type = msg.type except: pass message_text = "unknown" try: message_text = msg.text except: pass # Basic console message with minimal content entry = { "type": message_type, "text": message_text, "timestamp": time.time() } captured_console.append(entry) except Exception as e: if self.logger: self.logger.warning(f"Error capturing console message: {e}", tag="CAPTURE") # Still add something to the list even on error captured_console.append({ "type": "console_capture_error", "error": str(e), "timestamp": time.time() }) def handle_pageerror_capture(err): try: error_message = "Unknown error" try: error_message = err.message except: pass error_stack = "" try: error_stack = err.stack except: pass captured_console.append({ "type": "error", "text": error_message, "stack": error_stack, "timestamp": time.time() }) except Exception as e: if self.logger: self.logger.warning(f"Error capturing page error: {e}", tag="CAPTURE") captured_console.append({ "type": "pageerror_capture_error", "error": str(e), "timestamp": time.time() }) # Add event listeners directly page.on("console", handle_console_capture) page.on("pageerror", handle_pageerror_capture) # Set up console logging if requested if config.log_console: def log_consol( msg, console_log_type="debug" ): # Corrected the parameter syntax if console_log_type == "error": self.logger.error( message=f"Console error: {msg}", # Use f-string for variable interpolation tag="CONSOLE" ) elif console_log_type == "debug": self.logger.debug( message=f"Console: {msg}", # Use f-string for variable interpolation tag="CONSOLE" ) page.on("console", log_consol) page.on("pageerror", lambda e: log_consol(e, "error")) try: # Get SSL certificate information if requested and URL is HTTPS ssl_cert = None if config.fetch_ssl_certificate: ssl_cert = SSLCertificate.from_url(url) # Set up download handling if self.browser_config.accept_downloads: page.on( "download", lambda download: asyncio.create_task( self._handle_download(download) ), ) # Handle page navigation and content loading if not config.js_only: await self.execute_hook("before_goto", page, context=context, url=url, config=config) try: # Generate a unique nonce for this request if config.experimental.get("use_csp_nonce", False): nonce = hashlib.sha256(os.urandom(32)).hexdigest() # Add CSP headers to the request await page.set_extra_http_headers( { "Content-Security-Policy": f"default-src 'self'; script-src 'self' 'nonce-{nonce}' 'strict-dynamic'" } ) response = await page.goto( url, wait_until=config.wait_until, timeout=config.page_timeout ) redirected_url = page.url except Error as e: # Allow navigation to be aborted when downloading files # This is expected behavior for downloads in some browser engines if 'net::ERR_ABORTED' in str(e) and self.browser_config.accept_downloads: self.logger.info( message=f"Navigation aborted, likely due to file download: {url}", tag="GOTO", params={"url": url}, ) response = None else: raise RuntimeError(f"Failed on navigating ACS-GOTO:\n{str(e)}") await self.execute_hook( "after_goto", page, context=context, url=url, response=response, config=config ) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Walk the redirect chain. Playwright returns only the last # hop, so we trace the `request.redirected_from` links until the # first response that differs from the final one and surface its # status-code. # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ if response is None: status_code = 200 response_headers = {} else: first_resp = response req = response.request while req and req.redirected_from: prev_req = req.redirected_from prev_resp = await prev_req.response() if prev_resp: # keep earliest first_resp = prev_resp req = prev_req status_code = first_resp.status response_headers = first_resp.headers # if response is None: # status_code = 200 # response_headers = {} # else: # status_code = response.status # response_headers = response.headers else: status_code = 200 response_headers = {} # Wait for body element and visibility try: await page.wait_for_selector("body", state="attached", timeout=30000) # Use the new check_visibility function with csp_compliant_wait is_visible = await self.csp_compliant_wait( page, """() => { const element = document.body; if (!element) return false; const style = window.getComputedStyle(element); const isVisible = style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'; return isVisible; }""", timeout=30000, ) if not is_visible and not config.ignore_body_visibility: visibility_info = await self.check_visibility(page) raise Error(f"Body element is hidden: {visibility_info}") except Error: visibility_info = await self.check_visibility(page) if self.browser_config.verbose: self.logger.debug( message="Body visibility info: {info}", tag="DEBUG", params={"info": visibility_info}, ) if not config.ignore_body_visibility: raise Error(f"Body element is hidden: {visibility_info}") # try: # await page.wait_for_selector("body", state="attached", timeout=30000) # await page.wait_for_function( # """ # () => { # const body = document.body; # const style = window.getComputedStyle(body); # return style.display !== 'none' && # style.visibility !== 'hidden' && # style.opacity !== '0'; # } # """, # timeout=30000, # ) # except Error as e: # visibility_info = await page.evaluate( # """ # () => { # const body = document.body; # const style = window.getComputedStyle(body); # return { # display: style.display, # visibility: style.visibility, # opacity: style.opacity, # hasContent: body.innerHTML.length, # classList: Array.from(body.classList) # } # } # """ # ) # if self.config.verbose: # self.logger.debug( # message="Body visibility info: {info}", # tag="DEBUG", # params={"info": visibility_info}, # ) # if not config.ignore_body_visibility: # raise Error(f"Body element is hidden: {visibility_info}") # Handle content loading and viewport adjustment if not self.browser_config.text_mode and ( config.wait_for_images or config.adjust_viewport_to_content ): await page.wait_for_load_state("domcontentloaded") await asyncio.sleep(0.1) # Check for image loading with improved error handling images_loaded = await self.csp_compliant_wait( page, "() => Array.from(document.getElementsByTagName('img')).every(img => img.complete)", timeout=1000, ) if not images_loaded and self.logger: self.logger.warning( message="Some images failed to load within timeout", tag="SCRAPE", ) # Adjust viewport if needed if not self.browser_config.text_mode and config.adjust_viewport_to_content: try: dimensions = await self.get_page_dimensions(page) page_height = dimensions["height"] page_width = dimensions["width"] # page_width = await page.evaluate( # "document.documentElement.scrollWidth" # ) # page_height = await page.evaluate( # "document.documentElement.scrollHeight" # ) target_width = self.browser_config.viewport_width target_height = int(target_width * page_width / page_height * 0.95) await page.set_viewport_size( {"width": target_width, "height": target_height} ) scale = min(target_width / page_width, target_height / page_height) cdp = await page.context.new_cdp_session(page) await cdp.send( "Emulation.setDeviceMetricsOverride", { "width": page_width, "height": page_height, "deviceScaleFactor": 1, "mobile": False, "scale": scale, }, ) except Exception as e: self.logger.warning( message="Failed to adjust viewport to content: {error}", tag="VIEWPORT", params={"error": str(e)}, ) # Handle full page scanning if config.scan_full_page: # await self._handle_full_page_scan(page, config.scroll_delay) await self._handle_full_page_scan(page, config.scroll_delay, config.max_scroll_steps) # Handle virtual scroll if configured if config.virtual_scroll_config: await self._handle_virtual_scroll(page, config.virtual_scroll_config) # Execute JavaScript if provided # if config.js_code: # if isinstance(config.js_code, str): # await page.evaluate(config.js_code) # elif isinstance(config.js_code, list): # for js in config.js_code: # await page.evaluate(js) if config.js_code: # execution_result = await self.execute_user_script(page, config.js_code) execution_result = await self.robust_execute_user_script( page, config.js_code ) if not execution_result["success"]: self.logger.warning( message="User script execution had issues: {error}", tag="JS_EXEC", params={"error": execution_result.get("error")}, ) await self.execute_hook("on_execution_started", page, context=context, config=config) await self.execute_hook("on_execution_ended", page, context=context, config=config, result=execution_result) # Handle user simulation if config.simulate_user or config.magic: await page.mouse.move(100, 100) await page.mouse.down() await page.mouse.up() await page.keyboard.press("ArrowDown") # Handle wait_for condition # Todo: Decide how to handle this if not config.wait_for and config.css_selector and False: # if not config.wait_for and config.css_selector: config.wait_for = f"css:{config.css_selector}" if config.wait_for: try: # Use wait_for_timeout if specified, otherwise fall back to page_timeout timeout = config.wait_for_timeout if config.wait_for_timeout is not None else config.page_timeout await self.smart_wait( page, config.wait_for, timeout=timeout ) except Exception as e: raise RuntimeError(f"Wait condition failed: {str(e)}") # Update image dimensions if needed if not self.browser_config.text_mode: update_image_dimensions_js = load_js_script("update_image_dimensions") try: try: await page.wait_for_load_state("domcontentloaded", timeout=5) except PlaywrightTimeoutError: pass await page.evaluate(update_image_dimensions_js) except Exception as e: self.logger.error( message="Error updating image dimensions: {error}", tag="ERROR", params={"error": str(e)}, ) # Process iframes if needed if config.process_iframes: page = await self.process_iframes(page) # Pre-content retrieval hooks and delay await self.execute_hook("before_retrieve_html", page, context=context, config=config) if config.delay_before_return_html: await asyncio.sleep(config.delay_before_return_html) # Handle overlay removal if config.remove_overlay_elements: await self.remove_overlay_elements(page) if config.css_selector: try: # Handle comma-separated selectors by splitting them selectors = [s.strip() for s in config.css_selector.split(',')] html_parts = [] for selector in selectors: try: content = await page.evaluate( f"""Array.from(document.querySelectorAll("{selector}")) .map(el => el.outerHTML) .join('')""" ) html_parts.append(content) except Error as e: print(f"Warning: Could not get content for selector '{selector}': {str(e)}") # Wrap in a div to create a valid HTML structure html = f"<div class='crawl4ai-result'>\n" + "\n".join(html_parts) + "\n</div>" except Error as e: raise RuntimeError(f"Failed to extract HTML content: {str(e)}") else: html = await page.content() # # Get final HTML content # html = await page.content() await self.execute_hook( "before_return_html", page=page, html=html, context=context, config=config ) # Handle PDF, MHTML and screenshot generation start_export_time = time.perf_counter() pdf_data = None screenshot_data = None mhtml_data = None if config.pdf: pdf_data = await self.export_pdf(page) if config.capture_mhtml: mhtml_data = await self.capture_mhtml(page) if config.screenshot: if config.screenshot_wait_for: await asyncio.sleep(config.screenshot_wait_for) screenshot_data = await self.take_screenshot( page, screenshot_height_threshold=config.screenshot_height_threshold ) if screenshot_data or pdf_data or mhtml_data: self.logger.info( message="Exporting media (PDF/MHTML/screenshot) took {duration:.2f}s", tag="EXPORT", params={"duration": time.perf_counter() - start_export_time}, ) # Define delayed content getter async def get_delayed_content(delay: float = 5.0) -> str: self.logger.info( message="Waiting for {delay} seconds before retrieving content for {url}", tag="INFO", params={"delay": delay, "url": url}, ) await asyncio.sleep(delay) return await page.content() # Return complete response return AsyncCrawlResponse( html=html, response_headers=response_headers, js_execution_result=execution_result, status_code=status_code, screenshot=screenshot_data, pdf_data=pdf_data, mhtml_data=mhtml_data, get_delayed_content=get_delayed_content, ssl_certificate=ssl_cert, downloaded_files=( self._downloaded_files if self._downloaded_files else None ), redirected_url=redirected_url, # Include captured data if enabled network_requests=captured_requests if config.capture_network_requests else None, console_messages=captured_console if config.capture_console_messages else None, ) except Exception as e: raise e finally: # If no session_id is given we should close the page all_contexts = page.context.browser.contexts total_pages = sum(len(context.pages) for context in all_contexts) if config.session_id: pass elif total_pages <= 1 and (self.browser_config.use_managed_browser or self.browser_config.headless): pass else: # Detach listeners before closing to prevent potential errors during close if config.capture_network_requests: page.remove_listener("request", handle_request_capture) page.remove_listener("response", handle_response_capture) page.remove_listener("requestfailed", handle_request_failed_capture) if config.capture_console_messages: page.remove_listener("console", handle_console_capture) page.remove_listener("pageerror", handle_pageerror_capture) # Close the page await page.close() # async def _handle_full_page_scan(self, page: Page, scroll_delay: float = 0.1): async def _handle_full_page_scan(self, page: Page, scroll_delay: float = 0.1, max_scroll_steps: Optional[int] = None): """ Helper method to handle full page scanning. How it works: 1. Get the viewport height. 2. Scroll to the bottom of the page. 3. Get the total height of the page. 4. Scroll back to the top of the page. 5. Scroll to the bottom of the page again. 6. Continue scrolling until the bottom of the page is reached. Args: page (Page): The Playwright page object scroll_delay (float): The delay between page scrolls max_scroll_steps (Optional[int]): Maximum number of scroll steps to perform. If None, scrolls until end. """ try: viewport_size = page.viewport_size if viewport_size is None: await page.set_viewport_size( {"width": self.browser_config.viewport_width, "height": self.browser_config.viewport_height} ) viewport_size = page.viewport_size viewport_height = viewport_size.get( "height", self.browser_config.viewport_height ) current_position = viewport_height # await page.evaluate(f"window.scrollTo(0, {current_position})") await self.safe_scroll(page, 0, current_position, delay=scroll_delay) # await self.csp_scroll_to(page, 0, current_position) # await asyncio.sleep(scroll_delay) # total_height = await page.evaluate("document.documentElement.scrollHeight") dimensions = await self.get_page_dimensions(page) total_height = dimensions["height"] scroll_step_count = 0 while current_position < total_height: #### # NEW FEATURE: Check if we've reached the maximum allowed scroll steps # This prevents infinite scrolling on very long pages or infinite scroll scenarios # If max_scroll_steps is None, this check is skipped (unlimited scrolling - original behavior) #### if max_scroll_steps is not None and scroll_step_count >= max_scroll_steps: break current_position = min(current_position + viewport_height, total_height) await self.safe_scroll(page, 0, current_position, delay=scroll_delay) # Increment the step counter for max_scroll_steps tracking scroll_step_count += 1 # await page.evaluate(f"window.scrollTo(0, {current_position})") # await asyncio.sleep(scroll_delay) # new_height = await page.evaluate("document.documentElement.scrollHeight") dimensions = await self.get_page_dimensions(page) new_height = dimensions["height"] if new_height > total_height: total_height = new_height # await page.evaluate("window.scrollTo(0, 0)") await self.safe_scroll(page, 0, 0) except Exception as e: self.logger.warning( message="Failed to perform full page scan: {error}", tag="PAGE_SCAN", params={"error": str(e)}, ) else: # await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await self.safe_scroll(page, 0, total_height) async def _handle_virtual_scroll(self, page: Page, config: "VirtualScrollConfig"): """ Handle virtual scroll containers (e.g., Twitter-like feeds) by capturing content at different scroll positions and merging unique elements. Following the design: 1. Get container HTML 2. Scroll by container height 3. Wait and check if container HTML changed 4. Three cases: - No change: continue scrolling - New items added (appended): continue (items already in page) - Items replaced: capture HTML chunk and add to list 5. After N scrolls, merge chunks if any were captured Args: page: The Playwright page object config: Virtual scroll configuration """ try: # Import VirtualScrollConfig to avoid circular import from .async_configs import VirtualScrollConfig # Ensure config is a VirtualScrollConfig instance if isinstance(config, dict): config = VirtualScrollConfig.from_dict(config) self.logger.info( message="Starting virtual scroll capture for container: {selector}", tag="VSCROLL", params={"selector": config.container_selector} ) # JavaScript function to handle virtual scroll capture virtual_scroll_js = """ async (config) => { const container = document.querySelector(config.container_selector); if (!container) { throw new Error(`Container not found: ${config.container_selector}`); } // List to store HTML chunks when content is replaced const htmlChunks = []; let previousHTML = container.innerHTML; let scrollCount = 0; // Determine scroll amount let scrollAmount; if (typeof config.scroll_by === 'number') { scrollAmount = config.scroll_by; } else if (config.scroll_by === 'page_height') { scrollAmount = window.innerHeight; } else { // container_height scrollAmount = container.offsetHeight; } // Perform scrolling while (scrollCount < config.scroll_count) { // Scroll the container container.scrollTop += scrollAmount; // Wait for content to potentially load await new Promise(resolve => setTimeout(resolve, config.wait_after_scroll * 1000)); // Get current HTML const currentHTML = container.innerHTML; // Determine what changed if (currentHTML === previousHTML) { // Case 0: No change - continue scrolling console.log(`Scroll ${scrollCount + 1}: No change in content`); } else if (currentHTML.startsWith(previousHTML)) { // Case 1: New items appended - content already in page console.log(`Scroll ${scrollCount + 1}: New items appended`); } else { // Case 2: Items replaced - capture the previous HTML console.log(`Scroll ${scrollCount + 1}: Content replaced, capturing chunk`); htmlChunks.push(previousHTML); } // Update previous HTML for next iteration previousHTML = currentHTML; scrollCount++; // Check if we've reached the end if (container.scrollTop + container.clientHeight >= container.scrollHeight - 10) { console.log(`Reached end of scrollable content at scroll ${scrollCount}`); // Capture final chunk if content was replaced if (htmlChunks.length > 0) { htmlChunks.push(currentHTML); } break; } } // If we have chunks (case 2 occurred), merge them if (htmlChunks.length > 0) { console.log(`Merging ${htmlChunks.length} HTML chunks`); // Parse all chunks to extract unique elements const tempDiv = document.createElement('div'); const seenTexts = new Set(); const uniqueElements = []; // Process each chunk for (const chunk of htmlChunks) { tempDiv.innerHTML = chunk; const elements = tempDiv.children; for (let i = 0; i < elements.length; i++) { const element = elements[i]; // Normalize text for deduplication const normalizedText = element.innerText .toLowerCase() .replace(/[\\s\\W]/g, ''); // Remove spaces and symbols if (!seenTexts.has(normalizedText)) { seenTexts.add(normalizedText); uniqueElements.push(element.outerHTML); } } } // Replace container content with merged unique elements container.innerHTML = uniqueElements.join('\\n'); console.log(`Merged ${uniqueElements.length} unique elements from ${htmlChunks.length} chunks`); return { success: true, chunksCount: htmlChunks.length, uniqueCount: uniqueElements.length, replaced: true }; } else { console.log('No content replacement detected, all content remains in page'); return { success: true, chunksCount: 0, uniqueCount: 0, replaced: false }; } } """ # Execute virtual scroll capture result = await page.evaluate(virtual_scroll_js, config.to_dict()) if result.get("replaced", False): self.logger.success( message="Virtual scroll completed. Merged {unique} unique elements from {chunks} chunks", tag="VSCROLL", params={ "unique": result.get("uniqueCount", 0), "chunks": result.get("chunksCount", 0) } ) else: self.logger.info( message="Virtual scroll completed. Content was appended, no merging needed", tag="VSCROLL" ) except Exception as e: self.logger.error( message="Virtual scroll capture failed: {error}", tag="VSCROLL", params={"error": str(e)} ) # Continue with normal flow even if virtual scroll fails async def _handle_download(self, download): """ Handle file downloads. How it works: 1. Get the suggested filename. 2. Get the download path. 3. Log the download. 4. Start the download. 5. Save the downloaded file. 6. Log the completion. Args: download (Download): The Playwright download object Returns: None """ try: suggested_filename = download.suggested_filename download_path = os.path.join(self.browser_config.downloads_path, suggested_filename) self.logger.info( message="Downloading {filename} to {path}", tag="FETCH", params={"filename": suggested_filename, "path": download_path}, ) start_time = time.perf_counter() await download.save_as(download_path) end_time = time.perf_counter() self._downloaded_files.append(download_path) self.logger.success( message="Downloaded {filename} successfully", tag="COMPLETE", params={ "filename": suggested_filename, "path": download_path, "duration": f"{end_time - start_time:.2f}s", }, ) except Exception as e: self.logger.error( message="Failed to handle download: {error}", tag="ERROR", params={"error": str(e)}, ) async def remove_overlay_elements(self, page: Page) -> None: """ Removes popup overlays, modals, cookie notices, and other intrusive elements from the page. Args: page (Page): The Playwright page instance """ remove_overlays_js = load_js_script("remove_overlay_elements") try: await page.evaluate( f""" (() => {{ try {{ {remove_overlays_js} return {{ success: true }}; }} catch (error) {{ return {{ success: false, error: error.toString(), stack: error.stack }}; }} }})() """ ) await page.wait_for_timeout(500) # Wait for any animations to complete except Exception as e: self.logger.warning( message="Failed to remove overlay elements: {error}", tag="SCRAPE", params={"error": str(e)}, ) async def export_pdf(self, page: Page) -> bytes: """ Exports the current page as a PDF. Args: page (Page): The Playwright page object Returns: bytes: The PDF data """ pdf_data = await page.pdf(print_background=True) return pdf_data async def capture_mhtml(self, page: Page) -> Optional[str]: """ Captures the current page as MHTML using CDP. MHTML (MIME HTML) is a web page archive format that combines the HTML content with its resources (images, CSS, etc.) into a single MIME-encoded file. Args: page (Page): The Playwright page object Returns: Optional[str]: The MHTML content as a string, or None if there was an error """ try: # Ensure the page is fully loaded before capturing try: # Wait for DOM content and network to be idle await page.wait_for_load_state("domcontentloaded", timeout=5000) await page.wait_for_load_state("networkidle", timeout=5000) # Give a little extra time for JavaScript execution await page.wait_for_timeout(1000) # Wait for any animations to complete await page.evaluate(""" () => new Promise(resolve => { // First requestAnimationFrame gets scheduled after the next repaint requestAnimationFrame(() => { // Second requestAnimationFrame gets called after all animations complete requestAnimationFrame(resolve); }); }) """) except Error as e: if self.logger: self.logger.warning( message="Wait for load state timed out: {error}", tag="MHTML", params={"error": str(e)}, ) # Create a new CDP session cdp_session = await page.context.new_cdp_session(page) # Call Page.captureSnapshot with format "mhtml" result = await cdp_session.send("Page.captureSnapshot", {"format": "mhtml"}) # The result contains a 'data' field with the MHTML content mhtml_content = result.get("data") # Detach the CDP session to clean up resources await cdp_session.detach() return mhtml_content except Exception as e: # Log the error but don't raise it - we'll just return None for the MHTML if self.logger: self.logger.error( message="Failed to capture MHTML: {error}", tag="MHTML", params={"error": str(e)}, ) return None async def _capture_console_messages( self, page: Page, file_path: str ) -> List[Dict[str, Union[str, float]]]: """ Captures console messages from the page. Args: page (Page): The Playwright page object Returns: List[Dict[str, Union[str, float]]]: A list of captured console messages """ captured_console = [] def handle_console_message(msg): try: message_type = msg.type message_text = msg.text entry = { "type": message_type, "text": message_text, "timestamp": time.time(), } captured_console.append(entry) except Exception as e: if self.logger: self.logger.warning( f"Error capturing console message: {e}", tag="CAPTURE" ) page.on("console", handle_console_message) await page.goto(file_path) return captured_console async def take_screenshot(self, page, **kwargs) -> str: """ Take a screenshot of the current page. Args: page (Page): The Playwright page object kwargs: Additional keyword arguments Returns: str: The base64-encoded screenshot data """ need_scroll = await self.page_need_scroll(page) if not need_scroll: # Page is short enough, just take a screenshot return await self.take_screenshot_naive(page) else: # Page is too long, try to take a full-page screenshot return await self.take_screenshot_scroller(page, **kwargs) # return await self.take_screenshot_from_pdf(await self.export_pdf(page)) async def take_screenshot_from_pdf(self, pdf_data: bytes) -> str: """ Convert the first page of the PDF to a screenshot. Requires pdf2image and poppler. Args: pdf_data (bytes): The PDF data Returns: str: The base64-encoded screenshot data """ try: from pdf2image import convert_from_bytes images = convert_from_bytes(pdf_data) final_img = images[0].convert("RGB") buffered = BytesIO() final_img.save(buffered, format="JPEG") return base64.b64encode(buffered.getvalue()).decode("utf-8") except Exception as e: error_message = f"Failed to take PDF-based screenshot: {str(e)}" self.logger.error( message="PDF Screenshot failed: {error}", tag="ERROR", params={"error": error_message}, ) # Return error image as fallback img = Image.new("RGB", (800, 600), color="black") draw = ImageDraw.Draw(img) font = ImageFont.load_default() draw.text((10, 10), error_message, fill=(255, 255, 255), font=font) buffered = BytesIO() img.save(buffered, format="JPEG") return base64.b64encode(buffered.getvalue()).decode("utf-8") async def take_screenshot_scroller(self, page: Page, **kwargs) -> str: """ Attempt to set a large viewport and take a full-page screenshot. If still too large, segment the page as before. Requires pdf2image and poppler. Args: page (Page): The Playwright page object kwargs: Additional keyword arguments Returns: str: The base64-encoded screenshot data """ try: # Get page height dimensions = await self.get_page_dimensions(page) page_width = dimensions["width"] page_height = dimensions["height"] # page_height = await page.evaluate("document.documentElement.scrollHeight") # page_width = await page.evaluate("document.documentElement.scrollWidth") # Set a large viewport large_viewport_height = min( page_height, kwargs.get("screenshot_height_threshold", SCREENSHOT_HEIGHT_TRESHOLD), ) await page.set_viewport_size( {"width": page_width, "height": large_viewport_height} ) # Page still too long, segment approach segments = [] viewport_size = page.viewport_size viewport_height = viewport_size["height"] num_segments = (page_height // viewport_height) + 1 for i in range(num_segments): y_offset = i * viewport_height # Special handling for the last segment if i == num_segments - 1: last_part_height = page_height % viewport_height # If page_height is an exact multiple of viewport_height, # we don't need an extra segment if last_part_height == 0: # Skip last segment if page height is exact multiple of viewport break # Adjust viewport to exactly match the remaining content height await page.set_viewport_size({"width": page_width, "height": last_part_height}) await page.evaluate(f"window.scrollTo(0, {y_offset})") await asyncio.sleep(0.01) # wait for render # Capture the current segment # Note: Using compression options (format, quality) would go here seg_shot = await page.screenshot(full_page=False, type="jpeg", quality=85) # seg_shot = await page.screenshot(full_page=False) img = Image.open(BytesIO(seg_shot)).convert("RGB") segments.append(img) # Reset viewport to original size after capturing segments await page.set_viewport_size({"width": page_width, "height": viewport_height}) total_height = sum(img.height for img in segments) stitched = Image.new("RGB", (segments[0].width, total_height)) offset = 0 for img in segments: # stitched.paste(img, (0, offset)) stitched.paste(img.convert("RGB"), (0, offset)) offset += img.height buffered = BytesIO() stitched = stitched.convert("RGB") stitched.save(buffered, format="BMP", quality=85) encoded = base64.b64encode(buffered.getvalue()).decode("utf-8") return encoded except Exception as e: error_message = f"Failed to take large viewport screenshot: {str(e)}" self.logger.error( message="Large viewport screenshot failed: {error}", tag="ERROR", params={"error": error_message}, ) # return error image img = Image.new("RGB", (800, 600), color="black") draw = ImageDraw.Draw(img) font = ImageFont.load_default() draw.text((10, 10), error_message, fill=(255, 255, 255), font=font) buffered = BytesIO() img.save(buffered, format="JPEG") return base64.b64encode(buffered.getvalue()).decode("utf-8") # finally: # await page.close() async def take_screenshot_naive(self, page: Page) -> str: """ Takes a screenshot of the current page. Args: page (Page): The Playwright page instance Returns: str: Base64-encoded screenshot image """ try: # The page is already loaded, just take the screenshot screenshot = await page.screenshot(full_page=False) return base64.b64encode(screenshot).decode("utf-8") except Exception as e: error_message = f"Failed to take screenshot: {str(e)}" self.logger.error( message="Screenshot failed: {error}", tag="ERROR", params={"error": error_message}, ) # Generate an error image img = Image.new("RGB", (800, 600), color="black") draw = ImageDraw.Draw(img) font = ImageFont.load_default() draw.text((10, 10), error_message, fill=(255, 255, 255), font=font) buffered = BytesIO() img.save(buffered, format="JPEG") return base64.b64encode(buffered.getvalue()).decode("utf-8") # finally: # await page.close() async def export_storage_state(self, path: str = None) -> dict: """ Exports the current storage state (cookies, localStorage, sessionStorage) to a JSON file at the specified path. Args: path (str): The path to save the storage state JSON file Returns: dict: The exported storage state """ if self.default_context: state = await self.default_context.storage_state(path=path) self.logger.info( message="Exported storage state to {path}", tag="INFO", params={"path": path}, ) return state else: self.logger.warning( message="No default_context available to export storage state.", tag="WARNING", ) async def robust_execute_user_script( self, page: Page, js_code: Union[str, List[str]] ) -> Dict[str, Any]: """ Executes user-provided JavaScript code with proper error handling and context, supporting both synchronous and async user code, plus navigations. How it works: 1. Wait for load state 'domcontentloaded' 2. If js_code is a string, execute it directly 3. If js_code is a list, execute each element in sequence 4. Wait for load state 'networkidle' 5. Return results Args: page (Page): The Playwright page instance js_code (Union[str, List[str]]): The JavaScript code to execute Returns: Dict[str, Any]: The results of the execution """ try: await page.wait_for_load_state("domcontentloaded") if isinstance(js_code, str): scripts = [js_code] else: scripts = js_code results = [] for script in scripts: try: # Attempt the evaluate # If the user code triggers navigation, we catch the "context destroyed" error # then wait for the new page to load before continuing result = None try: # OLD VERSION: # result = await page.evaluate( # f""" # (async () => {{ # try {{ # const script_result = {script}; # return {{ success: true, result: script_result }}; # }} catch (err) {{ # return {{ success: false, error: err.toString(), stack: err.stack }}; # }} # }})(); # """ # ) # """ NEW VERSION: # When {script} contains statements (e.g., const link = โ€ฆ; link.click();), # this forms invalid JavaScript, causing Playwright execution error: SyntaxError: Unexpected token 'const'. # """ result = await page.evaluate( f""" (async () => {{ try {{ return await (async () => {{ {script} }})(); }} catch (err) {{ return {{ success: false, error: err.toString(), stack: err.stack }}; }} }})(); """ ) except Error as e: # If it's due to navigation destroying the context, handle gracefully if "Execution context was destroyed" in str(e): self.logger.info( "Navigation triggered by script, waiting for load state", tag="JS_EXEC", ) try: await page.wait_for_load_state("load", timeout=30000) except Error as nav_err: self.logger.warning( message="Navigation wait failed: {error}", tag="JS_EXEC", params={"error": str(nav_err)}, ) try: await page.wait_for_load_state( "networkidle", timeout=30000 ) except Error as nav_err: self.logger.warning( message="Network idle wait failed: {error}", tag="JS_EXEC", params={"error": str(nav_err)}, ) # Return partial success, or adapt as you see fit result = { "success": True, "info": "Navigation triggered, ignoring context destroyed error", } else: # It's some other error, log and continue self.logger.error( message="Playwright execution error: {error}", tag="JS_EXEC", params={"error": str(e)}, ) result = {"success": False, "error": str(e)} # If we made it this far with no repeated error, do post-load waits t1 = time.time() try: await page.wait_for_load_state("domcontentloaded", timeout=5000) except Error as e: self.logger.warning( message="DOM content load timeout: {error}", tag="JS_EXEC", params={"error": str(e)}, ) # t1 = time.time() # try: # await page.wait_for_load_state('networkidle', timeout=5000) # print("Network idle after script execution in", time.time() - t1) # except Error as e: # self.logger.warning( # message="Network idle timeout: {error}", # tag="JS_EXEC", # params={"error": str(e)} # ) results.append(result if result else {"success": True}) except Exception as e: # Catch anything else self.logger.error( message="Script chunk failed: {error}", tag="JS_EXEC", params={"error": str(e)}, ) results.append({"success": False, "error": str(e)}) return {"success": True, "results": results} except Exception as e: self.logger.error( message="Script execution failed: {error}", tag="JS_EXEC", params={"error": str(e)}, ) return {"success": False, "error": str(e)} async def execute_user_script( self, page: Page, js_code: Union[str, List[str]] ) -> Dict[str, Any]: """ Executes user-provided JavaScript code with proper error handling and context. Args: page: Playwright page object js_code: Single JavaScript string or list of JavaScript code strings Returns: Dict containing execution status and results/errors """ try: # Ensure the page is ready for script execution await page.wait_for_load_state("domcontentloaded") # Handle single script or multiple scripts if isinstance(js_code, str): scripts = [js_code] else: scripts = js_code results = [] for script in scripts: try: # Execute the script and wait for network idle result = await page.evaluate( f""" (() => {{ return new Promise((resolve) => {{ try {{ const result = (function() {{ {script} }})(); // If result is a promise, wait for it if (result instanceof Promise) {{ result.then(() => {{ // Wait a bit for any triggered effects setTimeout(() => resolve({{ success: true }}), 100); }}).catch(error => {{ resolve({{ success: false, error: error.toString(), stack: error.stack }}); }}); }} else {{ // For non-promise results, still wait a bit for effects setTimeout(() => resolve({{ success: true }}), 100); }} }} catch (error) {{ resolve({{ success: false, error: error.toString(), stack: error.stack }}); }} }}); }})() """ ) # Wait for network idle after script execution t1 = time.time() await page.wait_for_load_state("domcontentloaded", timeout=5000) t1 = time.time() await page.wait_for_load_state("networkidle", timeout=5000) results.append(result if result else {"success": True}) except Error as e: # Handle Playwright-specific errors self.logger.error( message="Playwright execution error: {error}", tag="JS_EXEC", params={"error": str(e)}, ) results.append({"success": False, "error": str(e)}) return {"success": True, "results": results} except Exception as e: self.logger.error( message="Script execution failed: {error}", tag="JS_EXEC", params={"error": str(e)}, ) return {"success": False, "error": str(e)} except Exception as e: self.logger.error( message="Script execution failed: {error}", tag="JS_EXEC", params={"error": str(e)}, ) return {"success": False, "error": str(e)} async def check_visibility(self, page): """ Checks if an element is visible on the page. Args: page: Playwright page object Returns: Boolean indicating visibility """ return await page.evaluate( """ () => { const element = document.body; if (!element) return false; const style = window.getComputedStyle(element); const isVisible = style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'; return isVisible; } """ ) async def safe_scroll(self, page: Page, x: int, y: int, delay: float = 0.1): """ Safely scroll the page with rendering time. Args: page: Playwright page object x: Horizontal scroll position y: Vertical scroll position """ result = await self.csp_scroll_to(page, x, y) if result["success"]: await page.wait_for_timeout(delay * 1000) return result async def csp_scroll_to(self, page: Page, x: int, y: int) -> Dict[str, Any]: """ Performs a CSP-compliant scroll operation and returns the result status. Args: page: Playwright page object x: Horizontal scroll position y: Vertical scroll position Returns: Dict containing scroll status and position information """ try: result = await page.evaluate( f"""() => {{ try {{ const startX = window.scrollX; const startY = window.scrollY; window.scrollTo({x}, {y}); // Get final position after scroll const endX = window.scrollX; const endY = window.scrollY; return {{ success: true, startPosition: {{ x: startX, y: startY }}, endPosition: {{ x: endX, y: endY }}, targetPosition: {{ x: {x}, y: {y} }}, delta: {{ x: Math.abs(endX - {x}), y: Math.abs(endY - {y}) }} }}; }} catch (e) {{ return {{ success: false, error: e.toString() }}; }} }}""" ) if not result["success"]: self.logger.warning( message="Scroll operation failed: {error}", tag="SCROLL", params={"error": result.get("error")}, ) return result except Exception as e: self.logger.error( message="Failed to execute scroll: {error}", tag="SCROLL", params={"error": str(e)}, ) return {"success": False, "error": str(e)} async def get_page_dimensions(self, page: Page): """ Get the dimensions of the page. Args: page: Playwright page object Returns: Dict containing width and height of the page """ return await page.evaluate( """ () => { const {scrollWidth, scrollHeight} = document.documentElement; return {width: scrollWidth, height: scrollHeight}; } """ ) async def page_need_scroll(self, page: Page) -> bool: """ Determine whether the page need to scroll Args: page: Playwright page object Returns: bool: True if page needs scrolling """ try: need_scroll = await page.evaluate( """ () => { const scrollHeight = document.documentElement.scrollHeight; const viewportHeight = window.innerHeight; return scrollHeight > viewportHeight; } """ ) return need_scroll except Exception as e: self.logger.warning( message="Failed to check scroll need: {error}. Defaulting to True for safety.", tag="SCROLL", params={"error": str(e)}, ) return True # Default to scrolling if check fails #################################################################################################### # HTTP Crawler Strategy #################################################################################################### class HTTPCrawlerError(Exception): """Base error class for HTTP crawler specific exceptions""" pass class ConnectionTimeoutError(HTTPCrawlerError): """Raised when connection timeout occurs""" pass class HTTPStatusError(HTTPCrawlerError): """Raised for unexpected status codes""" def __init__(self, status_code: int, message: str): self.status_code = status_code super().__init__(f"HTTP {status_code}: {message}") class AsyncHTTPCrawlerStrategy(AsyncCrawlerStrategy): """ Fast, lightweight HTTP-only crawler strategy optimized for memory efficiency. """ __slots__ = ('logger', 'max_connections', 'dns_cache_ttl', 'chunk_size', '_session', 'hooks', 'browser_config') DEFAULT_TIMEOUT: Final[int] = 30 DEFAULT_CHUNK_SIZE: Final[int] = 64 * 1024 DEFAULT_MAX_CONNECTIONS: Final[int] = min(32, (os.cpu_count() or 1) * 4) DEFAULT_DNS_CACHE_TTL: Final[int] = 300 VALID_SCHEMES: Final = frozenset({'http', 'https', 'file', 'raw'}) _BASE_HEADERS: Final = MappingProxyType({ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' }) def __init__( self, browser_config: Optional[HTTPCrawlerConfig] = None, logger: Optional[AsyncLogger] = None, max_connections: int = DEFAULT_MAX_CONNECTIONS, dns_cache_ttl: int = DEFAULT_DNS_CACHE_TTL, chunk_size: int = DEFAULT_CHUNK_SIZE ): """Initialize the HTTP crawler with config""" self.browser_config = browser_config or HTTPCrawlerConfig() self.logger = logger self.max_connections = max_connections self.dns_cache_ttl = dns_cache_ttl self.chunk_size = chunk_size self._session: Optional[aiohttp.ClientSession] = None self.hooks = { k: partial(self._execute_hook, k) for k in ('before_request', 'after_request', 'on_error') } # Set default hooks self.set_hook('before_request', lambda *args, **kwargs: None) self.set_hook('after_request', lambda *args, **kwargs: None) self.set_hook('on_error', lambda *args, **kwargs: None) async def __aenter__(self) -> AsyncHTTPCrawlerStrategy: await self.start() return self async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: await self.close() @contextlib.asynccontextmanager async def _session_context(self): try: if not self._session: await self.start() yield self._session finally: pass def set_hook(self, hook_type: str, hook_func: Callable) -> None: if hook_type in self.hooks: self.hooks[hook_type] = partial(self._execute_hook, hook_type, hook_func) else: raise ValueError(f"Invalid hook type: {hook_type}") async def _execute_hook( self, hook_type: str, hook_func: Callable, *args: Any, **kwargs: Any ) -> Any: if asyncio.iscoroutinefunction(hook_func): return await hook_func(*args, **kwargs) return hook_func(*args, **kwargs) async def start(self) -> None: if not self._session: connector = aiohttp.TCPConnector( limit=self.max_connections, ttl_dns_cache=self.dns_cache_ttl, use_dns_cache=True, force_close=False ) self._session = aiohttp.ClientSession( headers=dict(self._BASE_HEADERS), connector=connector, timeout=ClientTimeout(total=self.DEFAULT_TIMEOUT) ) async def close(self) -> None: if self._session and not self._session.closed: try: await asyncio.wait_for(self._session.close(), timeout=5.0) except asyncio.TimeoutError: if self.logger: self.logger.warning( message="Session cleanup timed out", tag="CLEANUP" ) finally: self._session = None async def _stream_file(self, path: str) -> AsyncGenerator[memoryview, None]: async with aiofiles.open(path, mode='rb') as f: while chunk := await f.read(self.chunk_size): yield memoryview(chunk) async def _handle_file(self, path: str) -> AsyncCrawlResponse: if not os.path.exists(path): raise FileNotFoundError(f"Local file not found: {path}") chunks = [] async for chunk in self._stream_file(path): chunks.append(chunk.tobytes().decode('utf-8', errors='replace')) return AsyncCrawlResponse( html=''.join(chunks), response_headers={}, status_code=200 ) async def _handle_raw(self, content: str) -> AsyncCrawlResponse: return AsyncCrawlResponse( html=content, response_headers={}, status_code=200 ) async def _handle_http( self, url: str, config: CrawlerRunConfig ) -> AsyncCrawlResponse: async with self._session_context() as session: timeout = ClientTimeout( total=config.page_timeout or self.DEFAULT_TIMEOUT, connect=10, sock_read=30 ) headers = dict(self._BASE_HEADERS) if self.browser_config.headers: headers.update(self.browser_config.headers) request_kwargs = { 'timeout': timeout, 'allow_redirects': self.browser_config.follow_redirects, 'ssl': self.browser_config.verify_ssl, 'headers': headers } if self.browser_config.method == "POST": if self.browser_config.data: request_kwargs['data'] = self.browser_config.data if self.browser_config.json: request_kwargs['json'] = self.browser_config.json await self.hooks['before_request'](url, request_kwargs) try: async with session.request(self.browser_config.method, url, **request_kwargs) as response: content = memoryview(await response.read()) if not (200 <= response.status < 300): raise HTTPStatusError( response.status, f"Unexpected status code for {url}" ) encoding = response.charset if not encoding: encoding = chardet.detect(content.tobytes())['encoding'] or 'utf-8' result = AsyncCrawlResponse( html=content.tobytes().decode(encoding, errors='replace'), response_headers=dict(response.headers), status_code=response.status, redirected_url=str(response.url) ) await self.hooks['after_request'](result) return result except aiohttp.ServerTimeoutError as e: await self.hooks['on_error'](e) raise ConnectionTimeoutError(f"Request timed out: {str(e)}") except aiohttp.ClientConnectorError as e: await self.hooks['on_error'](e) raise ConnectionError(f"Connection failed: {str(e)}") except aiohttp.ClientError as e: await self.hooks['on_error'](e) raise HTTPCrawlerError(f"HTTP client error: {str(e)}") except asyncio.exceptions.TimeoutError as e: await self.hooks['on_error'](e) raise ConnectionTimeoutError(f"Request timed out: {str(e)}") except Exception as e: await self.hooks['on_error'](e) raise HTTPCrawlerError(f"HTTP request failed: {str(e)}") async def crawl( self, url: str, config: Optional[CrawlerRunConfig] = None, **kwargs ) -> AsyncCrawlResponse: config = config or CrawlerRunConfig.from_kwargs(kwargs) parsed = urlparse(url) scheme = parsed.scheme.rstrip('/') if scheme not in self.VALID_SCHEMES: raise ValueError(f"Unsupported URL scheme: {scheme}") try: if scheme == 'file': return await self._handle_file(parsed.path) elif scheme == 'raw': return await self._handle_raw(parsed.path) else: # http or https return await self._handle_http(url, config) except Exception as e: if self.logger: self.logger.error( message="Crawl failed: {error}", tag="CRAWL", params={"error": str(e), "url": url} ) raise
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/async_crawler_strategy.back.py", "license": "Apache License 2.0", "lines": 2108, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:crawl4ai/browser_adapter.py
# browser_adapter.py """ Browser adapter for Crawl4AI to support both Playwright and undetected browsers with minimal changes to existing codebase. """ from abc import ABC, abstractmethod from typing import List, Dict, Any, Optional, Callable import time import json # Import both, but use conditionally try: from playwright.async_api import Page except ImportError: Page = Any try: from patchright.async_api import Page as UndetectedPage except ImportError: UndetectedPage = Any class BrowserAdapter(ABC): """Abstract adapter for browser-specific operations""" @abstractmethod async def evaluate(self, page: Page, expression: str, arg: Any = None) -> Any: """Execute JavaScript in the page""" pass @abstractmethod async def setup_console_capture(self, page: Page, captured_console: List[Dict]) -> Optional[Callable]: """Setup console message capturing, returns handler function if needed""" pass @abstractmethod async def setup_error_capture(self, page: Page, captured_console: List[Dict]) -> Optional[Callable]: """Setup error capturing, returns handler function if needed""" pass @abstractmethod async def retrieve_console_messages(self, page: Page) -> List[Dict]: """Retrieve captured console messages (for undetected browsers)""" pass @abstractmethod async def cleanup_console_capture(self, page: Page, handle_console: Optional[Callable], handle_error: Optional[Callable]): """Clean up console event listeners""" pass @abstractmethod def get_imports(self) -> tuple: """Get the appropriate imports for this adapter""" pass class PlaywrightAdapter(BrowserAdapter): """Adapter for standard Playwright""" async def evaluate(self, page: Page, expression: str, arg: Any = None) -> Any: """Standard Playwright evaluate""" if arg is not None: return await page.evaluate(expression, arg) return await page.evaluate(expression) async def setup_console_capture(self, page: Page, captured_console: List[Dict]) -> Optional[Callable]: """Setup console capture using Playwright's event system""" def handle_console_capture(msg): try: message_type = "unknown" try: message_type = msg.type except: pass message_text = "unknown" try: message_text = msg.text except: pass entry = { "type": message_type, "text": message_text, "timestamp": time.time() } captured_console.append(entry) except Exception as e: captured_console.append({ "type": "console_capture_error", "error": str(e), "timestamp": time.time() }) page.on("console", handle_console_capture) return handle_console_capture async def setup_error_capture(self, page: Page, captured_console: List[Dict]) -> Optional[Callable]: """Setup error capture using Playwright's event system""" def handle_pageerror_capture(err): try: error_message = "Unknown error" try: error_message = err.message except: pass error_stack = "" try: error_stack = err.stack except: pass captured_console.append({ "type": "error", "text": error_message, "stack": error_stack, "timestamp": time.time() }) except Exception as e: captured_console.append({ "type": "pageerror_capture_error", "error": str(e), "timestamp": time.time() }) page.on("pageerror", handle_pageerror_capture) return handle_pageerror_capture async def retrieve_console_messages(self, page: Page) -> List[Dict]: """Not needed for Playwright - messages are captured via events""" return [] async def cleanup_console_capture(self, page: Page, handle_console: Optional[Callable], handle_error: Optional[Callable]): """Remove event listeners""" if handle_console: page.remove_listener("console", handle_console) if handle_error: page.remove_listener("pageerror", handle_error) def get_imports(self) -> tuple: """Return Playwright imports""" from playwright.async_api import Page, Error from playwright.async_api import TimeoutError as PlaywrightTimeoutError return Page, Error, PlaywrightTimeoutError class StealthAdapter(BrowserAdapter): """Adapter for Playwright with stealth features using playwright_stealth""" def __init__(self): self._console_script_injected = {} self._stealth_available = self._check_stealth_availability() def _check_stealth_availability(self) -> bool: """Check if playwright_stealth is available and get the correct function""" try: from playwright_stealth import stealth_async self._stealth_function = stealth_async return True except ImportError: try: from playwright_stealth import stealth_sync self._stealth_function = stealth_sync return True except ImportError: self._stealth_function = None return False async def apply_stealth(self, page: Page): """Apply stealth to a page if available""" if self._stealth_available and self._stealth_function: try: if hasattr(self._stealth_function, '__call__'): if 'async' in getattr(self._stealth_function, '__name__', ''): await self._stealth_function(page) else: self._stealth_function(page) except Exception as e: # Fail silently or log error depending on requirements pass async def evaluate(self, page: Page, expression: str, arg: Any = None) -> Any: """Standard Playwright evaluate with stealth applied""" if arg is not None: return await page.evaluate(expression, arg) return await page.evaluate(expression) async def setup_console_capture(self, page: Page, captured_console: List[Dict]) -> Optional[Callable]: """Setup console capture using Playwright's event system with stealth""" # Apply stealth to the page first await self.apply_stealth(page) def handle_console_capture(msg): try: message_type = "unknown" try: message_type = msg.type except: pass message_text = "unknown" try: message_text = msg.text except: pass entry = { "type": message_type, "text": message_text, "timestamp": time.time() } captured_console.append(entry) except Exception as e: captured_console.append({ "type": "console_capture_error", "error": str(e), "timestamp": time.time() }) page.on("console", handle_console_capture) return handle_console_capture async def setup_error_capture(self, page: Page, captured_console: List[Dict]) -> Optional[Callable]: """Setup error capture using Playwright's event system""" def handle_pageerror_capture(err): try: error_message = "Unknown error" try: error_message = err.message except: pass error_stack = "" try: error_stack = err.stack except: pass captured_console.append({ "type": "error", "text": error_message, "stack": error_stack, "timestamp": time.time() }) except Exception as e: captured_console.append({ "type": "pageerror_capture_error", "error": str(e), "timestamp": time.time() }) page.on("pageerror", handle_pageerror_capture) return handle_pageerror_capture async def retrieve_console_messages(self, page: Page) -> List[Dict]: """Not needed for Playwright - messages are captured via events""" return [] async def cleanup_console_capture(self, page: Page, handle_console: Optional[Callable], handle_error: Optional[Callable]): """Remove event listeners""" if handle_console: page.remove_listener("console", handle_console) if handle_error: page.remove_listener("pageerror", handle_error) def get_imports(self) -> tuple: """Return Playwright imports""" from playwright.async_api import Page, Error from playwright.async_api import TimeoutError as PlaywrightTimeoutError return Page, Error, PlaywrightTimeoutError class UndetectedAdapter(BrowserAdapter): """Adapter for undetected browser automation with stealth features""" def __init__(self): self._console_script_injected = {} async def evaluate(self, page: UndetectedPage, expression: str, arg: Any = None) -> Any: """Undetected browser evaluate with isolated context""" # For most evaluations, use isolated context for stealth # Only use non-isolated when we need to access our injected console capture isolated = not ( "__console" in expression or "__captured" in expression or "__error" in expression or "window.__" in expression ) if arg is not None: return await page.evaluate(expression, arg, isolated_context=isolated) return await page.evaluate(expression, isolated_context=isolated) async def setup_console_capture(self, page: UndetectedPage, captured_console: List[Dict]) -> Optional[Callable]: """Setup console capture using JavaScript injection for undetected browsers""" if not self._console_script_injected.get(page, False): await page.add_init_script(""" // Initialize console capture window.__capturedConsole = []; window.__capturedErrors = []; // Store original console methods const originalConsole = {}; ['log', 'info', 'warn', 'error', 'debug'].forEach(method => { originalConsole[method] = console[method]; console[method] = function(...args) { try { window.__capturedConsole.push({ type: method, text: args.map(arg => { try { if (typeof arg === 'object') { return JSON.stringify(arg); } return String(arg); } catch (e) { return '[Object]'; } }).join(' '), timestamp: Date.now() }); } catch (e) { // Fail silently to avoid detection } // Call original method originalConsole[method].apply(console, args); }; }); """) self._console_script_injected[page] = True return None # No handler function needed for undetected browser async def setup_error_capture(self, page: UndetectedPage, captured_console: List[Dict]) -> Optional[Callable]: """Setup error capture using JavaScript injection for undetected browsers""" if not self._console_script_injected.get(page, False): await page.add_init_script(""" // Capture errors window.addEventListener('error', (event) => { try { window.__capturedErrors.push({ type: 'error', text: event.message, stack: event.error ? event.error.stack : '', filename: event.filename, lineno: event.lineno, colno: event.colno, timestamp: Date.now() }); } catch (e) { // Fail silently } }); // Capture unhandled promise rejections window.addEventListener('unhandledrejection', (event) => { try { window.__capturedErrors.push({ type: 'unhandledrejection', text: event.reason ? String(event.reason) : 'Unhandled Promise Rejection', stack: event.reason && event.reason.stack ? event.reason.stack : '', timestamp: Date.now() }); } catch (e) { // Fail silently } }); """) self._console_script_injected[page] = True return None # No handler function needed for undetected browser async def retrieve_console_messages(self, page: UndetectedPage) -> List[Dict]: """Retrieve captured console messages and errors from the page""" messages = [] try: # Get console messages console_messages = await page.evaluate( "() => { const msgs = window.__capturedConsole || []; window.__capturedConsole = []; return msgs; }", isolated_context=False ) messages.extend(console_messages) # Get errors errors = await page.evaluate( "() => { const errs = window.__capturedErrors || []; window.__capturedErrors = []; return errs; }", isolated_context=False ) messages.extend(errors) # Convert timestamps from JS to Python format for msg in messages: if 'timestamp' in msg and isinstance(msg['timestamp'], (int, float)): msg['timestamp'] = msg['timestamp'] / 1000.0 # Convert from ms to seconds except Exception: # If retrieval fails, return empty list pass return messages async def cleanup_console_capture(self, page: UndetectedPage, handle_console: Optional[Callable], handle_error: Optional[Callable]): """Clean up for undetected browser - retrieve final messages""" # For undetected browser, we don't have event listeners to remove # but we should retrieve any final messages final_messages = await self.retrieve_console_messages(page) return final_messages def get_imports(self) -> tuple: """Return undetected browser imports""" from patchright.async_api import Page, Error from patchright.async_api import TimeoutError as PlaywrightTimeoutError return Page, Error, PlaywrightTimeoutError
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/browser_adapter.py", "license": "Apache License 2.0", "lines": 354, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/demo_multi_config_clean.py
""" ๐ŸŽฏ Multi-Config URL Matching Demo ================================= Learn how to use different crawler configurations for different URL patterns in a single crawl batch with Crawl4AI's multi-config feature. Part 1: Understanding URL Matching (Pattern Testing) Part 2: Practical Example with Real Crawling """ import asyncio from crawl4ai import ( AsyncWebCrawler, CrawlerRunConfig, MatchMode ) from crawl4ai.processors.pdf import PDFContentScrapingStrategy from crawl4ai.extraction_strategy import JsonCssExtractionStrategy from crawl4ai.content_filter_strategy import PruningContentFilter from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator def print_section(title): """Print a formatted section header""" print(f"\n{'=' * 60}") print(f"{title}") print(f"{'=' * 60}\n") def test_url_matching(config, test_urls, config_name): """Test URL matching for a config and show results""" print(f"Config: {config_name}") print(f"Matcher: {config.url_matcher}") if hasattr(config, 'match_mode'): print(f"Mode: {config.match_mode.value}") print("-" * 40) for url in test_urls: matches = config.is_match(url) symbol = "โœ“" if matches else "โœ—" print(f"{symbol} {url}") print() # ============================================================================== # PART 1: Understanding URL Matching # ============================================================================== def demo_part1_pattern_matching(): """Part 1: Learn how URL matching works without crawling""" print_section("PART 1: Understanding URL Matching") print("Let's explore different ways to match URLs with configs.\n") # Test URLs we'll use throughout test_urls = [ "https://example.com/report.pdf", "https://example.com/data.json", "https://example.com/blog/post-1", "https://example.com/article/news", "https://api.example.com/v1/users", "https://example.com/about" ] # 1.1 Simple String Pattern print("1.1 Simple String Pattern Matching") print("-" * 40) pdf_config = CrawlerRunConfig( url_matcher="*.pdf" ) test_url_matching(pdf_config, test_urls, "PDF Config") # 1.2 Multiple String Patterns print("1.2 Multiple String Patterns (OR logic)") print("-" * 40) blog_config = CrawlerRunConfig( url_matcher=["*/blog/*", "*/article/*", "*/news/*"], match_mode=MatchMode.OR # This is default, shown for clarity ) test_url_matching(blog_config, test_urls, "Blog/Article Config") # 1.3 Single Function Matcher print("1.3 Function-based Matching") print("-" * 40) api_config = CrawlerRunConfig( url_matcher=lambda url: 'api' in url or url.endswith('.json') ) test_url_matching(api_config, test_urls, "API Config") # 1.4 List of Functions print("1.4 Multiple Functions with AND Logic") print("-" * 40) # Must be HTTPS AND contain 'api' AND have version number secure_api_config = CrawlerRunConfig( url_matcher=[ lambda url: url.startswith('https://'), lambda url: 'api' in url, lambda url: '/v' in url # Version indicator ], match_mode=MatchMode.AND ) test_url_matching(secure_api_config, test_urls, "Secure API Config") # 1.5 Mixed: String and Function Together print("1.5 Mixed Patterns: String + Function") print("-" * 40) # Match JSON files OR any API endpoint json_or_api_config = CrawlerRunConfig( url_matcher=[ "*.json", # String pattern lambda url: 'api' in url # Function ], match_mode=MatchMode.OR ) test_url_matching(json_or_api_config, test_urls, "JSON or API Config") # 1.6 Complex: Multiple Strings + Multiple Functions print("1.6 Complex Matcher: Mixed Types with AND Logic") print("-" * 40) # Must be: HTTPS AND (.com domain) AND (blog OR article) AND NOT a PDF complex_config = CrawlerRunConfig( url_matcher=[ lambda url: url.startswith('https://'), # Function: HTTPS check "*.com/*", # String: .com domain lambda url: any(pattern in url for pattern in ['/blog/', '/article/']), # Function: Blog OR article lambda url: not url.endswith('.pdf') # Function: Not PDF ], match_mode=MatchMode.AND ) test_url_matching(complex_config, test_urls, "Complex Mixed Config") print("\nโœ… Key Takeaway: First matching config wins when passed to arun_many()!") # ============================================================================== # PART 2: Practical Multi-URL Crawling # ============================================================================== async def demo_part2_practical_crawling(): """Part 2: Real-world example with different content types""" print_section("PART 2: Practical Multi-URL Crawling") print("Now let's see multi-config in action with real URLs.\n") # Create specialized configs for different content types configs = [ # Config 1: PDF documents - only match files ending with .pdf CrawlerRunConfig( url_matcher="*.pdf", scraping_strategy=PDFContentScrapingStrategy() ), # Config 2: Blog/article pages with content filtering CrawlerRunConfig( url_matcher=["*/blog/*", "*/article/*", "*python.org*"], markdown_generator=DefaultMarkdownGenerator( content_filter=PruningContentFilter(threshold=0.48) ) ), # Config 3: Dynamic pages requiring JavaScript CrawlerRunConfig( url_matcher=lambda url: 'github.com' in url, js_code="window.scrollTo(0, 500);" # Scroll to load content ), # Config 4: Mixed matcher - API endpoints (string OR function) CrawlerRunConfig( url_matcher=[ "*.json", # String pattern for JSON files lambda url: 'api' in url or 'httpbin.org' in url # Function for API endpoints ], match_mode=MatchMode.OR, ), # Config 5: Complex matcher - Secure documentation sites CrawlerRunConfig( url_matcher=[ lambda url: url.startswith('https://'), # Must be HTTPS "*.org/*", # String: .org domain lambda url: any(doc in url for doc in ['docs', 'documentation', 'reference']), # Has docs lambda url: not url.endswith(('.pdf', '.json')) # Not PDF or JSON ], match_mode=MatchMode.AND, # wait_for="css:.content, css:article" # Wait for content to load ), # Default config for everything else # CrawlerRunConfig() # No url_matcher means it matches everything (use it as fallback) ] # URLs to crawl - each will use a different config urls = [ "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", # โ†’ PDF config "https://blog.python.org/", # โ†’ Blog config with content filter "https://github.com/microsoft/playwright", # โ†’ JS config "https://httpbin.org/json", # โ†’ Mixed matcher config (API) "https://docs.python.org/3/reference/", # โ†’ Complex matcher config "https://www.w3schools.com/", # โ†’ Default config, if you uncomment the default config line above, if not you will see `Error: No matching configuration` ] print("URLs to crawl:") for i, url in enumerate(urls, 1): print(f"{i}. {url}") print("\nCrawling with appropriate config for each URL...\n") async with AsyncWebCrawler() as crawler: results = await crawler.arun_many( urls=urls, config=configs ) # Display results print("Results:") print("-" * 60) for result in results: if result.success: # Determine which config was used config_type = "Default" if result.url.endswith('.pdf'): config_type = "PDF Strategy" elif any(pattern in result.url for pattern in ['blog', 'python.org']) and 'docs' not in result.url: config_type = "Blog + Content Filter" elif 'github.com' in result.url: config_type = "JavaScript Enabled" elif 'httpbin.org' in result.url or result.url.endswith('.json'): config_type = "Mixed Matcher (API)" elif 'docs.python.org' in result.url: config_type = "Complex Matcher (Secure Docs)" print(f"\nโœ“ {result.url}") print(f" Config used: {config_type}") print(f" Content size: {len(result.markdown)} chars") # Show if we have fit_markdown (from content filter) if hasattr(result.markdown, 'fit_markdown') and result.markdown.fit_markdown: print(f" Fit markdown size: {len(result.markdown.fit_markdown)} chars") reduction = (1 - len(result.markdown.fit_markdown) / len(result.markdown)) * 100 print(f" Content reduced by: {reduction:.1f}%") # Show extracted data if using extraction strategy if hasattr(result, 'extracted_content') and result.extracted_content: print(f" Extracted data: {str(result.extracted_content)[:100]}...") else: print(f"\nโœ— {result.url}") print(f" Error: {result.error_message}") print("\n" + "=" * 60) print("โœ… Multi-config crawling complete!") print("\nBenefits demonstrated:") print("- PDFs handled with specialized scraper") print("- Blog content filtered for relevance") print("- JavaScript executed only where needed") print("- Mixed matchers (string + function) for flexible matching") print("- Complex matchers for precise URL targeting") print("- Each URL got optimal configuration automatically!") async def main(): """Run both parts of the demo""" print(""" ๐ŸŽฏ Multi-Config URL Matching Demo ================================= Learn how Crawl4AI can use different configurations for different URLs in a single batch. """) # Part 1: Pattern matching demo_part1_pattern_matching() print("\nPress Enter to continue to Part 2...") try: input() except EOFError: # Running in non-interactive mode, skip input pass # Part 2: Practical crawling await demo_part2_practical_crawling() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/demo_multi_config_clean.py", "license": "Apache License 2.0", "lines": 239, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/hello_world_undetected.py
import asyncio from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, DefaultMarkdownGenerator, PruningContentFilter, CrawlResult, UndetectedAdapter ) from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy async def main(): # Create browser config browser_config = BrowserConfig( headless=False, verbose=True, ) # Create the undetected adapter undetected_adapter = UndetectedAdapter() # Create the crawler strategy with the undetected adapter crawler_strategy = AsyncPlaywrightCrawlerStrategy( browser_config=browser_config, browser_adapter=undetected_adapter ) # Create the crawler with our custom strategy async with AsyncWebCrawler( crawler_strategy=crawler_strategy, config=browser_config ) as crawler: # Configure the crawl crawler_config = CrawlerRunConfig( markdown_generator=DefaultMarkdownGenerator( content_filter=PruningContentFilter() ), capture_console_messages=True, # Enable console capture to test adapter ) # Test on a site that typically detects bots print("Testing undetected adapter...") result: CrawlResult = await crawler.arun( url="https://www.helloworld.org", config=crawler_config ) print(f"Status: {result.status_code}") print(f"Success: {result.success}") print(f"Console messages captured: {len(result.console_messages or [])}") print(f"Markdown content (first 500 chars):\n{result.markdown.raw_markdown[:500]}") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/hello_world_undetected.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/simple_anti_bot_examples.py
import asyncio from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, UndetectedAdapter from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy # Example 1: Stealth Mode async def stealth_mode_example(): browser_config = BrowserConfig( enable_stealth=True, headless=False ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun("https://example.com") return result.html[:500] # Example 2: Undetected Browser async def undetected_browser_example(): browser_config = BrowserConfig( headless=False ) adapter = UndetectedAdapter() strategy = AsyncPlaywrightCrawlerStrategy( browser_config=browser_config, browser_adapter=adapter ) async with AsyncWebCrawler( crawler_strategy=strategy, config=browser_config ) as crawler: result = await crawler.arun("https://example.com") return result.html[:500] # Example 3: Both Combined async def combined_example(): browser_config = BrowserConfig( enable_stealth=True, headless=False ) adapter = UndetectedAdapter() strategy = AsyncPlaywrightCrawlerStrategy( browser_config=browser_config, browser_adapter=adapter ) async with AsyncWebCrawler( crawler_strategy=strategy, config=browser_config ) as crawler: result = await crawler.arun("https://example.com") return result.html[:500] # Run examples if __name__ == "__main__": asyncio.run(stealth_mode_example()) asyncio.run(undetected_browser_example()) asyncio.run(combined_example())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/simple_anti_bot_examples.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/stealth_mode_example.py
""" Stealth Mode Example with Crawl4AI This example demonstrates how to use the stealth mode feature to bypass basic bot detection. The stealth mode uses playwright-stealth to modify browser fingerprints and behaviors that are commonly used to detect automated browsers. Key features demonstrated: 1. Comparing crawling with and without stealth mode 2. Testing against bot detection sites 3. Accessing sites that block automated browsers 4. Best practices for stealth crawling """ import asyncio import json from typing import Dict, Any from colorama import Fore, Style, init from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig from crawl4ai.async_logger import AsyncLogger # Initialize colorama for colored output init() # Create a logger for better output logger = AsyncLogger(verbose=True) async def test_bot_detection(use_stealth: bool = False) -> Dict[str, Any]: """Test against a bot detection service""" logger.info( f"Testing bot detection with stealth={'ON' if use_stealth else 'OFF'}", tag="STEALTH" ) # Configure browser with or without stealth browser_config = BrowserConfig( headless=False, # Use False to see the browser in action enable_stealth=use_stealth, viewport_width=1280, viewport_height=800 ) async with AsyncWebCrawler(config=browser_config) as crawler: # JavaScript to extract bot detection results detection_script = """ // Comprehensive bot detection checks (() => { const detectionResults = { // Basic WebDriver detection webdriver: navigator.webdriver, // Chrome specific chrome: !!window.chrome, chromeRuntime: !!window.chrome?.runtime, // Automation indicators automationControlled: navigator.webdriver, // Permissions API permissionsPresent: !!navigator.permissions?.query, // Plugins pluginsLength: navigator.plugins.length, pluginsArray: Array.from(navigator.plugins).map(p => p.name), // Languages languages: navigator.languages, language: navigator.language, // User agent userAgent: navigator.userAgent, // Screen and window properties screen: { width: screen.width, height: screen.height, availWidth: screen.availWidth, availHeight: screen.availHeight, colorDepth: screen.colorDepth, pixelDepth: screen.pixelDepth }, // WebGL vendor webglVendor: (() => { try { const canvas = document.createElement('canvas'); const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl'); const ext = gl.getExtension('WEBGL_debug_renderer_info'); return gl.getParameter(ext.UNMASKED_VENDOR_WEBGL); } catch (e) { return 'Error'; } })(), // Platform platform: navigator.platform, // Hardware concurrency hardwareConcurrency: navigator.hardwareConcurrency, // Device memory deviceMemory: navigator.deviceMemory, // Connection connection: navigator.connection?.effectiveType }; // Log results for console capture console.log('DETECTION_RESULTS:', JSON.stringify(detectionResults, null, 2)); // Return results return detectionResults; })(); """ # Crawl bot detection test page config = CrawlerRunConfig( js_code=detection_script, capture_console_messages=True, wait_until="networkidle", delay_before_return_html=2.0 # Give time for all checks to complete ) result = await crawler.arun( url="https://bot.sannysoft.com", config=config ) if result.success: # Extract detection results from console detection_data = None for msg in result.console_messages or []: if "DETECTION_RESULTS:" in msg.get("text", ""): try: json_str = msg["text"].replace("DETECTION_RESULTS:", "").strip() detection_data = json.loads(json_str) except: pass # Also try to get from JavaScript execution result if not detection_data and result.js_execution_result: detection_data = result.js_execution_result return { "success": True, "url": result.url, "detection_data": detection_data, "page_title": result.metadata.get("title", ""), "stealth_enabled": use_stealth } else: return { "success": False, "error": result.error_message, "stealth_enabled": use_stealth } async def test_cloudflare_site(use_stealth: bool = False) -> Dict[str, Any]: """Test accessing a Cloudflare-protected site""" logger.info( f"Testing Cloudflare site with stealth={'ON' if use_stealth else 'OFF'}", tag="STEALTH" ) browser_config = BrowserConfig( headless=True, # Cloudflare detection works better in headless mode with stealth enable_stealth=use_stealth, viewport_width=1920, viewport_height=1080 ) async with AsyncWebCrawler(config=browser_config) as crawler: config = CrawlerRunConfig( wait_until="networkidle", page_timeout=30000, # 30 seconds delay_before_return_html=3.0 ) # Test on a site that often shows Cloudflare challenges result = await crawler.arun( url="https://nowsecure.nl", config=config ) # Check if we hit Cloudflare challenge cloudflare_detected = False if result.html: cloudflare_indicators = [ "Checking your browser", "Just a moment", "cf-browser-verification", "cf-challenge", "ray ID" ] cloudflare_detected = any(indicator in result.html for indicator in cloudflare_indicators) return { "success": result.success, "url": result.url, "cloudflare_challenge": cloudflare_detected, "status_code": result.status_code, "page_title": result.metadata.get("title", "") if result.metadata else "", "stealth_enabled": use_stealth, "html_snippet": result.html[:500] if result.html else "" } async def test_anti_bot_site(use_stealth: bool = False) -> Dict[str, Any]: """Test against sites with anti-bot measures""" logger.info( f"Testing anti-bot site with stealth={'ON' if use_stealth else 'OFF'}", tag="STEALTH" ) browser_config = BrowserConfig( headless=False, enable_stealth=use_stealth, # Additional browser arguments that help with stealth extra_args=[ "--disable-blink-features=AutomationControlled", "--disable-features=site-per-process" ] if not use_stealth else [] # These are automatically applied with stealth ) async with AsyncWebCrawler(config=browser_config) as crawler: # Some sites check for specific behaviors behavior_script = """ (async () => { // Simulate human-like behavior const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); // Random mouse movement const moveX = Math.random() * 100; const moveY = Math.random() * 100; // Simulate reading time await sleep(1000 + Math.random() * 2000); // Scroll slightly window.scrollBy(0, 100 + Math.random() * 200); console.log('Human behavior simulation complete'); return true; })() """ config = CrawlerRunConfig( js_code=behavior_script, wait_until="networkidle", delay_before_return_html=5.0, # Longer delay to appear more human capture_console_messages=True ) # Test on a site that implements anti-bot measures result = await crawler.arun( url="https://www.g2.com/", config=config ) # Check for common anti-bot blocks blocked_indicators = [ "Access Denied", "403 Forbidden", "Security Check", "Verify you are human", "captcha", "challenge" ] blocked = False if result.html: blocked = any(indicator.lower() in result.html.lower() for indicator in blocked_indicators) return { "success": result.success and not blocked, "url": result.url, "blocked": blocked, "status_code": result.status_code, "page_title": result.metadata.get("title", "") if result.metadata else "", "stealth_enabled": use_stealth } async def compare_results(): """Run all tests with and without stealth mode and compare results""" print(f"\n{Fore.CYAN}{'='*60}{Style.RESET_ALL}") print(f"{Fore.CYAN}Crawl4AI Stealth Mode Comparison{Style.RESET_ALL}") print(f"{Fore.CYAN}{'='*60}{Style.RESET_ALL}\n") # Test 1: Bot Detection print(f"{Fore.YELLOW}1. Bot Detection Test (bot.sannysoft.com){Style.RESET_ALL}") print("-" * 40) # Without stealth regular_detection = await test_bot_detection(use_stealth=False) if regular_detection["success"] and regular_detection["detection_data"]: print(f"{Fore.RED}Without Stealth:{Style.RESET_ALL}") data = regular_detection["detection_data"] print(f" โ€ข WebDriver detected: {data.get('webdriver', 'Unknown')}") print(f" โ€ข Chrome: {data.get('chrome', 'Unknown')}") print(f" โ€ข Languages: {data.get('languages', 'Unknown')}") print(f" โ€ข Plugins: {data.get('pluginsLength', 'Unknown')}") print(f" โ€ข User Agent: {data.get('userAgent', 'Unknown')[:60]}...") # With stealth stealth_detection = await test_bot_detection(use_stealth=True) if stealth_detection["success"] and stealth_detection["detection_data"]: print(f"\n{Fore.GREEN}With Stealth:{Style.RESET_ALL}") data = stealth_detection["detection_data"] print(f" โ€ข WebDriver detected: {data.get('webdriver', 'Unknown')}") print(f" โ€ข Chrome: {data.get('chrome', 'Unknown')}") print(f" โ€ข Languages: {data.get('languages', 'Unknown')}") print(f" โ€ข Plugins: {data.get('pluginsLength', 'Unknown')}") print(f" โ€ข User Agent: {data.get('userAgent', 'Unknown')[:60]}...") # Test 2: Cloudflare Site print(f"\n\n{Fore.YELLOW}2. Cloudflare Protected Site Test{Style.RESET_ALL}") print("-" * 40) # Without stealth regular_cf = await test_cloudflare_site(use_stealth=False) print(f"{Fore.RED}Without Stealth:{Style.RESET_ALL}") print(f" โ€ข Success: {regular_cf['success']}") print(f" โ€ข Cloudflare Challenge: {regular_cf['cloudflare_challenge']}") print(f" โ€ข Status Code: {regular_cf['status_code']}") print(f" โ€ข Page Title: {regular_cf['page_title']}") # With stealth stealth_cf = await test_cloudflare_site(use_stealth=True) print(f"\n{Fore.GREEN}With Stealth:{Style.RESET_ALL}") print(f" โ€ข Success: {stealth_cf['success']}") print(f" โ€ข Cloudflare Challenge: {stealth_cf['cloudflare_challenge']}") print(f" โ€ข Status Code: {stealth_cf['status_code']}") print(f" โ€ข Page Title: {stealth_cf['page_title']}") # Test 3: Anti-bot Site print(f"\n\n{Fore.YELLOW}3. Anti-Bot Site Test{Style.RESET_ALL}") print("-" * 40) # Without stealth regular_antibot = await test_anti_bot_site(use_stealth=False) print(f"{Fore.RED}Without Stealth:{Style.RESET_ALL}") print(f" โ€ข Success: {regular_antibot['success']}") print(f" โ€ข Blocked: {regular_antibot['blocked']}") print(f" โ€ข Status Code: {regular_antibot['status_code']}") print(f" โ€ข Page Title: {regular_antibot['page_title']}") # With stealth stealth_antibot = await test_anti_bot_site(use_stealth=True) print(f"\n{Fore.GREEN}With Stealth:{Style.RESET_ALL}") print(f" โ€ข Success: {stealth_antibot['success']}") print(f" โ€ข Blocked: {stealth_antibot['blocked']}") print(f" โ€ข Status Code: {stealth_antibot['status_code']}") print(f" โ€ข Page Title: {stealth_antibot['page_title']}") # Summary print(f"\n{Fore.CYAN}{'='*60}{Style.RESET_ALL}") print(f"{Fore.CYAN}Summary:{Style.RESET_ALL}") print(f"{Fore.CYAN}{'='*60}{Style.RESET_ALL}") print(f"\nStealth mode helps bypass basic bot detection by:") print(f" โ€ข Hiding webdriver property") print(f" โ€ข Modifying browser fingerprints") print(f" โ€ข Adjusting navigator properties") print(f" โ€ข Emulating real browser plugin behavior") print(f"\n{Fore.YELLOW}Note:{Style.RESET_ALL} Stealth mode is not a silver bullet.") print(f"Advanced anti-bot systems may still detect automation.") print(f"Always respect robots.txt and website terms of service.") async def stealth_best_practices(): """Demonstrate best practices for using stealth mode""" print(f"\n\n{Fore.CYAN}{'='*60}{Style.RESET_ALL}") print(f"{Fore.CYAN}Stealth Mode Best Practices{Style.RESET_ALL}") print(f"{Fore.CYAN}{'='*60}{Style.RESET_ALL}\n") # Best Practice 1: Combine with realistic behavior print(f"{Fore.YELLOW}1. Combine with Realistic Behavior:{Style.RESET_ALL}") browser_config = BrowserConfig( headless=False, enable_stealth=True, viewport_width=1920, viewport_height=1080 ) async with AsyncWebCrawler(config=browser_config) as crawler: # Simulate human-like behavior human_behavior_script = """ (async () => { // Wait random time between actions const randomWait = () => Math.random() * 2000 + 1000; // Simulate reading await new Promise(resolve => setTimeout(resolve, randomWait())); // Smooth scroll const smoothScroll = async () => { const totalHeight = document.body.scrollHeight; const viewHeight = window.innerHeight; let currentPosition = 0; while (currentPosition < totalHeight - viewHeight) { const scrollAmount = Math.random() * 300 + 100; window.scrollBy({ top: scrollAmount, behavior: 'smooth' }); currentPosition += scrollAmount; await new Promise(resolve => setTimeout(resolve, randomWait())); } }; await smoothScroll(); console.log('Human-like behavior simulation completed'); return true; })() """ config = CrawlerRunConfig( js_code=human_behavior_script, wait_until="networkidle", delay_before_return_html=3.0, capture_console_messages=True ) result = await crawler.arun( url="https://example.com", config=config ) print(f" โœ“ Simulated human-like scrolling and reading patterns") print(f" โœ“ Added random delays between actions") print(f" โœ“ Result: {result.success}") # Best Practice 2: Use appropriate viewport and user agent print(f"\n{Fore.YELLOW}2. Use Realistic Viewport and User Agent:{Style.RESET_ALL}") # Get a realistic user agent from crawl4ai.user_agent_generator import UserAgentGenerator ua_generator = UserAgentGenerator() browser_config = BrowserConfig( headless=True, enable_stealth=True, viewport_width=1920, viewport_height=1080, user_agent=ua_generator.generate(device_type="desktop", browser_type="chrome") ) print(f" โœ“ Using realistic viewport: 1920x1080") print(f" โœ“ Using current Chrome user agent") print(f" โœ“ Stealth mode will ensure consistency") # Best Practice 3: Manage request rate print(f"\n{Fore.YELLOW}3. Manage Request Rate:{Style.RESET_ALL}") print(f" โœ“ Add delays between requests") print(f" โœ“ Randomize timing patterns") print(f" โœ“ Respect robots.txt") # Best Practice 4: Session management print(f"\n{Fore.YELLOW}4. Use Session Management:{Style.RESET_ALL}") browser_config = BrowserConfig( headless=False, enable_stealth=True ) async with AsyncWebCrawler(config=browser_config) as crawler: # Create a session for multiple requests session_id = "stealth_session_1" config = CrawlerRunConfig( session_id=session_id, wait_until="domcontentloaded" ) # First request result1 = await crawler.arun( url="https://example.com", config=config ) # Subsequent request reuses the same browser context result2 = await crawler.arun( url="https://example.com/about", config=config ) print(f" โœ“ Reused browser session for multiple requests") print(f" โœ“ Maintains cookies and state between requests") print(f" โœ“ More efficient and realistic browsing pattern") print(f"\n{Fore.CYAN}{'='*60}{Style.RESET_ALL}") async def main(): """Run all examples""" # Run comparison tests await compare_results() # Show best practices await stealth_best_practices() print(f"\n{Fore.GREEN}Examples completed!{Style.RESET_ALL}") print(f"\n{Fore.YELLOW}Remember:{Style.RESET_ALL}") print(f"โ€ข Stealth mode helps with basic bot detection") print(f"โ€ข Always respect website terms of service") print(f"โ€ข Consider rate limiting and ethical scraping practices") print(f"โ€ข For advanced protection, consider additional measures") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/stealth_mode_example.py", "license": "Apache License 2.0", "lines": 424, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/stealth_mode_quick_start.py
""" Quick Start: Using Stealth Mode in Crawl4AI This example shows practical use cases for the stealth mode feature. Stealth mode helps bypass basic bot detection mechanisms. """ import asyncio from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig async def example_1_basic_stealth(): """Example 1: Basic stealth mode usage""" print("\n=== Example 1: Basic Stealth Mode ===") # Enable stealth mode in browser config browser_config = BrowserConfig( enable_stealth=True, # This is the key parameter headless=True ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun(url="https://example.com") print(f"โœ“ Crawled {result.url} successfully") print(f"โœ“ Title: {result.metadata.get('title', 'N/A')}") async def example_2_stealth_with_screenshot(): """Example 2: Stealth mode with screenshot to show detection results""" print("\n=== Example 2: Stealth Mode Visual Verification ===") browser_config = BrowserConfig( enable_stealth=True, headless=False # Set to False to see the browser ) async with AsyncWebCrawler(config=browser_config) as crawler: config = CrawlerRunConfig( screenshot=True, wait_until="networkidle" ) result = await crawler.arun( url="https://bot.sannysoft.com", config=config ) if result.success: print(f"โœ“ Successfully crawled bot detection site") print(f"โœ“ With stealth enabled, many detection tests should show as passed") if result.screenshot: # Save screenshot for verification import base64 with open("stealth_detection_results.png", "wb") as f: f.write(base64.b64decode(result.screenshot)) print(f"โœ“ Screenshot saved as 'stealth_detection_results.png'") print(f" Check the screenshot to see detection results!") async def example_3_stealth_for_protected_sites(): """Example 3: Using stealth for sites with bot protection""" print("\n=== Example 3: Stealth for Protected Sites ===") browser_config = BrowserConfig( enable_stealth=True, headless=True, viewport_width=1920, viewport_height=1080 ) async with AsyncWebCrawler(config=browser_config) as crawler: # Add human-like behavior config = CrawlerRunConfig( wait_until="networkidle", delay_before_return_html=2.0, # Wait 2 seconds js_code=""" // Simulate human-like scrolling window.scrollTo({ top: document.body.scrollHeight / 2, behavior: 'smooth' }); """ ) # Try accessing a site that might have bot protection result = await crawler.arun( url="https://www.g2.com/products/slack/reviews", config=config ) if result.success: print(f"โœ“ Successfully accessed protected site") print(f"โœ“ Retrieved {len(result.html)} characters of HTML") else: print(f"โœ— Failed to access site: {result.error_message}") async def example_4_stealth_with_sessions(): """Example 4: Stealth mode with session management""" print("\n=== Example 4: Stealth + Session Management ===") browser_config = BrowserConfig( enable_stealth=True, headless=False ) async with AsyncWebCrawler(config=browser_config) as crawler: session_id = "my_stealth_session" # First request - establish session config = CrawlerRunConfig( session_id=session_id, wait_until="domcontentloaded" ) result1 = await crawler.arun( url="https://news.ycombinator.com", config=config ) print(f"โœ“ First request completed: {result1.url}") # Second request - reuse session await asyncio.sleep(2) # Brief delay between requests result2 = await crawler.arun( url="https://news.ycombinator.com/best", config=config ) print(f"โœ“ Second request completed: {result2.url}") print(f"โœ“ Session reused, maintaining cookies and state") async def example_5_stealth_comparison(): """Example 5: Compare results with and without stealth using screenshots""" print("\n=== Example 5: Stealth Mode Comparison ===") test_url = "https://bot.sannysoft.com" # First test WITHOUT stealth print("\nWithout stealth:") regular_config = BrowserConfig( enable_stealth=False, headless=True ) async with AsyncWebCrawler(config=regular_config) as crawler: config = CrawlerRunConfig( screenshot=True, wait_until="networkidle" ) result = await crawler.arun(url=test_url, config=config) if result.success and result.screenshot: import base64 with open("comparison_without_stealth.png", "wb") as f: f.write(base64.b64decode(result.screenshot)) print(f" โœ“ Screenshot saved: comparison_without_stealth.png") print(f" Many tests will show as FAILED (red)") # Then test WITH stealth print("\nWith stealth:") stealth_config = BrowserConfig( enable_stealth=True, headless=True ) async with AsyncWebCrawler(config=stealth_config) as crawler: config = CrawlerRunConfig( screenshot=True, wait_until="networkidle" ) result = await crawler.arun(url=test_url, config=config) if result.success and result.screenshot: import base64 with open("comparison_with_stealth.png", "wb") as f: f.write(base64.b64decode(result.screenshot)) print(f" โœ“ Screenshot saved: comparison_with_stealth.png") print(f" More tests should show as PASSED (green)") print("\nCompare the two screenshots to see the difference!") async def main(): """Run all examples""" print("Crawl4AI Stealth Mode Examples") print("==============================") # Run basic example await example_1_basic_stealth() # Run screenshot verification example await example_2_stealth_with_screenshot() # Run protected site example await example_3_stealth_for_protected_sites() # Run session example await example_4_stealth_with_sessions() # Run comparison example await example_5_stealth_comparison() print("\n" + "="*50) print("Tips for using stealth mode effectively:") print("- Use realistic viewport sizes (1920x1080, 1366x768)") print("- Add delays between requests to appear more human") print("- Combine with session management for better results") print("- Remember: stealth mode is for legitimate scraping only") print("="*50) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/stealth_mode_quick_start.py", "license": "Apache License 2.0", "lines": 168, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/stealth_test_simple.py
""" Simple test to verify stealth mode is working """ import asyncio from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig async def test_stealth(): """Test stealth mode effectiveness""" # Test WITHOUT stealth print("=== WITHOUT Stealth ===") config1 = BrowserConfig( headless=False, enable_stealth=False ) async with AsyncWebCrawler(config=config1) as crawler: result = await crawler.arun( url="https://bot.sannysoft.com", config=CrawlerRunConfig( wait_until="networkidle", screenshot=True ) ) print(f"Success: {result.success}") # Take screenshot if result.screenshot: with open("without_stealth.png", "wb") as f: import base64 f.write(base64.b64decode(result.screenshot)) print("Screenshot saved: without_stealth.png") # Test WITH stealth print("\n=== WITH Stealth ===") config2 = BrowserConfig( headless=False, enable_stealth=True ) async with AsyncWebCrawler(config=config2) as crawler: result = await crawler.arun( url="https://bot.sannysoft.com", config=CrawlerRunConfig( wait_until="networkidle", screenshot=True ) ) print(f"Success: {result.success}") # Take screenshot if result.screenshot: with open("with_stealth.png", "wb") as f: import base64 f.write(base64.b64decode(result.screenshot)) print("Screenshot saved: with_stealth.png") print("\nCheck the screenshots to see the difference in bot detection results!") if __name__ == "__main__": asyncio.run(test_stealth())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/stealth_test_simple.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/undetectability/undetected_basic_test.py
""" Basic Undetected Browser Test Simple example to test if undetected mode works """ import asyncio from crawl4ai import AsyncWebCrawler, BrowserConfig async def test_regular_mode(): """Test with regular browser""" print("Testing Regular Browser Mode...") browser_config = BrowserConfig( headless=False, verbose=True ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun(url="https://www.example.com") print(f"Regular Mode - Success: {result.success}") print(f"Regular Mode - Status: {result.status_code}") print(f"Regular Mode - Content length: {len(result.markdown.raw_markdown)}") print(f"Regular Mode - First 100 chars: {result.markdown.raw_markdown[:100]}...") return result.success async def test_undetected_mode(): """Test with undetected browser""" print("\nTesting Undetected Browser Mode...") from crawl4ai import UndetectedAdapter from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy browser_config = BrowserConfig( headless=False, verbose=True ) # Create undetected adapter undetected_adapter = UndetectedAdapter() # Create strategy with undetected adapter crawler_strategy = AsyncPlaywrightCrawlerStrategy( browser_config=browser_config, browser_adapter=undetected_adapter ) async with AsyncWebCrawler( crawler_strategy=crawler_strategy, config=browser_config ) as crawler: result = await crawler.arun(url="https://www.example.com") print(f"Undetected Mode - Success: {result.success}") print(f"Undetected Mode - Status: {result.status_code}") print(f"Undetected Mode - Content length: {len(result.markdown.raw_markdown)}") print(f"Undetected Mode - First 100 chars: {result.markdown.raw_markdown[:100]}...") return result.success async def main(): """Run both tests""" print("๐Ÿค– Crawl4AI Basic Adapter Test\n") # Test regular mode regular_success = await test_regular_mode() # Test undetected mode undetected_success = await test_undetected_mode() # Summary print("\n" + "="*50) print("Summary:") print(f"Regular Mode: {'โœ… Success' if regular_success else 'โŒ Failed'}") print(f"Undetected Mode: {'โœ… Success' if undetected_success else 'โŒ Failed'}") print("="*50) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/undetectability/undetected_basic_test.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:docs/examples/undetectability/undetected_bot_test.py
""" Bot Detection Test - Compare Regular vs Undetected Tests browser fingerprinting differences at bot.sannysoft.com """ import asyncio from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, UndetectedAdapter, CrawlResult ) from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy # Bot detection test site TEST_URL = "https://bot.sannysoft.com" def analyze_bot_detection(result: CrawlResult) -> dict: """Analyze bot detection results from the page""" detections = { "webdriver": False, "headless": False, "automation": False, "user_agent": False, "total_tests": 0, "failed_tests": 0 } if not result.success or not result.html: return detections # Look for specific test results in the HTML html_lower = result.html.lower() # Check for common bot indicators if "webdriver" in html_lower and ("fail" in html_lower or "true" in html_lower): detections["webdriver"] = True detections["failed_tests"] += 1 if "headless" in html_lower and ("fail" in html_lower or "true" in html_lower): detections["headless"] = True detections["failed_tests"] += 1 if "automation" in html_lower and "detected" in html_lower: detections["automation"] = True detections["failed_tests"] += 1 # Count total tests (approximate) detections["total_tests"] = html_lower.count("test") + html_lower.count("check") return detections async def test_browser_mode(adapter_name: str, adapter=None): """Test a browser mode and return results""" print(f"\n{'='*60}") print(f"Testing: {adapter_name}") print(f"{'='*60}") browser_config = BrowserConfig( headless=False, # Run in headed mode for better results verbose=True, viewport_width=1920, viewport_height=1080, ) if adapter: # Use undetected mode crawler_strategy = AsyncPlaywrightCrawlerStrategy( browser_config=browser_config, browser_adapter=adapter ) crawler = AsyncWebCrawler( crawler_strategy=crawler_strategy, config=browser_config ) else: # Use regular mode crawler = AsyncWebCrawler(config=browser_config) async with crawler: config = CrawlerRunConfig( delay_before_return_html=3.0, # Let detection scripts run wait_for_images=True, screenshot=True, simulate_user=False, # Don't simulate for accurate detection ) result = await crawler.arun(url=TEST_URL, config=config) print(f"\nโœ“ Success: {result.success}") print(f"โœ“ Status Code: {result.status_code}") if result.success: # Analyze detection results detections = analyze_bot_detection(result) print(f"\n๐Ÿ” Bot Detection Analysis:") print(f" - WebDriver Detected: {'โŒ Yes' if detections['webdriver'] else 'โœ… No'}") print(f" - Headless Detected: {'โŒ Yes' if detections['headless'] else 'โœ… No'}") print(f" - Automation Detected: {'โŒ Yes' if detections['automation'] else 'โœ… No'}") print(f" - Failed Tests: {detections['failed_tests']}") # Show some content if result.markdown.raw_markdown: print(f"\nContent preview:") lines = result.markdown.raw_markdown.split('\n') for line in lines[:20]: # Show first 20 lines if any(keyword in line.lower() for keyword in ['test', 'pass', 'fail', 'yes', 'no']): print(f" {line.strip()}") return result, detections if result.success else {} async def main(): """Run the comparison""" print("๐Ÿค– Crawl4AI - Bot Detection Test") print(f"Testing at: {TEST_URL}") print("This site runs various browser fingerprinting tests\n") # Test regular browser regular_result, regular_detections = await test_browser_mode("Regular Browser") # Small delay await asyncio.sleep(2) # Test undetected browser undetected_adapter = UndetectedAdapter() undetected_result, undetected_detections = await test_browser_mode( "Undetected Browser", undetected_adapter ) # Summary comparison print(f"\n{'='*60}") print("COMPARISON SUMMARY") print(f"{'='*60}") print(f"\n{'Test':<25} {'Regular':<15} {'Undetected':<15}") print(f"{'-'*55}") if regular_detections and undetected_detections: print(f"{'WebDriver Detection':<25} {'โŒ Detected' if regular_detections['webdriver'] else 'โœ… Passed':<15} {'โŒ Detected' if undetected_detections['webdriver'] else 'โœ… Passed':<15}") print(f"{'Headless Detection':<25} {'โŒ Detected' if regular_detections['headless'] else 'โœ… Passed':<15} {'โŒ Detected' if undetected_detections['headless'] else 'โœ… Passed':<15}") print(f"{'Automation Detection':<25} {'โŒ Detected' if regular_detections['automation'] else 'โœ… Passed':<15} {'โŒ Detected' if undetected_detections['automation'] else 'โœ… Passed':<15}") print(f"{'Failed Tests':<25} {regular_detections['failed_tests']:<15} {undetected_detections['failed_tests']:<15}") print(f"\n{'='*60}") if undetected_detections.get('failed_tests', 0) < regular_detections.get('failed_tests', 1): print("โœ… Undetected browser performed better at evading detection!") else: print("โ„น๏ธ Both browsers had similar detection results") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/undetectability/undetected_bot_test.py", "license": "Apache License 2.0", "lines": 125, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:docs/examples/undetectability/undetected_cloudflare_test.py
""" Undetected Browser Test - Cloudflare Protected Site Tests the difference between regular and undetected modes on a Cloudflare-protected site """ import asyncio from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, UndetectedAdapter ) from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy # Test URL with Cloudflare protection TEST_URL = "https://nowsecure.nl" async def test_regular_browser(): """Test with regular browser - likely to be blocked""" print("=" * 60) print("Testing with Regular Browser") print("=" * 60) browser_config = BrowserConfig( headless=False, verbose=True, viewport_width=1920, viewport_height=1080, ) async with AsyncWebCrawler(config=browser_config) as crawler: config = CrawlerRunConfig( delay_before_return_html=2.0, simulate_user=True, magic=True, # Try with magic mode too ) result = await crawler.arun(url=TEST_URL, config=config) print(f"\nโœ“ Success: {result.success}") print(f"โœ“ Status Code: {result.status_code}") print(f"โœ“ HTML Length: {len(result.html)}") # Check for Cloudflare challenge if result.html: cf_indicators = [ "Checking your browser", "Please stand by", "cloudflare", "cf-browser-verification", "Access denied", "Ray ID" ] detected = False for indicator in cf_indicators: if indicator.lower() in result.html.lower(): print(f"โš ๏ธ Cloudflare Challenge Detected: '{indicator}' found") detected = True break if not detected and len(result.markdown.raw_markdown) > 100: print("โœ… Successfully bypassed Cloudflare!") print(f"Content preview: {result.markdown.raw_markdown[:200]}...") elif not detected: print("โš ๏ธ Page loaded but content seems minimal") return result async def test_undetected_browser(): """Test with undetected browser - should bypass Cloudflare""" print("\n" + "=" * 60) print("Testing with Undetected Browser") print("=" * 60) browser_config = BrowserConfig( headless=False, # Headless is easier to detect verbose=True, viewport_width=1920, viewport_height=1080, ) # Create undetected adapter undetected_adapter = UndetectedAdapter() # Create strategy with undetected adapter crawler_strategy = AsyncPlaywrightCrawlerStrategy( browser_config=browser_config, browser_adapter=undetected_adapter ) async with AsyncWebCrawler( crawler_strategy=crawler_strategy, config=browser_config ) as crawler: config = CrawlerRunConfig( delay_before_return_html=2.0, simulate_user=True, ) result = await crawler.arun(url=TEST_URL, config=config) print(f"\nโœ“ Success: {result.success}") print(f"โœ“ Status Code: {result.status_code}") print(f"โœ“ HTML Length: {len(result.html)}") # Check for Cloudflare challenge if result.html: cf_indicators = [ "Checking your browser", "Please stand by", "cloudflare", "cf-browser-verification", "Access denied", "Ray ID" ] detected = False for indicator in cf_indicators: if indicator.lower() in result.html.lower(): print(f"โš ๏ธ Cloudflare Challenge Detected: '{indicator}' found") detected = True break if not detected and len(result.markdown.raw_markdown) > 100: print("โœ… Successfully bypassed Cloudflare!") print(f"Content preview: {result.markdown.raw_markdown[:200]}...") elif not detected: print("โš ๏ธ Page loaded but content seems minimal") return result async def main(): """Compare regular vs undetected browser""" print("๐Ÿค– Crawl4AI - Cloudflare Bypass Test") print(f"Testing URL: {TEST_URL}\n") # Test regular browser regular_result = await test_regular_browser() # Small delay await asyncio.sleep(2) # Test undetected browser undetected_result = await test_undetected_browser() # Summary print("\n" + "=" * 60) print("SUMMARY") print("=" * 60) print(f"Regular Browser:") print(f" - Success: {regular_result.success}") print(f" - Content Length: {len(regular_result.markdown.raw_markdown) if regular_result.markdown else 0}") print(f"\nUndetected Browser:") print(f" - Success: {undetected_result.success}") print(f" - Content Length: {len(undetected_result.markdown.raw_markdown) if undetected_result.markdown else 0}") if undetected_result.success and len(undetected_result.markdown.raw_markdown) > len(regular_result.markdown.raw_markdown): print("\nโœ… Undetected browser successfully bypassed protection!") print("=" * 60) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/undetectability/undetected_cloudflare_test.py", "license": "Apache License 2.0", "lines": 134, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:docs/examples/undetectability/undetected_vs_regular_comparison.py
""" Undetected vs Regular Browser Comparison This example demonstrates the difference between regular and undetected browser modes when accessing sites with bot detection services. Based on tested anti-bot services: - Cloudflare - Kasada - Akamai - DataDome - Bet365 - And others """ import asyncio from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, PlaywrightAdapter, UndetectedAdapter, CrawlResult ) from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy # Test URLs for various bot detection services TEST_SITES = { "Cloudflare Protected": "https://nowsecure.nl", # "Bot Detection Test": "https://bot.sannysoft.com", # "Fingerprint Test": "https://fingerprint.com/products/bot-detection", # "Browser Scan": "https://browserscan.net", # "CreepJS": "https://abrahamjuliot.github.io/creepjs", } async def test_with_adapter(url: str, adapter_name: str, adapter): """Test a URL with a specific adapter""" browser_config = BrowserConfig( headless=False, # Better for avoiding detection viewport_width=1920, viewport_height=1080, verbose=True, ) # Create the crawler strategy with the adapter crawler_strategy = AsyncPlaywrightCrawlerStrategy( browser_config=browser_config, browser_adapter=adapter ) print(f"\n{'='*60}") print(f"Testing with {adapter_name} adapter") print(f"URL: {url}") print(f"{'='*60}") try: async with AsyncWebCrawler( crawler_strategy=crawler_strategy, config=browser_config ) as crawler: crawler_config = CrawlerRunConfig( delay_before_return_html=3.0, # Give page time to load wait_for_images=True, screenshot=True, simulate_user=True, # Add user simulation ) result: CrawlResult = await crawler.arun( url=url, config=crawler_config ) # Check results print(f"โœ“ Status Code: {result.status_code}") print(f"โœ“ Success: {result.success}") print(f"โœ“ HTML Length: {len(result.html)}") print(f"โœ“ Markdown Length: {len(result.markdown.raw_markdown)}") # Check for common bot detection indicators detection_indicators = [ "Access denied", "Please verify you are human", "Checking your browser", "Enable JavaScript", "captcha", "403 Forbidden", "Bot detection", "Security check" ] content_lower = result.markdown.raw_markdown.lower() detected = False for indicator in detection_indicators: if indicator.lower() in content_lower: print(f"โš ๏ธ Possible detection: Found '{indicator}'") detected = True break if not detected: print("โœ… No obvious bot detection triggered!") # Show first 200 chars of content print(f"Content preview: {result.markdown.raw_markdown[:200]}...") return result.success and not detected except Exception as e: print(f"โŒ Error: {str(e)}") return False async def compare_adapters(url: str, site_name: str): """Compare regular and undetected adapters on the same URL""" print(f"\n{'#'*60}") print(f"# Testing: {site_name}") print(f"{'#'*60}") # Test with regular adapter regular_adapter = PlaywrightAdapter() regular_success = await test_with_adapter(url, "Regular", regular_adapter) # Small delay between tests await asyncio.sleep(2) # Test with undetected adapter undetected_adapter = UndetectedAdapter() undetected_success = await test_with_adapter(url, "Undetected", undetected_adapter) # Summary print(f"\n{'='*60}") print(f"Summary for {site_name}:") print(f"Regular Adapter: {'โœ… Passed' if regular_success else 'โŒ Blocked/Detected'}") print(f"Undetected Adapter: {'โœ… Passed' if undetected_success else 'โŒ Blocked/Detected'}") print(f"{'='*60}") return regular_success, undetected_success async def main(): """Run comparison tests on multiple sites""" print("๐Ÿค– Crawl4AI Browser Adapter Comparison") print("Testing regular vs undetected browser modes\n") results = {} # Test each site for site_name, url in TEST_SITES.items(): regular, undetected = await compare_adapters(url, site_name) results[site_name] = { "regular": regular, "undetected": undetected } # Delay between different sites await asyncio.sleep(3) # Final summary print(f"\n{'#'*60}") print("# FINAL RESULTS") print(f"{'#'*60}") print(f"{'Site':<30} {'Regular':<15} {'Undetected':<15}") print(f"{'-'*60}") for site, result in results.items(): regular_status = "โœ… Passed" if result["regular"] else "โŒ Blocked" undetected_status = "โœ… Passed" if result["undetected"] else "โŒ Blocked" print(f"{site:<30} {regular_status:<15} {undetected_status:<15}") # Calculate success rates regular_success = sum(1 for r in results.values() if r["regular"]) undetected_success = sum(1 for r in results.values() if r["undetected"]) total = len(results) print(f"\n{'='*60}") print(f"Success Rates:") print(f"Regular Adapter: {regular_success}/{total} ({regular_success/total*100:.1f}%)") print(f"Undetected Adapter: {undetected_success}/{total} ({undetected_success/total*100:.1f}%)") print(f"{'='*60}") if __name__ == "__main__": # Note: This example may take a while to run as it tests multiple sites # You can comment out sites in TEST_SITES to run faster tests asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/undetectability/undetected_vs_regular_comparison.py", "license": "Apache License 2.0", "lines": 150, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/undetected_simple_demo.py
""" Simple Undetected Browser Demo Demonstrates the basic usage of undetected browser mode """ import asyncio from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, UndetectedAdapter ) from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy async def crawl_with_regular_browser(url: str): """Crawl with regular browser""" print("\n[Regular Browser Mode]") browser_config = BrowserConfig( headless=False, verbose=True, ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun( url=url, config=CrawlerRunConfig( delay_before_return_html=2.0 ) ) print(f"Success: {result.success}") print(f"Status: {result.status_code}") print(f"Content length: {len(result.markdown.raw_markdown)}") # Check for bot detection keywords content = result.markdown.raw_markdown.lower() if any(word in content for word in ["cloudflare", "checking your browser", "please wait"]): print("โš ๏ธ Bot detection triggered!") else: print("โœ… Page loaded successfully") return result async def crawl_with_undetected_browser(url: str): """Crawl with undetected browser""" print("\n[Undetected Browser Mode]") browser_config = BrowserConfig( headless=False, verbose=True, ) # Create undetected adapter and strategy undetected_adapter = UndetectedAdapter() crawler_strategy = AsyncPlaywrightCrawlerStrategy( browser_config=browser_config, browser_adapter=undetected_adapter ) async with AsyncWebCrawler( crawler_strategy=crawler_strategy, config=browser_config ) as crawler: result = await crawler.arun( url=url, config=CrawlerRunConfig( delay_before_return_html=2.0 ) ) print(f"Success: {result.success}") print(f"Status: {result.status_code}") print(f"Content length: {len(result.markdown.raw_markdown)}") # Check for bot detection keywords content = result.markdown.raw_markdown.lower() if any(word in content for word in ["cloudflare", "checking your browser", "please wait"]): print("โš ๏ธ Bot detection triggered!") else: print("โœ… Page loaded successfully") return result async def main(): """Demo comparing regular vs undetected modes""" print("๐Ÿค– Crawl4AI Undetected Browser Demo") print("="*50) # Test URLs - you can change these test_urls = [ "https://www.example.com", # Simple site "https://httpbin.org/headers", # Shows request headers ] for url in test_urls: print(f"\n๐Ÿ“ Testing URL: {url}") # Test with regular browser regular_result = await crawl_with_regular_browser(url) # Small delay await asyncio.sleep(2) # Test with undetected browser undetected_result = await crawl_with_undetected_browser(url) # Compare results print(f"\n๐Ÿ“Š Comparison for {url}:") print(f"Regular browser content: {len(regular_result.markdown.raw_markdown)} chars") print(f"Undetected browser content: {len(undetected_result.markdown.raw_markdown)} chars") if url == "https://httpbin.org/headers": # Show headers for comparison print("\nHeaders seen by server:") print("Regular:", regular_result.markdown.raw_markdown[:500]) print("\nUndetected:", undetected_result.markdown.raw_markdown[:500]) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/undetected_simple_demo.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:tests/check_dependencies.py
#!/usr/bin/env python3 """ Dependency checker for Crawl4AI Analyzes imports in the codebase and shows which files use them """ import ast import os import sys from pathlib import Path from typing import Set, Dict, List, Tuple from collections import defaultdict import re import toml # Standard library modules to ignore STDLIB_MODULES = { 'abc', 'argparse', 'asyncio', 'base64', 'collections', 'concurrent', 'contextlib', 'copy', 'datetime', 'decimal', 'email', 'enum', 'functools', 'glob', 'hashlib', 'http', 'importlib', 'io', 'itertools', 'json', 'logging', 'math', 'mimetypes', 'multiprocessing', 'os', 'pathlib', 'pickle', 'platform', 'pprint', 'random', 're', 'shutil', 'signal', 'socket', 'sqlite3', 'string', 'subprocess', 'sys', 'tempfile', 'threading', 'time', 'traceback', 'typing', 'unittest', 'urllib', 'uuid', 'warnings', 'weakref', 'xml', 'zipfile', 'dataclasses', 'secrets', 'statistics', 'textwrap', 'queue', 'csv', 'gzip', 'tarfile', 'configparser', 'inspect', 'operator', 'struct', 'binascii', 'codecs', 'locale', 'gc', 'atexit', 'builtins', 'html', 'errno', 'fcntl', 'pwd', 'grp', 'resource', 'termios', 'tty', 'pty', 'select', 'selectors', 'ssl', 'zlib', 'bz2', 'lzma', 'types', 'copy', 'pydoc', 'profile', 'cProfile', 'timeit', 'trace', 'doctest', 'pdb', 'contextvars', 'dataclasses', 'graphlib', 'zoneinfo', 'tomllib', 'cgi', 'wsgiref', 'fileinput', 'linecache', 'tokenize', 'tabnanny', 'compileall', 'dis', 'pickletools', 'formatter', '__future__', 'array', 'ctypes', 'heapq', 'bisect', 'array', 'weakref', 'types', 'copy', 'pprint', 'repr', 'numbers', 'cmath', 'fractions', 'statistics', 'itertools', 'functools', 'operator', 'pathlib', 'fileinput', 'stat', 'filecmp', 'tempfile', 'glob', 'fnmatch', 'linecache', 'shutil', 'pickle', 'copyreg', 'shelve', 'marshal', 'dbm', 'sqlite3', 'zlib', 'gzip', 'bz2', 'lzma', 'zipfile', 'tarfile', 'configparser', 'netrc', 'xdrlib', 'plistlib', 'hashlib', 'hmac', 'secrets', 'os', 'io', 'time', 'argparse', 'getopt', 'logging', 'getpass', 'curses', 'platform', 'errno', 'ctypes', 'threading', 'multiprocessing', 'concurrent', 'subprocess', 'sched', 'queue', 'contextvars', 'asyncio', 'socket', 'ssl', 'email', 'json', 'mailcap', 'mailbox', 'mimetypes', 'base64', 'binhex', 'binascii', 'quopri', 'uu', 'html', 'xml', 'webbrowser', 'cgi', 'cgitb', 'wsgiref', 'urllib', 'http', 'ftplib', 'poplib', 'imaplib', 'nntplib', 'smtplib', 'smtpd', 'telnetlib', 'uuid', 'socketserver', 'xmlrpc', 'ipaddress', 'audioop', 'aifc', 'sunau', 'wave', 'chunk', 'colorsys', 'imghdr', 'sndhdr', 'ossaudiodev', 'gettext', 'locale', 'turtle', 'cmd', 'shlex', 'tkinter', 'typing', 'pydoc', 'doctest', 'unittest', 'test', '2to3', 'distutils', 'venv', 'ensurepip', 'zipapp', 'py_compile', 'compileall', 'dis', 'pickletools', 'pdb', 'timeit', 'trace', 'tracemalloc', 'warnings', 'faulthandler', 'pdb', 'dataclasses', 'cgi', 'cgitb', 'chunk', 'crypt', 'imghdr', 'mailcap', 'nis', 'nntplib', 'optparse', 'ossaudiodev', 'pipes', 'smtpd', 'sndhdr', 'spwd', 'sunau', 'telnetlib', 'uu', 'xdrlib', 'msilib', 'pstats', 'rlcompleter', 'tkinter', 'ast' } # Known package name mappings (import name -> package name) PACKAGE_MAPPINGS = { 'bs4': 'beautifulsoup4', 'PIL': 'pillow', 'cv2': 'opencv-python', 'sklearn': 'scikit-learn', 'yaml': 'PyYAML', 'OpenSSL': 'pyOpenSSL', 'sqlalchemy': 'SQLAlchemy', 'playwright': 'playwright', 'patchright': 'patchright', 'dotenv': 'python-dotenv', 'fake_useragent': 'fake-useragent', 'playwright_stealth': 'tf-playwright-stealth', 'sentence_transformers': 'sentence-transformers', 'rank_bm25': 'rank-bm25', 'snowballstemmer': 'snowballstemmer', 'pypdf': 'pypdf', 'pdf2image': 'pdf2image', } class ImportVisitor(ast.NodeVisitor): """AST visitor to extract imports from Python files""" def __init__(self): self.imports = {} # Changed to dict to store line numbers self.from_imports = {} def visit_Import(self, node): for alias in node.names: module_name = alias.name.split('.')[0] if module_name not in self.imports: self.imports[module_name] = [] self.imports[module_name].append(node.lineno) def visit_ImportFrom(self, node): if node.module and node.level == 0: # absolute imports only module_name = node.module.split('.')[0] if module_name not in self.from_imports: self.from_imports[module_name] = [] self.from_imports[module_name].append(node.lineno) def extract_imports_from_file(filepath: Path) -> Dict[str, List[int]]: """Extract all imports from a Python file with line numbers""" all_imports = {} try: with open(filepath, 'r', encoding='utf-8') as f: content = f.read() tree = ast.parse(content) visitor = ImportVisitor() visitor.visit(tree) # Merge imports and from_imports for module, lines in visitor.imports.items(): if module not in all_imports: all_imports[module] = [] all_imports[module].extend(lines) for module, lines in visitor.from_imports.items(): if module not in all_imports: all_imports[module] = [] all_imports[module].extend(lines) except Exception as e: # Silently skip files that can't be parsed pass return all_imports def get_codebase_imports_with_files(root_dir: Path) -> Dict[str, List[Tuple[str, List[int]]]]: """Get all imports from the crawl4ai library and docs folders with file locations and line numbers""" import_to_files = defaultdict(list) # Only scan crawl4ai library folder and docs folder target_dirs = [ root_dir / 'crawl4ai', root_dir / 'docs' ] for target_dir in target_dirs: if not target_dir.exists(): continue for py_file in target_dir.rglob('*.py'): # Skip __pycache__ directories if '__pycache__' in py_file.parts: continue # Skip setup.py and similar files if py_file.name in ['setup.py', 'setup.cfg', 'conf.py']: continue imports = extract_imports_from_file(py_file) # Map each import to the file and line numbers for imp, line_numbers in imports.items(): relative_path = py_file.relative_to(root_dir) import_to_files[imp].append((str(relative_path), sorted(line_numbers))) return dict(import_to_files) def get_declared_dependencies() -> Set[str]: """Get declared dependencies from pyproject.toml and requirements.txt""" declared = set() # Read from pyproject.toml if Path('pyproject.toml').exists(): with open('pyproject.toml', 'r') as f: data = toml.load(f) # Get main dependencies deps = data.get('project', {}).get('dependencies', []) for dep in deps: # Parse dependency string (e.g., "numpy>=1.26.0,<3") match = re.match(r'^([a-zA-Z0-9_-]+)', dep) if match: pkg_name = match.group(1).lower() declared.add(pkg_name) # Get optional dependencies optional = data.get('project', {}).get('optional-dependencies', {}) for group, deps in optional.items(): for dep in deps: match = re.match(r'^([a-zA-Z0-9_-]+)', dep) if match: pkg_name = match.group(1).lower() declared.add(pkg_name) # Also check requirements.txt as backup if Path('requirements.txt').exists(): with open('requirements.txt', 'r') as f: for line in f: line = line.strip() if line and not line.startswith('#'): match = re.match(r'^([a-zA-Z0-9_-]+)', line) if match: pkg_name = match.group(1).lower() declared.add(pkg_name) return declared def normalize_package_name(name: str) -> str: """Normalize package name for comparison""" # Handle known mappings first if name in PACKAGE_MAPPINGS: return PACKAGE_MAPPINGS[name].lower() # Basic normalization return name.lower().replace('_', '-') def check_missing_dependencies(): """Main function to check for missing dependencies""" print("๐Ÿ” Analyzing crawl4ai library and docs folders...\n") # Get all imports with their file locations root_dir = Path('.') import_to_files = get_codebase_imports_with_files(root_dir) # Get declared dependencies declared_deps = get_declared_dependencies() # Normalize declared dependencies normalized_declared = {normalize_package_name(dep) for dep in declared_deps} # Categorize imports external_imports = {} local_imports = {} # Known local packages local_packages = {'crawl4ai'} for imp, file_info in import_to_files.items(): # Skip standard library if imp in STDLIB_MODULES: continue # Check if it's a local import if any(imp.startswith(local) for local in local_packages): local_imports[imp] = file_info else: external_imports[imp] = file_info # Check which external imports are not declared not_declared = {} declared_imports = {} for imp, file_info in external_imports.items(): normalized_imp = normalize_package_name(imp) # Check if import is covered by declared dependencies found = False for declared in normalized_declared: if normalized_imp == declared or normalized_imp.startswith(declared + '.') or declared.startswith(normalized_imp): found = True break if found: declared_imports[imp] = file_info else: not_declared[imp] = file_info # Print results print(f"๐Ÿ“Š Summary:") print(f" - Total unique imports: {len(import_to_files)}") print(f" - External imports: {len(external_imports)}") print(f" - Declared dependencies: {len(declared_deps)}") print(f" - External imports NOT in dependencies: {len(not_declared)}\n") if not_declared: print("โŒ External imports NOT declared in pyproject.toml or requirements.txt:\n") # Sort by import name for imp in sorted(not_declared.keys()): file_info = not_declared[imp] print(f" ๐Ÿ“ฆ {imp}") if imp in PACKAGE_MAPPINGS: print(f" โ†’ Package name: {PACKAGE_MAPPINGS[imp]}") # Show up to 3 files that use this import for i, (file_path, line_numbers) in enumerate(file_info[:3]): # Format line numbers for clickable output if len(line_numbers) == 1: print(f" - {file_path}:{line_numbers[0]}") else: # Show first few line numbers line_str = ','.join(str(ln) for ln in line_numbers[:3]) if len(line_numbers) > 3: line_str += f"... ({len(line_numbers)} imports)" print(f" - {file_path}: lines {line_str}") if len(file_info) > 3: print(f" ... and {len(file_info) - 3} more files") print() # Check for potentially unused dependencies print("\n๐Ÿ”Ž Checking declared dependencies usage...\n") # Get all used external packages used_packages = set() for imp in external_imports.keys(): normalized = normalize_package_name(imp) used_packages.add(normalized) # Find unused unused = [] for dep in declared_deps: normalized_dep = normalize_package_name(dep) # Check if any import uses this dependency found_usage = False for used in used_packages: if used == normalized_dep or used.startswith(normalized_dep) or normalized_dep.startswith(used): found_usage = True break if not found_usage: # Some packages are commonly unused directly indirect_deps = {'wheel', 'setuptools', 'pip', 'colorama', 'certifi', 'packaging', 'urllib3'} if normalized_dep not in indirect_deps: unused.append(dep) if unused: print("โš ๏ธ Declared dependencies with NO imports found:") for dep in sorted(unused): print(f" - {dep}") print("\n Note: These might be used indirectly or by other dependencies") else: print("โœ… All declared dependencies have corresponding imports") print("\n" + "="*60) print("๐Ÿ’ก How to use this report:") print(" 1. Check each โŒ import to see if it's legitimate") print(" 2. If legitimate, add the package to pyproject.toml") print(" 3. If it's an internal module or typo, fix the import") print(" 4. Review unused dependencies - remove if truly not needed") print("="*60) if __name__ == '__main__': check_missing_dependencies()
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/check_dependencies.py", "license": "Apache License 2.0", "lines": 282, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_arun_many.py
""" Test example for multiple crawler configs feature """ import asyncio import sys from pathlib import Path # Add parent directory to path for imports sys.path.insert(0, str(Path(__file__).parent.parent)) from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode from crawl4ai.processors.pdf import PDFContentScrapingStrategy async def test_run_many(): default_config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, # scraping_strategy=PDFContentScrapingStrategy() ) test_urls = [ # "https://blog.python.org/", # Blog URL "https://www.python.org/", # Generic HTTPS page "https://www.kidocode.com/", # Generic HTTPS page "https://www.example.com/", # Generic HTTPS page # "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", ] async with AsyncWebCrawler() as crawler: # Single config - traditional usage still works print("Test 1: Single config (backwards compatible)") result = await crawler.arun_many( urls=test_urls[:2], config=default_config ) print(f"Crawled {len(result)} URLs with single config\n") for item in result: print(f" {item.url} -> {item.status_code}") if __name__ == "__main__": asyncio.run(test_run_many())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_arun_many.py", "license": "Apache License 2.0", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_config_matching_only.py
""" Test only the config matching logic without running crawler """ import sys from pathlib import Path # Add parent directory to path for imports sys.path.insert(0, str(Path(__file__).parent.parent)) from crawl4ai.async_configs import CrawlerRunConfig, MatchMode def test_all_matching_scenarios(): print("Testing CrawlerRunConfig.is_match() method") print("=" * 50) # Test 1: Single string pattern print("\n1. Single string pattern (glob style)") config = CrawlerRunConfig( url_matcher="*.pdf", # For example we can set this => scraping_strategy=PDFContentScrapingStrategy() ) test_urls = [ ("https://example.com/file.pdf", True), ("https://example.com/doc.PDF", False), # Case sensitive ("https://example.com/file.txt", False), ("file.pdf", True), ] for url, expected in test_urls: result = config.is_match(url) status = "โœ“" if result == expected else "โœ—" print(f" {status} {url} -> {result}") # Test 2: List of patterns with OR print("\n2. List of patterns with OR (default)") config = CrawlerRunConfig( url_matcher=["*/article/*", "*/blog/*", "*.html"], match_mode=MatchMode.OR ) test_urls = [ ("https://example.com/article/news", True), ("https://example.com/blog/post", True), ("https://example.com/page.html", True), ("https://example.com/page.php", False), ] for url, expected in test_urls: result = config.is_match(url) status = "โœ“" if result == expected else "โœ—" print(f" {status} {url} -> {result}") # Test 3: Custom function print("\n3. Custom function matcher") config = CrawlerRunConfig( url_matcher=lambda url: 'api' in url and (url.endswith('.json') or url.endswith('.xml')) ) test_urls = [ ("https://api.example.com/data.json", True), ("https://api.example.com/data.xml", True), ("https://api.example.com/data.html", False), ("https://example.com/data.json", False), # No 'api' ] for url, expected in test_urls: result = config.is_match(url) status = "โœ“" if result == expected else "โœ—" print(f" {status} {url} -> {result}") # Test 4: Mixed list with AND print("\n4. Mixed patterns and functions with AND") config = CrawlerRunConfig( url_matcher=[ "https://*", # Must be HTTPS lambda url: '.com' in url, # Must have .com lambda url: len(url) < 50 # Must be short ], match_mode=MatchMode.AND ) test_urls = [ ("https://example.com/page", True), ("http://example.com/page", False), # Not HTTPS ("https://example.org/page", False), # No .com ("https://example.com/" + "x" * 50, False), # Too long ] for url, expected in test_urls: result = config.is_match(url) status = "โœ“" if result == expected else "โœ—" print(f" {status} {url} -> {result}") # Test 5: Complex real-world scenario print("\n5. Complex pattern combinations") config = CrawlerRunConfig( url_matcher=[ "*/api/v[0-9]/*", # API versioned endpoints lambda url: 'graphql' in url, # GraphQL endpoints "*.json" # JSON files ], match_mode=MatchMode.OR ) test_urls = [ ("https://example.com/api/v1/users", True), ("https://example.com/api/v2/posts", True), ("https://example.com/graphql", True), ("https://example.com/data.json", True), ("https://example.com/api/users", False), # No version ] for url, expected in test_urls: result = config.is_match(url) status = "โœ“" if result == expected else "โœ—" print(f" {status} {url} -> {result}") # Test 6: Edge cases print("\n6. Edge cases") # No matcher config = CrawlerRunConfig() result = config.is_match("https://example.com") print(f" {'โœ“' if not result else 'โœ—'} No matcher -> {result}") # Empty list config = CrawlerRunConfig(url_matcher=[]) result = config.is_match("https://example.com") print(f" {'โœ“' if not result else 'โœ—'} Empty list -> {result}") # None in list (should be skipped) config = CrawlerRunConfig(url_matcher=["*.pdf", None, "*.doc"]) result = config.is_match("test.pdf") print(f" {'โœ“' if result else 'โœ—'} List with None -> {result}") print("\n" + "=" * 50) print("All matching tests completed!") if __name__ == "__main__": test_all_matching_scenarios()
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_config_matching_only.py", "license": "Apache License 2.0", "lines": 117, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_config_selection.py
""" Test config selection logic in dispatchers """ import asyncio import sys from pathlib import Path from unittest.mock import AsyncMock, MagicMock # Add parent directory to path for imports sys.path.insert(0, str(Path(__file__).parent.parent)) from crawl4ai.async_configs import CrawlerRunConfig, MatchMode from crawl4ai.async_dispatcher import BaseDispatcher, MemoryAdaptiveDispatcher class TestDispatcher(BaseDispatcher): """Simple test dispatcher to verify config selection""" async def crawl_url(self, url, config, task_id, **kwargs): # Just return which config was selected selected = self.select_config(url, config) return {"url": url, "config_id": id(selected)} async def run_urls(self, urls, crawler, config): results = [] for url in urls: result = await self.crawl_url(url, config, "test") results.append(result) return results async def test_dispatcher_config_selection(): print("Testing dispatcher config selection") print("=" * 50) # Create test configs with different matchers pdf_config = CrawlerRunConfig(url_matcher="*.pdf") api_config = CrawlerRunConfig(url_matcher=lambda url: 'api' in url) default_config = CrawlerRunConfig() # No matcher configs = [pdf_config, api_config, default_config] # Create test dispatcher dispatcher = TestDispatcher() # Test single config print("\nTest 1: Single config") result = await dispatcher.crawl_url("https://example.com/file.pdf", pdf_config, "test1") assert result["config_id"] == id(pdf_config) print("โœ“ Single config works") # Test config list selection print("\nTest 2: Config list selection") test_cases = [ ("https://example.com/file.pdf", id(pdf_config)), ("https://api.example.com/data", id(api_config)), ("https://example.com/page", id(configs[0])), # No match, uses first ] for url, expected_id in test_cases: result = await dispatcher.crawl_url(url, configs, "test") assert result["config_id"] == expected_id, f"URL {url} got wrong config" print(f"โœ“ {url} -> correct config selected") # Test with MemoryAdaptiveDispatcher print("\nTest 3: MemoryAdaptiveDispatcher config selection") mem_dispatcher = MemoryAdaptiveDispatcher() # Test select_config method directly selected = mem_dispatcher.select_config("https://example.com/doc.pdf", configs) assert selected == pdf_config print("โœ“ MemoryAdaptiveDispatcher.select_config works") # Test empty config list print("\nTest 4: Edge cases") selected = mem_dispatcher.select_config("https://example.com", []) assert isinstance(selected, CrawlerRunConfig) # Should return default print("โœ“ Empty config list returns default config") # Test None config selected = mem_dispatcher.select_config("https://example.com", None) assert isinstance(selected, CrawlerRunConfig) # Should return default print("โœ“ None config returns default config") print("\n" + "=" * 50) print("All dispatcher tests passed! โœ“") if __name__ == "__main__": asyncio.run(test_dispatcher_config_selection())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_config_selection.py", "license": "Apache License 2.0", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_docker_api_with_llm_provider.py
#!/usr/bin/env python3 """Test script to verify Docker API with LLM provider configuration.""" import requests import json import time BASE_URL = "http://localhost:11235" def test_health(): """Test health endpoint.""" print("1. Testing health endpoint...") response = requests.get(f"{BASE_URL}/health") print(f" Status: {response.status_code}") print(f" Response: {response.json()}") print() def test_schema(): """Test schema endpoint to see configuration.""" print("2. Testing schema endpoint...") response = requests.get(f"{BASE_URL}/schema") print(f" Status: {response.status_code}") # Print only browser config to keep output concise print(f" Browser config keys: {list(response.json().get('browser', {}).keys())[:5]}...") print() def test_markdown_with_llm_filter(): """Test markdown endpoint with LLM filter (should use configured provider).""" print("3. Testing markdown endpoint with LLM filter...") print(" This should use the Groq provider from LLM_PROVIDER env var") # Note: This will fail with dummy API keys, but we can see if it tries to use Groq payload = { "url": "https://httpbin.org/html", "f": "llm", "q": "Extract the main content" } response = requests.post(f"{BASE_URL}/md", json=payload) print(f" Status: {response.status_code}") if response.status_code != 200: print(f" Error: {response.text[:200]}...") else: print(f" Success! Markdown length: {len(response.json().get('markdown', ''))} chars") print() def test_markdown_with_provider_override(): """Test markdown endpoint with provider override in request.""" print("4. Testing markdown endpoint with provider override...") print(" This should use OpenAI provider from request parameter") payload = { "url": "https://httpbin.org/html", "f": "llm", "q": "Extract the main content", "provider": "openai/gpt-4" # Override to use OpenAI } response = requests.post(f"{BASE_URL}/md", json=payload) print(f" Status: {response.status_code}") if response.status_code != 200: print(f" Error: {response.text[:200]}...") else: print(f" Success! Markdown length: {len(response.json().get('markdown', ''))} chars") print() def test_simple_crawl(): """Test simple crawl without LLM.""" print("5. Testing simple crawl (no LLM required)...") payload = { "urls": ["https://httpbin.org/html"], "browser_config": { "type": "BrowserConfig", "params": {"headless": True} }, "crawler_config": { "type": "CrawlerRunConfig", "params": {"cache_mode": "bypass"} } } response = requests.post(f"{BASE_URL}/crawl", json=payload) print(f" Status: {response.status_code}") if response.status_code == 200: result = response.json() print(f" Success: {result.get('success')}") print(f" Results count: {len(result.get('results', []))}") if result.get('results'): print(f" First result success: {result['results'][0].get('success')}") else: print(f" Error: {response.text[:200]}...") print() def test_playground(): """Test if playground is accessible.""" print("6. Testing playground interface...") response = requests.get(f"{BASE_URL}/playground") print(f" Status: {response.status_code}") print(f" Content-Type: {response.headers.get('content-type')}") print() if __name__ == "__main__": print("=== Crawl4AI Docker API Tests ===\n") print(f"Testing API at {BASE_URL}\n") # Wait a bit for server to be fully ready time.sleep(2) test_health() test_schema() test_simple_crawl() test_playground() print("\nTesting LLM functionality (these may fail with dummy API keys):\n") test_markdown_with_llm_filter() test_markdown_with_provider_override() print("\nTests completed!")
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_docker_api_with_llm_provider.py", "license": "Apache License 2.0", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_memory_macos.py
#!/usr/bin/env python3 """Test script to verify macOS memory calculation accuracy.""" import psutil import platform import time from crawl4ai.utils import get_true_memory_usage_percent, get_memory_stats, get_true_available_memory_gb def test_memory_calculation(): """Test and compare memory calculations.""" print(f"Platform: {platform.system()}") print(f"Python version: {platform.python_version()}") print("-" * 60) # Get psutil's view vm = psutil.virtual_memory() psutil_percent = vm.percent psutil_available_gb = vm.available / (1024**3) total_gb = vm.total / (1024**3) # Get our corrected view true_percent = get_true_memory_usage_percent() true_available_gb = get_true_available_memory_gb() true_percent_calc, available_calc, total_calc = get_memory_stats() print("Memory Statistics Comparison:") print(f"Total Memory: {total_gb:.2f} GB") print() print("PSUtil (Standard) Calculation:") print(f" - Memory Used: {psutil_percent:.1f}%") print(f" - Available: {psutil_available_gb:.2f} GB") print() print("Platform-Aware Calculation:") print(f" - Memory Used: {true_percent:.1f}%") print(f" - Available: {true_available_gb:.2f} GB") print(f" - Difference: {true_available_gb - psutil_available_gb:.2f} GB of reclaimable memory") print() # Show the impact on dispatcher behavior print("Impact on MemoryAdaptiveDispatcher:") thresholds = { "Normal": 90.0, "Critical": 95.0, "Recovery": 85.0 } for name, threshold in thresholds.items(): psutil_triggered = psutil_percent >= threshold true_triggered = true_percent >= threshold print(f" - {name} Threshold ({threshold}%):") print(f" PSUtil: {'TRIGGERED' if psutil_triggered else 'OK'}") print(f" Platform-Aware: {'TRIGGERED' if true_triggered else 'OK'}") if psutil_triggered != true_triggered: print(f" โ†’ Difference: Platform-aware prevents false {'pressure' if psutil_triggered else 'recovery'}") print() # Monitor for a few seconds print("Monitoring memory for 10 seconds...") for i in range(10): vm = psutil.virtual_memory() true_pct = get_true_memory_usage_percent() print(f" {i+1}s - PSUtil: {vm.percent:.1f}% | Platform-Aware: {true_pct:.1f}%", end="\r") time.sleep(1) print("\n") if __name__ == "__main__": test_memory_calculation()
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_memory_macos.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_multi_config.py
""" Test example for multiple crawler configs feature """ import asyncio import sys from pathlib import Path # Add parent directory to path for imports sys.path.insert(0, str(Path(__file__).parent.parent)) from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, MatchMode, CacheMode async def test_multi_config(): # Create different configs for different URL patterns # Config for PDF files pdf_config = CrawlerRunConfig( url_matcher="*.pdf", ) # Config for articles (using multiple patterns with OR logic) article_config = CrawlerRunConfig( url_matcher=["*/news/*", "*blog*", "*/article/*"], match_mode=MatchMode.OR, screenshot=True, ) # Config using custom matcher function api_config = CrawlerRunConfig( url_matcher=lambda url: 'api' in url or 'json' in url, ) # Config combining patterns and functions with AND logic secure_docs_config = CrawlerRunConfig( url_matcher=[ "*.doc*", # Matches .doc, .docx lambda url: url.startswith('https://') # Must be HTTPS ], match_mode=MatchMode.AND, ) # Default config (no url_matcher means it won't match anything unless it's the fallback) default_config = CrawlerRunConfig( # cache_mode=CacheMode.BYPASS, ) # List of configs - order matters! First match wins configs = [ pdf_config, article_config, api_config, secure_docs_config, default_config # Fallback ] # Test URLs - using real URLs that exist test_urls = [ "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", # Real PDF "https://www.bbc.com/news/articles/c5y3e3glnldo", # News article "https://blog.python.org/", # Blog URL "https://api.github.com/users/github", # GitHub API (returns JSON) "https://httpbin.org/json", # API endpoint that returns JSON "https://www.python.org/", # Generic HTTPS page "http://info.cern.ch/", # HTTP (not HTTPS) page "https://example.com/", # โ†’ Default config ] # Test the matching logic print("Config matching test:") print("-" * 50) for url in test_urls: for i, config in enumerate(configs): if config.is_match(url): print(f"{url} -> Config {i} matches") break else: print(f"{url} -> No match, will use fallback (first config)") print("\n" + "=" * 50 + "\n") # Now test with actual crawler async with AsyncWebCrawler() as crawler: # Single config - traditional usage still works print("Test 1: Single config (backwards compatible)") result = await crawler.arun_many( urls=["https://www.python.org/"], config=default_config ) print(f"Crawled {len(result)} URLs with single config\n") # Multiple configs - new feature print("Test 2: Multiple configs") # Just test with 2 URLs to avoid timeout results = await crawler.arun_many( urls=test_urls[:2], # Just test first 2 URLs config=configs # Pass list of configs ) print(f"Crawled {len(results)} URLs with multiple configs") # Using custom matcher inline print("\nTest 3: Inline custom matcher") custom_config = CrawlerRunConfig( url_matcher=lambda url: len(url) > 50 and 'python' in url.lower(), verbose=False ) results = await crawler.arun_many( urls=[ "https://docs.python.org/3/library/asyncio.html", # Long URL with 'python' "https://python.org/", # Short URL with 'python' - won't match "https://www.google.com/" # No 'python' - won't match ], config=[custom_config, default_config] ) print(f"Crawled {len(results)} URLs with custom matcher") if __name__ == "__main__": asyncio.run(test_multi_config())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_multi_config.py", "license": "Apache License 2.0", "lines": 101, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:crawl4ai/adaptive_crawler copy.py
""" Adaptive Web Crawler for Crawl4AI This module implements adaptive information foraging for efficient web crawling. It determines when sufficient information has been gathered to answer a query, avoiding unnecessary crawls while ensuring comprehensive coverage. """ from abc import ABC, abstractmethod from typing import Dict, List, Optional, Set, Tuple, Any, Union from dataclasses import dataclass, field import asyncio import pickle import os import json import math from collections import defaultdict, Counter import re from pathlib import Path from crawl4ai.async_webcrawler import AsyncWebCrawler from crawl4ai.async_configs import CrawlerRunConfig, LinkPreviewConfig from crawl4ai.models import Link, CrawlResult @dataclass class CrawlState: """Tracks the current state of adaptive crawling""" crawled_urls: Set[str] = field(default_factory=set) knowledge_base: List[CrawlResult] = field(default_factory=list) pending_links: List[Link] = field(default_factory=list) query: str = "" metrics: Dict[str, float] = field(default_factory=dict) # Statistical tracking term_frequencies: Dict[str, int] = field(default_factory=lambda: defaultdict(int)) document_frequencies: Dict[str, int] = field(default_factory=lambda: defaultdict(int)) documents_with_terms: Dict[str, Set[int]] = field(default_factory=lambda: defaultdict(set)) total_documents: int = 0 # History tracking for saturation new_terms_history: List[int] = field(default_factory=list) crawl_order: List[str] = field(default_factory=list) # Embedding-specific tracking (only if strategy is embedding) kb_embeddings: Optional[Any] = None # Will be numpy array query_embeddings: Optional[Any] = None # Will be numpy array expanded_queries: List[str] = field(default_factory=list) coverage_shape: Optional[Any] = None # Alpha shape semantic_gaps: List[Tuple[List[float], float]] = field(default_factory=list) # Serializable embedding_model: str = "" def save(self, path: Union[str, Path]): """Save state to disk for persistence""" path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) # Convert CrawlResult objects to dicts for serialization state_dict = { 'crawled_urls': list(self.crawled_urls), 'knowledge_base': [self._crawl_result_to_dict(cr) for cr in self.knowledge_base], 'pending_links': [link.model_dump() for link in self.pending_links], 'query': self.query, 'metrics': self.metrics, 'term_frequencies': dict(self.term_frequencies), 'document_frequencies': dict(self.document_frequencies), 'documents_with_terms': {k: list(v) for k, v in self.documents_with_terms.items()}, 'total_documents': self.total_documents, 'new_terms_history': self.new_terms_history, 'crawl_order': self.crawl_order, # Embedding-specific fields (convert numpy arrays to lists for JSON) 'kb_embeddings': self.kb_embeddings.tolist() if self.kb_embeddings is not None else None, 'query_embeddings': self.query_embeddings.tolist() if self.query_embeddings is not None else None, 'expanded_queries': self.expanded_queries, 'semantic_gaps': self.semantic_gaps, 'embedding_model': self.embedding_model } with open(path, 'w') as f: json.dump(state_dict, f, indent=2) @classmethod def load(cls, path: Union[str, Path]) -> 'CrawlState': """Load state from disk""" path = Path(path) with open(path, 'r') as f: state_dict = json.load(f) state = cls() state.crawled_urls = set(state_dict['crawled_urls']) state.knowledge_base = [cls._dict_to_crawl_result(d) for d in state_dict['knowledge_base']] state.pending_links = [Link(**link_dict) for link_dict in state_dict['pending_links']] state.query = state_dict['query'] state.metrics = state_dict['metrics'] state.term_frequencies = defaultdict(int, state_dict['term_frequencies']) state.document_frequencies = defaultdict(int, state_dict['document_frequencies']) state.documents_with_terms = defaultdict(set, {k: set(v) for k, v in state_dict['documents_with_terms'].items()}) state.total_documents = state_dict['total_documents'] state.new_terms_history = state_dict['new_terms_history'] state.crawl_order = state_dict['crawl_order'] # Load embedding-specific fields (convert lists back to numpy arrays) import numpy as np state.kb_embeddings = np.array(state_dict['kb_embeddings']) if state_dict.get('kb_embeddings') is not None else None state.query_embeddings = np.array(state_dict['query_embeddings']) if state_dict.get('query_embeddings') is not None else None state.expanded_queries = state_dict.get('expanded_queries', []) state.semantic_gaps = state_dict.get('semantic_gaps', []) state.embedding_model = state_dict.get('embedding_model', '') return state @staticmethod def _crawl_result_to_dict(cr: CrawlResult) -> Dict: """Convert CrawlResult to serializable dict""" # Extract markdown content safely markdown_content = "" if hasattr(cr, 'markdown') and cr.markdown: if hasattr(cr.markdown, 'raw_markdown'): markdown_content = cr.markdown.raw_markdown else: markdown_content = str(cr.markdown) return { 'url': cr.url, 'content': markdown_content, 'links': cr.links if hasattr(cr, 'links') else {}, 'metadata': cr.metadata if hasattr(cr, 'metadata') else {} } @staticmethod def _dict_to_crawl_result(d: Dict): """Convert dict back to CrawlResult""" # Create a mock object that has the minimal interface we need class MockMarkdown: def __init__(self, content): self.raw_markdown = content class MockCrawlResult: def __init__(self, url, content, links, metadata): self.url = url self.markdown = MockMarkdown(content) self.links = links self.metadata = metadata return MockCrawlResult( url=d['url'], content=d.get('content', ''), links=d.get('links', {}), metadata=d.get('metadata', {}) ) @dataclass class AdaptiveConfig: """Configuration for adaptive crawling""" confidence_threshold: float = 0.7 max_depth: int = 5 max_pages: int = 20 top_k_links: int = 3 min_gain_threshold: float = 0.1 strategy: str = "statistical" # statistical, embedding, llm # Advanced parameters saturation_threshold: float = 0.8 consistency_threshold: float = 0.7 coverage_weight: float = 0.4 consistency_weight: float = 0.3 saturation_weight: float = 0.3 # Link scoring parameters relevance_weight: float = 0.5 novelty_weight: float = 0.3 authority_weight: float = 0.2 # Persistence save_state: bool = False state_path: Optional[str] = None # Embedding strategy parameters embedding_model: str = "sentence-transformers/all-MiniLM-L6-v2" embedding_llm_config: Optional[Dict] = None # Separate config for embeddings n_query_variations: int = 10 coverage_threshold: float = 0.85 alpha_shape_alpha: float = 0.5 # Embedding confidence calculation parameters embedding_coverage_radius: float = 0.2 # Distance threshold for "covered" query points # Example: With radius=0.2, a query point is considered covered if ANY document # is within cosine distance 0.2 (very similar). Smaller = stricter coverage requirement embedding_k_exp: float = 3.0 # Exponential decay factor for distance-to-score mapping # Example: score = exp(-k_exp * distance). With k_exp=1, distance 0.2 โ†’ score 0.82, # distance 0.5 โ†’ score 0.61. Higher k_exp = steeper decay = more emphasis on very close matches embedding_nearest_weight: float = 0.7 # Weight for nearest neighbor in hybrid scoring embedding_top_k_weight: float = 0.3 # Weight for top-k average in hybrid scoring # Example: If nearest doc has score 0.9 and top-3 avg is 0.6, final = 0.7*0.9 + 0.3*0.6 = 0.81 # Higher nearest_weight = more focus on best match vs neighborhood density # Embedding link selection parameters embedding_overlap_threshold: float = 0.85 # Similarity threshold for penalizing redundant links # Example: Links with >0.85 similarity to existing KB get penalized to avoid redundancy # Lower = more aggressive deduplication, Higher = allow more similar content # Embedding stopping criteria parameters embedding_min_relative_improvement: float = 0.1 # Minimum relative improvement to continue # Example: If confidence is 0.6, need improvement > 0.06 per batch to continue crawling # Lower = more patient crawling, Higher = stop earlier when progress slows embedding_validation_min_score: float = 0.4 # Minimum validation score to trust convergence # Example: Even if learning converged, keep crawling if validation score < 0.4 # This prevents premature stopping when we haven't truly covered the query space # Quality confidence mapping parameters (for display to user) embedding_quality_min_confidence: float = 0.7 # Minimum confidence for validated systems embedding_quality_max_confidence: float = 0.95 # Maximum realistic confidence embedding_quality_scale_factor: float = 0.833 # Scaling factor for confidence mapping # Example: Validated system with learning_score=0.5 โ†’ confidence = 0.7 + (0.5-0.4)*0.833 = 0.78 # These control how internal scores map to user-friendly confidence percentages def validate(self): """Validate configuration parameters""" assert 0 <= self.confidence_threshold <= 1, "confidence_threshold must be between 0 and 1" assert self.max_depth > 0, "max_depth must be positive" assert self.max_pages > 0, "max_pages must be positive" assert self.top_k_links > 0, "top_k_links must be positive" assert 0 <= self.min_gain_threshold <= 1, "min_gain_threshold must be between 0 and 1" # Check weights sum to 1 weight_sum = self.coverage_weight + self.consistency_weight + self.saturation_weight assert abs(weight_sum - 1.0) < 0.001, f"Coverage weights must sum to 1, got {weight_sum}" weight_sum = self.relevance_weight + self.novelty_weight + self.authority_weight assert abs(weight_sum - 1.0) < 0.001, f"Link scoring weights must sum to 1, got {weight_sum}" # Validate embedding parameters assert 0 < self.embedding_coverage_radius < 1, "embedding_coverage_radius must be between 0 and 1" assert self.embedding_k_exp > 0, "embedding_k_exp must be positive" assert 0 <= self.embedding_nearest_weight <= 1, "embedding_nearest_weight must be between 0 and 1" assert 0 <= self.embedding_top_k_weight <= 1, "embedding_top_k_weight must be between 0 and 1" assert abs(self.embedding_nearest_weight + self.embedding_top_k_weight - 1.0) < 0.001, "Embedding weights must sum to 1" assert 0 <= self.embedding_overlap_threshold <= 1, "embedding_overlap_threshold must be between 0 and 1" assert 0 < self.embedding_min_relative_improvement < 1, "embedding_min_relative_improvement must be between 0 and 1" assert 0 <= self.embedding_validation_min_score <= 1, "embedding_validation_min_score must be between 0 and 1" assert 0 <= self.embedding_quality_min_confidence <= 1, "embedding_quality_min_confidence must be between 0 and 1" assert 0 <= self.embedding_quality_max_confidence <= 1, "embedding_quality_max_confidence must be between 0 and 1" assert self.embedding_quality_scale_factor > 0, "embedding_quality_scale_factor must be positive" class CrawlStrategy(ABC): """Abstract base class for crawling strategies""" @abstractmethod async def calculate_confidence(self, state: CrawlState) -> float: """Calculate overall confidence that we have sufficient information""" pass @abstractmethod async def rank_links(self, state: CrawlState, config: AdaptiveConfig) -> List[Tuple[Link, float]]: """Rank pending links by expected information gain""" pass @abstractmethod async def should_stop(self, state: CrawlState, config: AdaptiveConfig) -> bool: """Determine if crawling should stop""" pass @abstractmethod async def update_state(self, state: CrawlState, new_results: List[CrawlResult]) -> None: """Update state with new crawl results""" pass class StatisticalStrategy(CrawlStrategy): """Pure statistical approach - no LLM, no embeddings""" def __init__(self): self.idf_cache = {} self.bm25_k1 = 1.2 # BM25 parameter self.bm25_b = 0.75 # BM25 parameter async def calculate_confidence(self, state: CrawlState) -> float: """Calculate confidence using coverage, consistency, and saturation""" if not state.knowledge_base: return 0.0 coverage = self._calculate_coverage(state) consistency = self._calculate_consistency(state) saturation = self._calculate_saturation(state) # Store individual metrics state.metrics['coverage'] = coverage state.metrics['consistency'] = consistency state.metrics['saturation'] = saturation # Weighted combination (weights from config not accessible here, using defaults) confidence = 0.4 * coverage + 0.3 * consistency + 0.3 * saturation return confidence def _calculate_coverage(self, state: CrawlState) -> float: """Coverage scoring - measures query term presence across knowledge base Returns a score between 0 and 1, where: - 0 means no query terms found - 1 means excellent coverage of all query terms """ if not state.query or state.total_documents == 0: return 0.0 query_terms = self._tokenize(state.query.lower()) if not query_terms: return 0.0 term_scores = [] max_tf = max(state.term_frequencies.values()) if state.term_frequencies else 1 for term in query_terms: tf = state.term_frequencies.get(term, 0) df = state.document_frequencies.get(term, 0) if df > 0: # Document coverage: what fraction of docs contain this term doc_coverage = df / state.total_documents # Frequency signal: normalized log frequency freq_signal = math.log(1 + tf) / math.log(1 + max_tf) if max_tf > 0 else 0 # Combined score: document coverage with frequency boost term_score = doc_coverage * (1 + 0.5 * freq_signal) term_scores.append(term_score) else: term_scores.append(0.0) # Average across all query terms coverage = sum(term_scores) / len(term_scores) # Apply square root curve to make score more intuitive # This helps differentiate between partial and good coverage return min(1.0, math.sqrt(coverage)) def _calculate_consistency(self, state: CrawlState) -> float: """Information overlap between pages - high overlap suggests coherent topic coverage""" if len(state.knowledge_base) < 2: return 1.0 # Single or no documents are perfectly consistent # Calculate pairwise term overlap overlaps = [] for i in range(len(state.knowledge_base)): for j in range(i + 1, len(state.knowledge_base)): # Get terms from both documents terms_i = set(self._get_document_terms(state.knowledge_base[i])) terms_j = set(self._get_document_terms(state.knowledge_base[j])) if terms_i and terms_j: # Jaccard similarity overlap = len(terms_i & terms_j) / len(terms_i | terms_j) overlaps.append(overlap) if overlaps: # Average overlap as consistency measure consistency = sum(overlaps) / len(overlaps) else: consistency = 0.0 return consistency def _calculate_saturation(self, state: CrawlState) -> float: """Diminishing returns indicator - are we still discovering new information?""" if not state.new_terms_history: return 0.0 if len(state.new_terms_history) < 2: return 0.0 # Not enough history # Calculate rate of new term discovery recent_rate = state.new_terms_history[-1] if state.new_terms_history[-1] > 0 else 1 initial_rate = state.new_terms_history[0] if state.new_terms_history[0] > 0 else 1 # Saturation increases as rate decreases saturation = 1 - (recent_rate / initial_rate) return max(0.0, min(saturation, 1.0)) async def rank_links(self, state: CrawlState, config: AdaptiveConfig) -> List[Tuple[Link, float]]: """Rank links by expected information gain""" scored_links = [] for link in state.pending_links: # Skip already crawled URLs if link.href in state.crawled_urls: continue # Calculate component scores relevance = self._calculate_relevance(link, state) novelty = self._calculate_novelty(link, state) authority = 1.0 # authority = self._calculate_authority(link) # Combined score score = (config.relevance_weight * relevance + config.novelty_weight * novelty + config.authority_weight * authority) scored_links.append((link, score)) # Sort by score descending scored_links.sort(key=lambda x: x[1], reverse=True) return scored_links def _calculate_relevance(self, link: Link, state: CrawlState) -> float: """BM25 relevance score between link preview and query""" if not state.query or not link: return 0.0 # Combine available text from link link_text = ' '.join(filter(None, [ link.text or '', link.title or '', link.head_data.get('meta', {}).get('title', '') if link.head_data else '', link.head_data.get('meta', {}).get('description', '') if link.head_data else '', link.head_data.get('meta', {}).get('keywords', '') if link.head_data else '' ])).lower() if not link_text: return 0.0 # Use contextual score if available (from BM25 scoring during crawl) # if link.contextual_score is not None: if link.contextual_score and link.contextual_score > 0: return link.contextual_score # Otherwise, calculate simple term overlap query_terms = set(self._tokenize(state.query.lower())) link_terms = set(self._tokenize(link_text)) if not query_terms: return 0.0 overlap = len(query_terms & link_terms) / len(query_terms) return overlap def _calculate_novelty(self, link: Link, state: CrawlState) -> float: """Estimate how much new information this link might provide""" if not state.knowledge_base: return 1.0 # First links are maximally novel # Get terms from link preview link_text = ' '.join(filter(None, [ link.text or '', link.title or '', link.head_data.get('title', '') if link.head_data else '', link.head_data.get('description', '') if link.head_data else '', link.head_data.get('keywords', '') if link.head_data else '' ])).lower() link_terms = set(self._tokenize(link_text)) if not link_terms: return 0.5 # Unknown novelty # Calculate what percentage of link terms are new existing_terms = set(state.term_frequencies.keys()) new_terms = link_terms - existing_terms novelty = len(new_terms) / len(link_terms) if link_terms else 0.0 return novelty def _calculate_authority(self, link: Link) -> float: """Simple authority score based on URL structure and link attributes""" score = 0.5 # Base score if not link.href: return 0.0 url = link.href.lower() # Positive indicators if '/docs/' in url or '/documentation/' in url: score += 0.2 if '/api/' in url or '/reference/' in url: score += 0.2 if '/guide/' in url or '/tutorial/' in url: score += 0.1 # Check for file extensions if url.endswith('.pdf'): score += 0.1 elif url.endswith(('.jpg', '.png', '.gif')): score -= 0.3 # Reduce score for images # Use intrinsic score if available if link.intrinsic_score is not None: score = 0.7 * score + 0.3 * link.intrinsic_score return min(score, 1.0) async def should_stop(self, state: CrawlState, config: AdaptiveConfig) -> bool: """Determine if crawling should stop""" # Check confidence threshold confidence = state.metrics.get('confidence', 0.0) if confidence >= config.confidence_threshold: return True # Check resource limits if len(state.crawled_urls) >= config.max_pages: return True # Check if we have any links left if not state.pending_links: return True # Check saturation if state.metrics.get('saturation', 0.0) >= config.saturation_threshold: return True return False async def update_state(self, state: CrawlState, new_results: List[CrawlResult]) -> None: """Update state with new crawl results""" for result in new_results: # Track new terms old_term_count = len(state.term_frequencies) # Extract and process content - try multiple fields try: content = result.markdown.raw_markdown except AttributeError: print(f"Warning: CrawlResult {result.url} has no markdown content") content = "" # content = "" # if hasattr(result, 'extracted_content') and result.extracted_content: # content = result.extracted_content # elif hasattr(result, 'markdown') and result.markdown: # content = result.markdown.raw_markdown # elif hasattr(result, 'cleaned_html') and result.cleaned_html: # content = result.cleaned_html # elif hasattr(result, 'html') and result.html: # # Use raw HTML as last resort # content = result.html terms = self._tokenize(content.lower()) # Update term frequencies term_set = set() for term in terms: state.term_frequencies[term] += 1 term_set.add(term) # Update document frequencies doc_id = state.total_documents for term in term_set: if term not in state.documents_with_terms[term]: state.document_frequencies[term] += 1 state.documents_with_terms[term].add(doc_id) # Track new terms discovered new_term_count = len(state.term_frequencies) new_terms = new_term_count - old_term_count state.new_terms_history.append(new_terms) # Update document count state.total_documents += 1 # Add to crawl order state.crawl_order.append(result.url) def _tokenize(self, text: str) -> List[str]: """Simple tokenization - can be enhanced""" # Remove punctuation and split text = re.sub(r'[^\w\s]', ' ', text) tokens = text.split() # Filter short tokens and stop words (basic) tokens = [t for t in tokens if len(t) > 2] return tokens def _get_document_terms(self, crawl_result: CrawlResult) -> List[str]: """Extract terms from a crawl result""" content = crawl_result.markdown.raw_markdown or "" return self._tokenize(content.lower()) class EmbeddingStrategy(CrawlStrategy): """Embedding-based adaptive crawling using semantic space coverage""" def __init__(self, embedding_model: str = None, llm_config: Dict = None): self.embedding_model = embedding_model or "sentence-transformers/all-MiniLM-L6-v2" self.llm_config = llm_config self._embedding_cache = {} self._link_embedding_cache = {} # Cache for link embeddings self._validation_passed = False # Track if validation passed # Performance optimization caches self._distance_matrix_cache = None # Cache for query-KB distances self._kb_embeddings_hash = None # Track KB changes self._validation_embeddings_cache = None # Cache validation query embeddings self._kb_similarity_threshold = 0.95 # Threshold for deduplication async def _get_embeddings(self, texts: List[str]) -> Any: """Get embeddings using configured method""" from .utils import get_text_embeddings embedding_llm_config = { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY') } return await get_text_embeddings( texts, embedding_llm_config, self.embedding_model ) def _compute_distance_matrix(self, query_embeddings: Any, kb_embeddings: Any) -> Any: """Compute distance matrix using vectorized operations""" import numpy as np if kb_embeddings is None or len(kb_embeddings) == 0: return None # Ensure proper shapes if len(query_embeddings.shape) == 1: query_embeddings = query_embeddings.reshape(1, -1) if len(kb_embeddings.shape) == 1: kb_embeddings = kb_embeddings.reshape(1, -1) # Vectorized cosine distance: 1 - cosine_similarity # Normalize vectors query_norm = query_embeddings / np.linalg.norm(query_embeddings, axis=1, keepdims=True) kb_norm = kb_embeddings / np.linalg.norm(kb_embeddings, axis=1, keepdims=True) # Compute cosine similarity matrix similarity_matrix = np.dot(query_norm, kb_norm.T) # Convert to distance distance_matrix = 1 - similarity_matrix return distance_matrix def _get_cached_distance_matrix(self, query_embeddings: Any, kb_embeddings: Any) -> Any: """Get distance matrix with caching""" import numpy as np if kb_embeddings is None or len(kb_embeddings) == 0: return None # Check if KB has changed kb_hash = hash(kb_embeddings.tobytes()) if kb_embeddings is not None else None if (self._distance_matrix_cache is None or kb_hash != self._kb_embeddings_hash): # Recompute matrix self._distance_matrix_cache = self._compute_distance_matrix(query_embeddings, kb_embeddings) self._kb_embeddings_hash = kb_hash return self._distance_matrix_cache async def map_query_semantic_space(self, query: str, n_synthetic: int = 10) -> Any: """Generate a point cloud representing the semantic neighborhood of the query""" from .utils import perform_completion_with_backoff # Generate more variations than needed for train/val split n_total = int(n_synthetic * 1.3) # Generate 30% more for validation # Generate variations using LLM prompt = f"""Generate {n_total} variations of this query that explore different aspects: '{query}' These should be queries a user might ask when looking for similar information. Include different phrasings, related concepts, and specific aspects. Return as a JSON array of strings.""" # Use the LLM for query generation provider = self.llm_config.get('provider', 'openai/gpt-4o-mini') if self.llm_config else 'openai/gpt-4o-mini' api_token = self.llm_config.get('api_token') if self.llm_config else None # response = perform_completion_with_backoff( # provider=provider, # prompt_with_variables=prompt, # api_token=api_token, # json_response=True # ) # variations = json.loads(response.choices[0].message.content) # # Mock data with more variations for split variations ={'queries': ['what are the best vegetables to use in fried rice?', 'how do I make vegetable fried rice from scratch?', 'can you provide a quick recipe for vegetable fried rice?', 'what cooking techniques are essential for perfect fried rice with vegetables?', 'how to add flavor to vegetable fried rice?', 'are there any tips for making healthy fried rice with vegetables?']} variations = {'queries': [ 'How do async and await work with coroutines in Python?', 'What is the role of event loops in asynchronous programming?', 'Can you explain the differences between async/await and traditional callback methods?', 'How do coroutines interact with event loops in JavaScript?', 'What are the benefits of using async await over promises in Node.js?', # 'How to manage multiple coroutines with an event loop?', # 'What are some common pitfalls when using async await with coroutines?', # 'How do different programming languages implement async await and event loops?', # 'What happens when an async function is called without await?', # 'How does the event loop handle blocking operations?', 'Can you nest async functions and how does that affect the event loop?', 'What is the performance impact of using async/await?' ]} # Split into train and validation # all_queries = [query] + variations['queries'] # Randomly shuffle for proper train/val split (keeping original query in training) import random # Keep original query always in training other_queries = variations['queries'].copy() random.shuffle(other_queries) # Split: 80% for training, 20% for validation n_validation = max(2, int(len(other_queries) * 0.2)) # At least 2 for validation val_queries = other_queries[-n_validation:] train_queries = [query] + other_queries[:-n_validation] # Embed only training queries for now (faster) train_embeddings = await self._get_embeddings(train_queries) # Store validation queries for later (don't embed yet to save time) self._validation_queries = val_queries return train_embeddings, train_queries def compute_coverage_shape(self, query_points: Any, alpha: float = 0.5): """Find the minimal shape that covers all query points using alpha shape""" try: import numpy as np if len(query_points) < 3: return None # For high-dimensional embeddings (e.g., 384-dim, 768-dim), # alpha shapes require exponentially more points than available. # Instead, use a statistical coverage model query_points = np.array(query_points) # Store coverage as centroid + radius model coverage = { 'center': np.mean(query_points, axis=0), 'std': np.std(query_points, axis=0), 'points': query_points, 'radius': np.max(np.linalg.norm(query_points - np.mean(query_points, axis=0), axis=1)) } return coverage except Exception: # Fallback if computation fails return None def _sample_boundary_points(self, shape, n_samples: int = 20) -> List[Any]: """Sample points from the boundary of a shape""" import numpy as np # Simplified implementation - in practice would sample from actual shape boundary # For now, return empty list if shape is None if shape is None: return [] # This is a placeholder - actual implementation would depend on shape type return [] def find_coverage_gaps(self, kb_embeddings: Any, query_embeddings: Any) -> List[Tuple[Any, float]]: """Calculate gap distances for all query variations using vectorized operations""" import numpy as np gaps = [] if kb_embeddings is None or len(kb_embeddings) == 0: # If no KB yet, all query points have maximum gap for q_emb in query_embeddings: gaps.append((q_emb, 1.0)) return gaps # Use cached distance matrix distance_matrix = self._get_cached_distance_matrix(query_embeddings, kb_embeddings) if distance_matrix is None: # Fallback for q_emb in query_embeddings: gaps.append((q_emb, 1.0)) return gaps # Find minimum distance for each query (vectorized) min_distances = np.min(distance_matrix, axis=1) # Create gaps list for i, q_emb in enumerate(query_embeddings): gaps.append((q_emb, min_distances[i])) return gaps async def select_links_for_expansion( self, candidate_links: List[Link], gaps: List[Tuple[Any, float]], kb_embeddings: Any ) -> List[Tuple[Link, float]]: """Select links that most efficiently fill the gaps""" from .utils import cosine_distance, cosine_similarity, get_text_embeddings import numpy as np import hashlib scored_links = [] # Prepare for embedding - separate cached vs uncached links_to_embed = [] texts_to_embed = [] link_embeddings_map = {} for link in candidate_links: # Extract text from link link_text = ' '.join(filter(None, [ link.text or '', link.title or '', link.meta.get('description', '') if hasattr(link, 'meta') and link.meta else '', link.head_data.get('meta', {}).get('description', '') if link.head_data else '' ])) if not link_text.strip(): continue # Create cache key from URL + text content cache_key = hashlib.md5(f"{link.href}:{link_text}".encode()).hexdigest() # Check cache if cache_key in self._link_embedding_cache: link_embeddings_map[link.href] = self._link_embedding_cache[cache_key] else: links_to_embed.append(link) texts_to_embed.append(link_text) # Batch embed only uncached links if texts_to_embed: embedding_llm_config = { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY') } new_embeddings = await get_text_embeddings(texts_to_embed, embedding_llm_config, self.embedding_model) # Cache the new embeddings for link, text, embedding in zip(links_to_embed, texts_to_embed, new_embeddings): cache_key = hashlib.md5(f"{link.href}:{text}".encode()).hexdigest() self._link_embedding_cache[cache_key] = embedding link_embeddings_map[link.href] = embedding # Get coverage radius from config coverage_radius = self.config.embedding_coverage_radius if hasattr(self, 'config') else 0.2 # Score each link for link in candidate_links: if link.href not in link_embeddings_map: continue # Skip links without embeddings link_embedding = link_embeddings_map[link.href] if not gaps: score = 0.0 else: # Calculate how many gaps this link helps with gaps_helped = 0 total_improvement = 0 for gap_point, gap_distance in gaps: # Only consider gaps that actually need filling (outside coverage radius) if gap_distance > coverage_radius: new_distance = cosine_distance(link_embedding, gap_point) if new_distance < gap_distance: # This link helps this gap improvement = gap_distance - new_distance # Scale improvement - moving from 0.5 to 0.3 is valuable scaled_improvement = improvement * 2 # Amplify the signal total_improvement += scaled_improvement gaps_helped += 1 # Average improvement per gap that needs help gaps_needing_help = sum(1 for _, d in gaps if d > coverage_radius) if gaps_needing_help > 0: gap_reduction_score = total_improvement / gaps_needing_help else: gap_reduction_score = 0 # Check overlap with existing KB (vectorized) if kb_embeddings is not None and len(kb_embeddings) > 0: # Normalize embeddings link_norm = link_embedding / np.linalg.norm(link_embedding) kb_norm = kb_embeddings / np.linalg.norm(kb_embeddings, axis=1, keepdims=True) # Compute all similarities at once similarities = np.dot(kb_norm, link_norm) max_similarity = np.max(similarities) # Only penalize if very similar (above threshold) overlap_threshold = self.config.embedding_overlap_threshold if hasattr(self, 'config') else 0.85 if max_similarity > overlap_threshold: overlap_penalty = (max_similarity - overlap_threshold) * 2 # 0 to 0.3 range else: overlap_penalty = 0 else: overlap_penalty = 0 # Final score - emphasize gap reduction score = gap_reduction_score * (1 - overlap_penalty) # Add contextual score boost if available if hasattr(link, 'contextual_score') and link.contextual_score: score = score * 0.8 + link.contextual_score * 0.2 scored_links.append((link, score)) return sorted(scored_links, key=lambda x: x[1], reverse=True) async def calculate_confidence(self, state: CrawlState) -> float: """Coverage-based learning score (0โ€“1).""" import numpy as np # Guard clauses if state.kb_embeddings is None or state.query_embeddings is None: return 0.0 if len(state.kb_embeddings) == 0 or len(state.query_embeddings) == 0: return 0.0 # Prepare L2-normalised arrays Q = np.asarray(state.query_embeddings, dtype=np.float32) D = np.asarray(state.kb_embeddings, dtype=np.float32) Q /= np.linalg.norm(Q, axis=1, keepdims=True) + 1e-8 D /= np.linalg.norm(D, axis=1, keepdims=True) + 1e-8 # Best cosine per query best = (Q @ D.T).max(axis=1) # Mean similarity or hit-rate above tau tau = getattr(self.config, 'coverage_tau', None) score = float((best >= tau).mean()) if tau is not None else float(best.mean()) # Store quick metrics state.metrics['coverage_score'] = score state.metrics['avg_best_similarity'] = float(best.mean()) state.metrics['median_best_similarity'] = float(np.median(best)) return score # async def calculate_confidence(self, state: CrawlState) -> float: # """Calculate learning score for adaptive crawling (used for stopping)""" # import numpy as np # if state.kb_embeddings is None or state.query_embeddings is None: # return 0.0 # if len(state.kb_embeddings) == 0: # return 0.0 # # Get cached distance matrix # distance_matrix = self._get_cached_distance_matrix(state.query_embeddings, state.kb_embeddings) # if distance_matrix is None: # return 0.0 # # Vectorized analysis for all queries at once # all_query_metrics = [] # for i in range(len(state.query_embeddings)): # # Get distances for this query # distances = distance_matrix[i] # sorted_distances = np.sort(distances) # # Store metrics for this query # query_metric = { # 'min_distance': sorted_distances[0], # 'top_3_distances': sorted_distances[:3], # 'top_5_distances': sorted_distances[:5], # 'close_neighbors': np.sum(distances < 0.3), # 'very_close_neighbors': np.sum(distances < 0.2), # 'all_distances': distances # } # all_query_metrics.append(query_metric) # # Hybrid approach with density (exponential base) # k_exp = self.config.embedding_k_exp if hasattr(self, 'config') else 1.0 # coverage_scores_hybrid_exp = [] # for metric in all_query_metrics: # # Base score from nearest neighbor # nearest_score = np.exp(-k_exp * metric['min_distance']) # # Top-k average (top 3) # top_k = min(3, len(metric['all_distances'])) # top_k_avg = np.mean([np.exp(-k_exp * d) for d in metric['top_3_distances'][:top_k]]) # # Combine using configured weights # nearest_weight = self.config.embedding_nearest_weight if hasattr(self, 'config') else 0.7 # top_k_weight = self.config.embedding_top_k_weight if hasattr(self, 'config') else 0.3 # hybrid_score = nearest_weight * nearest_score + top_k_weight * top_k_avg # coverage_scores_hybrid_exp.append(hybrid_score) # learning_score = np.mean(coverage_scores_hybrid_exp) # # Store as learning score # state.metrics['learning_score'] = learning_score # # Store embedding-specific metrics # state.metrics['avg_min_distance'] = np.mean([m['min_distance'] for m in all_query_metrics]) # state.metrics['avg_close_neighbors'] = np.mean([m['close_neighbors'] for m in all_query_metrics]) # state.metrics['avg_very_close_neighbors'] = np.mean([m['very_close_neighbors'] for m in all_query_metrics]) # state.metrics['total_kb_docs'] = len(state.kb_embeddings) # # Store query-level metrics for detailed analysis # self._query_metrics = all_query_metrics # # For stopping criteria, return learning score # return float(learning_score) async def rank_links(self, state: CrawlState, config: AdaptiveConfig) -> List[Tuple[Link, float]]: """Main entry point for link ranking""" # Store config for use in other methods self.config = config # Filter out already crawled URLs and remove duplicates seen_urls = set() uncrawled_links = [] for link in state.pending_links: if link.href not in state.crawled_urls and link.href not in seen_urls: uncrawled_links.append(link) seen_urls.add(link.href) if not uncrawled_links: return [] # Get gaps in coverage (no threshold needed anymore) gaps = self.find_coverage_gaps( state.kb_embeddings, state.query_embeddings ) state.semantic_gaps = [(g[0].tolist(), g[1]) for g in gaps] # Store as list for serialization # Select links that fill gaps (only from uncrawled) return await self.select_links_for_expansion( uncrawled_links, gaps, state.kb_embeddings ) async def validate_coverage(self, state: CrawlState) -> float: """Validate coverage using held-out queries with caching""" if not hasattr(self, '_validation_queries') or not self._validation_queries: return state.metrics.get('confidence', 0.0) import numpy as np # Cache validation embeddings (only embed once!) if self._validation_embeddings_cache is None: self._validation_embeddings_cache = await self._get_embeddings(self._validation_queries) val_embeddings = self._validation_embeddings_cache # Use vectorized distance computation if state.kb_embeddings is None or len(state.kb_embeddings) == 0: return 0.0 # Compute distance matrix for validation queries distance_matrix = self._compute_distance_matrix(val_embeddings, state.kb_embeddings) if distance_matrix is None: return 0.0 # Find minimum distance for each validation query (vectorized) min_distances = np.min(distance_matrix, axis=1) # Compute scores using same exponential as training k_exp = self.config.embedding_k_exp if hasattr(self, 'config') else 1.0 scores = np.exp(-k_exp * min_distances) validation_confidence = np.mean(scores) state.metrics['validation_confidence'] = validation_confidence return validation_confidence async def should_stop(self, state: CrawlState, config: AdaptiveConfig) -> bool: """Stop based on learning curve convergence""" confidence = state.metrics.get('confidence', 0.0) # Basic limits if len(state.crawled_urls) >= config.max_pages or not state.pending_links: return True # Track confidence history if not hasattr(state, 'confidence_history'): state.confidence_history = [] state.confidence_history.append(confidence) # Need at least 3 iterations to check convergence if len(state.confidence_history) < 2: return False improvement_diffs = list(zip(state.confidence_history[:-1], state.confidence_history[1:])) # Calculate average improvement avg_improvement = sum(abs(b - a) for a, b in improvement_diffs) / len(improvement_diffs) state.metrics['avg_improvement'] = avg_improvement min_relative_improvement = self.config.embedding_min_relative_improvement * confidence if hasattr(self, 'config') else 0.1 * confidence if avg_improvement < min_relative_improvement: # Converged - validate before stopping val_score = await self.validate_coverage(state) # Only stop if validation is reasonable validation_min = self.config.embedding_validation_min_score if hasattr(self, 'config') else 0.4 if val_score > validation_min: state.metrics['stopped_reason'] = 'converged_validated' self._validation_passed = True return True else: state.metrics['stopped_reason'] = 'low_validation' # Continue crawling despite convergence return False def get_quality_confidence(self, state: CrawlState) -> float: """Calculate quality-based confidence score for display""" learning_score = state.metrics.get('learning_score', 0.0) validation_score = state.metrics.get('validation_confidence', 0.0) # Get config values validation_min = self.config.embedding_validation_min_score if hasattr(self, 'config') else 0.4 quality_min = self.config.embedding_quality_min_confidence if hasattr(self, 'config') else 0.7 quality_max = self.config.embedding_quality_max_confidence if hasattr(self, 'config') else 0.95 scale_factor = self.config.embedding_quality_scale_factor if hasattr(self, 'config') else 0.833 if self._validation_passed and validation_score > validation_min: # Validated systems get boosted scores # Map 0.4-0.7 learning โ†’ quality_min-quality_max confidence if learning_score < 0.4: confidence = quality_min # Minimum for validated systems elif learning_score > 0.7: confidence = quality_max # Maximum realistic confidence else: # Linear mapping in between confidence = quality_min + (learning_score - 0.4) * scale_factor else: # Not validated = conservative mapping confidence = learning_score * 0.8 return confidence async def update_state(self, state: CrawlState, new_results: List[CrawlResult]) -> None: """Update embeddings and coverage metrics with deduplication""" from .utils import get_text_embeddings import numpy as np # Extract text from results new_texts = [] valid_results = [] for result in new_results: content = result.markdown.raw_markdown if hasattr(result, 'markdown') and result.markdown else "" if content: # Only process non-empty content new_texts.append(content[:5000]) # Limit text length valid_results.append(result) if not new_texts: return # Get embeddings for new texts embedding_llm_config = { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY') } new_embeddings = await get_text_embeddings(new_texts, embedding_llm_config, self.embedding_model) # Deduplicate embeddings before adding to KB if state.kb_embeddings is None: # First batch - no deduplication needed state.kb_embeddings = new_embeddings deduplicated_indices = list(range(len(new_embeddings))) else: # Check for duplicates using vectorized similarity deduplicated_embeddings = [] deduplicated_indices = [] for i, new_emb in enumerate(new_embeddings): # Compute similarities with existing KB new_emb_normalized = new_emb / np.linalg.norm(new_emb) kb_normalized = state.kb_embeddings / np.linalg.norm(state.kb_embeddings, axis=1, keepdims=True) similarities = np.dot(kb_normalized, new_emb_normalized) # Only add if not too similar to existing content if np.max(similarities) < self._kb_similarity_threshold: deduplicated_embeddings.append(new_emb) deduplicated_indices.append(i) # Add deduplicated embeddings if deduplicated_embeddings: state.kb_embeddings = np.vstack([state.kb_embeddings, np.array(deduplicated_embeddings)]) # Update crawl order only for non-duplicate results for idx in deduplicated_indices: state.crawl_order.append(valid_results[idx].url) # Invalidate distance matrix cache since KB changed self._kb_embeddings_hash = None self._distance_matrix_cache = None # Update coverage shape if needed if hasattr(state, 'query_embeddings') and state.query_embeddings is not None: state.coverage_shape = self.compute_coverage_shape(state.query_embeddings, self.config.alpha_shape_alpha if hasattr(self, 'config') else 0.5) class AdaptiveCrawler: """Main adaptive crawler that orchestrates the crawling process""" def __init__(self, crawler: Optional[AsyncWebCrawler] = None, config: Optional[AdaptiveConfig] = None, strategy: Optional[CrawlStrategy] = None): self.crawler = crawler self.config = config or AdaptiveConfig() self.config.validate() # Create strategy based on config if strategy: self.strategy = strategy else: self.strategy = self._create_strategy(self.config.strategy) # Initialize state self.state: Optional[CrawlState] = None # Track if we own the crawler (for cleanup) self._owns_crawler = crawler is None def _create_strategy(self, strategy_name: str) -> CrawlStrategy: """Create strategy instance based on name""" if strategy_name == "statistical": return StatisticalStrategy() elif strategy_name == "embedding": return EmbeddingStrategy( embedding_model=self.config.embedding_model, llm_config=self.config.embedding_llm_config ) else: raise ValueError(f"Unknown strategy: {strategy_name}") async def digest(self, start_url: str, query: str, resume_from: Optional[str] = None) -> CrawlState: """Main entry point for adaptive crawling""" # Initialize or resume state if resume_from: self.state = CrawlState.load(resume_from) self.state.query = query # Update query in case it changed else: self.state = CrawlState( crawled_urls=set(), knowledge_base=[], pending_links=[], query=query, metrics={} ) # Create crawler if needed if not self.crawler: self.crawler = AsyncWebCrawler() await self.crawler.__aenter__() self.strategy.config = self.config # Pass config to strategy # If using embedding strategy and not resuming, expand query space if isinstance(self.strategy, EmbeddingStrategy) and not resume_from: # Generate query space query_embeddings, expanded_queries = await self.strategy.map_query_semantic_space( query, self.config.n_query_variations ) self.state.query_embeddings = query_embeddings self.state.expanded_queries = expanded_queries[1:] # Skip original query self.state.embedding_model = self.strategy.embedding_model try: # Initial crawl if not resuming if start_url not in self.state.crawled_urls: result = await self._crawl_with_preview(start_url, query) if result and hasattr(result, 'success') and result.success: self.state.knowledge_base.append(result) self.state.crawled_urls.add(start_url) # Extract links from result - handle both dict and Links object formats if hasattr(result, 'links') and result.links: if isinstance(result.links, dict): # Extract internal and external links from dict internal_links = [Link(**link) for link in result.links.get('internal', [])] external_links = [Link(**link) for link in result.links.get('external', [])] self.state.pending_links.extend(internal_links + external_links) else: # Handle Links object self.state.pending_links.extend(result.links.internal + result.links.external) # Update state await self.strategy.update_state(self.state, [result]) # adaptive expansion depth = 0 while depth < self.config.max_depth: # Calculate confidence confidence = await self.strategy.calculate_confidence(self.state) self.state.metrics['confidence'] = confidence # Check stopping criteria if await self.strategy.should_stop(self.state, self.config): break # Rank candidate links ranked_links = await self.strategy.rank_links(self.state, self.config) if not ranked_links: break # Check minimum gain threshold if ranked_links[0][1] < self.config.min_gain_threshold: break # Select top K links to_crawl = [(link, score) for link, score in ranked_links[:self.config.top_k_links] if link.href not in self.state.crawled_urls] if not to_crawl: break # Crawl selected links new_results = await self._crawl_batch(to_crawl, query) if new_results: # Update knowledge base self.state.knowledge_base.extend(new_results) # Update crawled URLs and pending links for result, (link, _) in zip(new_results, to_crawl): if result: self.state.crawled_urls.add(link.href) # Extract links from result - handle both dict and Links object formats if hasattr(result, 'links') and result.links: new_links = [] if isinstance(result.links, dict): # Extract internal and external links from dict internal_links = [Link(**link_data) for link_data in result.links.get('internal', [])] external_links = [Link(**link_data) for link_data in result.links.get('external', [])] new_links = internal_links + external_links else: # Handle Links object new_links = result.links.internal + result.links.external # Add new links to pending for new_link in new_links: if new_link.href not in self.state.crawled_urls: self.state.pending_links.append(new_link) # Update state with new results await self.strategy.update_state(self.state, new_results) depth += 1 # Save state if configured if self.config.save_state and self.config.state_path: self.state.save(self.config.state_path) # Final confidence calculation learning_score = await self.strategy.calculate_confidence(self.state) # For embedding strategy, get quality-based confidence if isinstance(self.strategy, EmbeddingStrategy): self.state.metrics['confidence'] = self.strategy.get_quality_confidence(self.state) else: # For statistical strategy, use the same as before self.state.metrics['confidence'] = learning_score self.state.metrics['pages_crawled'] = len(self.state.crawled_urls) self.state.metrics['depth_reached'] = depth # Final save if self.config.save_state and self.config.state_path: self.state.save(self.config.state_path) return self.state finally: # Cleanup if we created the crawler if self._owns_crawler and self.crawler: await self.crawler.__aexit__(None, None, None) async def _crawl_with_preview(self, url: str, query: str) -> Optional[CrawlResult]: """Crawl a URL with link preview enabled""" config = CrawlerRunConfig( link_preview_config=LinkPreviewConfig( include_internal=True, include_external=False, query=query, # For BM25 scoring concurrency=5, timeout=5, max_links=50, # Reasonable limit verbose=False ), score_links=True # Enable intrinsic scoring ) try: result = await self.crawler.arun(url=url, config=config) # Extract the actual CrawlResult from the container if hasattr(result, '_results') and result._results: result = result._results[0] # Filter our all links do not have head_date if hasattr(result, 'links') and result.links: result.links['internal'] = [link for link in result.links['internal'] if link.get('head_data')] # For now let's ignore external links without head_data # result.links['external'] = [link for link in result.links['external'] if link.get('head_data')] return result except Exception as e: print(f"Error crawling {url}: {e}") return None async def _crawl_batch(self, links_with_scores: List[Tuple[Link, float]], query: str) -> List[CrawlResult]: """Crawl multiple URLs in parallel""" tasks = [] for link, score in links_with_scores: task = self._crawl_with_preview(link.href, query) tasks.append(task) results = await asyncio.gather(*tasks, return_exceptions=True) # Filter out exceptions and failed crawls valid_results = [] for result in results: if isinstance(result, CrawlResult): # Only include successful crawls if hasattr(result, 'success') and result.success: valid_results.append(result) else: print(f"Skipping failed crawl: {result.url if hasattr(result, 'url') else 'unknown'}") elif isinstance(result, Exception): print(f"Error in batch crawl: {result}") return valid_results # Status properties @property def confidence(self) -> float: """Current confidence level""" if self.state: return self.state.metrics.get('confidence', 0.0) return 0.0 @property def coverage_stats(self) -> Dict[str, Any]: """Detailed coverage statistics""" if not self.state: return {} total_content_length = sum( len(result.markdown.raw_markdown or "") for result in self.state.knowledge_base ) return { 'pages_crawled': len(self.state.crawled_urls), 'total_content_length': total_content_length, 'unique_terms': len(self.state.term_frequencies), 'total_terms': sum(self.state.term_frequencies.values()), 'pending_links': len(self.state.pending_links), 'confidence': self.confidence, 'coverage': self.state.metrics.get('coverage', 0.0), 'consistency': self.state.metrics.get('consistency', 0.0), 'saturation': self.state.metrics.get('saturation', 0.0) } @property def is_sufficient(self) -> bool: """Check if current knowledge is sufficient""" if isinstance(self.strategy, EmbeddingStrategy): # For embedding strategy, sufficient = validation passed return self.strategy._validation_passed else: # For statistical strategy, use threshold return self.confidence >= self.config.confidence_threshold def print_stats(self, detailed: bool = False) -> None: """Print comprehensive statistics about the knowledge base Args: detailed: If True, show detailed statistics including top terms """ if not self.state: print("No crawling state available.") return # Import here to avoid circular imports try: from rich.console import Console from rich.table import Table console = Console() use_rich = True except ImportError: use_rich = False if not detailed and use_rich: # Summary view with nice table (like original) table = Table(title=f"Adaptive Crawl Stats - Query: '{self.state.query}'") table.add_column("Metric", style="cyan", no_wrap=True) table.add_column("Value", style="magenta") # Basic stats stats = self.coverage_stats table.add_row("Pages Crawled", str(stats.get('pages_crawled', 0))) table.add_row("Unique Terms", str(stats.get('unique_terms', 0))) table.add_row("Total Terms", str(stats.get('total_terms', 0))) table.add_row("Content Length", f"{stats.get('total_content_length', 0):,} chars") table.add_row("Pending Links", str(stats.get('pending_links', 0))) table.add_row("", "") # Spacer # Strategy-specific metrics if isinstance(self.strategy, EmbeddingStrategy): # Embedding-specific metrics table.add_row("Confidence", f"{stats.get('confidence', 0):.2%}") table.add_row("Avg Min Distance", f"{self.state.metrics.get('avg_min_distance', 0):.3f}") table.add_row("Avg Close Neighbors", f"{self.state.metrics.get('avg_close_neighbors', 0):.1f}") table.add_row("Validation Score", f"{self.state.metrics.get('validation_confidence', 0):.2%}") table.add_row("", "") # Spacer table.add_row("Is Sufficient?", "[green]Yes (Validated)[/green]" if self.is_sufficient else "[red]No[/red]") else: # Statistical strategy metrics table.add_row("Confidence", f"{stats.get('confidence', 0):.2%}") table.add_row("Coverage", f"{stats.get('coverage', 0):.2%}") table.add_row("Consistency", f"{stats.get('consistency', 0):.2%}") table.add_row("Saturation", f"{stats.get('saturation', 0):.2%}") table.add_row("", "") # Spacer table.add_row("Is Sufficient?", "[green]Yes[/green]" if self.is_sufficient else "[red]No[/red]") console.print(table) else: # Detailed view or fallback when rich not available print("\n" + "="*80) print(f"Adaptive Crawl Statistics - Query: '{self.state.query}'") print("="*80) # Basic stats print("\n[*] Basic Statistics:") print(f" Pages Crawled: {len(self.state.crawled_urls)}") print(f" Pending Links: {len(self.state.pending_links)}") print(f" Total Documents: {self.state.total_documents}") # Content stats total_content_length = sum( len(self._get_content_from_result(result)) for result in self.state.knowledge_base ) total_words = sum(self.state.term_frequencies.values()) unique_terms = len(self.state.term_frequencies) print(f"\n[*] Content Statistics:") print(f" Total Content: {total_content_length:,} characters") print(f" Total Words: {total_words:,}") print(f" Unique Terms: {unique_terms:,}") if total_words > 0: print(f" Vocabulary Richness: {unique_terms/total_words:.2%}") # Strategy-specific output if isinstance(self.strategy, EmbeddingStrategy): # Semantic coverage for embedding strategy print(f"\n[*] Semantic Coverage Analysis:") print(f" Average Min Distance: {self.state.metrics.get('avg_min_distance', 0):.3f}") print(f" Avg Close Neighbors (< 0.3): {self.state.metrics.get('avg_close_neighbors', 0):.1f}") print(f" Avg Very Close Neighbors (< 0.2): {self.state.metrics.get('avg_very_close_neighbors', 0):.1f}") # Confidence metrics print(f"\n[*] Confidence Metrics:") if self.is_sufficient: if use_rich: console.print(f" Overall Confidence: {self.confidence:.2%} [green][VALIDATED][/green]") else: print(f" Overall Confidence: {self.confidence:.2%} [VALIDATED]") else: if use_rich: console.print(f" Overall Confidence: {self.confidence:.2%} [red][NOT VALIDATED][/red]") else: print(f" Overall Confidence: {self.confidence:.2%} [NOT VALIDATED]") print(f" Learning Score: {self.state.metrics.get('learning_score', 0):.2%}") print(f" Validation Score: {self.state.metrics.get('validation_confidence', 0):.2%}") else: # Query coverage for statistical strategy print(f"\n[*] Query Coverage:") query_terms = self.strategy._tokenize(self.state.query.lower()) for term in query_terms: tf = self.state.term_frequencies.get(term, 0) df = self.state.document_frequencies.get(term, 0) if df > 0: if use_rich: console.print(f" '{term}': found in {df}/{self.state.total_documents} docs ([green]{df/self.state.total_documents:.0%}[/green]), {tf} occurrences") else: print(f" '{term}': found in {df}/{self.state.total_documents} docs ({df/self.state.total_documents:.0%}), {tf} occurrences") else: if use_rich: console.print(f" '{term}': [red][X] not found[/red]") else: print(f" '{term}': [X] not found") # Confidence metrics print(f"\n[*] Confidence Metrics:") status = "[OK]" if self.is_sufficient else "[!!]" if use_rich: status_colored = "[green][OK][/green]" if self.is_sufficient else "[red][!!][/red]" console.print(f" Overall Confidence: {self.confidence:.2%} {status_colored}") else: print(f" Overall Confidence: {self.confidence:.2%} {status}") print(f" Coverage Score: {self.state.metrics.get('coverage', 0):.2%}") print(f" Consistency Score: {self.state.metrics.get('consistency', 0):.2%}") print(f" Saturation Score: {self.state.metrics.get('saturation', 0):.2%}") # Crawl efficiency if self.state.new_terms_history: avg_new_terms = sum(self.state.new_terms_history) / len(self.state.new_terms_history) print(f"\n[*] Crawl Efficiency:") print(f" Avg New Terms per Page: {avg_new_terms:.1f}") print(f" Information Saturation: {self.state.metrics.get('saturation', 0):.2%}") if detailed: print("\n" + "-"*80) if use_rich: console.print("[bold cyan]DETAILED STATISTICS[/bold cyan]") else: print("DETAILED STATISTICS") print("-"*80) # Top terms print("\n[+] Top 20 Terms by Frequency:") top_terms = sorted(self.state.term_frequencies.items(), key=lambda x: x[1], reverse=True)[:20] for i, (term, freq) in enumerate(top_terms, 1): df = self.state.document_frequencies.get(term, 0) if use_rich: console.print(f" {i:2d}. [yellow]'{term}'[/yellow]: {freq} occurrences in {df} docs") else: print(f" {i:2d}. '{term}': {freq} occurrences in {df} docs") # URLs crawled print(f"\n[+] URLs Crawled ({len(self.state.crawled_urls)}):") for i, url in enumerate(self.state.crawl_order, 1): new_terms = self.state.new_terms_history[i-1] if i <= len(self.state.new_terms_history) else 0 if use_rich: console.print(f" {i}. [cyan]{url}[/cyan]") console.print(f" -> Added [green]{new_terms}[/green] new terms") else: print(f" {i}. {url}") print(f" -> Added {new_terms} new terms") # Document frequency distribution print("\n[+] Document Frequency Distribution:") df_counts = {} for df in self.state.document_frequencies.values(): df_counts[df] = df_counts.get(df, 0) + 1 for df in sorted(df_counts.keys()): count = df_counts[df] print(f" Terms in {df} docs: {count} terms") # Embedding stats if self.state.embedding_model: print("\n[+] Semantic Coverage Analysis:") print(f" Embedding Model: {self.state.embedding_model}") print(f" Query Variations: {len(self.state.expanded_queries)}") if self.state.kb_embeddings is not None: print(f" Knowledge Embeddings: {self.state.kb_embeddings.shape}") else: print(f" Knowledge Embeddings: None") print(f" Semantic Gaps: {len(self.state.semantic_gaps)}") print(f" Coverage Achievement: {self.confidence:.2%}") # Show sample expanded queries if self.state.expanded_queries: print("\n[+] Query Space (samples):") for i, eq in enumerate(self.state.expanded_queries[:5], 1): if use_rich: console.print(f" {i}. [yellow]{eq}[/yellow]") else: print(f" {i}. {eq}") print("\n" + "="*80) def _get_content_from_result(self, result) -> str: """Helper to safely extract content from result""" if hasattr(result, 'markdown') and result.markdown: if hasattr(result.markdown, 'raw_markdown'): return result.markdown.raw_markdown or "" return str(result.markdown) return "" def export_knowledge_base(self, filepath: Union[str, Path], format: str = "jsonl") -> None: """Export the knowledge base to a file Args: filepath: Path to save the file format: Export format - currently supports 'jsonl' """ if not self.state or not self.state.knowledge_base: print("No knowledge base to export.") return filepath = Path(filepath) filepath.parent.mkdir(parents=True, exist_ok=True) if format == "jsonl": # Export as JSONL - one CrawlResult per line with open(filepath, 'w', encoding='utf-8') as f: for result in self.state.knowledge_base: # Convert CrawlResult to dict result_dict = self._crawl_result_to_export_dict(result) # Write as single line JSON f.write(json.dumps(result_dict, ensure_ascii=False) + '\n') print(f"Exported {len(self.state.knowledge_base)} documents to {filepath}") else: raise ValueError(f"Unsupported export format: {format}") def _crawl_result_to_export_dict(self, result) -> Dict[str, Any]: """Convert CrawlResult to a dictionary for export""" # Extract all available fields export_dict = { 'url': getattr(result, 'url', ''), 'timestamp': getattr(result, 'timestamp', None), 'success': getattr(result, 'success', True), 'query': self.state.query if self.state else '', } # Extract content if hasattr(result, 'markdown') and result.markdown: if hasattr(result.markdown, 'raw_markdown'): export_dict['content'] = result.markdown.raw_markdown else: export_dict['content'] = str(result.markdown) else: export_dict['content'] = '' # Extract metadata if hasattr(result, 'metadata'): export_dict['metadata'] = result.metadata # Extract links if available if hasattr(result, 'links'): export_dict['links'] = result.links # Add crawl-specific metadata if self.state: export_dict['crawl_metadata'] = { 'crawl_order': self.state.crawl_order.index(export_dict['url']) + 1 if export_dict['url'] in self.state.crawl_order else 0, 'confidence_at_crawl': self.state.metrics.get('confidence', 0), 'total_documents': self.state.total_documents } return export_dict def import_knowledge_base(self, filepath: Union[str, Path], format: str = "jsonl") -> None: """Import a knowledge base from a file Args: filepath: Path to the file to import format: Import format - currently supports 'jsonl' """ filepath = Path(filepath) if not filepath.exists(): raise FileNotFoundError(f"File not found: {filepath}") if format == "jsonl": imported_results = [] with open(filepath, 'r', encoding='utf-8') as f: for line in f: if line.strip(): data = json.loads(line) # Convert back to a mock CrawlResult mock_result = self._import_dict_to_crawl_result(data) imported_results.append(mock_result) # Initialize state if needed if not self.state: self.state = CrawlState() # Add imported results self.state.knowledge_base.extend(imported_results) # Update state with imported data asyncio.run(self.strategy.update_state(self.state, imported_results)) print(f"Imported {len(imported_results)} documents from {filepath}") else: raise ValueError(f"Unsupported import format: {format}") def _import_dict_to_crawl_result(self, data: Dict[str, Any]): """Convert imported dict back to a mock CrawlResult""" class MockMarkdown: def __init__(self, content): self.raw_markdown = content class MockCrawlResult: def __init__(self, data): self.url = data.get('url', '') self.markdown = MockMarkdown(data.get('content', '')) self.links = data.get('links', {}) self.metadata = data.get('metadata', {}) self.success = data.get('success', True) self.timestamp = data.get('timestamp') return MockCrawlResult(data) def get_relevant_content(self, top_k: int = 5) -> List[Dict[str, Any]]: """Get most relevant content for the query""" if not self.state or not self.state.knowledge_base: return [] # Simple relevance ranking based on term overlap scored_docs = [] query_terms = set(self.state.query.lower().split()) for i, result in enumerate(self.state.knowledge_base): content = (result.markdown.raw_markdown or "").lower() content_terms = set(content.split()) # Calculate relevance score overlap = len(query_terms & content_terms) score = overlap / len(query_terms) if query_terms else 0.0 scored_docs.append({ 'url': result.url, 'score': score, 'content': result.markdown.raw_markdown, 'index': i }) # Sort by score and return top K scored_docs.sort(key=lambda x: x['score'], reverse=True) return scored_docs[:top_k]
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/adaptive_crawler copy.py", "license": "Apache License 2.0", "lines": 1491, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:crawl4ai/adaptive_crawler.py
""" Adaptive Web Crawler for Crawl4AI This module implements adaptive information foraging for efficient web crawling. It determines when sufficient information has been gathered to answer a query, avoiding unnecessary crawls while ensuring comprehensive coverage. """ from abc import ABC, abstractmethod from typing import Dict, List, Optional, Set, Tuple, Any, Union from dataclasses import dataclass, field import asyncio import pickle import os import json import math from collections import defaultdict, Counter import re from pathlib import Path from crawl4ai.async_webcrawler import AsyncWebCrawler from crawl4ai.async_configs import CrawlerRunConfig, LinkPreviewConfig, LLMConfig from crawl4ai.models import Link, CrawlResult import numpy as np @dataclass class CrawlState: """Tracks the current state of adaptive crawling""" crawled_urls: Set[str] = field(default_factory=set) knowledge_base: List[CrawlResult] = field(default_factory=list) pending_links: List[Link] = field(default_factory=list) query: str = "" metrics: Dict[str, float] = field(default_factory=dict) # Statistical tracking term_frequencies: Dict[str, int] = field(default_factory=lambda: defaultdict(int)) document_frequencies: Dict[str, int] = field(default_factory=lambda: defaultdict(int)) documents_with_terms: Dict[str, Set[int]] = field(default_factory=lambda: defaultdict(set)) total_documents: int = 0 # History tracking for saturation new_terms_history: List[int] = field(default_factory=list) crawl_order: List[str] = field(default_factory=list) # Embedding-specific tracking (only if strategy is embedding) kb_embeddings: Optional[Any] = None # Will be numpy array query_embeddings: Optional[Any] = None # Will be numpy array expanded_queries: List[str] = field(default_factory=list) coverage_shape: Optional[Any] = None # Alpha shape semantic_gaps: List[Tuple[List[float], float]] = field(default_factory=list) # Serializable embedding_model: str = "" def save(self, path: Union[str, Path]): """Save state to disk for persistence""" path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) # Convert CrawlResult objects to dicts for serialization state_dict = { 'crawled_urls': list(self.crawled_urls), 'knowledge_base': [self._crawl_result_to_dict(cr) for cr in self.knowledge_base], 'pending_links': [link.model_dump() for link in self.pending_links], 'query': self.query, 'metrics': self.metrics, 'term_frequencies': dict(self.term_frequencies), 'document_frequencies': dict(self.document_frequencies), 'documents_with_terms': {k: list(v) for k, v in self.documents_with_terms.items()}, 'total_documents': self.total_documents, 'new_terms_history': self.new_terms_history, 'crawl_order': self.crawl_order, # Embedding-specific fields (convert numpy arrays to lists for JSON) 'kb_embeddings': self.kb_embeddings.tolist() if self.kb_embeddings is not None else None, 'query_embeddings': self.query_embeddings.tolist() if self.query_embeddings is not None else None, 'expanded_queries': self.expanded_queries, 'semantic_gaps': self.semantic_gaps, 'embedding_model': self.embedding_model } with open(path, 'w') as f: json.dump(state_dict, f, indent=2) @classmethod def load(cls, path: Union[str, Path]) -> 'CrawlState': """Load state from disk""" path = Path(path) with open(path, 'r') as f: state_dict = json.load(f) state = cls() state.crawled_urls = set(state_dict['crawled_urls']) state.knowledge_base = [cls._dict_to_crawl_result(d) for d in state_dict['knowledge_base']] state.pending_links = [Link(**link_dict) for link_dict in state_dict['pending_links']] state.query = state_dict['query'] state.metrics = state_dict['metrics'] state.term_frequencies = defaultdict(int, state_dict['term_frequencies']) state.document_frequencies = defaultdict(int, state_dict['document_frequencies']) state.documents_with_terms = defaultdict(set, {k: set(v) for k, v in state_dict['documents_with_terms'].items()}) state.total_documents = state_dict['total_documents'] state.new_terms_history = state_dict['new_terms_history'] state.crawl_order = state_dict['crawl_order'] # Load embedding-specific fields (convert lists back to numpy arrays) state.kb_embeddings = np.array(state_dict['kb_embeddings']) if state_dict.get('kb_embeddings') is not None else None state.query_embeddings = np.array(state_dict['query_embeddings']) if state_dict.get('query_embeddings') is not None else None state.expanded_queries = state_dict.get('expanded_queries', []) state.semantic_gaps = state_dict.get('semantic_gaps', []) state.embedding_model = state_dict.get('embedding_model', '') return state @staticmethod def _crawl_result_to_dict(cr: CrawlResult) -> Dict: """Convert CrawlResult to serializable dict""" # Extract markdown content safely markdown_content = "" if hasattr(cr, 'markdown') and cr.markdown: if hasattr(cr.markdown, 'raw_markdown'): markdown_content = cr.markdown.raw_markdown else: markdown_content = str(cr.markdown) return { 'url': cr.url, 'content': markdown_content, 'links': cr.links if hasattr(cr, 'links') else {}, 'metadata': cr.metadata if hasattr(cr, 'metadata') else {} } @staticmethod def _dict_to_crawl_result(d: Dict): """Convert dict back to CrawlResult""" # Create a mock object that has the minimal interface we need class MockMarkdown: def __init__(self, content): self.raw_markdown = content class MockCrawlResult: def __init__(self, url, content, links, metadata): self.url = url self.markdown = MockMarkdown(content) self.links = links self.metadata = metadata return MockCrawlResult( url=d['url'], content=d.get('content', ''), links=d.get('links', {}), metadata=d.get('metadata', {}) ) @dataclass class AdaptiveConfig: """Configuration for adaptive crawling""" confidence_threshold: float = 0.7 max_depth: int = 5 max_pages: int = 20 top_k_links: int = 3 min_gain_threshold: float = 0.1 strategy: str = "statistical" # statistical, embedding, llm # Advanced parameters saturation_threshold: float = 0.8 consistency_threshold: float = 0.7 coverage_weight: float = 0.4 consistency_weight: float = 0.3 saturation_weight: float = 0.3 # Link scoring parameters relevance_weight: float = 0.5 novelty_weight: float = 0.3 authority_weight: float = 0.2 # Persistence save_state: bool = False state_path: Optional[str] = None # Embedding strategy parameters embedding_model: str = "sentence-transformers/all-MiniLM-L6-v2" embedding_llm_config: Optional[Union[LLMConfig, Dict]] = None # Separate config for embeddings n_query_variations: int = 10 coverage_threshold: float = 0.85 alpha_shape_alpha: float = 0.5 # Minimum confidence threshold for relevance embedding_min_confidence_threshold: float = 0.1 # Below this, content is considered completely irrelevant # Example: If confidence < 0.1, stop immediately as query and content are unrelated # Embedding confidence calculation parameters embedding_coverage_radius: float = 0.2 # Distance threshold for "covered" query points # Example: With radius=0.2, a query point is considered covered if ANY document # is within cosine distance 0.2 (very similar). Smaller = stricter coverage requirement embedding_k_exp: float = 1.0 # Exponential decay factor for distance-to-score mapping # Example: score = exp(-k_exp * distance). With k_exp=1, distance 0.2 โ†’ score 0.82, # distance 0.5 โ†’ score 0.61. Higher k_exp = steeper decay = more emphasis on very close matches embedding_nearest_weight: float = 0.7 # Weight for nearest neighbor in hybrid scoring embedding_top_k_weight: float = 0.3 # Weight for top-k average in hybrid scoring # Example: If nearest doc has score 0.9 and top-3 avg is 0.6, final = 0.7*0.9 + 0.3*0.6 = 0.81 # Higher nearest_weight = more focus on best match vs neighborhood density # Embedding link selection parameters embedding_overlap_threshold: float = 0.85 # Similarity threshold for penalizing redundant links # Example: Links with >0.85 similarity to existing KB get penalized to avoid redundancy # Lower = more aggressive deduplication, Higher = allow more similar content # Embedding stopping criteria parameters embedding_min_relative_improvement: float = 0.1 # Minimum relative improvement to continue # Example: If confidence is 0.6, need improvement > 0.06 per batch to continue crawling # Lower = more patient crawling, Higher = stop earlier when progress slows embedding_validation_min_score: float = 0.3 # Minimum validation score to trust convergence # Example: Even if learning converged, keep crawling if validation score < 0.4 # This prevents premature stopping when we haven't truly covered the query space # Quality confidence mapping parameters (for display to user) embedding_quality_min_confidence: float = 0.7 # Minimum confidence for validated systems embedding_quality_max_confidence: float = 0.95 # Maximum realistic confidence embedding_quality_scale_factor: float = 0.833 # Scaling factor for confidence mapping # Example: Validated system with learning_score=0.5 โ†’ confidence = 0.7 + (0.5-0.4)*0.833 = 0.78 # These control how internal scores map to user-friendly confidence percentages def validate(self): """Validate configuration parameters""" assert 0 <= self.confidence_threshold <= 1, "confidence_threshold must be between 0 and 1" assert self.max_depth > 0, "max_depth must be positive" assert self.max_pages > 0, "max_pages must be positive" assert self.top_k_links > 0, "top_k_links must be positive" assert 0 <= self.min_gain_threshold <= 1, "min_gain_threshold must be between 0 and 1" # Check weights sum to 1 weight_sum = self.coverage_weight + self.consistency_weight + self.saturation_weight assert abs(weight_sum - 1.0) < 0.001, f"Coverage weights must sum to 1, got {weight_sum}" weight_sum = self.relevance_weight + self.novelty_weight + self.authority_weight assert abs(weight_sum - 1.0) < 0.001, f"Link scoring weights must sum to 1, got {weight_sum}" # Validate embedding parameters assert 0 < self.embedding_coverage_radius < 1, "embedding_coverage_radius must be between 0 and 1" assert self.embedding_k_exp > 0, "embedding_k_exp must be positive" assert 0 <= self.embedding_nearest_weight <= 1, "embedding_nearest_weight must be between 0 and 1" assert 0 <= self.embedding_top_k_weight <= 1, "embedding_top_k_weight must be between 0 and 1" assert abs(self.embedding_nearest_weight + self.embedding_top_k_weight - 1.0) < 0.001, "Embedding weights must sum to 1" assert 0 <= self.embedding_overlap_threshold <= 1, "embedding_overlap_threshold must be between 0 and 1" assert 0 < self.embedding_min_relative_improvement < 1, "embedding_min_relative_improvement must be between 0 and 1" assert 0 <= self.embedding_validation_min_score <= 1, "embedding_validation_min_score must be between 0 and 1" assert 0 <= self.embedding_quality_min_confidence <= 1, "embedding_quality_min_confidence must be between 0 and 1" assert 0 <= self.embedding_quality_max_confidence <= 1, "embedding_quality_max_confidence must be between 0 and 1" assert self.embedding_quality_scale_factor > 0, "embedding_quality_scale_factor must be positive" assert 0 <= self.embedding_min_confidence_threshold <= 1, "embedding_min_confidence_threshold must be between 0 and 1" @property def _embedding_llm_config_dict(self) -> Optional[Dict]: """Convert LLMConfig to dict format for backward compatibility.""" if self.embedding_llm_config is None: return None if isinstance(self.embedding_llm_config, dict): # Already a dict - return as-is for backward compatibility return self.embedding_llm_config # Convert LLMConfig object to dict format return { 'provider': self.embedding_llm_config.provider, 'api_token': self.embedding_llm_config.api_token, 'base_url': getattr(self.embedding_llm_config, 'base_url', None), 'temperature': getattr(self.embedding_llm_config, 'temperature', None), 'max_tokens': getattr(self.embedding_llm_config, 'max_tokens', None), 'top_p': getattr(self.embedding_llm_config, 'top_p', None), 'frequency_penalty': getattr(self.embedding_llm_config, 'frequency_penalty', None), 'presence_penalty': getattr(self.embedding_llm_config, 'presence_penalty', None), 'stop': getattr(self.embedding_llm_config, 'stop', None), 'n': getattr(self.embedding_llm_config, 'n', None), } class CrawlStrategy(ABC): """Abstract base class for crawling strategies""" @abstractmethod async def calculate_confidence(self, state: CrawlState) -> float: """Calculate overall confidence that we have sufficient information""" pass @abstractmethod async def rank_links(self, state: CrawlState, config: AdaptiveConfig) -> List[Tuple[Link, float]]: """Rank pending links by expected information gain""" pass @abstractmethod async def should_stop(self, state: CrawlState, config: AdaptiveConfig) -> bool: """Determine if crawling should stop""" pass @abstractmethod async def update_state(self, state: CrawlState, new_results: List[CrawlResult]) -> None: """Update state with new crawl results""" pass class StatisticalStrategy(CrawlStrategy): """Pure statistical approach - no LLM, no embeddings""" def __init__(self): self.idf_cache = {} self.bm25_k1 = 1.2 # BM25 parameter self.bm25_b = 0.75 # BM25 parameter async def calculate_confidence(self, state: CrawlState) -> float: """Calculate confidence using coverage, consistency, and saturation""" if not state.knowledge_base: return 0.0 coverage = self._calculate_coverage(state) consistency = self._calculate_consistency(state) saturation = self._calculate_saturation(state) # Store individual metrics state.metrics['coverage'] = coverage state.metrics['consistency'] = consistency state.metrics['saturation'] = saturation # Weighted combination (weights from config not accessible here, using defaults) confidence = 0.4 * coverage + 0.3 * consistency + 0.3 * saturation return confidence def _calculate_coverage(self, state: CrawlState) -> float: """Coverage scoring - measures query term presence across knowledge base Returns a score between 0 and 1, where: - 0 means no query terms found - 1 means excellent coverage of all query terms """ if not state.query or state.total_documents == 0: return 0.0 query_terms = self._tokenize(state.query.lower()) if not query_terms: return 0.0 term_scores = [] max_tf = max(state.term_frequencies.values()) if state.term_frequencies else 1 for term in query_terms: tf = state.term_frequencies.get(term, 0) df = state.document_frequencies.get(term, 0) if df > 0: # Document coverage: what fraction of docs contain this term doc_coverage = df / state.total_documents # Frequency signal: normalized log frequency freq_signal = math.log(1 + tf) / math.log(1 + max_tf) if max_tf > 0 else 0 # Combined score: document coverage with frequency boost term_score = doc_coverage * (1 + 0.5 * freq_signal) term_scores.append(term_score) else: term_scores.append(0.0) # Average across all query terms coverage = sum(term_scores) / len(term_scores) # Apply square root curve to make score more intuitive # This helps differentiate between partial and good coverage return min(1.0, math.sqrt(coverage)) def _calculate_consistency(self, state: CrawlState) -> float: """Information overlap between pages - high overlap suggests coherent topic coverage""" if len(state.knowledge_base) < 2: return 1.0 # Single or no documents are perfectly consistent # Calculate pairwise term overlap overlaps = [] for i in range(len(state.knowledge_base)): for j in range(i + 1, len(state.knowledge_base)): # Get terms from both documents terms_i = set(self._get_document_terms(state.knowledge_base[i])) terms_j = set(self._get_document_terms(state.knowledge_base[j])) if terms_i and terms_j: # Jaccard similarity overlap = len(terms_i & terms_j) / len(terms_i | terms_j) overlaps.append(overlap) if overlaps: # Average overlap as consistency measure consistency = sum(overlaps) / len(overlaps) else: consistency = 0.0 return consistency def _calculate_saturation(self, state: CrawlState) -> float: """Diminishing returns indicator - are we still discovering new information?""" if not state.new_terms_history: return 0.0 if len(state.new_terms_history) < 2: return 0.0 # Not enough history # Calculate rate of new term discovery recent_rate = state.new_terms_history[-1] if state.new_terms_history[-1] > 0 else 1 initial_rate = state.new_terms_history[0] if state.new_terms_history[0] > 0 else 1 # Saturation increases as rate decreases saturation = 1 - (recent_rate / initial_rate) return max(0.0, min(saturation, 1.0)) async def rank_links(self, state: CrawlState, config: AdaptiveConfig) -> List[Tuple[Link, float]]: """Rank links by expected information gain""" scored_links = [] for link in state.pending_links: # Skip already crawled URLs if link.href in state.crawled_urls: continue # Calculate component scores relevance = self._calculate_relevance(link, state) novelty = self._calculate_novelty(link, state) authority = 1.0 # authority = self._calculate_authority(link) # Combined score score = (config.relevance_weight * relevance + config.novelty_weight * novelty + config.authority_weight * authority) scored_links.append((link, score)) # Sort by score descending scored_links.sort(key=lambda x: x[1], reverse=True) return scored_links def _calculate_relevance(self, link: Link, state: CrawlState) -> float: """BM25 relevance score between link preview and query""" if not state.query or not link: return 0.0 # Combine available text from link link_text = ' '.join(filter(None, [ link.text or '', link.title or '', link.head_data.get('meta', {}).get('title', '') if link.head_data else '', link.head_data.get('meta', {}).get('description', '') if link.head_data else '', link.head_data.get('meta', {}).get('keywords', '') if link.head_data else '' ])).lower() if not link_text: return 0.0 # Use contextual score if available (from BM25 scoring during crawl) # if link.contextual_score is not None: if link.contextual_score and link.contextual_score > 0: return link.contextual_score # Otherwise, calculate simple term overlap query_terms = set(self._tokenize(state.query.lower())) link_terms = set(self._tokenize(link_text)) if not query_terms: return 0.0 overlap = len(query_terms & link_terms) / len(query_terms) return overlap def _calculate_novelty(self, link: Link, state: CrawlState) -> float: """Estimate how much new information this link might provide""" if not state.knowledge_base: return 1.0 # First links are maximally novel # Get terms from link preview link_text = ' '.join(filter(None, [ link.text or '', link.title or '', link.head_data.get('title', '') if link.head_data else '', link.head_data.get('description', '') if link.head_data else '', link.head_data.get('keywords', '') if link.head_data else '' ])).lower() link_terms = set(self._tokenize(link_text)) if not link_terms: return 0.5 # Unknown novelty # Calculate what percentage of link terms are new existing_terms = set(state.term_frequencies.keys()) new_terms = link_terms - existing_terms novelty = len(new_terms) / len(link_terms) if link_terms else 0.0 return novelty def _calculate_authority(self, link: Link) -> float: """Simple authority score based on URL structure and link attributes""" score = 0.5 # Base score if not link.href: return 0.0 url = link.href.lower() # Positive indicators if '/docs/' in url or '/documentation/' in url: score += 0.2 if '/api/' in url or '/reference/' in url: score += 0.2 if '/guide/' in url or '/tutorial/' in url: score += 0.1 # Check for file extensions if url.endswith('.pdf'): score += 0.1 elif url.endswith(('.jpg', '.png', '.gif')): score -= 0.3 # Reduce score for images # Use intrinsic score if available if link.intrinsic_score is not None: score = 0.7 * score + 0.3 * link.intrinsic_score return min(score, 1.0) async def should_stop(self, state: CrawlState, config: AdaptiveConfig) -> bool: """Determine if crawling should stop""" # Check confidence threshold confidence = state.metrics.get('confidence', 0.0) if confidence >= config.confidence_threshold: return True # Check resource limits if len(state.crawled_urls) >= config.max_pages: return True # Check if we have any links left if not state.pending_links: return True # Check saturation if state.metrics.get('saturation', 0.0) >= config.saturation_threshold: return True return False async def update_state(self, state: CrawlState, new_results: List[CrawlResult]) -> None: """Update state with new crawl results""" for result in new_results: # Track new terms old_term_count = len(state.term_frequencies) # Extract and process content - try multiple fields try: content = result.markdown.raw_markdown except AttributeError: print(f"Warning: CrawlResult {result.url} has no markdown content") content = "" # content = "" # if hasattr(result, 'extracted_content') and result.extracted_content: # content = result.extracted_content # elif hasattr(result, 'markdown') and result.markdown: # content = result.markdown.raw_markdown # elif hasattr(result, 'cleaned_html') and result.cleaned_html: # content = result.cleaned_html # elif hasattr(result, 'html') and result.html: # # Use raw HTML as last resort # content = result.html terms = self._tokenize(content.lower()) # Update term frequencies term_set = set() for term in terms: state.term_frequencies[term] += 1 term_set.add(term) # Update document frequencies doc_id = state.total_documents for term in term_set: if term not in state.documents_with_terms[term]: state.document_frequencies[term] += 1 state.documents_with_terms[term].add(doc_id) # Track new terms discovered new_term_count = len(state.term_frequencies) new_terms = new_term_count - old_term_count state.new_terms_history.append(new_terms) # Update document count state.total_documents += 1 # Add to crawl order state.crawl_order.append(result.url) def _tokenize(self, text: str) -> List[str]: """Simple tokenization - can be enhanced""" # Remove punctuation and split text = re.sub(r'[^\w\s]', ' ', text) tokens = text.split() # Filter short tokens and stop words (basic) tokens = [t for t in tokens if len(t) > 2] return tokens def _get_document_terms(self, crawl_result: CrawlResult) -> List[str]: """Extract terms from a crawl result""" content = crawl_result.markdown.raw_markdown or "" return self._tokenize(content.lower()) class EmbeddingStrategy(CrawlStrategy): """Embedding-based adaptive crawling using semantic space coverage""" def __init__(self, embedding_model: str = None, llm_config: Union[LLMConfig, Dict] = None): self.embedding_model = embedding_model or "sentence-transformers/all-MiniLM-L6-v2" self.llm_config = llm_config self._embedding_cache = {} self._link_embedding_cache = {} # Cache for link embeddings self._validation_passed = False # Track if validation passed # Performance optimization caches self._distance_matrix_cache = None # Cache for query-KB distances self._kb_embeddings_hash = None # Track KB changes self._validation_embeddings_cache = None # Cache validation query embeddings self._kb_similarity_threshold = 0.95 # Threshold for deduplication def _get_embedding_llm_config_dict(self) -> Dict: """Get embedding LLM config as dict with fallback to default.""" if hasattr(self, 'config') and self.config: config_dict = self.config._embedding_llm_config_dict if config_dict: return config_dict # Fallback to default if no config provided return { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY') } async def _get_embeddings(self, texts: List[str]) -> Any: """Get embeddings using configured method""" from .utils import get_text_embeddings embedding_llm_config = self._get_embedding_llm_config_dict() return await get_text_embeddings( texts, embedding_llm_config, self.embedding_model ) def _compute_distance_matrix(self, query_embeddings: Any, kb_embeddings: Any) -> Any: """Compute distance matrix using vectorized operations""" if kb_embeddings is None or len(kb_embeddings) == 0: return None # Ensure proper shapes if len(query_embeddings.shape) == 1: query_embeddings = query_embeddings.reshape(1, -1) if len(kb_embeddings.shape) == 1: kb_embeddings = kb_embeddings.reshape(1, -1) # Vectorized cosine distance: 1 - cosine_similarity # Normalize vectors query_norm = query_embeddings / np.linalg.norm(query_embeddings, axis=1, keepdims=True) kb_norm = kb_embeddings / np.linalg.norm(kb_embeddings, axis=1, keepdims=True) # Compute cosine similarity matrix similarity_matrix = np.dot(query_norm, kb_norm.T) # Convert to distance distance_matrix = 1 - similarity_matrix return distance_matrix def _get_cached_distance_matrix(self, query_embeddings: Any, kb_embeddings: Any) -> Any: """Get distance matrix with caching""" if kb_embeddings is None or len(kb_embeddings) == 0: return None # Check if KB has changed kb_hash = hash(kb_embeddings.tobytes()) if kb_embeddings is not None else None if (self._distance_matrix_cache is None or kb_hash != self._kb_embeddings_hash): # Recompute matrix self._distance_matrix_cache = self._compute_distance_matrix(query_embeddings, kb_embeddings) self._kb_embeddings_hash = kb_hash return self._distance_matrix_cache async def map_query_semantic_space(self, query: str, n_synthetic: int = 10) -> Any: """Generate a point cloud representing the semantic neighborhood of the query""" from .utils import perform_completion_with_backoff # Generate more variations than needed for train/val split n_total = int(n_synthetic * 1.3) # Generate 30% more for validation # Generate variations using LLM prompt = f"""Generate {n_total} variations of this query that explore different aspects: '{query}' These should be queries a user might ask when looking for similar information. Include different phrasings, related concepts, and specific aspects. Return as a JSON array of strings.""" # Use the LLM for query generation # Convert LLMConfig to dict if needed llm_config_dict = None if self.llm_config: if isinstance(self.llm_config, dict): llm_config_dict = self.llm_config else: # Convert LLMConfig object to dict llm_config_dict = { 'provider': self.llm_config.provider, 'api_token': self.llm_config.api_token } provider = llm_config_dict.get('provider', 'openai/gpt-4o-mini') if llm_config_dict else 'openai/gpt-4o-mini' api_token = llm_config_dict.get('api_token') if llm_config_dict else None response = perform_completion_with_backoff( provider=provider, prompt_with_variables=prompt, api_token=api_token, json_response=True ) variations = json.loads(response.choices[0].message.content) # # Mock data with more variations for split # variations ={'queries': ['what are the best vegetables to use in fried rice?', 'how do I make vegetable fried rice from scratch?', 'can you provide a quick recipe for vegetable fried rice?', 'what cooking techniques are essential for perfect fried rice with vegetables?', 'how to add flavor to vegetable fried rice?', 'are there any tips for making healthy fried rice with vegetables?']} # variations = {'queries': [ # 'How do async and await work with coroutines in Python?', # 'What is the role of event loops in asynchronous programming?', # 'Can you explain the differences between async/await and traditional callback methods?', # 'How do coroutines interact with event loops in JavaScript?', # 'What are the benefits of using async await over promises in Node.js?', # 'How to manage multiple coroutines with an event loop?', # 'What are some common pitfalls when using async await with coroutines?', # 'How do different programming languages implement async await and event loops?', # 'What happens when an async function is called without await?', # 'How does the event loop handle blocking operations?', # 'Can you nest async functions and how does that affect the event loop?', # 'What is the performance impact of using async/await?' # ]} # Split into train and validation # all_queries = [query] + variations['queries'] # Randomly shuffle for proper train/val split (keeping original query in training) import random # Keep original query always in training other_queries = variations['queries'].copy() random.shuffle(other_queries) # Split: 80% for training, 20% for validation n_validation = max(2, int(len(other_queries) * 0.2)) # At least 2 for validation val_queries = other_queries[-n_validation:] train_queries = [query] + other_queries[:-n_validation] # Embed only training queries for now (faster) train_embeddings = await self._get_embeddings(train_queries) # Store validation queries for later (don't embed yet to save time) self._validation_queries = val_queries return train_embeddings, train_queries def compute_coverage_shape(self, query_points: Any, alpha: float = 0.5): """Find the minimal shape that covers all query points using alpha shape""" try: if len(query_points) < 3: return None # For high-dimensional embeddings (e.g., 384-dim, 768-dim), # alpha shapes require exponentially more points than available. # Instead, use a statistical coverage model query_points = np.array(query_points) # Store coverage as centroid + radius model coverage = { 'center': np.mean(query_points, axis=0), 'std': np.std(query_points, axis=0), 'points': query_points, 'radius': np.max(np.linalg.norm(query_points - np.mean(query_points, axis=0), axis=1)) } return coverage except Exception: # Fallback if computation fails return None def _sample_boundary_points(self, shape, n_samples: int = 20) -> List[Any]: """Sample points from the boundary of a shape""" # Simplified implementation - in practice would sample from actual shape boundary # For now, return empty list if shape is None if shape is None: return [] # This is a placeholder - actual implementation would depend on shape type return [] def find_coverage_gaps(self, kb_embeddings: Any, query_embeddings: Any) -> List[Tuple[Any, float]]: """Calculate gap distances for all query variations using vectorized operations""" gaps = [] if kb_embeddings is None or len(kb_embeddings) == 0: # If no KB yet, all query points have maximum gap for q_emb in query_embeddings: gaps.append((q_emb, 1.0)) return gaps # Use cached distance matrix distance_matrix = self._get_cached_distance_matrix(query_embeddings, kb_embeddings) if distance_matrix is None: # Fallback for q_emb in query_embeddings: gaps.append((q_emb, 1.0)) return gaps # Find minimum distance for each query (vectorized) min_distances = np.min(distance_matrix, axis=1) # Create gaps list for i, q_emb in enumerate(query_embeddings): gaps.append((q_emb, min_distances[i])) return gaps async def select_links_for_expansion( self, candidate_links: List[Link], gaps: List[Tuple[Any, float]], kb_embeddings: Any ) -> List[Tuple[Link, float]]: """Select links that most efficiently fill the gaps""" from .utils import cosine_distance, cosine_similarity, get_text_embeddings import hashlib scored_links = [] # Prepare for embedding - separate cached vs uncached links_to_embed = [] texts_to_embed = [] link_embeddings_map = {} for link in candidate_links: # Extract text from link link_text = ' '.join(filter(None, [ link.text or '', link.title or '', link.meta.get('description', '') if hasattr(link, 'meta') and link.meta else '', link.head_data.get('meta', {}).get('description', '') if link.head_data else '' ])) if not link_text.strip(): continue # Create cache key from URL + text content cache_key = hashlib.md5(f"{link.href}:{link_text}".encode()).hexdigest() # Check cache if cache_key in self._link_embedding_cache: link_embeddings_map[link.href] = self._link_embedding_cache[cache_key] else: links_to_embed.append(link) texts_to_embed.append(link_text) # Batch embed only uncached links if texts_to_embed: embedding_llm_config = self._get_embedding_llm_config_dict() new_embeddings = await get_text_embeddings(texts_to_embed, embedding_llm_config, self.embedding_model) # Cache the new embeddings for link, text, embedding in zip(links_to_embed, texts_to_embed, new_embeddings): cache_key = hashlib.md5(f"{link.href}:{text}".encode()).hexdigest() self._link_embedding_cache[cache_key] = embedding link_embeddings_map[link.href] = embedding # Get coverage radius from config coverage_radius = self.config.embedding_coverage_radius if hasattr(self, 'config') else 0.2 # Score each link for link in candidate_links: if link.href not in link_embeddings_map: continue # Skip links without embeddings link_embedding = link_embeddings_map[link.href] if not gaps: score = 0.0 else: # Calculate how many gaps this link helps with gaps_helped = 0 total_improvement = 0 for gap_point, gap_distance in gaps: # Only consider gaps that actually need filling (outside coverage radius) if gap_distance > coverage_radius: new_distance = cosine_distance(link_embedding, gap_point) if new_distance < gap_distance: # This link helps this gap improvement = gap_distance - new_distance # Scale improvement - moving from 0.5 to 0.3 is valuable scaled_improvement = improvement * 2 # Amplify the signal total_improvement += scaled_improvement gaps_helped += 1 # Average improvement per gap that needs help gaps_needing_help = sum(1 for _, d in gaps if d > coverage_radius) if gaps_needing_help > 0: gap_reduction_score = total_improvement / gaps_needing_help else: gap_reduction_score = 0 # Check overlap with existing KB (vectorized) if kb_embeddings is not None and len(kb_embeddings) > 0: # Normalize embeddings link_norm = link_embedding / np.linalg.norm(link_embedding) kb_norm = kb_embeddings / np.linalg.norm(kb_embeddings, axis=1, keepdims=True) # Compute all similarities at once similarities = np.dot(kb_norm, link_norm) max_similarity = np.max(similarities) # Only penalize if very similar (above threshold) overlap_threshold = self.config.embedding_overlap_threshold if hasattr(self, 'config') else 0.85 if max_similarity > overlap_threshold: overlap_penalty = (max_similarity - overlap_threshold) * 2 # 0 to 0.3 range else: overlap_penalty = 0 else: overlap_penalty = 0 # Final score - emphasize gap reduction score = gap_reduction_score * (1 - overlap_penalty) # Add contextual score boost if available if hasattr(link, 'contextual_score') and link.contextual_score: score = score * 0.8 + link.contextual_score * 0.2 scored_links.append((link, score)) return sorted(scored_links, key=lambda x: x[1], reverse=True) async def calculate_confidence(self, state: CrawlState) -> float: """Coverage-based learning score (0โ€“1).""" # Guard clauses if state.kb_embeddings is None or state.query_embeddings is None: return 0.0 if len(state.kb_embeddings) == 0 or len(state.query_embeddings) == 0: return 0.0 # Prepare L2-normalised arrays Q = np.asarray(state.query_embeddings, dtype=np.float32) D = np.asarray(state.kb_embeddings, dtype=np.float32) Q /= np.linalg.norm(Q, axis=1, keepdims=True) + 1e-8 D /= np.linalg.norm(D, axis=1, keepdims=True) + 1e-8 # Best cosine per query best = (Q @ D.T).max(axis=1) # Mean similarity or hit-rate above tau tau = getattr(self.config, 'coverage_tau', None) score = float((best >= tau).mean()) if tau is not None else float(best.mean()) # Store quick metrics state.metrics['coverage_score'] = score state.metrics['avg_best_similarity'] = float(best.mean()) state.metrics['median_best_similarity'] = float(np.median(best)) return score # async def calculate_confidence(self, state: CrawlState) -> float: # """Calculate learning score for adaptive crawling (used for stopping)""" # # if state.kb_embeddings is None or state.query_embeddings is None: # return 0.0 # if len(state.kb_embeddings) == 0: # return 0.0 # # Get cached distance matrix # distance_matrix = self._get_cached_distance_matrix(state.query_embeddings, state.kb_embeddings) # if distance_matrix is None: # return 0.0 # # Vectorized analysis for all queries at once # all_query_metrics = [] # for i in range(len(state.query_embeddings)): # # Get distances for this query # distances = distance_matrix[i] # sorted_distances = np.sort(distances) # # Store metrics for this query # query_metric = { # 'min_distance': sorted_distances[0], # 'top_3_distances': sorted_distances[:3], # 'top_5_distances': sorted_distances[:5], # 'close_neighbors': np.sum(distances < 0.3), # 'very_close_neighbors': np.sum(distances < 0.2), # 'all_distances': distances # } # all_query_metrics.append(query_metric) # # Hybrid approach with density (exponential base) # k_exp = self.config.embedding_k_exp if hasattr(self, 'config') else 1.0 # coverage_scores_hybrid_exp = [] # for metric in all_query_metrics: # # Base score from nearest neighbor # nearest_score = np.exp(-k_exp * metric['min_distance']) # # Top-k average (top 3) # top_k = min(3, len(metric['all_distances'])) # top_k_avg = np.mean([np.exp(-k_exp * d) for d in metric['top_3_distances'][:top_k]]) # # Combine using configured weights # nearest_weight = self.config.embedding_nearest_weight if hasattr(self, 'config') else 0.7 # top_k_weight = self.config.embedding_top_k_weight if hasattr(self, 'config') else 0.3 # hybrid_score = nearest_weight * nearest_score + top_k_weight * top_k_avg # coverage_scores_hybrid_exp.append(hybrid_score) # learning_score = np.mean(coverage_scores_hybrid_exp) # # Store as learning score # state.metrics['learning_score'] = learning_score # # Store embedding-specific metrics # state.metrics['avg_min_distance'] = np.mean([m['min_distance'] for m in all_query_metrics]) # state.metrics['avg_close_neighbors'] = np.mean([m['close_neighbors'] for m in all_query_metrics]) # state.metrics['avg_very_close_neighbors'] = np.mean([m['very_close_neighbors'] for m in all_query_metrics]) # state.metrics['total_kb_docs'] = len(state.kb_embeddings) # # Store query-level metrics for detailed analysis # self._query_metrics = all_query_metrics # # For stopping criteria, return learning score # return float(learning_score) async def rank_links(self, state: CrawlState, config: AdaptiveConfig) -> List[Tuple[Link, float]]: """Main entry point for link ranking""" # Store config for use in other methods self.config = config # Filter out already crawled URLs and remove duplicates seen_urls = set() uncrawled_links = [] for link in state.pending_links: if link.href not in state.crawled_urls and link.href not in seen_urls: uncrawled_links.append(link) seen_urls.add(link.href) if not uncrawled_links: return [] # Get gaps in coverage (no threshold needed anymore) gaps = self.find_coverage_gaps( state.kb_embeddings, state.query_embeddings ) state.semantic_gaps = [(g[0].tolist(), g[1]) for g in gaps] # Store as list for serialization # Select links that fill gaps (only from uncrawled) return await self.select_links_for_expansion( uncrawled_links, gaps, state.kb_embeddings ) async def validate_coverage(self, state: CrawlState) -> float: """Validate coverage using held-out queries with caching""" if not hasattr(self, '_validation_queries') or not self._validation_queries: return state.metrics.get('confidence', 0.0) # Cache validation embeddings (only embed once!) if self._validation_embeddings_cache is None: self._validation_embeddings_cache = await self._get_embeddings(self._validation_queries) val_embeddings = self._validation_embeddings_cache # Use vectorized distance computation if state.kb_embeddings is None or len(state.kb_embeddings) == 0: return 0.0 # Compute distance matrix for validation queries distance_matrix = self._compute_distance_matrix(val_embeddings, state.kb_embeddings) if distance_matrix is None: return 0.0 # Find minimum distance for each validation query (vectorized) min_distances = np.min(distance_matrix, axis=1) scores = 1.0 - min_distances # Convert distances to scores (0-1 range) # Compute scores using same exponential as training # k_exp = self.config.embedding_k_exp if hasattr(self, 'config') else 1.0 # scores = np.exp(-k_exp * min_distances) validation_confidence = np.mean(scores) state.metrics['validation_confidence'] = validation_confidence return validation_confidence async def should_stop(self, state: CrawlState, config: AdaptiveConfig) -> bool: """Stop based on learning curve convergence""" confidence = state.metrics.get('confidence', 0.0) # Check if confidence is below minimum threshold (completely irrelevant) min_confidence_threshold = config.embedding_min_confidence_threshold if hasattr(config, 'embedding_min_confidence_threshold') else 0.1 if confidence < min_confidence_threshold and len(state.crawled_urls) > 0: state.metrics['stopped_reason'] = 'below_minimum_relevance_threshold' state.metrics['is_irrelevant'] = True return True # Basic limits if len(state.crawled_urls) >= config.max_pages or not state.pending_links: return True # Track confidence history if not hasattr(state, 'confidence_history'): state.confidence_history = [] state.confidence_history.append(confidence) # Need at least 3 iterations to check convergence if len(state.confidence_history) < 2: return False improvement_diffs = list(zip(state.confidence_history[:-1], state.confidence_history[1:])) # Calculate average improvement avg_improvement = sum(abs(b - a) for a, b in improvement_diffs) / len(improvement_diffs) state.metrics['avg_improvement'] = avg_improvement min_relative_improvement = self.config.embedding_min_relative_improvement * confidence if hasattr(self, 'config') else 0.1 * confidence if avg_improvement < min_relative_improvement: # Converged - validate before stopping val_score = await self.validate_coverage(state) # Only stop if validation is reasonable validation_min = self.config.embedding_validation_min_score if hasattr(self, 'config') else 0.4 # k_exp = self.config.embedding_k_exp if hasattr(self, 'config') else 1.0 # validation_min = np.exp(-k_exp * validation_min) if val_score > validation_min: state.metrics['stopped_reason'] = 'converged_validated' self._validation_passed = True return True else: state.metrics['stopped_reason'] = 'low_validation' # Continue crawling despite convergence return False def get_quality_confidence(self, state: CrawlState) -> float: """Calculate quality-based confidence score for display""" learning_score = state.metrics.get('learning_score', 0.0) validation_score = state.metrics.get('validation_confidence', 0.0) # Get config values validation_min = self.config.embedding_validation_min_score if hasattr(self, 'config') else 0.4 quality_min = self.config.embedding_quality_min_confidence if hasattr(self, 'config') else 0.7 quality_max = self.config.embedding_quality_max_confidence if hasattr(self, 'config') else 0.95 scale_factor = self.config.embedding_quality_scale_factor if hasattr(self, 'config') else 0.833 if self._validation_passed and validation_score > validation_min: # Validated systems get boosted scores # Map 0.4-0.7 learning โ†’ quality_min-quality_max confidence if learning_score < 0.4: confidence = quality_min # Minimum for validated systems elif learning_score > 0.7: confidence = quality_max # Maximum realistic confidence else: # Linear mapping in between confidence = quality_min + (learning_score - 0.4) * scale_factor else: # Not validated = conservative mapping confidence = learning_score * 0.8 return confidence async def update_state(self, state: CrawlState, new_results: List[CrawlResult]) -> None: """Update embeddings and coverage metrics with deduplication""" from .utils import get_text_embeddings # Extract text from results new_texts = [] valid_results = [] for result in new_results: content = result.markdown.raw_markdown if hasattr(result, 'markdown') and result.markdown else "" if content: # Only process non-empty content new_texts.append(content[:5000]) # Limit text length valid_results.append(result) if not new_texts: return # Get embeddings for new texts embedding_llm_config = self._get_embedding_llm_config_dict() new_embeddings = await get_text_embeddings(new_texts, embedding_llm_config, self.embedding_model) # Deduplicate embeddings before adding to KB if state.kb_embeddings is None: # First batch - no deduplication needed state.kb_embeddings = new_embeddings deduplicated_indices = list(range(len(new_embeddings))) else: # Check for duplicates using vectorized similarity deduplicated_embeddings = [] deduplicated_indices = [] for i, new_emb in enumerate(new_embeddings): # Compute similarities with existing KB new_emb_normalized = new_emb / np.linalg.norm(new_emb) kb_normalized = state.kb_embeddings / np.linalg.norm(state.kb_embeddings, axis=1, keepdims=True) similarities = np.dot(kb_normalized, new_emb_normalized) # Only add if not too similar to existing content if np.max(similarities) < self._kb_similarity_threshold: deduplicated_embeddings.append(new_emb) deduplicated_indices.append(i) # Add deduplicated embeddings if deduplicated_embeddings: state.kb_embeddings = np.vstack([state.kb_embeddings, np.array(deduplicated_embeddings)]) # Update crawl order only for non-duplicate results for idx in deduplicated_indices: state.crawl_order.append(valid_results[idx].url) # Invalidate distance matrix cache since KB changed self._kb_embeddings_hash = None self._distance_matrix_cache = None # Update coverage shape if needed if hasattr(state, 'query_embeddings') and state.query_embeddings is not None: state.coverage_shape = self.compute_coverage_shape(state.query_embeddings, self.config.alpha_shape_alpha if hasattr(self, 'config') else 0.5) class AdaptiveCrawler: """Main adaptive crawler that orchestrates the crawling process""" def __init__(self, crawler: Optional[AsyncWebCrawler] = None, config: Optional[AdaptiveConfig] = None, strategy: Optional[CrawlStrategy] = None): self.crawler = crawler self.config = config or AdaptiveConfig() self.config.validate() # Create strategy based on config if strategy: self.strategy = strategy else: self.strategy = self._create_strategy(self.config.strategy) # Initialize state self.state: Optional[CrawlState] = None # Track if we own the crawler (for cleanup) self._owns_crawler = crawler is None def _create_strategy(self, strategy_name: str) -> CrawlStrategy: """Create strategy instance based on name""" if strategy_name == "statistical": return StatisticalStrategy() elif strategy_name == "embedding": strategy = EmbeddingStrategy( embedding_model=self.config.embedding_model, llm_config=self.config.embedding_llm_config ) strategy.config = self.config # Pass config to strategy return strategy else: raise ValueError(f"Unknown strategy: {strategy_name}") async def digest(self, start_url: str, query: str, resume_from: Optional[str] = None) -> CrawlState: """Main entry point for adaptive crawling""" # Initialize or resume state if resume_from: self.state = CrawlState.load(resume_from) self.state.query = query # Update query in case it changed else: self.state = CrawlState( crawled_urls=set(), knowledge_base=[], pending_links=[], query=query, metrics={} ) # Create crawler if needed if not self.crawler: self.crawler = AsyncWebCrawler() await self.crawler.__aenter__() self.strategy.config = self.config # Pass config to strategy # If using embedding strategy and not resuming, expand query space if isinstance(self.strategy, EmbeddingStrategy) and not resume_from: # Generate query space query_embeddings, expanded_queries = await self.strategy.map_query_semantic_space( query, self.config.n_query_variations ) self.state.query_embeddings = query_embeddings self.state.expanded_queries = expanded_queries[1:] # Skip original query self.state.embedding_model = self.strategy.embedding_model try: # Initial crawl if not resuming if start_url not in self.state.crawled_urls: result = await self._crawl_with_preview(start_url, query) if result and hasattr(result, 'success') and result.success: self.state.knowledge_base.append(result) self.state.crawled_urls.add(start_url) # Extract links from result - handle both dict and Links object formats if hasattr(result, 'links') and result.links: if isinstance(result.links, dict): # Extract internal and external links from dict internal_links = [Link(**link) for link in result.links.get('internal', [])] external_links = [Link(**link) for link in result.links.get('external', [])] self.state.pending_links.extend(internal_links + external_links) else: # Handle Links object self.state.pending_links.extend(result.links.internal + result.links.external) # Update state await self.strategy.update_state(self.state, [result]) # adaptive expansion depth = 0 while depth < self.config.max_depth: # Calculate confidence confidence = await self.strategy.calculate_confidence(self.state) self.state.metrics['confidence'] = confidence # Check stopping criteria if await self.strategy.should_stop(self.state, self.config): break # Rank candidate links ranked_links = await self.strategy.rank_links(self.state, self.config) if not ranked_links: break # Check minimum gain threshold if ranked_links[0][1] < self.config.min_gain_threshold: break # Select top K links to_crawl = [(link, score) for link, score in ranked_links[:self.config.top_k_links] if link.href not in self.state.crawled_urls] if not to_crawl: break # Crawl selected links new_results = await self._crawl_batch(to_crawl, query) if new_results: # Update knowledge base self.state.knowledge_base.extend(new_results) # Update crawled URLs and pending links for result, (link, _) in zip(new_results, to_crawl): if result: self.state.crawled_urls.add(link.href) # Extract links from result - handle both dict and Links object formats if hasattr(result, 'links') and result.links: new_links = [] if isinstance(result.links, dict): # Extract internal and external links from dict internal_links = [Link(**link_data) for link_data in result.links.get('internal', [])] external_links = [Link(**link_data) for link_data in result.links.get('external', [])] new_links = internal_links + external_links else: # Handle Links object new_links = result.links.internal + result.links.external # Add new links to pending for new_link in new_links: if new_link.href not in self.state.crawled_urls: self.state.pending_links.append(new_link) # Update state with new results await self.strategy.update_state(self.state, new_results) depth += 1 # Save state if configured if self.config.save_state and self.config.state_path: self.state.save(self.config.state_path) # Final confidence calculation learning_score = await self.strategy.calculate_confidence(self.state) # For embedding strategy, get quality-based confidence if isinstance(self.strategy, EmbeddingStrategy): self.state.metrics['confidence'] = self.strategy.get_quality_confidence(self.state) else: # For statistical strategy, use the same as before self.state.metrics['confidence'] = learning_score self.state.metrics['pages_crawled'] = len(self.state.crawled_urls) self.state.metrics['depth_reached'] = depth # Final save if self.config.save_state and self.config.state_path: self.state.save(self.config.state_path) return self.state finally: # Cleanup if we created the crawler if self._owns_crawler and self.crawler: await self.crawler.__aexit__(None, None, None) async def _crawl_with_preview(self, url: str, query: str) -> Optional[CrawlResult]: """Crawl a URL with link preview enabled""" config = CrawlerRunConfig( link_preview_config=LinkPreviewConfig( include_internal=True, include_external=False, query=query, # For BM25 scoring concurrency=5, timeout=5, max_links=50, # Reasonable limit verbose=False ), score_links=True # Enable intrinsic scoring ) try: result = await self.crawler.arun(url=url, config=config) # Extract the actual CrawlResult from the container if hasattr(result, '_results') and result._results: result = result._results[0] # Filter our all links do not have head_date if hasattr(result, 'links') and result.links: result.links['internal'] = [link for link in result.links['internal'] if link.get('head_data')] # For now let's ignore external links without head_data # result.links['external'] = [link for link in result.links['external'] if link.get('head_data')] return result except Exception as e: print(f"Error crawling {url}: {e}") return None async def _crawl_batch(self, links_with_scores: List[Tuple[Link, float]], query: str) -> List[CrawlResult]: """Crawl multiple URLs in parallel""" tasks = [] for link, score in links_with_scores: task = self._crawl_with_preview(link.href, query) tasks.append(task) results = await asyncio.gather(*tasks, return_exceptions=True) # Filter out exceptions and failed crawls valid_results = [] for result in results: if isinstance(result, CrawlResult): # Only include successful crawls if hasattr(result, 'success') and result.success: valid_results.append(result) else: print(f"Skipping failed crawl: {result.url if hasattr(result, 'url') else 'unknown'}") elif isinstance(result, Exception): print(f"Error in batch crawl: {result}") return valid_results # Status properties @property def confidence(self) -> float: """Current confidence level""" if self.state: return self.state.metrics.get('confidence', 0.0) return 0.0 @property def coverage_stats(self) -> Dict[str, Any]: """Detailed coverage statistics""" if not self.state: return {} total_content_length = sum( len(result.markdown.raw_markdown or "") for result in self.state.knowledge_base ) return { 'pages_crawled': len(self.state.crawled_urls), 'total_content_length': total_content_length, 'unique_terms': len(self.state.term_frequencies), 'total_terms': sum(self.state.term_frequencies.values()), 'pending_links': len(self.state.pending_links), 'confidence': self.confidence, 'coverage': self.state.metrics.get('coverage', 0.0), 'consistency': self.state.metrics.get('consistency', 0.0), 'saturation': self.state.metrics.get('saturation', 0.0) } @property def is_sufficient(self) -> bool: """Check if current knowledge is sufficient""" if isinstance(self.strategy, EmbeddingStrategy): # For embedding strategy, sufficient = validation passed return self.strategy._validation_passed else: # For statistical strategy, use threshold return self.confidence >= self.config.confidence_threshold def print_stats(self, detailed: bool = False) -> None: """Print comprehensive statistics about the knowledge base Args: detailed: If True, show detailed statistics including top terms """ if not self.state: print("No crawling state available.") return # Import here to avoid circular imports try: from rich.console import Console from rich.table import Table console = Console() use_rich = True except ImportError: use_rich = False if not detailed and use_rich: # Summary view with nice table (like original) table = Table(title=f"Adaptive Crawl Stats - Query: '{self.state.query}'") table.add_column("Metric", style="cyan", no_wrap=True) table.add_column("Value", style="magenta") # Basic stats stats = self.coverage_stats table.add_row("Pages Crawled", str(stats.get('pages_crawled', 0))) table.add_row("Unique Terms", str(stats.get('unique_terms', 0))) table.add_row("Total Terms", str(stats.get('total_terms', 0))) table.add_row("Content Length", f"{stats.get('total_content_length', 0):,} chars") table.add_row("Pending Links", str(stats.get('pending_links', 0))) table.add_row("", "") # Spacer # Strategy-specific metrics if isinstance(self.strategy, EmbeddingStrategy): # Embedding-specific metrics table.add_row("Confidence", f"{stats.get('confidence', 0):.2%}") table.add_row("Avg Min Distance", f"{self.state.metrics.get('avg_min_distance', 0):.3f}") table.add_row("Avg Close Neighbors", f"{self.state.metrics.get('avg_close_neighbors', 0):.1f}") table.add_row("Validation Score", f"{self.state.metrics.get('validation_confidence', 0):.2%}") table.add_row("", "") # Spacer table.add_row("Is Sufficient?", "[green]Yes (Validated)[/green]" if self.is_sufficient else "[red]No[/red]") else: # Statistical strategy metrics table.add_row("Confidence", f"{stats.get('confidence', 0):.2%}") table.add_row("Coverage", f"{stats.get('coverage', 0):.2%}") table.add_row("Consistency", f"{stats.get('consistency', 0):.2%}") table.add_row("Saturation", f"{stats.get('saturation', 0):.2%}") table.add_row("", "") # Spacer table.add_row("Is Sufficient?", "[green]Yes[/green]" if self.is_sufficient else "[red]No[/red]") console.print(table) else: # Detailed view or fallback when rich not available print("\n" + "="*80) print(f"Adaptive Crawl Statistics - Query: '{self.state.query}'") print("="*80) # Basic stats print("\n[*] Basic Statistics:") print(f" Pages Crawled: {len(self.state.crawled_urls)}") print(f" Pending Links: {len(self.state.pending_links)}") print(f" Total Documents: {self.state.total_documents}") # Content stats total_content_length = sum( len(self._get_content_from_result(result)) for result in self.state.knowledge_base ) total_words = sum(self.state.term_frequencies.values()) unique_terms = len(self.state.term_frequencies) print(f"\n[*] Content Statistics:") print(f" Total Content: {total_content_length:,} characters") print(f" Total Words: {total_words:,}") print(f" Unique Terms: {unique_terms:,}") if total_words > 0: print(f" Vocabulary Richness: {unique_terms/total_words:.2%}") # Strategy-specific output if isinstance(self.strategy, EmbeddingStrategy): # Semantic coverage for embedding strategy print(f"\n[*] Semantic Coverage Analysis:") print(f" Average Min Distance: {self.state.metrics.get('avg_min_distance', 0):.3f}") print(f" Avg Close Neighbors (< 0.3): {self.state.metrics.get('avg_close_neighbors', 0):.1f}") print(f" Avg Very Close Neighbors (< 0.2): {self.state.metrics.get('avg_very_close_neighbors', 0):.1f}") # Confidence metrics print(f"\n[*] Confidence Metrics:") if self.is_sufficient: if use_rich: console.print(f" Overall Confidence: {self.confidence:.2%} [green][VALIDATED][/green]") else: print(f" Overall Confidence: {self.confidence:.2%} [VALIDATED]") else: if use_rich: console.print(f" Overall Confidence: {self.confidence:.2%} [red][NOT VALIDATED][/red]") else: print(f" Overall Confidence: {self.confidence:.2%} [NOT VALIDATED]") print(f" Learning Score: {self.state.metrics.get('learning_score', 0):.2%}") print(f" Validation Score: {self.state.metrics.get('validation_confidence', 0):.2%}") else: # Query coverage for statistical strategy print(f"\n[*] Query Coverage:") query_terms = self.strategy._tokenize(self.state.query.lower()) for term in query_terms: tf = self.state.term_frequencies.get(term, 0) df = self.state.document_frequencies.get(term, 0) if df > 0: if use_rich: console.print(f" '{term}': found in {df}/{self.state.total_documents} docs ([green]{df/self.state.total_documents:.0%}[/green]), {tf} occurrences") else: print(f" '{term}': found in {df}/{self.state.total_documents} docs ({df/self.state.total_documents:.0%}), {tf} occurrences") else: if use_rich: console.print(f" '{term}': [red][X] not found[/red]") else: print(f" '{term}': [X] not found") # Confidence metrics print(f"\n[*] Confidence Metrics:") status = "[OK]" if self.is_sufficient else "[!!]" if use_rich: status_colored = "[green][OK][/green]" if self.is_sufficient else "[red][!!][/red]" console.print(f" Overall Confidence: {self.confidence:.2%} {status_colored}") else: print(f" Overall Confidence: {self.confidence:.2%} {status}") print(f" Coverage Score: {self.state.metrics.get('coverage', 0):.2%}") print(f" Consistency Score: {self.state.metrics.get('consistency', 0):.2%}") print(f" Saturation Score: {self.state.metrics.get('saturation', 0):.2%}") # Crawl efficiency if self.state.new_terms_history: avg_new_terms = sum(self.state.new_terms_history) / len(self.state.new_terms_history) print(f"\n[*] Crawl Efficiency:") print(f" Avg New Terms per Page: {avg_new_terms:.1f}") print(f" Information Saturation: {self.state.metrics.get('saturation', 0):.2%}") if detailed: print("\n" + "-"*80) if use_rich: console.print("[bold cyan]DETAILED STATISTICS[/bold cyan]") else: print("DETAILED STATISTICS") print("-"*80) # Top terms print("\n[+] Top 20 Terms by Frequency:") top_terms = sorted(self.state.term_frequencies.items(), key=lambda x: x[1], reverse=True)[:20] for i, (term, freq) in enumerate(top_terms, 1): df = self.state.document_frequencies.get(term, 0) if use_rich: console.print(f" {i:2d}. [yellow]'{term}'[/yellow]: {freq} occurrences in {df} docs") else: print(f" {i:2d}. '{term}': {freq} occurrences in {df} docs") # URLs crawled print(f"\n[+] URLs Crawled ({len(self.state.crawled_urls)}):") for i, url in enumerate(self.state.crawl_order, 1): new_terms = self.state.new_terms_history[i-1] if i <= len(self.state.new_terms_history) else 0 if use_rich: console.print(f" {i}. [cyan]{url}[/cyan]") console.print(f" -> Added [green]{new_terms}[/green] new terms") else: print(f" {i}. {url}") print(f" -> Added {new_terms} new terms") # Document frequency distribution print("\n[+] Document Frequency Distribution:") df_counts = {} for df in self.state.document_frequencies.values(): df_counts[df] = df_counts.get(df, 0) + 1 for df in sorted(df_counts.keys()): count = df_counts[df] print(f" Terms in {df} docs: {count} terms") # Embedding stats if self.state.embedding_model: print("\n[+] Semantic Coverage Analysis:") print(f" Embedding Model: {self.state.embedding_model}") print(f" Query Variations: {len(self.state.expanded_queries)}") if self.state.kb_embeddings is not None: print(f" Knowledge Embeddings: {self.state.kb_embeddings.shape}") else: print(f" Knowledge Embeddings: None") print(f" Semantic Gaps: {len(self.state.semantic_gaps)}") print(f" Coverage Achievement: {self.confidence:.2%}") # Show sample expanded queries if self.state.expanded_queries: print("\n[+] Query Space (samples):") for i, eq in enumerate(self.state.expanded_queries[:5], 1): if use_rich: console.print(f" {i}. [yellow]{eq}[/yellow]") else: print(f" {i}. {eq}") print("\n" + "="*80) def _get_content_from_result(self, result) -> str: """Helper to safely extract content from result""" if hasattr(result, 'markdown') and result.markdown: if hasattr(result.markdown, 'raw_markdown'): return result.markdown.raw_markdown or "" return str(result.markdown) return "" def export_knowledge_base(self, filepath: Union[str, Path], format: str = "jsonl") -> None: """Export the knowledge base to a file Args: filepath: Path to save the file format: Export format - currently supports 'jsonl' """ if not self.state or not self.state.knowledge_base: print("No knowledge base to export.") return filepath = Path(filepath) filepath.parent.mkdir(parents=True, exist_ok=True) if format == "jsonl": # Export as JSONL - one CrawlResult per line with open(filepath, 'w', encoding='utf-8') as f: for result in self.state.knowledge_base: # Convert CrawlResult to dict result_dict = self._crawl_result_to_export_dict(result) # Write as single line JSON f.write(json.dumps(result_dict, ensure_ascii=False) + '\n') print(f"Exported {len(self.state.knowledge_base)} documents to {filepath}") else: raise ValueError(f"Unsupported export format: {format}") def _crawl_result_to_export_dict(self, result) -> Dict[str, Any]: """Convert CrawlResult to a dictionary for export""" # Extract all available fields export_dict = { 'url': getattr(result, 'url', ''), 'timestamp': getattr(result, 'timestamp', None), 'success': getattr(result, 'success', True), 'query': self.state.query if self.state else '', } # Extract content if hasattr(result, 'markdown') and result.markdown: if hasattr(result.markdown, 'raw_markdown'): export_dict['content'] = result.markdown.raw_markdown else: export_dict['content'] = str(result.markdown) else: export_dict['content'] = '' # Extract metadata if hasattr(result, 'metadata'): export_dict['metadata'] = result.metadata # Extract links if available if hasattr(result, 'links'): export_dict['links'] = result.links # Add crawl-specific metadata if self.state: export_dict['crawl_metadata'] = { 'crawl_order': self.state.crawl_order.index(export_dict['url']) + 1 if export_dict['url'] in self.state.crawl_order else 0, 'confidence_at_crawl': self.state.metrics.get('confidence', 0), 'total_documents': self.state.total_documents } return export_dict def import_knowledge_base(self, filepath: Union[str, Path], format: str = "jsonl") -> None: """Import a knowledge base from a file Args: filepath: Path to the file to import format: Import format - currently supports 'jsonl' """ filepath = Path(filepath) if not filepath.exists(): raise FileNotFoundError(f"File not found: {filepath}") if format == "jsonl": imported_results = [] with open(filepath, 'r', encoding='utf-8') as f: for line in f: if line.strip(): data = json.loads(line) # Convert back to a mock CrawlResult mock_result = self._import_dict_to_crawl_result(data) imported_results.append(mock_result) # Initialize state if needed if not self.state: self.state = CrawlState() # Add imported results self.state.knowledge_base.extend(imported_results) # Update state with imported data asyncio.run(self.strategy.update_state(self.state, imported_results)) print(f"Imported {len(imported_results)} documents from {filepath}") else: raise ValueError(f"Unsupported import format: {format}") def _import_dict_to_crawl_result(self, data: Dict[str, Any]): """Convert imported dict back to a mock CrawlResult""" class MockMarkdown: def __init__(self, content): self.raw_markdown = content class MockCrawlResult: def __init__(self, data): self.url = data.get('url', '') self.markdown = MockMarkdown(data.get('content', '')) self.links = data.get('links', {}) self.metadata = data.get('metadata', {}) self.success = data.get('success', True) self.timestamp = data.get('timestamp') return MockCrawlResult(data) def get_relevant_content(self, top_k: int = 5) -> List[Dict[str, Any]]: """Get most relevant content for the query""" if not self.state or not self.state.knowledge_base: return [] # Simple relevance ranking based on term overlap scored_docs = [] query_terms = set(self.state.query.lower().split()) for i, result in enumerate(self.state.knowledge_base): content = (result.markdown.raw_markdown or "").lower() content_terms = set(content.split()) # Calculate relevance score overlap = len(query_terms & content_terms) score = overlap / len(query_terms) if query_terms else 0.0 scored_docs.append({ 'url': result.url, 'score': score, 'content': result.markdown.raw_markdown, 'index': i }) # Sort by score and return top K scored_docs.sort(key=lambda x: x['score'], reverse=True) return scored_docs[:top_k]
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/adaptive_crawler.py", "license": "Apache License 2.0", "lines": 1531, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:crawl4ai/async_url_seeder.py
""" async_url_seeder.py Fast async URL discovery for Crawl4AI Features -------- * Common-Crawl streaming via httpx.AsyncClient (HTTP/2, keep-alive) * robots.txt โ†’ sitemap chain (.gz + nested indexes) via async httpx * Per-domain CDX result cache on disk (~/.crawl4ai/<index>_<domain>_<hash>.jsonl) * Optional HEAD-only liveness check * Optional partial <head> download + meta parsing * Global hits-per-second rate-limit via asyncio.Semaphore * Concurrency in the thousands โ€” fine on a single event-loop """ from __future__ import annotations import aiofiles import asyncio import gzip import hashlib import io import json import os import pathlib import re import time from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Sequence, Union from urllib.parse import quote, urljoin import httpx import fnmatch try: from lxml import html as lxml_html from lxml import etree LXML = True except ImportError: LXML = False try: import brotli HAS_BROTLI = True except ImportError: HAS_BROTLI = False try: import rank_bm25 HAS_BM25 = True except ImportError: HAS_BM25 = False # Import AsyncLoggerBase from crawl4ai's logger module # Assuming crawl4ai/async_logger.py defines AsyncLoggerBase # You might need to adjust this import based on your exact file structure # Import AsyncLogger for default if needed from .async_logger import AsyncLoggerBase, AsyncLogger # Import SeedingConfig for type hints from typing import TYPE_CHECKING if TYPE_CHECKING: from .async_configs import SeedingConfig # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ consts COLLINFO_URL = "https://index.commoncrawl.org/collinfo.json" # CACHE_DIR = pathlib.Path("~/.crawl4ai").expanduser() # REMOVED: now managed by __init__ # CACHE_DIR.mkdir(exist_ok=True) # REMOVED: now managed by __init__ # INDEX_CACHE = CACHE_DIR / "latest_cc_index.txt" # REMOVED: now managed by __init__ TTL = timedelta(days=7) # Keeping this constant as it's a seeder-specific TTL _meta_rx = re.compile( r'<meta\s+(?:[^>]*?(?:name|property|http-equiv)\s*=\s*["\']?([^"\' >]+)[^>]*?content\s*=\s*["\']?([^"\' >]+)[^>]*?)\/?>', re.I) _charset_rx = re.compile(r'<meta\s+[^>]*charset=["\']?([^"\' >]+)', re.I) _title_rx = re.compile(r'<title>(.*?)</title>', re.I | re.S) _link_rx = re.compile( r'<link\s+[^>]*rel=["\']?([^"\' >]+)[^>]*href=["\']?([^"\' >]+)', re.I) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ helpers def _parse_sitemap_lastmod(xml_content: bytes) -> Optional[str]: """Extract the most recent lastmod from sitemap XML.""" try: if LXML: root = etree.fromstring(xml_content) # Get all lastmod elements (namespace-agnostic) lastmods = root.xpath("//*[local-name()='lastmod']/text()") if lastmods: # Return the most recent one return max(lastmods) except Exception: pass return None def _is_cache_valid( cache_path: pathlib.Path, ttl_hours: int, validate_lastmod: bool, current_lastmod: Optional[str] = None ) -> bool: """ Check if sitemap cache is still valid. Returns False (invalid) if: - File doesn't exist - File is corrupted/unreadable - TTL expired (if ttl_hours > 0) - Sitemap lastmod is newer than cache (if validate_lastmod=True) """ if not cache_path.exists(): return False try: with open(cache_path, "r") as f: data = json.load(f) # Check version if data.get("version") != 1: return False # Check TTL if ttl_hours > 0: created_at = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00")) age_hours = (datetime.now(timezone.utc) - created_at).total_seconds() / 3600 if age_hours > ttl_hours: return False # Check lastmod if validate_lastmod and current_lastmod: cached_lastmod = data.get("sitemap_lastmod") if cached_lastmod and current_lastmod > cached_lastmod: return False # Check URL count (sanity check - if 0, likely corrupted) if data.get("url_count", 0) == 0: return False return True except (json.JSONDecodeError, KeyError, ValueError, IOError): # Corrupted cache - return False to trigger refetch return False def _read_cache(cache_path: pathlib.Path) -> List[str]: """Read URLs from cache file. Returns empty list on error.""" try: with open(cache_path, "r") as f: data = json.load(f) return data.get("urls", []) except Exception: return [] def _write_cache( cache_path: pathlib.Path, urls: List[str], sitemap_url: str, sitemap_lastmod: Optional[str] ) -> None: """Write URLs to cache with metadata.""" data = { "version": 1, "created_at": datetime.now(timezone.utc).isoformat(), "sitemap_lastmod": sitemap_lastmod, "sitemap_url": sitemap_url, "url_count": len(urls), "urls": urls } try: with open(cache_path, "w") as f: json.dump(data, f) except Exception: pass # Fail silently - cache is optional def _match(url: str, pattern: str) -> bool: if fnmatch.fnmatch(url, pattern): return True canon = url.split("://", 1)[-1] return (fnmatch.fnmatch(canon, pattern) or (canon.startswith("www.") and fnmatch.fnmatch(canon[4:], pattern))) def _parse_head(src: str) -> Dict[str, Any]: if LXML: try: if isinstance(src, str): # strip Unicode, let lxml decode src = src.encode("utf-8", "replace") doc = lxml_html.fromstring(src) except (ValueError, etree.ParserError): return {} # malformed, bail gracefully info: Dict[str, Any] = { "title": (doc.find(".//title").text or "").strip() if doc.find(".//title") is not None else None, "charset": None, "meta": {}, "link": {}, "jsonld": [] } for el in doc.xpath(".//meta"): k = el.attrib.get("name") or el.attrib.get( "property") or el.attrib.get("http-equiv") if k: info["meta"][k.lower()] = el.attrib.get("content", "") elif "charset" in el.attrib: info["charset"] = el.attrib["charset"].lower() for el in doc.xpath(".//link"): rel_attr = el.attrib.get("rel", "") if not rel_attr: continue # Handle multiple space-separated rel values rel_values = rel_attr.lower().split() entry = {a: el.attrib[a] for a in ( "href", "as", "type", "hreflang") if a in el.attrib} # Add entry for each rel value for rel in rel_values: info["link"].setdefault(rel, []).append(entry) # Extract JSON-LD structured data for script in doc.xpath('.//script[@type="application/ld+json"]'): if script.text: try: jsonld_data = json.loads(script.text.strip()) info["jsonld"].append(jsonld_data) except json.JSONDecodeError: pass # Extract html lang attribute html_elem = doc.find(".//html") if html_elem is not None: info["lang"] = html_elem.attrib.get("lang", "") return info # regex fallback info: Dict[str, Any] = {"title": None, "charset": None, "meta": {}, "link": {}, "jsonld": [], "lang": ""} m = _title_rx.search(src) info["title"] = m.group(1).strip() if m else None for k, v in _meta_rx.findall(src): info["meta"][k.lower()] = v m = _charset_rx.search(src) info["charset"] = m.group(1).lower() if m else None for rel, href in _link_rx.findall(src): info["link"].setdefault(rel.lower(), []).append({"href": href}) # Try to extract JSON-LD with regex jsonld_pattern = re.compile( r'<script[^>]*type=["\']application/ld\+json["\'][^>]*>(.*?)</script>', re.I | re.S) for match in jsonld_pattern.findall(src): try: jsonld_data = json.loads(match.strip()) info["jsonld"].append(jsonld_data) except json.JSONDecodeError: pass # Try to extract lang attribute lang_match = re.search(r'<html[^>]*lang=["\']?([^"\' >]+)', src, re.I) if lang_match: info["lang"] = lang_match.group(1) return info # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ class class AsyncUrlSeeder: """ Async version of UrlSeeder. Call pattern is await/async for / async with. Public coroutines ----------------- await seed.urls(...) returns List[Dict[str,Any]] (url, status, head_data) await seed.many_urls(...) returns Dict[str, List[Dict[str,Any]]] await seed.close() closes the HTTP client if owned by seeder Usage examples -------------- # Manual cleanup: seeder = AsyncUrlSeeder() try: urls = await seeder.urls("example.com", config) finally: await seeder.close() # Using async context manager (recommended): async with AsyncUrlSeeder() as seeder: urls = await seeder.urls("example.com", config) # Reusing existing client: client = httpx.AsyncClient() seeder = AsyncUrlSeeder(client=client) urls = await seeder.urls("example.com", config) # No need to close seeder, as it doesn't own the client """ def __init__( self, ttl: timedelta = TTL, client: Optional[httpx.AsyncClient] = None, logger: Optional[AsyncLoggerBase] = None, # NEW: Add logger parameter # NEW: Add base_directory base_directory: Optional[Union[str, pathlib.Path]] = None, cache_root: Optional[Union[str, Path]] = None, ): self.ttl = ttl self._owns_client = client is None # Track if we created the client self.client = client or httpx.AsyncClient(http2=True, timeout=20, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) +AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36" }) self.logger = logger # Store the logger instance self.base_directory = pathlib.Path(base_directory or os.getenv( "CRAWL4_AI_BASE_DIRECTORY", Path.home())) # Resolve base_directory self.cache_dir = self.base_directory / ".crawl4ai" / \ "seeder_cache" # NEW: Specific cache dir for seeder self.cache_dir.mkdir(parents=True, exist_ok=True) # Ensure it exists self.index_cache_path = self.cache_dir / \ "latest_cc_index.txt" # NEW: Index cache path # defer โ€“ grabbing the index inside an active loop blows up self.index_id: Optional[str] = None self._rate_sem: Optional[asyncio.Semaphore] = None # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ cache dirs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ self.cache_root = Path(os.path.expanduser( cache_root or "~/.cache/url_seeder")) (self.cache_root / "live").mkdir(parents=True, exist_ok=True) (self.cache_root / "head").mkdir(exist_ok=True) def _log(self, level: str, message: str, tag: str = "URL_SEED", **kwargs: Any): """Helper to log messages using the provided logger, if available.""" if self.logger: log_method = getattr(self.logger, level, None) if log_method: log_method(message=message, tag=tag, params=kwargs.get('params', {})) # else: # Fallback for unknown level, should not happen with AsyncLoggerBase # print(f"[{tag}] {level.upper()}: {message.format(**kwargs)}") # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ cache helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _cache_path(self, kind: str, url: str) -> Path: h = hashlib.sha1(url.encode()).hexdigest() return self.cache_root / kind / f"{h}.json" async def _cache_get(self, kind: str, url: str) -> Optional[Dict[str, Any]]: p = self._cache_path(kind, url) if not p.exists(): return None if time.time()-p.stat().st_mtime > self.ttl.total_seconds(): return None try: async with aiofiles.open(p, "r") as f: return json.loads(await f.read()) except Exception: return None async def _cache_set(self, kind: str, url: str, data: Dict[str, Any]) -> None: try: async with aiofiles.open(self._cache_path(kind, url), "w") as f: await f.write(json.dumps(data, separators=(",", ":"))) except Exception: pass # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ discovery entry async def urls(self, domain: str, config: "SeedingConfig", ) -> List[Dict[str, Any]]: """ Fetch URLs for a domain using configuration from SeedingConfig. Parameters ---------- domain : str The domain to fetch URLs for (e.g., "example.com") config : SeedingConfig Configuration object containing all seeding parameters """ # Extract parameters from config pattern = config.pattern or "*" source = config.source live_check = config.live_check extract_head = config.extract_head concurrency = config.concurrency head_timeout = 5 # Default timeout for HEAD requests hits_per_sec = config.hits_per_sec self.force = config.force # Store force flag as instance attribute force = config.force verbose = config.verbose if config.verbose is not None else ( self.logger.verbose if self.logger else False) max_urls = config.max_urls if config.max_urls is not None else -1 query = config.query score_threshold = config.score_threshold scoring_method = config.scoring_method # Store cache config for use in _from_sitemaps self._cache_ttl_hours = getattr(config, 'cache_ttl_hours', 24) self._validate_sitemap_lastmod = getattr(config, 'validate_sitemap_lastmod', True) # Ensure seeder's logger verbose matches the config's verbose if it's set if self.logger and hasattr(self.logger, 'verbose') and config.verbose is not None: self.logger.verbose = config.verbose # ensure we have the latest CC collection id if self.index_id is None: self.index_id = await self._latest_index() # Parse source parameter - split by '+' to get list of sources sources = source.split('+') valid_sources = {"cc", "sitemap"} for s in sources: if s not in valid_sources: raise ValueError( f"Invalid source '{s}'. Valid sources are: {', '.join(valid_sources)}") if hits_per_sec: if hits_per_sec <= 0: self._log( "warning", "hits_per_sec must be positive. Disabling rate limiting.", tag="URL_SEED") self._rate_sem = None else: self._rate_sem = asyncio.Semaphore(hits_per_sec) else: self._rate_sem = None # Ensure it's None if no rate limiting self._log("info", "Starting URL seeding for {domain} with source={source}", params={"domain": domain, "source": source}, tag="URL_SEED") # choose stream async def gen(): if "sitemap" in sources: self._log("debug", "Fetching from sitemaps...", tag="URL_SEED") async for u in self._from_sitemaps(domain, pattern, force): yield u if "cc" in sources: self._log("debug", "Fetching from Common Crawl...", tag="URL_SEED") async for u in self._from_cc(domain, pattern, force): yield u # Use bounded queue to prevent RAM spikes with large domains queue_size = min(10000, max(1000, concurrency * 100)) # Dynamic size based on concurrency queue = asyncio.Queue(maxsize=queue_size) producer_done = asyncio.Event() stop_event = asyncio.Event() seen: set[str] = set() filter_nonsense = config.filter_nonsense_urls # Extract this for passing to workers async def producer(): try: async for u in gen(): if u in seen: self._log("debug", "Skipping duplicate URL: {url}", params={"url": u}, tag="URL_SEED") continue if stop_event.is_set(): self._log( "info", "Producer stopping due to max_urls limit.", tag="URL_SEED") break seen.add(u) await queue.put(u) # Will block if queue is full, providing backpressure except Exception as e: self._log("error", "Producer encountered an error: {error}", params={ "error": str(e)}, tag="URL_SEED") finally: producer_done.set() self._log("debug", "Producer finished.", tag="URL_SEED") async def worker(res_list: List[Dict[str, Any]]): while True: if queue.empty() and producer_done.is_set(): # self._log("debug", "Worker exiting: queue empty and producer done.", tag="URL_SEED") break try: # Increased timeout slightly url = await asyncio.wait_for(queue.get(), 5) except asyncio.TimeoutError: continue # Keep checking queue and producer_done status except Exception as e: self._log("error", "Worker failed to get URL from queue: {error}", params={ "error": str(e)}, tag="URL_SEED") continue if max_urls > 0 and len(res_list) >= max_urls: self._log( "info", "Worker stopping due to max_urls limit.", tag="URL_SEED", ) stop_event.set() # mark the current item done queue.task_done() # flush whatever is still sitting in the queue so # queue.join() can finish cleanly while not queue.empty(): try: queue.get_nowait() queue.task_done() except asyncio.QueueEmpty: break break if self._rate_sem: # global QPS control async with self._rate_sem: await self._validate(url, res_list, live_check, extract_head, head_timeout, verbose, query, score_threshold, scoring_method, filter_nonsense) else: await self._validate(url, res_list, live_check, extract_head, head_timeout, verbose, query, score_threshold, scoring_method, filter_nonsense) queue.task_done() # Mark task as done for queue.join() if ever used # launch results: List[Dict[str, Any]] = [] prod_task = asyncio.create_task(producer()) workers = [asyncio.create_task(worker(results)) for _ in range(concurrency)] # Wait for all workers to finish await asyncio.gather(prod_task, *workers) await queue.join() # Ensure all queued items are processed self._log("info", "Finished URL seeding for {domain}. Total URLs: {count}", params={"domain": domain, "count": len(results)}, tag="URL_SEED") # Apply BM25 scoring if query was provided if query and extract_head and scoring_method == "bm25": # Apply collective BM25 scoring across all documents results = await self._apply_bm25_scoring(results, config) # Filter by score threshold if specified if score_threshold is not None: original_count = len(results) results = [r for r in results if r.get("relevance_score", 0) >= score_threshold] if original_count > len(results): self._log("info", "Filtered {filtered} URLs below score threshold {threshold}", params={"filtered": original_count - len(results), "threshold": score_threshold}, tag="URL_SEED") # Sort by relevance score results.sort(key=lambda x: x.get("relevance_score", 0.0), reverse=True) self._log("info", "Sorted {count} URLs by relevance score for query: '{query}'", params={"count": len(results), "query": query}, tag="URL_SEED") elif query and not extract_head: self._log( "warning", "Query provided but extract_head is False. Enable extract_head for relevance scoring.", tag="URL_SEED") return results[:max_urls] if max_urls > 0 else results async def many_urls( self, domains: Sequence[str], config: "SeedingConfig", ) -> Dict[str, List[Dict[str, Any]]]: """ Fetch URLs for many domains in parallel. Parameters ---------- domains : Sequence[str] List of domains to fetch URLs for config : SeedingConfig Configuration object containing all seeding parameters Returns a {domain: urls-list} dict. """ self._log("info", "Starting URL seeding for {count} domains...", params={"count": len(domains)}, tag="URL_SEED") # Ensure seeder's logger verbose matches the config's verbose if it's set if self.logger and hasattr(self.logger, 'verbose') and config.verbose is not None: self.logger.verbose = config.verbose tasks = [ self.urls(domain, config) for domain in domains ] results = await asyncio.gather(*tasks) final_results = dict(zip(domains, results)) self._log( "info", "Finished URL seeding for multiple domains.", tag="URL_SEED") return final_results async def extract_head_for_urls( self, urls: List[str], config: Optional["SeedingConfig"] = None, concurrency: int = 10, timeout: int = 5 ) -> List[Dict[str, Any]]: """ Extract head content for a custom list of URLs using URLSeeder's parallel processing. This method reuses URLSeeder's efficient parallel processing, caching, and head extraction logic to process a custom list of URLs rather than discovering URLs from sources. Parameters ---------- urls : List[str] List of URLs to extract head content from config : SeedingConfig, optional Configuration object. If None, uses default settings for head extraction concurrency : int, default=10 Number of concurrent requests timeout : int, default=5 Timeout for each request in seconds Returns ------- List[Dict[str, Any]] List of dictionaries containing url, status, head_data, and optional relevance_score """ # Create default config if none provided if config is None: # Import here to avoid circular imports from .async_configs import SeedingConfig config = SeedingConfig( extract_head=True, concurrency=concurrency, verbose=False ) # Override concurrency and ensure head extraction is enabled config.concurrency = concurrency config.extract_head = True self._log("info", "Starting head extraction for {count} custom URLs", params={"count": len(urls)}, tag="URL_SEED") # Setup rate limiting if specified in config if config.hits_per_sec: if config.hits_per_sec <= 0: self._log("warning", "hits_per_sec must be positive. Disabling rate limiting.", tag="URL_SEED") self._rate_sem = None else: self._rate_sem = asyncio.Semaphore(config.hits_per_sec) else: self._rate_sem = None # Use bounded queue to prevent memory issues with large URL lists queue_size = min(10000, max(1000, concurrency * 100)) queue = asyncio.Queue(maxsize=queue_size) producer_done = asyncio.Event() stop_event = asyncio.Event() seen: set[str] = set() # Results collection results: List[Dict[str, Any]] = [] async def producer(): """Producer to feed URLs into the queue.""" try: for url in urls: if url in seen: self._log("debug", "Skipping duplicate URL: {url}", params={"url": url}, tag="URL_SEED") continue if stop_event.is_set(): break seen.add(url) await queue.put(url) finally: producer_done.set() async def worker(res_list: List[Dict[str, Any]]): """Worker to process URLs from the queue.""" while True: try: # Wait for URL or producer completion url = await asyncio.wait_for(queue.get(), timeout=1.0) except asyncio.TimeoutError: if producer_done.is_set() and queue.empty(): break continue try: # Use existing _validate method which handles head extraction, caching, etc. await self._validate( url, res_list, live=False, # We're not doing live checks, just head extraction extract=True, # Always extract head content timeout=timeout, verbose=config.verbose or False, query=config.query, score_threshold=config.score_threshold, scoring_method=config.scoring_method or "bm25", filter_nonsense=config.filter_nonsense_urls ) except Exception as e: self._log("error", "Failed to process URL {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") # Add failed entry to results res_list.append({ "url": url, "status": "failed", "head_data": {}, "error": str(e) }) finally: queue.task_done() # Start producer producer_task = asyncio.create_task(producer()) # Start workers worker_tasks = [] for _ in range(concurrency): worker_task = asyncio.create_task(worker(results)) worker_tasks.append(worker_task) # Wait for producer to finish await producer_task # Wait for all items to be processed await queue.join() # Cancel workers for task in worker_tasks: task.cancel() # Wait for workers to finish canceling await asyncio.gather(*worker_tasks, return_exceptions=True) # Apply BM25 scoring if query is provided if config.query and config.scoring_method == "bm25": results = await self._apply_bm25_scoring(results, config) # Apply score threshold filtering if config.score_threshold is not None: results = [r for r in results if r.get("relevance_score", 0) >= config.score_threshold] # Sort by relevance score if available if any("relevance_score" in r for r in results): results.sort(key=lambda x: x.get("relevance_score", 0), reverse=True) self._log("info", "Completed head extraction for {count} URLs, {success} successful", params={ "count": len(urls), "success": len([r for r in results if r.get("status") == "valid"]) }, tag="URL_SEED") return results async def _apply_bm25_scoring(self, results: List[Dict[str, Any]], config: "SeedingConfig") -> List[Dict[str, Any]]: """Apply BM25 scoring to results that have head_data.""" if not HAS_BM25: self._log("warning", "BM25 scoring requested but rank_bm25 not available", tag="URL_SEED") return results # Extract text contexts from head data text_contexts = [] valid_results = [] for result in results: if result.get("status") == "valid" and result.get("head_data"): text_context = self._extract_text_context(result["head_data"]) if text_context: text_contexts.append(text_context) valid_results.append(result) else: # Use URL-based scoring as fallback score = self._calculate_url_relevance_score(config.query, result["url"]) result["relevance_score"] = float(score) elif result.get("status") == "valid": # No head data but valid URL - use URL-based scoring score = self._calculate_url_relevance_score(config.query, result["url"]) result["relevance_score"] = float(score) # Calculate BM25 scores for results with text context if text_contexts and valid_results: scores = await asyncio.to_thread(self._calculate_bm25_score, config.query, text_contexts) for i, result in enumerate(valid_results): if i < len(scores): result["relevance_score"] = float(scores[i]) return results async def _resolve_head(self, url: str) -> Optional[str]: """ HEAD-probe a URL. Returns: * the same URL if it answers 2xx, * the absolute redirect target if it answers 3xx, * None on any other status or network error. """ try: r = await self.client.head(url, timeout=10, follow_redirects=False) # direct hit if 200 <= r.status_code < 300: return str(r.url) # single level redirect if r.status_code in (301, 302, 303, 307, 308): loc = r.headers.get("location") if loc: return urljoin(url, loc) return None except Exception as e: self._log("debug", "HEAD {url} failed: {err}", params={"url": url, "err": str(e)}, tag="URL_SEED") return None # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ CC async def _from_cc(self, domain: str, pattern: str, force: bool): import re digest = hashlib.md5(pattern.encode()).hexdigest()[:8] # โ”€โ”€ normalise for CC (strip scheme, query, fragment) raw = re.sub(r'^https?://', '', domain).split('#', 1)[0].split('?', 1)[0].lstrip('.') # โ”€โ”€ sanitize only for cache-file name safe = re.sub('[/?#]+', '_', raw) path = self.cache_dir / f"{self.index_id}_{safe}_{digest}.jsonl" if path.exists() and not force: self._log("info", "Loading CC URLs for {domain} from cache: {path}", params={"domain": domain, "path": path}, tag="URL_SEED") async with aiofiles.open(path, "r") as fp: async for line in fp: url = line.strip() if _match(url, pattern): yield url return # build CC glob โ€“ if a path is present keep it, else add trailing /* glob = f"*.{raw}*" if '/' in raw else f"*.{raw}/*" url = f"https://index.commoncrawl.org/{self.index_id}-index?url={quote(glob, safe='*')}&output=json" retries = (1, 3, 7) self._log("info", "Fetching CC URLs for {domain} from Common Crawl index: {url}", params={"domain": domain, "url": url}, tag="URL_SEED") for i, d in enumerate(retries+(-1,)): # last -1 means don't retry try: async with self.client.stream("GET", url) as r: r.raise_for_status() async with aiofiles.open(path, "w") as fp: async for line in r.aiter_lines(): rec = json.loads(line) u = rec["url"] await fp.write(u+"\n") if _match(u, pattern): yield u return except httpx.HTTPStatusError as e: if e.response.status_code == 503 and i < len(retries): self._log("warning", "Common Crawl API returned 503 for {domain}. Retrying in {delay}s.", params={"domain": domain, "delay": retries[i]}, tag="URL_SEED") await asyncio.sleep(retries[i]) continue self._log("error", "HTTP error fetching CC index for {domain}: {error}", params={"domain": domain, "error": str(e)}, tag="URL_SEED") raise except Exception as e: self._log("error", "Error fetching CC index for {domain}: {error}", params={"domain": domain, "error": str(e)}, tag="URL_SEED") raise # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Sitemaps async def _from_sitemaps(self, domain: str, pattern: str, force: bool = False): """ Discover URLs from sitemaps with smart TTL-based caching. 1. Check cache validity (TTL + lastmod) 2. If valid, yield from cache 3. If invalid or force=True, fetch fresh and update cache 4. FALLBACK: If anything fails, bypass cache and fetch directly """ # Get config values (passed via self during urls() call) cache_ttl_hours = getattr(self, '_cache_ttl_hours', 24) validate_lastmod = getattr(self, '_validate_sitemap_lastmod', True) # Cache file path (new format: .json instead of .jsonl) host = re.sub(r'^https?://', '', domain).rstrip('/') host_safe = re.sub('[/?#]+', '_', host) digest = hashlib.md5(pattern.encode()).hexdigest()[:8] cache_path = self.cache_dir / f"sitemap_{host_safe}_{digest}.json" # Check for old .jsonl format and delete it old_cache_path = self.cache_dir / f"sitemap_{host_safe}_{digest}.jsonl" if old_cache_path.exists(): try: old_cache_path.unlink() self._log("info", "Deleted old cache format: {p}", params={"p": str(old_cache_path)}, tag="URL_SEED") except Exception: pass # Step 1: Find sitemap URL and get lastmod (needed for validation) sitemap_url = None sitemap_lastmod = None sitemap_content = None schemes = ('https', 'http') for scheme in schemes: for suffix in ("/sitemap.xml", "/sitemap_index.xml"): sm = f"{scheme}://{host}{suffix}" resolved = await self._resolve_head(sm) if resolved: sitemap_url = resolved # Fetch sitemap content to get lastmod try: r = await self.client.get(sitemap_url, timeout=15, follow_redirects=True) if 200 <= r.status_code < 300: sitemap_content = r.content sitemap_lastmod = _parse_sitemap_lastmod(sitemap_content) except Exception: pass break if sitemap_url: break # Step 2: Check cache validity (skip if force=True) if not force and cache_path.exists(): if _is_cache_valid(cache_path, cache_ttl_hours, validate_lastmod, sitemap_lastmod): self._log("info", "Loading sitemap URLs from valid cache: {p}", params={"p": str(cache_path)}, tag="URL_SEED") cached_urls = _read_cache(cache_path) for url in cached_urls: if _match(url, pattern): yield url return else: self._log("info", "Cache invalid/expired, refetching sitemap for {d}", params={"d": domain}, tag="URL_SEED") # Step 3: Fetch fresh URLs discovered_urls = [] if sitemap_url and sitemap_content: self._log("info", "Found sitemap at {url}", params={"url": sitemap_url}, tag="URL_SEED") # Parse sitemap (reuse content we already fetched) async for u in self._iter_sitemap_content(sitemap_url, sitemap_content): discovered_urls.append(u) if _match(u, pattern): yield u elif sitemap_url: # We have a sitemap URL but no content (fetch failed earlier), try again self._log("info", "Found sitemap at {url}", params={"url": sitemap_url}, tag="URL_SEED") async for u in self._iter_sitemap(sitemap_url): discovered_urls.append(u) if _match(u, pattern): yield u else: # Fallback: robots.txt robots = f"https://{host}/robots.txt" try: r = await self.client.get(robots, timeout=10, follow_redirects=True) if 200 <= r.status_code < 300: sitemap_lines = [l.split(":", 1)[1].strip() for l in r.text.splitlines() if l.lower().startswith("sitemap:")] for sm in sitemap_lines: async for u in self._iter_sitemap(sm): discovered_urls.append(u) if _match(u, pattern): yield u else: self._log("warning", "robots.txt unavailable for {d} HTTP{c}", params={"d": domain, "c": r.status_code}, tag="URL_SEED") return except Exception as e: self._log("warning", "Failed to fetch robots.txt for {d}: {e}", params={"d": domain, "e": str(e)}, tag="URL_SEED") return # Step 4: Write to cache (FALLBACK: if write fails, URLs still yielded above) if discovered_urls: _write_cache(cache_path, discovered_urls, sitemap_url or "", sitemap_lastmod) self._log("info", "Cached {count} URLs for {d}", params={"count": len(discovered_urls), "d": domain}, tag="URL_SEED") async def _iter_sitemap_content(self, url: str, content: bytes): """Parse sitemap from already-fetched content.""" data = gzip.decompress(content) if url.endswith(".gz") else content base_url = url def _normalize_loc(raw: Optional[str]) -> Optional[str]: if not raw: return None normalized = urljoin(base_url, raw.strip()) if not normalized: return None return normalized # Detect if this is a sitemap index is_sitemap_index = False sub_sitemaps = [] regular_urls = [] if LXML: try: parser = etree.XMLParser(recover=True) root = etree.fromstring(data, parser=parser) sitemap_loc_nodes = root.xpath("//*[local-name()='sitemap']/*[local-name()='loc']") url_loc_nodes = root.xpath("//*[local-name()='url']/*[local-name()='loc']") if sitemap_loc_nodes: is_sitemap_index = True for sitemap_elem in sitemap_loc_nodes: loc = _normalize_loc(sitemap_elem.text) if loc: sub_sitemaps.append(loc) if not is_sitemap_index: for loc_elem in url_loc_nodes: loc = _normalize_loc(loc_elem.text) if loc: regular_urls.append(loc) except Exception as e: self._log("error", "LXML parsing error for sitemap {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") return else: import xml.etree.ElementTree as ET try: root = ET.fromstring(data) for elem in root.iter(): if '}' in elem.tag: elem.tag = elem.tag.split('}')[1] sitemaps = root.findall('.//sitemap') url_entries = root.findall('.//url') if sitemaps: is_sitemap_index = True for sitemap in sitemaps: loc_elem = sitemap.find('loc') loc = _normalize_loc(loc_elem.text if loc_elem is not None else None) if loc: sub_sitemaps.append(loc) if not is_sitemap_index: for url_elem in url_entries: loc_elem = url_elem.find('loc') loc = _normalize_loc(loc_elem.text if loc_elem is not None else None) if loc: regular_urls.append(loc) except Exception as e: self._log("error", "ElementTree parsing error for sitemap {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") return # Process based on type if is_sitemap_index and sub_sitemaps: self._log("info", "Processing sitemap index with {count} sub-sitemaps", params={"count": len(sub_sitemaps)}, tag="URL_SEED") queue_size = min(50000, len(sub_sitemaps) * 1000) result_queue = asyncio.Queue(maxsize=queue_size) completed_count = 0 total_sitemaps = len(sub_sitemaps) async def process_subsitemap(sitemap_url: str): try: async for u in self._iter_sitemap(sitemap_url): await result_queue.put(u) except Exception as e: self._log("error", "Error processing sub-sitemap {url}: {error}", params={"url": sitemap_url, "error": str(e)}, tag="URL_SEED") finally: await result_queue.put(None) tasks = [asyncio.create_task(process_subsitemap(sm)) for sm in sub_sitemaps] while completed_count < total_sitemaps: item = await result_queue.get() if item is None: completed_count += 1 else: yield item await asyncio.gather(*tasks, return_exceptions=True) else: for u in regular_urls: yield u async def _iter_sitemap(self, url: str): try: r = await self.client.get(url, timeout=15, follow_redirects=True) r.raise_for_status() except httpx.HTTPStatusError as e: self._log("warning", "Failed to fetch sitemap {url}: HTTP {status_code}", params={"url": url, "status_code": e.response.status_code}, tag="URL_SEED") return except httpx.RequestError as e: self._log("warning", "Network error fetching sitemap {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") return except Exception as e: self._log("error", "Unexpected error fetching sitemap {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") return data = gzip.decompress(r.content) if url.endswith(".gz") else r.content base_url = str(r.url) def _normalize_loc(raw: Optional[str]) -> Optional[str]: if not raw: return None normalized = urljoin(base_url, raw.strip()) if not normalized: return None return normalized # Detect if this is a sitemap index by checking for <sitemapindex> or presence of <sitemap> elements is_sitemap_index = False sub_sitemaps = [] regular_urls = [] # Use lxml for XML parsing if available, as it's generally more robust if LXML: try: # Use XML parser for sitemaps, not HTML parser parser = etree.XMLParser(recover=True) root = etree.fromstring(data, parser=parser) # Namespace-agnostic lookups using local-name() so we honor custom or missing namespaces sitemap_loc_nodes = root.xpath("//*[local-name()='sitemap']/*[local-name()='loc']") url_loc_nodes = root.xpath("//*[local-name()='url']/*[local-name()='loc']") self._log( "debug", "Parsed sitemap {url}: {sitemap_count} sitemap entries, {url_count} url entries discovered", params={ "url": url, "sitemap_count": len(sitemap_loc_nodes), "url_count": len(url_loc_nodes), }, tag="URL_SEED", ) # Check for sitemap index entries if sitemap_loc_nodes: is_sitemap_index = True for sitemap_elem in sitemap_loc_nodes: loc = _normalize_loc(sitemap_elem.text) if loc: sub_sitemaps.append(loc) # If not a sitemap index, get regular URLs if not is_sitemap_index: for loc_elem in url_loc_nodes: loc = _normalize_loc(loc_elem.text) if loc: regular_urls.append(loc) if not regular_urls: self._log( "warning", "No <loc> entries found inside <url> tags for sitemap {url}. The sitemap might be empty or use an unexpected structure.", params={"url": url}, tag="URL_SEED", ) except Exception as e: self._log("error", "LXML parsing error for sitemap {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") return else: # Fallback to xml.etree.ElementTree import xml.etree.ElementTree as ET try: # Parse the XML root = ET.fromstring(data) # Remove namespace from tags for easier processing for elem in root.iter(): if '}' in elem.tag: elem.tag = elem.tag.split('}')[1] # Check for sitemap index entries sitemaps = root.findall('.//sitemap') url_entries = root.findall('.//url') self._log( "debug", "ElementTree parsed sitemap {url}: {sitemap_count} sitemap entries, {url_count} url entries discovered", params={ "url": url, "sitemap_count": len(sitemaps), "url_count": len(url_entries), }, tag="URL_SEED", ) if sitemaps: is_sitemap_index = True for sitemap in sitemaps: loc_elem = sitemap.find('loc') loc = _normalize_loc(loc_elem.text if loc_elem is not None else None) if loc: sub_sitemaps.append(loc) # If not a sitemap index, get regular URLs if not is_sitemap_index: for url_elem in url_entries: loc_elem = url_elem.find('loc') loc = _normalize_loc(loc_elem.text if loc_elem is not None else None) if loc: regular_urls.append(loc) if not regular_urls: self._log( "warning", "No <loc> entries found inside <url> tags for sitemap {url}. The sitemap might be empty or use an unexpected structure.", params={"url": url}, tag="URL_SEED", ) except Exception as e: self._log("error", "ElementTree parsing error for sitemap {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") return # Process based on type if is_sitemap_index and sub_sitemaps: self._log("info", "Processing sitemap index with {count} sub-sitemaps in parallel", params={"count": len(sub_sitemaps)}, tag="URL_SEED") # Create a bounded queue for results to prevent RAM issues # For sitemap indexes, use a larger queue as we expect many URLs queue_size = min(50000, len(sub_sitemaps) * 1000) # Estimate 1000 URLs per sitemap result_queue = asyncio.Queue(maxsize=queue_size) completed_count = 0 total_sitemaps = len(sub_sitemaps) async def process_subsitemap(sitemap_url: str): try: self._log( "debug", "Processing sub-sitemap: {url}", params={"url": sitemap_url}, tag="URL_SEED") # Recursively process sub-sitemap async for u in self._iter_sitemap(sitemap_url): await result_queue.put(u) # Will block if queue is full except Exception as e: self._log("error", "Error processing sub-sitemap {url}: {error}", params={"url": sitemap_url, "error": str(e)}, tag="URL_SEED") finally: # Put sentinel to signal completion await result_queue.put(None) # Start all tasks tasks = [asyncio.create_task(process_subsitemap(sm)) for sm in sub_sitemaps] # Yield results as they come in while completed_count < total_sitemaps: item = await result_queue.get() if item is None: completed_count += 1 else: yield item # Ensure all tasks are done await asyncio.gather(*tasks, return_exceptions=True) else: # Regular sitemap - yield URLs directly for u in regular_urls: yield u # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ validate helpers async def _validate(self, url: str, res_list: List[Dict[str, Any]], live: bool, extract: bool, timeout: int, verbose: bool, query: Optional[str] = None, score_threshold: Optional[float] = None, scoring_method: str = "bm25", filter_nonsense: bool = True): # Local verbose parameter for this function is used to decide if intermediate logs should be printed # The main logger's verbose status should be controlled by the caller. # First check if this is a nonsense URL (if filtering is enabled) if filter_nonsense and self._is_nonsense_url(url): self._log("debug", "Filtered out nonsense URL: {url}", params={"url": url}, tag="URL_SEED") return cache_kind = "head" if extract else "live" # ---------- try cache ---------- if not (hasattr(self, 'force') and self.force): cached = await self._cache_get(cache_kind, url) if cached: res_list.append(cached) return if extract: self._log("debug", "Fetching head for {url}", params={ "url": url}, tag="URL_SEED") ok, html, final = await self._fetch_head(url, timeout) status = "valid" if ok else "not_valid" self._log("info" if ok else "warning", "HEAD {status} for {final_url}", params={"status": status.upper(), "final_url": final or url}, tag="URL_SEED") # head_data = _parse_head(html) if ok else {} head_data = await asyncio.to_thread(_parse_head, html) if ok else {} entry = { "url": final or url, "status": status, "head_data": head_data, } elif live: self._log("debug", "Performing live check for {url}", params={ "url": url}, tag="URL_SEED") ok = await self._resolve_head(url) status = "valid" if ok else "not_valid" self._log("info" if ok else "warning", "LIVE CHECK {status} for {url}", params={"status": status.upper(), "url": url}, tag="URL_SEED") entry = {"url": url, "status": status, "head_data": {}} else: entry = {"url": url, "status": "unknown", "head_data": {}} # Add entry to results (scoring will be done later) if live or extract: await self._cache_set(cache_kind, url, entry) res_list.append(entry) async def _head_ok(self, url: str, timeout: int) -> bool: try: r = await self.client.head(url, timeout=timeout, headers={"Range": "bytes=0-0", "Accept-Encoding": "identity"}) r.raise_for_status() # Raise for bad status codes (4xx, 5xx) return True except httpx.RequestError as e: self._log("debug", "HEAD check network error for {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") return False except httpx.HTTPStatusError as e: self._log("debug", "HEAD check HTTP status error for {url}: {status_code}", params={"url": url, "status_code": e.response.status_code}, tag="URL_SEED") return False except Exception as e: self._log("error", "Unexpected error during HEAD check for {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") return False async def _fetch_head( self, url: str, timeout: int, max_redirects: int = 5, max_bytes: int = 65_536, # stop after 64 kB even if </head> never comes chunk_size: int = 4096, # how much we read per await ): for _ in range(max_redirects+1): try: # ask the first `max_bytes` and force plain text to avoid # partial-gzip decode headaches async with self.client.stream( "GET", url, timeout=timeout, headers={ # "Range": f"bytes=0-{max_bytes-1}", # Dropped the Range header โ€“ no need now, and some servers ignore it. We still keep an upperโ€bound max_bytes as a fail-safe. "Accept-Encoding": "identity", }, follow_redirects=False, ) as r: if r.status_code in (301, 302, 303, 307, 308): location = r.headers.get("Location") if location: url = urljoin(url, location) self._log("debug", "Redirecting from {original_url} to {new_url}", params={"original_url": r.url, "new_url": url}, tag="URL_SEED") continue else: self._log("warning", "Redirect status {status_code} but no Location header for {url}", params={"status_code": r.status_code, "url": r.url}, tag="URL_SEED") # Return original URL if no new location return False, "", str(r.url) # For 2xx or other non-redirect codes, proceed to read content # Only allow successful codes, or continue if not (200 <= r.status_code < 400): self._log("warning", "Non-success status {status_code} when fetching head for {url}", params={"status_code": r.status_code, "url": r.url}, tag="URL_SEED") return False, "", str(r.url) buf = bytearray() async for chunk in r.aiter_bytes(chunk_size): buf.extend(chunk) low = buf.lower() if b"</head>" in low or len(buf) >= max_bytes: await r.aclose() break enc = r.headers.get("Content-Encoding", "").lower() try: if enc == "gzip" and buf[:2] == b"\x1f\x8b": buf = gzip.decompress(buf) elif enc == "br" and HAS_BROTLI and buf[:4] == b"\x8b\x6c\x0a\x1a": buf = brotli.decompress(buf) elif enc in {"gzip", "br"}: # Header says โ€œgzipโ€ or โ€œbrโ€ but payload is plain โ€“ ignore self._log( "debug", "Skipping bogus {encoding} for {url}", params={"encoding": enc, "url": r.url}, tag="URL_SEED", ) except Exception as e: self._log( "warning", "Decompression error for {url} ({encoding}): {error}", params={"url": r.url, "encoding": enc, "error": str(e)}, tag="URL_SEED", ) # fall through with raw buf # Find the </head> tag case-insensitively and decode idx = buf.lower().find(b"</head>") if idx == -1: self._log("debug", "No </head> tag found in initial bytes of {url}", params={"url": r.url}, tag="URL_SEED") # If no </head> is found, take a reasonable chunk or all if small # Take max 10KB if no head tag html_bytes = buf if len(buf) < 10240 else buf[:10240] else: html_bytes = buf[:idx+7] # Include </head> tag try: html = html_bytes.decode("utf-8", "replace") except Exception as e: self._log( "warning", "Failed to decode head content for {url}: {error}", params={"url": r.url, "error": str(e)}, tag="URL_SEED", ) html = html_bytes.decode("latin-1", "replace") # Return the actual URL after redirects return True, html, str(r.url) except httpx.RequestError as e: self._log("debug", "Fetch head network error for {url}: {error}", params={"url": url, "error": str(e)}, tag="URL_SEED") return False, "", url # If loop finishes without returning (e.g. too many redirects) self._log("warning", "Exceeded max redirects ({max_redirects}) for {url}", params={"max_redirects": max_redirects, "url": url}, tag="URL_SEED") return False, "", url # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ BM25 scoring helpers def _extract_text_context(self, head_data: Dict[str, Any]) -> str: """Extract all relevant text from head metadata for scoring.""" # Priority fields with their weights (for future enhancement) text_parts = [] # Title if head_data.get("title"): text_parts.append(head_data["title"]) # Standard meta tags meta = head_data.get("meta", {}) for key in ["description", "keywords", "author", "subject", "summary", "abstract"]: if meta.get(key): text_parts.append(meta[key]) # Open Graph tags for key in ["og:title", "og:description", "og:site_name", "article:tag"]: if meta.get(key): text_parts.append(meta[key]) # Twitter Card tags for key in ["twitter:title", "twitter:description", "twitter:image:alt"]: if meta.get(key): text_parts.append(meta[key]) # Dublin Core tags for key in ["dc.title", "dc.description", "dc.subject", "dc.creator"]: if meta.get(key): text_parts.append(meta[key]) # JSON-LD structured data for jsonld in head_data.get("jsonld", []): if isinstance(jsonld, dict): # Extract common fields from JSON-LD for field in ["name", "headline", "description", "abstract", "keywords"]: if field in jsonld: if isinstance(jsonld[field], str): text_parts.append(jsonld[field]) elif isinstance(jsonld[field], list): text_parts.extend(str(item) for item in jsonld[field] if item) # Handle @graph structures if "@graph" in jsonld and isinstance(jsonld["@graph"], list): for item in jsonld["@graph"]: if isinstance(item, dict): for field in ["name", "headline", "description"]: if field in item and isinstance(item[field], str): text_parts.append(item[field]) # Combine all text parts return " ".join(filter(None, text_parts)) def _calculate_url_relevance_score(self, query: str, url: str) -> float: """Calculate relevance score between query and URL using string matching.""" # Normalize inputs query_lower = query.lower() url_lower = url.lower() # Extract URL components from urllib.parse import urlparse parsed = urlparse(url) domain = parsed.netloc.replace('www.', '') path = parsed.path.strip('/') # Create searchable text from URL # Split domain by dots and path by slashes domain_parts = domain.split('.') path_parts = [p for p in path.split('/') if p] # Include query parameters if any query_params = parsed.query param_parts = [] if query_params: for param in query_params.split('&'): if '=' in param: key, value = param.split('=', 1) param_parts.extend([key, value]) # Combine all parts all_parts = domain_parts + path_parts + param_parts # Calculate scores scores = [] query_tokens = query_lower.split() # 1. Exact match in any part (highest score) for part in all_parts: part_lower = part.lower() if query_lower in part_lower: scores.append(1.0) elif part_lower in query_lower: scores.append(0.9) # 2. Token matching for token in query_tokens: token_scores = [] for part in all_parts: part_lower = part.lower() if token in part_lower: # Score based on how much of the part the token covers coverage = len(token) / len(part_lower) token_scores.append(0.7 * coverage) elif part_lower in token: coverage = len(part_lower) / len(token) token_scores.append(0.6 * coverage) if token_scores: scores.append(max(token_scores)) # 3. Character n-gram similarity (for fuzzy matching) def get_ngrams(text, n=3): return set(text[i:i+n] for i in range(len(text)-n+1)) # Combine all URL parts into one string for n-gram comparison url_text = ' '.join(all_parts).lower() if len(query_lower) >= 3 and len(url_text) >= 3: query_ngrams = get_ngrams(query_lower) url_ngrams = get_ngrams(url_text) if query_ngrams and url_ngrams: intersection = len(query_ngrams & url_ngrams) union = len(query_ngrams | url_ngrams) jaccard = intersection / union if union > 0 else 0 scores.append(0.5 * jaccard) # Calculate final score if not scores: return 0.0 # Weighted average with bias towards higher scores scores.sort(reverse=True) weighted_score = 0 total_weight = 0 for i, score in enumerate(scores): weight = 1 / (i + 1) # Higher weight for better matches weighted_score += score * weight total_weight += weight final_score = weighted_score / total_weight if total_weight > 0 else 0 return min(final_score, 1.0) # Cap at 1.0 def _is_nonsense_url(self, url: str) -> bool: """ Check if URL is a utility/nonsense URL that shouldn't be crawled. Returns True if the URL should be filtered out. """ url_lower = url.lower() # Extract path and filename from urllib.parse import urlparse parsed = urlparse(url) path = parsed.path.lower() # 1. Robot and sitemap files if path.endswith(('/robots.txt', '/sitemap.xml', '/sitemap_index.xml')): return True # 2. Sitemap variations if '/sitemap' in path and path.endswith(('.xml', '.xml.gz', '.txt')): return True # 3. Common utility files utility_files = [ 'ads.txt', 'humans.txt', 'security.txt', '.well-known/security.txt', 'crossdomain.xml', 'browserconfig.xml', 'manifest.json', 'apple-app-site-association', '.well-known/apple-app-site-association', 'favicon.ico', 'apple-touch-icon.png', 'android-chrome-192x192.png' ] if any(path.endswith(f'/{file}') for file in utility_files): return True # # 4. Feed files # if path.endswith(('.rss', '.atom', '/feed', '/rss', '/atom', '/feed.xml', '/rss.xml')): # return True # # 5. API endpoints and data files # api_patterns = ['/api/', '/v1/', '/v2/', '/v3/', '/graphql', '/.json', '/.xml'] # if any(pattern in path for pattern in api_patterns): # return True # # 6. Archive and download files # download_extensions = [ # '.zip', '.tar', '.gz', '.rar', '.7z', '.bz2', # '.exe', '.dmg', '.pkg', '.deb', '.rpm', # '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', # '.csv', '.tsv', '.sql', '.db', '.sqlite' # ] # if any(path.endswith(ext) for ext in download_extensions): # return True # # 7. Media files (often not useful for text content) # media_extensions = [ # '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.ico', # '.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', # '.mp3', '.wav', '.ogg', '.m4a', '.flac', # '.woff', '.woff2', '.ttf', '.eot', '.otf' # ] # if any(path.endswith(ext) for ext in media_extensions): # return True # # 8. Source code and config files # code_extensions = [ # '.js', '.css', '.scss', '.sass', '.less', # '.map', '.min.js', '.min.css', # '.py', '.rb', '.php', '.java', '.cpp', '.h', # '.yaml', '.yml', '.toml', '.ini', '.conf', '.config' # ] # if any(path.endswith(ext) for ext in code_extensions): # return True # 9. Hidden files and directories path_parts = path.split('/') if any(part.startswith('.') for part in path_parts if part): return True # 10. Common non-content paths non_content_paths = [ '/wp-admin', '/wp-includes', '/wp-content/uploads', '/admin', '/login', '/signin', '/signup', '/register', '/checkout', '/cart', '/account', '/profile', '/search', '/404', '/error', '/.git', '/.svn', '/.hg', '/cgi-bin', '/scripts', '/includes' ] if any(ncp in path for ncp in non_content_paths): return True # 11. URL patterns that indicate non-content if any(pattern in url_lower for pattern in ['?print=', '&print=', '/print/', '_print.']): return True # 12. Very short paths (likely homepage redirects or errors) if len(path.strip('/')) < 3 and path not in ['/', '/en', '/de', '/fr', '/es', '/it']: return True return False def _calculate_bm25_score(self, query: str, documents: List[str]) -> List[float]: """Calculate BM25 scores for documents against a query.""" if not HAS_BM25: self._log( "warning", "rank_bm25 not installed. Returning zero scores.", tag="URL_SEED") return [0.0] * len(documents) if not query or not documents: return [0.0] * len(documents) # Tokenize query and documents (simple whitespace tokenization) # For production, consider using a proper tokenizer query_tokens = query.lower().split() tokenized_docs = [doc.lower().split() for doc in documents] # Handle edge case where all documents are empty if all(len(doc) == 0 for doc in tokenized_docs): return [0.0] * len(documents) # Create BM25 instance and calculate scores try: from rank_bm25 import BM25Okapi bm25 = BM25Okapi(tokenized_docs) scores = bm25.get_scores(query_tokens) # Normalize scores to 0-1 range # BM25 can return negative scores, so we need to handle the full range if len(scores) == 0: return [] min_score = min(scores) max_score = max(scores) # If all scores are the same, return 0.5 for all if max_score == min_score: return [0.5] * len(scores) # Normalize to 0-1 range using min-max normalization normalized_scores = [(score - min_score) / (max_score - min_score) for score in scores] return normalized_scores except Exception as e: self._log("error", "Error calculating BM25 scores: {error}", params={"error": str(e)}, tag="URL_SEED") return [0.0] * len(documents) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ cleanup methods async def close(self): """Close the HTTP client if we own it.""" if self._owns_client and self.client: await self.client.aclose() self._log("debug", "Closed HTTP client", tag="URL_SEED") async def __aenter__(self): """Async context manager entry.""" return self async def __aexit__(self, exc_type, exc_val, exc_tb): """Async context manager exit.""" await self.close() return False # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ index helper async def _latest_index(self) -> str: if self.index_cache_path.exists() and (time.time()-self.index_cache_path.stat().st_mtime) < self.ttl.total_seconds(): self._log("info", "Loading latest CC index from cache: {path}", params={"path": self.index_cache_path}, tag="URL_SEED") return self.index_cache_path.read_text().strip() self._log("info", "Fetching latest Common Crawl index from {url}", params={"url": COLLINFO_URL}, tag="URL_SEED") try: async with httpx.AsyncClient() as c: j = await c.get(COLLINFO_URL, timeout=10) j.raise_for_status() # Raise an exception for bad status codes idx = j.json()[0]["id"] self.index_cache_path.write_text(idx) self._log("success", "Successfully fetched and cached CC index: {index_id}", params={"index_id": idx}, tag="URL_SEED") return idx except httpx.RequestError as e: self._log("error", "Network error fetching CC index info: {error}", params={"error": str(e)}, tag="URL_SEED") raise except httpx.HTTPStatusError as e: self._log("error", "HTTP error fetching CC index info: {status_code}", params={"status_code": e.response.status_code}, tag="URL_SEED") raise except Exception as e: self._log("error", "Unexpected error fetching CC index info: {error}", params={"error": str(e)}, tag="URL_SEED") raise
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/async_url_seeder.py", "license": "Apache License 2.0", "lines": 1545, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:crawl4ai/link_preview.py
""" Link Extractor for Crawl4AI Extracts head content from links discovered during crawling using URLSeeder's efficient parallel processing and caching infrastructure. """ import asyncio import fnmatch from typing import Dict, List, Optional, Any from .async_logger import AsyncLogger from .async_url_seeder import AsyncUrlSeeder from .async_configs import SeedingConfig, CrawlerRunConfig from .models import Links, Link from .utils import calculate_total_score class LinkPreview: """ Extracts head content from links using URLSeeder's parallel processing infrastructure. This class provides intelligent link filtering and head content extraction with: - Pattern-based inclusion/exclusion filtering - Parallel processing with configurable concurrency - Caching for performance - BM25 relevance scoring - Memory-safe processing for large link sets """ def __init__(self, logger: Optional[AsyncLogger] = None): """ Initialize the LinkPreview. Args: logger: Optional logger instance for recording events """ self.logger = logger self.seeder: Optional[AsyncUrlSeeder] = None self._owns_seeder = False async def __aenter__(self): """Async context manager entry.""" await self.start() return self async def __aexit__(self, exc_type, exc_val, exc_tb): """Async context manager exit.""" await self.close() async def start(self): """Initialize the URLSeeder instance.""" if not self.seeder: self.seeder = AsyncUrlSeeder(logger=self.logger) await self.seeder.__aenter__() self._owns_seeder = True async def close(self): """Clean up resources.""" if self.seeder and self._owns_seeder: await self.seeder.__aexit__(None, None, None) self.seeder = None self._owns_seeder = False def _log(self, level: str, message: str, tag: str = "LINK_EXTRACT", **kwargs): """Helper method to safely log messages.""" if self.logger: log_method = getattr(self.logger, level, None) if log_method: log_method(message=message, tag=tag, params=kwargs.get('params', {})) async def extract_link_heads( self, links: Links, config: CrawlerRunConfig ) -> Links: """ Extract head content for filtered links and attach to Link objects. Args: links: Links object containing internal and external links config: CrawlerRunConfig with link_preview_config settings Returns: Links object with head_data attached to filtered Link objects """ link_config = config.link_preview_config # Ensure seeder is initialized await self.start() # Filter links based on configuration filtered_urls = self._filter_links(links, link_config) if not filtered_urls: self._log("info", "No links matched filtering criteria") return links self._log("info", "Extracting head content for {count} filtered links", params={"count": len(filtered_urls)}) # Extract head content using URLSeeder head_results = await self._extract_heads_parallel(filtered_urls, link_config) # Merge results back into Link objects updated_links = self._merge_head_data(links, head_results, config) self._log("info", "Completed head extraction for links, {success} successful", params={"success": len([r for r in head_results if r.get("status") == "valid"])}) return updated_links def _filter_links(self, links: Links, link_config: Dict[str, Any]) -> List[str]: """ Filter links based on configuration parameters. Args: links: Links object containing internal and external links link_config: Configuration dictionary for link extraction Returns: List of filtered URL strings """ filtered_urls = [] # Include internal links if configured if link_config.include_internal: filtered_urls.extend([link.href for link in links.internal if link.href]) self._log("debug", "Added {count} internal links", params={"count": len(links.internal)}) # Include external links if configured if link_config.include_external: filtered_urls.extend([link.href for link in links.external if link.href]) self._log("debug", "Added {count} external links", params={"count": len(links.external)}) # Apply include patterns include_patterns = link_config.include_patterns if include_patterns: filtered_urls = [ url for url in filtered_urls if any(fnmatch.fnmatch(url, pattern) for pattern in include_patterns) ] self._log("debug", "After include patterns: {count} links remain", params={"count": len(filtered_urls)}) # Apply exclude patterns exclude_patterns = link_config.exclude_patterns if exclude_patterns: filtered_urls = [ url for url in filtered_urls if not any(fnmatch.fnmatch(url, pattern) for pattern in exclude_patterns) ] self._log("debug", "After exclude patterns: {count} links remain", params={"count": len(filtered_urls)}) # Limit number of links max_links = link_config.max_links if max_links > 0 and len(filtered_urls) > max_links: filtered_urls = filtered_urls[:max_links] self._log("debug", "Limited to {max_links} links", params={"max_links": max_links}) # Remove duplicates while preserving order seen = set() unique_urls = [] for url in filtered_urls: if url not in seen: seen.add(url) unique_urls.append(url) self._log("debug", "Final filtered URLs: {count} unique links", params={"count": len(unique_urls)}) return unique_urls async def _extract_heads_parallel( self, urls: List[str], link_config: Dict[str, Any] ) -> List[Dict[str, Any]]: """ Extract head content for URLs using URLSeeder's parallel processing. Args: urls: List of URLs to process link_config: Configuration dictionary for link extraction Returns: List of dictionaries with url, status, head_data, and optional relevance_score """ verbose = link_config.verbose concurrency = link_config.concurrency if verbose: self._log("info", "Starting batch processing: {total} links with {concurrency} concurrent workers", params={"total": len(urls), "concurrency": concurrency}) # Create SeedingConfig for URLSeeder seeding_config = SeedingConfig( extract_head=True, concurrency=concurrency, hits_per_sec=getattr(link_config, 'hits_per_sec', None), query=link_config.query, score_threshold=link_config.score_threshold, scoring_method="bm25" if link_config.query else None, verbose=verbose ) # Use URLSeeder's extract_head_for_urls method with progress tracking if verbose: # Create a wrapper to track progress results = await self._extract_with_progress(urls, seeding_config, link_config) else: results = await self.seeder.extract_head_for_urls( urls=urls, config=seeding_config, concurrency=concurrency, timeout=link_config.timeout ) return results async def _extract_with_progress( self, urls: List[str], seeding_config: SeedingConfig, link_config: Dict[str, Any] ) -> List[Dict[str, Any]]: """Extract head content with progress reporting.""" total_urls = len(urls) concurrency = link_config.concurrency batch_size = max(1, total_urls // 10) # Report progress every 10% # Process URLs and track progress completed = 0 successful = 0 failed = 0 # Create a custom progress tracking version # We'll modify URLSeeder's method to include progress callbacks # For now, let's use the existing method and report at the end # In a production version, we would modify URLSeeder to accept progress callbacks self._log("info", "Processing links in batches...") # Use existing method results = await self.seeder.extract_head_for_urls( urls=urls, config=seeding_config, concurrency=concurrency, timeout=link_config.timeout ) # Count results for result in results: completed += 1 if result.get("status") == "valid": successful += 1 else: failed += 1 # Final progress report self._log("info", "Batch processing completed: {completed}/{total} processed, {successful} successful, {failed} failed", params={ "completed": completed, "total": total_urls, "successful": successful, "failed": failed }) return results def _merge_head_data( self, original_links: Links, head_results: List[Dict[str, Any]], config: CrawlerRunConfig ) -> Links: """ Merge head extraction results back into Link objects. Args: original_links: Original Links object head_results: Results from head extraction Returns: Links object with head_data attached to matching links """ # Create URL to head_data mapping url_to_head_data = {} for result in head_results: url = result.get("url") if url: url_to_head_data[url] = { "head_data": result.get("head_data", {}), "status": result.get("status", "unknown"), "error": result.get("error"), "relevance_score": result.get("relevance_score") } # Update internal links updated_internal = [] for link in original_links.internal: if link.href in url_to_head_data: head_info = url_to_head_data[link.href] # Create new Link object with head data and scoring contextual_score = head_info.get("relevance_score") updated_link = Link( href=link.href, text=link.text, title=link.title, base_domain=link.base_domain, head_data=head_info["head_data"], head_extraction_status=head_info["status"], head_extraction_error=head_info.get("error"), intrinsic_score=getattr(link, 'intrinsic_score', None), contextual_score=contextual_score ) # Add relevance score to head_data for backward compatibility if contextual_score is not None: updated_link.head_data = updated_link.head_data or {} updated_link.head_data["relevance_score"] = contextual_score # Calculate total score combining intrinsic and contextual scores updated_link.total_score = calculate_total_score( intrinsic_score=updated_link.intrinsic_score, contextual_score=updated_link.contextual_score, score_links_enabled=getattr(config, 'score_links', False), query_provided=bool(config.link_preview_config.query) ) updated_internal.append(updated_link) else: # Keep original link unchanged updated_internal.append(link) # Update external links updated_external = [] for link in original_links.external: if link.href in url_to_head_data: head_info = url_to_head_data[link.href] # Create new Link object with head data and scoring contextual_score = head_info.get("relevance_score") updated_link = Link( href=link.href, text=link.text, title=link.title, base_domain=link.base_domain, head_data=head_info["head_data"], head_extraction_status=head_info["status"], head_extraction_error=head_info.get("error"), intrinsic_score=getattr(link, 'intrinsic_score', None), contextual_score=contextual_score ) # Add relevance score to head_data for backward compatibility if contextual_score is not None: updated_link.head_data = updated_link.head_data or {} updated_link.head_data["relevance_score"] = contextual_score # Calculate total score combining intrinsic and contextual scores updated_link.total_score = calculate_total_score( intrinsic_score=updated_link.intrinsic_score, contextual_score=updated_link.contextual_score, score_links_enabled=getattr(config, 'score_links', False), query_provided=bool(config.link_preview_config.query) ) updated_external.append(updated_link) else: # Keep original link unchanged updated_external.append(link) # Sort links by relevance score if available if any(hasattr(link, 'head_data') and link.head_data and 'relevance_score' in link.head_data for link in updated_internal + updated_external): def get_relevance_score(link): if hasattr(link, 'head_data') and link.head_data and 'relevance_score' in link.head_data: return link.head_data['relevance_score'] return 0.0 updated_internal.sort(key=get_relevance_score, reverse=True) updated_external.sort(key=get_relevance_score, reverse=True) return Links( internal=updated_internal, external=updated_external )
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/link_preview.py", "license": "Apache License 2.0", "lines": 327, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:crawl4ai/script/c4a_compile.py
""" Clean C4A-Script API with Result pattern No exceptions - always returns results """ from __future__ import annotations import pathlib import re from typing import Union, List, Optional # JSON_SCHEMA_BUILDER is still used elsewhere, # but we now also need the new script-builder prompt. from ..prompts import GENERATE_JS_SCRIPT_PROMPT, GENERATE_SCRIPT_PROMPT import logging import re from .c4a_result import ( CompilationResult, ValidationResult, ErrorDetail, WarningDetail, ErrorType, Severity, Suggestion ) from .c4ai_script import Compiler from lark.exceptions import UnexpectedToken, UnexpectedCharacters, VisitError from ..async_configs import LLMConfig from ..utils import perform_completion_with_backoff class C4ACompiler: """Main compiler with result-based API""" # Error code mapping ERROR_CODES = { "missing_then": "E001", "missing_paren": "E002", "missing_comma": "E003", "missing_endproc": "E004", "undefined_proc": "E005", "missing_backticks": "E006", "invalid_command": "E007", "syntax_error": "E999" } @classmethod def compile(cls, script: Union[str, List[str]], root: Optional[pathlib.Path] = None) -> CompilationResult: """ Compile C4A-Script to JavaScript Args: script: C4A-Script as string or list of lines root: Root directory for includes Returns: CompilationResult with success status and JS code or errors """ # Normalize input if isinstance(script, list): script_text = '\n'.join(script) script_lines = script else: script_text = script script_lines = script.split('\n') try: # Try compilation compiler = Compiler(root) js_code = compiler.compile(script_text) # Success! result = CompilationResult( success=True, js_code=js_code, metadata={ "lineCount": len(script_lines), "statementCount": len(js_code) } ) # Add any warnings (future feature) # result.warnings = cls._check_warnings(script_text) return result except Exception as e: # Convert exception to ErrorDetail error = cls._exception_to_error(e, script_lines) return CompilationResult( success=False, errors=[error], metadata={ "lineCount": len(script_lines) } ) @classmethod def validate(cls, script: Union[str, List[str]]) -> ValidationResult: """ Validate script syntax without generating code Args: script: C4A-Script to validate Returns: ValidationResult with validity status and any errors """ result = cls.compile(script) return ValidationResult( valid=result.success, errors=result.errors, warnings=result.warnings ) @classmethod def compile_file(cls, path: Union[str, pathlib.Path]) -> CompilationResult: """ Compile a C4A-Script file Args: path: Path to the file Returns: CompilationResult """ path = pathlib.Path(path) if not path.exists(): error = ErrorDetail( type=ErrorType.RUNTIME, code="E100", severity=Severity.ERROR, message=f"File not found: {path}", line=0, column=0, source_line="" ) return CompilationResult(success=False, errors=[error]) try: script = path.read_text() return cls.compile(script, root=path.parent) except Exception as e: error = ErrorDetail( type=ErrorType.RUNTIME, code="E101", severity=Severity.ERROR, message=f"Error reading file: {str(e)}", line=0, column=0, source_line="" ) return CompilationResult(success=False, errors=[error]) @classmethod def _exception_to_error(cls, exc: Exception, script_lines: List[str]) -> ErrorDetail: """Convert an exception to ErrorDetail""" if isinstance(exc, UnexpectedToken): return cls._handle_unexpected_token(exc, script_lines) elif isinstance(exc, UnexpectedCharacters): return cls._handle_unexpected_chars(exc, script_lines) elif isinstance(exc, ValueError): return cls._handle_value_error(exc, script_lines) else: # Generic error return ErrorDetail( type=ErrorType.SYNTAX, code=cls.ERROR_CODES["syntax_error"], severity=Severity.ERROR, message=str(exc), line=1, column=1, source_line=script_lines[0] if script_lines else "" ) @classmethod def _handle_unexpected_token(cls, exc: UnexpectedToken, script_lines: List[str]) -> ErrorDetail: """Handle UnexpectedToken errors""" line = exc.line column = exc.column # Get context lines source_line = script_lines[line - 1] if 0 < line <= len(script_lines) else "" line_before = script_lines[line - 2] if line > 1 and line <= len(script_lines) + 1 else None line_after = script_lines[line] if 0 < line < len(script_lines) else None # Determine error type and suggestions if exc.token.type == 'CLICK' and 'THEN' in str(exc.expected): code = cls.ERROR_CODES["missing_then"] message = "Missing 'THEN' keyword after IF condition" suggestions = [ Suggestion( "Add 'THEN' after the condition", source_line.replace("CLICK", "THEN CLICK") if source_line else None ) ] elif exc.token.type == '$END': code = cls.ERROR_CODES["missing_endproc"] message = "Unexpected end of script" suggestions = [ Suggestion("Check for missing ENDPROC"), Suggestion("Ensure all procedures are properly closed") ] elif 'RPAR' in str(exc.expected): code = cls.ERROR_CODES["missing_paren"] message = "Missing closing parenthesis ')'" suggestions = [ Suggestion("Add closing parenthesis at the end of the condition") ] elif 'COMMA' in str(exc.expected): code = cls.ERROR_CODES["missing_comma"] message = "Missing comma ',' in command" suggestions = [ Suggestion("Add comma between arguments") ] else: # Check if this might be missing backticks if exc.token.type == 'NAME' and 'BACKTICK_STRING' in str(exc.expected): code = cls.ERROR_CODES["missing_backticks"] message = "Selector must be wrapped in backticks" suggestions = [ Suggestion( "Wrap the selector in backticks", f"`{exc.token.value}`" ) ] else: code = cls.ERROR_CODES["syntax_error"] message = f"Unexpected '{exc.token.value}'" if exc.expected: expected_list = [str(e) for e in exc.expected if not str(e).startswith('_')][:3] if expected_list: message += f". Expected: {', '.join(expected_list)}" suggestions = [] return ErrorDetail( type=ErrorType.SYNTAX, code=code, severity=Severity.ERROR, message=message, line=line, column=column, source_line=source_line, line_before=line_before, line_after=line_after, suggestions=suggestions ) @classmethod def _handle_unexpected_chars(cls, exc: UnexpectedCharacters, script_lines: List[str]) -> ErrorDetail: """Handle UnexpectedCharacters errors""" line = exc.line column = exc.column source_line = script_lines[line - 1] if 0 < line <= len(script_lines) else "" # Check for missing backticks if "CLICK" in source_line and column > source_line.find("CLICK"): code = cls.ERROR_CODES["missing_backticks"] message = "Selector must be wrapped in backticks" suggestions = [ Suggestion( "Wrap the selector in backticks", re.sub(r'CLICK\s+([^\s]+)', r'CLICK `\1`', source_line) ) ] else: code = cls.ERROR_CODES["syntax_error"] message = f"Invalid character at position {column}" suggestions = [] return ErrorDetail( type=ErrorType.SYNTAX, code=code, severity=Severity.ERROR, message=message, line=line, column=column, source_line=source_line, suggestions=suggestions ) @classmethod def _handle_value_error(cls, exc: ValueError, script_lines: List[str]) -> ErrorDetail: """Handle ValueError (runtime errors)""" message = str(exc) # Check for undefined procedure if "Unknown procedure" in message: proc_match = re.search(r"'([^']+)'", message) if proc_match: proc_name = proc_match.group(1) # Find the line with the procedure call for i, line in enumerate(script_lines): if proc_name in line and not line.strip().startswith('PROC'): return ErrorDetail( type=ErrorType.RUNTIME, code=cls.ERROR_CODES["undefined_proc"], severity=Severity.ERROR, message=f"Undefined procedure '{proc_name}'", line=i + 1, column=line.find(proc_name) + 1, source_line=line, suggestions=[ Suggestion( f"Define the procedure before using it", f"PROC {proc_name}\n # commands here\nENDPROC" ) ] ) # Generic runtime error return ErrorDetail( type=ErrorType.RUNTIME, code="E999", severity=Severity.ERROR, message=message, line=1, column=1, source_line=script_lines[0] if script_lines else "" ) @staticmethod def generate_script( html: str, query: str | None = None, mode: str = "c4a", llm_config: LLMConfig | None = None, **completion_kwargs, ) -> str: """ One-shot helper that calls the LLM exactly once to convert a natural-language goal + HTML snippet into either: 1. raw JavaScript (`mode="js"`) 2. Crawl4ai DSL (`mode="c4a"`) The returned string is guaranteed to be free of markdown wrappers or explanatory text, ready for direct execution. """ if llm_config is None: llm_config = LLMConfig() # falls back to env vars / defaults # Build the user chunk user_prompt = "\n".join( [ "## GOAL", "<<goael>>", (query or "Prepare the page for crawling."), "<</goal>>", "", "## HTML", "<<html>>", html[:100000], # guardrail against token blast "<</html>>", "", "## MODE", mode, ] ) # Call the LLM with retry/back-off logic full_prompt = f"{GENERATE_SCRIPT_PROMPT}\n\n{user_prompt}" if mode == "c4a" else f"{GENERATE_JS_SCRIPT_PROMPT}\n\n{user_prompt}" response = perform_completion_with_backoff( provider=llm_config.provider, prompt_with_variables=full_prompt, api_token=llm_config.api_token, json_response=False, base_url=getattr(llm_config, 'base_url', None), **completion_kwargs, ) # Extract content from the response raw_response = response.choices[0].message.content.strip() # Strip accidental markdown fences (```js โ€ฆ ```) clean = re.sub(r"^```(?:[a-zA-Z0-9_-]+)?\s*|```$", "", raw_response, flags=re.MULTILINE).strip() if not clean: raise RuntimeError("LLM returned empty script.") return clean # Convenience functions for direct use def compile(script: Union[str, List[str]], root: Optional[pathlib.Path] = None) -> CompilationResult: """Compile C4A-Script to JavaScript""" return C4ACompiler.compile(script, root) def validate(script: Union[str, List[str]]) -> ValidationResult: """Validate C4A-Script syntax""" return C4ACompiler.validate(script) def compile_file(path: Union[str, pathlib.Path]) -> CompilationResult: """Compile C4A-Script file""" return C4ACompiler.compile_file(path)
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/script/c4a_compile.py", "license": "Apache License 2.0", "lines": 345, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:crawl4ai/script/c4a_result.py
""" Result classes for C4A-Script compilation Clean API design with no exceptions """ from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import List, Dict, Any, Optional import json class ErrorType(Enum): SYNTAX = "syntax" SEMANTIC = "semantic" RUNTIME = "runtime" class Severity(Enum): ERROR = "error" WARNING = "warning" INFO = "info" @dataclass class Suggestion: """A suggestion for fixing an error""" message: str fix: Optional[str] = None def to_dict(self) -> dict: return { "message": self.message, "fix": self.fix } @dataclass class ErrorDetail: """Detailed information about a compilation error""" # Core info type: ErrorType code: str # E001, E002, etc. severity: Severity message: str # Location line: int column: int # Context source_line: str # Optional fields with defaults end_line: Optional[int] = None end_column: Optional[int] = None line_before: Optional[str] = None line_after: Optional[str] = None # Help suggestions: List[Suggestion] = field(default_factory=list) documentation_url: Optional[str] = None def to_dict(self) -> dict: """Convert to dictionary for JSON serialization""" return { "type": self.type.value, "code": self.code, "severity": self.severity.value, "message": self.message, "location": { "line": self.line, "column": self.column, "endLine": self.end_line, "endColumn": self.end_column }, "context": { "sourceLine": self.source_line, "lineBefore": self.line_before, "lineAfter": self.line_after, "marker": { "start": self.column - 1, "length": (self.end_column - self.column) if self.end_column else 1 } }, "suggestions": [s.to_dict() for s in self.suggestions], "documentationUrl": self.documentation_url } def to_json(self) -> str: """Convert to JSON string""" return json.dumps(self.to_dict(), indent=2) @property def formatted_message(self) -> str: """Returns the nice text format for terminals""" lines = [] lines.append(f"\n{'='*60}") lines.append(f"{self.type.value.title()} Error [{self.code}]") lines.append(f"{'='*60}") lines.append(f"Location: Line {self.line}, Column {self.column}") lines.append(f"Error: {self.message}") if self.source_line: marker = " " * (self.column - 1) + "^" if self.end_column: marker += "~" * (self.end_column - self.column - 1) lines.append(f"\nCode:") if self.line_before: lines.append(f" {self.line - 1: >3} | {self.line_before}") lines.append(f" {self.line: >3} | {self.source_line}") lines.append(f" | {marker}") if self.line_after: lines.append(f" {self.line + 1: >3} | {self.line_after}") if self.suggestions: lines.append("\nSuggestions:") for i, suggestion in enumerate(self.suggestions, 1): lines.append(f" {i}. {suggestion.message}") if suggestion.fix: lines.append(f" Fix: {suggestion.fix}") lines.append("="*60) return "\n".join(lines) @property def simple_message(self) -> str: """Returns just the error message without formatting""" return f"Line {self.line}: {self.message}" @dataclass class WarningDetail: """Information about a compilation warning""" code: str message: str line: int column: int def to_dict(self) -> dict: return { "code": self.code, "message": self.message, "line": self.line, "column": self.column } @dataclass class CompilationResult: """Result of C4A-Script compilation""" success: bool js_code: Optional[List[str]] = None errors: List[ErrorDetail] = field(default_factory=list) warnings: List[WarningDetail] = field(default_factory=list) metadata: Dict[str, Any] = field(default_factory=dict) def to_dict(self) -> dict: """Convert to dictionary for JSON serialization""" return { "success": self.success, "jsCode": self.js_code, "errors": [e.to_dict() for e in self.errors], "warnings": [w.to_dict() for w in self.warnings], "metadata": self.metadata } def to_json(self) -> str: """Convert to JSON string""" return json.dumps(self.to_dict(), indent=2) @property def has_errors(self) -> bool: """Check if there are any errors""" return len(self.errors) > 0 @property def has_warnings(self) -> bool: """Check if there are any warnings""" return len(self.warnings) > 0 @property def first_error(self) -> Optional[ErrorDetail]: """Get the first error if any""" return self.errors[0] if self.errors else None def __str__(self) -> str: """String representation for debugging""" if self.success: msg = f"โœ“ Compilation successful" if self.js_code: msg += f" - {len(self.js_code)} statements generated" if self.warnings: msg += f" ({len(self.warnings)} warnings)" return msg else: return f"โœ— Compilation failed - {len(self.errors)} error(s)" @dataclass class ValidationResult: """Result of script validation""" valid: bool errors: List[ErrorDetail] = field(default_factory=list) warnings: List[WarningDetail] = field(default_factory=list) def to_dict(self) -> dict: return { "valid": self.valid, "errors": [e.to_dict() for e in self.errors], "warnings": [w.to_dict() for w in self.warnings] } def to_json(self) -> str: return json.dumps(self.to_dict(), indent=2) @property def first_error(self) -> Optional[ErrorDetail]: return self.errors[0] if self.errors else None
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/script/c4a_result.py", "license": "Apache License 2.0", "lines": 182, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:crawl4ai/script/c4ai_script.py
""" 2025-06-03 By Unclcode: C4A-Script Language Documentation Feeds Crawl4AI via CrawlerRunConfig(js_code=[ ... ]) โ€“ no core modifications. """ from __future__ import annotations import pathlib, re, sys, textwrap from dataclasses import dataclass from typing import Any, Dict, List, Union from lark import Lark, Transformer, v_args from lark.exceptions import UnexpectedToken, UnexpectedCharacters, VisitError # --------------------------------------------------------------------------- # # Custom Error Classes # --------------------------------------------------------------------------- # class C4AScriptError(Exception): """Custom error class for C4A-Script compilation errors""" def __init__(self, message: str, line: int = None, column: int = None, error_type: str = "Syntax Error", details: str = None): self.message = message self.line = line self.column = column self.error_type = error_type self.details = details super().__init__(self._format_message()) def _format_message(self) -> str: """Format a clear error message""" lines = [f"\n{'='*60}"] lines.append(f"C4A-Script {self.error_type}") lines.append(f"{'='*60}") if self.line: lines.append(f"Location: Line {self.line}" + (f", Column {self.column}" if self.column else "")) lines.append(f"Error: {self.message}") if self.details: lines.append(f"\nDetails: {self.details}") lines.append("="*60) return "\n".join(lines) @classmethod def from_exception(cls, exc: Exception, script: Union[str, List[str]]) -> 'C4AScriptError': """Create C4AScriptError from another exception""" script_text = script if isinstance(script, str) else '\n'.join(script) script_lines = script_text.split('\n') if isinstance(exc, UnexpectedToken): # Extract line and column from UnexpectedToken line = exc.line column = exc.column # Get the problematic line if 0 < line <= len(script_lines): problem_line = script_lines[line - 1] marker = " " * (column - 1) + "^" details = f"\nCode:\n {problem_line}\n {marker}\n" # Improve error message based on context if exc.token.type == 'CLICK' and 'THEN' in str(exc.expected): message = "Missing 'THEN' keyword after IF condition" elif exc.token.type == '$END': message = "Unexpected end of script. Check for missing ENDPROC or incomplete commands" elif 'RPAR' in str(exc.expected): message = "Missing closing parenthesis ')'" elif 'COMMA' in str(exc.expected): message = "Missing comma ',' in command" else: message = f"Unexpected '{exc.token}'" if exc.expected: expected_list = [str(e) for e in exc.expected if not e.startswith('_')] if expected_list: message += f". Expected: {', '.join(expected_list[:3])}" details += f"Token: {exc.token.type} ('{exc.token.value}')" else: message = str(exc) details = None return cls(message, line, column, "Syntax Error", details) elif isinstance(exc, UnexpectedCharacters): # Extract line and column line = exc.line column = exc.column if 0 < line <= len(script_lines): problem_line = script_lines[line - 1] marker = " " * (column - 1) + "^" details = f"\nCode:\n {problem_line}\n {marker}\n" message = f"Invalid character or unexpected text at position {column}" else: message = str(exc) details = None return cls(message, line, column, "Syntax Error", details) elif isinstance(exc, ValueError): # Handle runtime errors like undefined procedures message = str(exc) # Try to find which line caused the error if "Unknown procedure" in message: proc_name = re.search(r"'([^']+)'", message) if proc_name: proc_name = proc_name.group(1) for i, line in enumerate(script_lines, 1): if proc_name in line and not line.strip().startswith('PROC'): details = f"\nCode:\n {line.strip()}\n\nMake sure the procedure '{proc_name}' is defined with PROC...ENDPROC" return cls(f"Undefined procedure '{proc_name}'", i, None, "Runtime Error", details) return cls(message, None, None, "Runtime Error", None) else: # Generic error return cls(str(exc), None, None, "Compilation Error", None) # --------------------------------------------------------------------------- # # 1. Grammar # --------------------------------------------------------------------------- # GRAMMAR = r""" start : line* ?line : command | proc_def | include | comment command : wait | nav | click_cmd | double_click | right_click | move | drag | scroll | type | clear | set_input | press | key_down | key_up | eval_cmd | setvar | proc_call | if_cmd | repeat_cmd wait : "WAIT" (ESCAPED_STRING|BACKTICK_STRING|NUMBER) NUMBER? -> wait_cmd nav : "GO" URL -> go | "RELOAD" -> reload | "BACK" -> back | "FORWARD" -> forward click_cmd : "CLICK" (BACKTICK_STRING|NUMBER NUMBER) -> click double_click : "DOUBLE_CLICK" (BACKTICK_STRING|NUMBER NUMBER) -> double_click right_click : "RIGHT_CLICK" (BACKTICK_STRING|NUMBER NUMBER) -> right_click move : "MOVE" coords -> move drag : "DRAG" coords coords -> drag scroll : "SCROLL" DIR NUMBER? -> scroll type : "TYPE" (ESCAPED_STRING | NAME) -> type clear : "CLEAR" BACKTICK_STRING -> clear set_input : "SET" BACKTICK_STRING (ESCAPED_STRING | BACKTICK_STRING | NAME) -> set_input press : "PRESS" WORD -> press key_down : "KEY_DOWN" WORD -> key_down key_up : "KEY_UP" WORD -> key_up eval_cmd : "EVAL" BACKTICK_STRING -> eval_cmd setvar : "SETVAR" NAME "=" value -> setvar proc_call : NAME -> proc_call proc_def : "PROC" NAME line* "ENDPROC" -> proc_def include : "USE" ESCAPED_STRING -> include comment : /#.*/ -> comment if_cmd : "IF" "(" condition ")" "THEN" command ("ELSE" command)? -> if_cmd repeat_cmd : "REPEAT" "(" command "," repeat_count ")" -> repeat_cmd condition : not_cond | exists_cond | js_cond not_cond : "NOT" condition -> not_cond exists_cond : "EXISTS" BACKTICK_STRING -> exists_cond js_cond : BACKTICK_STRING -> js_cond repeat_count : NUMBER | BACKTICK_STRING coords : NUMBER NUMBER value : ESCAPED_STRING | BACKTICK_STRING | NUMBER DIR : /(UP|DOWN|LEFT|RIGHT)/i REST : /[^\n]+/ URL : /(http|https):\/\/[^\s]+/ NAME : /\$?[A-Za-z_][A-Za-z0-9_]*/ WORD : /[A-Za-z0-9+]+/ BACKTICK_STRING : /`[^`]*`/ %import common.NUMBER %import common.ESCAPED_STRING %import common.WS_INLINE %import common.NEWLINE %ignore WS_INLINE %ignore NEWLINE """ # --------------------------------------------------------------------------- # # 2. IR dataclasses # --------------------------------------------------------------------------- # @dataclass class Cmd: op: str args: List[Any] @dataclass class Proc: name: str body: List[Cmd] # --------------------------------------------------------------------------- # # 3. AST โ†’ IR # --------------------------------------------------------------------------- # @v_args(inline=True) class ASTBuilder(Transformer): # helpers def _strip(self, s): if s.startswith('"') and s.endswith('"'): return s[1:-1] elif s.startswith('`') and s.endswith('`'): return s[1:-1] return s def start(self,*i): return list(i) def line(self,i): return i def command(self,i): return i # WAIT def wait_cmd(self, rest, timeout=None): rest_str = str(rest) # Check if it's a number (including floats) try: num_val = float(rest_str) payload = (num_val, "seconds") except ValueError: if rest_str.startswith('"') and rest_str.endswith('"'): payload = (self._strip(rest_str), "text") elif rest_str.startswith('`') and rest_str.endswith('`'): payload = (self._strip(rest_str), "selector") else: payload = (rest_str, "selector") return Cmd("WAIT", [payload, int(timeout) if timeout else None]) # NAV def go(self,u): return Cmd("GO",[str(u)]) def reload(self): return Cmd("RELOAD",[]) def back(self): return Cmd("BACK",[]) def forward(self): return Cmd("FORWARD",[]) # CLICK, DOUBLE_CLICK, RIGHT_CLICK def click(self, *args): return self._handle_click("CLICK", args) def double_click(self, *args): return self._handle_click("DBLCLICK", args) def right_click(self, *args): return self._handle_click("RIGHTCLICK", args) def _handle_click(self, op, args): if len(args) == 1: # Single argument - backtick string target = self._strip(str(args[0])) return Cmd(op, [("selector", target)]) else: # Two arguments - coordinates x, y = args return Cmd(op, [("coords", int(x), int(y))]) # MOVE / DRAG / SCROLL def coords(self,x,y): return ("coords",int(x),int(y)) def move(self,c): return Cmd("MOVE",[c]) def drag(self,c1,c2): return Cmd("DRAG",[c1,c2]) def scroll(self,dir_tok,amt=None): return Cmd("SCROLL",[dir_tok.upper(), int(amt) if amt else 500]) # KEYS def type(self,tok): return Cmd("TYPE",[self._strip(str(tok))]) def clear(self,sel): return Cmd("CLEAR",[self._strip(str(sel))]) def set_input(self,sel,val): return Cmd("SET",[self._strip(str(sel)), self._strip(str(val))]) def press(self,w): return Cmd("PRESS",[str(w)]) def key_down(self,w): return Cmd("KEYDOWN",[str(w)]) def key_up(self,w): return Cmd("KEYUP",[str(w)]) # FLOW def eval_cmd(self,txt): return Cmd("EVAL",[self._strip(str(txt))]) def setvar(self,n,v): # v might be a Token or a Tree, extract value properly if hasattr(v, 'value'): value = v.value elif hasattr(v, 'children') and len(v.children) > 0: value = v.children[0].value else: value = str(v) return Cmd("SETVAR",[str(n), self._strip(value)]) def proc_call(self,n): return Cmd("CALL",[str(n)]) def proc_def(self,n,*body): return Proc(str(n),[b for b in body if isinstance(b,Cmd)]) def include(self,p): return Cmd("INCLUDE",[self._strip(p)]) def comment(self,*_): return Cmd("NOP",[]) # IF-THEN-ELSE and EXISTS def if_cmd(self, condition, then_cmd, else_cmd=None): return Cmd("IF", [condition, then_cmd, else_cmd]) def condition(self, cond): return cond def not_cond(self, cond): return ("NOT", cond) def exists_cond(self, selector): return ("EXISTS", self._strip(str(selector))) def js_cond(self, expr): return ("JS", self._strip(str(expr))) # REPEAT def repeat_cmd(self, cmd, count): return Cmd("REPEAT", [cmd, count]) def repeat_count(self, value): return str(value) # --------------------------------------------------------------------------- # # 4. Compiler # --------------------------------------------------------------------------- # class Compiler: def __init__(self, root: pathlib.Path|None=None): self.parser = Lark(GRAMMAR,start="start",parser="lalr") self.root = pathlib.Path(root or ".").resolve() self.vars: Dict[str,Any] = {} self.procs: Dict[str,Proc]= {} def compile(self, text: Union[str, List[str]]) -> List[str]: # Handle list input by joining with newlines if isinstance(text, list): text = '\n'.join(text) ir = self._parse_with_includes(text) ir = self._collect_procs(ir) ir = self._inline_calls(ir) ir = self._apply_set_vars(ir) return [self._emit_js(c) for c in ir if isinstance(c,Cmd) and c.op!="NOP"] # passes def _parse_with_includes(self,txt,seen=None): seen=seen or set() cmds=ASTBuilder().transform(self.parser.parse(txt)) out=[] for c in cmds: if isinstance(c,Cmd) and c.op=="INCLUDE": p=(self.root/c.args[0]).resolve() if p in seen: raise ValueError(f"Circular include {p}") seen.add(p); out+=self._parse_with_includes(p.read_text(),seen) else: out.append(c) return out def _collect_procs(self,ir): out=[] for i in ir: if isinstance(i,Proc): self.procs[i.name]=i else: out.append(i) return out def _inline_calls(self,ir): out=[] for c in ir: if isinstance(c,Cmd) and c.op=="CALL": if c.args[0] not in self.procs: raise ValueError(f"Unknown procedure {c.args[0]!r}") out+=self._inline_calls(self.procs[c.args[0]].body) else: out.append(c) return out def _apply_set_vars(self,ir): def sub(s): return re.sub(r"\$(\w+)",lambda m:str(self.vars.get(m.group(1),m.group(0))) ,s) if isinstance(s,str) else s out=[] for c in ir: if isinstance(c,Cmd): if c.op=="SETVAR": # Store variable self.vars[c.args[0].lstrip('$')]=c.args[1] else: # Apply variable substitution to commands that use them if c.op in("TYPE","EVAL","SET"): c.args=[sub(a) for a in c.args] out.append(c) return out # JS emitter def _emit_js(self, cmd: Cmd) -> str: op, a = cmd.op, cmd.args if op == "GO": return f"window.location.href = '{a[0]}';" if op == "RELOAD": return "window.location.reload();" if op == "BACK": return "window.history.back();" if op == "FORWARD": return "window.history.forward();" if op == "WAIT": arg, kind = a[0] timeout = a[1] or 10 if kind == "seconds": return f"await new Promise(r=>setTimeout(r,{arg}*1000));" if kind == "selector": sel = arg.replace("\\","\\\\").replace("'","\\'") return textwrap.dedent(f""" await new Promise((res,rej)=>{{ const max = {timeout*1000}, t0 = performance.now(); const id = setInterval(()=>{{ if(document.querySelector('{sel}')){{clearInterval(id);res();}} else if(performance.now()-t0>max){{clearInterval(id);rej('WAIT selector timeout');}} }},100); }}); """).strip() if kind == "text": txt = arg.replace('`', '\\`') return textwrap.dedent(f""" await new Promise((res,rej)=>{{ const max={timeout*1000},t0=performance.now(); const id=setInterval(()=>{{ if(document.body.innerText.includes(`{txt}`)){{clearInterval(id);res();}} else if(performance.now()-t0>max){{clearInterval(id);rej('WAIT text timeout');}} }},100); }}); """).strip() # click-style helpers def _js_click(sel, evt="click", button=0, detail=1): sel = sel.replace("'", "\\'") return textwrap.dedent(f""" (()=>{{ const el=document.querySelector('{sel}'); if(el){{ el.focus&&el.focus(); el.dispatchEvent(new MouseEvent('{evt}',{{bubbles:true,button:{button},detail:{detail}}})); }} }})(); """).strip() def _js_click_xy(x, y, evt="click", button=0, detail=1): return textwrap.dedent(f""" (()=>{{ const el=document.elementFromPoint({x},{y}); if(el){{ el.focus&&el.focus(); el.dispatchEvent(new MouseEvent('{evt}',{{bubbles:true,button:{button},detail:{detail}}})); }} }})(); """).strip() if op in ("CLICK", "DBLCLICK", "RIGHTCLICK"): evt = {"CLICK":"click","DBLCLICK":"dblclick","RIGHTCLICK":"contextmenu"}[op] btn = 2 if op=="RIGHTCLICK" else 0 det = 2 if op=="DBLCLICK" else 1 kind,*rest = a[0] return _js_click_xy(*rest) if kind=="coords" else _js_click(rest[0],evt,btn,det) if op == "MOVE": _, x, y = a[0] return textwrap.dedent(f""" document.dispatchEvent(new MouseEvent('mousemove',{{clientX:{x},clientY:{y},bubbles:true}})); """).strip() if op == "DRAG": (_, x1, y1), (_, x2, y2) = a return textwrap.dedent(f""" (()=>{{ const s=document.elementFromPoint({x1},{y1}); if(!s) return; s.dispatchEvent(new MouseEvent('mousedown',{{bubbles:true,clientX:{x1},clientY:{y1}}})); document.dispatchEvent(new MouseEvent('mousemove',{{bubbles:true,clientX:{x2},clientY:{y2}}})); document.dispatchEvent(new MouseEvent('mouseup', {{bubbles:true,clientX:{x2},clientY:{y2}}})); }})(); """).strip() if op == "SCROLL": dir_, amt = a dx, dy = {"UP":(0,-amt),"DOWN":(0,amt),"LEFT":(-amt,0),"RIGHT":(amt,0)}[dir_] return f"window.scrollBy({dx},{dy});" if op == "TYPE": txt = a[0].replace("'", "\\'") return textwrap.dedent(f""" (()=>{{ const el=document.activeElement; if(el){{ el.value += '{txt}'; el.dispatchEvent(new Event('input',{{bubbles:true}})); }} }})(); """).strip() if op == "CLEAR": sel = a[0].replace("'", "\\'") return textwrap.dedent(f""" (()=>{{ const el=document.querySelector('{sel}'); if(el && 'value' in el){{ el.value = ''; el.dispatchEvent(new Event('input',{{bubbles:true}})); el.dispatchEvent(new Event('change',{{bubbles:true}})); }} }})(); """).strip() if op == "SET" and len(a) == 2: # This is SET for input fields (SET `#field` "value") sel = a[0].replace("'", "\\'") val = a[1].replace("'", "\\'") return textwrap.dedent(f""" (()=>{{ const el=document.querySelector('{sel}'); if(el && 'value' in el){{ el.value = ''; el.focus&&el.focus(); el.value = '{val}'; el.dispatchEvent(new Event('input',{{bubbles:true}})); el.dispatchEvent(new Event('change',{{bubbles:true}})); }} }})(); """).strip() if op in ("PRESS","KEYDOWN","KEYUP"): key = a[0] evs = {"PRESS":("keydown","keyup"),"KEYDOWN":("keydown",),"KEYUP":("keyup",)}[op] return ";".join([f"document.dispatchEvent(new KeyboardEvent('{e}',{{key:'{key}',bubbles:true}}))" for e in evs]) + ";" if op == "EVAL": return textwrap.dedent(f""" (()=>{{ try {{ {a[0]}; }} catch (e) {{ console.error('C4A-Script EVAL error:', e); }} }})(); """).strip() if op == "IF": condition, then_cmd, else_cmd = a # Generate condition JavaScript js_condition = self._emit_condition(condition) # Generate commands - handle both regular commands and procedure calls then_js = self._handle_cmd_or_proc(then_cmd) else_js = self._handle_cmd_or_proc(else_cmd) if else_cmd else "" if else_cmd: return textwrap.dedent(f""" if ({js_condition}) {{ {then_js} }} else {{ {else_js} }} """).strip() else: return textwrap.dedent(f""" if ({js_condition}) {{ {then_js} }} """).strip() if op == "REPEAT": cmd, count = a # Handle the count - could be number or JS expression if count.isdigit(): # Simple number repeat_js = self._handle_cmd_or_proc(cmd) return textwrap.dedent(f""" for (let _i = 0; _i < {count}; _i++) {{ {repeat_js} }} """).strip() else: # JS expression (from backticks) count_expr = count[1:-1] if count.startswith('`') and count.endswith('`') else count repeat_js = self._handle_cmd_or_proc(cmd) return textwrap.dedent(f""" (()=>{{ const _count = {count_expr}; if (typeof _count === 'number') {{ for (let _i = 0; _i < _count; _i++) {{ {repeat_js} }} }} else if (_count) {{ {repeat_js} }} }})(); """).strip() raise ValueError(f"Unhandled op {op}") def _emit_condition(self, condition): """Convert a condition tuple to JavaScript""" cond_type = condition[0] if cond_type == "EXISTS": return f"!!document.querySelector('{condition[1]}')" elif cond_type == "NOT": # Recursively handle the negated condition inner_condition = self._emit_condition(condition[1]) return f"!({inner_condition})" else: # JS condition return condition[1] def _handle_cmd_or_proc(self, cmd): """Handle a command that might be a regular command or a procedure call""" if not cmd: return "" if isinstance(cmd, Cmd): if cmd.op == "CALL": # Inline the procedure if cmd.args[0] not in self.procs: raise ValueError(f"Unknown procedure {cmd.args[0]!r}") proc_body = self.procs[cmd.args[0]].body return "\n".join([self._emit_js(c) for c in proc_body if c.op != "NOP"]) else: return self._emit_js(cmd) return "" # --------------------------------------------------------------------------- # # 5. Helpers + demo # --------------------------------------------------------------------------- # def compile_string(script: Union[str, List[str]], *, root: Union[pathlib.Path, None] = None) -> List[str]: """Compile C4A-Script from string or list of strings to JavaScript. Args: script: C4A-Script as a string or list of command strings root: Root directory for resolving includes (optional) Returns: List of JavaScript command strings Raises: C4AScriptError: When compilation fails with detailed error information """ try: return Compiler(root).compile(script) except Exception as e: # Wrap the error with better formatting raise C4AScriptError.from_exception(e, script) def compile_file(path: pathlib.Path) -> List[str]: """Compile C4A-Script from file to JavaScript. Args: path: Path to C4A-Script file Returns: List of JavaScript command strings """ return compile_string(path.read_text(), root=path.parent) def compile_lines(lines: List[str], *, root: Union[pathlib.Path, None] = None) -> List[str]: """Compile C4A-Script from list of lines to JavaScript. Args: lines: List of C4A-Script command lines root: Root directory for resolving includes (optional) Returns: List of JavaScript command strings """ return compile_string(lines, root=root) DEMO = """ # quick sanity demo PROC login SET `input[name="username"]` $user SET `input[name="password"]` $pass CLICK `button.submit` ENDPROC SETVAR user = "tom@crawl4ai.com" SETVAR pass = "hunter2" GO https://example.com/login WAIT `input[name="username"]` 10 login WAIT 3 EVAL `console.log('logged in')` """ if __name__ == "__main__": if len(sys.argv) == 2: for js in compile_file(pathlib.Path(sys.argv[1])): print(js) else: print("=== DEMO ===") for js in compile_string(DEMO): print(js)
{ "repo_id": "unclecode/crawl4ai", "file_path": "crawl4ai/script/c4ai_script.py", "license": "Apache License 2.0", "lines": 585, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/adaptive_crawling/advanced_configuration.py
""" Advanced Adaptive Crawling Configuration This example demonstrates all configuration options available for adaptive crawling, including threshold tuning, persistence, and custom parameters. """ import asyncio from pathlib import Path from crawl4ai import AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig async def main(): """Demonstrate advanced configuration options""" # Example 1: Custom thresholds for different use cases print("="*60) print("EXAMPLE 1: Custom Confidence Thresholds") print("="*60) # High-precision configuration (exhaustive crawling) high_precision_config = AdaptiveConfig( confidence_threshold=0.9, # Very high confidence required max_pages=50, # Allow more pages top_k_links=5, # Follow more links per page min_gain_threshold=0.02 # Lower threshold to continue ) # Balanced configuration (default use case) balanced_config = AdaptiveConfig( confidence_threshold=0.7, # Moderate confidence max_pages=20, # Reasonable limit top_k_links=3, # Moderate branching min_gain_threshold=0.05 # Standard gain threshold ) # Quick exploration configuration quick_config = AdaptiveConfig( confidence_threshold=0.5, # Lower confidence acceptable max_pages=10, # Strict limit top_k_links=2, # Minimal branching min_gain_threshold=0.1 # High gain required ) async with AsyncWebCrawler(verbose=False) as crawler: # Test different configurations for config_name, config in [ ("High Precision", high_precision_config), ("Balanced", balanced_config), ("Quick Exploration", quick_config) ]: print(f"\nTesting {config_name} configuration...") adaptive = AdaptiveCrawler(crawler, config=config) result = await adaptive.digest( start_url="https://httpbin.org", query="http headers authentication" ) print(f" - Pages crawled: {len(result.crawled_urls)}") print(f" - Confidence achieved: {adaptive.confidence:.2%}") print(f" - Coverage score: {adaptive.coverage_stats['coverage']:.2f}") # Example 2: Persistence and state management print("\n" + "="*60) print("EXAMPLE 2: State Persistence") print("="*60) state_file = "crawl_state_demo.json" # Configuration with persistence persistent_config = AdaptiveConfig( confidence_threshold=0.8, max_pages=30, save_state=True, # Enable auto-save state_path=state_file # Specify save location ) async with AsyncWebCrawler(verbose=False) as crawler: # First crawl - will be interrupted print("\nStarting initial crawl (will interrupt after 5 pages)...") interrupt_config = AdaptiveConfig( confidence_threshold=0.8, max_pages=5, # Artificially low to simulate interruption save_state=True, state_path=state_file ) adaptive = AdaptiveCrawler(crawler, config=interrupt_config) result1 = await adaptive.digest( start_url="https://docs.python.org/3/", query="exception handling try except finally" ) print(f"First crawl completed: {len(result1.crawled_urls)} pages") print(f"Confidence reached: {adaptive.confidence:.2%}") # Resume crawl with higher page limit print("\nResuming crawl from saved state...") resume_config = AdaptiveConfig( confidence_threshold=0.8, max_pages=20, # Increase limit save_state=True, state_path=state_file ) adaptive2 = AdaptiveCrawler(crawler, config=resume_config) result2 = await adaptive2.digest( start_url="https://docs.python.org/3/", query="exception handling try except finally", resume_from=state_file ) print(f"Resumed crawl completed: {len(result2.crawled_urls)} total pages") print(f"Final confidence: {adaptive2.confidence:.2%}") # Clean up Path(state_file).unlink(missing_ok=True) # Example 3: Link selection strategies print("\n" + "="*60) print("EXAMPLE 3: Link Selection Strategies") print("="*60) # Conservative link following conservative_config = AdaptiveConfig( confidence_threshold=0.7, max_pages=15, top_k_links=1, # Only follow best link min_gain_threshold=0.15 # High threshold ) # Aggressive link following aggressive_config = AdaptiveConfig( confidence_threshold=0.7, max_pages=15, top_k_links=10, # Follow many links min_gain_threshold=0.01 # Very low threshold ) async with AsyncWebCrawler(verbose=False) as crawler: for strategy_name, config in [ ("Conservative", conservative_config), ("Aggressive", aggressive_config) ]: print(f"\n{strategy_name} link selection:") adaptive = AdaptiveCrawler(crawler, config=config) result = await adaptive.digest( start_url="https://httpbin.org", query="api endpoints" ) # Analyze crawl pattern print(f" - Total pages: {len(result.crawled_urls)}") print(f" - Unique domains: {len(set(url.split('/')[2] for url in result.crawled_urls))}") print(f" - Max depth reached: {max(url.count('/') for url in result.crawled_urls) - 2}") # Show saturation trend if hasattr(result, 'new_terms_history') and result.new_terms_history: print(f" - New terms discovered: {result.new_terms_history[:5]}...") print(f" - Saturation trend: {'decreasing' if result.new_terms_history[-1] < result.new_terms_history[0] else 'increasing'}") # Example 4: Monitoring crawl progress print("\n" + "="*60) print("EXAMPLE 4: Progress Monitoring") print("="*60) # Configuration with detailed monitoring monitor_config = AdaptiveConfig( confidence_threshold=0.75, max_pages=10, top_k_links=3 ) async with AsyncWebCrawler(verbose=False) as crawler: adaptive = AdaptiveCrawler(crawler, config=monitor_config) # Start crawl print("\nMonitoring crawl progress...") result = await adaptive.digest( start_url="https://httpbin.org", query="http methods headers" ) # Detailed statistics print("\nDetailed crawl analysis:") adaptive.print_stats(detailed=True) # Export for analysis print("\nExporting knowledge base for external analysis...") adaptive.export_knowledge_base("knowledge_export_demo.jsonl") print("Knowledge base exported to: knowledge_export_demo.jsonl") # Show sample of exported data with open("knowledge_export_demo.jsonl", 'r') as f: first_line = f.readline() print(f"Sample export: {first_line[:100]}...") # Clean up Path("knowledge_export_demo.jsonl").unlink(missing_ok=True) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/adaptive_crawling/advanced_configuration.py", "license": "Apache License 2.0", "lines": 167, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/adaptive_crawling/basic_usage.py
""" Basic Adaptive Crawling Example This example demonstrates the simplest use case of adaptive crawling: finding information about a specific topic and knowing when to stop. """ import asyncio from crawl4ai import AsyncWebCrawler, AdaptiveCrawler async def main(): """Basic adaptive crawling example""" # Initialize the crawler async with AsyncWebCrawler(verbose=True) as crawler: # Create an adaptive crawler with default settings (statistical strategy) adaptive = AdaptiveCrawler(crawler) # Note: You can also use embedding strategy for semantic understanding: # from crawl4ai import AdaptiveConfig # config = AdaptiveConfig(strategy="embedding") # adaptive = AdaptiveCrawler(crawler, config) # Start adaptive crawling print("Starting adaptive crawl for Python async programming information...") result = await adaptive.digest( start_url="https://docs.python.org/3/library/asyncio.html", query="async await context managers coroutines" ) # Display crawl statistics print("\n" + "="*50) print("CRAWL STATISTICS") print("="*50) adaptive.print_stats(detailed=False) # Get the most relevant content found print("\n" + "="*50) print("MOST RELEVANT PAGES") print("="*50) relevant_pages = adaptive.get_relevant_content(top_k=5) for i, page in enumerate(relevant_pages, 1): print(f"\n{i}. {page['url']}") print(f" Relevance Score: {page['score']:.2%}") # Show a snippet of the content content = page['content'] or "" if content: snippet = content[:200].replace('\n', ' ') if len(content) > 200: snippet += "..." print(f" Preview: {snippet}") # Show final confidence print(f"\n{'='*50}") print(f"Final Confidence: {adaptive.confidence:.2%}") print(f"Total Pages Crawled: {len(result.crawled_urls)}") print(f"Knowledge Base Size: {len(adaptive.state.knowledge_base)} documents") # Example: Check if we can answer specific questions print(f"\n{'='*50}") print("INFORMATION SUFFICIENCY CHECK") print(f"{'='*50}") if adaptive.confidence >= 0.8: print("โœ“ High confidence - can answer detailed questions about async Python") elif adaptive.confidence >= 0.6: print("~ Moderate confidence - can answer basic questions") else: print("โœ— Low confidence - need more information") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/adaptive_crawling/basic_usage.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/adaptive_crawling/custom_strategies.py
""" Custom Adaptive Crawling Strategies This example demonstrates how to implement custom scoring strategies for domain-specific crawling needs. """ import asyncio import re from typing import List, Dict, Set from crawl4ai import AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig from crawl4ai.adaptive_crawler import CrawlState, Link import math class APIDocumentationStrategy: """ Custom strategy optimized for API documentation crawling. Prioritizes endpoint references, code examples, and parameter descriptions. """ def __init__(self): # Keywords that indicate high-value API documentation self.api_keywords = { 'endpoint', 'request', 'response', 'parameter', 'authentication', 'header', 'body', 'query', 'path', 'method', 'get', 'post', 'put', 'delete', 'patch', 'status', 'code', 'example', 'curl', 'python' } # URL patterns that typically contain API documentation self.valuable_patterns = [ r'/api/', r'/reference/', r'/endpoints?/', r'/methods?/', r'/resources?/' ] # Patterns to avoid self.avoid_patterns = [ r'/blog/', r'/news/', r'/about/', r'/contact/', r'/legal/' ] def score_link(self, link: Link, query: str, state: CrawlState) -> float: """Custom link scoring for API documentation""" score = 1.0 url = link.href.lower() # Boost API-related URLs for pattern in self.valuable_patterns: if re.search(pattern, url): score *= 2.0 break # Reduce score for non-API content for pattern in self.avoid_patterns: if re.search(pattern, url): score *= 0.1 break # Boost if preview contains API keywords if link.text: preview_lower = link.text.lower() keyword_count = sum(1 for kw in self.api_keywords if kw in preview_lower) score *= (1 + keyword_count * 0.2) # Prioritize shallow URLs (likely overview pages) depth = url.count('/') - 2 # Subtract protocol slashes if depth <= 3: score *= 1.5 elif depth > 6: score *= 0.5 return score def calculate_api_coverage(self, state: CrawlState, query: str) -> Dict[str, float]: """Calculate specialized coverage metrics for API documentation""" metrics = { 'endpoint_coverage': 0.0, 'example_coverage': 0.0, 'parameter_coverage': 0.0 } # Analyze knowledge base for API-specific content endpoint_patterns = [r'GET\s+/', r'POST\s+/', r'PUT\s+/', r'DELETE\s+/'] example_patterns = [r'```\w+', r'curl\s+-', r'import\s+requests'] param_patterns = [r'param(?:eter)?s?\s*:', r'required\s*:', r'optional\s*:'] total_docs = len(state.knowledge_base) if total_docs == 0: return metrics docs_with_endpoints = 0 docs_with_examples = 0 docs_with_params = 0 for doc in state.knowledge_base: content = doc.markdown.raw_markdown if hasattr(doc, 'markdown') else str(doc) # Check for endpoints if any(re.search(pattern, content, re.IGNORECASE) for pattern in endpoint_patterns): docs_with_endpoints += 1 # Check for examples if any(re.search(pattern, content, re.IGNORECASE) for pattern in example_patterns): docs_with_examples += 1 # Check for parameters if any(re.search(pattern, content, re.IGNORECASE) for pattern in param_patterns): docs_with_params += 1 metrics['endpoint_coverage'] = docs_with_endpoints / total_docs metrics['example_coverage'] = docs_with_examples / total_docs metrics['parameter_coverage'] = docs_with_params / total_docs return metrics class ResearchPaperStrategy: """ Strategy optimized for crawling research papers and academic content. Prioritizes citations, abstracts, and methodology sections. """ def __init__(self): self.academic_keywords = { 'abstract', 'introduction', 'methodology', 'results', 'conclusion', 'references', 'citation', 'paper', 'study', 'research', 'analysis', 'hypothesis', 'experiment', 'findings', 'doi' } self.citation_patterns = [ r'\[\d+\]', # [1] style citations r'\(\w+\s+\d{4}\)', # (Author 2024) style r'doi:\s*\S+', # DOI references ] def calculate_academic_relevance(self, content: str, query: str) -> float: """Calculate relevance score for academic content""" score = 0.0 content_lower = content.lower() # Check for academic keywords keyword_matches = sum(1 for kw in self.academic_keywords if kw in content_lower) score += keyword_matches * 0.1 # Check for citations citation_count = sum( len(re.findall(pattern, content)) for pattern in self.citation_patterns ) score += min(citation_count * 0.05, 1.0) # Cap at 1.0 # Check for query terms in academic context query_terms = query.lower().split() for term in query_terms: # Boost if term appears near academic keywords for keyword in ['abstract', 'conclusion', 'results']: if keyword in content_lower: section = content_lower[content_lower.find(keyword):content_lower.find(keyword) + 500] if term in section: score += 0.2 return min(score, 2.0) # Cap total score async def demo_custom_strategies(): """Demonstrate custom strategy usage""" # Example 1: API Documentation Strategy print("="*60) print("EXAMPLE 1: Custom API Documentation Strategy") print("="*60) api_strategy = APIDocumentationStrategy() async with AsyncWebCrawler() as crawler: # Standard adaptive crawler config = AdaptiveConfig( confidence_threshold=0.8, max_pages=15 ) adaptive = AdaptiveCrawler(crawler, config) # Override link scoring with custom strategy original_rank_links = adaptive._rank_links def custom_rank_links(links, query, state): # Apply custom scoring scored_links = [] for link in links: base_score = api_strategy.score_link(link, query, state) scored_links.append((link, base_score)) # Sort by score scored_links.sort(key=lambda x: x[1], reverse=True) return [link for link, _ in scored_links[:config.top_k_links]] adaptive._rank_links = custom_rank_links # Crawl API documentation print("\nCrawling API documentation with custom strategy...") state = await adaptive.digest( start_url="https://httpbin.org", query="api endpoints authentication headers" ) # Calculate custom metrics api_metrics = api_strategy.calculate_api_coverage(state, "api endpoints") print(f"\nResults:") print(f"Pages crawled: {len(state.crawled_urls)}") print(f"Confidence: {adaptive.confidence:.2%}") print(f"\nAPI-Specific Metrics:") print(f" - Endpoint coverage: {api_metrics['endpoint_coverage']:.2%}") print(f" - Example coverage: {api_metrics['example_coverage']:.2%}") print(f" - Parameter coverage: {api_metrics['parameter_coverage']:.2%}") # Example 2: Combined Strategy print("\n" + "="*60) print("EXAMPLE 2: Hybrid Strategy Combining Multiple Approaches") print("="*60) class HybridStrategy: """Combines multiple strategies with weights""" def __init__(self): self.api_strategy = APIDocumentationStrategy() self.research_strategy = ResearchPaperStrategy() self.weights = { 'api': 0.7, 'research': 0.3 } def score_content(self, content: str, query: str) -> float: # Get scores from each strategy api_score = self._calculate_api_score(content, query) research_score = self.research_strategy.calculate_academic_relevance(content, query) # Weighted combination total_score = ( api_score * self.weights['api'] + research_score * self.weights['research'] ) return total_score def _calculate_api_score(self, content: str, query: str) -> float: # Simplified API scoring based on keyword presence content_lower = content.lower() api_keywords = self.api_strategy.api_keywords keyword_count = sum(1 for kw in api_keywords if kw in content_lower) return min(keyword_count * 0.1, 2.0) hybrid_strategy = HybridStrategy() async with AsyncWebCrawler() as crawler: adaptive = AdaptiveCrawler(crawler) # Crawl with hybrid scoring print("\nTesting hybrid strategy on technical documentation...") state = await adaptive.digest( start_url="https://docs.python.org/3/library/asyncio.html", query="async await coroutines api" ) # Analyze results with hybrid strategy print(f"\nHybrid Strategy Analysis:") total_score = 0 for doc in adaptive.get_relevant_content(top_k=5): content = doc['content'] or "" score = hybrid_strategy.score_content(content, "async await api") total_score += score print(f" - {doc['url'][:50]}... Score: {score:.2f}") print(f"\nAverage hybrid score: {total_score/5:.2f}") async def demo_performance_optimization(): """Demonstrate performance optimization with custom strategies""" print("\n" + "="*60) print("EXAMPLE 3: Performance-Optimized Strategy") print("="*60) class PerformanceOptimizedStrategy: """Strategy that balances thoroughness with speed""" def __init__(self): self.url_cache: Set[str] = set() self.domain_scores: Dict[str, float] = {} def should_crawl_domain(self, url: str) -> bool: """Implement domain-level filtering""" domain = url.split('/')[2] if url.startswith('http') else url # Skip if we've already crawled many pages from this domain domain_count = sum(1 for cached in self.url_cache if domain in cached) if domain_count > 5: return False # Skip low-scoring domains if domain in self.domain_scores and self.domain_scores[domain] < 0.3: return False return True def update_domain_score(self, url: str, relevance: float): """Track domain-level performance""" domain = url.split('/')[2] if url.startswith('http') else url if domain not in self.domain_scores: self.domain_scores[domain] = relevance else: # Moving average self.domain_scores[domain] = ( 0.7 * self.domain_scores[domain] + 0.3 * relevance ) perf_strategy = PerformanceOptimizedStrategy() async with AsyncWebCrawler() as crawler: config = AdaptiveConfig( confidence_threshold=0.7, max_pages=10, top_k_links=2 # Fewer links for speed ) adaptive = AdaptiveCrawler(crawler, config) # Track performance import time start_time = time.time() state = await adaptive.digest( start_url="https://httpbin.org", query="http methods headers" ) elapsed = time.time() - start_time print(f"\nPerformance Results:") print(f" - Time elapsed: {elapsed:.2f} seconds") print(f" - Pages crawled: {len(state.crawled_urls)}") print(f" - Pages per second: {len(state.crawled_urls)/elapsed:.2f}") print(f" - Final confidence: {adaptive.confidence:.2%}") print(f" - Efficiency: {adaptive.confidence/len(state.crawled_urls):.2%} confidence per page") async def main(): """Run all demonstrations""" try: await demo_custom_strategies() await demo_performance_optimization() print("\n" + "="*60) print("All custom strategy examples completed!") print("="*60) except Exception as e: print(f"Error: {e}") import traceback traceback.print_exc() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/adaptive_crawling/custom_strategies.py", "license": "Apache License 2.0", "lines": 291, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/adaptive_crawling/embedding_configuration.py
""" Advanced Embedding Configuration Example This example demonstrates all configuration options available for the embedding strategy, including fine-tuning parameters for different use cases. """ import asyncio import os from crawl4ai import AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig async def test_configuration(name: str, config: AdaptiveConfig, url: str, query: str): """Test a specific configuration""" print(f"\n{'='*60}") print(f"Configuration: {name}") print(f"{'='*60}") async with AsyncWebCrawler(verbose=False) as crawler: adaptive = AdaptiveCrawler(crawler, config) result = await adaptive.digest(start_url=url, query=query) print(f"Pages crawled: {len(result.crawled_urls)}") print(f"Final confidence: {adaptive.confidence:.1%}") print(f"Stopped reason: {result.metrics.get('stopped_reason', 'max_pages')}") if result.metrics.get('is_irrelevant', False): print("โš ๏ธ Query detected as irrelevant!") return result async def main(): """Demonstrate various embedding configurations""" print("EMBEDDING STRATEGY CONFIGURATION EXAMPLES") print("=" * 60) # Base URL and query for testing test_url = "https://docs.python.org/3/library/asyncio.html" # 1. Default Configuration config_default = AdaptiveConfig( strategy="embedding", max_pages=10 ) await test_configuration( "Default Settings", config_default, test_url, "async programming patterns" ) # 2. Strict Coverage Requirements config_strict = AdaptiveConfig( strategy="embedding", max_pages=20, # Stricter similarity requirements embedding_k_exp=5.0, # Default is 3.0, higher = stricter embedding_coverage_radius=0.15, # Default is 0.2, lower = stricter # Higher validation threshold embedding_validation_min_score=0.6, # Default is 0.3 # More query variations for better coverage n_query_variations=15 # Default is 10 ) await test_configuration( "Strict Coverage (Research/Academic)", config_strict, test_url, "comprehensive guide async await" ) # 3. Fast Exploration config_fast = AdaptiveConfig( strategy="embedding", max_pages=10, top_k_links=5, # Follow more links per page # Relaxed requirements for faster convergence embedding_k_exp=1.0, # Lower = more lenient embedding_min_relative_improvement=0.05, # Stop earlier # Lower quality thresholds embedding_quality_min_confidence=0.5, # Display lower confidence embedding_quality_max_confidence=0.85, # Fewer query variations for speed n_query_variations=5 ) await test_configuration( "Fast Exploration (Quick Overview)", config_fast, test_url, "async basics" ) # 4. Irrelevance Detection Focus config_irrelevance = AdaptiveConfig( strategy="embedding", max_pages=5, # Aggressive irrelevance detection embedding_min_confidence_threshold=0.2, # Higher threshold (default 0.1) embedding_k_exp=5.0, # Strict similarity # Quick stopping for irrelevant content embedding_min_relative_improvement=0.15 ) await test_configuration( "Irrelevance Detection", config_irrelevance, test_url, "recipe for chocolate cake" # Irrelevant query ) # 5. High-Quality Knowledge Base config_quality = AdaptiveConfig( strategy="embedding", max_pages=30, # Deduplication settings embedding_overlap_threshold=0.75, # More aggressive deduplication # Quality focus embedding_validation_min_score=0.5, embedding_quality_scale_factor=1.0, # Linear quality mapping # Balanced parameters embedding_k_exp=3.0, embedding_nearest_weight=0.8, # Focus on best matches embedding_top_k_weight=0.2 ) await test_configuration( "High-Quality Knowledge Base", config_quality, test_url, "asyncio advanced patterns best practices" ) # 6. Custom Embedding Provider if os.getenv('OPENAI_API_KEY'): config_openai = AdaptiveConfig( strategy="embedding", max_pages=10, # Use OpenAI embeddings embedding_llm_config={ 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY') }, # OpenAI embeddings are high quality, can be stricter embedding_k_exp=4.0, n_query_variations=12 ) await test_configuration( "OpenAI Embeddings", config_openai, test_url, "event-driven architecture patterns" ) # Parameter Guide print("\n" + "="*60) print("PARAMETER TUNING GUIDE") print("="*60) print("\n๐Ÿ“Š Key Parameters and Their Effects:") print("\n1. embedding_k_exp (default: 3.0)") print(" - Lower (1-2): More lenient, faster convergence") print(" - Higher (4-5): Stricter, better precision") print("\n2. embedding_coverage_radius (default: 0.2)") print(" - Lower (0.1-0.15): Requires closer matches") print(" - Higher (0.25-0.3): Accepts broader matches") print("\n3. n_query_variations (default: 10)") print(" - Lower (5-7): Faster, less comprehensive") print(" - Higher (15-20): Better coverage, slower") print("\n4. embedding_min_confidence_threshold (default: 0.1)") print(" - Set to 0.15-0.2 for aggressive irrelevance detection") print(" - Set to 0.05 to crawl even barely relevant content") print("\n5. embedding_validation_min_score (default: 0.3)") print(" - Higher (0.5-0.6): Requires strong validation") print(" - Lower (0.2): More permissive stopping") print("\n๐Ÿ’ก Tips:") print("- For research: High k_exp, more variations, strict validation") print("- For exploration: Low k_exp, fewer variations, relaxed thresholds") print("- For quality: Focus on overlap_threshold and validation scores") print("- For speed: Reduce variations, increase min_relative_improvement") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/adaptive_crawling/embedding_configuration.py", "license": "Apache License 2.0", "lines": 160, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/adaptive_crawling/embedding_strategy.py
""" Embedding Strategy Example for Adaptive Crawling This example demonstrates how to use the embedding-based strategy for semantic understanding and intelligent crawling. """ import asyncio import os from crawl4ai import AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig async def main(): """Demonstrate embedding strategy for adaptive crawling""" # Configure embedding strategy config = AdaptiveConfig( strategy="embedding", # Use embedding strategy embedding_model="sentence-transformers/all-MiniLM-L6-v2", # Default model n_query_variations=10, # Generate 10 semantic variations max_pages=15, top_k_links=3, min_gain_threshold=0.05, # Embedding-specific parameters embedding_k_exp=3.0, # Higher = stricter similarity requirements embedding_min_confidence_threshold=0.1, # Stop if <10% relevant embedding_validation_min_score=0.4 # Validation threshold ) # Optional: Use OpenAI embeddings instead if os.getenv('OPENAI_API_KEY'): config.embedding_llm_config = { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY') } print("Using OpenAI embeddings") else: print("Using sentence-transformers (local embeddings)") async with AsyncWebCrawler(verbose=True) as crawler: adaptive = AdaptiveCrawler(crawler, config) # Test 1: Relevant query with semantic understanding print("\n" + "="*50) print("TEST 1: Semantic Query Understanding") print("="*50) result = await adaptive.digest( start_url="https://docs.python.org/3/library/asyncio.html", query="concurrent programming event-driven architecture" ) print("\nQuery Expansion:") print(f"Original query expanded to {len(result.expanded_queries)} variations") for i, q in enumerate(result.expanded_queries[:3], 1): print(f" {i}. {q}") print(" ...") print("\nResults:") adaptive.print_stats(detailed=False) # Test 2: Detecting irrelevant queries print("\n" + "="*50) print("TEST 2: Irrelevant Query Detection") print("="*50) # Reset crawler for new query adaptive = AdaptiveCrawler(crawler, config) result = await adaptive.digest( start_url="https://docs.python.org/3/library/asyncio.html", query="how to bake chocolate chip cookies" ) if result.metrics.get('is_irrelevant', False): print("\nโœ… Successfully detected irrelevant query!") print(f"Stopped after just {len(result.crawled_urls)} pages") print(f"Reason: {result.metrics.get('stopped_reason', 'unknown')}") else: print("\nโŒ Failed to detect irrelevance") print(f"Final confidence: {adaptive.confidence:.1%}") # Test 3: Semantic gap analysis print("\n" + "="*50) print("TEST 3: Semantic Gap Analysis") print("="*50) # Show how embedding strategy identifies gaps adaptive = AdaptiveCrawler(crawler, config) result = await adaptive.digest( start_url="https://realpython.com", query="python decorators advanced patterns" ) print(f"\nSemantic gaps identified: {len(result.semantic_gaps)}") print(f"Knowledge base embeddings shape: {result.kb_embeddings.shape if result.kb_embeddings is not None else 'None'}") # Show coverage metrics specific to embedding strategy print("\nEmbedding-specific metrics:") print(f" Average best similarity: {result.metrics.get('avg_best_similarity', 0):.3f}") print(f" Coverage score: {result.metrics.get('coverage_score', 0):.3f}") print(f" Validation confidence: {result.metrics.get('validation_confidence', 0):.2%}") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/adaptive_crawling/embedding_strategy.py", "license": "Apache License 2.0", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/adaptive_crawling/embedding_vs_statistical.py
""" Comparison: Embedding vs Statistical Strategy This example demonstrates the differences between statistical and embedding strategies for adaptive crawling, showing when to use each approach. """ import asyncio import time import os from crawl4ai import AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig async def crawl_with_strategy(url: str, query: str, strategy: str, **kwargs): """Helper function to crawl with a specific strategy""" config = AdaptiveConfig( strategy=strategy, max_pages=20, top_k_links=3, min_gain_threshold=0.05, **kwargs ) async with AsyncWebCrawler(verbose=False) as crawler: adaptive = AdaptiveCrawler(crawler, config) start_time = time.time() result = await adaptive.digest(start_url=url, query=query) elapsed = time.time() - start_time return { 'result': result, 'crawler': adaptive, 'elapsed': elapsed, 'pages': len(result.crawled_urls), 'confidence': adaptive.confidence } async def main(): """Compare embedding and statistical strategies""" # Test scenarios test_cases = [ { 'name': 'Technical Documentation (Specific Terms)', 'url': 'https://docs.python.org/3/library/asyncio.html', 'query': 'asyncio.create_task event_loop.run_until_complete' }, { 'name': 'Conceptual Query (Semantic Understanding)', 'url': 'https://docs.python.org/3/library/asyncio.html', 'query': 'concurrent programming patterns' }, { 'name': 'Ambiguous Query', 'url': 'https://realpython.com', 'query': 'python performance optimization' } ] # Configure embedding strategy embedding_config = {} if os.getenv('OPENAI_API_KEY'): embedding_config['embedding_llm_config'] = { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY') } for test in test_cases: print("\n" + "="*70) print(f"TEST: {test['name']}") print(f"URL: {test['url']}") print(f"Query: '{test['query']}'") print("="*70) # Run statistical strategy print("\n๐Ÿ“Š Statistical Strategy:") stat_result = await crawl_with_strategy( test['url'], test['query'], 'statistical' ) print(f" Pages crawled: {stat_result['pages']}") print(f" Time taken: {stat_result['elapsed']:.2f}s") print(f" Confidence: {stat_result['confidence']:.1%}") print(f" Sufficient: {'Yes' if stat_result['crawler'].is_sufficient else 'No'}") # Show term coverage if hasattr(stat_result['result'], 'term_frequencies'): query_terms = test['query'].lower().split() covered = sum(1 for term in query_terms if term in stat_result['result'].term_frequencies) print(f" Term coverage: {covered}/{len(query_terms)} query terms found") # Run embedding strategy print("\n๐Ÿง  Embedding Strategy:") emb_result = await crawl_with_strategy( test['url'], test['query'], 'embedding', **embedding_config ) print(f" Pages crawled: {emb_result['pages']}") print(f" Time taken: {emb_result['elapsed']:.2f}s") print(f" Confidence: {emb_result['confidence']:.1%}") print(f" Sufficient: {'Yes' if emb_result['crawler'].is_sufficient else 'No'}") # Show semantic understanding if emb_result['result'].expanded_queries: print(f" Query variations: {len(emb_result['result'].expanded_queries)}") print(f" Semantic gaps: {len(emb_result['result'].semantic_gaps)}") # Compare results print("\n๐Ÿ“ˆ Comparison:") efficiency_diff = ((stat_result['pages'] - emb_result['pages']) / stat_result['pages'] * 100) if stat_result['pages'] > 0 else 0 print(f" Efficiency: ", end="") if efficiency_diff > 0: print(f"Embedding used {efficiency_diff:.0f}% fewer pages") else: print(f"Statistical used {-efficiency_diff:.0f}% fewer pages") print(f" Speed: ", end="") if stat_result['elapsed'] < emb_result['elapsed']: print(f"Statistical was {emb_result['elapsed']/stat_result['elapsed']:.1f}x faster") else: print(f"Embedding was {stat_result['elapsed']/emb_result['elapsed']:.1f}x faster") print(f" Confidence difference: {abs(stat_result['confidence'] - emb_result['confidence'])*100:.0f} percentage points") # Recommendation print("\n๐Ÿ’ก Recommendation:") if 'specific' in test['name'].lower() or all(len(term) > 5 for term in test['query'].split()): print(" โ†’ Statistical strategy is likely better for this use case (specific terms)") elif 'conceptual' in test['name'].lower() or 'semantic' in test['name'].lower(): print(" โ†’ Embedding strategy is likely better for this use case (semantic understanding)") else: if emb_result['confidence'] > stat_result['confidence'] + 0.1: print(" โ†’ Embedding strategy achieved significantly better understanding") elif stat_result['elapsed'] < emb_result['elapsed'] / 2: print(" โ†’ Statistical strategy is much faster with similar results") else: print(" โ†’ Both strategies performed similarly; choose based on your priorities") # Summary recommendations print("\n" + "="*70) print("STRATEGY SELECTION GUIDE") print("="*70) print("\nโœ… Use STATISTICAL strategy when:") print(" - Queries contain specific technical terms") print(" - Speed is critical") print(" - No API access available") print(" - Working with well-structured documentation") print("\nโœ… Use EMBEDDING strategy when:") print(" - Queries are conceptual or ambiguous") print(" - Semantic understanding is important") print(" - Need to detect irrelevant content") print(" - Working with diverse content sources") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/adaptive_crawling/embedding_vs_statistical.py", "license": "Apache License 2.0", "lines": 140, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/adaptive_crawling/export_import_kb.py
""" Knowledge Base Export and Import This example demonstrates how to export crawled knowledge bases and import them for reuse, sharing, or analysis. """ import asyncio import json from pathlib import Path from crawl4ai import AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig async def build_knowledge_base(): """Build a knowledge base about web technologies""" print("="*60) print("PHASE 1: Building Knowledge Base") print("="*60) async with AsyncWebCrawler(verbose=False) as crawler: adaptive = AdaptiveCrawler(crawler) # Crawl information about HTTP print("\n1. Gathering HTTP protocol information...") await adaptive.digest( start_url="https://httpbin.org", query="http methods headers status codes" ) print(f" - Pages crawled: {len(adaptive.state.crawled_urls)}") print(f" - Confidence: {adaptive.confidence:.2%}") # Add more information about APIs print("\n2. Adding API documentation knowledge...") await adaptive.digest( start_url="https://httpbin.org/anything", query="rest api json response request" ) print(f" - Total pages: {len(adaptive.state.crawled_urls)}") print(f" - Confidence: {adaptive.confidence:.2%}") # Export the knowledge base export_path = "web_tech_knowledge.jsonl" print(f"\n3. Exporting knowledge base to {export_path}") adaptive.export_knowledge_base(export_path) # Show export statistics export_size = Path(export_path).stat().st_size / 1024 with open(export_path, 'r') as f: line_count = sum(1 for _ in f) print(f" - Exported {line_count} documents") print(f" - File size: {export_size:.1f} KB") return export_path async def analyze_knowledge_base(kb_path): """Analyze the exported knowledge base""" print("\n" + "="*60) print("PHASE 2: Analyzing Exported Knowledge Base") print("="*60) # Read and analyze JSONL documents = [] with open(kb_path, 'r') as f: for line in f: documents.append(json.loads(line)) print(f"\nKnowledge base contains {len(documents)} documents:") # Analyze document properties total_content_length = 0 urls_by_domain = {} for doc in documents: # Content analysis content_length = len(doc.get('content', '')) total_content_length += content_length # URL analysis url = doc.get('url', '') domain = url.split('/')[2] if url.startswith('http') else 'unknown' urls_by_domain[domain] = urls_by_domain.get(domain, 0) + 1 # Show sample document if documents.index(doc) == 0: print(f"\nSample document structure:") print(f" - URL: {url}") print(f" - Content length: {content_length} chars") print(f" - Has metadata: {'metadata' in doc}") print(f" - Has links: {len(doc.get('links', []))} links") print(f" - Query: {doc.get('query', 'N/A')}") print(f"\nContent statistics:") print(f" - Total content: {total_content_length:,} characters") print(f" - Average per document: {total_content_length/len(documents):,.0f} chars") print(f"\nDomain distribution:") for domain, count in urls_by_domain.items(): print(f" - {domain}: {count} pages") async def import_and_continue(): """Import a knowledge base and continue crawling""" print("\n" + "="*60) print("PHASE 3: Importing and Extending Knowledge Base") print("="*60) kb_path = "web_tech_knowledge.jsonl" async with AsyncWebCrawler(verbose=False) as crawler: # Create new adaptive crawler adaptive = AdaptiveCrawler(crawler) # Import existing knowledge base print(f"\n1. Importing knowledge base from {kb_path}") adaptive.import_knowledge_base(kb_path) print(f" - Imported {len(adaptive.state.knowledge_base)} documents") print(f" - Existing URLs: {len(adaptive.state.crawled_urls)}") # Check current state print("\n2. Checking imported knowledge state:") adaptive.print_stats(detailed=False) # Continue crawling with new query print("\n3. Extending knowledge with new query...") await adaptive.digest( start_url="https://httpbin.org/status/200", query="error handling retry timeout" ) print("\n4. Final knowledge base state:") adaptive.print_stats(detailed=False) # Export extended knowledge base extended_path = "web_tech_knowledge_extended.jsonl" adaptive.export_knowledge_base(extended_path) print(f"\n5. Extended knowledge base exported to {extended_path}") async def share_knowledge_bases(): """Demonstrate sharing knowledge bases between projects""" print("\n" + "="*60) print("PHASE 4: Sharing Knowledge Between Projects") print("="*60) # Simulate two different projects project_a_kb = "project_a_knowledge.jsonl" project_b_kb = "project_b_knowledge.jsonl" async with AsyncWebCrawler(verbose=False) as crawler: # Project A: Security documentation print("\n1. Project A: Building security knowledge...") crawler_a = AdaptiveCrawler(crawler) await crawler_a.digest( start_url="https://httpbin.org/basic-auth/user/pass", query="authentication security headers" ) crawler_a.export_knowledge_base(project_a_kb) print(f" - Exported {len(crawler_a.state.knowledge_base)} documents") # Project B: API testing print("\n2. Project B: Building testing knowledge...") crawler_b = AdaptiveCrawler(crawler) await crawler_b.digest( start_url="https://httpbin.org/anything", query="testing endpoints mocking" ) crawler_b.export_knowledge_base(project_b_kb) print(f" - Exported {len(crawler_b.state.knowledge_base)} documents") # Merge knowledge bases print("\n3. Merging knowledge bases...") merged_crawler = AdaptiveCrawler(crawler) # Import both knowledge bases merged_crawler.import_knowledge_base(project_a_kb) initial_size = len(merged_crawler.state.knowledge_base) merged_crawler.import_knowledge_base(project_b_kb) final_size = len(merged_crawler.state.knowledge_base) print(f" - Project A documents: {initial_size}") print(f" - Additional from Project B: {final_size - initial_size}") print(f" - Total merged documents: {final_size}") # Export merged knowledge merged_kb = "merged_knowledge.jsonl" merged_crawler.export_knowledge_base(merged_kb) print(f"\n4. Merged knowledge base exported to {merged_kb}") # Show combined coverage print("\n5. Combined knowledge coverage:") merged_crawler.print_stats(detailed=False) async def main(): """Run all examples""" try: # Build initial knowledge base kb_path = await build_knowledge_base() # Analyze the export await analyze_knowledge_base(kb_path) # Import and extend await import_and_continue() # Demonstrate sharing await share_knowledge_bases() print("\n" + "="*60) print("All examples completed successfully!") print("="*60) finally: # Clean up generated files print("\nCleaning up generated files...") for file in [ "web_tech_knowledge.jsonl", "web_tech_knowledge_extended.jsonl", "project_a_knowledge.jsonl", "project_b_knowledge.jsonl", "merged_knowledge.jsonl" ]: Path(file).unlink(missing_ok=True) print("Cleanup complete.") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/adaptive_crawling/export_import_kb.py", "license": "Apache License 2.0", "lines": 181, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/c4a_script/amazon_example/amazon_r2d2_search.py
#!/usr/bin/env python3 """ Amazon R2D2 Product Search Example using Crawl4AI This example demonstrates: 1. Using LLM to generate C4A-Script from HTML snippets 2. Multi-step crawling with session persistence 3. JSON CSS extraction for structured product data 4. Complete workflow: homepage โ†’ search โ†’ extract products Requirements: - Crawl4AI with generate_script support - LLM API key (configured in environment) """ import asyncio import json import os from pathlib import Path from typing import List, Dict, Any from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode from crawl4ai import JsonCssExtractionStrategy from crawl4ai.script.c4a_compile import C4ACompiler class AmazonR2D2Scraper: def __init__(self): self.base_dir = Path(__file__).parent self.search_script_path = self.base_dir / "generated_search_script.js" self.schema_path = self.base_dir / "generated_product_schema.json" self.results_path = self.base_dir / "extracted_products.json" self.session_id = "amazon_r2d2_session" async def generate_search_script(self) -> str: """Generate JavaScript for Amazon search interaction""" print("๐Ÿ”ง Generating search script from header.html...") # Check if already generated if self.search_script_path.exists(): print("โœ… Using cached search script") return self.search_script_path.read_text() # Read the header HTML header_html = (self.base_dir / "header.html").read_text() # Generate script using LLM search_goal = """ Find the search box and search button, then: 1. Wait for the search box to be visible 2. Click on the search box to focus it 3. Clear any existing text 4. Type "r2d2" into the search box 5. Click the search submit button 6. Wait for navigation to complete and search results to appear """ try: script = C4ACompiler.generate_script( html=header_html, query=search_goal, mode="js" ) # Save for future use self.search_script_path.write_text(script) print("โœ… Search script generated and saved!") print(f"๐Ÿ“„ Script:\n{script}") return script except Exception as e: print(f"โŒ Error generating search script: {e}") async def generate_product_schema(self) -> Dict[str, Any]: """Generate JSON CSS extraction schema from product HTML""" print("\n๐Ÿ”ง Generating product extraction schema...") # Check if already generated if self.schema_path.exists(): print("โœ… Using cached extraction schema") return json.loads(self.schema_path.read_text()) # Read the product HTML product_html = (self.base_dir / "product.html").read_text() # Generate extraction schema using LLM schema_goal = """ Create a JSON CSS extraction schema to extract: - Product title (from the h2 element) - Price (the dollar amount) - Rating (star rating value) - Number of reviews - Delivery information - Product URL (from the main product link) - Whether it's sponsored - Small business badge if present The schema should handle multiple products on a search results page. """ try: # Generate JavaScript that returns the schema schema = JsonCssExtractionStrategy.generate_schema( html=product_html, query=schema_goal, ) # Save for future use self.schema_path.write_text(json.dumps(schema, indent=2)) print("โœ… Extraction schema generated and saved!") print(f"๐Ÿ“„ Schema fields: {[f['name'] for f in schema['fields']]}") return schema except Exception as e: print(f"โŒ Error generating schema: {e}") async def crawl_amazon(self): """Main crawling logic with 2 calls using same session""" print("\n๐Ÿš€ Starting Amazon R2D2 product search...") # Generate scripts and schemas search_script = await self.generate_search_script() product_schema = await self.generate_product_schema() # Configure browser (headless=False to see the action) browser_config = BrowserConfig( headless=False, verbose=True, viewport_width=1920, viewport_height=1080 ) async with AsyncWebCrawler(config=browser_config) as crawler: print("\n๐Ÿ“ Step 1: Navigate to Amazon and search for R2D2") # FIRST CALL: Navigate to Amazon and execute search search_config = CrawlerRunConfig( session_id=self.session_id, js_code= f"(() => {{ {search_script} }})()", # Execute generated JS wait_for=".s-search-results", # Wait for search results extraction_strategy=JsonCssExtractionStrategy(schema=product_schema), delay_before_return_html=3.0 # Give time for results to load ) results = await crawler.arun( url="https://www.amazon.com", config=search_config ) if not results.success: print("โŒ Failed to search Amazon") print(f"Error: {results.error_message}") return print("โœ… Search completed successfully!") print("โœ… Product extraction completed!") # Extract and save results print("\n๐Ÿ“ Extracting product data") if results[0].extracted_content: products = json.loads(results[0].extracted_content) print(f"๐Ÿ” Found {len(products)} products in search results") print(f"โœ… Extracted {len(products)} R2D2 products") # Save results self.results_path.write_text( json.dumps(products, indent=2) ) print(f"๐Ÿ’พ Results saved to: {self.results_path}") # Print sample results print("\n๐Ÿ“Š Sample Results:") for i, product in enumerate(products[:3], 1): print(f"\n{i}. {product['title'][:60]}...") print(f" Price: ${product['price']}") print(f" Rating: {product['rating']} ({product['number_of_reviews']} reviews)") print(f" {'๐Ÿช Small Business' if product['small_business_badge'] else ''}") print(f" {'๐Ÿ“ข Sponsored' if product['sponsored'] else ''}") else: print("โŒ No products extracted") async def main(): """Run the Amazon scraper""" scraper = AmazonR2D2Scraper() await scraper.crawl_amazon() print("\n๐ŸŽ‰ Amazon R2D2 search example completed!") print("Check the generated files:") print(" - generated_search_script.js") print(" - generated_product_schema.json") print(" - extracted_products.json") print(" - search_results_screenshot.png") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/c4a_script/amazon_example/amazon_r2d2_search.py", "license": "Apache License 2.0", "lines": 160, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/c4a_script/api_usage_examples.py
""" C4A-Script API Usage Examples Shows how to use the new Result-based API in various scenarios """ from crawl4ai.script.c4a_compile import compile, validate, compile_file from crawl4ai.script.c4a_result import CompilationResult, ValidationResult import json print("C4A-Script API Usage Examples") print("=" * 80) # Example 1: Basic compilation print("\n1. Basic Compilation") print("-" * 40) script = """ GO https://example.com WAIT 2 IF (EXISTS `.cookie-banner`) THEN CLICK `.accept` REPEAT (SCROLL DOWN 300, 3) """ result = compile(script) print(f"Success: {result.success}") print(f"Statements generated: {len(result.js_code) if result.js_code else 0}") # Example 2: Error handling print("\n\n2. Error Handling") print("-" * 40) error_script = """ GO https://example.com IF (EXISTS `.modal`) CLICK `.close` undefined_procedure """ result = compile(error_script) if not result.success: # Access error details error = result.first_error print(f"Error on line {error.line}: {error.message}") print(f"Error code: {error.code}") # Show suggestions if available if error.suggestions: print("Suggestions:") for suggestion in error.suggestions: print(f" - {suggestion.message}") # Example 3: Validation only print("\n\n3. Validation (no code generation)") print("-" * 40) validation_script = """ PROC validate_form IF (EXISTS `#email`) THEN TYPE "test@example.com" PRESS Tab ENDPROC validate_form """ validation = validate(validation_script) print(f"Valid: {validation.valid}") if validation.errors: print(f"Errors found: {len(validation.errors)}") # Example 4: JSON output for UI print("\n\n4. JSON Output for UI Integration") print("-" * 40) ui_script = """ CLICK button.submit """ result = compile(ui_script) if not result.success: # Get JSON for UI error_json = result.to_dict() print("Error data for UI:") print(json.dumps(error_json["errors"][0], indent=2)) # Example 5: File compilation print("\n\n5. File Compilation") print("-" * 40) # Create a test file test_file = "test_script.c4a" with open(test_file, "w") as f: f.write(""" GO https://example.com WAIT `.content` 5 CLICK `.main-button` """) result = compile_file(test_file) print(f"File compilation: {'Success' if result.success else 'Failed'}") if result.success: print(f"Generated {len(result.js_code)} JavaScript statements") # Clean up import os os.remove(test_file) # Example 6: Batch processing print("\n\n6. Batch Processing Multiple Scripts") print("-" * 40) scripts = [ "GO https://example1.com\nCLICK `.button`", "GO https://example2.com\nWAIT 2", "GO https://example3.com\nINVALID_CMD" ] results = [] for i, script in enumerate(scripts, 1): result = compile(script) results.append(result) status = "โœ“" if result.success else "โœ—" print(f"Script {i}: {status}") # Summary successful = sum(1 for r in results if r.success) print(f"\nBatch result: {successful}/{len(scripts)} successful") # Example 7: Custom error formatting print("\n\n7. Custom Error Formatting") print("-" * 40) def format_error_for_ide(error): """Format error for IDE integration""" return f"{error.source_line}:{error.line}:{error.column}: {error.type.value}: {error.message} [{error.code}]" error_script = "IF EXISTS `.button` THEN CLICK `.button`" result = compile(error_script) if not result.success: error = result.first_error print("IDE format:", format_error_for_ide(error)) print("Simple format:", error.simple_message) print("Full format:", error.formatted_message) # Example 8: Working with warnings (future feature) print("\n\n8. Handling Warnings") print("-" * 40) # In the future, we might have warnings result = compile("GO https://example.com\nWAIT 100") # Very long wait print(f"Success: {result.success}") print(f"Warnings: {len(result.warnings)}") # Example 9: Metadata usage print("\n\n9. Using Metadata") print("-" * 40) complex_script = """ PROC helper1 CLICK `.btn1` ENDPROC PROC helper2 CLICK `.btn2` ENDPROC GO https://example.com helper1 helper2 """ result = compile(complex_script) if result.success: print(f"Script metadata:") for key, value in result.metadata.items(): print(f" {key}: {value}") # Example 10: Integration patterns print("\n\n10. Integration Patterns") print("-" * 40) # Web API endpoint simulation def api_compile(request_body): """Simulate API endpoint""" script = request_body.get("script", "") result = compile(script) response = { "status": "success" if result.success else "error", "data": result.to_dict() } return response # CLI tool simulation def cli_compile(script, output_format="text"): """Simulate CLI tool""" result = compile(script) if output_format == "json": return result.to_json() elif output_format == "simple": if result.success: return f"OK: {len(result.js_code)} statements" else: return f"ERROR: {result.first_error.simple_message}" else: return str(result) # Test the patterns api_response = api_compile({"script": "GO https://example.com"}) print(f"API response status: {api_response['status']}") cli_output = cli_compile("WAIT 2", "simple") print(f"CLI output: {cli_output}") print("\n" + "=" * 80) print("All examples completed successfully!")
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/c4a_script/api_usage_examples.py", "license": "Apache License 2.0", "lines": 173, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/c4a_script/c4a_script_hello_world.py
""" C4A-Script Hello World A concise example showing how to use the C4A-Script compiler """ from crawl4ai.script.c4a_compile import compile # Define your C4A-Script script = """ GO https://example.com WAIT `#content` 5 IF (EXISTS `.cookie-banner`) THEN CLICK `.accept` CLICK `button.submit` """ # Compile the script result = compile(script) # Check if compilation was successful if result.success: # Success! Use the generated JavaScript print("โœ… Compilation successful!") print(f"Generated {len(result.js_code)} JavaScript statements:\n") for i, js in enumerate(result.js_code, 1): print(f"{i}. {js}\n") # In real usage, you'd pass result.js_code to Crawl4AI: # config = CrawlerRunConfig(js_code=result.js_code) else: # Error! Handle the compilation error print("โŒ Compilation failed!") # Get the first error (there might be multiple) error = result.first_error # Show error details print(f"Error at line {error.line}, column {error.column}") print(f"Message: {error.message}") # Show the problematic code print(f"\nCode: {error.source_line}") print(" " * (6 + error.column) + "^") # Show suggestions if available if error.suggestions: print("\n๐Ÿ’ก How to fix:") for suggestion in error.suggestions: print(f" {suggestion.message}") # For debugging or logging, you can also get JSON # error_json = result.to_json()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/c4a_script/c4a_script_hello_world.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/c4a_script/c4a_script_hello_world_error.py
""" C4A-Script Hello World - Error Example Shows how error handling works """ from crawl4ai.script.c4a_compile import compile # Define a script with an error (missing THEN) script = """ GO https://example.com WAIT `#content` 5 IF (EXISTS `.cookie-banner`) CLICK `.accept` CLICK `button.submit` """ # Compile the script result = compile(script) # Check if compilation was successful if result.success: # Success! Use the generated JavaScript print("โœ… Compilation successful!") print(f"Generated {len(result.js_code)} JavaScript statements:\n") for i, js in enumerate(result.js_code, 1): print(f"{i}. {js}\n") # In real usage, you'd pass result.js_code to Crawl4AI: # config = CrawlerRunConfig(js_code=result.js_code) else: # Error! Handle the compilation error print("โŒ Compilation failed!") # Get the first error (there might be multiple) error = result.first_error # Show error details print(f"Error at line {error.line}, column {error.column}") print(f"Message: {error.message}") # Show the problematic code print(f"\nCode: {error.source_line}") print(" " * (6 + error.column) + "^") # Show suggestions if available if error.suggestions: print("\n๐Ÿ’ก How to fix:") for suggestion in error.suggestions: print(f" {suggestion.message}") # For debugging or logging, you can also get JSON # error_json = result.to_json()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/c4a_script/c4a_script_hello_world_error.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/c4a_script/demo_c4a_crawl4ai.py
""" Demonstration of C4A-Script integration with Crawl4AI Shows various use cases and features """ import asyncio from crawl4ai import AsyncWebCrawler, CrawlerRunConfig from crawl4ai import c4a_compile, CompilationResult async def example_basic_usage(): """Basic C4A-Script usage with Crawl4AI""" print("\n" + "="*60) print("Example 1: Basic C4A-Script Usage") print("="*60) # Define your automation script c4a_script = """ # Wait for page to load WAIT `body` 2 # Handle cookie banner if present IF (EXISTS `.cookie-banner`) THEN CLICK `.accept-btn` # Scroll down to load more content SCROLL DOWN 500 WAIT 1 # Click load more button if exists IF (EXISTS `.load-more`) THEN CLICK `.load-more` """ # Create crawler config with C4A script config = CrawlerRunConfig( url="https://example.com", c4a_script=c4a_script, wait_for="css:.content", verbose=False ) print("โœ… C4A Script compiled successfully!") print(f"Generated {len(config.js_code)} JavaScript commands") # In production, you would run: # async with AsyncWebCrawler() as crawler: # result = await crawler.arun(config=config) async def example_form_filling(): """Form filling with C4A-Script""" print("\n" + "="*60) print("Example 2: Form Filling with C4A-Script") print("="*60) # Form automation script form_script = """ # Set form values SET email = "test@example.com" SET message = "This is a test message" # Fill the form CLICK `#email-input` TYPE $email CLICK `#message-textarea` TYPE $message # Submit the form CLICK `button[type="submit"]` # Wait for success message WAIT `.success-message` 10 """ config = CrawlerRunConfig( url="https://example.com/contact", c4a_script=form_script ) print("โœ… Form filling script ready") print("Script will:") print(" - Fill email field") print(" - Fill message textarea") print(" - Submit form") print(" - Wait for confirmation") async def example_dynamic_loading(): """Handle dynamic content loading""" print("\n" + "="*60) print("Example 3: Dynamic Content Loading") print("="*60) # Script for infinite scroll or pagination pagination_script = """ # Initial wait WAIT `.product-list` 5 # Load all products by clicking "Load More" repeatedly REPEAT (CLICK `.load-more`, `document.querySelector('.load-more') !== null`) # Alternative: Scroll to load (infinite scroll) # REPEAT (SCROLL DOWN 1000, `document.querySelectorAll('.product').length < 100`) # Extract count EVAL `console.log('Products loaded: ' + document.querySelectorAll('.product').length)` """ config = CrawlerRunConfig( url="https://example.com/products", c4a_script=pagination_script, screenshot=True # Capture final state ) print("โœ… Dynamic loading script ready") print("Script will load all products by repeatedly clicking 'Load More'") async def example_multi_step_workflow(): """Complex multi-step workflow with procedures""" print("\n" + "="*60) print("Example 4: Multi-Step Workflow with Procedures") print("="*60) # Complex workflow with reusable procedures workflow_script = """ # Define login procedure PROC login CLICK `#username` TYPE "demo_user" CLICK `#password` TYPE "demo_pass" CLICK `#login-btn` WAIT `.dashboard` 10 ENDPROC # Define search procedure PROC search_product CLICK `.search-box` TYPE "laptop" PRESS Enter WAIT `.search-results` 5 ENDPROC # Main workflow GO https://example.com login search_product # Process results IF (EXISTS `.no-results`) THEN EVAL `console.log('No products found')` ELSE REPEAT (CLICK `.add-to-cart`, 3) """ # Compile to check for errors result = c4a_compile(workflow_script) if result.success: print("โœ… Complex workflow compiled successfully!") print("Workflow includes:") print(" - Login procedure") print(" - Product search") print(" - Conditional cart additions") config = CrawlerRunConfig( url="https://example.com", c4a_script=workflow_script ) else: print("โŒ Compilation error:") error = result.first_error print(f" Line {error.line}: {error.message}") async def example_error_handling(): """Demonstrate error handling""" print("\n" + "="*60) print("Example 5: Error Handling") print("="*60) # Script with intentional error bad_script = """ WAIT body 2 CLICK button IF (EXISTS .modal) CLICK .close """ try: config = CrawlerRunConfig( url="https://example.com", c4a_script=bad_script ) except ValueError as e: print("โœ… Error caught as expected:") print(f" {e}") # Fixed version good_script = """ WAIT `body` 2 CLICK `button` IF (EXISTS `.modal`) THEN CLICK `.close` """ config = CrawlerRunConfig( url="https://example.com", c4a_script=good_script ) print("\nโœ… Fixed script compiled successfully!") async def example_combining_with_extraction(): """Combine C4A-Script with extraction strategies""" print("\n" + "="*60) print("Example 6: C4A-Script + Extraction Strategies") print("="*60) from crawl4ai import JsonCssExtractionStrategy # Script to prepare page for extraction prep_script = """ # Expand all collapsed sections REPEAT (CLICK `.expand-btn`, `document.querySelectorAll('.expand-btn:not(.expanded)').length > 0`) # Load all comments IF (EXISTS `.load-comments`) THEN CLICK `.load-comments` WAIT `.comments-section` 5 # Close any popups IF (EXISTS `.popup-close`) THEN CLICK `.popup-close` """ # Define extraction schema schema = { "name": "article", "selector": "article.main", "fields": { "title": {"selector": "h1", "type": "text"}, "content": {"selector": ".content", "type": "text"}, "comments": { "selector": ".comment", "type": "list", "fields": { "author": {"selector": ".author", "type": "text"}, "text": {"selector": ".text", "type": "text"} } } } } config = CrawlerRunConfig( url="https://example.com/article", c4a_script=prep_script, extraction_strategy=JsonCssExtractionStrategy(schema), wait_for="css:.comments-section" ) print("โœ… Combined C4A + Extraction ready") print("Workflow:") print(" 1. Expand collapsed sections") print(" 2. Load comments") print(" 3. Extract structured data") async def main(): """Run all examples""" print("\n๐Ÿš€ C4A-Script + Crawl4AI Integration Demo\n") # Run all examples await example_basic_usage() await example_form_filling() await example_dynamic_loading() await example_multi_step_workflow() await example_error_handling() await example_combining_with_extraction() print("\n" + "="*60) print("โœ… All examples completed successfully!") print("="*60) print("\nTo run actual crawls, uncomment the AsyncWebCrawler sections") print("or create your own scripts using these examples as templates.") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/c4a_script/demo_c4a_crawl4ai.py", "license": "Apache License 2.0", "lines": 227, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/c4a_script/generate_script_hello_world.py
#!/usr/bin/env python3 """ Hello World Example: LLM-Generated C4A-Script This example shows how to use the new generate_script() function to automatically create C4A-Script automation from natural language descriptions and HTML. """ from crawl4ai.script.c4a_compile import C4ACompiler def main(): print("๐Ÿค– C4A-Script Generation Hello World") print("=" * 50) # Example 1: Simple login form html = """ <html> <body> <form id="login"> <input id="email" type="email" placeholder="Email"> <input id="password" type="password" placeholder="Password"> <button id="submit">Login</button> </form> </body> </html> """ goal = "Fill in email 'user@example.com', password 'secret123', and submit the form" print("๐Ÿ“ Goal:", goal) print("๐ŸŒ HTML: Simple login form") print() # Generate C4A-Script print("๐Ÿ”ง Generated C4A-Script:") print("-" * 30) c4a_script = C4ACompiler.generate_script( html=html, query=goal, mode="c4a" ) print(c4a_script) print() # Generate JavaScript print("๐Ÿ”ง Generated JavaScript:") print("-" * 30) js_script = C4ACompiler.generate_script( html=html, query=goal, mode="js" ) print(js_script) print() # Example 2: Simple button click html2 = """ <html> <body> <div class="content"> <h1>Welcome!</h1> <button id="start-btn" class="primary">Get Started</button> </div> </body> </html> """ goal2 = "Click the 'Get Started' button" print("=" * 50) print("๐Ÿ“ Goal:", goal2) print("๐ŸŒ HTML: Simple button") print() print("๐Ÿ”ง Generated C4A-Script:") print("-" * 30) c4a_script2 = C4ACompiler.generate_script( html=html2, query=goal2, mode="c4a" ) print(c4a_script2) print() print("โœ… Done! The LLM automatically converted natural language goals") print(" into executable automation scripts.") if __name__ == "__main__": main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/c4a_script/generate_script_hello_world.py", "license": "Apache License 2.0", "lines": 75, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/examples/c4a_script/github_search/github_search_crawler.py
#!/usr/bin/env python3 """ GitHub Advanced Search Example using Crawl4AI This example demonstrates: 1. Using LLM to generate C4A-Script from HTML snippets 2. Single arun() call with navigation, search form filling, and extraction 3. JSON CSS extraction for structured repository data 4. Complete workflow: navigate โ†’ fill form โ†’ submit โ†’ extract results Requirements: - Crawl4AI with generate_script support - LLM API key (configured in environment) """ import asyncio import json import os from pathlib import Path from typing import List, Dict, Any from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode from crawl4ai import JsonCssExtractionStrategy from crawl4ai.script.c4a_compile import C4ACompiler class GitHubSearchScraper: def __init__(self): self.base_dir = Path(__file__).parent self.search_script_path = self.base_dir / "generated_search_script.js" self.schema_path = self.base_dir / "generated_result_schema.json" self.results_path = self.base_dir / "extracted_repositories.json" self.session_id = "github_search_session" async def generate_search_script(self) -> str: """Generate JavaScript for GitHub advanced search interaction""" print("๐Ÿ”ง Generating search script from search_form.html...") # Check if already generated if self.search_script_path.exists(): print("โœ… Using cached search script") return self.search_script_path.read_text() # Read the search form HTML search_form_html = (self.base_dir / "search_form.html").read_text() # Generate script using LLM search_goal = """ Search for crawl4AI repositories written in Python with more than 10000 stars: 1. Wait for the main search input to be visible 2. Type "crawl4AI" into the main search box 3. Select "Python" from the language dropdown (#search_language) 4. Type ">10000" into the stars input field (#search_stars) 5. Click the search button to submit the form 6. Wait for the search results to appear """ try: script = C4ACompiler.generate_script( html=search_form_html, query=search_goal, mode="js" ) # Save for future use self.search_script_path.write_text(script) print("โœ… Search script generated and saved!") print(f"๐Ÿ“„ Script preview:\n{script[:500]}...") return script except Exception as e: print(f"โŒ Error generating search script: {e}") raise async def generate_result_schema(self) -> Dict[str, Any]: """Generate JSON CSS extraction schema from result HTML""" print("\n๐Ÿ”ง Generating result extraction schema...") # Check if already generated if self.schema_path.exists(): print("โœ… Using cached extraction schema") return json.loads(self.schema_path.read_text()) # Read the result HTML result_html = (self.base_dir / "result.html").read_text() # Generate extraction schema using LLM schema_goal = """ Create a JSON CSS extraction schema to extract from each repository card: - Repository name (the repository name only, not including owner) - Repository owner (organization or username) - Repository URL (full GitHub URL) - Description - Primary programming language - Star count (numeric value) - Topics/tags (array of topic names) - Last updated (time ago string) - Whether it has a sponsor button The schema should handle multiple repository results on the search results page. """ try: # Generate schema schema = JsonCssExtractionStrategy.generate_schema( html=result_html, query=schema_goal, ) # Save for future use self.schema_path.write_text(json.dumps(schema, indent=2)) print("โœ… Extraction schema generated and saved!") print(f"๐Ÿ“„ Schema fields: {[f['name'] for f in schema['fields']]}") return schema except Exception as e: print(f"โŒ Error generating schema: {e}") raise async def crawl_github(self): """Main crawling logic with single arun() call""" print("\n๐Ÿš€ Starting GitHub repository search...") # Generate scripts and schemas search_script = await self.generate_search_script() result_schema = await self.generate_result_schema() # Configure browser (headless=False to see the action) browser_config = BrowserConfig( headless=False, verbose=True, viewport_width=1920, viewport_height=1080 ) async with AsyncWebCrawler(config=browser_config) as crawler: print("\n๐Ÿ“ Navigating to GitHub advanced search and executing search...") # Single call: Navigate, execute search, and extract results search_config = CrawlerRunConfig( session_id=self.session_id, js_code=search_script, # Execute generated JS # wait_for="[data-testid='results-list']", # Wait for search results wait_for=".Box-sc-g0xbh4-0.iwUbcA", # Wait for search results extraction_strategy=JsonCssExtractionStrategy(schema=result_schema), delay_before_return_html=3.0, # Give time for results to fully load cache_mode=CacheMode.BYPASS # Don't cache for fresh results ) result = await crawler.arun( url="https://github.com/search/advanced", config=search_config ) if not result.success: print("โŒ Failed to search GitHub") print(f"Error: {result.error_message}") return print("โœ… Search and extraction completed successfully!") # Extract and save results if result.extracted_content: repositories = json.loads(result.extracted_content) print(f"\n๐Ÿ” Found {len(repositories)} repositories matching criteria") # Save results self.results_path.write_text( json.dumps(repositories, indent=2) ) print(f"๐Ÿ’พ Results saved to: {self.results_path}") # Print sample results print("\n๐Ÿ“Š Sample Results:") for i, repo in enumerate(repositories[:5], 1): print(f"\n{i}. {repo.get('owner', 'Unknown')}/{repo.get('name', 'Unknown')}") print(f" Description: {repo.get('description', 'No description')[:80]}...") print(f" Language: {repo.get('language', 'Unknown')}") print(f" Stars: {repo.get('stars', 'Unknown')}") print(f" Updated: {repo.get('last_updated', 'Unknown')}") if repo.get('topics'): print(f" Topics: {', '.join(repo['topics'][:5])}") print(f" URL: {repo.get('url', 'Unknown')}") else: print("โŒ No repositories extracted") # Save screenshot for reference if result.screenshot: screenshot_path = self.base_dir / "search_results_screenshot.png" with open(screenshot_path, "wb") as f: f.write(result.screenshot) print(f"\n๐Ÿ“ธ Screenshot saved to: {screenshot_path}") async def main(): """Run the GitHub search scraper""" scraper = GitHubSearchScraper() await scraper.crawl_github() print("\n๐ŸŽ‰ GitHub search example completed!") print("Check the generated files:") print(" - generated_search_script.js") print(" - generated_result_schema.json") print(" - extracted_repositories.json") print(" - search_results_screenshot.png") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/c4a_script/github_search/github_search_crawler.py", "license": "Apache License 2.0", "lines": 171, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/c4a_script/tutorial/server.py
#!/usr/bin/env python3 """ C4A-Script Tutorial Server Serves the tutorial app and provides C4A compilation API """ import sys import os from pathlib import Path from flask import Flask, render_template_string, request, jsonify, send_from_directory from flask_cors import CORS # Add parent directories to path to import crawl4ai sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent.parent)) try: from crawl4ai.script import compile as c4a_compile C4A_AVAILABLE = True except ImportError: print("โš ๏ธ C4A compiler not available. Using mock compiler.") C4A_AVAILABLE = False app = Flask(__name__) CORS(app) # Serve static files @app.route('/') def index(): return send_from_directory('.', 'index.html') @app.route('/assets/<path:path>') def serve_assets(path): return send_from_directory('assets', path) @app.route('/playground/') def playground(): return send_from_directory('playground', 'index.html') @app.route('/playground/<path:path>') def serve_playground(path): return send_from_directory('playground', path) # API endpoint for C4A compilation @app.route('/api/compile', methods=['POST']) def compile_endpoint(): try: data = request.get_json() script = data.get('script', '') if not script: return jsonify({ 'success': False, 'error': { 'line': 1, 'column': 1, 'message': 'No script provided', 'suggestion': 'Write some C4A commands' } }) if C4A_AVAILABLE: # Use real C4A compiler result = c4a_compile(script) if result.success: return jsonify({ 'success': True, 'jsCode': result.js_code, 'metadata': { 'lineCount': len(result.js_code), 'sourceLines': len(script.split('\n')) } }) else: error = result.first_error return jsonify({ 'success': False, 'error': { 'line': error.line, 'column': error.column, 'message': error.message, 'suggestion': error.suggestions[0].message if error.suggestions else None, 'code': error.code, 'sourceLine': error.source_line } }) else: # Use mock compiler for demo result = mock_compile(script) return jsonify(result) except Exception as e: return jsonify({ 'success': False, 'error': { 'line': 1, 'column': 1, 'message': f'Server error: {str(e)}', 'suggestion': 'Check server logs' } }), 500 def mock_compile(script): """Simple mock compiler for demo when C4A is not available""" lines = [line for line in script.split('\n') if line.strip() and not line.strip().startswith('#')] js_code = [] for i, line in enumerate(lines): line = line.strip() try: if line.startswith('GO '): url = line[3:].strip() # Handle relative URLs if not url.startswith(('http://', 'https://')): url = '/' + url.lstrip('/') js_code.append(f"await page.goto('{url}');") elif line.startswith('WAIT '): parts = line[5:].strip().split(' ') if parts[0].startswith('`'): selector = parts[0].strip('`') timeout = parts[1] if len(parts) > 1 else '5' js_code.append(f"await page.waitForSelector('{selector}', {{ timeout: {timeout}000 }});") else: seconds = parts[0] js_code.append(f"await page.waitForTimeout({seconds}000);") elif line.startswith('CLICK '): selector = line[6:].strip().strip('`') js_code.append(f"await page.click('{selector}');") elif line.startswith('TYPE '): text = line[5:].strip().strip('"') js_code.append(f"await page.keyboard.type('{text}');") elif line.startswith('SCROLL '): parts = line[7:].strip().split(' ') direction = parts[0] amount = parts[1] if len(parts) > 1 else '500' if direction == 'DOWN': js_code.append(f"await page.evaluate(() => window.scrollBy(0, {amount}));") elif direction == 'UP': js_code.append(f"await page.evaluate(() => window.scrollBy(0, -{amount}));") elif line.startswith('IF '): if 'THEN' not in line: return { 'success': False, 'error': { 'line': i + 1, 'column': len(line), 'message': "Missing 'THEN' keyword after IF condition", 'suggestion': "Add 'THEN' after the condition", 'sourceLine': line } } condition = line[3:line.index('THEN')].strip() action = line[line.index('THEN') + 4:].strip() if 'EXISTS' in condition: selector_match = condition.split('`') if len(selector_match) >= 2: selector = selector_match[1] action_selector = action.split('`')[1] if '`' in action else '' js_code.append( f"if (await page.$$('{selector}').length > 0) {{ " f"await page.click('{action_selector}'); }}" ) elif line.startswith('PRESS '): key = line[6:].strip() js_code.append(f"await page.keyboard.press('{key}');") else: # Unknown command return { 'success': False, 'error': { 'line': i + 1, 'column': 1, 'message': f"Unknown command: {line.split()[0]}", 'suggestion': "Check command syntax", 'sourceLine': line } } except Exception as e: return { 'success': False, 'error': { 'line': i + 1, 'column': 1, 'message': f"Failed to parse: {str(e)}", 'suggestion': "Check syntax", 'sourceLine': line } } return { 'success': True, 'jsCode': js_code, 'metadata': { 'lineCount': len(js_code), 'sourceLines': len(lines) } } # Example scripts endpoint @app.route('/api/examples') def get_examples(): examples = [ { 'id': 'cookie-banner', 'name': 'Handle Cookie Banner', 'description': 'Accept cookies and close newsletter popup', 'script': '''# Handle cookie banner and newsletter GO http://127.0.0.1:8000/playground/ WAIT `body` 2 IF (EXISTS `.cookie-banner`) THEN CLICK `.accept` IF (EXISTS `.newsletter-popup`) THEN CLICK `.close`''' }, { 'id': 'login', 'name': 'Login Flow', 'description': 'Complete login with credentials', 'script': '''# Login to the site CLICK `#login-btn` WAIT `.login-form` 2 CLICK `#email` TYPE "demo@example.com" CLICK `#password` TYPE "demo123" IF (EXISTS `#remember-me`) THEN CLICK `#remember-me` CLICK `button[type="submit"]` WAIT `.welcome-message` 5''' }, { 'id': 'infinite-scroll', 'name': 'Infinite Scroll', 'description': 'Load products with scrolling', 'script': '''# Navigate to catalog and scroll CLICK `#catalog-link` WAIT `.product-grid` 3 # Scroll multiple times to load products SCROLL DOWN 1000 WAIT 1 SCROLL DOWN 1000 WAIT 1 SCROLL DOWN 1000''' }, { 'id': 'form-wizard', 'name': 'Multi-step Form', 'description': 'Complete a multi-step survey', 'script': '''# Navigate to forms CLICK `a[href="#forms"]` WAIT `#survey-form` 2 # Step 1: Basic info CLICK `#full-name` TYPE "John Doe" CLICK `#survey-email` TYPE "john@example.com" CLICK `.next-step` WAIT 1 # Step 2: Preferences CLICK `#interests` CLICK `option[value="tech"]` CLICK `option[value="music"]` CLICK `.next-step` WAIT 1 # Step 3: Submit CLICK `#submit-survey` WAIT `.success-message` 5''' } ] return jsonify(examples) if __name__ == '__main__': port = int(os.environ.get('PORT', 8000)) print(f""" โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ C4A-Script Interactive Tutorial Server โ•‘ โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ โ•‘ โ•‘ โ•‘ Server running at: http://localhost:{port:<6} โ•‘ โ•‘ โ•‘ โ•‘ Features: โ•‘ โ•‘ โ€ข C4A-Script compilation API โ•‘ โ•‘ โ€ข Interactive playground โ•‘ โ•‘ โ€ข Real-time execution visualization โ•‘ โ•‘ โ•‘ โ•‘ C4A Compiler: {'โœ“ Available' if C4A_AVAILABLE else 'โœ— Using mock compiler':<30} โ•‘ โ•‘ โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• """) app.run(host='0.0.0.0', port=port, debug=True)
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/c4a_script/tutorial/server.py", "license": "Apache License 2.0", "lines": 269, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/link_head_extraction_example.py
#!/usr/bin/env python3 """ Link Head Extraction & Scoring Example This example demonstrates Crawl4AI's advanced link analysis capabilities: 1. Basic link head extraction 2. Three-layer scoring system (intrinsic, contextual, total) 3. Pattern-based filtering 4. Multiple practical use cases Requirements: - crawl4ai installed - Internet connection Usage: python link_head_extraction_example.py """ import asyncio from crawl4ai import AsyncWebCrawler, CrawlerRunConfig from crawl4ai import LinkPreviewConfig async def basic_link_head_extraction(): """ Basic example: Extract head content from internal links with scoring """ print("๐Ÿ”— Basic Link Head Extraction Example") print("=" * 50) config = CrawlerRunConfig( # Enable link head extraction link_preview_config=LinkPreviewConfig( include_internal=True, # Process internal links include_external=False, # Skip external links for this demo max_links=5, # Limit to 5 links concurrency=3, # Process 3 links simultaneously timeout=10, # 10 second timeout per link query="API documentation guide", # Query for relevance scoring verbose=True # Show detailed progress ), # Enable intrinsic link scoring score_links=True, only_text=True ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://docs.python.org/3/", config=config) if result.success: print(f"\nโœ… Successfully crawled: {result.url}") internal_links = result.links.get("internal", []) links_with_head = [link for link in internal_links if link.get("head_data") is not None] print(f"๐Ÿง  Links with head data: {len(links_with_head)}") # Show detailed results for i, link in enumerate(links_with_head[:3]): print(f"\n๐Ÿ“„ Link {i+1}: {link['href']}") print(f" Text: '{link.get('text', 'No text')[:50]}...'") # Show all three score types intrinsic = link.get('intrinsic_score') contextual = link.get('contextual_score') total = link.get('total_score') print(f" ๐Ÿ“Š Scores:") if intrinsic is not None: print(f" โ€ข Intrinsic: {intrinsic:.2f}/10.0") if contextual is not None: print(f" โ€ข Contextual: {contextual:.3f}") if total is not None: print(f" โ€ข Total: {total:.3f}") # Show head data head_data = link.get("head_data", {}) if head_data: title = head_data.get("title", "No title") description = head_data.get("meta", {}).get("description", "") print(f" ๐Ÿ“ฐ Title: {title[:60]}...") if description: print(f" ๐Ÿ“ Description: {description[:80]}...") else: print(f"โŒ Crawl failed: {result.error_message}") async def research_assistant_example(): """ Research Assistant: Find highly relevant documentation pages """ print("\n\n๐Ÿ” Research Assistant Example") print("=" * 50) config = CrawlerRunConfig( link_preview_config=LinkPreviewConfig( include_internal=True, include_external=True, include_patterns=["*/docs/*", "*/tutorial/*", "*/guide/*"], exclude_patterns=["*/login*", "*/admin*"], query="machine learning neural networks deep learning", max_links=15, score_threshold=0.4, # Only include high-relevance links concurrency=8, verbose=False # Clean output for this example ), score_links=True ) # Test with scikit-learn documentation async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://scikit-learn.org/stable/", config=config) if result.success: print(f"โœ… Analyzed: {result.url}") all_links = result.links.get("internal", []) + result.links.get("external", []) # Filter for high-scoring links high_scoring_links = [link for link in all_links if link.get("total_score", 0) > 0.6] # Sort by total score (highest first) high_scoring_links.sort(key=lambda x: x.get("total_score", 0), reverse=True) print(f"\n๐ŸŽฏ Found {len(high_scoring_links)} highly relevant links:") print(" (Showing top 5 by relevance score)") for i, link in enumerate(high_scoring_links[:5]): score = link.get("total_score", 0) title = link.get("head_data", {}).get("title", "No title") print(f"\n{i+1}. โญ {score:.3f} - {title[:70]}...") print(f" ๐Ÿ”— {link['href']}") # Show score breakdown intrinsic = link.get('intrinsic_score', 0) contextual = link.get('contextual_score', 0) print(f" ๐Ÿ“Š Quality: {intrinsic:.1f}/10 | Relevance: {contextual:.3f}") else: print(f"โŒ Research failed: {result.error_message}") async def api_discovery_example(): """ API Discovery: Find API endpoints and references """ print("\n\n๐Ÿ”ง API Discovery Example") print("=" * 50) config = CrawlerRunConfig( link_preview_config=LinkPreviewConfig( include_internal=True, include_patterns=["*/api/*", "*/reference/*", "*/endpoint/*"], exclude_patterns=["*/deprecated/*", "*/v1/*"], # Skip old versions max_links=25, concurrency=10, timeout=8, verbose=False ), score_links=True ) # Example with a documentation site that has API references async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/", config=config) if result.success: print(f"โœ… Discovered APIs at: {result.url}") api_links = result.links.get("internal", []) # Categorize by detected content endpoints = {"GET": [], "POST": [], "PUT": [], "DELETE": [], "OTHER": []} for link in api_links: if link.get("head_data"): title = link.get("head_data", {}).get("title", "").upper() text = link.get("text", "").upper() # Simple categorization based on content if "GET" in title or "GET" in text: endpoints["GET"].append(link) elif "POST" in title or "POST" in text: endpoints["POST"].append(link) elif "PUT" in title or "PUT" in text: endpoints["PUT"].append(link) elif "DELETE" in title or "DELETE" in text: endpoints["DELETE"].append(link) else: endpoints["OTHER"].append(link) # Display results total_found = sum(len(links) for links in endpoints.values()) print(f"\n๐Ÿ“ก Found {total_found} API-related links:") for method, links in endpoints.items(): if links: print(f"\n{method} Endpoints ({len(links)}):") for link in links[:3]: # Show first 3 of each type title = link.get("head_data", {}).get("title", "No title") score = link.get("intrinsic_score", 0) print(f" โ€ข [{score:.1f}] {title[:50]}...") print(f" {link['href']}") else: print(f"โŒ API discovery failed: {result.error_message}") async def link_quality_analysis(): """ Link Quality Analysis: Analyze website structure and link quality """ print("\n\n๐Ÿ“Š Link Quality Analysis Example") print("=" * 50) config = CrawlerRunConfig( link_preview_config=LinkPreviewConfig( include_internal=True, max_links=30, # Analyze more links for better statistics concurrency=15, timeout=6, verbose=False ), score_links=True ) async with AsyncWebCrawler() as crawler: # Test with a content-rich site result = await crawler.arun("https://docs.python.org/3/", config=config) if result.success: print(f"โœ… Analyzed: {result.url}") links = result.links.get("internal", []) # Extract intrinsic scores for analysis scores = [link.get('intrinsic_score', 0) for link in links if link.get('intrinsic_score') is not None] if scores: avg_score = sum(scores) / len(scores) high_quality = len([s for s in scores if s >= 7.0]) medium_quality = len([s for s in scores if 4.0 <= s < 7.0]) low_quality = len([s for s in scores if s < 4.0]) print(f"\n๐Ÿ“ˆ Quality Analysis Results:") print(f" ๐Ÿ“Š Average Score: {avg_score:.2f}/10.0") print(f" ๐ŸŸข High Quality (โ‰ฅ7.0): {high_quality} links") print(f" ๐ŸŸก Medium Quality (4.0-6.9): {medium_quality} links") print(f" ๐Ÿ”ด Low Quality (<4.0): {low_quality} links") # Show best and worst links scored_links = [(link, link.get('intrinsic_score', 0)) for link in links if link.get('intrinsic_score') is not None] scored_links.sort(key=lambda x: x[1], reverse=True) print(f"\n๐Ÿ† Top 3 Quality Links:") for i, (link, score) in enumerate(scored_links[:3]): text = link.get('text', 'No text')[:40] print(f" {i+1}. [{score:.1f}] {text}...") print(f" {link['href']}") print(f"\nโš ๏ธ Bottom 3 Quality Links:") for i, (link, score) in enumerate(scored_links[-3:]): text = link.get('text', 'No text')[:40] print(f" {i+1}. [{score:.1f}] {text}...") print(f" {link['href']}") else: print("โŒ No scoring data available") else: print(f"โŒ Analysis failed: {result.error_message}") async def pattern_filtering_example(): """ Pattern Filtering: Demonstrate advanced filtering capabilities """ print("\n\n๐ŸŽฏ Pattern Filtering Example") print("=" * 50) # Example with multiple filtering strategies filters = [ { "name": "Documentation Only", "config": LinkPreviewConfig( include_internal=True, max_links=10, concurrency=5, verbose=False, include_patterns=["*/docs/*", "*/documentation/*"], exclude_patterns=["*/api/*"] ) }, { "name": "API References Only", "config": LinkPreviewConfig( include_internal=True, max_links=10, concurrency=5, verbose=False, include_patterns=["*/api/*", "*/reference/*"], exclude_patterns=["*/tutorial/*"] ) }, { "name": "Exclude Admin Areas", "config": LinkPreviewConfig( include_internal=True, max_links=10, concurrency=5, verbose=False, exclude_patterns=["*/admin/*", "*/login/*", "*/dashboard/*"] ) } ] async with AsyncWebCrawler() as crawler: for filter_example in filters: print(f"\n๐Ÿ” Testing: {filter_example['name']}") config = CrawlerRunConfig( link_preview_config=filter_example['config'], score_links=True ) result = await crawler.arun("https://docs.python.org/3/", config=config) if result.success: links = result.links.get("internal", []) links_with_head = [link for link in links if link.get("head_data")] print(f" ๐Ÿ“Š Found {len(links_with_head)} matching links") if links_with_head: # Show sample matches for link in links_with_head[:2]: title = link.get("head_data", {}).get("title", "No title") print(f" โ€ข {title[:50]}...") print(f" {link['href']}") else: print(f" โŒ Failed: {result.error_message}") async def main(): """ Run all examples """ print("๐Ÿš€ Crawl4AI Link Head Extraction Examples") print("=" * 60) print("This will demonstrate various link analysis capabilities.\n") try: # Run all examples await basic_link_head_extraction() await research_assistant_example() await api_discovery_example() await link_quality_analysis() await pattern_filtering_example() print("\n" + "=" * 60) print("โœจ All examples completed successfully!") print("\nNext steps:") print("1. Try modifying the queries and patterns above") print("2. Test with your own websites") print("3. Experiment with different score thresholds") print("4. Check out the full documentation for more options") except KeyboardInterrupt: print("\nโน๏ธ Examples interrupted by user") except Exception as e: print(f"\n๐Ÿ’ฅ Error running examples: {str(e)}") import traceback traceback.print_exc() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/link_head_extraction_example.py", "license": "Apache License 2.0", "lines": 311, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/url_seeder/bbc_sport_research_assistant.py
""" BBC Sport Research Assistant Pipeline ===================================== This example demonstrates how URLSeeder helps create an efficient research pipeline: 1. Discover all available URLs without crawling 2. Filter and rank them based on relevance 3. Crawl only the most relevant content 4. Generate comprehensive research insights Pipeline Steps: 1. Get user query 2. Optionally enhance query using LLM 3. Use URLSeeder to discover and rank URLs 4. Crawl top K URLs with BM25 filtering 5. Generate detailed response with citations Requirements: - pip install crawl4ai - pip install litellm - export GEMINI_API_KEY="your-api-key" Usage: - Run normally: python bbc_sport_research_assistant.py - Run test mode: python bbc_sport_research_assistant.py test Note: AsyncUrlSeeder now uses context manager for automatic cleanup. """ import asyncio import json import os import hashlib import pickle from typing import List, Dict, Optional, Tuple from dataclasses import dataclass, asdict from datetime import datetime from pathlib import Path # Rich for colored output from rich.console import Console from rich.text import Text from rich.panel import Panel from rich.table import Table from rich.progress import Progress, SpinnerColumn, TextColumn # Crawl4AI imports from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, AsyncUrlSeeder, SeedingConfig, AsyncLogger ) from crawl4ai.content_filter_strategy import PruningContentFilter from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator # LiteLLM for AI communication import litellm # Initialize Rich console console = Console() # Get the current directory where this script is located SCRIPT_DIR = Path(__file__).parent.resolve() # Cache configuration - relative to script directory CACHE_DIR = SCRIPT_DIR / "temp_cache" CACHE_DIR.mkdir(parents=True, exist_ok=True) # Testing limits TESTING_MODE = True MAX_URLS_DISCOVERY = 100 if TESTING_MODE else 1000 MAX_URLS_TO_CRAWL = 5 if TESTING_MODE else 10 def get_cache_key(prefix: str, *args) -> str: """Generate cache key from prefix and arguments""" content = f"{prefix}:{'|'.join(str(arg) for arg in args)}" return hashlib.md5(content.encode()).hexdigest() def load_from_cache(cache_key: str) -> Optional[any]: """Load data from cache if exists""" cache_path = CACHE_DIR / f"{cache_key}.pkl" if cache_path.exists(): with open(cache_path, 'rb') as f: return pickle.load(f) return None def save_to_cache(cache_key: str, data: any) -> None: """Save data to cache""" cache_path = CACHE_DIR / f"{cache_key}.pkl" with open(cache_path, 'wb') as f: pickle.dump(data, f) @dataclass class ResearchConfig: """Configuration for research pipeline""" # Core settings domain: str = "www.bbc.com/sport" max_urls_discovery: int = 100 max_urls_to_crawl: int = 10 top_k_urls: int = 10 # Scoring and filtering score_threshold: float = 0.1 scoring_method: str = "bm25" # Processing options use_llm_enhancement: bool = True extract_head_metadata: bool = True live_check: bool = True force_refresh: bool = False # Crawler settings max_concurrent_crawls: int = 5 timeout: int = 30000 headless: bool = True # Output settings save_json: bool = True save_markdown: bool = True output_dir: str = None # Will be set in __post_init__ # Development settings test_mode: bool = False interactive_mode: bool = False verbose: bool = True def __post_init__(self): """Adjust settings based on test mode""" if self.test_mode: self.max_urls_discovery = 50 self.max_urls_to_crawl = 3 self.top_k_urls = 5 # Set default output directory relative to script location if self.output_dir is None: self.output_dir = str(SCRIPT_DIR / "research_results") @dataclass class ResearchQuery: """Container for research query and metadata""" original_query: str enhanced_query: Optional[str] = None search_patterns: List[str] = None timestamp: str = None @dataclass class ResearchResult: """Container for research results""" query: ResearchQuery discovered_urls: List[Dict] crawled_content: List[Dict] synthesis: str citations: List[Dict] metadata: Dict async def get_user_query() -> str: """ Get research query from user input """ query = input("\n๐Ÿ” Enter your research query: ") return query.strip() async def enhance_query_with_llm(query: str) -> ResearchQuery: """ Use LLM to enhance the research query: - Extract key terms - Generate search patterns - Identify related topics """ # Check cache cache_key = get_cache_key("enhanced_query", query) cached_result = load_from_cache(cache_key) if cached_result: console.print("[dim cyan]๐Ÿ“ฆ Using cached enhanced query[/dim cyan]") return cached_result try: response = await litellm.acompletion( model="gemini/gemini-2.5-flash-preview-04-17", messages=[{ "role": "user", "content": f"""Given this research query: "{query}" Extract: 1. Key terms and concepts (as a list) 2. Related search terms 3. A more specific/enhanced version of the query Return as JSON: {{ "key_terms": ["term1", "term2"], "related_terms": ["related1", "related2"], "enhanced_query": "enhanced version of query" }}""" }], # reasoning_effort="low", temperature=0.3, response_format={"type": "json_object"} ) data = json.loads(response.choices[0].message.content) # Create search patterns all_terms = data["key_terms"] + data["related_terms"] patterns = [f"*{term.lower()}*" for term in all_terms] result = ResearchQuery( original_query=query, enhanced_query=data["enhanced_query"], search_patterns=patterns[:10], # Limit patterns timestamp=datetime.now().isoformat() ) # Cache the result save_to_cache(cache_key, result) return result except Exception as e: console.print(f"[yellow]โš ๏ธ LLM enhancement failed: {e}[/yellow]") # Fallback to simple tokenization return ResearchQuery( original_query=query, enhanced_query=query, search_patterns=tokenize_query_to_patterns(query), timestamp=datetime.now().isoformat() ) def tokenize_query_to_patterns(query: str) -> List[str]: """ Convert query into URL patterns for URLSeeder Example: "AI startups funding" -> ["*ai*", "*startup*", "*funding*"] """ # Simple tokenization - split and create patterns words = query.lower().split() # Filter out common words stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'that'} keywords = [w for w in words if w not in stop_words and len(w) > 2] # Create patterns patterns = [f"*{keyword}*" for keyword in keywords] return patterns[:8] # Limit to 8 patterns async def discover_urls(domain: str, query: str, config: ResearchConfig) -> List[Dict]: """ Use URLSeeder to discover and rank URLs: 1. Fetch all URLs from domain 2. Filter by patterns 3. Extract metadata (titles, descriptions) 4. Rank by BM25 relevance score 5. Return top K URLs """ # Check cache cache_key = get_cache_key("discovered_urls", domain, query, config.top_k_urls) cached_result = load_from_cache(cache_key) if cached_result and not config.force_refresh: console.print("[dim cyan]๐Ÿ“ฆ Using cached URL discovery[/dim cyan]") return cached_result console.print(f"\n[cyan]๐Ÿ” Discovering URLs from {domain}...[/cyan]") # Initialize URL seeder with context manager async with AsyncUrlSeeder(logger=AsyncLogger(verbose=config.verbose)) as seeder: # Configure seeding seeding_config = SeedingConfig( source="sitemap+cc", # Use both sitemap and Common Crawl extract_head=config.extract_head_metadata, query=query, scoring_method=config.scoring_method, score_threshold=config.score_threshold, max_urls=config.max_urls_discovery, live_check=config.live_check, force=config.force_refresh ) try: # Discover URLs urls = await seeder.urls(domain, seeding_config) # Sort by relevance score (descending) sorted_urls = sorted( urls, key=lambda x: x.get('relevance_score', 0), reverse=True ) # Take top K top_urls = sorted_urls[:config.top_k_urls] console.print(f"[green]โœ… Discovered {len(urls)} URLs, selected top {len(top_urls)}[/green]") # Cache the result save_to_cache(cache_key, top_urls) return top_urls except Exception as e: console.print(f"[red]โŒ URL discovery failed: {e}[/red]") return [] async def crawl_selected_urls(urls: List[str], query: str, config: ResearchConfig) -> List[Dict]: """ Crawl selected URLs with content filtering: - Use AsyncWebCrawler.arun_many() - Apply content filter - Generate clean markdown """ # Extract just URLs from the discovery results url_list = [u['url'] for u in urls if 'url' in u][:config.max_urls_to_crawl] if not url_list: console.print("[red]โŒ No URLs to crawl[/red]") return [] console.print(f"\n[cyan]๐Ÿ•ท๏ธ Crawling {len(url_list)} URLs...[/cyan]") # Check cache for each URL crawled_results = [] urls_to_crawl = [] for url in url_list: cache_key = get_cache_key("crawled_content", url, query) cached_content = load_from_cache(cache_key) if cached_content and not config.force_refresh: crawled_results.append(cached_content) else: urls_to_crawl.append(url) if urls_to_crawl: console.print(f"[cyan]๐Ÿ“ฅ Crawling {len(urls_to_crawl)} new URLs (cached: {len(crawled_results)})[/cyan]") # Configure markdown generator with content filter md_generator = DefaultMarkdownGenerator( content_filter=PruningContentFilter( threshold=0.48, threshold_type="dynamic", min_word_threshold=10 ), ) # Configure crawler crawler_config = CrawlerRunConfig( markdown_generator=md_generator, exclude_external_links=True, excluded_tags=['nav', 'header', 'footer', 'aside'], ) # Create crawler with browser config async with AsyncWebCrawler( config=BrowserConfig( headless=config.headless, verbose=config.verbose ) ) as crawler: # Crawl URLs results = await crawler.arun_many( urls_to_crawl, config=crawler_config, max_concurrent=config.max_concurrent_crawls ) # Process results for url, result in zip(urls_to_crawl, results): if result.success: content_data = { 'url': url, 'title': result.metadata.get('title', ''), 'markdown': result.markdown.fit_markdown or result.markdown.raw_markdown, 'raw_length': len(result.markdown.raw_markdown), 'fit_length': len(result.markdown.fit_markdown) if result.markdown.fit_markdown else len(result.markdown.raw_markdown), 'metadata': result.metadata } crawled_results.append(content_data) # Cache the result cache_key = get_cache_key("crawled_content", url, query) save_to_cache(cache_key, content_data) else: console.print(f" [red]โŒ Failed: {url[:50]}... - {result.error}[/red]") console.print(f"[green]โœ… Successfully crawled {len(crawled_results)} URLs[/green]") return crawled_results async def generate_research_synthesis( query: str, crawled_content: List[Dict] ) -> Tuple[str, List[Dict]]: """ Use LLM to synthesize research findings: - Analyze all crawled content - Generate comprehensive answer - Extract citations and references """ if not crawled_content: return "No content available for synthesis.", [] console.print("\n[cyan]๐Ÿค– Generating research synthesis...[/cyan]") # Prepare content for LLM content_sections = [] for i, content in enumerate(crawled_content, 1): section = f""" SOURCE {i}: Title: {content['title']} URL: {content['url']} Content Preview: {content['markdown'][:1500]}... """ content_sections.append(section) combined_content = "\n---\n".join(content_sections) try: response = await litellm.acompletion( model="gemini/gemini-2.5-flash-preview-04-17", messages=[{ "role": "user", "content": f"""Research Query: "{query}" Based on the following sources, provide a comprehensive research synthesis. {combined_content} Please provide: 1. An executive summary (2-3 sentences) 2. Key findings (3-5 bullet points) 3. Detailed analysis (2-3 paragraphs) 4. Future implications or trends Format your response with clear sections and cite sources using [Source N] notation. Keep the total response under 800 words.""" }], # reasoning_effort="medium", temperature=0.7 ) synthesis = response.choices[0].message.content # Extract citations from the synthesis citations = [] for i, content in enumerate(crawled_content, 1): if f"[Source {i}]" in synthesis or f"Source {i}" in synthesis: citations.append({ 'source_id': i, 'title': content['title'], 'url': content['url'] }) return synthesis, citations except Exception as e: console.print(f"[red]โŒ Synthesis generation failed: {e}[/red]") # Fallback to simple summary summary = f"Research on '{query}' found {len(crawled_content)} relevant articles:\n\n" for content in crawled_content[:3]: summary += f"- {content['title']}\n {content['url']}\n\n" return summary, [] def format_research_output(result: ResearchResult) -> str: """ Format the final research output with: - Executive summary - Key findings - Detailed analysis - Citations and sources """ output = [] output.append("\n" + "=" * 60) output.append("๐Ÿ”ฌ RESEARCH RESULTS") output.append("=" * 60) # Query info output.append(f"\n๐Ÿ“‹ Query: {result.query.original_query}") if result.query.enhanced_query != result.query.original_query: output.append(f" Enhanced: {result.query.enhanced_query}") # Discovery stats output.append(f"\n๐Ÿ“Š Statistics:") output.append(f" - URLs discovered: {len(result.discovered_urls)}") output.append(f" - URLs crawled: {len(result.crawled_content)}") output.append(f" - Processing time: {result.metadata.get('duration', 'N/A')}") # Synthesis output.append(f"\n๐Ÿ“ SYNTHESIS") output.append("-" * 60) output.append(result.synthesis) # Citations if result.citations: output.append(f"\n๐Ÿ“š SOURCES") output.append("-" * 60) for citation in result.citations: output.append(f"[{citation['source_id']}] {citation['title']}") output.append(f" {citation['url']}") return "\n".join(output) async def save_research_results(result: ResearchResult, config: ResearchConfig) -> Tuple[str, str]: """ Save research results in JSON and Markdown formats Returns: Tuple of (json_path, markdown_path) """ # Create output directory output_dir = Path(config.output_dir) output_dir.mkdir(parents=True, exist_ok=True) # Generate filename based on query and timestamp timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") query_slug = result.query.original_query[:50].replace(" ", "_").replace("/", "_") base_filename = f"{timestamp}_{query_slug}" json_path = None md_path = None # Save JSON if config.save_json: json_path = output_dir / f"{base_filename}.json" with open(json_path, 'w') as f: json.dump(asdict(result), f, indent=2, default=str) console.print(f"\n[green]๐Ÿ’พ JSON saved: {json_path}[/green]") # Save Markdown if config.save_markdown: md_path = output_dir / f"{base_filename}.md" # Create formatted markdown md_content = [ f"# Research Report: {result.query.original_query}", f"\n**Generated on:** {result.metadata.get('timestamp', 'N/A')}", f"\n**Domain:** {result.metadata.get('domain', 'N/A')}", f"\n**Processing time:** {result.metadata.get('duration', 'N/A')}", "\n---\n", "## Query Information", f"- **Original Query:** {result.query.original_query}", f"- **Enhanced Query:** {result.query.enhanced_query or 'N/A'}", f"- **Search Patterns:** {', '.join(result.query.search_patterns or [])}", "\n## Statistics", f"- **URLs Discovered:** {len(result.discovered_urls)}", f"- **URLs Crawled:** {len(result.crawled_content)}", f"- **Sources Cited:** {len(result.citations)}", "\n## Research Synthesis\n", result.synthesis, "\n## Sources\n" ] # Add citations for citation in result.citations: md_content.append(f"### [{citation['source_id']}] {citation['title']}") md_content.append(f"- **URL:** [{citation['url']}]({citation['url']})") md_content.append("") # Add discovered URLs summary md_content.extend([ "\n## Discovered URLs (Top 10)\n", "| Score | URL | Title |", "|-------|-----|-------|" ]) for url_data in result.discovered_urls[:10]: score = url_data.get('relevance_score', 0) url = url_data.get('url', '') title = 'N/A' if 'head_data' in url_data and url_data['head_data']: title = url_data['head_data'].get('title', 'N/A')[:60] + '...' md_content.append(f"| {score:.3f} | {url[:50]}... | {title} |") # Write markdown with open(md_path, 'w') as f: f.write('\n'.join(md_content)) console.print(f"[green]๐Ÿ“„ Markdown saved: {md_path}[/green]") return str(json_path) if json_path else None, str(md_path) if md_path else None async def wait_for_user(message: str = "\nPress Enter to continue..."): """Wait for user input in interactive mode""" input(message) async def research_pipeline( query: str, config: ResearchConfig ) -> ResearchResult: """ Main research pipeline orchestrator with configurable settings """ start_time = datetime.now() # Display pipeline header header = Panel( f"[bold cyan]Research Pipeline[/bold cyan]\n\n" f"[dim]Domain:[/dim] {config.domain}\n" f"[dim]Mode:[/dim] {'Test' if config.test_mode else 'Production'}\n" f"[dim]Interactive:[/dim] {'Yes' if config.interactive_mode else 'No'}", title="๐Ÿš€ Starting", border_style="cyan" ) console.print(header) # Step 1: Enhance query (optional) console.print(f"\n[bold cyan]๐Ÿ“ Step 1: Query Processing[/bold cyan]") if config.interactive_mode: await wait_for_user() if config.use_llm_enhancement: research_query = await enhance_query_with_llm(query) else: research_query = ResearchQuery( original_query=query, enhanced_query=query, search_patterns=tokenize_query_to_patterns(query), timestamp=datetime.now().isoformat() ) console.print(f" [green]โœ… Query ready:[/green] {research_query.enhanced_query or query}") # Step 2: Discover URLs console.print(f"\n[bold cyan]๐Ÿ” Step 2: URL Discovery[/bold cyan]") if config.interactive_mode: await wait_for_user() discovered_urls = await discover_urls( domain=config.domain, query=research_query.enhanced_query or query, config=config ) if not discovered_urls: return ResearchResult( query=research_query, discovered_urls=[], crawled_content=[], synthesis="No relevant URLs found for the given query.", citations=[], metadata={'duration': str(datetime.now() - start_time)} ) console.print(f" [green]โœ… Found {len(discovered_urls)} relevant URLs[/green]") # Step 3: Crawl selected URLs console.print(f"\n[bold cyan]๐Ÿ•ท๏ธ Step 3: Content Crawling[/bold cyan]") if config.interactive_mode: await wait_for_user() crawled_content = await crawl_selected_urls( urls=discovered_urls, query=research_query.enhanced_query or query, config=config ) console.print(f" [green]โœ… Successfully crawled {len(crawled_content)} pages[/green]") # Step 4: Generate synthesis console.print(f"\n[bold cyan]๐Ÿค– Step 4: Synthesis Generation[/bold cyan]") if config.interactive_mode: await wait_for_user() synthesis, citations = await generate_research_synthesis( query=research_query.enhanced_query or query, crawled_content=crawled_content ) console.print(f" [green]โœ… Generated synthesis with {len(citations)} citations[/green]") # Step 5: Create result result = ResearchResult( query=research_query, discovered_urls=discovered_urls, crawled_content=crawled_content, synthesis=synthesis, citations=citations, metadata={ 'duration': str(datetime.now() - start_time), 'domain': config.domain, 'timestamp': datetime.now().isoformat(), 'config': asdict(config) } ) duration = datetime.now() - start_time console.print(f"\n[bold green]โœ… Research completed in {duration}[/bold green]") return result async def main(): """ Main entry point for the BBC Sport Research Assistant """ # Example queries example_queries = [ "Premier League transfer news and rumors", "Champions League match results and analysis", "World Cup qualifying updates", "Football injury reports and return dates", "Tennis grand slam tournament results" ] # Display header console.print(Panel.fit( "[bold cyan]BBC Sport Research Assistant[/bold cyan]\n\n" "This tool demonstrates efficient research using URLSeeder:\n" "[dim]โ€ข Discover all URLs without crawling\n" "โ€ข Filter and rank by relevance\n" "โ€ข Crawl only the most relevant content\n" "โ€ข Generate AI-powered insights with citations[/dim]\n\n" f"[dim]๐Ÿ“ Working directory: {SCRIPT_DIR}[/dim]", title="๐Ÿ”ฌ Welcome", border_style="cyan" )) # Configuration options table config_table = Table(title="\nโš™๏ธ Configuration Options", show_header=False, box=None) config_table.add_column(style="bold cyan", width=3) config_table.add_column() config_table.add_row("1", "Quick Test Mode (3 URLs, fast)") config_table.add_row("2", "Standard Mode (10 URLs, balanced)") config_table.add_row("3", "Comprehensive Mode (20 URLs, thorough)") config_table.add_row("4", "Custom Configuration") console.print(config_table) config_choice = input("\nSelect configuration (1-4): ").strip() # Create config based on choice if config_choice == "1": config = ResearchConfig(test_mode=True, interactive_mode=False) elif config_choice == "2": config = ResearchConfig(max_urls_to_crawl=10, top_k_urls=10) elif config_choice == "3": config = ResearchConfig(max_urls_to_crawl=20, top_k_urls=20, max_urls_discovery=200) else: # Custom configuration config = ResearchConfig() config.test_mode = input("\nTest mode? (y/n): ").lower() == 'y' config.interactive_mode = input("Interactive mode (pause between steps)? (y/n): ").lower() == 'y' config.use_llm_enhancement = input("Use AI to enhance queries? (y/n): ").lower() == 'y' if not config.test_mode: try: config.max_urls_to_crawl = int(input("Max URLs to crawl (default 10): ") or "10") config.top_k_urls = int(input("Top K URLs to select (default 10): ") or "10") except ValueError: console.print("[yellow]Using default values[/yellow]") # Display example queries query_table = Table(title="\n๐Ÿ“‹ Example Queries", show_header=False, box=None) query_table.add_column(style="bold cyan", width=3) query_table.add_column() for i, q in enumerate(example_queries, 1): query_table.add_row(str(i), q) console.print(query_table) query_input = input("\nSelect a query (1-5) or enter your own: ").strip() if query_input.isdigit() and 1 <= int(query_input) <= len(example_queries): query = example_queries[int(query_input) - 1] else: query = query_input if query_input else example_queries[0] console.print(f"\n[bold cyan]๐Ÿ“ Selected Query:[/bold cyan] {query}") # Run the research pipeline result = await research_pipeline(query=query, config=config) # Display results formatted_output = format_research_output(result) # print(formatted_output) console.print(Panel.fit( formatted_output, title="๐Ÿ”ฌ Research Results", border_style="green" )) # Save results if config.save_json or config.save_markdown: json_path, md_path = await save_research_results(result, config) # print(f"\nโœ… Results saved successfully!") if json_path: console.print(f"[green]JSON saved at:[/green] {json_path}") if md_path: console.print(f"[green]Markdown saved at:[/green] {md_path}") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/url_seeder/bbc_sport_research_assistant.py", "license": "Apache License 2.0", "lines": 661, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/url_seeder/url_seeder_demo.py
""" URL Seeder Demo - Interactive showcase of Crawl4AI's URL discovery capabilities This demo shows: 1. Basic URL discovery from sitemaps and Common Crawl 2. Cache management and forced refresh 3. Live URL validation and metadata extraction 4. BM25 relevance scoring for intelligent filtering 5. Integration with AsyncWebCrawler for the complete pipeline 6. Multi-domain discovery across multiple sites Note: The AsyncUrlSeeder now supports context manager protocol for automatic cleanup. """ import asyncio import time from datetime import datetime from rich.console import Console from rich.table import Table from rich.panel import Panel from rich.progress import Progress, SpinnerColumn, BarColumn, TimeElapsedColumn from rich.prompt import Prompt, Confirm from crawl4ai import ( AsyncWebCrawler, CrawlerRunConfig, AsyncUrlSeeder, SeedingConfig ) console = Console() console.rule("[bold green]๐ŸŒ Crawl4AI URL Seeder: Interactive Demo") DOMAIN = "crawl4ai.com" # Utils def print_head_info(head_data): table = Table(title="<head> Metadata", expand=True) table.add_column("Key", style="cyan", no_wrap=True) table.add_column("Value", style="magenta") if not head_data: console.print("[yellow]No head data found.") return if head_data.get("title"): table.add_row("title", head_data["title"]) if head_data.get("charset"): table.add_row("charset", head_data["charset"]) for k, v in head_data.get("meta", {}).items(): table.add_row(f"meta:{k}", v) for rel, items in head_data.get("link", {}).items(): for item in items: table.add_row(f"link:{rel}", item.get("href", "")) console.print(table) async def section_1_basic_exploration(seed: AsyncUrlSeeder): console.rule("[bold cyan]1. Basic Seeding") cfg = SeedingConfig(source="cc+sitemap", pattern="*", verbose=True) start_time = time.time() with Progress(SpinnerColumn(), "[progress.description]{task.description}") as p: p.add_task(description="Fetching from Common Crawl + Sitemap...", total=None) urls = await seed.urls(DOMAIN, cfg) elapsed = time.time() - start_time console.print(f"[green]โœ“ Fetched {len(urls)} URLs in {elapsed:.2f} seconds") console.print(f"[dim] Speed: {len(urls)/elapsed:.0f} URLs/second[/dim]\n") console.print("[bold]Sample URLs:[/bold]") for u in urls[:5]: console.print(f" โ€ข {u['url']}") async def section_2_cache_demo(seed: AsyncUrlSeeder): console.rule("[bold cyan]2. Caching Demonstration") console.print("[yellow]Using `force=True` to bypass cache and fetch fresh data.[/yellow]") cfg = SeedingConfig(source="cc", pattern="*crawl4ai.com/core/*", verbose=False, force = True) await seed.urls(DOMAIN, cfg) async def section_3_live_head(seed: AsyncUrlSeeder): console.rule("[bold cyan]3. Live Check + Head Extraction") cfg = SeedingConfig( extract_head=True, concurrency=10, hits_per_sec=5, pattern="*crawl4ai.com/*", max_urls=10, verbose=False, ) urls = await seed.urls(DOMAIN, cfg) valid = [u for u in urls if u["status"] == "valid"] console.print(f"[green]Valid: {len(valid)} / {len(urls)}") if valid: print_head_info(valid[0]["head_data"]) async def section_4_bm25_scoring(seed: AsyncUrlSeeder): console.rule("[bold cyan]4. BM25 Relevance Scoring") console.print("[yellow]Using AI-powered relevance scoring to find the most relevant content[/yellow]") query = "markdown generation extraction strategies" cfg = SeedingConfig( source="sitemap", extract_head=True, query=query, scoring_method="bm25", score_threshold=0.3, # Only URLs with >30% relevance max_urls=20, verbose=False ) with Progress(SpinnerColumn(), "[progress.description]{task.description}") as p: p.add_task(description=f"Searching for: '{query}'", total=None) urls = await seed.urls(DOMAIN, cfg) console.print(f"[green]Found {len(urls)} relevant URLs (score > 0.3)") # Show top results with scores table = Table(title="Top 5 Most Relevant Pages", expand=True) table.add_column("Score", style="cyan", width=8) table.add_column("Title", style="magenta") table.add_column("URL", style="blue", overflow="fold") for url in urls[:5]: score = f"{url['relevance_score']:.2f}" title = url['head_data'].get('title', 'No title')[:60] + "..." table.add_row(score, title, url['url']) console.print(table) async def section_5_keyword_filter_to_agent(seed: AsyncUrlSeeder): console.rule("[bold cyan]5. Complete Pipeline: Discover โ†’ Filter โ†’ Crawl") cfg = SeedingConfig( extract_head=True, concurrency=20, hits_per_sec=10, max_urls=10, pattern="*crawl4ai.com/*", force=True, ) urls = await seed.urls(DOMAIN, cfg) keywords = ["deep crawling", "markdown", "llm"] selected = [u for u in urls if any(k in str(u["head_data"]).lower() for k in keywords)] console.print(f"[cyan]Selected {len(selected)} URLs with relevant keywords:") for u in selected[:10]: console.print("โ€ข", u["url"]) console.print("\n[yellow]Passing above URLs to arun_many() LLM agent for crawling...") async with AsyncWebCrawler(verbose=True) as crawler: crawl_run_config = CrawlerRunConfig( # Example crawl settings for these URLs: only_text=True, # Just get text content screenshot=False, pdf=False, word_count_threshold=50, # Only process pages with at least 50 words stream=True, verbose=False # Keep logs clean for arun_many in this demo ) # Extract just the URLs from the selected results urls_to_crawl = [u["url"] for u in selected] # We'll stream results for large lists, but collect them here for demonstration crawled_results_stream = await crawler.arun_many(urls_to_crawl, config=crawl_run_config) final_crawled_data = [] async for result in crawled_results_stream: final_crawled_data.append(result) if len(final_crawled_data) % 5 == 0: print(f" Processed {len(final_crawled_data)}/{len(urls_to_crawl)} URLs...") print(f"\n Successfully crawled {len(final_crawled_data)} URLs.") if final_crawled_data: print("\n Example of a crawled result's URL and Markdown (first successful one):") for result in final_crawled_data: if result.success and result.markdown.raw_markdown: print(f" URL: {result.url}") print(f" Markdown snippet: {result.markdown.raw_markdown[:200]}...") break else: print(" No successful crawls with markdown found.") else: print(" No successful crawls found.") async def section_6_multi_domain(seed: AsyncUrlSeeder): console.rule("[bold cyan]6. Multi-Domain Discovery") console.print("[yellow]Discovering Python tutorials across multiple educational sites[/yellow]\n") domains = ["docs.python.org", "realpython.com", "docs.crawl4ai.com"] cfg = SeedingConfig( source="sitemap", extract_head=True, query="python tutorial guide", scoring_method="bm25", score_threshold=0.2, max_urls=5 # Per domain ) start_time = time.time() with Progress(SpinnerColumn(), "[progress.description]{task.description}") as p: task = p.add_task(description="Discovering across domains...", total=None) results = await seed.many_urls(domains, cfg) elapsed = time.time() - start_time total_urls = sum(len(urls) for urls in results.values()) console.print(f"[green]โœ“ Found {total_urls} relevant URLs across {len(domains)} domains in {elapsed:.2f}s\n") # Show results per domain for domain, urls in results.items(): console.print(f"[bold]{domain}:[/bold] {len(urls)} relevant pages") if urls: top = urls[0] console.print(f" Top result: [{top['relevance_score']:.2f}] {top['head_data'].get('title', 'No title')}") async def main(): async with AsyncUrlSeeder() as seed: # Interactive menu sections = { "1": ("Basic URL Discovery", section_1_basic_exploration), "2": ("Cache Management Demo", section_2_cache_demo), "3": ("Live Check & Metadata Extraction", section_3_live_head), "4": ("BM25 Relevance Scoring", section_4_bm25_scoring), "5": ("Complete Pipeline (Discover โ†’ Filter โ†’ Crawl)", section_5_keyword_filter_to_agent), "6": ("Multi-Domain Discovery", section_6_multi_domain), "7": ("Run All Demos", None) } console.print("\n[bold]Available Demos:[/bold]") for key, (title, _) in sections.items(): console.print(f" {key}. {title}") choice = Prompt.ask("\n[cyan]Which demo would you like to run?[/cyan]", choices=list(sections.keys()), default="7") console.print() if choice == "7": # Run all demos for key, (title, func) in sections.items(): if key != "7" and func: await func(seed) if key != "6": # Don't pause after the last demo if not Confirm.ask("\n[yellow]Continue to next demo?[/yellow]", default=True): break console.print() else: # Run selected demo _, func = sections[choice] await func(seed) console.rule("[bold green]Demo Complete โœ”๏ธŽ") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/url_seeder/url_seeder_demo.py", "license": "Apache License 2.0", "lines": 214, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/url_seeder/url_seeder_quick_demo.py
""" ๐Ÿš€ URL Seeder + AsyncWebCrawler = Magic! Quick demo showing discovery โ†’ filter โ†’ crawl pipeline Note: Uses context manager for automatic cleanup of resources. """ import asyncio, os from crawl4ai import AsyncUrlSeeder, AsyncWebCrawler, SeedingConfig, CrawlerRunConfig, AsyncLogger, DefaultMarkdownGenerator from crawl4ai.content_filter_strategy import PruningContentFilter CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) # ๐Ÿ” Example 1: Discover ALL โ†’ Filter โ†’ Crawl async def discover_and_crawl(): """Find Python module tutorials & extract them all!""" async with AsyncUrlSeeder(logger=AsyncLogger()) as seeder: # Step 1: See how many URLs exist (spoiler: A LOT!) print("๐Ÿ“Š Let's see what RealPython has...") all_urls = await seeder.urls("realpython.com", SeedingConfig(source="sitemap")) print(f"๐Ÿ˜ฑ Found {len(all_urls)} total URLs!") # Step 2: Filter for Python modules (perfect size ~13) print("\n๐ŸŽฏ Filtering for 'python-modules' tutorials...") module_urls = await seeder.urls("realpython.com", SeedingConfig( source="sitemap", pattern="*python-modules*", live_check=True # Make sure they're alive! )) print(f"โœจ Found {len(module_urls)} module tutorials") for url in module_urls[:3]: # Show first 3 status = "โœ…" if url["status"] == "valid" else "โŒ" print(f"{status} {url['url']}") # Step 3: Crawl them all with pruning (keep it lean!) print("\n๐Ÿ•ท๏ธ Crawling all module tutorials...") async with AsyncWebCrawler() as crawler: config = CrawlerRunConfig( markdown_generator=DefaultMarkdownGenerator( content_filter=PruningContentFilter( # Smart filtering! threshold=0.48, # Remove fluff threshold_type="fixed", ), ), only_text=True, stream=True, ) # Extract just the URLs from the seeder results urls_to_crawl = [u["url"] for u in module_urls[:5]] results = await crawler.arun_many(urls_to_crawl, config=config) # Process & save saved = 0 async for result in results: if result.success: # Save each tutorial (name from URL) name = result.url.split("/")[-2] + ".md" name = os.path.join(CURRENT_DIR, name) with open(name, "w") as f: f.write(result.markdown.fit_markdown) saved += 1 print(f"๐Ÿ’พ Saved: {name}") print(f"\n๐ŸŽ‰ Successfully saved {saved} tutorials!") # ๐Ÿ” Example 2: Beautiful Soup articles with metadata peek async def explore_beautifulsoup(): """Discover BeautifulSoup content & peek at metadata""" async with AsyncUrlSeeder(logger=AsyncLogger()) as seeder: print("๐Ÿฒ Looking for Beautiful Soup articles...") soup_urls = await seeder.urls("realpython.com", SeedingConfig( source="sitemap", pattern="*beautiful-soup*", extract_head=True # Get the metadata! )) print(f"\n๐Ÿ“š Found {len(soup_urls)} Beautiful Soup articles:\n") # Show what we discovered for i, url in enumerate(soup_urls, 1): meta = url["head_data"]["meta"] print(f"{i}. {url['head_data']['title']}") print(f" ๐Ÿ“ {meta.get('description', 'No description')[:60]}...") print(f" ๐Ÿ‘ค By: {meta.get('author', 'Unknown')}") print(f" ๐Ÿ”— {url['url']}\n") # ๐Ÿ” Example 3: Smart search with BM25 relevance scoring async def smart_search_with_bm25(): """Use AI-powered relevance scoring to find the best content""" async with AsyncUrlSeeder(logger=AsyncLogger()) as seeder: print("๐Ÿง  Smart search: 'web scraping tutorial quiz'") # Search with BM25 scoring - AI finds the best matches! results = await seeder.urls("realpython.com", SeedingConfig( source="sitemap", pattern="*beautiful-soup*", extract_head=True, query="web scraping tutorial quiz", # Our search scoring_method="bm25", score_threshold=0.2 # Quality filter )) print(f"\n๐ŸŽฏ Top {len(results)} most relevant results:\n") # Show ranked results with relevance scores for i, result in enumerate(results[:3], 1): print(f"{i}. [{result['relevance_score']:.2f}] {result['head_data']['title']}") print(f" ๐Ÿ”— {result['url'][:60]}...") print("\nโœจ BM25 automatically ranked by relevance!") # ๐ŸŽฌ Run the show! async def main(): print("=" * 60) await discover_and_crawl() print("\n" + "=" * 60 + "\n") await explore_beautifulsoup() print("\n" + "=" * 60 + "\n") await smart_search_with_bm25() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/url_seeder/url_seeder_quick_demo.py", "license": "Apache License 2.0", "lines": 108, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/virtual_scroll_example.py
""" Example of using the virtual scroll feature to capture content from pages with virtualized scrolling (like Twitter, Instagram, or other infinite scroll feeds). This example demonstrates virtual scroll with a local test server serving different types of scrolling behaviors from HTML files in the assets directory. """ import asyncio import os import http.server import socketserver import threading from pathlib import Path from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, VirtualScrollConfig, CacheMode, BrowserConfig # Get the assets directory path ASSETS_DIR = Path(__file__).parent / "assets" class TestServer: """Simple HTTP server to serve our test HTML files""" def __init__(self, port=8080): self.port = port self.httpd = None self.server_thread = None async def start(self): """Start the test server""" Handler = http.server.SimpleHTTPRequestHandler # Save current directory and change to assets directory self.original_cwd = os.getcwd() os.chdir(ASSETS_DIR) # Try to find an available port for _ in range(10): try: self.httpd = socketserver.TCPServer(("", self.port), Handler) break except OSError: self.port += 1 if self.httpd is None: raise RuntimeError("Could not find available port") self.server_thread = threading.Thread(target=self.httpd.serve_forever) self.server_thread.daemon = True self.server_thread.start() # Give server time to start await asyncio.sleep(0.5) print(f"Test server started on http://localhost:{self.port}") return self.port def stop(self): """Stop the test server""" if self.httpd: self.httpd.shutdown() # Restore original directory if hasattr(self, 'original_cwd'): os.chdir(self.original_cwd) async def example_twitter_like_virtual_scroll(): """ Example 1: Twitter-like virtual scroll where content is REPLACED. This is the classic virtual scroll use case - only visible items exist in DOM. """ print("\n" + "="*60) print("EXAMPLE 1: Twitter-like Virtual Scroll") print("="*60) server = TestServer() port = await server.start() try: # Configure virtual scroll for Twitter-like timeline virtual_config = VirtualScrollConfig( container_selector="#timeline", # The scrollable container scroll_count=50, # Scroll up to 50 times to get all content scroll_by="container_height", # Scroll by container's height wait_after_scroll=0.3 # Wait 300ms after each scroll ) config = CrawlerRunConfig( virtual_scroll_config=virtual_config, cache_mode=CacheMode.BYPASS ) # TIP: Set headless=False to watch the scrolling happen! browser_config = BrowserConfig( headless=False, viewport={"width": 1280, "height": 800} ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun( url=f"http://localhost:{port}/virtual_scroll_twitter_like.html", config=config ) # Count tweets captured import re tweets = re.findall(r'data-tweet-id="(\d+)"', result.html) unique_tweets = sorted(set(int(id) for id in tweets)) print(f"\n๐Ÿ“Š Results:") print(f" Total HTML length: {len(result.html):,} characters") print(f" Tweets captured: {len(unique_tweets)} unique tweets") if unique_tweets: print(f" Tweet IDs range: {min(unique_tweets)} to {max(unique_tweets)}") print(f" Expected range: 0 to 499 (500 tweets total)") if len(unique_tweets) == 500: print(f" โœ… SUCCESS! All tweets captured!") else: print(f" โš ๏ธ Captured {len(unique_tweets)}/500 tweets") finally: server.stop() async def example_traditional_append_scroll(): """ Example 2: Traditional infinite scroll where content is APPENDED. No virtual scroll needed - all content stays in DOM. """ print("\n" + "="*60) print("EXAMPLE 2: Traditional Append-Only Scroll") print("="*60) server = TestServer() port = await server.start() try: # Configure virtual scroll virtual_config = VirtualScrollConfig( container_selector=".posts-container", scroll_count=15, # Less scrolls needed since content accumulates scroll_by=500, # Scroll by 500 pixels wait_after_scroll=0.4 ) config = CrawlerRunConfig( virtual_scroll_config=virtual_config, cache_mode=CacheMode.BYPASS ) async with AsyncWebCrawler() as crawler: result = await crawler.arun( url=f"http://localhost:{port}/virtual_scroll_append_only.html", config=config ) # Count posts import re posts = re.findall(r'data-post-id="(\d+)"', result.html) unique_posts = sorted(set(int(id) for id in posts)) print(f"\n๐Ÿ“Š Results:") print(f" Total HTML length: {len(result.html):,} characters") print(f" Posts captured: {len(unique_posts)} unique posts") if unique_posts: print(f" Post IDs range: {min(unique_posts)} to {max(unique_posts)}") print(f" โ„น๏ธ Note: This page appends content, so virtual scroll") print(f" just helps trigger more loads. All content stays in DOM.") finally: server.stop() async def example_instagram_grid(): """ Example 3: Instagram-like grid with virtual scroll. Grid layout where only visible rows are rendered. """ print("\n" + "="*60) print("EXAMPLE 3: Instagram Grid Virtual Scroll") print("="*60) server = TestServer() port = await server.start() try: # Configure for grid layout virtual_config = VirtualScrollConfig( container_selector=".feed-container", # Container with the grid scroll_count=100, # Many scrolls for 999 posts scroll_by="container_height", wait_after_scroll=0.2 # Faster scrolling for grid ) config = CrawlerRunConfig( virtual_scroll_config=virtual_config, cache_mode=CacheMode.BYPASS, screenshot=True # Take a screenshot of the final grid ) # Show browser for this visual example browser_config = BrowserConfig( headless=False, viewport={"width": 1200, "height": 900} ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun( url=f"http://localhost:{port}/virtual_scroll_instagram_grid.html", config=config ) # Count posts in grid import re posts = re.findall(r'data-post-id="(\d+)"', result.html) unique_posts = sorted(set(int(id) for id in posts)) print(f"\n๐Ÿ“Š Results:") print(f" Posts in grid: {len(unique_posts)} unique posts") if unique_posts: print(f" Post IDs range: {min(unique_posts)} to {max(unique_posts)}") print(f" Expected: 0 to 998 (999 posts total)") # Save screenshot if result.screenshot: import base64 with open("instagram_grid_result.png", "wb") as f: f.write(base64.b64decode(result.screenshot)) print(f" ๐Ÿ“ธ Screenshot saved as instagram_grid_result.png") finally: server.stop() async def example_mixed_content(): """ Example 4: News feed with mixed behavior. Featured articles stay (no virtual scroll), regular articles are virtualized. """ print("\n" + "="*60) print("EXAMPLE 4: News Feed with Mixed Behavior") print("="*60) server = TestServer() port = await server.start() try: # Configure virtual scroll virtual_config = VirtualScrollConfig( container_selector="#newsContainer", scroll_count=25, scroll_by="container_height", wait_after_scroll=0.3 ) config = CrawlerRunConfig( virtual_scroll_config=virtual_config, cache_mode=CacheMode.BYPASS ) async with AsyncWebCrawler() as crawler: result = await crawler.arun( url=f"http://localhost:{port}/virtual_scroll_news_feed.html", config=config ) # Count different types of articles import re featured = re.findall(r'data-article-id="featured-\d+"', result.html) regular = re.findall(r'data-article-id="article-(\d+)"', result.html) print(f"\n๐Ÿ“Š Results:") print(f" Featured articles: {len(set(featured))} (always visible)") print(f" Regular articles: {len(set(regular))} unique articles") if regular: regular_ids = sorted(set(int(id) for id in regular)) print(f" Regular article IDs: {min(regular_ids)} to {max(regular_ids)}") print(f" โ„น๏ธ Note: Featured articles stay in DOM, only regular") print(f" articles are replaced during virtual scroll") finally: server.stop() async def compare_with_without_virtual_scroll(): """ Comparison: Show the difference between crawling with and without virtual scroll. """ print("\n" + "="*60) print("COMPARISON: With vs Without Virtual Scroll") print("="*60) server = TestServer() port = await server.start() try: url = f"http://localhost:{port}/virtual_scroll_twitter_like.html" # First, crawl WITHOUT virtual scroll print("\n1๏ธโƒฃ Crawling WITHOUT virtual scroll...") async with AsyncWebCrawler() as crawler: config_normal = CrawlerRunConfig(cache_mode=CacheMode.BYPASS) result_normal = await crawler.arun(url=url, config=config_normal) # Count items import re tweets_normal = len(set(re.findall(r'data-tweet-id="(\d+)"', result_normal.html))) # Then, crawl WITH virtual scroll print("2๏ธโƒฃ Crawling WITH virtual scroll...") virtual_config = VirtualScrollConfig( container_selector="#timeline", scroll_count=50, scroll_by="container_height", wait_after_scroll=0.2 ) config_virtual = CrawlerRunConfig( virtual_scroll_config=virtual_config, cache_mode=CacheMode.BYPASS ) async with AsyncWebCrawler() as crawler: result_virtual = await crawler.arun(url=url, config=config_virtual) # Count items tweets_virtual = len(set(re.findall(r'data-tweet-id="(\d+)"', result_virtual.html))) # Compare results print(f"\n๐Ÿ“Š Comparison Results:") print(f" Without virtual scroll: {tweets_normal} tweets (only initial visible)") print(f" With virtual scroll: {tweets_virtual} tweets (all content captured)") print(f" Improvement: {tweets_virtual / tweets_normal if tweets_normal > 0 else 'N/A':.1f}x more content!") print(f"\n HTML size without: {len(result_normal.html):,} characters") print(f" HTML size with: {len(result_virtual.html):,} characters") finally: server.stop() if __name__ == "__main__": print(""" โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ Virtual Scroll Examples for Crawl4AI โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• These examples demonstrate different virtual scroll scenarios: 1. Twitter-like (content replaced) - Classic virtual scroll 2. Traditional append - Content accumulates 3. Instagram grid - Visual grid layout 4. Mixed behavior - Some content stays, some virtualizes Starting examples... """) # Run all examples asyncio.run(example_twitter_like_virtual_scroll()) asyncio.run(example_traditional_append_scroll()) asyncio.run(example_instagram_grid()) asyncio.run(example_mixed_content()) asyncio.run(compare_with_without_virtual_scroll()) print("\nโœ… All examples completed!") print("\nTIP: Set headless=False in BrowserConfig to watch the scrolling in action!")
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/virtual_scroll_example.py", "license": "Apache License 2.0", "lines": 293, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex