This commit is contained in:
afkarxyz committed 2025-12-05 05:00:51 +07:00
1 parent 8e5f18c6cc
commit 280133649d
92 files changed
+15747 -4673

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
# Building Extractor Binary
This guide explains how to build the `extractor` binary from `twitter_cli.py`.
## Quick Start - Use Pre-built Binary
**You don't need to build the binary yourself!** After running the main application once, the pre-built binary is automatically extracted to:
```
Windows: C:\Users\YourUsername\.twitterxmediabatchdownloader\extractor.exe
Linux: ~/.twitterxmediabatchdownloader/extractor
macOS: ~/.twitterxmediabatchdownloader/extractor
```
You can use this binary directly for CLI operations without rebuilding.
### Using the Pre-built Binary
```powershell
# Windows
C:\Users\YourUsername\.twitterxmediabatchdownloader\extractor.exe https://x.com/username/media --limit 10 --json --guest
# Linux/macOS
~/.twitterxmediabatchdownloader/extractor https://x.com/username/media --limit 10 --json --guest
```
---
## Building from Source (Optional)
If you need to rebuild the binary (e.g., after modifying `twitter_cli.py`):
### Prerequisites
```bash
pip install pyinstaller
# or
pip install nuitka
```
### Build Commands
```bash
# PyInstaller (faster build, larger file)
pyinstaller --onefile --name extractor --collect-all gallery_dl twitter_cli.py
# Nuitka (slower build, better performance, smaller file)
python -m nuitka --onefile --output-filename=extractor.exe --include-package=gallery_dl --include-package-data=gallery_dl twitter_cli.py
```
### Output Location
- PyInstaller: `dist/extractor` or `dist/extractor.exe`
- Nuitka: `extractor` or `extractor.exe` (in current directory)
---
## Notes
- The main application automatically manages the binary (extracts, updates, and uses it)
- Manual building is only needed if you're developing or customizing the extractor
- The pre-built binary is kept in sync with the application version
+331
View File
@@ -0,0 +1,331 @@
# twitter_cli.py — Usage Guide
CLI tool for extracting media and metadata from Twitter/X using gallery-dl extractor.
## Quickstart
1. **Set up environment**
```powershell
cd helper
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
```
2. **Verify gallery-dl**
```powershell
python -c "import gallery_dl; print(gallery_dl.__version__)"
```
3. **Quick test** (using demo account):
```powershell
python twitter_cli.py https://x.com/xbatchdemo/media --limit 1 --json --guest
```
---
## Command Line Arguments
### Required
- `url` — Twitter/X URL (timeline, media, likes, search, etc.)
### Authentication
- `--auth-token TOKEN` — Your auth_token cookie value
- `--guest` — Force guest mode (no authentication)
### Content Options
- `--retweets {skip|include|original}` — Control retweets (default: skip)
- `--no-videos` — Skip video downloads
- `--text-tweets` — Include tweets without media
- `--type {photo|video|animated_gif|all}` — Filter by media type (default: all)
### Quality & Format
- `--size SIZE` — Image size: `orig`, `4096x4096`, `large`, `medium`, `small` (default: orig)
### Fetch Control
- `--limit N` — Maximum media items to fetch (0 = unlimited)
- `--cursor CURSOR` — Resume from specific cursor position
### Output Options
- `--json` — Output results as JSON
- `--metadata` — Include tweet metadata (author, counts, etc.)
- `--output FILE` / `-o FILE` — Save to JSON file with resume capability
- `--resume FILE` / `-r FILE` — Resume from previous JSON file
- `--progress` — Show progress during fetch
### Advanced
- `--set KEY=VALUE` — Set gallery-dl extractor options (repeatable)
- `-v` / `--verbose` — Show detailed metadata during fetch
---
## Usage Examples
### Basic Fetch
```powershell
# Guest mode (no auth)
python twitter_cli.py https://x.com/username/media --limit 10 --json --guest
# With authentication
python twitter_cli.py https://x.com/username/media --limit 10 --json --auth-token YOUR_TOKEN
```
### Media Type Filtering
```powershell
# Photos only
python twitter_cli.py https://x.com/username/media --type photo --json --guest
# Videos only
python twitter_cli.py https://x.com/username/media --type video --json --guest
# Animated GIFs only
python twitter_cli.py https://x.com/username/media --type animated_gif --json --guest
```
### With Metadata
```powershell
# Include tweet metadata (author, date, counts)
python twitter_cli.py https://x.com/username/media --limit 5 --json --metadata --guest
```
### Retweets Control
```powershell
# Skip retweets (default)
python twitter_cli.py https://x.com/username/timeline --retweets skip --json --guest
# Include retweets
python twitter_cli.py https://x.com/username/timeline --retweets include --json --guest
# Get original tweet from retweets
python twitter_cli.py https://x.com/username/timeline --retweets original --json --guest
```
### Save & Resume
```powershell
# Save to file (with resume capability)
python twitter_cli.py https://x.com/username/media --limit 100 --output results.json --progress --guest
# Resume from saved file
python twitter_cli.py https://x.com/username/media --resume results.json --limit 100 --output results.json --guest
# Fetch all remaining
python twitter_cli.py https://x.com/username/media --resume results.json --limit 0 --output results.json --guest
```
### Private Content (Requires Auth)
```powershell
# Your likes
python twitter_cli.py https://x.com/username/likes --limit 20 --json --auth-token YOUR_TOKEN
# Your bookmarks
python twitter_cli.py https://x.com/i/bookmarks --limit 20 --json --auth-token YOUR_TOKEN
```
### Search
```powershell
# Search with filters
python twitter_cli.py "https://x.com/search?q=from:username filter:media" --limit 50 --json --guest
# Date range search
python twitter_cli.py "https://x.com/search?q=from:username since:2024-01-01 until:2024-12-31" --json --guest
```
### Advanced Filtering
```powershell
# Filter by date (2024 only)
python twitter_cli.py https://x.com/username/media --json --metadata --set filter="date.year == 2024" --guest
# Filter by engagement (>1000 likes)
python twitter_cli.py https://x.com/username/media --json --metadata --set filter="favorite_count > 1000" --guest
# Combine filters (photos from 2024 with >100 likes)
python twitter_cli.py https://x.com/username/media --type photo --json --metadata --set filter="date.year == 2024 and favorite_count > 100" --guest
```
### Text-Only Tweets
```powershell
# Fetch tweets without media
python twitter_cli.py https://x.com/username/tweets --text-tweets --json --metadata --guest
```
---
## Output Format
### JSON Structure
```json
{
"media": [
{
"url": "https://pbs.twimg.com/media/...",
"tweet_id": 1234567890,
"extension": "jpg",
"width": 2048,
"height": 1536,
"type": "photo"
}
],
"metadata": [
{
"tweet_id": 1234567890,
"date": "2024-01-15T10:30:00+00:00",
"author": {
"id": 123456,
"name": "username",
"nick": "Display Name"
},
"content": "Tweet text content",
"favorite_count": 150,
"retweet_count": 25,
"reply_count": 5,
"view_count": 5000
}
],
"cursor": "1/DAABCgABG7OZH1D___0KAAIW...",
"total": 100,
"completed": false
}
```
### Resume File Structure
When using `--output`, the file includes:
- `url` — Original URL
- `cursor` — Position for resume
- `total` — Total items fetched
- `completed` — Whether fetch is complete
- `media` — All media items
- `metadata` — All metadata (if requested)
---
## Pagination & Resume
### How It Works
- Twitter API returns ~100-200 items per batch
- Cursor tracks position for next fetch
- System ensures cursor availability before stopping
- Resume continues from exact position (no duplicates)
### Resume Workflow
```powershell
# Step 1: Initial fetch (saves state)
python twitter_cli.py https://x.com/user/media --limit 100 --output data.json --progress --guest
# Output: Saved 202 media to data.json [partial (can resume)]
# Step 2: Resume and fetch more
python twitter_cli.py https://x.com/user/media --resume data.json --limit 100 --output data.json --guest
# Output: Resuming from cursor, 202 media already fetched
# Added 100 new media (total: 302)
# Step 3: Fetch all remaining
python twitter_cli.py https://x.com/user/media --resume data.json --limit 0 --output data.json --guest
# Output: Added 244 new media (total: 546) [completed]
```
---
## Supported URL Patterns
### User Timelines
- `https://x.com/username/media` — Media timeline
- `https://x.com/username/timeline` — Full timeline
- `https://x.com/username/tweets` — Tweets only
- `https://x.com/username/with_replies` — With replies
- `https://x.com/username/likes` — Liked tweets (requires auth)
### Private Content
- `https://x.com/i/bookmarks` — Your bookmarks (requires auth)
### Search
- `https://x.com/search?q=QUERY` — Search tweets
- `https://x.com/hashtag/NAME` — Hashtag search
### Individual Tweet
- `https://x.com/username/status/1234567890` — Single tweet
---
## Search Operators
Use in search URLs:
| Operator | Example | Description |
|----------|---------|-------------|
| `from:USER` | `from:username` | Tweets from user |
| `to:USER` | `to:username` | Tweets mentioning user |
| `filter:media` | `cats filter:media` | Only with media |
| `filter:images` | `cats filter:images` | Only images |
| `filter:videos` | `cats filter:videos` | Only videos |
| `since:DATE` | `since:2024-01-01` | After date |
| `until:DATE` | `until:2024-12-31` | Before date |
| `-filter:retweets` | `cats -filter:retweets` | Exclude retweets |
| `min_faves:N` | `min_faves:1000` | Min likes |
| `min_retweets:N` | `min_retweets:100` | Min retweets |
---
## Authentication
### Getting Your Auth Token
1. Open Twitter/X in your browser
2. Open Developer Tools (F12)
3. Go to Application/Storage → Cookies
4. Find cookie named `auth_token`
5. Copy its value
### Security Notes
- Use a dummy/secondary account for scraping
- Don't share your auth token
- Excessive usage may cause account suspension
- Guest mode has stricter rate limits
---
## Rate Limits
- **Guest mode**: Lower limits, may hit rate limit faster
- **Authenticated**: Higher limits but still restricted
- **Rate limit hit**: Script will wait and retry automatically
- **Best practice**: Use `--limit` to control fetch size
---
## Tips & Tricks
### 1. Progressive Fetch with Resume
```powershell
# Fetch in batches to avoid long waits
python twitter_cli.py URL --limit 200 --output data.json --progress --guest
python twitter_cli.py URL --resume data.json --limit 200 --output data.json --guest
```
### 2. Combine Type Filter with Custom Filter
```powershell
# Photos from 2024 with high engagement
python twitter_cli.py URL --type photo --metadata --set filter="date.year == 2024 and favorite_count > 500" --json --guest
```
### 3. Use Progress Flag for Long Fetches
```powershell
python twitter_cli.py URL --limit 1000 --progress --output data.json --guest
```
### 4. Check Cursor Availability
- If `completed: false` in output → can resume
- If `completed: true` → all data fetched
- If `cursor: null` → no more data available
+309
View File
@@ -0,0 +1,309 @@
"""Command-line helper for gallery-dl's Twitter extractor.
Features:
- Cursor-based resume: Use --output to save progress, --resume to continue
- Progress tracking: See fetch progress in real-time
- Rate limit: Automatically handled by gallery-dl
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import Dict, List, Optional
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from twitter_common import ( # type: ignore
TwitterRequest,
coerce_literal,
load_resume_state,
merge_options,
run_request_dict,
save_state,
)
DEFAULT_AUTH_TOKEN = ""
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Light-weight CLI wrapper around gallery-dl's Twitter extractor",
)
parser.add_argument("url", help="Any supported Twitter/X URL (timeline, media, likes, ...)")
parser.add_argument(
"--auth-token",
default=DEFAULT_AUTH_TOKEN,
help="Value of the auth_token cookie (leave empty to skip)",
)
parser.add_argument(
"--guest",
action="store_true",
help="Force guest mode (do not send auth_token)",
)
parser.add_argument(
"--retweets",
choices=["skip", "include", "original"],
default="skip",
help="Control retweet handling (skip, include, or swap for originals)",
)
parser.add_argument(
"--no-videos",
action="store_true",
help="Skip video/animated GIF variants",
)
parser.add_argument(
"--size",
default="orig",
help="Image size to request (orig, 4096x4096, large, ...)",
)
parser.add_argument(
"--limit",
type=int,
default=0,
help="Stop after N media files (0 = all)",
)
parser.add_argument(
"--json",
action="store_true",
help="Emit JSON instead of plain URLs",
)
parser.add_argument(
"--metadata",
action="store_true",
help="Include tweet metadata in output",
)
parser.add_argument(
"--text-tweets",
action="store_true",
help="Include text tweets (without media)",
)
parser.add_argument(
"--type",
choices=["photo", "video", "animated_gif", "all"],
default="all",
help="Filter by media type (photo, video, animated_gif, or all)",
)
parser.add_argument(
"--verbose",
"-v",
action="store_true",
help="Echo tweet metadata to stderr while crawling",
)
parser.add_argument(
"--set",
metavar="KEY=VALUE",
action="append",
default=[],
help="Add override for extractor.twitter.* options (repeatable)",
)
parser.add_argument(
"--output",
"-o",
metavar="FILE",
help="Save results to JSON file (includes cursor for resume)",
)
parser.add_argument(
"--resume",
"-r",
metavar="FILE",
help="Resume from previous JSON file (continues from saved cursor)",
)
parser.add_argument(
"--cursor",
metavar="CURSOR",
help="Resume from specific cursor position",
)
parser.add_argument(
"--progress",
action="store_true",
help="Show progress during fetch",
)
return parser.parse_args()
def _retweets_value(mode: str):
if mode == "original":
return "original"
if mode == "include":
return True
return False
def _parse_overrides(entries: List[str]) -> Dict[str, object]:
overrides: Dict[str, object] = {}
for entry in entries:
if "=" not in entry:
raise ValueError(f"Format must be KEY=VALUE, got: {entry}")
key, raw = entry.split("=", 1)
overrides[key.strip()] = coerce_literal(raw.strip())
return overrides
def _progress_callback(count: int, cursor: Optional[str]) -> None:
"""Print progress to stderr."""
cursor_info = f" (cursor: {cursor[:20]}...)" if cursor and len(cursor) > 20 else ""
cursor_info = f" (cursor: {cursor})" if cursor and len(cursor) <= 20 else cursor_info
print(f"Fetching... {count} media{cursor_info}", file=sys.stderr)
def main() -> None:
args = parse_args()
# Handle resume from file
resume_cursor: Optional[str] = None
previous_media: List[Dict] = []
previous_metadata: List[Dict] = []
seen_urls: set = set()
url = args.url
# Convert --type to filter expression
type_filter = None
if args.type != "all":
type_filter = f"type == '{args.type}'"
if args.resume:
state = load_resume_state(args.resume)
if state:
if state.get("completed"):
print(f"Previous fetch already completed ({state.get('total', 0)} media)", file=sys.stderr)
print("Use --output to start fresh or remove the file", file=sys.stderr)
sys.exit(0)
resume_cursor = state.get("cursor")
previous_media = state.get("media", [])
previous_metadata = state.get("metadata", [])
# Track seen URLs to avoid duplicates
seen_urls = {m.get("url") for m in previous_media if m.get("url")}
url = state.get("url", args.url)
if resume_cursor:
print(f"Resuming from cursor, {len(previous_media)} media already fetched", file=sys.stderr)
else:
print(f"No cursor available, will deduplicate {len(previous_media)} existing media", file=sys.stderr)
else:
print(f"Could not load resume file: {args.resume}", file=sys.stderr)
sys.exit(1)
# Manual cursor override
if args.cursor:
resume_cursor = args.cursor
include_videos = not args.no_videos
auth_token = None if args.guest or not args.auth_token.strip() else args.auth_token
# Parse user overrides
user_overrides = _parse_overrides(args.set)
# Add type filter if specified (merge with existing filter if any)
if type_filter:
existing_filter = user_overrides.get("filter")
if existing_filter:
# Combine with AND
user_overrides["filter"] = f"({existing_filter}) and ({type_filter})"
else:
user_overrides["filter"] = type_filter
options = merge_options(
{
"auth_token": auth_token,
"retweets": _retweets_value(args.retweets),
"videos": include_videos,
"size": args.size,
"text-tweets": args.text_tweets,
},
user_overrides,
)
request = TwitterRequest(
url=url,
limit=args.limit,
metadata=(args.metadata or args.verbose),
options=options,
cursor=resume_cursor,
)
progress_cb = _progress_callback if (args.progress or args.verbose) else None
# Pass seen_urls for deduplication if no cursor available
skip_urls = seen_urls if (not resume_cursor and seen_urls) else None
try:
result = run_request_dict(request, on_progress=progress_cb, skip_urls=skip_urls)
except KeyboardInterrupt:
print("\nInterrupted by user", file=sys.stderr)
sys.exit(130)
except Exception as exc:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
# Merge with previous results if resuming
if previous_media:
if resume_cursor:
# With cursor: filter duplicates that might occur at boundary
new_media = [m for m in result["media"] if m.get("url") not in seen_urls]
result["media"] = previous_media + new_media
result["metadata"] = previous_metadata + result["metadata"]
else:
# Without cursor: results already deduplicated via skip_urls
result["media"] = previous_media + result["media"]
result["metadata"] = previous_metadata + result["metadata"]
result["total"] = len(result["media"])
new_count = result["total"] - len(previous_media)
if new_count > 0:
print(f"Added {new_count} new media (total: {result['total']})", file=sys.stderr)
else:
print(f"No new media found", file=sys.stderr)
media = result["media"]
metadata = result["metadata"]
# Save to file if --output specified
if args.output:
save_state(args.output, result, url)
status = "completed" if result.get("completed") else "partial (can resume)"
print(f"Saved {len(media)} media to {args.output} [{status}]", file=sys.stderr)
if not result.get("completed") and result.get("cursor"):
print(f"Resume with: --resume {args.output}", file=sys.stderr)
if args.verbose:
for entry in metadata:
author = (entry.get("author") or {}).get("name")
print(
f"Processing tweet {entry.get('tweet_id')} / {author}",
file=sys.stderr,
)
if args.json:
payload: Dict[str, object] = {
"media": media,
"total": len(media),
"completed": result.get("completed", True),
}
if result.get("cursor"):
payload["cursor"] = result["cursor"]
if args.metadata:
payload["metadata"] = metadata
print(json.dumps(payload, indent=2, default=str))
else:
for item in media:
print(item["url"])
if args.metadata:
print("\n# Metadata", file=sys.stderr)
for entry in metadata:
print(
f"{entry['tweet_id']}: {entry['content']}",
file=sys.stderr,
)
# Print summary
print(f"\nTotal: {len(media)} media", file=sys.stderr)
if not result.get("completed") and result.get("cursor"):
print(f"Cursor for resume: {result['cursor']}", file=sys.stderr)
if __name__ == "__main__":
main()
+326
View File
@@ -0,0 +1,326 @@
"""Shared abstraction for all Twitter gallery-dl examples.
This file provides utility functions that build gallery-dl configuration
based on parameters in ``twitter-parameters.md`` and execute the Twitter
extractor in a single run. All four interfaces (direct module, CLI, FastAPI, and
Flask) rely on this module to ensure consistent behavior.
Features:
- Cursor-based resume: Save progress and continue from where you left off
- Progress tracking: Monitor fetch progress in real-time
- Rate limit handling: Automatically handled by gallery-dl
"""
from __future__ import annotations
import json
import os
import sys
import threading
from dataclasses import dataclass, field
from datetime import date, datetime
from typing import Any, Callable, Dict, Iterable, List, MutableMapping, Optional
REPO_ROOT = os.path.dirname(os.path.abspath(__file__))
if REPO_ROOT not in sys.path:
sys.path.append(REPO_ROOT)
from gallery_dl import config, extractor as extractor_mod # type: ignore
from gallery_dl.extractor.common import Message # type: ignore
_CONFIG_LOCK = threading.Lock()
# Internal keys that should not be directly passed to extractor config.
_INTERNAL_KEYS = {
"url",
"limit",
"metadata",
"options",
"auth_token",
"guest",
"cookies",
"cursor",
}
@dataclass
class TwitterRequest:
"""Standard request structure for all frontends."""
url: str
options: Dict[str, Any] = field(default_factory=dict)
limit: int = 0
metadata: bool = False
cursor: Optional[str] = None # Resume from this cursor position
@dataclass
class TwitterResult:
"""Result structure with cursor for resume capability."""
media: List[Dict[str, Any]]
metadata: List[Dict[str, Any]]
cursor: Optional[str] = None # Cursor to resume from
total: int = 0
completed: bool = True # False if stopped before completion
def _serialize_value(value: Any) -> Any:
if isinstance(value, (datetime, date)):
return value.isoformat()
if isinstance(value, set):
return sorted(value)
return value
def _extract_tweet_metadata(data: MutableMapping[str, Any]) -> Dict[str, Any]:
keys = (
"tweet_id",
"retweet_id",
"quote_id",
"reply_id",
"conversation_id",
"date",
"author",
"content",
"lang",
"hashtags",
"mentions",
"sensitive",
"sensitive_flags",
"favorite_count",
"retweet_count",
"quote_count",
"reply_count",
"bookmark_count",
"view_count",
)
meta = {key: _serialize_value(data.get(key)) for key in keys}
if isinstance(meta["author"], dict):
meta["author"] = {
"id": meta["author"].get("id"),
"name": meta["author"].get("name"),
"nick": meta["author"].get("nick"),
}
return meta
def _clean_file_metadata(meta: MutableMapping[str, Any]) -> Dict[str, Any]:
return {key: _serialize_value(value) for key, value in meta.items()}
def _apply_options(options: Dict[str, Any], cursor: Optional[str] = None) -> None:
"""Reset config and apply all extractor options."""
config.clear()
cookies = options.get("cookies")
auth_token = options.get("auth_token")
if auth_token:
cookies = dict(cookies or {})
cookies["auth_token"] = auth_token
if cookies:
config.set(("extractor", "twitter"), "cookies", cookies)
# Enable cursor tracking, or set specific cursor for resume
if cursor:
config.set(("extractor", "twitter"), "cursor", cursor)
else:
config.set(("extractor", "twitter"), "cursor", True)
for key, value in options.items():
if key in _INTERNAL_KEYS or value is None:
continue
config.set(("extractor", "twitter"), key, value)
def run_request(
request: TwitterRequest,
on_progress: Optional[Callable[[int, Optional[str]], None]] = None,
skip_urls: Optional[set] = None,
ensure_cursor: bool = True,
) -> TwitterResult:
"""Run Twitter extractor and return media & metadata results.
Args:
request: The TwitterRequest configuration
on_progress: Optional callback(count, cursor) called periodically during fetch
skip_urls: Optional set of URLs to skip (for resume/deduplication)
ensure_cursor: If True, continue fetching until cursor is available (for reliable resume)
Returns:
TwitterResult with media, metadata, cursor for resume, and completion status
"""
skip_urls = skip_urls or set()
with _CONFIG_LOCK:
_apply_options(request.options, request.cursor)
extractor = extractor_mod.find(request.url)
if extractor is None or extractor.category != "twitter":
raise ValueError(f"URL not recognized by Twitter extractor: {request.url}")
media: List[Dict[str, Any]] = []
metadata: List[Dict[str, Any]] = []
collected = 0
skipped = 0
last_cursor: Optional[str] = None
last_tweet_id: Optional[int] = None
completed = True
limit_reached = False
try:
for message in extractor:
mtype = message[0]
if mtype is Message.Directory and request.metadata:
metadata.append(_extract_tweet_metadata(message[1]))
elif mtype is Message.Url:
url = message[1]
# Skip if already seen
if url in skip_urls:
skipped += 1
continue
file_meta = _clean_file_metadata(message[2])
# Apply client-side filter if specified
# Note: gallery-dl's filter only works for downloads, not message iteration
filter_expr = request.options.get("filter")
if filter_expr:
try:
# Create evaluation context with file metadata
eval_context = {**file_meta}
# Add common functions that might be used in filters
eval_context['datetime'] = datetime
eval_context['date'] = date
# Evaluate filter expression
if not eval(filter_expr, {"__builtins__": {}}, eval_context):
continue # Skip this item
except Exception as e:
# If filter evaluation fails, include the item (fail-open)
pass
media.append({"url": url, **file_meta})
collected += 1
# Track last tweet_id for progress display
if "tweet_id" in file_meta:
last_tweet_id = file_meta["tweet_id"]
# Try to get cursor from extractor
if hasattr(extractor, '_cursor') and extractor._cursor:
last_cursor = extractor._cursor
# Report progress every 10 items
if on_progress and collected % 10 == 0:
on_progress(collected, last_cursor)
# Check if limit reached
if request.limit and collected >= request.limit:
if ensure_cursor and not last_cursor:
# Continue until cursor is available for reliable resume
limit_reached = True
continue
completed = False # Stopped due to limit
break
# If we were waiting for cursor and now have it, stop
if limit_reached and last_cursor:
completed = False
break
except KeyboardInterrupt:
completed = False
finally:
# Get final cursor from extractor
if hasattr(extractor, '_cursor') and extractor._cursor:
last_cursor = extractor._cursor
return TwitterResult(
media=media,
metadata=metadata,
cursor=last_cursor,
total=collected,
completed=completed,
)
def run_request_dict(
request: TwitterRequest,
on_progress: Optional[Callable[[int, Optional[str]], None]] = None,
skip_urls: Optional[set] = None,
ensure_cursor: bool = True,
) -> Dict[str, Any]:
"""Run request and return as dictionary (for JSON serialization)."""
result = run_request(request, on_progress, skip_urls, ensure_cursor)
return {
"media": result.media,
"metadata": result.metadata,
"cursor": result.cursor,
"total": result.total,
"completed": result.completed,
}
def load_resume_state(filepath: str) -> Optional[Dict[str, Any]]:
"""Load previous state from JSON file for resume."""
if not os.path.exists(filepath):
return None
try:
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
return data
except (json.JSONDecodeError, IOError):
return None
def save_state(filepath: str, result: Dict[str, Any], url: str) -> None:
"""Save current state to JSON file."""
state = {
"url": url,
"cursor": result.get("cursor"),
"total": result.get("total", len(result.get("media", []))),
"completed": result.get("completed", True),
"media": result.get("media", []),
"metadata": result.get("metadata", []),
}
with open(filepath, "w", encoding="utf-8") as f:
json.dump(state, f, indent=2, default=str)
def merge_options(*sources: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""Merge multiple configuration dicts (None values ignored)."""
merged: Dict[str, Any] = {}
for source in sources:
if not source:
continue
for key, value in source.items():
merged[key] = value
return merged
def coerce_literal(value: str) -> Any:
"""Infer basic type from CLI argument string."""
lowered = value.lower()
if lowered in {"true", "false"}:
return lowered == "true"
if lowered in {"null", "none"}:
return None
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
if (value.startswith("[") and value.endswith("]")) or (
value.startswith("{") and value.endswith("}")
):
try:
return json.loads(value)
except json.JSONDecodeError:
return value
return value