Guest User

Untitled

a guest
Apr 3rd, 2017
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.57 KB | None | 0 0
  1. import html
  2. import json
  3. import math
  4. import random
  5. import re
  6. import sys
  7. import time
  8. from io import BytesIO
  9. from urllib.request import urlopen
  10.  
  11. import requests
  12. from PIL import Image
  13. from requests.adapters import HTTPAdapter
  14.  
  15. username = sys.argv[1]
  16. password = sys.argv[2]
  17. percent = 0
  18.  
  19. s = requests.Session()
  20. s.mount('https://www.reddit.com', HTTPAdapter(max_retries=5))
  21. s.headers["User-Agent"] = "PlacePlacer"
  22. r = s.post("https://www.reddit.com/api/login/{}".format(username),
  23.            data={"user": username, "passwd": password, "api_type": "json"})
  24. s.headers['x-modhash'] = r.json()["json"]["data"]["modhash"]
  25.  
  26. wiki_info = None
  27.  
  28. def update_image():
  29.     global img, origin, wiki_info
  30.  
  31.     text = s.get('https://www.reddit.com/r/Quebec/wiki/place')
  32.     while (text.status_code != 200):
  33.             s.get('https://www.reddit.com/r/Quebec/wiki/place')
  34.                      
  35.     wiki_data = text.content.decode()
  36.     js = re.findall(r'''({"origine":.*?})''', html.unescape(wiki_data))[0]
  37.     data = json.loads(js)
  38.     if data == wiki_info:
  39.         return False
  40.     else:
  41.         wiki_info = data
  42.     data['url'] = 'https://' + data['url']
  43.  
  44.     img = Image.open(BytesIO(urlopen(data['url']).read()))
  45.     origin = (data['origine'][0], data['origine'][1])
  46.  
  47.     print("URL: {}, origine: {}".format(data['url'], data['origine']))
  48.  
  49.     return True
  50.  
  51. update_image()
  52.  
  53. def find_palette(point):
  54.     rgb_code_dictionary = {
  55.         (255, 255, 255): 0,
  56.         (228, 228, 228): 1,
  57.         (136, 136, 136): 2,
  58.         (34, 34, 34): 3,
  59.         (255, 167, 209): 4,
  60.         (229, 0, 0): 5,
  61.         (229, 149, 0): 6,
  62.         (160, 106, 66): 7,
  63.         (229, 217, 0): 8,
  64.         (148, 224, 68): 9,
  65.         (2, 190, 1): 10,
  66.         (0, 211, 211): 11,
  67.         (0, 131, 199): 12,
  68.         (0, 0, 234): 13,
  69.         (207, 110, 228): 14,
  70.         (130, 0, 128): 15
  71.     }
  72.  
  73.     def distance(c1, c2):
  74.         (r1, g1, b1) = c1
  75.         (r2, g2, b2) = c2
  76.         return math.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)
  77.  
  78.     colors = list(rgb_code_dictionary.keys())
  79.     closest_colors = sorted(colors, key=lambda color: distance(color, point))
  80.     closest_color = closest_colors[0]
  81.     code = rgb_code_dictionary[closest_color]
  82.     return code
  83.  
  84.  
  85. def place_pixel(ax, ay, new_color):
  86.     message = "Probing absolute pixel {},{}".format(ax, ay)
  87.  
  88.     while True:
  89.         r = s.get("http://reddit.com/api/place/pixel.json?x={}&y={}".format(ax, ay), timeout=5)
  90.         if r.status_code == 200:
  91.             data = r.json()
  92.             break
  93.         else:
  94.             print("ERROR: ", r, r.text)
  95.         time.sleep(5)
  96.  
  97.     try:
  98.         old_color = data["color"] if "color" in data else 0
  99.     except:
  100.         return
  101.  
  102.     if old_color == new_color:
  103.         print("{}: skipping, color #{} set by {}".format(message, new_color, data[
  104.             "user_name"] if "user_name" in data else "<nobody>"))
  105.         time.sleep(.25)
  106.     else:
  107.         print("{}: Placing color #{}".format(message, new_color, ax, ay))
  108.         r = s.post("https://www.reddit.com/api/place/draw.json",
  109.                    data={"x": str(ax), "y": str(ay), "color": str(new_color)})
  110.  
  111.         secs = float(r.json()["wait_seconds"])
  112.         if "error" not in r.json():
  113.             message = "Placed color, waiting {} seconds. {}% complete."
  114.         else:
  115.             message = "Cooldown already active - waiting {} seconds. {}% complete."
  116.         waitTime = int(secs) + 2
  117.         while(waitTime > 0):
  118.             m = message.format(waitTime, percent)
  119.             time.sleep(1)
  120.             waitTime -= 1
  121.             if waitTime > 0:
  122.                 print(m, end="              \r")
  123.             else:
  124.                 print(m)
  125.         if update_image():
  126.             return False
  127.         if "error" in r.json():
  128.             place_pixel(ax, ay, new_color)
  129.     return True
  130.  
  131. # From: http://stackoverflow.com/questions/27337784/how-do-i-shuffle-a-multidimensional-list-in-python
  132. def shuffle2d(arr2d, rand=random):
  133.     """Shuffes entries of 2-d array arr2d, preserving shape."""
  134.     reshape = []
  135.     data = []
  136.     iend = 0
  137.     for row in arr2d:
  138.         data.extend(row)
  139.         istart, iend = iend, iend+len(row)
  140.         reshape.append((istart, iend))
  141.     rand.shuffle(data)
  142.     return [data[istart:iend] for (istart,iend) in reshape]
  143.  
  144. class RestartTheLoop(Exception):
  145.     pass
  146.  
  147. while True:
  148.     try:
  149.         print("starting image placement for img height: {}, width: {}".format(img.height, img.width))
  150.         arr2d = shuffle2d([[[i,j] for i in range(img.width)] for j in range(img.height)])
  151.         total = img.width * img.height
  152.         checked = 0
  153.         for x in range(img.width ):
  154.             for y in range(img.height ):
  155.                 xx = arr2d[x][y]
  156.                 pixel = img.getpixel((xx[0], xx[1]))
  157.  
  158.                 if pixel[3] > 0:  # Check if the pixel should be transparent
  159.                     pal = find_palette((pixel[0], pixel[1], pixel[2]))
  160.  
  161.                     ax = xx[0] + origin[0]
  162.                     ay = xx[1] + origin[1]
  163.  
  164.                     if not place_pixel(ax, ay, pal):
  165.                         raise RestartTheLoop()
  166.                     checked += 1
  167.                     percent = round((checked/total) * 100, 2)
  168.         message = "All pixels placed, sleeping {}s..."
  169.         waitTime = 60
  170.         while(waitTime > 0):
  171.             m = message.format(waitTime)
  172.             time.sleep(1)
  173.             waitTime -= 1
  174.             if waitTime > 0:
  175.                 print(m, end="              \r")
  176.             else:
  177.                 print(m)
  178.     except RestartTheLoop:
  179.         pass
Add Comment
Please, Sign In to add comment