anim_ingest.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import io
  2. import math
  3. import itertools
  4. from multiprocessing import Pool
  5. import multiprocessing
  6. from typing import Callable, NamedTuple
  7. from PIL import Image
  8. from bs4 import BeautifulSoup
  9. from colorspacious import cspace_convert
  10. from scipy.cluster import vq
  11. import requests
  12. import numpy as np
  13. import ingest
  14. cluster_seed = 20220328
  15. cluster_attempts = 10
  16. base = "https://play.pokemonshowdown.com/sprites/ani/"
  17. back_base = "https://play.pokemonshowdown.com/sprites/ani-back/"
  18. # removing all forms of a pokemon, and also pokestars
  19. start_with_filters = [
  20. # no significant visual changes
  21. "arceus-", "silvally-", "genesect-", "pumpkaboo-", "gourgeist-", "unown-", "giratina-",
  22. # cannot start the battle in alternate form
  23. "castform-", "cherrim-", "aegislash-", "xerneas-", "wishiwashi-", "eiscue-", "mimikyu-",
  24. "cramorant-", "morepeko-",
  25. # weird event thing
  26. "greninja-", "eevee-", "pikachu-", "zarude-", "magearna-",
  27. # pokestars
  28. "pokestar",
  29. ]
  30. # removing all forms of a type
  31. end_with_filters = [
  32. "-mega.gif", "-megax.gif", "-megay.gif", "-primal.gif", "-ultra.gif",
  33. "-gmax.gif", "-eternamax.gif", "-totem.gif", "-f.gif", "-b.gif",
  34. ]
  35. # removing pokemon entirely
  36. full_filters = [
  37. # darmanitan zen forms (cannot start in zen)
  38. "darmanitan-galarzen.gif", "darmanitan-zen.gif",
  39. # morpeko hangry (cannot start hangry)
  40. "morpeko-hangry.gif",
  41. # minior core forms (cannot start in anything but -meteor, renamed below)
  42. "minior.gif", "minior-blue.gif", "minior-green.gif", "minior-indigo.gif",
  43. "minior-orange.gif", "minior-violet.gif", "minior-yellow.gif",
  44. # because it is a create-a-pokemon
  45. "astrolotl.gif", "aurumoth.gif", "caribolt.gif", "cawmodore.gif", "chromera.gif", "crucibelle.gif",
  46. "equilibra.gif", "fidgit.gif", "jumbao.gif", "justyke.gif", "kerfluffle.gif", "kitsunoh.gif",
  47. "krilowatt.gif", "malaconda.gif", "miasmaw.gif", "mollux.gif", "naviathan.gif", "necturna.gif",
  48. "pajantom.gif", "plasmanta.gif", "pluffle.gif", "protowatt.gif", "scratchet.gif", "smogecko.gif",
  49. "smoguana.gif", "smokomodo.gif", "snaelstrom.gif", "stratagem.gif", "tomohawk.gif", "volkraken.gif", "voodoom.gif",
  50. # typos/duplicates
  51. "buffalant.gif", "klinklang-back.gif", "krikretot.gif",
  52. "pumpkabo-super.gif", "magcargo%20.gif", "meowstic-female.gif",
  53. "ratatta-a.gif", "ratatta-alola.gif", "raticate-a.gif",
  54. "rotom-h.gif", "rotom-m.gif", "rotom-s.gif", "rotom-w.gif",
  55. # not a pokemon
  56. "substitute.gif",
  57. ]
  58. # force certain pokemon to stay
  59. force_keep = [ "meowstic-f.gif", "unfezant-f.gif", "pyroar-f.gif" ]
  60. # rename certain pokemon after the fact
  61. rename = {
  62. # dash consistency
  63. "nidoranm": "nidoran-m",
  64. "nidoranf": "nidoran-f",
  65. "porygonz": "porygon-z",
  66. "tapubulu": "tapu-bulu",
  67. "tapufini": "tapu-fini",
  68. "tapukoko": "tapu-koko",
  69. "tapulele": "tapu-lele",
  70. "hooh": "ho-oh",
  71. "mimejr": "mime-jr",
  72. "mrmime": "mr-mime",
  73. "mrmime-galar": "mr-mime-galar",
  74. "mrrime": "mr-rime",
  75. "jangmoo": "jangmo-o",
  76. "hakamoo": "hakamo-o",
  77. "kommoo": "kommo-o",
  78. "typenull": "type-null",
  79. "oricorio-pompom": "oricorio-pom-pom",
  80. "necrozma-duskmane": "necrozma-dusk-mane",
  81. "necrozma-dawnwings": "necrozma-dawn-wings",
  82. "toxtricity-lowkey": "toxtricity-low-key",
  83. # rename forms
  84. "shellos": "shellos-west",
  85. "shaymin": "shaymin-land",
  86. "meloetta": "meloetta-aria",
  87. "keldeo": "keldeo-ordinary",
  88. "hoopa": "hoopa-confined",
  89. "burmy": "burmy-plant",
  90. "wormadam": "wormadam-plant",
  91. "deerling": "deerling-spring",
  92. "sawsbuck": "sawsbuck-spring",
  93. "vivillon": "vivillon-meadow",
  94. "basculin": "basculin-redstriped",
  95. "meowstic": "meowstic-male",
  96. "meowstic-f": "meowstic-female",
  97. "pyroar-f": "pyroar-female",
  98. "flabebe": "flabebe-red",
  99. "floette": "floette-red",
  100. "florges": "florges-red",
  101. "minior-meteor": "minior",
  102. "sinistea": "sinistea-phony",
  103. "polteageist": "polteageist-phony",
  104. "gastrodon": "gastrodon-west",
  105. "furfrou": "furfrou-natural",
  106. "wishiwashi": "wishiwashi-school",
  107. "tornadus": "tornadus-incarnate",
  108. "landorus": "landorus-incarnate",
  109. "thundurus": "thundurus-incarnate",
  110. "calyrex-ice": "calyrex-ice-rider",
  111. "calyrex-shadow": "calyrex-shadow-rider",
  112. "urshifu-rapidstrike": "urshifu-rapid-strike",
  113. "zacian": "zacian-hero",
  114. "zamazenta": "zamazenta-hero",
  115. }
  116. def get_all_pokemon() -> list[str]:
  117. soup = BeautifulSoup(requests.get(back_base).text, "html.parser")
  118. gifs = [href for a in soup.find_all("a") if (href := a.get("href")).endswith("gif")]
  119. return [
  120. g[:-4]
  121. for g in gifs
  122. if g in force_keep or (
  123. g not in full_filters
  124. and not any(g.startswith(f) for f in start_with_filters)
  125. and not any(g.endswith(f) for f in end_with_filters)
  126. )
  127. ]
  128. def load_image(base: str, name: str) -> Image:
  129. return Image.open(io.BytesIO(requests.get(base + name + ".gif").content))
  130. def get_all_pixels(im: Image) -> list[tuple[int, int, int]]:
  131. rgb_pixels = []
  132. for fr in range(getattr(im, "n_frames", 1)):
  133. im.seek(fr)
  134. rgb_pixels += [
  135. (r, g, b)
  136. for r, g, b, a in im.convert("RGBA").getdata()
  137. if not ingest.is_outline(r, g, b, a)
  138. ]
  139. return rgb_pixels
  140. def merge_dist_jab(p: np.array, q: np.array) -> float:
  141. pj, pa, pb = p
  142. qj, qa, qb = q
  143. light_diff = abs(pj - qj)
  144. hue_angle = math.acos((pa * qa + pb * qb) / math.sqrt((pa ** 2 + pb ** 2) * (qa ** 2 + qb ** 2))) * 180 / math.pi
  145. return light_diff if hue_angle <= 10 and light_diff <= 20 else None
  146. def merge_dist_rgb(p: np.array, q: np.array) -> float:
  147. return merge_dist_jab(*cspace_convert(np.array([p, q]), "sRGB255", "CAM02-UCS"))
  148. def score_clustering_jab(means: list[np.array]) -> float:
  149. score = 0
  150. count = 0
  151. for p, q in itertools.combinations(means, 2):
  152. # squared dist in the a-b plane
  153. _, pa, pb = p
  154. _, qa, qb = q
  155. score += (pa - qa) ** 2 + (pb - qb) ** 2
  156. count += 1
  157. return score / count
  158. def score_clustering_rgb(means: list[np.array]) -> float:
  159. return score_clustering_jab(list(cspace_convert(np.array(means), "sRGB255", "CAM02-UCS")))
  160. Stats = NamedTuple("Stats", [("size", int), ("inertia", float), ("mu", np.array), ("nu", np.array)])
  161. def merge_stats(s1: Stats, s2: Stats) -> Stats:
  162. ts = s1.size + s2.size
  163. f1 = s1.size / ts
  164. f2 = s2.size / ts
  165. return Stats(
  166. size=ts,
  167. inertia=s1.inertia * f1 + s2.inertia * f2,
  168. mu=s1.mu * f1 + s2.mu * f2,
  169. nu=s1.nu * f1 + s2.nu * f2,
  170. )
  171. def flatten_stats(ss: list[Stats], target_len: int = 40) -> list[float]:
  172. to_return = []
  173. for s in ss:
  174. to_return += [s.size, s.inertia, *s.mu, *s.nu]
  175. return to_return + ([0] * (target_len - len(to_return)))
  176. def compute_stats(
  177. pixels: np.array,
  178. clustering_scorer: Callable[[list[np.array]], float],
  179. merge_dist: Callable[[np.array, np.array], float],
  180. ) -> list[Stats]:
  181. total_stats = Stats(
  182. size=len(pixels),
  183. inertia=ingest.inertia(pixels),
  184. mu=ingest.mu(pixels),
  185. nu=ingest.nu(pixels),
  186. )
  187. # run k-means multiple times, for multiple k's, trying to maximize the clustering_scorer
  188. best = None
  189. for k in (2, 3, 4):
  190. for i in range(cluster_attempts):
  191. means, labels = vq.kmeans2(pixels.astype(float), k, minit="++", seed=cluster_seed + i)
  192. score = clustering_scorer(means)
  193. if best is None or best[0] < score:
  194. best = (score, means, labels)
  195. _, best_means, best_labels = best
  196. cluster_stats = []
  197. for i in range(len(best_means)):
  198. cluster_pixels = pixels[best_labels == i]
  199. cluster_stats.append(Stats(
  200. size=len(cluster_pixels),
  201. inertia=ingest.inertia(cluster_pixels),
  202. mu=best_means[i],
  203. nu=ingest.nu(cluster_pixels),
  204. ))
  205. # assuming there are still more than two clusters,
  206. # attempt to merge the closest if they're close enough
  207. if len(cluster_stats) > 2:
  208. # first, find all the options
  209. options = []
  210. for i, j in itertools.combinations(range(len(cluster_stats)), 2):
  211. ci = cluster_stats[i]
  212. cj = cluster_stats[j]
  213. if (dist := merge_dist(ci.mu, cj.mu)) is not None:
  214. rest = [c for k, c in enumerate(cluster_stats) if k not in (i, j)]
  215. options.append((dist, [merge_stats(ci, cj), *rest]))
  216. # if there are multiple options, use the closest,
  217. # otherwise leaves cluster_stats the same
  218. if len(options) > 0:
  219. cluster_stats = min(options, key=lambda x: x[0])[1]
  220. return [total_stats, *cluster_stats]
  221. def get_stats(name: str) -> list[float]:
  222. front = get_all_pixels(load_image(base, name))
  223. back = get_all_pixels(load_image(back_base, name))
  224. rgb_pixels = np.array(front + back)
  225. jab_pixels = cspace_convert(rgb_pixels, "sRGB255", "CAM02-UCS")
  226. jab_stats = flatten_stats(compute_stats(
  227. jab_pixels,
  228. score_clustering_jab,
  229. merge_dist_jab,
  230. ))[1:]
  231. rgb_stats = flatten_stats(compute_stats(
  232. rgb_pixels,
  233. score_clustering_rgb,
  234. merge_dist_rgb,
  235. ))[1:]
  236. return [len(rgb_pixels), *jab_stats, *rgb_stats]
  237. if __name__ == "__main__":
  238. pkmn = get_all_pokemon()
  239. print("Found", len(pkmn), "sprites...")
  240. errors = []
  241. def ingest_and_format(name: str) -> str:
  242. try:
  243. print(f"Ingesting {name}...")
  244. stats = get_stats(name)
  245. format_name = rename.get(name, name)
  246. print(f"Finished {name}, saving under {format_name}")
  247. return f' [ "{format_name}", {", ".join(str(n) for n in stats)} ],\n'
  248. except Exception as e:
  249. print(e)
  250. errors.append((name, e))
  251. with multiprocessing.Pool(4) as pool:
  252. stats = sorted(pool.imap_unordered(ingest_and_format, pkmn, 100))
  253. print(f"Calculated {len(stats)} statistics, writing...")
  254. with open("database-v3.js", "w") as outfile:
  255. outfile.write("const databaseV3 = [\n")
  256. for line in sorted(stats):
  257. outfile.write(line)
  258. outfile.write("];\n")
  259. print("Errors:", errors)