thohan88 commited on
Commit
69c47d3
·
1 Parent(s): 7a3e326

Add simple scraper

Browse files
Files changed (4) hide show
  1. app.py +16 -3
  2. requirements.txt +7 -1
  3. tools/scraper.py +469 -0
  4. tools/worker.py +425 -0
app.py CHANGED
@@ -1,16 +1,29 @@
1
  from pathlib import Path
2
  from tools.pdf2svg import mod_pdf2svg_ui, mod_pdf2svg_server
 
3
  from shiny import ui, App
4
 
 
 
 
 
5
  app_dir = Path(__file__).parent
6
- www_dir = app_dir / "www"
7
- www_dir.mkdir(exist_ok=True)
 
 
 
 
 
8
 
9
  app_ui = ui.page_navbar(
10
- ui.nav_panel("PDF2SVG", mod_pdf2svg_ui("pdf2svg"))
 
 
11
  )
12
 
13
  def server(input, output, session):
 
14
  mod_pdf2svg_server("pdf2svg", www_dir)
15
 
16
  app = App(app_ui, server, static_assets=www_dir)
 
1
  from pathlib import Path
2
  from tools.pdf2svg import mod_pdf2svg_ui, mod_pdf2svg_server
3
+ from tools.scraper import mod_scraper_ui, mod_scraper_server
4
  from shiny import ui, App
5
 
6
+ import tempfile
7
+ import shutil
8
+ import atexit
9
+
10
  app_dir = Path(__file__).parent
11
+ www_dir = Path(tempfile.mkdtemp(prefix="scraper_www_"))
12
+
13
+ def cleanup_www():
14
+ if www_dir.exists():
15
+ shutil.rmtree(www_dir, ignore_errors=True)
16
+
17
+ atexit.register(cleanup_www)
18
 
19
  app_ui = ui.page_navbar(
20
+ ui.nav_panel("Scraper", mod_scraper_ui("scraper")),
21
+ ui.nav_panel("PDF2SVG", mod_pdf2svg_ui("pdf2svg")),
22
+ title="Tools App"
23
  )
24
 
25
  def server(input, output, session):
26
+ mod_scraper_server("scraper", www_dir)
27
  mod_pdf2svg_server("pdf2svg", www_dir)
28
 
29
  app = App(app_ui, server, static_assets=www_dir)
requirements.txt CHANGED
@@ -1 +1,7 @@
1
- shiny==1.4.0
 
 
 
 
 
 
 
1
+ shiny==1.5.0
2
+ markitdown[all]
3
+ selenium==4.11.2
4
+ requests==2.32.5
5
+ beautifulsoup4==4.14.3
6
+ duckdb==1.4.2
7
+ cloudscraper==1.2.71
tools/scraper.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ from pathlib import Path
4
+ from urllib.parse import urlparse
5
+ import time
6
+
7
+ from shiny import ui, module, reactive, render
8
+
9
+ @module.ui
10
+ def mod_scraper_ui():
11
+ return ui.page_fluid(
12
+ ui.div(
13
+ {"class": "container my-5"},
14
+ ui.h2("Web Scraper", class_="text-center mb-3 fw-bold"),
15
+ ui.p(
16
+ "Enter a URL to scrape. The process runs in the background.",
17
+ class_="text-center text-muted mb-5",
18
+ ),
19
+ ui.card(
20
+ ui.input_text("url", "Target URL", placeholder="https://example.com", width="100%"),
21
+ ui.layout_columns(
22
+ ui.input_numeric("max_depth", "Max Depth", value=None, min=0),
23
+ ui.input_numeric("max_pages", "Max Pages", value=1000, min=1),
24
+ ui.input_text("link_filter", "Link Filter Regex", placeholder="e.g. /news/"),
25
+ ui.div(
26
+ ui.input_checkbox("cloudscraper", "Use Cloudscraper"),
27
+ ui.input_checkbox("keep_pdfs", "Keep PDFs"),
28
+ ),
29
+ col_widths=[2, 2, 5, 3],
30
+ gap="1rem",
31
+ ),
32
+ ui.div(
33
+ {"class": "d-flex gap-2 justify-content-center mt-3"},
34
+ ui.output_ui("scraper_controls"),
35
+ ),
36
+ ),
37
+ ui.card(
38
+ ui.card_header("Log Output"),
39
+ ui.output_text_verbatim("log_output"),
40
+ class_="mt-3",
41
+ max_height="400px",
42
+ ),
43
+ ui.output_ui("download_ui"),
44
+ )
45
+ )
46
+
47
+ @module.server
48
+ def mod_scraper_server(input, output, session, www_dir):
49
+ session_dir = www_dir / session.id
50
+ session_dir.mkdir(exist_ok=True)
51
+
52
+ # Reactive values
53
+ is_running = reactive.Value(False)
54
+ db_file_path = reactive.Value(None)
55
+ log_file_path = reactive.Value(None)
56
+
57
+ # Process handle
58
+ proc = reactive.Value(None)
59
+ active_process = None
60
+
61
+ # Track last auto-populated filter to allow manual override
62
+ last_auto_filter = reactive.Value(None)
63
+
64
+ def check_log_mtime():
65
+ path = log_file_path.get()
66
+ if not path or not path.exists():
67
+ return None
68
+ return path.stat().st_mtime
69
+
70
+ @reactive.effect
71
+ def sync_filter():
72
+ url = input.url()
73
+ if not url:
74
+ return
75
+
76
+ # try:
77
+ if not url.startswith("http"):
78
+ url = "https://" + url
79
+
80
+ try:
81
+ host = urlparse(url).hostname
82
+ except Exception:
83
+ return
84
+
85
+ # Only auto-populate if we have a valid-looking host (has a dot)
86
+ if host and "." in host:
87
+ with reactive.isolate():
88
+ current_filter = input.link_filter()
89
+
90
+ # Simple logic: only update if currently empty
91
+ if not current_filter:
92
+ ui.update_text("link_filter", value=host, session=session)
93
+ # except Exception as e:
94
+ # print(f"DEBUG: sync_filter error: {e}", flush=True)
95
+
96
+ @reactive.effect
97
+ def update_filter():
98
+ path = session_dir / "filter.txt"
99
+ regex = input.link_filter()
100
+ if regex:
101
+ with open(path, "w") as f:
102
+ f.write(regex)
103
+ elif path.exists():
104
+ path.unlink()
105
+
106
+ @reactive.poll(check_log_mtime, interval_secs=0.1)
107
+ def log_content():
108
+ path = log_file_path.get()
109
+ if not path or not path.exists():
110
+ return ""
111
+ try:
112
+ with open(path, "r") as f:
113
+ # Read last 100 lines
114
+ lines = f.readlines()
115
+ return "".join(lines[-100:][::-1])
116
+ except Exception:
117
+ return ""
118
+
119
+ @reactive.effect
120
+ @reactive.event(input.start_scraper)
121
+ async def start_scraping():
122
+ if is_running.get():
123
+ ui.notification_show("Scraper is already running.", type="warning")
124
+ return
125
+
126
+ url = input.url()
127
+ if not url:
128
+ ui.notification_show("Please enter a URL.", type="error")
129
+ return
130
+
131
+ # Determine DB path
132
+ try:
133
+ if not url.startswith("http://") and not url.startswith("https://"):
134
+ url = "https://" + url
135
+
136
+ hostname = urlparse(url).hostname
137
+ if not hostname:
138
+ raise ValueError("Invalid URL")
139
+ sanitized_host = hostname.replace(".", "_")
140
+
141
+ # Check for existing DB
142
+ existing_dbs = list(session_dir.glob(f"*_{sanitized_host}.db"))
143
+ if existing_dbs:
144
+ # Use the most recent one
145
+ existing_dbs.sort(key=lambda p: p.stat().st_mtime, reverse=True)
146
+ db_path = existing_dbs[0]
147
+ # Try to find corresponding log
148
+ log_name = db_path.stem + ".log"
149
+ log_path = session_dir / log_name
150
+ if not log_path.exists():
151
+ log_path.touch()
152
+ else:
153
+ timestamp = time.strftime("%Y%m%dT%H%M%S")
154
+ db_name = f"{timestamp}_{sanitized_host}.db"
155
+ db_path = session_dir / db_name
156
+
157
+ # Log file
158
+ log_name = f"{timestamp}_{sanitized_host}.log"
159
+ log_path = session_dir / log_name
160
+ # Create empty log file
161
+ log_path.touch()
162
+
163
+ except Exception:
164
+ ui.notification_show("Invalid URL.", type="error")
165
+ return
166
+
167
+ is_running.set(True)
168
+ db_file_path.set(db_path)
169
+ log_file_path.set(log_path)
170
+
171
+ # Construct command
172
+ # Assuming scraper.py is in the root of the project, which is parent of tools/
173
+ # app.py is in root, so we can assume CWD is root when running app.py
174
+ # Worker is now in the same directory as this file
175
+ scraper_script = Path(__file__).parent / "worker.py"
176
+
177
+ cmd = [sys.executable, "-u", str(scraper_script), url, str(db_path), "--log-file", str(log_path)]
178
+
179
+
180
+ if input.cloudscraper():
181
+ cmd.append("--cloudscraper")
182
+
183
+ if input.max_depth() is not None:
184
+ cmd.extend(["--max-depth", str(input.max_depth())])
185
+
186
+ if input.max_pages() is not None:
187
+ cmd.extend(["--max-reqs", str(input.max_pages())])
188
+
189
+ if input.keep_pdfs():
190
+ cmd.append("--keep-pdfs")
191
+
192
+ try:
193
+ p = await asyncio.create_subprocess_exec(
194
+ *cmd,
195
+ stdout=asyncio.subprocess.PIPE,
196
+ stderr=asyncio.subprocess.PIPE,
197
+ cwd=str(session_dir)
198
+ )
199
+ proc.set(p)
200
+ nonlocal active_process
201
+ active_process = p
202
+
203
+ # Wait for process in background
204
+ asyncio.create_task(wait_for_process(p))
205
+
206
+ except Exception as e:
207
+ is_running.set(False)
208
+ proc.set(None)
209
+ ui.notification_show(f"Error starting scraper: {e}", type="error")
210
+
211
+ async def wait_for_process(p):
212
+ await p.wait()
213
+ async with reactive.lock():
214
+ is_running.set(False)
215
+ proc.set(None)
216
+ nonlocal active_process
217
+ active_process = None
218
+
219
+ if p.returncode == 0:
220
+ ui.notification_show("Scraping finished successfully.", type="message")
221
+ elif p.returncode == -15 or p.returncode == -9:
222
+ # -15 is SIGTERM, -9 is SIGKILL - these are expected when stopping
223
+ pass
224
+ else:
225
+ ui.notification_show(f"Scraper exited with code {p.returncode}", type="warning")
226
+
227
+ @reactive.effect
228
+ @reactive.event(input.stop_scraper)
229
+ async def stop_scraping():
230
+ p = proc.get()
231
+ if p:
232
+ p.terminate()
233
+ try:
234
+ await asyncio.wait_for(p.wait(), timeout=5.0)
235
+ except asyncio.TimeoutError:
236
+ p.kill()
237
+
238
+ is_running.set(False)
239
+ proc.set(None)
240
+ nonlocal active_process
241
+ active_process = None
242
+ ui.notification_show("Scraper stopped.", type="message")
243
+
244
+ @output
245
+ @render.text
246
+ def log_output():
247
+ return log_content()
248
+
249
+ @output
250
+ @render.ui
251
+ def scraper_controls():
252
+ if is_running.get():
253
+ return ui.input_action_button("stop_scraper", "Stop Scraper", class_="btn-danger")
254
+ else:
255
+ # Check if DB exists to show delete button
256
+ db_path = db_file_path.get()
257
+ buttons = [ui.input_action_button("start_scraper", "Start Scraper", class_="btn-primary")]
258
+
259
+ if db_path and db_path.exists():
260
+ buttons.append(
261
+ ui.input_action_button("delete_db", "Delete Database", class_="btn-warning ms-2")
262
+ )
263
+ return ui.div(*buttons)
264
+
265
+ @reactive.Effect
266
+ @reactive.event(input.delete_db)
267
+ def delete_db():
268
+ if is_running.get():
269
+ ui.notification_show("Cannot delete while scraper is running.", type="error")
270
+ return
271
+
272
+ db_path = db_file_path.get()
273
+ log_path = log_file_path.get()
274
+
275
+ try:
276
+ if db_path and db_path.exists():
277
+ db_path.unlink()
278
+ if log_path and log_path.exists():
279
+ log_path.unlink()
280
+
281
+ # Reset state
282
+ db_file_path.set(None)
283
+ log_file_path.set(None)
284
+ ui.notification_show("Database deleted.", type="message")
285
+
286
+ except Exception as e:
287
+ ui.notification_show(f"Error deleting database: {e}", type="error")
288
+
289
+ @output
290
+ @render.ui
291
+ def download_ui():
292
+ path = db_file_path.get()
293
+ running = is_running.get()
294
+ exists = path.exists() if path else False
295
+
296
+ if path and exists and not running:
297
+ return ui.div(
298
+ ui.div(
299
+ ui.input_radio_buttons("export_structure", "Export Structure",
300
+ {"flat": "Flat", "folder": "Folder"},
301
+ selected="flat", inline=True),
302
+ class_="mb-2 text-center"
303
+ ),
304
+ ui.div(
305
+ ui.download_button("download_db", "Download Database", class_="btn-success"),
306
+ ui.download_button("download_md", "Download Markdown", class_="btn-info"),
307
+ class_="d-flex gap-2 justify-content-center"
308
+ ),
309
+ class_="d-flex flex-column align-items-center"
310
+ )
311
+ return None
312
+
313
+ @render.download(filename=lambda: db_file_path.get().name if db_file_path.get() else "data.db")
314
+ def download_db():
315
+ path = db_file_path.get()
316
+ if path and path.exists():
317
+ yield str(path)
318
+
319
+ @render.download(filename=lambda: (db_file_path.get().stem + "_markdown.zip") if db_file_path.get() else "markdown.zip")
320
+ def download_md():
321
+ path = db_file_path.get()
322
+ if not path or not path.exists():
323
+ return None
324
+
325
+ import duckdb
326
+ import zipfile
327
+ import tempfile
328
+ import shutil
329
+ import os
330
+ import hashlib
331
+
332
+ # Create temp dir for zip creation
333
+ with tempfile.TemporaryDirectory() as temp_dir:
334
+ temp_path = Path(temp_dir)
335
+
336
+
337
+ con = duckdb.connect(str(path))
338
+ try:
339
+ # Check if markdown table exists
340
+ try:
341
+ # Check for binary_content column
342
+ has_binary = False
343
+ try:
344
+ con.execute("SELECT binary_content FROM markdown LIMIT 1")
345
+ has_binary = True
346
+ except:
347
+ pass
348
+
349
+ if has_binary:
350
+ rows = con.execute("SELECT url, content, binary_content FROM markdown").fetchall()
351
+ else:
352
+ rows = con.execute("SELECT url, content, NULL as binary_content FROM markdown").fetchall()
353
+ except duckdb.CatalogException as e:
354
+ rows = []
355
+
356
+ structure = input.export_structure()
357
+
358
+ for url, content, binary_content in rows:
359
+ if not content and not binary_content:
360
+ continue
361
+
362
+ parsed = urlparse(url)
363
+
364
+ if structure == "folder":
365
+ # Folder structure logic
366
+ # Create directory structure based on URL path
367
+ rel_path = parsed.path.strip("/")
368
+ if not rel_path:
369
+ rel_path = "index.md"
370
+ elif parsed.path.endswith("/"):
371
+ rel_path = os.path.join(rel_path, "index.md")
372
+ else:
373
+ # Add extension if missing
374
+ if binary_content:
375
+ if not rel_path.lower().endswith(".pdf"):
376
+ rel_path += ".pdf"
377
+ else:
378
+ if not rel_path.endswith(".md"):
379
+ rel_path += ".md"
380
+
381
+ # Combine netloc and path
382
+ full_rel_path = os.path.join(parsed.netloc, rel_path)
383
+
384
+ # Ensure safe path (prevent traversal)
385
+ full_rel_path = full_rel_path.replace("..", "")
386
+
387
+ file_path = temp_path / full_rel_path
388
+ file_path.parent.mkdir(parents=True, exist_ok=True)
389
+
390
+ else:
391
+ # Flat structure logic (default)
392
+ filename = parsed.netloc + parsed.path
393
+ if filename.endswith("/"):
394
+ filename += "index"
395
+
396
+ # Replace unsafe chars
397
+ safe_filename = "".join([c if c.isalnum() or c in "._-" else "_" for c in filename])
398
+
399
+ # Truncate if too long
400
+ if len(safe_filename) > 200:
401
+ # Keep extension if present
402
+ name_part, ext_part = os.path.splitext(safe_filename)
403
+ if not ext_part:
404
+ ext_part = ".pdf" if binary_content else ".md"
405
+
406
+ # Hash the full original URL for uniqueness
407
+ url_hash = hashlib.md5(url.encode()).hexdigest()[:8]
408
+
409
+ # Truncate name part
410
+ max_name_len = 200 - 9 - len(ext_part)
411
+ safe_filename = name_part[:max_name_len] + "_" + url_hash + ext_part
412
+
413
+ if binary_content:
414
+ if not safe_filename.lower().endswith(".pdf"):
415
+ safe_filename += ".pdf"
416
+ else:
417
+ if not safe_filename.endswith(".md"):
418
+ safe_filename += ".md"
419
+
420
+ file_path = temp_path / safe_filename
421
+
422
+ # Write file
423
+ try:
424
+ if binary_content:
425
+ with open(file_path, "wb") as f:
426
+ f.write(binary_content)
427
+ else:
428
+ with open(file_path, "w", encoding="utf-8") as f:
429
+ f.write(f"# Source: {url}\n\n")
430
+ f.write(content)
431
+ except Exception as e:
432
+ print(f"Error writing file {file_path}: {e}", flush=True)
433
+
434
+ finally:
435
+ con.close()
436
+
437
+ # Create zip using zipfile module
438
+ zip_path = path.parent / (path.stem + "_markdown.zip")
439
+
440
+
441
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
442
+ for root, dirs, files in os.walk(temp_path):
443
+ for file in files:
444
+ file_path = Path(root) / file
445
+ arcname = file_path.relative_to(temp_path)
446
+ zipf.write(file_path, arcname)
447
+
448
+
449
+ return str(zip_path)
450
+
451
+ @session.on_ended
452
+ async def on_end():
453
+ # Terminate process if running
454
+ nonlocal active_process
455
+ p = active_process
456
+ if p:
457
+ try:
458
+ p.terminate()
459
+ # Give it a moment to terminate gracefully
460
+ # We can't await too long here as it might block shutdown
461
+ # But we can try to kill if it doesn't die
462
+ p.kill()
463
+ except Exception:
464
+ pass
465
+
466
+ # Cleanup session dir
467
+ if session_dir.exists():
468
+ import shutil
469
+ shutil.rmtree(session_dir, ignore_errors=True)
tools/worker.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import duckdb
3
+ import time
4
+ import re
5
+ from urllib.parse import urlparse, urljoin
6
+ from bs4 import BeautifulSoup
7
+ import os
8
+ import argparse
9
+ import sys
10
+ import re
11
+ from pathlib import Path
12
+ import tempfile
13
+ from markitdown import MarkItDown
14
+ import logging
15
+ import cloudscraper
16
+
17
+ # Suppress noisy PDF warnings
18
+ logging.getLogger("pdfminer").setLevel(logging.ERROR)
19
+ logging.getLogger("pdfplumber").setLevel(logging.ERROR)
20
+ logging.getLogger("pypdf").setLevel(logging.ERROR)
21
+
22
+ def normalize_url(url):
23
+ if not url.startswith("http://") and not url.startswith("https://"):
24
+ url = "https://" + url
25
+
26
+ # Strip fragment
27
+ parsed = urlparse(url)
28
+ url = parsed.scheme + "://" + parsed.netloc + parsed.path
29
+ if parsed.query:
30
+ url += "?" + parsed.query
31
+
32
+ return url.rstrip('/')
33
+
34
+ def get_host(url):
35
+ try:
36
+ url = normalize_url(url)
37
+ return urlparse(url).hostname
38
+ except Exception:
39
+ return None
40
+
41
+ def make_req(url, throttle_rate=2, user_agent=None, cloudscraper_session=None):
42
+ if cloudscraper_session:
43
+ time.sleep(1.0 / throttle_rate)
44
+ try:
45
+ return cloudscraper_session.get(url, timeout=30)
46
+ except Exception as e:
47
+ print(f"Cloudscraper failed for {url}: {e}")
48
+ return None
49
+
50
+ if user_agent is None:
51
+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"
52
+
53
+ headers = {'User-Agent': user_agent}
54
+
55
+ # Simple throttling
56
+ time.sleep(1.0 / throttle_rate)
57
+
58
+ try:
59
+ response = requests.get(url, headers=headers, timeout=10)
60
+ response.raise_for_status()
61
+ return response
62
+ except requests.RequestException as e:
63
+ print(f"Request failed for {url}: {e}")
64
+ return None
65
+
66
+ def get_doc_size(url):
67
+ try:
68
+ response = requests.head(url, timeout=5)
69
+ if 'content-length' in response.headers:
70
+ return int(response.headers['content-length'])
71
+ except Exception:
72
+ pass
73
+ return None
74
+
75
+ def extract_links(html_content, current_url):
76
+ if not html_content:
77
+ return {'web_links': [], 'doc_links': []}
78
+
79
+ soup = BeautifulSoup(html_content, 'html.parser')
80
+ all_links = set()
81
+
82
+ for a in soup.find_all('a', href=True):
83
+ href = a['href']
84
+ try:
85
+ absolute_url = urljoin(current_url, href)
86
+ all_links.add(normalize_url(absolute_url))
87
+ except Exception:
88
+ continue
89
+
90
+ doc_pattern = re.compile(r'\.(pdf|pptx?|docx?)(\?|$)', re.IGNORECASE)
91
+
92
+ doc_links = [l for l in all_links if doc_pattern.search(l)]
93
+ web_links = [l for l in all_links if not doc_pattern.search(l)]
94
+
95
+ return {'web_links': web_links, 'doc_links': doc_links}
96
+
97
+ def init_db(con, page_table="pages", doc_table="documents", queue_table="queue"):
98
+ con.execute(f"""
99
+ CREATE TABLE IF NOT EXISTS {page_table} (
100
+ insert_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
101
+ url VARCHAR PRIMARY KEY,
102
+ html TEXT
103
+ );
104
+ """)
105
+ con.execute(f"""
106
+ CREATE TABLE IF NOT EXISTS {doc_table} (
107
+ insert_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
108
+ url VARCHAR PRIMARY KEY,
109
+ source_page VARCHAR,
110
+ size BIGINT
111
+ );
112
+ """)
113
+ con.execute(f"""
114
+ CREATE TABLE IF NOT EXISTS {queue_table} (
115
+ insert_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
116
+ url VARCHAR PRIMARY KEY,
117
+ depth INTEGER DEFAULT 0
118
+ );
119
+ """)
120
+ con.execute(f"""
121
+ CREATE TABLE IF NOT EXISTS markdown (
122
+ insert_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
123
+ url VARCHAR PRIMARY KEY,
124
+ content TEXT,
125
+ source_type VARCHAR,
126
+ binary_content BLOB
127
+ );
128
+ """)
129
+
130
+ # Migration: Check if binary_content column exists, if not add it
131
+ try:
132
+ con.execute("SELECT binary_content FROM markdown LIMIT 1")
133
+ except duckdb.BinderException:
134
+ print("Migrating markdown table: adding binary_content column")
135
+ con.execute("ALTER TABLE markdown ADD COLUMN binary_content BLOB")
136
+
137
+ # Create unified view
138
+ con.execute("""
139
+ CREATE OR REPLACE VIEW full_content AS
140
+ SELECT
141
+ m.url,
142
+ m.content,
143
+ m.source_type,
144
+ m.insert_time,
145
+ COALESCE(p.insert_time, d.insert_time) as original_insert_time,
146
+ d.source_page as parent_url
147
+ FROM markdown m
148
+ LEFT JOIN pages p ON m.url = p.url
149
+ LEFT JOIN documents d ON m.url = d.url
150
+ """)
151
+
152
+ # Migration: Check if depth column exists in queue, if not add it
153
+ try:
154
+ con.execute(f"SELECT depth FROM {queue_table} LIMIT 1")
155
+ except duckdb.BinderException:
156
+ print("Migrating queue table: adding depth column")
157
+ con.execute(f"ALTER TABLE {queue_table} ADD COLUMN depth INTEGER DEFAULT 0")
158
+
159
+ def store_documents(con, doc_links, source_url, doc_table="documents"):
160
+ if not doc_links:
161
+ return
162
+
163
+ # Check existing
164
+ placeholders = ','.join(['?'] * len(doc_links))
165
+ existing = con.execute(f"SELECT url FROM {doc_table} WHERE url IN ({placeholders})", doc_links).fetchall()
166
+ existing_urls = {r[0] for r in existing}
167
+
168
+ new_links = [l for l in doc_links if l not in existing_urls]
169
+
170
+ if not new_links:
171
+ return
172
+
173
+ for link in new_links:
174
+ size = get_doc_size(link)
175
+ con.execute(f"INSERT INTO {doc_table} (url, source_page, size) VALUES (?, ?, ?)",
176
+ (link, source_url, size))
177
+
178
+ def scrape(start_url, db_path, throttle_rate=2, max_reqs=100, max_depth=None, keep_pdfs=False, use_cloudscraper=False):
179
+ start_url = normalize_url(start_url)
180
+ base_host = get_host(start_url)
181
+
182
+ con = duckdb.connect(db_path)
183
+ init_db(con)
184
+
185
+ # Initialize queue if empty and no pages scraped
186
+ page_count = con.execute("SELECT COUNT(*) FROM pages").fetchone()[0]
187
+ queue_count = con.execute("SELECT COUNT(*) FROM queue").fetchone()[0]
188
+
189
+ if page_count == 0 and queue_count == 0:
190
+ con.execute("INSERT INTO queue (url, depth) VALUES (?, ?)", (start_url, 0))
191
+
192
+ print(f"Starting scraper for: {start_url}", flush=True)
193
+ if max_depth is not None:
194
+ print(f"Max depth: {max_depth}", flush=True)
195
+ print(f"Keep PDFs: {keep_pdfs}", flush=True)
196
+ if use_cloudscraper:
197
+ print("Using Cloudscraper", flush=True)
198
+
199
+ cloudscraper_session = None
200
+ if use_cloudscraper:
201
+ try:
202
+ cloudscraper_session = cloudscraper.create_scraper()
203
+ except Exception as e:
204
+ print(f"Failed to create Cloudscraper session: {e}", flush=True)
205
+
206
+ try:
207
+ reqs_made = 0
208
+ while reqs_made < max_reqs:
209
+ # Dynamic regex filter
210
+ filter_regex = None
211
+ filter_path = Path("filter.txt")
212
+ if filter_path.exists():
213
+ try:
214
+ with open(filter_path, "r") as f:
215
+ pattern = f.read().strip()
216
+ if pattern:
217
+ filter_regex = re.compile(pattern)
218
+ except Exception as e:
219
+ print(f"Error reading filter: {e}", file=sys.stderr)
220
+
221
+ # Get next URL
222
+ # Order by depth to do BFS
223
+ next_url_row = con.execute("SELECT url, depth FROM queue ORDER BY depth ASC LIMIT 1").fetchone()
224
+ if not next_url_row:
225
+ print("Queue is empty. Exiting.", flush=True)
226
+ break
227
+
228
+ current_url, current_depth = next_url_row
229
+ con.execute("DELETE FROM queue WHERE url = ?", (current_url,)) # Remove from queue
230
+
231
+ # Check against regex (skip if doesn't match)
232
+ # Exception: always allow start_url to ensure we start
233
+ if filter_regex and current_url != start_url and not filter_regex.search(current_url):
234
+ # print(f"Skipping {current_url} (regex mismatch)", flush=True)
235
+ continue
236
+
237
+ # Check if already scraped (double check)
238
+ if con.execute("SELECT 1 FROM pages WHERE url = ?", (current_url,)).fetchone():
239
+ continue
240
+
241
+ resp = make_req(current_url, throttle_rate, cloudscraper_session=cloudscraper_session)
242
+ reqs_made += 1
243
+
244
+ if not resp:
245
+ continue
246
+
247
+ # Wrapper response might not have headers like requests
248
+ content_type = resp.headers.get('Content-Type', '')
249
+ if 'text/html' not in content_type:
250
+ pass
251
+
252
+ html = resp.text
253
+
254
+ # Store page
255
+ con.execute("INSERT OR IGNORE INTO pages (url, html) VALUES (?, ?)", (current_url, html))
256
+
257
+ # Convert page to markdown
258
+ try:
259
+ md = MarkItDown()
260
+ with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode='w', encoding='utf-8') as tmp:
261
+ tmp.write(html)
262
+ tmp_path = tmp.name
263
+
264
+ result = md.convert(tmp_path)
265
+ os.remove(tmp_path)
266
+
267
+ if result and result.text_content:
268
+ con.execute("INSERT OR REPLACE INTO markdown (url, content, source_type) VALUES (?, ?, ?)",
269
+ (current_url, result.text_content, 'page'))
270
+ except Exception as e:
271
+ print(f"Failed to convert page to markdown: {e}", flush=True)
272
+
273
+ # Extract and store links
274
+ links_dict = extract_links(html, current_url)
275
+ store_documents(con, links_dict['doc_links'], current_url)
276
+
277
+ # Filter and queue web links
278
+ scraped_urls = set(r[0] for r in con.execute("SELECT url FROM pages").fetchall())
279
+ queued_urls = set(r[0] for r in con.execute("SELECT url FROM queue").fetchall())
280
+
281
+ web_links = links_dict['web_links']
282
+ new_links = []
283
+
284
+ for link in web_links:
285
+ # Host filter
286
+ if get_host(link) != base_host:
287
+ continue
288
+
289
+ # Duplicate filter
290
+ if link in scraped_urls or link in queued_urls:
291
+ continue
292
+
293
+ # Regex filter
294
+ if filter_regex and not filter_regex.search(link):
295
+ continue
296
+
297
+ new_links.append(link)
298
+
299
+ # Add to queue
300
+ if new_links:
301
+ if max_depth is None or current_depth < max_depth:
302
+ next_depth = current_depth + 1
303
+ con.executemany("INSERT INTO queue (url, depth) VALUES (?, ?)", [(l, next_depth) for l in new_links])
304
+
305
+ queue_len = con.execute("SELECT COUNT(*) FROM queue").fetchone()[0]
306
+ print(f"Scraped: {len(scraped_urls)} | Queue: {queue_len} | Depth: {current_depth} | New: {len(new_links) if (max_depth is None or current_depth < max_depth) else 0} | {current_url}", flush=True)
307
+
308
+ # Convert documents to markdown or keep as PDF
309
+ for doc_url in links_dict['doc_links']:
310
+ # Check if already converted/stored
311
+ if con.execute("SELECT 1 FROM markdown WHERE url = ?", (doc_url,)).fetchone():
312
+ continue
313
+ try:
314
+ print(f"Processing document: {doc_url}", flush=True)
315
+
316
+ # Always try to download first (to handle retries)
317
+ doc_resp = None
318
+ try:
319
+ # Try normal download first
320
+ doc_resp = make_req(doc_url, throttle_rate, cloudscraper_session=cloudscraper_session)
321
+
322
+ # Validate response
323
+ is_valid_pdf = False
324
+ if doc_resp and doc_resp.status_code == 200:
325
+ content_type = doc_resp.headers.get('Content-Type', '').lower()
326
+ if 'application/pdf' in content_type:
327
+ is_valid_pdf = True
328
+ elif len(doc_resp.content) > 1000 and b'%PDF-' in doc_resp.content[:1024]:
329
+ # Fallback: check magic bytes if header is missing/wrong but size is reasonable
330
+ is_valid_pdf = True
331
+ else:
332
+ # print(f"Invalid PDF content: Type={content_type}, Size={len(doc_resp.content)}", flush=True)
333
+ if len(doc_resp.content) < 500:
334
+ # print(f"Small content preview: {doc_resp.content[:200]}", flush=True)
335
+ pass
336
+
337
+ # If failed or not PDF content, try with cloudscraper if enabled and not already used
338
+ if not is_valid_pdf and use_cloudscraper and not cloudscraper_session:
339
+ # This assumes if we passed cloudscraper_session it was already used.
340
+ # But wait, we pass it to make_req. If it's active, we used it.
341
+ # If we failed WITH cloudscraper, there's not much more we can do easily without a browser.
342
+ # If we failed WITHOUT cloudscraper (maybe user didn't check it but we want to try?)
343
+ # No, we stick to user preference.
344
+
345
+ # However, previous logic had ephemeral Flaresolverr.
346
+ # If we are using Cloudscraper, 'make_req' used it.
347
+ # If we are NOT using Cloudscraper, we can't spin up an "ephemeral" one easily because it's just a library call,
348
+ # but we respected the user's flag.
349
+ # If the user wants to bypass, they should check the box.
350
+ pass
351
+
352
+ except Exception as e:
353
+ print(f"Download failed: {e}", flush=True)
354
+
355
+ if not doc_resp or doc_resp.status_code != 200 or not is_valid_pdf:
356
+ print(f"Could not download document {doc_url}", flush=True)
357
+ continue
358
+
359
+ # If keep_pdfs is True, store raw content
360
+ if keep_pdfs:
361
+ con.execute("INSERT OR REPLACE INTO markdown (url, content, source_type, binary_content) VALUES (?, ?, ?, ?)",
362
+ (doc_url, None, 'document', doc_resp.content))
363
+ print(f"Stored raw PDF: {doc_url}", flush=True)
364
+ continue # Skip markdown conversion if kept as PDF
365
+
366
+ # Convert to markdown using the downloaded content
367
+ # MarkItDown needs a file path
368
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False, mode='wb') as tmp:
369
+ tmp.write(doc_resp.content)
370
+ tmp_path = tmp.name
371
+
372
+ try:
373
+ # print(f"Attempting conversion of {tmp_path} size={os.path.getsize(tmp_path)}", flush=True)
374
+ result = md.convert(tmp_path)
375
+ if result:
376
+ if result.text_content:
377
+ con.execute("INSERT OR REPLACE INTO markdown (url, content, source_type) VALUES (?, ?, ?)",
378
+ (doc_url, result.text_content, 'document'))
379
+ print(f"Converted to Markdown: {doc_url}", flush=True)
380
+ else:
381
+ print(f"Warning: No text content extracted from {doc_url}", flush=True)
382
+ else:
383
+ print(f"Warning: Conversion returned None for {doc_url}", flush=True)
384
+ finally:
385
+ if os.path.exists(tmp_path):
386
+ os.remove(tmp_path)
387
+
388
+ except Exception as e:
389
+ print(f"Failed to convert document {doc_url}: {e}", flush=True)
390
+
391
+ finally:
392
+ con.close()
393
+ print("Scraping finished.", flush=True)
394
+
395
+ if __name__ == "__main__":
396
+ parser = argparse.ArgumentParser(description="Web scraper with optional Cloudscraper support")
397
+ parser.add_argument("url", help="Target URL")
398
+ parser.add_argument("db_path", nargs="?", help="Path to DuckDB database (optional, defaults to hostname.duckdb)")
399
+ parser.add_argument("--cloudscraper", action="store_true", help="Use Cloudscraper for requests")
400
+ parser.add_argument("--throttle", type=float, default=2.0, help="Throttle rate (requests per second)")
401
+ parser.add_argument("--max-reqs", type=int, default=100, help="Maximum number of requests")
402
+ parser.add_argument("--max-depth", type=int, default=None, help="Maximum depth to scrape (default: unlimited)")
403
+ parser.add_argument("--keep-pdfs", action="store_true", help="Keep PDFs in original format")
404
+ parser.add_argument("--log-file", help="Path to log file")
405
+
406
+ args = parser.parse_args()
407
+
408
+ # Redirect stdout to log file if provided
409
+ if args.log_file:
410
+ sys.stdout = open(args.log_file, "a", buffering=1)
411
+ sys.stderr = sys.stdout
412
+
413
+ db_path = args.db_path
414
+ if not db_path:
415
+ host = get_host(args.url)
416
+ if host:
417
+ timestamp = time.strftime("%Y%m%dT%H%M%S")
418
+ sanitized_host = host.replace(".", "_")
419
+ db_path = f"{timestamp}_{sanitized_host}.db"
420
+ print(f"No database path provided. Using default: {db_path}")
421
+ else:
422
+ print("Error: Could not derive database name from URL. Please specify db_path.")
423
+ sys.exit(1)
424
+
425
+ scrape(args.url, db_path, throttle_rate=args.throttle, max_reqs=args.max_reqs, max_depth=args.max_depth, keep_pdfs=args.keep_pdfs, use_cloudscraper=args.cloudscraper)