"""Service for extracting metadata from external URLs.""" from typing import Any, Dict, Optional import httpx from bs4 import BeautifulSoup async def extract_url_metadata(url: str) -> Dict[str, Any]: """Extracts basic metadata (title, description) from a URL. Used to provide context for Magic Auto-fill and AI-assisted submission. Args: url: The URL to extract metadata from. Returns: A dictionary containing title, description, and url. """ try: async with httpx.AsyncClient(timeout=10.0, follow_redirects=True) as client: headers = { "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") } response = await client.get(url, headers=headers) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") # Extract Title title = soup.title.string.strip() if soup.title else None # Extract Description (multiple common patterns) description = None desc_meta = ( soup.find("meta", property="og:description") or soup.find("meta", attrs={"name": "description"}) or soup.find("meta", property="twitter:description")) if desc_meta: description = desc_meta.get("content", "").strip() # Fallback if title is missing if not title: og_title = soup.find("meta", property="og:title") if og_title: title = og_title.get("content", "").strip() return {"title": title, "description": description, "url": url} except Exception as e: print(f"Extraction failed for {url}: {e}") return {"title": None, "description": None, "url": url, "error": str(e)}