anim_ingest.py 9.4 KB

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