perfect_hash.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. # Derived from: https://github.com/ilanschnell/perfect-hash
  2. # Commit: 6b7dd80a525dbd4349ea2c69f04a9c96f3c2fd54
  3. # BSD 3-Clause License
  4. #
  5. # Copyright (c) 2019 - 2021, Ilan Schnell
  6. # All rights reserved.
  7. #
  8. # Redistribution and use in source and binary forms, with or without
  9. # modification, are permitted provided that the following conditions are met:
  10. # * Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # * Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in the
  14. # documentation and/or other materials provided with the distribution.
  15. # * Neither the name of the Ilan Schnell nor the
  16. # names of its contributors may be used to endorse or promote products
  17. # derived from this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  20. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  21. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. # DISCLAIMED. IN NO EVENT SHALL ILAN SCHNELL BE LIABLE FOR ANY
  23. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  25. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  26. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. """
  30. Generate a minimal perfect hash function for the keys in a file,
  31. desired hash values may be specified within this file as well.
  32. A given code template is filled with parameters, such that the
  33. output is code which implements the hash function.
  34. Templates can easily be constructed for any programming language.
  35. The code is based on an a program A.M. Kuchling wrote:
  36. http://www.amk.ca/python/code/perfect-hash
  37. The algorithm the program uses is described in the paper
  38. 'Optimal algorithms for minimal perfect hashing',
  39. Z. J. Czech, G. Havas and B.S. Majewski.
  40. http://citeseer.ist.psu.edu/122364.html
  41. The algorithm works like this:
  42. 1. You have K keys, that you want to perfectly hash against some
  43. desired hash values.
  44. 2. Choose a number N larger than K. This is the number of
  45. vertices in a graph G, and also the size of the resulting table G.
  46. 3. Pick two random hash functions f1, f2, that return values from 0..N-1.
  47. 4. Now, for all keys, you draw an edge between vertices f1(key) and f2(key)
  48. of the graph G, and associate the desired hash value with that edge.
  49. 5. If G is cyclic, go back to step 2.
  50. 6. Assign values to each vertex such that, for each edge, you can add
  51. the values for the two vertices and get the desired (hash) value
  52. for that edge. This task is easy, because the graph is acyclic.
  53. This is done by picking a vertex, and assigning it a value of 0.
  54. Then do a depth-first search, assigning values to new vertices so that
  55. they sum up properly.
  56. 7. f1, f2, and vertex values of G now make up a perfect hash function.
  57. For simplicity, the implementation of the algorithm combines steps 5 and 6.
  58. That is, we check for loops in G and assign the vertex values in one procedure.
  59. If this procedure succeeds, G is acyclic and the vertex values are assigned.
  60. If the procedure fails, G is cyclic, and we go back to step 2, replacing G
  61. with a new graph, and thereby discarding the vertex values from the failed
  62. attempt.
  63. """
  64. from __future__ import absolute_import, division, print_function
  65. import random
  66. import shutil
  67. import string
  68. import subprocess
  69. import sys
  70. import tempfile
  71. from collections import defaultdict
  72. from optparse import Values
  73. from os.path import join
  74. from typing import Any, Sequence, TypeVar
  75. if sys.version_info[0] == 2:
  76. from cStringIO import StringIO
  77. else:
  78. from io import StringIO
  79. __version__ = "0.4.2"
  80. verbose = False
  81. trials = 150
  82. class Graph(object):
  83. """
  84. Implements a graph with 'N' vertices. First, you connect the graph with
  85. edges, which have a desired value associated. Then the vertex values
  86. are assigned, which will fail if the graph is cyclic. The vertex values
  87. are assigned such that the two values corresponding to an edge add up to
  88. the desired edge value (mod N).
  89. """
  90. def __init__(self, N: int):
  91. self.N = N # number of vertices
  92. # maps a vertex number to the list of tuples (vertex, edge value)
  93. # to which it is connected by edges.
  94. self.adjacent: dict[int, list[tuple[int, int]]] = defaultdict(list)
  95. def connect(self, vertex1: int, vertex2: int, edge_value: int) -> None:
  96. """
  97. Connect 'vertex1' and 'vertex2' with an edge, with associated
  98. value 'value'
  99. """
  100. # Add vertices to each other's adjacent list
  101. self.adjacent[vertex1].append((vertex2, edge_value))
  102. self.adjacent[vertex2].append((vertex1, edge_value))
  103. def assign_vertex_values(self) -> bool:
  104. """
  105. Try to assign the vertex values, such that, for each edge, you can
  106. add the values for the two vertices involved and get the desired
  107. value for that edge, i.e. the desired hash key.
  108. This will fail when the graph is cyclic.
  109. This is done by a Depth-First Search of the graph. If the search
  110. finds a vertex that was visited before, there's a loop and False is
  111. returned immediately, i.e. the assignment is terminated.
  112. On success (when the graph is acyclic) True is returned.
  113. """
  114. self.vertex_values = self.N * [-1] # -1 means unassigned
  115. visited = self.N * [False]
  116. # Loop over all vertices, taking unvisited ones as roots.
  117. for root in range(self.N):
  118. if visited[root]:
  119. continue
  120. # explore tree starting at 'root'
  121. self.vertex_values[root] = 0 # set arbitrarily to zero
  122. # Stack of vertices to visit, a list of tuples (parent, vertex)
  123. tovisit: list[tuple[int | None, int]] = [(None, root)]
  124. while tovisit:
  125. parent, vertex = tovisit.pop()
  126. visited[vertex] = True
  127. # Loop over adjacent vertices, but skip the vertex we arrived
  128. # here from the first time it is encountered.
  129. skip = True
  130. for neighbor, edge_value in self.adjacent[vertex]:
  131. if skip and neighbor == parent:
  132. skip = False
  133. continue
  134. if visited[neighbor]:
  135. # We visited here before, so the graph is cyclic.
  136. return False
  137. tovisit.append((vertex, neighbor))
  138. # Set new vertex's value to the desired edge value,
  139. # minus the value of the vertex we came here from.
  140. self.vertex_values[neighbor] = (
  141. edge_value - self.vertex_values[vertex]
  142. ) % self.N
  143. # check if all vertices have a valid value
  144. for vertex in range(self.N):
  145. assert self.vertex_values[vertex] >= 0
  146. # We got though, so the graph is acyclic,
  147. # and all values are now assigned.
  148. return True
  149. class StrSaltHash:
  150. """
  151. Random hash function generator.
  152. Simple byte level hashing: each byte is multiplied to another byte from
  153. a random string of characters, summed up, and finally modulo NG is
  154. taken.
  155. """
  156. chars = string.ascii_letters + string.digits
  157. def __init__(self, N: int):
  158. self.N = N
  159. self.salt = ""
  160. def __call__(self, key: Sequence[str]) -> int:
  161. # XXX: xkbcommon modification: make the salt length a power of 2
  162. # so that the % operation in the hash is fast.
  163. while len(self.salt) < max(len(key), 32): # add more salt as necessary
  164. self.salt += random.choice(self.chars)
  165. return sum(ord(self.salt[i]) * ord(c) for i, c in enumerate(key)) % self.N
  166. template = """
  167. def hash_f(key, T):
  168. return sum(ord(T[i % $NS]) * ord(c) for i, c in enumerate(key)) % $NG
  169. def perfect_hash(key):
  170. return (G[hash_f(key, "$S1")] +
  171. G[hash_f(key, "$S2")]) % $NG
  172. """
  173. class IntSaltHash:
  174. """
  175. Random hash function generator.
  176. Simple byte level hashing, each byte is multiplied in sequence to a table
  177. containing random numbers, summed tp, and finally modulo NG is taken.
  178. """
  179. def __init__(self, N: int):
  180. self.N: int = N
  181. self.salt: list[int] = []
  182. def __call__(self, key: Sequence[str]) -> int:
  183. while len(self.salt) < len(key): # add more salt as necessary
  184. self.salt.append(random.randint(1, self.N - 1))
  185. return sum(self.salt[i] * ord(c) for i, c in enumerate(key)) % self.N
  186. template = """
  187. S1 = [$S1]
  188. S2 = [$S2]
  189. assert len(S1) == len(S2) == $NS
  190. def hash_f(key, T):
  191. return sum(T[i % $NS] * ord(c) for i, c in enumerate(key)) % $NG
  192. def perfect_hash(key):
  193. return (G[hash_f(key, S1)] + G[hash_f(key, S2)]) % $NG
  194. """
  195. H = TypeVar("H", StrSaltHash, IntSaltHash)
  196. def builtin_template(Hash: type[H]) -> str:
  197. return (
  198. """\
  199. # =======================================================================
  200. # ================= Python code for perfect hash function ===============
  201. # =======================================================================
  202. G = [$G]
  203. """
  204. + Hash.template
  205. + """
  206. # ============================ Sanity check =============================
  207. K = [$K]
  208. assert len(K) == $NK
  209. for h, k in enumerate(K):
  210. assert perfect_hash(k) == h
  211. """
  212. )
  213. class TooManyInterationsError(Exception):
  214. pass
  215. # NOTE: as of mypy 1.13, it is not possible to specify a default value for a generic
  216. # parameter, so `Hash: type[H] = StrSaltHash` will raise a type error. See:
  217. # • https://github.com/python/mypy/issues/3737
  218. # • https://github.com/python/mypy/issues/18017
  219. def generate_hash(
  220. keys: list[str], Hash: type[H] = StrSaltHash
  221. ) -> tuple[H, H, list[int]]:
  222. """
  223. Return hash functions f1 and f2, and G for a perfect minimal hash.
  224. Input is an iterable of 'keys', whos indicies are the desired hash values.
  225. 'Hash' is a random hash function generator, that means Hash(N) returns a
  226. returns a random hash function which returns hash values from 0..N-1.
  227. """
  228. if not isinstance(keys, (list, tuple)):
  229. raise TypeError("list or tuple expected")
  230. NK = len(keys)
  231. if NK != len(set(keys)):
  232. raise ValueError("duplicate keys")
  233. for key in keys:
  234. if not isinstance(key, str):
  235. raise TypeError("key a not string: %r" % key)
  236. if NK > 10000 and Hash == StrSaltHash:
  237. print(
  238. """\
  239. WARNING: You have %d keys.
  240. Using --hft=1 is likely to fail for so many keys.
  241. Please use --hft=2 instead.
  242. """
  243. % NK
  244. )
  245. # the number of vertices in the graph G
  246. NG = NK + 1
  247. if verbose:
  248. print("NG = %d" % NG)
  249. trial = 0 # Number of trial graphs so far
  250. while True:
  251. if (trial % trials) == 0: # trials failures, increase NG slightly
  252. if trial > 0:
  253. NG = max(NG + 1, int(1.05 * NG))
  254. if verbose:
  255. sys.stdout.write("\nGenerating graphs NG = %d " % NG)
  256. trial += 1
  257. if NG > 100 * (NK + 1):
  258. raise TooManyInterationsError("%d keys" % NK)
  259. if verbose:
  260. sys.stdout.write(".")
  261. sys.stdout.flush()
  262. G = Graph(NG) # Create graph with NG vertices
  263. f1 = Hash(NG) # Create 2 random hash functions
  264. f2 = Hash(NG)
  265. # Connect vertices given by the values of the two hash functions
  266. # for each key. Associate the desired hash value with each edge.
  267. for hashval, key in enumerate(keys):
  268. G.connect(f1(key), f2(key), hashval)
  269. # Try to assign the vertex values. This will fail when the graph
  270. # is cyclic. But when the graph is acyclic it will succeed and we
  271. # break out, because we're done.
  272. if G.assign_vertex_values():
  273. break
  274. if verbose:
  275. print("\nAcyclic graph found after %d trials." % trial)
  276. print("NG = %d" % NG)
  277. # Sanity check the result by actually verifying that all the keys
  278. # hash to the right value.
  279. for hashval, key in enumerate(keys):
  280. assert hashval == (G.vertex_values[f1(key)] + G.vertex_values[f2(key)]) % NG
  281. if verbose:
  282. print("OK")
  283. return f1, f2, G.vertex_values
  284. class Format(object):
  285. def __init__(self, width: int = 76, indent: int = 4, delimiter: str = ", "):
  286. self.width = width
  287. self.indent = indent
  288. self.delimiter = delimiter
  289. def print_format(self) -> None:
  290. print("Format options:")
  291. for name in "width", "indent", "delimiter":
  292. print(" %s: %r" % (name, getattr(self, name)))
  293. def __call__(self, data: Any, quote: bool = False) -> str:
  294. if not isinstance(data, (list, tuple)):
  295. return str(data)
  296. lendel = len(self.delimiter)
  297. aux = StringIO()
  298. pos = 20
  299. for i, elt in enumerate(data):
  300. last = bool(i == len(data) - 1)
  301. s = ('"%s"' if quote else "%s") % elt
  302. if pos + len(s) + lendel > self.width:
  303. aux.write("\n" + (self.indent * " "))
  304. pos = self.indent
  305. aux.write(s)
  306. pos += len(s)
  307. if not last:
  308. aux.write(self.delimiter)
  309. pos += lendel
  310. return "\n".join(l.rstrip() for l in aux.getvalue().split("\n"))
  311. def generate_code(
  312. keys: list[str],
  313. Hash: type[H] = StrSaltHash,
  314. template: str | None = None,
  315. options: Values | None = None,
  316. ) -> str:
  317. """
  318. Takes a list of key value pairs and inserts the generated parameter
  319. lists into the 'template' string. 'Hash' is the random hash function
  320. generator, and the optional keywords are formating options.
  321. The return value is the substituted code template.
  322. """
  323. f1, f2, G = generate_hash(keys, Hash)
  324. assert f1.N == f2.N == len(G)
  325. try:
  326. salt_len = len(f1.salt)
  327. assert salt_len == len(f2.salt)
  328. except TypeError:
  329. salt_len = None
  330. if template is None:
  331. template = builtin_template(Hash)
  332. if options is None:
  333. fmt = Format()
  334. else:
  335. fmt = Format(
  336. width=options.width, indent=options.indent, delimiter=options.delimiter
  337. )
  338. if verbose:
  339. fmt.print_format()
  340. return string.Template(template).substitute(
  341. NS=salt_len,
  342. S1=fmt(f1.salt),
  343. S2=fmt(f2.salt),
  344. NG=len(G),
  345. G=fmt(G),
  346. NK=len(keys),
  347. K=fmt(list(keys), quote=True),
  348. )
  349. def read_table(filename: str, options: Values) -> list[str]:
  350. """
  351. Reads keys and desired hash value pairs from a file. If no column
  352. for the hash value is specified, a sequence of hash values is generated,
  353. from 0 to N-1, where N is the number of rows found in the file.
  354. """
  355. if verbose:
  356. print("Reading table from file `%s' to extract keys." % filename)
  357. try:
  358. fi = open(filename)
  359. except IOError:
  360. sys.exit("Error: Could not open `%s' for reading." % filename)
  361. keys = []
  362. if verbose:
  363. print("Reader options:")
  364. for name in "comment", "splitby", "keycol":
  365. print(" %s: %r" % (name, getattr(options, name)))
  366. for n, line in enumerate(fi):
  367. line = line.strip()
  368. if not line or line.startswith(options.comment):
  369. continue
  370. if line.count(options.comment): # strip content after comment
  371. line = line.split(options.comment)[0].strip()
  372. row = [col.strip() for col in line.split(options.splitby)]
  373. try:
  374. key: str = row[options.keycol - 1]
  375. except IndexError:
  376. sys.exit(
  377. "%s:%d: Error: Cannot read key, not enough columns." % (filename, n + 1)
  378. )
  379. keys.append(key)
  380. fi.close()
  381. if not keys:
  382. exit("Error: no keys found in file `%s'." % filename)
  383. return keys
  384. def read_template(filename: str) -> str:
  385. if verbose:
  386. print("Reading template from file `%s'" % filename)
  387. try:
  388. with open(filename, "r") as fi:
  389. return fi.read()
  390. except IOError:
  391. sys.exit("Error: Could not open `%s' for reading." % filename)
  392. def run_code(code: str) -> None:
  393. tmpdir = tempfile.mkdtemp()
  394. path = join(tmpdir, "t.py")
  395. with open(path, "w") as fo:
  396. fo.write(code)
  397. try:
  398. subprocess.check_call([sys.executable, path])
  399. except subprocess.CalledProcessError as e:
  400. raise AssertionError(e)
  401. finally:
  402. shutil.rmtree(tmpdir)
  403. def main() -> None:
  404. from optparse import OptionParser
  405. usage = "usage: %prog [options] KEYS_FILE [TMPL_FILE]"
  406. description = """\
  407. Generates code for perfect hash functions from
  408. a file with keywords and a code template.
  409. If no template file is provided, a small built-in Python template
  410. is processed and the output code is written to stdout.
  411. """
  412. parser = OptionParser(
  413. usage=usage,
  414. description=description,
  415. prog=sys.argv[0],
  416. version="%prog: " + __version__,
  417. )
  418. parser.add_option(
  419. "--delimiter",
  420. action="store",
  421. default=", ",
  422. help="Delimiter for list items used in output, "
  423. "the default delimiter is '%default'",
  424. metavar="STR",
  425. )
  426. parser.add_option(
  427. "--indent",
  428. action="store",
  429. default=4,
  430. type="int",
  431. help="Make INT spaces at the beginning of a "
  432. "new line when generated list is wrapped. "
  433. "Default is %default",
  434. metavar="INT",
  435. )
  436. parser.add_option(
  437. "--width",
  438. action="store",
  439. default=76,
  440. type="int",
  441. help="Maximal width of generated list when wrapped. Default width is %default",
  442. metavar="INT",
  443. )
  444. parser.add_option(
  445. "--comment",
  446. action="store",
  447. default="#",
  448. help="STR is the character, or sequence of "
  449. "characters, which marks the beginning "
  450. "of a comment (which runs till "
  451. "the end of the line), in the input "
  452. "KEYS_FILE. "
  453. "Default is '%default'",
  454. metavar="STR",
  455. )
  456. parser.add_option(
  457. "--splitby",
  458. action="store",
  459. default=",",
  460. help="STR is the character by which the columns "
  461. "in the input KEYS_FILE are split. "
  462. "Default is '%default'",
  463. metavar="STR",
  464. )
  465. parser.add_option(
  466. "--keycol",
  467. action="store",
  468. default=1,
  469. type="int",
  470. help="Specifies the column INT in the input "
  471. "KEYS_FILE which contains the keys. "
  472. "Default is %default, i.e. the first column.",
  473. metavar="INT",
  474. )
  475. parser.add_option(
  476. "--trials",
  477. action="store",
  478. default=5,
  479. type="int",
  480. help="Specifies the number of trials before "
  481. "NG is increased. A small INT will give "
  482. "compute faster, but the array G will be "
  483. "large. A large INT will take longer to "
  484. "compute but G will be smaller. "
  485. "Default is %default",
  486. metavar="INT",
  487. )
  488. parser.add_option(
  489. "--hft",
  490. action="store",
  491. default=1,
  492. type="int",
  493. help="Hash function type INT. Possible values "
  494. "are 1 (StrSaltHash) and 2 (IntSaltHash). "
  495. "The default is %default",
  496. metavar="INT",
  497. )
  498. parser.add_option(
  499. "-e",
  500. "--execute",
  501. action="store_true",
  502. help="Execute the generated code within the Python interpreter.",
  503. )
  504. parser.add_option(
  505. "-o",
  506. "--output",
  507. action="store",
  508. help="Specify output FILE explicitly. "
  509. "`-o std' means standard output. "
  510. "`-o no' means no output. "
  511. "By default, the file name is obtained "
  512. "from the name of the template file by "
  513. "substituting `tmpl' to `code'.",
  514. metavar="FILE",
  515. )
  516. parser.add_option("-v", "--verbose", action="store_true", help="verbosity")
  517. options, args = parser.parse_args()
  518. if options.trials <= 0:
  519. parser.error("trials before increasing N has to be larger than zero")
  520. global trials
  521. trials = options.trials
  522. global verbose
  523. verbose = options.verbose
  524. if len(args) not in (1, 2):
  525. parser.error("incorrect number of arguments")
  526. if len(args) == 2 and not args[1].count("tmpl"):
  527. parser.error("template filename does not contain 'tmpl'")
  528. if options.hft == 1:
  529. Hash: type = StrSaltHash
  530. elif options.hft == 2:
  531. Hash = IntSaltHash
  532. else:
  533. parser.error("Hash function %s not implemented." % options.hft)
  534. # --------------------- end parsing and checking --------------
  535. keys_file = args[0]
  536. if verbose:
  537. print("keys_file = %r" % keys_file)
  538. keys = read_table(keys_file, options)
  539. if verbose:
  540. print("Number os keys: %d" % len(keys))
  541. tmpl_file = args[1] if len(args) == 2 else None
  542. if verbose:
  543. print("tmpl_file = %r" % tmpl_file)
  544. template = read_template(tmpl_file) if tmpl_file else None
  545. if options.output:
  546. outname = options.output
  547. else:
  548. if tmpl_file:
  549. if "tmpl" not in tmpl_file:
  550. sys.exit("Hmm, template filename does not contain 'tmpl'")
  551. outname = tmpl_file.replace("tmpl", "code")
  552. else:
  553. outname = "std"
  554. if verbose:
  555. print("outname = %r\n" % outname)
  556. if outname == "std":
  557. outstream = sys.stdout
  558. elif outname == "no":
  559. outstream = None
  560. else:
  561. try:
  562. outstream = open(outname, "w")
  563. except IOError:
  564. sys.exit("Error: Could not open `%s' for writing." % outname)
  565. code = generate_code(keys, Hash, template, options)
  566. if options.execute or template == builtin_template(Hash):
  567. if verbose:
  568. print("Executing code...\n")
  569. run_code(code)
  570. if outstream:
  571. outstream.write(code)
  572. if not outname == "std":
  573. outstream.close()
  574. if __name__ == "__main__":
  575. main()