| import json | |
| import requests | |
| import os | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| import time | |
| from tqdm import tqdm | |
| import logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| def download_image(item): | |
| image_id = item['image_id'] | |
| prompt = item['prompt'] | |
| url = f"https://api.recraft.ai/image/{image_id}" | |
| output_dir = Path("downloaded_images") | |
| output_dir.mkdir(exist_ok=True) | |
| image_path = output_dir / f"{image_id}.jpg" | |
| prompt_path = output_dir / f"{image_id}.txt" | |
| try: | |
| if image_path.exists() and prompt_path.exists(): | |
| logger.info(f"File exists, skipping: {image_id}") | |
| return True | |
| response = requests.get(url) | |
| response.raise_for_status() | |
| with open(image_path, 'wb') as f: | |
| f.write(response.content) | |
| with open(prompt_path, 'w', encoding='utf-8') as f: | |
| f.write(prompt) | |
| logger.debug(f"Successfully downloaded: {image_id}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Download failed {image_id}: {str(e)}") | |
| return False | |
| def main(): | |
| print("=== Recraft Image Downloader ===") | |
| if not Path('merged.json').exists(): | |
| logger.error("merged.json file not found!") | |
| return | |
| try: | |
| with open('merged.json', 'r', encoding='utf-8') as f: | |
| data = json.load(f) | |
| except Exception as e: | |
| logger.error(f"Failed to read JSON file: {str(e)}") | |
| return | |
| total_images = len(data['recraft_images']) | |
| print(f"\nFound {total_images} images") | |
| user_input = input("\nStart downloading? (y/n): ") | |
| if user_input.lower() != 'y': | |
| print("Download cancelled") | |
| return | |
| success_count = 0 | |
| start_time = time.time() | |
| print("\nStarting download...") | |
| with ThreadPoolExecutor(max_workers=10) as executor: | |
| results = list(tqdm( | |
| executor.map(download_image, data['recraft_images']), | |
| total=total_images, | |
| desc="Download Progress", | |
| unit="images" | |
| )) | |
| success_count = sum(results) | |
| end_time = time.time() | |
| print("\n=== Download Complete! ===") | |
| print(f"Success: {success_count} images") | |
| print(f"Failed: {total_images - success_count} images") | |
| print(f"Total time: {end_time - start_time:.2f} seconds") | |
| print(f"Average speed: {total_images / (end_time - start_time):.2f} images/sec") | |
| if __name__ == "__main__": | |
| main() | |