File size: 1,859 Bytes
1c1f3a2 14ea209 1c1f3a2 14ea209 1c1f3a2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import requests
from PIL import Image, PngImagePlugin
from io import BytesIO
import json
import os
import time
import get_token
import requests
def get_json(id):
url = f"https://api.cosmo.fans/objekt/v1/token/{id}"
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return {"error": "Request failed with status code " + str(response.status_code)}
# Function to fetch image with retries
def fetch_image_with_retries(url, retries=3, delay=5):
for i in range(retries):
try:
response = requests.get(url)
response.raise_for_status()
return Image.open(BytesIO(response.content))
except requests.exceptions.RequestException as e:
print(f"Attempt {i+1} failed: {e}")
time.sleep(delay)
raise Exception("Failed to fetch image after several attempts")
def download_img(token_id, folder_name):
response_json = get_json(token_id)
# Check if 'objekt' key exists in the response
if 'objekt' in response_json and 'thumbnailImage' in response_json['objekt']:
thumbnail_url = response_json['objekt']['thumbnailImage']
name = response_json.get('name', 'Unknown') # Use 'Unknown' if 'name' key is not found
class_nft = response_json['objekt']['class'] # Use 'Unknown' if 'name' key is not found
# Fetching the thumbnail image
img = fetch_image_with_retries(thumbnail_url)
# Adding metadata
meta = PngImagePlugin.PngInfo()
meta.add_text("name", f"{name} {class_nft}")
# Saving the image with tokenId as filename
filename = f"./{folder_name}/{token_id}.png"
img.save(filename, pnginfo=meta)
else:
print(f"Key 'objekt' or 'thumbnailImage' not found in response for token_id {token_id}. Skipping...")
|