Borealum

CIVITAI collection dowload script

Feb 22nd, 2025 (edited)
729
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.69 KB | Source Code | 1 0
  1. #CIVITAI collection dowload
  2. import requests
  3. import os
  4. import json
  5. import urllib
  6.  
  7. ###
  8. #SET THIS STUFF AS NEEDED
  9. collectionID = 8022086
  10. myApiKey = 'apiapiapi564687apiapi' #<YOUR api key
  11. folderName = './downloadedImages/'
  12. ###
  13.  
  14. def processPage(url, first=False):
  15.     try:
  16.         response = requests.get(url, headers=requestHeaders)
  17.         response.raise_for_status()
  18.         responseJson = response.json()
  19.         nextCursor = responseJson['result']['data']['json']['nextCursor']
  20.         items = responseJson['result']['data']['json']['items']
  21.         print()
  22.         print('count of images in batch', len(items))
  23.         for item in items:
  24.             try:
  25.                 imageName = item['name'].replace('/', '')#sometimes '/' is at start, sometimes isn't
  26.                 fileType = item['mimeType'].split('/')[1]
  27.                 destination = folderName+imageName
  28.                 if('.' not in imageName):#sometimes "name" doesnt contain fileextension
  29.                     destination += '.' + fileType
  30.                 if(os.path.isfile(destination)):
  31.                     print(destination+' already exists, skipping download')
  32.                 else:
  33.                     url = 'https://image.civitai.com/'+myApiKey+'/'+item['url']+'/'+imageName
  34.                     print('downloading image from url', url)            
  35.                     with requests.get(url, stream=True) as response:
  36.                         response.raise_for_status()
  37.                         with open(destination, 'wb') as f:
  38.                             for chunk in response.iter_content():
  39.                                 f.write(chunk)
  40.                     print('saved to: '+destination)
  41.             except Exception as Y:
  42.                 print(Y)
  43.                 print("Image download failed")
  44.     except Exception as X:
  45.         print(X)
  46.         if first:
  47.             input("First page request failed, Press Enter to exit...")
  48.             sys.exit()
  49.         else:
  50.             print("Page request failed")
  51.     print('batch done, next cursor', nextCursor)
  52.     return nextCursor
  53.  
  54. print('your api key:',myApiKey)
  55. print('downloading collection ID:',collectionID)
  56. print('output folder:',folderName)
  57. os.makedirs(folderName, exist_ok=True)
  58. requestHeaders = {'Authorization': 'Bearer '+myApiKey}
  59.  
  60. #urlString = '%7B%22json%22%3A%7B%22collectionId%22%3A4192940%2C%22period%22%3A%22AllTime%22%2C%22sort%22%3A%22Newest%22%2C%22browsingLevel%22%3A31%2C%22include%22%3A%5B%22cosmetics%22%5D%2C%22cursor%22%3Anull%2C%22authed%22%3Atrue%7D%2C%22meta%22%3A%7B%22values%22%3A%7B%22cursor%22%3A%5B%22undefined%22%5D%7D%7D%7D'
  61. #decoded = urllib.parse.unquote(urlString)
  62. #print('decoded',decoded)
  63.  
  64. requestData = {
  65.     "json":{
  66.         "collectionId":collectionID,
  67.         "period":"AllTime",
  68.         "sort":"Newest",
  69.         "browsingLevel":31,# = 1(PG) + 2(PG-13) + 4(R) + 8(X) + 16(XXX)
  70.         "include":["cosmetics"],
  71.         "cursor":None,
  72.         "authed":True
  73.     },
  74.     "meta":{"values":{"cursor":["undefined"]}}
  75. }
  76.  
  77. #urlString2 = urllib.parse.quote(json.dumps(requestData,separators=(',', ':')))
  78. #print('urlString',urlString)
  79. #print('urlStrjng',urlString2)
  80. #print('dump',json.dumps(requestData))
  81.  
  82. url = 'https://civitai.com/api/trpc/image.getInfinite?input=' + urllib.parse.quote(json.dumps(requestData,separators=(',', ':')))
  83. nextCursor = processPage(url, True)
  84. del requestData["meta"] #delete "meta" part, only used in first request
  85.  
  86. while(nextCursor!=None):
  87.     requestData['json']['cursor'] = nextCursor
  88.     url = 'https://civitai.com/api/trpc/image.getInfinite?input=' + urllib.parse.quote(json.dumps(requestData,separators=(',', ':')))
  89.     nextCursor = processPage(url)
  90.    
  91. input("All done, Press Enter to finish...")
Advertisement
Add Comment
Please, Sign In to add comment