File size: 5,194 Bytes
5655a95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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()