Guest User

Untitled

a guest
Apr 2nd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.95 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 len(pixel) < 4 or pixel[3] > 0:
  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. old_color = data["color"] if "color" in data else 0
  87. if old_color == new_color:
  88. print("{}: skipping, color #{} set by {}".format(message, new_color, data[
  89. "user_name"] if "user_name" in data else "<nobody>"))
  90. time.sleep(.25)
  91. else:
  92. print("{}: Placing color #{}".format(message, new_color, ax, ay))
  93. r = s.post("https://www.reddit.com/api/place/draw.json",
  94. data={"x": str(ax), "y": str(ay), "color": str(new_color)})
  95.  
  96. secs = float(r.json()["wait_seconds"])
  97. if "error" not in r.json():
  98. message = "Placed color, waiting {} seconds. {}% complete."
  99. else:
  100. message = "Cooldown already active - waiting {} seconds. {}% complete."
  101. waitTime = int(secs) + 2
  102. while(waitTime > 0):
  103. m = message.format(waitTime, percent)
  104. time.sleep(1)
  105. waitTime -= 1
  106. if waitTime > 0:
  107. print(m, end=" \r")
  108. else:
  109. print(m)
  110. update_image()
  111. if "error" in r.json():
  112. place_pixel(ax, ay, new_color)
  113.  
  114. # From: http://stackoverflow.com/questions/27337784/how-do-i-shuffle-a-multidimensional-list-in-python
  115. def shuffle2d(arr2d, rand=random):
  116. """Shuffes entries of 2-d array arr2d, preserving shape."""
  117. reshape = []
  118. data = []
  119. iend = 0
  120. for row in arr2d:
  121. data.extend(row)
  122. istart, iend = iend, iend+len(row)
  123. reshape.append((istart, iend))
  124. rand.shuffle(data)
  125. return [data[istart:iend] for (istart,iend) in reshape]
  126.  
  127. while True:
  128. print("starting image placement for img height: {}, width: {}".format(img.height, img.width))
  129. arr2d = shuffle2d([[[i,j] for i in range(img.width)] for j in range(img.height)])
  130. total = img.width * img.height
  131. checked = 0
  132. for y in range(img.width ):
  133. for x in range(img.height ):
  134. xx = arr2d[x][y]
  135. pixel = img.getpixel((xx[0], xx[1]))
  136.  
  137. if True:
  138. pal = find_palette((pixel[0], pixel[1], pixel[2]))
  139.  
  140. ax = xx[0] + origin[0]
  141. ay = xx[1] + origin[1]
  142.  
  143. place_pixel(ax, ay, pal)
  144. checked += 1
  145. percent = round((checked/total) * 100, 2)
  146. message = "All pixels placed, sleeping {}s..."
  147. waitTime = 60
  148. while(waitTime > 0):
  149. m = message.format(waitTime)
  150. time.sleep(1)
  151. waitTime -= 1
  152. if waitTime > 0:
  153. print(m, end=" \r")
  154. else:
  155. print(m)
Add Comment
Please, Sign In to add comment