import asyncio import aiohttp import gzip import xml.etree.ElementTree as ET from bs4 import BeautifulSoup from tqdm import tqdm import csv import tempfile import os import nest_asyncio import gradio as gr nest_asyncio.apply() # ---------------------------- # helpers (your original code) # ---------------------------- def is_gzip(data: bytes): return len(data) >= 2 and data[:2] == b"\x1f\x8b" def parse_sitemap(xml_bytes): root = ET.fromstring(xml_bytes) urls = [e.text.strip() for e in root.findall(".//{*}loc") if e.text] sitemap_urls = [e.text.strip() for e in root.findall(".//{*}sitemap/{*}loc") if e.text] return urls, sitemap_urls def extract_title_and_description(html): soup = BeautifulSoup(html, "lxml") title = "" if soup.title and soup.title.string: title = soup.title.string.strip() description = "" tag = soup.find("meta", attrs={"name": "description"}) if tag and tag.get("content"): description = tag["content"].strip() else: tag = soup.find("meta", attrs={"property": "og:description"}) if tag and tag.get("content"): description = tag["content"].strip() return title, description async def fetch_bytes(session, url): async with session.get(url) as r: r.raise_for_status() return await r.read() async def fetch_html(session, url): async with session.get(url) as r: r.raise_for_status() return await r.text(errors="ignore") async def collect_all_urls(session, sitemap_url): queue = [sitemap_url] visited = set() all_urls = [] while queue: current = queue.pop(0) if current in visited: continue visited.add(current) try: data = await fetch_bytes(session, current) except Exception as e: print("Failed sitemap:", current, e) continue if is_gzip(data): try: data = gzip.decompress(data) except Exception: pass try: urls, sitemap_urls = parse_sitemap(data) except Exception as e: print("Bad sitemap XML:", current, e) continue all_urls.extend(urls) queue.extend(sitemap_urls) return list(dict.fromkeys(all_urls)) async def worker(semaphore, session, url): async with semaphore: try: html = await fetch_html(session, url) title, desc = extract_title_and_description(html) return {"url": url, "title": title, "description": desc, "error": ""} except Exception as e: return {"url": url, "title": "", "description": "", "error": str(e)} async def run_bulk(sitemap_url, concurrency=15, max_urls=None): headers = {"User-Agent": "hf-sitemap-extractor/1.0"} timeout = aiohttp.ClientTimeout(total=40) async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session: urls = await collect_all_urls(session, sitemap_url) urls = [u for u in urls if "/wp-content/" not in u.lower()] if max_urls and max_urls > 0: urls = urls[:max_urls] semaphore = asyncio.Semaphore(concurrency) tasks = [worker(semaphore, session, url) for url in urls] results = [] for coro in asyncio.as_completed(tasks): result = await coro results.append(result) return results # ---------------------------- # Gradio wrapper # ---------------------------- def extract_sitemap(sitemap_url, max_urls): if not sitemap_url.strip(): return "Please enter a sitemap URL.", None try: max_urls = int(max_urls) if max_urls and int(max_urls) > 0 else None results = asyncio.get_event_loop().run_until_complete( run_bulk(sitemap_url=sitemap_url.strip(), concurrency=15, max_urls=max_urls) ) # Save to a temp CSV file tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", newline="", encoding="utf-8") writer = csv.DictWriter(tmp, fieldnames=["url", "title", "description", "error"]) writer.writeheader() writer.writerows(results) tmp.close() summary = f"βœ… Done! Extracted {len(results)} URLs." return summary, tmp.name except Exception as e: return f"❌ Error: {str(e)}", None # ---------------------------- # Gradio UI # ---------------------------- with gr.Blocks(title="Sitemap Title & Description Extractor") as app: gr.Markdown("## πŸ—ΊοΈ Sitemap Title & Description Extractor") gr.Markdown("Enter your sitemap URL and get a downloadable CSV with titles and meta descriptions.") with gr.Row(): sitemap_input = gr.Textbox(label="Sitemap URL", placeholder="https://example.com/sitemap.xml") max_urls_input = gr.Number(label="Max URLs (0 = all)", value=0) run_btn = gr.Button("Extract", variant="primary") status_output = gr.Textbox(label="Status") file_output = gr.File(label="Download CSV") run_btn.click( fn=extract_sitemap, inputs=[sitemap_input, max_urls_input], outputs=[status_output, file_output] ) app.launch()