File size: 1,769 Bytes
46efd9c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | """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)}
|