File size: 6,633 Bytes
518406c
 
 
 
 
 
 
1019e6a
518406c
f74584d
518406c
f74584d
518406c
1019e6a
518406c
 
1019e6a
 
 
 
 
 
 
 
518406c
 
 
 
 
 
 
 
1019e6a
518406c
 
1019e6a
518406c
 
 
 
1019e6a
518406c
 
 
 
1019e6a
518406c
 
1019e6a
518406c
 
 
 
1019e6a
518406c
 
 
 
 
 
 
 
 
 
 
 
1019e6a
518406c
1019e6a
 
518406c
 
 
 
 
 
1019e6a
518406c
1019e6a
 
518406c
1019e6a
 
 
 
 
518406c
1019e6a
518406c
 
 
 
1019e6a
518406c
 
1019e6a
518406c
 
 
 
 
1019e6a
 
 
 
518406c
 
1019e6a
 
 
518406c
 
 
 
1019e6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518406c
1019e6a
 
 
 
518406c
1019e6a
 
518406c
 
1019e6a
 
 
 
518406c
1019e6a
 
518406c
1019e6a
 
518406c
1019e6a
 
 
518406c
 
 
 
 
 
c5f38d7
518406c
 
1019e6a
 
 
 
46bfd69
1019e6a
518406c
1019e6a
 
46bfd69
1019e6a
 
46bfd69
 
c5f38d7
 
1019e6a
 
 
46bfd69
 
1019e6a
 
 
46bfd69
1019e6a
 
46bfd69
 
 
 
 
 
1019e6a
 
 
 
 
 
518406c
1019e6a
 
 
 
 
518406c
1019e6a
 
 
 
 
 
 
 
 
 
518406c
 
 
 
c5f38d7
518406c
1019e6a
518406c
46bfd69
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, urljoin
from markdownify import markdownify as md
import tempfile
import zipfile
import re
from typing import Tuple
import os
import gradio as gr
from collections import deque

# ===========================================================
# 🌐 WEBSITE CRAWLER
# ===========================================================

def crawl_site_for_links(start_url: str, max_pages: int = 50, max_depth: int = 2):
    """
    Recursively crawl a website and collect:
    β€’ Internal HTML pages
    β€’ PDF files
    
    We stay inside the same domain for safety.
    """

    visited = set()
    html_links = set()
    pdf_links = set()

    parsed_base = urlparse(start_url)
    domain = parsed_base.netloc

    queue = deque([(start_url, 0)])
    session = requests.Session()
    session.headers.update({
        "User-Agent": "Mozilla/5.0"
    })

    while queue and len(visited) < max_pages:
        current_url, depth = queue.popleft()

        if current_url in visited or depth > max_depth:
            continue

        visited.add(current_url)

        try:
            response = session.get(current_url, timeout=10)

            if "text/html" not in response.headers.get("Content-Type", ""):
                continue

            soup = BeautifulSoup(response.content, "html.parser")

            for a in soup.find_all("a", href=True):
                href = a["href"]
                full_url = urljoin(current_url, href)
                parsed = urlparse(full_url)

                if parsed.netloc != domain:
                    continue

                if full_url.lower().endswith(".pdf"):
                    pdf_links.add(full_url)
                elif not href.startswith(("#", "javascript:", "mailto:", "tel:")):
                    html_links.add(full_url)
                    if full_url not in visited:
                        queue.append((full_url, depth + 1))

        except Exception:
            continue

    return html_links, pdf_links


# ===========================================================
# πŸ“¦ EXTRACTION ENGINE
# ===========================================================

def extract_all_content_as_zip(url: str, max_links: int, max_depth: int) -> Tuple[str, str]:
    """
    Main function:
    β€’ Crawls the site
    β€’ Converts pages to Markdown
    β€’ Downloads PDFs
    β€’ Packs everything into a ZIP file
    """

    try:
        if not url.startswith(("http://", "https://")):
            url = "https://" + url

        html_links, pdf_links = crawl_site_for_links(url, max_links, max_depth)

        if not html_links and not pdf_links:
            return "❌ No internal pages or PDFs found.", None

        with tempfile.NamedTemporaryFile(delete=False, suffix=".zip") as temp_zip:
            zip_path = temp_zip.name

        session = requests.Session()
        session.headers.update({"User-Agent": "Mozilla/5.0"})

        html_ok = 0
        pdf_ok = 0

        with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zip_file:

            # ---- HTML β†’ Markdown ----
            for i, link_url in enumerate(html_links, 1):
                try:
                    resp = session.get(link_url, timeout=10)
                    soup = BeautifulSoup(resp.content, "html.parser")

                    for tag in soup(["script","style","nav","footer","header","aside"]):
                        tag.decompose()

                    main_content = (
                        soup.find("main")
                        or soup.find("article")
                        or soup.find("body")
                    )

                    markdown_text = md(str(main_content))
                    title = soup.find("title")
                    if title:
                        markdown_text = f"# {title.text.strip()}\n\n{markdown_text}"

                    filename = f"page_{i}.md"
                    zip_file.writestr(filename, markdown_text)
                    html_ok += 1

                except Exception:
                    pass

            # ---- PDFs ----
            for j, pdf_url in enumerate(pdf_links, 1):
                try:
                    resp = session.get(pdf_url, timeout=20)
                    zip_file.writestr(f"pdfs/document_{j}.pdf", resp.content)
                    pdf_ok += 1
                except Exception:
                    pass

        message = f"""
βœ… Extraction completed!

β€’ HTML pages saved as Markdown: {html_ok}
β€’ PDFs downloaded: {pdf_ok}

You can now download the ZIP file below.
"""
        return message, zip_path

    except Exception as e:
        return f"❌ Error: {str(e)}", None


# ===========================================================
# 🎨 GRADIO WEB APP (GRADIO 6 SAFE)
# ===========================================================

def run_extraction(url, max_links, depth):
    return extract_all_content_as_zip(url, int(max_links), int(depth))


with gr.Blocks(title="Website Content Extractor") as app:

    gr.Markdown("""
# 🌍 Website Content & PDF Extractor

Download the **text and PDFs from a website** and package everything into a ZIP file.
""")

    gr.Markdown("---")

    # HOW TO USE SECTION (replaces Box)
    with gr.Group():
        gr.Markdown("## 🧭 How to use")

        gr.Markdown("""
1️⃣ Enter a website homepage  
2️⃣ Choose how deep to crawl  
3️⃣ Click **Start Extraction**  
4️⃣ Download your ZIP file  

⚠️ Large sites may take several minutes.
""")

    gr.Markdown("---")

    url_input = gr.Textbox(
        label="Website URL",
        placeholder="https://example.com"
    )

    with gr.Row():
        max_links_input = gr.Slider(
            10, 200, value=50, step=10,
            label="Maximum pages to scan",
            info="Higher = more content but slower"
        )

        depth_input = gr.Slider(
            1, 3, value=2, step=1,
            label="Crawl depth",
            info="How many clicks away from homepage"
        )

    run_btn = gr.Button("πŸš€ Start Extraction", variant="primary")

    status_output = gr.Textbox(label="Status")
    file_output = gr.File(label="Download ZIP")

    run_btn.click(
        fn=run_extraction,
        inputs=[url_input, max_links_input, depth_input],
        outputs=[status_output, file_output]
    )


# ===========================================================
# πŸš€ ENTRY POINT
# ===========================================================

if __name__ == "__main__":
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        theme=gr.themes.Soft()
    )