Skip already-downloaded TikTok IDs across runs Log failed URLs to ./failed.txt for later retry
328 lines
10 KiB
Python
328 lines
10 KiB
Python
import json
|
|
import logging
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from typing import List
|
|
from urllib.parse import urlparse
|
|
|
|
# Setup logging
|
|
logging.basicConfig(
|
|
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
DOWNLOAD_DIR = "./downloads"
|
|
YT_DLP_PATH = "./yt-dlp"
|
|
DOWNLOADED_IDS_FILE = "./downloaded_ids.txt"
|
|
FAILED_FILE = "./failed.txt"
|
|
|
|
# Rate limiting configuration
|
|
DOWNLOAD_DELAY = 1 # Delay in seconds between downloads
|
|
|
|
|
|
def extract_tiktok_id(url: str) -> str | None:
|
|
"""
|
|
Extracts the TikTok video/photo ID from a URL.
|
|
|
|
Examples:
|
|
https://www.tiktok.com/@user/video/7500623452873723158 -> 7500623452873723158
|
|
https://www.tiktok.com/@user/photo/7500623452873723158 -> 7500623452873723158
|
|
"""
|
|
match = re.search(r"/(?:video|photo)/(\d+)", url)
|
|
return match.group(1) if match else None
|
|
|
|
|
|
def load_downloaded_ids() -> set:
|
|
"""Loads the set of already-downloaded TikTok IDs from disk."""
|
|
if not os.path.exists(DOWNLOADED_IDS_FILE):
|
|
return set()
|
|
with open(DOWNLOADED_IDS_FILE, "r") as f:
|
|
return set(line.strip() for line in f if line.strip())
|
|
|
|
|
|
def save_downloaded_id(video_id: str) -> None:
|
|
"""Appends a TikTok ID to the downloaded-ids tracking file."""
|
|
with open(DOWNLOADED_IDS_FILE, "a") as f:
|
|
f.write(video_id + "\n")
|
|
|
|
|
|
def log_failed_url(url: str) -> None:
|
|
"""Appends a failed URL to ./failed.txt."""
|
|
with open(FAILED_FILE, "a") as f:
|
|
f.write(url + "\n")
|
|
|
|
|
|
def download_video(url: str) -> str:
|
|
"""
|
|
Downloads a TikTok video using yt-dlp.
|
|
|
|
Args:
|
|
url (str): The TikTok video URL.
|
|
|
|
Returns:
|
|
str: Path to the downloaded video file.
|
|
"""
|
|
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
|
|
|
# First, get metadata to extract the publish date
|
|
metadata_cmd = [YT_DLP_PATH, "--no-check-certificate", "--dump-json", url]
|
|
|
|
metadata_result = subprocess.run(metadata_cmd, capture_output=True, text=True)
|
|
|
|
# Default template without date
|
|
output_template = os.path.join(DOWNLOAD_DIR, "%(id)s.%(ext)s")
|
|
|
|
# Try to extract date from metadata
|
|
try:
|
|
if metadata_result.returncode == 0:
|
|
metadata = json.loads(metadata_result.stdout)
|
|
|
|
# Extract the upload date if available
|
|
if "upload_date" in metadata:
|
|
# Format is typically YYYYMMDD
|
|
upload_date = metadata["upload_date"]
|
|
uploader = metadata["uploader"]
|
|
uploader_id = metadata["uploader_id"]
|
|
# You can reformat it if you want (e.g., YYYY-MM-DD)
|
|
formatted_date = (
|
|
f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
|
|
)
|
|
|
|
# Update the output template to include the date
|
|
output_template = os.path.join(
|
|
DOWNLOAD_DIR,
|
|
f"{formatted_date}_%(id)s_{uploader}_{uploader_id}.%(ext)s",
|
|
)
|
|
# logger.info(f"Using date format: {formatted_date}")
|
|
except Exception as e:
|
|
logger.error(f"Error parsing metadata: {str(e)}")
|
|
# Continue with the default template if there's an error
|
|
|
|
# Download the video with the determined output template
|
|
cmd = [
|
|
YT_DLP_PATH,
|
|
"--no-check-certificate",
|
|
"--format",
|
|
"bestvideo+bestaudio/best",
|
|
"--verbose",
|
|
"-o",
|
|
output_template,
|
|
url,
|
|
]
|
|
|
|
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
|
|
if result.returncode != 0:
|
|
logger.error(f"yt-dlp error: {result.stderr}")
|
|
return None
|
|
|
|
# Look for the file path in both stdout and stderr
|
|
full_output = result.stdout + result.stderr
|
|
|
|
# Try to find the destination file
|
|
filename = None
|
|
for line in full_output.split("\n"):
|
|
if "[download]" in line and "Destination:" in line:
|
|
parts = line.split("Destination:")
|
|
if len(parts) > 1:
|
|
filename = parts[1].strip()
|
|
break
|
|
|
|
# If we couldn't find it with the above method, try alternative approaches
|
|
if not filename:
|
|
# Look for the "[download] ... has already been downloaded" message
|
|
for line in full_output.split("\n"):
|
|
if "[download]" in line and "has already been downloaded" in line:
|
|
match = re.search(
|
|
r"\[download\] (.*?) has already been downloaded", line
|
|
)
|
|
if match:
|
|
filename = match.group(1)
|
|
break
|
|
|
|
# If we still couldn't find it, try to find any file in the download directory that was recently created
|
|
if not filename:
|
|
try:
|
|
files = [os.path.join(DOWNLOAD_DIR, f) for f in os.listdir(DOWNLOAD_DIR)]
|
|
if files:
|
|
newest_file = max(files, key=os.path.getctime)
|
|
if time.time() - os.path.getctime(newest_file) < 30:
|
|
filename = newest_file
|
|
except Exception as e:
|
|
logger.error(f"Error finding recent files: {str(e)}")
|
|
|
|
# logger.info(f"Found filename: {filename}")
|
|
|
|
if not filename or not os.path.exists(filename):
|
|
logger.error(f"Full yt-dlp output: {full_output}")
|
|
raise Exception("Failed to retrieve downloaded file")
|
|
|
|
return filename
|
|
|
|
|
|
def download_photo(url: str) -> List[str]:
|
|
"""
|
|
Downloads a TikTok photo slideshow and returns list of file paths.
|
|
|
|
Files are saved as: xxx1.jpg, xxx2.jpg, etc.
|
|
"""
|
|
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
|
|
|
# Get metadata to extract ID or date
|
|
metadata_cmd = [YT_DLP_PATH, "--no-check-certificate", "--dump-json", url]
|
|
metadata_result = subprocess.run(metadata_cmd, capture_output=True, text=True)
|
|
|
|
base_name = "xxx"
|
|
try:
|
|
if metadata_result.returncode == 0:
|
|
metadata = json.loads(metadata_result.stdout)
|
|
upload_date = metadata.get("upload_date", "")
|
|
if upload_date:
|
|
formatted_date = (
|
|
f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
|
|
)
|
|
base_name = f"{formatted_date}_xxx"
|
|
except Exception as e:
|
|
logger.warning(f"Could not parse metadata for photo naming: {e}")
|
|
|
|
# Output template for photos
|
|
output_template = os.path.join(
|
|
DOWNLOAD_DIR, f"{base_name}%(playlist_index)s.%(ext)s"
|
|
)
|
|
|
|
# Download command with best image quality
|
|
cmd = [
|
|
YT_DLP_PATH,
|
|
"--no-check-certificate",
|
|
"--format",
|
|
"bestvideo+bestaudio/best",
|
|
"-o",
|
|
output_template,
|
|
url,
|
|
]
|
|
|
|
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
|
|
if result.returncode != 0:
|
|
logger.error(f"yt-dlp error downloading photo: {result.stderr}")
|
|
raise Exception("Failed to download TikTok photo slideshow")
|
|
|
|
full_output = result.stdout + result.stderr
|
|
downloaded_files = []
|
|
|
|
# Parse downloaded files from output
|
|
for line in full_output.split("\n"):
|
|
if "[download]" in line and "Destination:" in line:
|
|
parts = line.split("Destination:")
|
|
if len(parts) > 1:
|
|
file_path = parts[1].strip()
|
|
downloaded_files.append(file_path)
|
|
|
|
if not downloaded_files:
|
|
logger.warning("No photo files were found in the output.")
|
|
|
|
return downloaded_files
|
|
|
|
|
|
def is_valid_tiktok_url(url: str) -> bool:
|
|
"""
|
|
Validates a TikTok URL.
|
|
|
|
Args:
|
|
url (str): The URL to validate.
|
|
|
|
Returns:
|
|
bool: True if valid, False otherwise.
|
|
"""
|
|
parsed = urlparse(url)
|
|
return (
|
|
parsed.scheme in ["http", "https"]
|
|
and "tiktok.com" in parsed.netloc
|
|
and ("/video/" in parsed.path or "/photo/" in parsed.path)
|
|
)
|
|
|
|
|
|
def is_tiktok_photo_url(url: str) -> bool:
|
|
"""
|
|
Checks if a TikTok URL points to a photo/slideshow post.
|
|
"""
|
|
parsed = urlparse(url)
|
|
return (
|
|
parsed.scheme in ["http", "https"]
|
|
and "tiktok.com" in parsed.netloc
|
|
and "/photo/" in parsed.path
|
|
)
|
|
|
|
|
|
def process_urls(urls: List[str]):
|
|
"""
|
|
Processes a list of TikTok URLs for downloading.
|
|
|
|
Args:
|
|
urls (List[str]): List of TikTok video URLs.
|
|
"""
|
|
valid_urls = [url.strip() for url in urls if is_valid_tiktok_url(url.strip())]
|
|
if not valid_urls:
|
|
logger.error("No valid TikTok URLs found.")
|
|
print("No valid TikTok URLs found.")
|
|
return
|
|
|
|
downloaded_ids = load_downloaded_ids()
|
|
|
|
for i, url in enumerate(valid_urls, start=1):
|
|
logger.info(f"Processing URL {i}/{len(valid_urls)}: {url}")
|
|
# print(f"Processing URL {i}/{len(valid_urls)}: {url}")
|
|
try:
|
|
# Extract ID and check if already downloaded
|
|
video_id = extract_tiktok_id(url)
|
|
if video_id and video_id in downloaded_ids:
|
|
logger.info(f"Skipping (already downloaded): {url}")
|
|
continue
|
|
|
|
if is_tiktok_photo_url(url):
|
|
photo_paths = download_photo(url)
|
|
for path in photo_paths:
|
|
logger.info(f"Downloaded photo: {path}")
|
|
else:
|
|
video_path = download_video(url)
|
|
logger.info(f"Downloaded video: {video_path}")
|
|
|
|
# Mark as downloaded
|
|
if video_id:
|
|
save_downloaded_id(video_id)
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error processing {url}: {str(e)}")
|
|
log_failed_url(url)
|
|
|
|
# Apply rate limiting
|
|
if i < len(valid_urls):
|
|
logger.info(f"Waiting {DOWNLOAD_DELAY} seconds before next download...")
|
|
time.sleep(DOWNLOAD_DELAY)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python downloader.py <url_or_input_file>")
|
|
sys.exit(1)
|
|
|
|
input_arg = sys.argv[1]
|
|
|
|
# Check if the input is a file
|
|
if os.path.isfile(input_arg):
|
|
try:
|
|
with open(input_arg, "r") as f:
|
|
urls = f.readlines()
|
|
logger.info(f"Processing URLs from file: {input_arg}")
|
|
process_urls(urls)
|
|
except Exception as e:
|
|
logger.error(f"Error reading input file: {str(e)}")
|
|
print(f"Error reading input file: {str(e)}")
|
|
else:
|
|
# Assume it's a single URL
|
|
urls = [input_arg]
|
|
process_urls(urls)
|