Skip to content

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

33 Commits

Folders and files

Repository files navigation

Douyin Video Scanner

A complete system for scraping Douyin (Chinese TikTok) videos and processing them through an async pipeline.

Architecture

┌─────────────────────────────────────────────────────────────┐
│              Node.js Scraper (douyin-scraper.js)            │
│  - Scrapes videos from Douyin via Chrome CDP                │
│  - Extracts: title, author, likes, comments, shares         │
│  - Saves to PostgreSQL                                      │
└─────────────────────────┬───────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                      PostgreSQL                             │
│  - douyin_videos      : Video metadata                      │
│  - douyin_comments    : Top comments per video              │
│  - video_tasks        : Pipeline status                     │
│  - video_task_steps   : Step history + JSON results         │
└─────────────────────────┬───────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│           Python CLI + Celery Worker (worker/)              │
│  - Per video: download → Codex CLI 视觉概括 → 删除本地 mp4 │
│  - Triggered via CLI or Beat (process_pending_videos)       │
└─────────────────────────────────────────────────────────────┘

Prerequisites

  • Node.js 18+
  • Python 3.9+
  • uv (Python package manager)
  • PostgreSQL
  • Redis
  • Google Chrome
  • Native Codex CLI with an existing account login, plus ffmpeg/ffprobe

The primary video-summary provider uses uniformly sampled static frames, not audio or ASR. Model and effort come from device ~/.config/agent-im/models.env: AGENT_IM_CLIENT_MODEL (API prefix stripped for CLI) and AGENT_IM_REASONING_EFFORT. Missing/invalid settings warn and fall back to gpt-6.1-sol / medium. See worker/README.md for CLI isolation and offline-test boundaries; no browser-summary service is needed.

服务管理

可通过 local-service 管理 Celery Worker:

# 启动 Celery Worker + Beat
./start-bg.sh

# 停止
./stop-bg.sh

Quick Start

1. Database Setup

# Start PostgreSQL (if not running)
brew services start postgresql

# Initialize database and tables
node init-db.js

Expected output:

🐘 Douyin Scraper Database Initialization
✅ Database "douyin" exists
📦 Ensuring tables exist...
✅ Tables ready

2. Scraper Setup (Node.js)

# Install dependencies
npm install

# Open the shared Chrome profile, log in, then press Enter to close it
node open-browser.js

# Run scraper (scrape 5 videos with >= 5000 comments)
node douyin-scraper.js 5

Both browser entrypoints use browser-options.js: the default profile is path.join(os.tmpdir(), 'douyin-scraper-user-data'). Set BROWSER_USER_DATA_DIR consistently for both commands to use another profile. On macOS, only Patchright's --use-mock-keychain and --password-store=basic defaults are removed, so login cookies use Chrome's real keychain encryption; other default arguments remain. macOS may request Chrome keychain access on the next launch. Do not run the login window and scraper simultaneously against the same profile. No separate Chrome remote-debugging service is required for these entrypoints.

Daily feed mode always follows the strict navigation path below before scraping:

  1. Open the Douyin featured page (https://www.douyin.com/).
  2. Click the visible left-side 推荐 menu.
  3. Verify the current route matches that menu's link target.
  4. Wait for the active recommendation video to become playable.
  5. Continue with the existing scrape, filter, comment, share-link, and database logic.

The scraper retries this full navigation once. If it still cannot prove that the recommendation feed is active, it exits instead of scraping the featured page. --url target-video mode bypasses this feed navigation.

Expected output:

🎬 Douyin Video Scraper
📊 Will scrape 5 video(s) with >= 5000 comments

🏠 Opening Douyin featured page (attempt 1/2)...
🖱️  Clicking 推荐 menu: ...
✅ Recommendation route matched: ...
✅ Recommendation video feed is ready

📹 Scraping video #1...
  📝 Title: ...
  👤 Author: @username
  💬 Comments: 6.3万
  💾 Saved to PostgreSQL
  📊 Progress: 1/5 videos collected

Scraper Environment Variables

Variable Default Description
SAVE_TO_FILE false Set to true to save JSON/Markdown files
BROWSER_USER_DATA_DIR OS temp directory + douyin-scraper-user-data Shared profile for login and scraping
PGHOST localhost PostgreSQL host
PGPORT 5432 PostgreSQL port
PGDATABASE douyin Database name
PGUSER postgres Database user
PGPASSWORD postgres Database password

3. Worker Setup (Python/Celery)

# Start Redis (if not running)
brew services start redis

# Setup Python worker
cd worker
uv sync

# Copy environment config
cp .env.example .env
# Edit .env if needed

# Start Celery worker (keep running in terminal)
uv run celery -A celery_app worker --loglevel=info --concurrency=1

Expected output:

[tasks]
  . tasks.process_pending_videos
  . tasks.process_one_video_summary
  . tasks.reset_stale_tasks
  . tasks.scrape_douyin_daily

celery@hostname ready.

4. Process Videos

cd worker

# Check status
uv run python cli.py status

# Process 20 oldest videos without summary
uv run python cli.py trigger 20

# Process a single video
uv run python cli.py process <video_id>

# Reset stuck tasks
uv run python cli.py reset

Expected output:

============================================================
DOUYIN VIDEO TASK STATUS
============================================================

📹 Videos without summary: 5

📊 Task Statistics:
------------------------------------------------------------
  completed: 10
  pending: 5

📋 Step Statistics:
------------------------------------------------------------
  download        | completed    | 10
  submit          | completed    | 10
  get_summary     | completed    | 10
============================================================

5. Automate with Crontab

# Edit crontab
crontab -e

# Add daily job at 4am
0 4 * * * cd /path/to/tiktok-scanner/worker && uv run python cli.py trigger 20 >> /var/log/douyin-worker.log 2>&1

Project Structure

tiktok-scanner/
├── douyin-scraper.js     # Main scraper (Node.js)
├── init-db.js            # Database initialization
├── package.json          # Node.js dependencies
├── browser-options.js    # Shared production profile and keychain launch settings
├── output/               # Scraped files (if SAVE_TO_FILE=true)
└── worker/               # Python Celery worker
    ├── pyproject.toml    # Python dependencies (uv)
    ├── uv.lock           # Lock file
    ├── .env.example      # Environment template
    ├── celery_app.py     # Celery configuration
    ├── config.py         # Settings from env vars
    ├── db.py             # Database operations
    ├── tasks.py          # Pipeline tasks (download, submit, get_summary)
    ├── cli.py            # CLI tool
    └── README.md         # Worker documentation

Database Schema

douyin_videos

Column Type Description
video_id VARCHAR(64) Unique video ID
title TEXT Video title
author VARCHAR(255) Author username
likes INTEGER Like count
comments_count INTEGER Comment count
favorites INTEGER Favorite count
shares INTEGER Share count
share_link TEXT Full video URL

video_tasks

Column Type Description
video_id VARCHAR(64) Reference to video
current_step VARCHAR(32) pending/download/submit/get_summary/completed
status VARCHAR(32) pending/processing/completed/failed

video_task_steps

Column Type Description
video_id VARCHAR(64) Reference to video
step_name VARCHAR(32) download/submit/get_summary
status VARCHAR(32) pending/processing/completed/failed
result JSONB Step output data
error_message TEXT Error details if failed

Pipeline Steps

The worker processes videos through 3 steps:

  1. download - Download video file
  2. submit - Submit to AI service for processing
  3. get_summary - Retrieve generated summary

Implementing Actual Logic

Edit worker/tasks.py to implement real logic:

def _execute_download(video_id):
    # TODO: Download video from Douyin
    # - Fetch video URL from database
    # - Download video file
    # - Upload to cloud storage
    pass

def _execute_submit(video_id, download_result):
    # TODO: Submit to AI service
    # - Read video from download_result['file_path']
    # - Call AI API (OpenAI, Claude, etc.)
    # - Return submission ID
    pass

def _execute_get_summary(video_id, submit_result):
    # TODO: Get summary from AI service
    # - Poll using submit_result['submission_id']
    # - Store summary in database
    pass

Common Commands

# === Database ===
node init-db.js              # Initialize tables
node init-db.js --drop       # Reset all data (WARNING!)

# === Scraper ===
node douyin-scraper.js 10    # Scrape 10 videos
SAVE_TO_FILE=true node douyin-scraper.js 5  # Save to files too

# === Worker ===
cd worker
uv run celery -A celery_app worker --loglevel=info --concurrency=1  # Start worker
uv run celery -A celery_app beat --loglevel=info    # Start scheduler (optional)
uv run python cli.py status                          # Check status
uv run python cli.py trigger 20                      # Process 20 videos
uv run python cli.py process <video_id>              # Process one video
uv run python cli.py reset                           # Reset stuck tasks

# === Monitoring ===
uv run --with flower celery -A celery_app flower     # Web UI at :5555

Troubleshooting

Chrome login missing or profile already in use

Use the same BROWSER_USER_DATA_DIR for login and scheduled scraping. Close any existing Chrome using that profile before launching the other entrypoint; do not delete its profile or Cookie database. For a fresh login:

node open-browser.js

Log in, then press Enter to close this window before the scraper runs. These entrypoints launch Chrome themselves through Patchright, not port 9222/CDP.

PostgreSQL connection failed

Error: ECONNREFUSED

Start PostgreSQL:

brew services start postgresql

Redis connection failed

Error: Connection refused redis://localhost:6379

Start Redis:

brew services start redis

Task stuck in processing

cd worker
uv run python cli.py reset

License

MIT

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages