Guest User

Untitled

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