dmaneja

ChickenSmoothie.py

Aug 12th, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.08 KB | None | 0 0
  1. ## Last edited August 17, 2018
  2. ## Use for CS Rarity List
  3.  
  4. import io
  5. import os
  6. import sys
  7. import urllib.request
  8. import json
  9. import requests
  10. import re
  11.  
  12. from PIL import Image, ImageChops
  13. from requests.packages.urllib3.util.retry import Retry
  14. from requests.adapters import HTTPAdapter
  15.  
  16. ## pip install Pillow
  17. ## pip install requests
  18. ## pip install -U pyopenssl
  19.  
  20. REFERENCE_DIR = "reference_images"
  21. PET_IMAGE_URL = "https://www.chickensmoothie.com/pet/%s&trans=1&noitems=1.jpg"
  22. UNKNOWN_key = "UNKNOWN"
  23. ERROR_key = "ERROR"
  24. directory = {}
  25. petCount = {}
  26. ONLINE = "your account to get HTML";
  27. VERYRARE = '/img/rarity/veryrare.png'
  28. OMGSR = '/img/rarity/omgsorare.png'
  29. onlineIDs = ''
  30.    
  31.  
  32. def url(start,instancenum):     #grab URL of pet
  33.     URL = "https://www.chickensmoothie.com/viewpet.php?id="+str(start)+".xml:443"
  34.     # response = requests.get(URL,allow_redirects=False, stream=False,timeout=None)
  35.     with requests.Session() as s:
  36.         retry = Retry(connect=5, read=5, redirect=1, backoff_factor=0.5)
  37.         adapter = HTTPAdapter(max_retries=retry)
  38.         s.mount('http://',adapter)
  39.         s.mount('https://',adapter)
  40.         r = s.get(URL,allow_redirects=False, stream=False, timeout=3.05)
  41.         with open('site_'+instancenum+'.xml','wb')as file:
  42.             file.write(r.content)   #response.content
  43.             file.close()
  44.         s.close()
  45.  
  46.  
  47. def defineOnline(start_id, end_id,onlineIDs,instancenum):
  48.     isWanted = False
  49.     isOnline = False
  50.     start_id = int(start_id)
  51.     end_id = int(end_id)+1
  52.     while(start_id<end_id):
  53.         url(start_id,instancenum)
  54.         with open('site_'+instancenum+'.xml',encoding="utf8") as petfile:
  55.             print ("Checking:",str(start_id))
  56.             for line in petfile:
  57.                 if VERYRARE in line or OMGSR in line:
  58.                     isWanted = True
  59.                     print ('\tVR or OMGSR')
  60.                 if ONLINE in line:
  61.                     isOnline = True
  62.                     print ("\t"+str(start_id)+" is ONLINE")
  63.             if isWanted is True and isOnline is True:
  64.                 onlineIDs += str(start_id)+"\n"
  65.             petfile.close()
  66.         start_id += 1
  67.         isWanted = False
  68.         isOnline = False
  69.     with open('onlineIDs_'+str(instancenum)+'.txt','w')as idfile:
  70.         for id in onlineIDs:
  71.             idfile.write("%s"%id)
  72.         idfile.close()
  73.  
  74.  
  75. def processLine(line):
  76.         id_key_list = line.split(',')
  77.         #print (id_key_list)
  78.         ids = id_key_list[0].split(',')
  79.         id = ids[0]
  80.         keys = id_key_list[1].split('\n')
  81.         key = keys[0]
  82.         print (key, id)
  83.         id = directory.get(key)
  84.         # print (id)
  85.         count(key,id)
  86.        
  87.        
  88. def createDirectory():      #creates ID directory
  89.     with open('CS Code Directory.txt')as file: #or .csv
  90.         for line in file:
  91.             array = []
  92.             updated = line.split(",")
  93.             array.append(updated)
  94.             directory[array[0][2]] = array[0][1]    #pet key : pet name
  95.         file.close()
  96.  
  97. def count(key,id):
  98.     if key in directory:
  99.         if petCount.get(id) is None:
  100.             petCount[id] = 0
  101.         petCount[id] += 1
  102.  
  103. def countfile(start_id,end_id,instancenum):
  104.  
  105.     with open('onlineIDs_'+instancenum+'_out_['+str(start_id)+','+str(end_id)+'].txt','r') as f:
  106.         for line in f:
  107.             processLine(line)
  108.         f.close()
  109.     with open('['+start_id+','+end_id+'].txt', 'w') as file:
  110.         file.write(json.dumps(petCount,sort_keys=True,separators=('',': '),indent=3))
  111.         file.write('\n\nRANGE: ['+start_id+', '+end_id+']')
  112.         file.close()
  113. ###############
  114.  
  115. def crop(img):
  116.   """Remove part of the pet that says "___'s pet and transparent edges."""
  117.   w, h = img.size
  118.  
  119.   h = h - 9
  120.   img = img.crop((0, 0, w, h))
  121.  
  122.   # Get cropping border
  123.   left = w
  124.   top = h
  125.   right = 0
  126.   bottom = 0
  127.  
  128.   img_data = img.getdata()
  129.   # Loop from left->right and top->bottom to get the left/top cropping borders.
  130.   for i_h in range(h):
  131.     for i_w in range(w):
  132.       if img_data[i_w + i_h * w] == (0, 0, 0, 0):
  133.         continue
  134.       top = min(top, i_h)
  135.       left = min(left, i_w)
  136.       break
  137.  
  138.   # Loop from right->left and bottom->top to get the right/bottom cropping
  139.   # borders.
  140.   for i_h in range(h - 1, 0, -1):
  141.     for i_w in range(w - 1, 0, -1):
  142.       if img_data[i_w + i_h * w] == (0, 0, 0, 0):
  143.         continue
  144.       bottom = max(bottom, i_h)
  145.       right = max(right, i_w)
  146.       break
  147.  
  148.   img = img.crop((left, top, right, bottom))
  149.   return img
  150.  
  151. def download_image(img_url):
  152.     """Downloads an image from a URL and returns an `Image` object."""
  153.     with urllib.request.urlopen(img_url) as url:
  154.         f = io.BytesIO(url.read())
  155.     return Image.open(f)
  156.  
  157.  
  158. def equal(image1, image2):
  159.     """Checks that 2 images are exactly the same."""
  160.     return ImageChops.difference(image1, image2).getbbox() is None
  161.  
  162.  
  163. class PetReference(object):
  164.     def __init__(self, reference_dir):
  165.         self.reference_dir = reference_dir
  166.  
  167.         # Map string pet key/code to an Image
  168.         self.key_to_image = {}
  169.  
  170.         # Maps int tuple of (width, height) to a list of pet keys
  171.         self.size_to_key = {}
  172.  
  173.         for img_file in os.listdir(reference_dir):
  174.             pet_key = img_file.split('.')[0]
  175.             img = crop(Image.open(os.path.join(reference_dir, img_file)))
  176.             size = img.size
  177.  
  178.             self.key_to_image[pet_key] = img
  179.             if size not in self.size_to_key:
  180.                 self.size_to_key[size] = []
  181.             self.size_to_key[size].append(pet_key)
  182.  
  183.     def get_key(self, pet_id):
  184.         # Assert pet_id is an integer
  185.         assert isinstance(pet_id, int), "Pet ID must be an integer"
  186.         image_url = PET_IMAGE_URL % pet_id
  187.         downloaded_img = crop(download_image(image_url))
  188.  
  189.         size = downloaded_img.size
  190.  
  191.         if size in self.size_to_key:
  192.             for pet_key in self.size_to_key[size]:
  193.                 img = self.key_to_image[pet_key]
  194.                 if equal(img, downloaded_img):
  195.                     return pet_key
  196.  
  197.         return UNKNOWN_key
  198.  
  199.  
  200. def main(args):
  201.     # if len(args) < 2:
  202.         # print("Please enter an input file. Quitting.")
  203.         # sys.exit(0)  
  204.     ref = PetReference(REFERENCE_DIR)
  205.     createDirectory()
  206.  
  207.    
  208.     start_id = args[1]
  209.     end_id = args[2]
  210.     instancenum = args[3]
  211.     input_file = 'onlineIDs_'+instancenum+'.txt'
  212.     id = int(start_id)
  213.     print (start_id, end_id)
  214.     defineOnline(start_id,end_id,onlineIDs,instancenum)
  215.    
  216.     output_file = os.path.basename(input_file).split('.')[0] + "_out_["+start_id+","+end_id+"].txt"
  217.  
  218.     errors = []
  219.     with open('inputfile.txt','w') as filename:
  220.         while(id<int(end_id)):
  221.             filename.write("%s\n"%str(id))
  222.             id+=1
  223.         filename.write("%s\n"%str(end_id))
  224.     filename.close()
  225.  
  226.     with open(input_file, 'r') as f:
  227.         with open(output_file, 'w') as w:
  228.             for line in f:
  229.                 pet_id = line.strip()
  230.                 if not pet_id:
  231.                     continue
  232.  
  233.                 print("Identifying pet", pet_id)
  234.                 try:
  235.                     pet_id = int(pet_id)
  236.                     pet_key = ref.get_key(pet_id)
  237.                 except Exception as e:
  238.                     print("\tSkipped %s because there was an error.")
  239.                     errors.append((pet_id, e))
  240.                     pet_key = ERROR_key
  241.                 if pet_key in directory:
  242.                     w.write("%s,%s,%s\n" % (pet_id, pet_key, directory.get(pet_key)))
  243.                 else:
  244.                     w.write("%s,%s\n" % (pet_id, pet_key))
  245.  
  246.     if errors:
  247.         print("List of all errors")
  248.         for pet_id, e in errors:
  249.             print("\nPet ID:", pet_id)
  250.             print(e)
  251.  
  252.  
  253. # createDirectory()
  254.     countfile(start_id,end_id,instancenum)
  255. # print(directory)
  256. # print(petCount)
  257.    
  258.    
  259.     print ("FINISHED")
  260.     print ('---> Check \"onlineIDs_'+instancenum+'_out_['+str(start_id)+','+str(end_id)+'].txt\" for any pet IDs with UNKNOWN')
  261.     print ("---> Results: \"["+start_id+','+end_id+'].txt\"')
  262.  
  263.  
  264.    
  265.    
  266.  
  267. if __name__ == "__main__":
  268.     main(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment