Add Scribd PDF Downloader under Scribd/

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Michael-A-SloanandCursor committed 2026-05-15 10:44:57 -04:00
commit 5d2933ea95
28 files changed
+2159

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
__pycache__/
*.py[cod]
.venv/
venv/
.env
session.json
temp_capture/
temp_preview/
.chrome-runtime-profile/
*.pdf
history.json
.pytest_cache/
build/pyinstaller/
dist/
*.spec.bak
.idea/
.vscode/
+224
View File
@@ -0,0 +1,224 @@
# AIDNA — App Installation, Distribution, Notes & Architecture
This document explains how **Scribd PDF Downloader** is put together, how to install it, and how to ship it to other computers.
---
## A — App (what you get)
Three ways to run the same core downloader:
| Mode | Entry point | Best for |
|------|-------------|----------|
| **GUI** | `Start Scribd Downloader.bat` or `Scribd PDF Downloader.exe` | Daily use, preview before download |
| **CLI** | `main.py download <url>` | Automation, scripts, ebooks |
| **Frozen** | Built `.exe` / `.app` in `dist/` | Sharing with people who don’t have Python |
The GUI and CLI both use the `scribd_downloader` package. PDFs and `session.json` are saved in the **current working directory** (next to the `.exe` when using a built app).
---
## I — Installation
### Option 1: Pre-built Windows app (recommended for end users)
1. Build once on your PC (see [BUILD.md](BUILD.md)) or copy the `dist\Scribd PDF Downloader` folder from someone who built it.
2. Copy the **entire folder** to the target PC (do not move only the `.exe` — Chromium lives in `_internal`).
3. Run `Scribd PDF Downloader.exe`.
### Option 2: Run from source (developers)
Full steps are in [INSTALL.md](INSTALL.md). Short version:
```powershell
cd "Scribe PDF Downloader"
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
playwright install chromium
```
Then:
```powershell
.\.venv\Scripts\python.exe gui.py
# or
.\Start Scribd Downloader.bat
```
### Option 3: macOS app
Build **on a Mac** only:
```bash
./build/macos/build.sh
open "dist/Scribd PDF Downloader.app"
```
---
## D — Distribution (shipping to others)
### Windows
| Artifact | Location | Share how |
|----------|----------|-----------|
| Portable app | `dist\Scribd PDF Downloader\` | Zip the whole folder (~800 MB with Chromium) |
| Zip (optional) | `dist\Scribd-PDF-Downloader-Windows.zip` | Created by `build\windows\build.ps1` |
**Rebuild command:**
```powershell
.\build\windows\build.ps1
```
**Recipient notes:**
- No Python required.
- First run: Windows Defender / SmartScreen may warn — app is unsigned.
- Antivirus may scan `_internal` — allow if prompted.
### macOS
| Artifact | Location | Share how |
|----------|----------|-----------|
| App bundle | `dist/Scribd PDF Downloader.app` | Zip or AirDrop |
| Zip | `dist/Scribd-PDF-Downloader-macOS.zip` | From `build/macos/build.sh` |
**Recipient notes:**
- Unsigned apps: **Right-click → Open** the first time.
- Optional: `codesign --force --deep --sign - "dist/Scribd PDF Downloader.app"`
- For wide public release: Apple Developer ID + notarization.
### What is *not* in the frozen build
- Command-line `main.py` (use source + venv for CLI / `login`).
- Automatic updates — ship a new zip when you release.
---
## N — Notes (behavior & limits)
### Supported URLs
```
https://www.scribd.com/document/<id>/<title>
https://www.scribd.com/doc/<id>/<title>
https://www.scribd.com/book/<id>/<title> # needs login
```
### Documents vs ebooks
| Type | Login | Method |
|------|-------|--------|
| Document / upload | Usually no | Embed viewer → page screenshots → `img2pdf` |
| Ebook | Yes (`main.py login`) | Read viewer → print-to-PDF per page → `pypdf` merge |
### Configuration (`config.ini`)
```ini
[SETTINGS]
delay = 2.0 # seconds between page captures
scale = 2 # screenshot sharpness (1–3)
output = # optional default PDF filename
```
### Files created at runtime
| File / folder | Purpose |
|---------------|---------|
| `session.json` | Saved Scribd login (gitignored) |
| `temp_capture/` | Page images during download |
| `temp_preview/` | Preview screenshots |
| `*.pdf` | Downloaded output |
### Performance tips
- **Blurry text** → increase `scale` to `2` or `3`.
- **Missing pages** → increase `delay` to `2.5`–`3`.
- **Large docs** → use page range `-p 1-50` for a test batch first.
### Legal / ethical use
- Personal archival of content you may legally access.
- Not for bypassing paywalls or redistributing copyrighted material.
---
## A — Architecture (how it works)
```mermaid
flowchart LR
subgraph UI
GUI[gui.py]
CLI[main.py]
end
subgraph Core
URL[url.py]
PRE[preview.py]
DOC[document.py]
BOOK[book.py]
AUTH[auth.py]
end
subgraph External
PW[Playwright + Chromium]
SCR[Scribd embed / read URLs]
end
GUI --> PRE
GUI --> DOC
CLI --> DOC
CLI --> BOOK
PRE --> URL
DOC --> URL
DOC --> PW
PRE --> PW
BOOK --> AUTH
BOOK --> PW
PW --> SCR
DOC --> PDF[img2pdf → .pdf]
BOOK --> PDF2[pypdf merge → .pdf]
```
### Module roles
| Module | Role |
|--------|------|
| `url.py` | Parse Scribd URLs, build embed/read links |
| `preview.py` | Load one page screenshot for GUI preview |
| `document.py` | Capture all `.outer_page` elements, merge to PDF |
| `book.py` | Vertical reader mode, chapter-by-chapter PDF |
| `auth.py` | Login flow, `session.json`, browser context |
| `pages.py` | Parse `1-10` style page selections |
### Build pipeline (frozen app)
1. `PLAYWRIGHT_BROWSERS_PATH=0 playwright install chromium` — browsers inside the package.
2. PyInstaller reads `build/scribd_gui.spec` — bundles GUI, Playwright driver, Chromium, Tcl/Tk.
3. `build/runtime_hook.py` — sets working directory and `PLAYWRIGHT_BROWSERS_PATH=0` when frozen.
### Tech stack
- **Python 3.10+**
- **Playwright** — headless Chromium
- **Pillow** — preview images in GUI
- **img2pdf** — document PDF assembly
- **pypdf** — ebook chapter merge
- **tkinter** — desktop UI
- **PyInstaller** — Windows / macOS packages
---
## Quick reference
| Task | Command |
|------|---------|
| Open GUI (source) | `Start Scribd Downloader.bat` |
| Install deps | See [INSTALL.md](INSTALL.md) |
| Build Windows exe | `.\build\windows\build.ps1` |
| Build Mac app | `./build/macos/build.sh` |
| CLI download | `.\.venv\Scripts\python.exe main.py download "<url>"` |
| Login for books | `.\.venv\Scripts\python.exe main.py login` |
For step-by-step setup, see **[INSTALL.md](INSTALL.md)**.
For packaging details, see **[BUILD.md](BUILD.md)**.
+79
View File
@@ -0,0 +1,79 @@
# Building installable apps
You can ship **Scribd PDF Downloader** as a standalone app on Windows and macOS. Each platform must be built **on that OS** (you cannot build a Mac `.app` from Windows).
| Platform | Output | Build machine |
|----------|--------|---------------|
| Windows | `dist/Scribd PDF Downloader/Scribd PDF Downloader.exe` + zip | Windows PC |
| macOS | `dist/Scribd PDF Downloader.app` + zip | MacBook Pro / any Mac |
The app bundles **Python + Chromium** (~200–350 MB). No separate Python install is required on the target machine.
---
## Windows (.exe)
1. Open **PowerShell** in the project folder.
2. Run:
```powershell
.\build\windows\build.ps1
```
3. When finished:
- **Folder:** `dist\Scribd PDF Downloader\`
- **Zip:** `dist\Scribd-PDF-Downloader-Windows.zip`
Copy the whole folder (or unzip the archive) to any Windows PC and run **Scribd PDF Downloader.exe**.
---
## macOS (.app)
On your **MacBook Pro** (or any Mac):
```bash
chmod +x build/macos/build.sh
./build/macos/build.sh
```
Outputs:
- **App:** `dist/Scribd PDF Downloader.app`
- **Zip:** `dist/Scribd-PDF-Downloader-macOS.zip`
### First launch on Mac
macOS may block unsigned apps:
1. Right-click the app → **Open** → **Open** again, or
2. **System Settings → Privacy & Security → Open Anyway**
### Optional: ad-hoc sign (reduces warnings)
```bash
codesign --force --deep --sign - "dist/Scribd PDF Downloader.app"
```
For distribution outside your Mac, use an **Apple Developer ID** certificate and notarize the app.
---
## Troubleshooting builds
| Issue | Fix |
|-------|-----|
| `pyinstaller` not found | Run build script again (installs `requirements-build.txt`) |
| Chromium missing at runtime | Rebuild after `PLAYWRIGHT_BROWSERS_PATH=0 playwright install chromium` |
| Windows SmartScreen | Expected for unsigned exe; click **More info → Run anyway** |
| Mac “damaged” message | Run `xattr -cr "dist/Scribd PDF Downloader.app"` or ad-hoc sign above |
---
## What gets built
- **GUI only** (`gui.py`) — same as **Start Scribd Downloader.bat**
- **config.ini** copied next to the executable
- **session.json** and downloaded PDFs are saved in the same folder as the `.exe` / `.app`
Command-line use (`main.py`) is not included in the frozen build; use the source project with `.venv` for CLI.
+171
View File
@@ -0,0 +1,171 @@
# Installation Guide
Step-by-step setup for **Scribd PDF Downloader** on Windows, macOS, and Linux.
---
## Prerequisites
- **Python 3.10 or newer** — [python.org/downloads](https://www.python.org/downloads/)
- On Windows, check **“Add python.exe to PATH”** during install.
- **Internet** — to install packages and download Chromium (~150 MB).
- **Disk space** — ~1 GB for venv + browsers; more if you build a standalone app.
Check Python:
```powershell
python --version
```
---
## Windows installation
### 1. Open the project folder
```powershell
cd "C:\Users\Michael Sloan\Desktop\git\Scribe PDF Downloader"
```
(Use your actual path if different.)
### 2. Create a virtual environment
```powershell
python -m venv .venv
```
### 3. Activate the virtual environment
```powershell
.\.venv\Scripts\Activate.ps1
```
If you see an execution policy error:
```powershell
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
```
Then activate again.
### 4. Install Python packages
```powershell
pip install -r requirements.txt
```
### 5. Install Chromium for Playwright
```powershell
playwright install chromium
```
### 6. Run the app
**GUI (recommended):**
```powershell
# With venv active:
python gui.py
```
Or double-click **`Start Scribd Downloader.bat`** (uses `.venv` automatically).
**Command line:**
```powershell
.\.venv\Scripts\python.exe main.py download "https://www.scribd.com/document/123456789/Your-Document"
```
> **Important:** Always use `.\.venv\Scripts\python.exe` if you are not sure the venv is active. Using plain `python` often hits the system install and causes `ModuleNotFoundError: No module named 'rich'`.
---
## macOS installation
```bash
cd ~/path/to/Scribe\ PDF\ Downloader
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
playwright install chromium
python gui.py
```
---
## Linux installation
```bash
cd /path/to/Scribe\ PDF\ Downloader
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
playwright install chromium
python gui.py
```
You may need system libraries for Chromium:
```bash
playwright install-deps chromium
```
---
## Optional: build tools
Only needed to create a standalone `.exe` or `.app`:
```powershell
pip install -r requirements-build.txt
```
See [BUILD.md](BUILD.md).
---
## Verify installation
```powershell
.\.venv\Scripts\python.exe -c "import playwright, rich, PIL; print('OK')"
.\.venv\Scripts\python.exe main.py --help
```
---
## Login (books & private documents)
```powershell
.\.venv\Scripts\python.exe main.py login
```
A browser window opens. Sign in to Scribd, then wait until your account appears. Cookies are saved to `session.json` in the project folder.
Check status:
```powershell
.\.venv\Scripts\python.exe main.py status
```
---
## Uninstall
1. Delete the project folder (includes `.venv` and browsers).
2. No system-wide install is required if you only used a venv.
---
## Troubleshooting
| Error | Solution |
|-------|----------|
| `python` not found | Reinstall Python with PATH enabled, or use `py -3` on Windows |
| `ModuleNotFoundError` | Use `.\.venv\Scripts\python.exe`, not global Python |
| Playwright browser missing | Run `playwright install chromium` inside the venv |
| GUI does not open | Run `python gui.py` from a terminal to see errors |
| Permission denied on `.venv` | Run terminal as normal user, not from a protected folder |
More detail: [AIDNA.md](AIDNA.md) and [README.md](README.md).
+106
View File
@@ -0,0 +1,106 @@
# Scribd PDF Downloader
Save [Scribd](https://www.scribd.com) documents as PDF files for offline reading. Includes a desktop GUI, command-line tools, and optional standalone builds for Windows and macOS.
![Python](https://img.shields.io/badge/python-3.10%2B-blue)
![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey)
---
## Quick start
| How you want to run it | What to do |
|------------------------|------------|
| **Easiest (Windows)** | Double-click `Start Scribd Downloader.bat` |
| **Built app (no Python)** | Run `dist\Scribd PDF Downloader\Scribd PDF Downloader.exe` after [building](BUILD.md) |
| **From source** | Follow [INSTALL.md](INSTALL.md) |
1. Paste a Scribd **document** URL (example below).
2. Click **Load Preview**, then **Download PDF**.
```
https://www.scribd.com/document/1019749989/Form-6-Recloser-Control-Modbus-Protocol-Documentation-Td280014en
```
---
## Features
- **GUI** — URL field, live page preview, progress bar, open PDF / folder
- **Documents** — PDFs, presentations, uploads (most public docs work without login)
- **Ebooks** — Reflowable books (requires Scribd login + subscription)
- **Page ranges** — `all`, `5`, `1-10`, or `1-5, 8`
- **CLI** — Scriptable downloads via `main.py`
- **Standalone builds** — Windows `.exe` and macOS `.app` ([BUILD.md](BUILD.md))
---
## Documentation
| File | Contents |
|------|----------|
| [INSTALL.md](INSTALL.md) | Install Python, venv, dependencies, first run |
| [AIDNA.md](AIDNA.md) | App install, distribution, notes & architecture |
| [BUILD.md](BUILD.md) | Package `.exe` / `.app` with PyInstaller |
---
## Legal notice
Use this tool only for content you have **lawful access** to (your uploads, a valid Scribd subscription, etc.). Respect [Scribd’s Terms of Service](https://support.scribd.com/hc/en-us/articles/210129326-General-Terms-of-Use) and the rights of authors and publishers. The authors of this project are not responsible for misuse.
---
## Command line (summary)
Use the project virtual environment — see [INSTALL.md](INSTALL.md).
```powershell
.\.venv\Scripts\python.exe main.py download "https://www.scribd.com/document/..."
.\.venv\Scripts\python.exe main.py login # books / private docs
.\.venv\Scripts\python.exe main.py status
.\.venv\Scripts\python.exe gui.py # GUI from source
```
| Option | Description |
|--------|-------------|
| `-o, --output` | Output PDF path |
| `-p, --pages` | `all`, `3`, or `1-10` |
| `-d, --delay` | Seconds per page (documents) |
| `-s, --scale` | Screenshot quality `1`–`3` |
---
## Project structure
```
Scribe PDF Downloader/
├── gui.py # Desktop GUI
├── main.py # CLI (download, login, status)
├── Start Scribd Downloader.bat # One-click launcher (Windows)
├── scribd_downloader/ # Core library
├── build/ # PyInstaller specs & build scripts
├── config.ini # Default delay, scale, output
├── INSTALL.md # Setup guide
├── AIDNA.md # Install, distribution & architecture
└── BUILD.md # Build .exe / .app
```
---
## Troubleshooting
| Problem | Fix |
|---------|-----|
| `ModuleNotFoundError: rich` | Use `.venv\Scripts\python.exe`, not system `python` — see [INSTALL.md](INSTALL.md) |
| No pages detected | Document may be private; try `main.py login` |
| Blurry PDF | Increase scale: `-s 2` or `-s 3` |
| Missing pages | Increase delay: `-d 3` |
| Windows SmartScreen | Unsigned build — **More info → Run anyway** |
| Mac blocks app | Right-click → **Open** — see [BUILD.md](BUILD.md) |
---
## License
MIT — use responsibly.
+22
View File
@@ -0,0 +1,22 @@
@echo off
title Scribd PDF Downloader
cd /d "%~dp0"
if not exist ".venv\Scripts\python.exe" (
echo Setting up first time — this may take a minute...
python -m venv .venv
if errorlevel 1 (
echo Python not found. Install Python 3.10+ from https://python.org
pause
exit /b 1
)
call .venv\Scripts\pip install -r requirements.txt
call .venv\Scripts\playwright install chromium
)
".venv\Scripts\pythonw.exe" gui.py
if errorlevel 1 (
echo GUI failed to start. Trying with console...
".venv\Scripts\python.exe" gui.py
pause
)
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Build macOS .app bundle — run ON A MAC from project root:
# chmod +x build/macos/build.sh
# ./build/macos/build.sh
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT"
echo "=== Scribd PDF Downloader — macOS build ==="
if [[ "$(uname)" != "Darwin" ]]; then
echo "Error: macOS builds must run on a Mac (MacBook Pro, etc.)."
exit 1
fi
if [[ ! -d .venv ]]; then
echo "Creating virtual environment..."
python3 -m venv .venv
fi
# shellcheck disable=SC1091
source .venv/bin/activate
pip install -r requirements-build.txt -q
echo "Installing Chromium into package (for bundling)..."
export PLAYWRIGHT_BROWSERS_PATH=0
playwright install chromium
echo "Running PyInstaller..."
pyinstaller --noconfirm --clean build/scribd_gui.spec
APP="dist/Scribd PDF Downloader.app"
if [[ ! -d "$APP" ]]; then
echo "Error: $APP not found."
exit 1
fi
cp -f config.ini "$APP/Contents/MacOS/" 2>/dev/null || cp -f config.ini "$APP/Contents/Resources/" 2>/dev/null || true
ZIP="dist/Scribd-PDF-Downloader-macOS.zip"
rm -f "$ZIP"
ditto -c -k --sequesterRsrc --keepParent "$APP" "$ZIP"
echo ""
echo "Build complete!"
echo " App: $APP"
echo " Zip: $ZIP"
echo ""
echo "First launch: right-click → Open (Gatekeeper) if macOS blocks the app."
echo "Optional signing: codesign --force --deep --sign - \"$APP\""
+17
View File
@@ -0,0 +1,17 @@
"""PyInstaller runtime hook — configure paths when running as a frozen app."""
from __future__ import annotations
import os
import sys
def _app_dir() -> str:
if getattr(sys, "frozen", False):
return os.path.dirname(sys.executable)
return os.getcwd()
if getattr(sys, "frozen", False):
os.chdir(_app_dir())
os.environ.setdefault("PLAYWRIGHT_BROWSERS_PATH", "0")
+98
View File
@@ -0,0 +1,98 @@
# -*- mode: python ; coding: utf-8 -*-
# PyInstaller spec for Scribd PDF Downloader (GUI).
# Build from project root:
# .\build\windows\build.ps1
# ./build/macos/build.sh
import sys
from pathlib import Path
import playwright
block_cipher = None
# SPECPATH is the directory containing this spec file (build/)
ROOT = Path(SPECPATH).parent
HOOKS = Path(playwright.__file__).parent / "_impl" / "__pyinstaller"
datas = [(str(ROOT / "config.ini"), ".")]
hiddenimports = [
"scribd_downloader",
"scribd_downloader.auth",
"scribd_downloader.book",
"scribd_downloader.document",
"scribd_downloader.pages",
"scribd_downloader.preview",
"scribd_downloader.url",
"playwright",
"playwright.sync_api",
"playwright.sync_api._generated",
"greenlet",
"img2pdf",
"pikepdf",
"PIL",
"PIL.Image",
"PIL.ImageTk",
]
a = Analysis(
[str(ROOT / "gui.py")],
pathex=[str(ROOT)],
binaries=[],
datas=datas,
hiddenimports=hiddenimports,
hookspath=[str(HOOKS)],
hooksconfig={},
runtime_hooks=[str(ROOT / "build" / "runtime_hook.py")],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name="Scribd PDF Downloader",
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=False,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=False,
upx_exclude=[],
name="Scribd PDF Downloader",
)
# macOS .app bundle (only used when building on Darwin)
if sys.platform == "darwin":
app = BUNDLE(
coll,
name="Scribd PDF Downloader.app",
icon=None,
bundle_identifier="com.scribd.pdfdownloader",
info_plist={
"CFBundleName": "Scribd PDF Downloader",
"CFBundleDisplayName": "Scribd PDF Downloader",
"CFBundleVersion": "1.0.0",
"CFBundleShortVersionString": "1.0.0",
"NSHighResolutionCapable": True,
},
)
+46
View File
@@ -0,0 +1,46 @@
# Build Windows portable app (folder with Scribd PDF Downloader.exe)
# Run from project root: .\build\windows\build.ps1
$ErrorActionPreference = "Stop"
$Root = Resolve-Path (Join-Path $PSScriptRoot "..\..")
Set-Location $Root
Write-Host "=== Scribd PDF Downloader - Windows build ===" -ForegroundColor Cyan
if (-not (Test-Path ".venv\Scripts\python.exe")) {
Write-Host "Creating virtual environment..."
python -m venv .venv
}
Write-Host "Installing dependencies..."
& .venv\Scripts\pip install -r requirements-build.txt -q
Write-Host "Installing Chromium into package (for bundling)..."
$env:PLAYWRIGHT_BROWSERS_PATH = "0"
& .venv\Scripts\playwright install chromium
Write-Host "Running PyInstaller..."
& .venv\Scripts\pyinstaller --noconfirm --clean "build\scribd_gui.spec"
$Dist = Join-Path $Root "dist\Scribd PDF Downloader"
if (-not (Test-Path $Dist)) {
throw "Build failed: dist folder not found."
}
Copy-Item "config.ini" $Dist -Force -ErrorAction SilentlyContinue
$Zip = Join-Path $Root "dist\Scribd-PDF-Downloader-Windows.zip"
if (Test-Path $Zip) { Remove-Item $Zip -Force }
Start-Sleep -Seconds 2
try {
Compress-Archive -Path $Dist -DestinationPath $Zip -Force
} catch {
Write-Host "Zip skipped (copy the dist folder instead): $_" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "Build complete!" -ForegroundColor Green
Write-Host " App folder: $Dist"
Write-Host " Zip archive: $Zip"
Write-Host ""
Write-Host ('Run: "' + (Join-Path $Dist 'Scribd PDF Downloader.exe') + '"')
+9
View File
@@ -0,0 +1,9 @@
[SETTINGS]
# Seconds to wait after scrolling each page into view (documents)
delay = 2.0
# Screenshot resolution multiplier (1 = normal, 2 = sharper, slower)
scale = 2
# Optional default output filename (leave empty to auto-name from title)
output =
+9
View File
@@ -0,0 +1,9 @@
@echo off
cd /d "%~dp0"
if not exist ".venv\Scripts\python.exe" (
echo Creating virtual environment...
python -m venv .venv
call .venv\Scripts\pip install -r requirements.txt
call .venv\Scripts\playwright install chromium
)
".venv\Scripts\python.exe" main.py download %*
+386
View File
@@ -0,0 +1,386 @@
#!/usr/bin/env python3
"""Scribd PDF Downloader — desktop GUI."""
from __future__ import annotations
import os
import queue
import subprocess
import sys
import threading
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, ttk
from PIL import Image, ImageTk
from scribd_downloader.auth import session_exists
from scribd_downloader.document import download_document
from scribd_downloader.preview import load_document_preview
from scribd_downloader.url import ContentType, parse_scribd_url
APP_TITLE = "Scribd PDF Downloader"
PREVIEW_MAX_WIDTH = 720
class ScribdDownloaderApp(tk.Tk):
def __init__(self) -> None:
super().__init__()
self.title(APP_TITLE)
self.minsize(900, 700)
self.geometry("1000x780")
self._queue: queue.Queue = queue.Queue()
self._photo: ImageTk.PhotoImage | None = None
self._last_pdf: Path | None = None
self._doc_total_pages = 0
self._busy = False
self._build_ui()
self._apply_style()
self.after(100, self._poll_queue)
def _apply_style(self) -> None:
style = ttk.Style(self)
if sys.platform == "win32":
style.theme_use("vista")
style.configure("Title.TLabel", font=("Segoe UI", 16, "bold"))
style.configure("Status.TLabel", font=("Segoe UI", 10))
style.configure("Big.TButton", padding=(12, 8))
def _build_ui(self) -> None:
root = ttk.Frame(self, padding=16)
root.pack(fill=tk.BOTH, expand=True)
ttk.Label(root, text=APP_TITLE, style="Title.TLabel").pack(anchor=tk.W)
ttk.Label(
root,
text="Paste a Scribd document URL, preview it, then download as PDF.",
style="Status.TLabel",
).pack(anchor=tk.W, pady=(4, 12))
url_frame = ttk.LabelFrame(root, text="Scribd URL", padding=10)
url_frame.pack(fill=tk.X, pady=(0, 10))
self.url_var = tk.StringVar()
url_entry = ttk.Entry(url_frame, textvariable=self.url_var, font=("Segoe UI", 11))
url_entry.pack(fill=tk.X, side=tk.LEFT, expand=True, padx=(0, 8))
url_entry.bind("<Return>", lambda _e: self._start_preview())
ttk.Button(url_frame, text="Paste", command=self._paste_url).pack(side=tk.RIGHT)
opts = ttk.Frame(root)
opts.pack(fill=tk.X, pady=(0, 10))
ttk.Label(opts, text="Pages:").grid(row=0, column=0, sticky=tk.W, padx=(0, 6))
self.pages_var = tk.StringVar(value="all")
ttk.Entry(opts, textvariable=self.pages_var, width=12).grid(row=0, column=1, sticky=tk.W)
ttk.Label(opts, text="Delay (s):").grid(row=0, column=2, sticky=tk.W, padx=(16, 6))
self.delay_var = tk.DoubleVar(value=2.0)
ttk.Spinbox(
opts, from_=0.5, to=10.0, increment=0.5, width=6, textvariable=self.delay_var
).grid(row=0, column=3, sticky=tk.W)
ttk.Label(opts, text="Quality:").grid(row=0, column=4, sticky=tk.W, padx=(16, 6))
self.scale_var = tk.IntVar(value=2)
ttk.Combobox(
opts,
textvariable=self.scale_var,
values=[1, 2, 3],
width=4,
state="readonly",
).grid(row=0, column=5, sticky=tk.W)
ttk.Label(opts, text="Preview page:").grid(row=0, column=6, sticky=tk.W, padx=(16, 6))
self.preview_page_var = tk.IntVar(value=1)
self.preview_spin = ttk.Spinbox(
opts,
from_=1,
to=1,
width=5,
textvariable=self.preview_page_var,
command=self._on_preview_page_change,
)
self.preview_spin.grid(row=0, column=7, sticky=tk.W)
btn_row = ttk.Frame(root)
btn_row.pack(fill=tk.X, pady=(0, 10))
self.preview_btn = ttk.Button(
btn_row, text="Load Preview", style="Big.TButton", command=self._start_preview
)
self.preview_btn.pack(side=tk.LEFT, padx=(0, 8))
self.download_btn = ttk.Button(
btn_row, text="Download PDF", style="Big.TButton", command=self._start_download
)
self.download_btn.pack(side=tk.LEFT, padx=(0, 8))
self.open_btn = ttk.Button(
btn_row, text="Open PDF", command=self._open_pdf, state=tk.DISABLED
)
self.open_btn.pack(side=tk.LEFT, padx=(0, 8))
self.folder_btn = ttk.Button(
btn_row, text="Open Folder", command=self._open_folder, state=tk.DISABLED
)
self.folder_btn.pack(side=tk.LEFT)
meta = ttk.Frame(root)
meta.pack(fill=tk.X, pady=(0, 8))
self.title_var = tk.StringVar(value="Title: —")
self.pages_info_var = tk.StringVar(value="Pages: —")
ttk.Label(meta, textvariable=self.title_var, font=("Segoe UI", 11, "bold")).pack(
anchor=tk.W
)
ttk.Label(meta, textvariable=self.pages_info_var, style="Status.TLabel").pack(
anchor=tk.W
)
preview_frame = ttk.LabelFrame(root, text="Preview", padding=8)
preview_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
self.canvas = tk.Canvas(preview_frame, bg="#2b2b2b", highlightthickness=0)
scroll_y = ttk.Scrollbar(preview_frame, orient=tk.VERTICAL, command=self.canvas.yview)
self.canvas.configure(yscrollcommand=scroll_y.set)
scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.preview_label = ttk.Label(
self.canvas,
text="Enter a URL and click Load Preview",
anchor=tk.CENTER,
background="#2b2b2b",
foreground="#cccccc",
)
self.canvas_window = self.canvas.create_window(
0, 0, window=self.preview_label, anchor=tk.NW
)
self.canvas.bind("<Configure>", self._on_canvas_resize)
prog = ttk.Frame(root)
prog.pack(fill=tk.X)
self.progress = ttk.Progressbar(prog, mode="determinate", maximum=100)
self.progress.pack(fill=tk.X, pady=(0, 4))
self.status_var = tk.StringVar(value="Ready")
ttk.Label(prog, textvariable=self.status_var, style="Status.TLabel").pack(anchor=tk.W)
def _on_canvas_resize(self, event: tk.Event) -> None:
self.canvas.itemconfig(self.canvas_window, width=event.width)
if self._photo:
self._center_preview()
def _center_preview(self) -> None:
self.canvas.update_idletasks()
cw = self.canvas.winfo_width()
ch = self.canvas.winfo_height()
if self._photo:
x = max(0, (cw - self._photo.width()) // 2)
y = max(0, (ch - self._photo.height()) // 2)
self.canvas.coords(self.canvas_window, x, y)
def _paste_url(self) -> None:
try:
text = self.clipboard_get().strip()
if text:
self.url_var.set(text)
except tk.TclError:
pass
def _parse_url(self) -> object:
url = self.url_var.get().strip()
if not url:
raise ValueError("Please enter a Scribd URL.")
return parse_scribd_url(url)
def _set_busy(self, busy: bool) -> None:
self._busy = busy
state = tk.DISABLED if busy else tk.NORMAL
self.preview_btn.configure(state=state)
self.download_btn.configure(state=state)
def _start_preview(self) -> None:
if self._busy:
return
try:
target = self._parse_url()
except ValueError as exc:
messagebox.showerror(APP_TITLE, str(exc))
return
if target.content_type == ContentType.BOOK:
messagebox.showinfo(
APP_TITLE,
"Ebooks need the command-line login.\n"
"Run: .venv\\Scripts\\python.exe main.py login",
)
return
page_num = max(1, self.preview_page_var.get())
self._set_busy(True)
self.status_var.set("Loading preview…")
self.progress.configure(mode="indeterminate")
self.progress.start(12)
def worker() -> None:
try:
info = load_document_preview(
target,
page_index=page_num - 1,
scale=self.scale_var.get(),
use_session=session_exists(),
)
self._queue.put(
("preview", info.title, info.total_pages, str(info.preview_path))
)
except Exception as exc:
self._queue.put(("error", str(exc)))
threading.Thread(target=worker, daemon=True).start()
def _on_preview_page_change(self) -> None:
if self._doc_total_pages > 0 and not self._busy:
self._start_preview()
def _start_download(self) -> None:
if self._busy:
return
try:
target = self._parse_url()
except ValueError as exc:
messagebox.showerror(APP_TITLE, str(exc))
return
if target.content_type == ContentType.BOOK:
messagebox.showinfo(
APP_TITLE,
"Ebooks need the command-line login.\n"
"Run: .venv\\Scripts\\python.exe main.py login",
)
return
self._set_busy(True)
self.open_btn.configure(state=tk.DISABLED)
self.folder_btn.configure(state=tk.DISABLED)
self.progress.stop()
self.progress.configure(mode="determinate", value=0)
self.status_var.set("Starting download…")
pages = self.pages_var.get().strip() or "all"
delay = float(self.delay_var.get())
scale = int(self.scale_var.get())
def on_progress(done: int, total: int, message: str) -> None:
self._queue.put(("progress", done, total, message))
def on_page(path: Path, page_no: int, total: int) -> None:
self._queue.put(("page", str(path), page_no, total))
def worker() -> None:
try:
pdf_path = download_document(
target,
pages=pages,
delay=delay,
scale=scale,
use_session=session_exists(),
on_progress=on_progress,
on_page=on_page,
)
self._queue.put(("done", str(pdf_path)))
except Exception as exc:
self._queue.put(("error", str(exc)))
threading.Thread(target=worker, daemon=True).start()
def _show_preview_image(self, path: str) -> None:
img = Image.open(path)
if img.width > PREVIEW_MAX_WIDTH:
ratio = PREVIEW_MAX_WIDTH / img.width
img = img.resize(
(PREVIEW_MAX_WIDTH, int(img.height * ratio)), Image.Resampling.LANCZOS
)
self._photo = ImageTk.PhotoImage(img)
self.preview_label.configure(image=self._photo, text="")
self._center_preview()
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def _poll_queue(self) -> None:
try:
while True:
msg = self._queue.get_nowait()
self._handle_message(msg)
except queue.Empty:
pass
self.after(100, self._poll_queue)
def _handle_message(self, msg: tuple) -> None:
kind = msg[0]
if kind == "preview":
_, title, total, path = msg
self._doc_total_pages = total
self.preview_spin.configure(to=max(1, total))
self.title_var.set(f"Title: {title}")
self.pages_info_var.set(f"Pages: {total}")
self._show_preview_image(path)
self.status_var.set(f"Preview loaded (page {self.preview_page_var.get()} of {total})")
self._finish_busy()
elif kind == "progress":
_, done, total, message = msg
if total > 0:
pct = min(100, int(100 * done / total))
self.progress.configure(value=pct)
self.status_var.set(message)
elif kind == "page":
_, path, page_no, total = msg
self._show_preview_image(path)
self.pages_info_var.set(f"Pages: {total} — capturing {page_no}/{total}")
if total > 0:
self.progress.configure(value=min(100, int(100 * page_no / total)))
elif kind == "done":
_, pdf_path = msg
self._last_pdf = Path(pdf_path)
self.progress.configure(value=100)
self.status_var.set(f"Saved: {self._last_pdf.name}")
self.open_btn.configure(state=tk.NORMAL)
self.folder_btn.configure(state=tk.NORMAL)
self._finish_busy()
messagebox.showinfo(APP_TITLE, f"Download complete:\n{self._last_pdf}")
elif kind == "error":
_, text = msg
self.status_var.set(f"Error: {text}")
self._finish_busy()
messagebox.showerror(APP_TITLE, text)
def _finish_busy(self) -> None:
self.progress.stop()
self.progress.configure(mode="determinate")
self._set_busy(False)
def _open_pdf(self) -> None:
if self._last_pdf and self._last_pdf.is_file():
os.startfile(self._last_pdf)
def _open_folder(self) -> None:
if self._last_pdf and self._last_pdf.is_file():
subprocess.run(
["explorer", "/select,", str(self._last_pdf.resolve())],
check=False,
)
else:
os.startfile(Path.cwd())
def main() -> None:
app = ScribdDownloaderApp()
app.mainloop()
if __name__ == "__main__":
main()
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Scribd PDF Downloader — CLI entry point."""
from __future__ import annotations
import configparser
import sys
from pathlib import Path
import click
from rich.console import Console
from rich.prompt import Prompt
from scribd_downloader import __version__
from scribd_downloader.auth import ensure_logged_in, session_exists
from scribd_downloader.book import download_book
from scribd_downloader.document import download_document
from scribd_downloader.url import ContentType, parse_scribd_url
console = Console()
def _load_defaults() -> dict:
defaults = {"delay": 2.0, "scale": 2, "output": None}
config_path = Path("config.ini")
if not config_path.is_file():
return defaults
config = configparser.ConfigParser()
config.read(config_path)
if "SETTINGS" in config:
s = config["SETTINGS"]
defaults["delay"] = s.getfloat("delay", defaults["delay"])
defaults["scale"] = s.getint("scale", defaults["scale"])
out = s.get("output", "").strip()
defaults["output"] = out or None
return defaults
@click.group()
@click.version_option(__version__, prog_name="scribd-dl")
def cli() -> None:
"""Download Scribd documents and ebooks as PDF files.
For personal use only — respect Scribd's terms and copyright holders.
"""
@cli.command("download")
@click.argument("url", required=False)
@click.option("-o", "--output", help="Output PDF filename")
@click.option("-p", "--pages", default="all", help='Pages: all, 5, or "1-10"')
@click.option("-d", "--delay", type=float, help="Seconds to wait per page (documents)")
@click.option("-s", "--scale", type=click.IntRange(1, 3), help="Screenshot scale 1–3")
@click.option("--login/--no-login", default=False, help="Use saved session cookies")
@click.option("--headed", is_flag=True, help="Show browser window")
def download_cmd(
url: str | None,
output: str | None,
pages: str,
delay: float | None,
scale: int | None,
login: bool,
headed: bool,
) -> None:
"""Download a Scribd URL as PDF."""
defaults = _load_defaults()
if not url:
url = Prompt.ask("[cyan]Scribd URL[/cyan]")
try:
target = parse_scribd_url(url)
except ValueError as exc:
console.print(f"[red]Error:[/red] {exc}")
sys.exit(1)
final_delay = delay if delay is not None else defaults["delay"]
final_scale = scale if scale is not None else defaults["scale"]
final_output = output or defaults["output"]
use_session = login or session_exists()
console.print(
f"\n[bold]Scribd PDF Downloader[/bold] v{__version__} — "
f"[dim]{target.content_type.value}[/dim]\n"
)
try:
if target.content_type == ContentType.BOOK:
if not session_exists() and not login:
console.print(
"[yellow]Books require a Scribd login.[/yellow] "
"Run: [bold]python main.py login[/bold]"
)
sys.exit(1)
download_book(
target,
output=final_output,
headless=not headed,
)
else:
download_document(
target,
output=final_output,
pages=pages,
delay=final_delay,
scale=final_scale,
headless=not headed,
use_session=use_session,
)
except Exception as exc:
console.print(f"[red]Download failed:[/red] {exc}")
sys.exit(1)
@cli.command("login")
@click.option("--force", is_flag=True, help="Re-authenticate even if session exists")
def login_cmd(force: bool) -> None:
"""Sign in to Scribd and save session for books / private documents."""
from playwright.sync_api import sync_playwright
with sync_playwright() as playwright:
ensure_logged_in(playwright, force_login=force)
console.print("[green]Login complete.[/green]")
@cli.command()
def status() -> None:
"""Show whether a saved login session exists."""
if session_exists():
console.print("[green]Session file found[/green] (session.json)")
else:
console.print("[dim]No session — run `python main.py login` for books[/dim]")
if __name__ == "__main__":
cli()
+2
View File
@@ -0,0 +1,2 @@
-r requirements.txt
pyinstaller>=6.0.0
+6
View File
@@ -0,0 +1,6 @@
playwright>=1.40.0
img2pdf>=0.5.0
pypdf>=4.0.0
click>=8.1.0
rich>=13.0.0
Pillow>=10.0.0
+3
View File
@@ -0,0 +1,3 @@
"""Scribd PDF downloader — save documents and ebooks as PDF."""
__version__ = "1.0.0"
+74
View File
@@ -0,0 +1,74 @@
"""Optional Scribd login for subscription or private content."""
from __future__ import annotations
from pathlib import Path
from playwright.sync_api import Browser, BrowserContext, Playwright
SESSION_FILE = Path("session.json")
LOGIN_URL = "https://www.scribd.com/login"
_LOGGED_IN_SELECTORS = (
"motion.header",
"header[data-e2e='header']",
".header__user-menu",
"div.user_row",
"[data-e2e='user-avatar']",
)
def session_exists() -> bool:
return SESSION_FILE.is_file()
def ensure_logged_in(playwright: Playwright, *, force_login: bool = False) -> None:
"""Open a visible browser for login and persist cookies to session.json."""
if session_exists() and not force_login:
return
print("Opening browser for Scribd login…")
print("Sign in, then wait until your account menu appears in the header.")
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto(LOGIN_URL, wait_until="domcontentloaded")
for selector in _LOGGED_IN_SELECTORS:
try:
page.locator(selector).first.wait_for(state="visible", timeout=300_000)
break
except Exception:
continue
else:
raise RuntimeError("Login timed out. Complete sign-in in the browser window.")
context.storage_state(path=str(SESSION_FILE))
print(f"Session saved to {SESSION_FILE.resolve()}")
context.close()
browser.close()
def open_browser(
playwright: Playwright,
*,
headless: bool = True,
use_session: bool = True,
viewport: dict | None = None,
device_scale_factor: float = 1.0,
) -> tuple[Browser, BrowserContext]:
storage = str(SESSION_FILE) if use_session and session_exists() else None
browser = playwright.chromium.launch(headless=headless)
context = browser.new_context(
storage_state=storage,
viewport=viewport or {"width": 1400, "height": 2000},
device_scale_factor=device_scale_factor,
ignore_https_errors=True,
user_agent=(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
),
)
return browser, context
+151
View File
@@ -0,0 +1,151 @@
"""Download Scribd ebooks (reflowable text) chapter by chapter."""
from __future__ import annotations
import re
import shutil
import time
from pathlib import Path
from pypdf import PdfWriter
from playwright.sync_api import sync_playwright
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from scribd_downloader.auth import ensure_logged_in, open_browser
from scribd_downloader.url import ScribdTarget, sanitize_filename
console = Console()
ZOOM = 0.625
def download_book(
target: ScribdTarget,
*,
output: str | None = None,
headless: bool = True,
) -> Path:
"""Render ebook pages to PDF. Requires an active Scribd subscription (login)."""
read_url = target.read_url or target.original_url.replace("/book/", "/read/")
with sync_playwright() as playwright:
ensure_logged_in(playwright)
browser, context = open_browser(playwright, headless=headless, use_session=True)
page = context.new_page()
console.print("[cyan]Opening book reader…[/cyan]")
page.goto(read_url, wait_until="domcontentloaded", timeout=120_000)
if "Browser limit exceeded" in page.content():
context.close()
browser.close()
raise RuntimeError(
"Scribd blocked this book (too many browsers). Wait up to 24 hours."
)
font_style = page.locator("#fontfaces").inner_html()
page.locator(".icon-ic_displaysettings").wait_for(state="visible", timeout=60_000)
page.evaluate("() => document.querySelector('.icon-ic_displaysettings').click()")
page.locator(".vertical_mode_btn").wait_for(state="visible")
page.evaluate("() => document.querySelector('.vertical_mode_btn').click()")
page.locator('div.vertical_page[data-page="0"], motion.div.vertical_page[data-page="0"]').first.wait_for(
state="visible", timeout=60_000
)
page.evaluate("() => document.querySelector('.icon-ic_toc_list').click()")
chapter_selector = page.locator('li.text_btn[role="none"]')
chapter_selector.nth(0).wait_for(state="visible")
num_chapters = chapter_selector.count()
page.evaluate('() => document.querySelector(\'li.text_btn[data-idx="0"]\').click()')
book_title = sanitize_filename(target.title_slug or f"book_{target.content_id}")
cache_dir = Path(f".cache_{target.content_id}")
cache_dir.mkdir(exist_ok=True)
render_page = context.new_page()
render_page.set_viewport_size({"width": 1200, "height": 1600})
chapter_no = 1
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
while True:
task = progress.add_task(
f"Chapter {chapter_no}/{num_chapters}…", total=None
)
page.locator(
'motion.div.vertical_page[data-page="0"], div.vertical_page[data-page="0"]'
).first.wait_for()
chapter_pages = page.locator("motion.div.vertical_page, div.vertical_page")
page_count = chapter_pages.count()
chapter_writer = PdfWriter()
for page_no in range(1, page_count + 1):
page_elem = chapter_pages.nth(page_no - 1)
html = page_elem.inner_html()
html = html.replace('src="/', 'src="https://www.scribd.com/')
match = re.findall(
r"width: ([0-9.]+)px; height: ([0-9.]+)px;", html
)
if not match:
continue
width, height = float(match[0]), float(match[1])
style = (
f"@page {{ size: {width * ZOOM}px {height * ZOOM}px; margin: 0; }} "
f"@media print {{ html, body {{ height: {height * ZOOM}px; "
f"width: {width * ZOOM}px;}}}}"
)
html = re.sub(
'data-colindex="0" style="',
'data-colindex="0" x="',
html,
)
html = re.sub(
r'position: absolute.*?"',
f'overflow: hidden; height: {height}px; width: {width}px; '
f'white-space: nowrap; zoom: {ZOOM};"',
html,
)
content = f"<html><head>{style}{font_style}</head><body>{html}</body></html>"
render_page.set_content(content)
part_pdf = cache_dir / f"{chapter_no}_{page_no}.pdf"
render_page.pdf(path=str(part_pdf), prefer_css_page_size=True)
chapter_writer.append(str(part_pdf))
part_pdf.unlink(missing_ok=True)
chapter_pdf = cache_dir / f"{chapter_no}.pdf"
with open(chapter_pdf, "wb") as f:
chapter_writer.write(f)
progress.remove_task(task)
if chapter_no >= num_chapters:
break
page.evaluate(
"() => document.querySelectorAll('button.load_next_btn')[0].click()"
)
time.sleep(1)
chapter_no += 1
output_path = Path(output or f"{book_title}.pdf")
if output_path.suffix.lower() != ".pdf":
output_path = output_path.with_suffix(".pdf")
final_writer = PdfWriter()
for ch in range(1, num_chapters + 1):
final_writer.append(str(cache_dir / f"{ch}.pdf"))
with open(output_path, "wb") as f:
final_writer.write(f)
shutil.rmtree(cache_dir, ignore_errors=True)
context.close()
browser.close()
console.print(f"[bold green]Saved:[/bold green] {output_path.resolve()}")
return output_path
+157
View File
@@ -0,0 +1,157 @@
"""Download Scribd documents (PDF uploads, presentations) as a single PDF."""
from __future__ import annotations
import time
from collections.abc import Callable
from pathlib import Path
import img2pdf
from playwright.sync_api import BrowserContext, Page, sync_playwright
from rich.console import Console
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
from scribd_downloader.auth import open_browser
from scribd_downloader.pages import parse_page_selection
from scribd_downloader.url import ScribdTarget, sanitize_filename
console = Console()
TEMP_DIR = Path("temp_capture")
ProgressCallback = Callable[[int, int, str], None]
PageCallback = Callable[[Path, int, int], None]
def _block_noise(context: BrowserContext) -> None:
for pattern in ("**/*osano*/**", "**/*analytics*/**", "**/*doubleclick*/**"):
context.route(pattern, lambda route: route.abort())
def _document_title(page: Page, target: ScribdTarget) -> str:
title = page.evaluate(
"""() => {
const og = document.querySelector('meta[property="og:title"]')?.content;
if (og && og.toLowerCase() !== 'scribd') return og.trim();
const inner = document.querySelector('.title_text, .doc_title')?.innerText;
return inner ? inner.trim() : '';
}"""
)
if title:
return sanitize_filename(title)
if target.title_slug:
return sanitize_filename(target.title_slug)
return "scribd_document"
def download_document(
target: ScribdTarget,
*,
output: str | None = None,
pages: str = "all",
delay: float = 2.0,
scale: int = 2,
headless: bool = True,
use_session: bool = True,
on_progress: ProgressCallback | None = None,
on_page: PageCallback | None = None,
) -> Path:
"""Capture document pages via the embed viewer and merge into one PDF."""
TEMP_DIR.mkdir(exist_ok=True)
with sync_playwright() as playwright:
browser, context = open_browser(
playwright,
headless=headless,
use_session=use_session,
device_scale_factor=float(scale),
)
_block_noise(context)
page = context.new_page()
if on_progress:
on_progress(0, 1, "Loading document from Scribd…")
else:
console.print("[cyan]Loading document from Scribd…[/cyan]")
page.goto(target.embed_url, wait_until="domcontentloaded", timeout=90_000)
try:
page.wait_for_selector(".outer_page", timeout=20_000)
except Exception:
pass
total = page.locator(".outer_page").count()
if total == 0:
context.close()
browser.close()
raise RuntimeError(
"No pages found. The document may be private, removed, or blocked. "
"Try: scribd-dl login"
)
doc_title = _document_title(page, target)
if not on_progress:
console.print(f"[dim]Title:[/dim] [bold]{doc_title}[/bold]")
console.print(f"[dim]Pages:[/dim] [bold cyan]{total}[/bold cyan]")
indices = parse_page_selection(pages, total)
image_paths: list[Path] = []
locators = page.locator(".outer_page")
total_capture = len(indices)
def capture_pages() -> None:
for n, idx in enumerate(indices, start=1):
if on_progress:
on_progress(n - 1, total_capture, f"Capturing page {idx + 1}…")
element = locators.nth(idx)
element.scroll_into_view_if_needed()
time.sleep(delay)
img_path = TEMP_DIR / f"page_{idx + 1:04d}.png"
element.screenshot(path=str(img_path))
image_paths.append(img_path)
if on_page:
on_page(img_path, idx + 1, total)
if on_progress:
capture_pages()
on_progress(total_capture, total_capture, "Building PDF…")
else:
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TaskProgressColumn(),
console=console,
) as progress:
task = progress.add_task("Capturing pages…", total=total_capture)
for n, idx in enumerate(indices, start=1):
element = locators.nth(idx)
element.scroll_into_view_if_needed()
time.sleep(delay)
img_path = TEMP_DIR / f"page_{idx + 1:04d}.png"
element.screenshot(path=str(img_path))
image_paths.append(img_path)
progress.advance(task)
progress.update(task, description="Building PDF…")
output_path = Path(output) if output else Path(f"{doc_title}.pdf")
if not output_path.suffix.lower() == ".pdf":
output_path = output_path.with_suffix(".pdf")
if pages.strip().lower() != "all":
stem = output_path.stem
safe_range = pages.replace(" ", "")
output_path = output_path.with_name(f"{stem}_[{safe_range}].pdf")
with open(output_path, "wb") as pdf_file:
pdf_file.write(img2pdf.convert([str(p) for p in image_paths]))
context.close()
browser.close()
for img in image_paths:
img.unlink(missing_ok=True)
if TEMP_DIR.exists() and not any(TEMP_DIR.iterdir()):
TEMP_DIR.rmdir()
if not on_progress:
console.print(f"[bold green]Saved:[/bold green] {output_path.resolve()}")
return output_path
+33
View File
@@ -0,0 +1,33 @@
"""Page range parsing for partial downloads."""
from __future__ import annotations
def parse_page_selection(selection: str, total_pages: int) -> list[int]:
"""Return zero-based page indices from strings like 'all', '3', or '1-10'."""
selection = selection.strip().lower()
if not selection or selection == "all":
return list(range(total_pages))
indices: set[int] = set()
for part in selection.split(","):
part = part.strip()
if not part:
continue
if "-" in part:
start_s, end_s = part.split("-", 1)
start, end = int(start_s), int(end_s)
if start < 1 or end > total_pages or start > end:
raise ValueError(
f"Range {start}-{end} is outside document bounds (1-{total_pages})."
)
indices.update(range(start - 1, end))
else:
page_num = int(part)
if page_num < 1 or page_num > total_pages:
raise ValueError(
f"Page {page_num} is outside document bounds (1-{total_pages})."
)
indices.add(page_num - 1)
return sorted(indices)
+80
View File
@@ -0,0 +1,80 @@
"""Load Scribd documents and capture preview screenshots."""
from __future__ import annotations
import time
from dataclasses import dataclass
from pathlib import Path
from playwright.sync_api import Page, sync_playwright
from scribd_downloader.auth import open_browser
from scribd_downloader.document import TEMP_DIR, _block_noise, _document_title
from scribd_downloader.url import ScribdTarget
PREVIEW_DIR = Path("temp_preview")
@dataclass
class DocumentInfo:
title: str
total_pages: int
preview_path: Path
def load_document_preview(
target: ScribdTarget,
*,
page_index: int = 0,
scale: int = 2,
use_session: bool = True,
) -> DocumentInfo:
"""Open the embed viewer and screenshot one page for preview."""
PREVIEW_DIR.mkdir(exist_ok=True)
page_index = max(0, page_index)
with sync_playwright() as playwright:
browser, context = open_browser(
playwright,
headless=True,
use_session=use_session,
device_scale_factor=float(scale),
)
_block_noise(context)
page = context.new_page()
title, total, preview_path = _load_page(
page, target, page_index=page_index
)
context.close()
browser.close()
return DocumentInfo(title=title, total_pages=total, preview_path=preview_path)
def _load_page(
page: Page,
target: ScribdTarget,
*,
page_index: int,
) -> tuple[str, int, Path]:
page.goto(target.embed_url, wait_until="domcontentloaded", timeout=90_000)
try:
page.wait_for_selector(".outer_page", timeout=20_000)
except Exception:
pass
total = page.locator(".outer_page").count()
if total == 0:
raise RuntimeError(
"No pages found. The document may be private or unavailable."
)
title = _document_title(page, target)
index = min(page_index, total - 1)
element = page.locator(".outer_page").nth(index)
element.scroll_into_view_if_needed()
time.sleep(0.5)
preview_path = PREVIEW_DIR / f"preview_{index + 1}.png"
element.screenshot(path=str(preview_path))
return title, total, preview_path
+102
View File
@@ -0,0 +1,102 @@
"""Parse Scribd URLs and build viewer URLs."""
from __future__ import annotations
import re
from dataclasses import dataclass
from enum import Enum
from urllib.parse import unquote
class ContentType(str, Enum):
DOCUMENT = "document"
BOOK = "book"
UNKNOWN = "unknown"
@dataclass(frozen=True)
class ScribdTarget:
content_id: str
content_type: ContentType
original_url: str
title_slug: str | None = None
@property
def embed_url(self) -> str:
return (
f"https://www.scribd.com/embeds/{self.content_id}/content"
f"?start_page=1&view_mode=scroll"
)
@property
def read_url(self) -> str | None:
if self.content_type != ContentType.BOOK:
return None
return self.original_url.replace("/book/", "/read/").replace(
"scribd.com/book", "scribd.com/read"
)
_ID_PATTERN = re.compile(
r"/(?:document|presentation|doc|book|article|listen)/(\d+)",
re.IGNORECASE,
)
def parse_scribd_url(url: str) -> ScribdTarget:
"""Extract document/book id and type from a Scribd URL."""
url = url.strip()
if url.isdigit():
return ScribdTarget(
content_id=url,
content_type=ContentType.DOCUMENT,
original_url=f"https://www.scribd.com/document/{url}",
)
match = _ID_PATTERN.search(url)
if not match:
raise ValueError(
"Invalid Scribd URL. Expected formats like:\n"
" https://www.scribd.com/document/123456/Title\n"
" https://www.scribd.com/book/123456/Title"
)
content_id = match.group(1)
path_lower = url.lower()
if "/book/" in path_lower:
content_type = ContentType.BOOK
elif any(
segment in path_lower
for segment in ("/document/", "/doc/", "/presentation/", "/article/")
):
content_type = ContentType.DOCUMENT
else:
content_type = ContentType.DOCUMENT
slug = _title_slug_from_url(url)
return ScribdTarget(
content_id=content_id,
content_type=content_type,
original_url=url.split("#")[0].split("?")[0],
title_slug=slug,
)
def _title_slug_from_url(url: str) -> str | None:
clean = url.split("#")[0].split("?")[0].rstrip("/")
parts = clean.split("/")
if len(parts) < 2:
return None
last = parts[-1]
if last.isdigit():
return None
return unquote(last).replace("-", " ").replace("_", " ")
def sanitize_filename(name: str, max_length: int = 120) -> str:
cleaned = "".join(c for c in name if c.isalnum() or c in (" ", "-", "_")).strip()
if not cleaned:
cleaned = "scribd_download"
if len(cleaned) > max_length:
cleaned = cleaned[:max_length].rstrip()
return cleaned
@@ -0,0 +1,24 @@
# Sync this project into ../PDF-Downloaders/Scribd/ for Gitea push.
# Run from project root: .\scripts\sync-to-pdf-downloaders.ps1
$ErrorActionPreference = "Stop"
$Source = Resolve-Path (Join-Path $PSScriptRoot "..")
$RepoRoot = Join-Path (Split-Path $Source -Parent) "PDF-Downloaders"
$Target = Join-Path $RepoRoot "Scribd"
Write-Host "Source: $Source"
Write-Host "Target: $Target"
New-Item -ItemType Directory -Force -Path $Target | Out-Null
$ExcludeDirs = @(
".venv", "venv", "dist", "build\scribd_gui",
"temp_capture", "temp_preview", ".git", "__pycache__"
)
robocopy $Source $Target /E /XD $ExcludeDirs /XF *.pdf session.json history.json `
/NFL /NDL /NJH /NJS /nc /ns /np | Out-Null
if ($LASTEXITCODE -ge 8) { throw "robocopy failed with code $LASTEXITCODE" }
Write-Host "Synced to $Target" -ForegroundColor Green
Write-Host "Next: cd `"$RepoRoot`" and run push-to-gitea.ps1 (after Gitea login)"