import os import sys import time import urllib.request from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from tqdm import tqdm def get_direct_url(url: str) -> tuple[str, int]: """Follows redirects and retrieves the final URL and total content length.""" req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) with urllib.request.urlopen(req) as resp: direct_url = resp.geturl() content_length = int(resp.headers.get("Content-Length", 0)) return direct_url, content_length def download_chunk(url: str, start: int, end: int, output_path: str, chunk_id: int): req = urllib.request.Request(url, headers={ "User-Agent": "Mozilla/5.0", "Range": f"bytes={start}-{end}" }) with urllib.request.urlopen(req) as resp: data = resp.read() with open(output_path, "r+b") as f: f.seek(start) f.write(data) return len(data) def download_file_parallel(url: str, dest_path: Path, num_threads: int = 8, chunk_size_mb: int = 16): dest_path.parent.mkdir(parents=True, exist_ok=True) temp_path = dest_path.with_suffix(dest_path.suffix + ".part") print(f"\nResolving URL: {url} ...") direct_url, total_size = get_direct_url(url) print(f"Target: {dest_path.name} | Total size: {total_size / (1024*1024):.2f} MB ({total_size / (1024**3):.2f} GB)") if dest_path.exists() and dest_path.stat().st_size == total_size: print(f"File already exists with matching size: {dest_path}") return dest_path # Initialize empty file if not exists or size mismatch if not temp_path.exists() or temp_path.stat().st_size != total_size: print(f"Preallocating file {temp_path.name} ({total_size} bytes)...") with open(temp_path, "wb") as f: f.truncate(total_size) chunk_size = chunk_size_mb * 1024 * 1024 chunks = [] for start in range(0, total_size, chunk_size): end = min(start + chunk_size - 1, total_size - 1) chunks.append((start, end)) print(f"Downloading {len(chunks)} chunks with {num_threads} worker threads...") start_time = time.time() downloaded_bytes = 0 with tqdm(total=total_size, unit="B", unit_scale=True, desc=dest_path.name) as pbar: with ThreadPoolExecutor(max_workers=num_threads) as executor: future_to_chunk = { executor.submit(download_chunk, direct_url, s, e, str(temp_path), idx): (s, e) for idx, (s, e) in enumerate(chunks) } for future in as_completed(future_to_chunk): nbytes = future.result() downloaded_bytes += nbytes pbar.update(nbytes) duration = time.time() - start_time print(f"\nDownload completed in {duration:.1f}s ({downloaded_bytes / (1024*1024) / duration:.2f} MB/s)") temp_path.rename(dest_path) return dest_path if __name__ == "__main__": if len(sys.argv) < 3: print("Usage: python download_parallel.py [num_threads]") sys.exit(1) url = sys.argv[1] dest = Path(sys.argv[2]) threads = int(sys.argv[3]) if len(sys.argv) > 3 else 8 download_file_parallel(url, dest, num_threads=threads)