m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.7 KiB

6 months ago
  1. import os
  2. import subprocess
  3. import glob
  4. from sympy.utilities.misc import debug
  5. here = os.path.dirname(__file__)
  6. grammar_file = os.path.abspath(os.path.join(here, "LaTeX.g4"))
  7. dir_latex_antlr = os.path.join(here, "_antlr")
  8. header = '''
  9. # encoding: utf-8
  10. # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
  11. #
  12. # Generated from ../LaTeX.g4, derived from latex2sympy
  13. # latex2sympy is licensed under the MIT license
  14. # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
  15. #
  16. # Generated with antlr4
  17. # antlr4 is licensed under the BSD-3-Clause License
  18. # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
  19. '''
  20. def check_antlr_version():
  21. debug("Checking antlr4 version...")
  22. try:
  23. debug(subprocess.check_output(["antlr4"])
  24. .decode('utf-8').split("\n")[0])
  25. return True
  26. except (subprocess.CalledProcessError, FileNotFoundError):
  27. debug("The 'antlr4' command line tool is not installed, "
  28. "or not on your PATH.\n"
  29. "> Please refer to the README.md file for more information.")
  30. return False
  31. def build_parser(output_dir=dir_latex_antlr):
  32. check_antlr_version()
  33. debug("Updating ANTLR-generated code in {}".format(output_dir))
  34. if not os.path.exists(output_dir):
  35. os.makedirs(output_dir)
  36. with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
  37. fp.write(header)
  38. args = [
  39. "antlr4",
  40. grammar_file,
  41. "-o", output_dir,
  42. # for now, not generating these as latex2sympy did not use them
  43. "-no-visitor",
  44. "-no-listener",
  45. ]
  46. debug("Running code generation...\n\t$ {}".format(" ".join(args)))
  47. subprocess.check_output(args, cwd=output_dir)
  48. debug("Applying headers, removing unnecessary files and renaming...")
  49. # Handle case insensitive file systems. If the files are already
  50. # generated, they will be written to latex* but LaTeX*.* won't match them.
  51. for path in (glob.glob(os.path.join(output_dir, "LaTeX*.*")) +
  52. glob.glob(os.path.join(output_dir, "latex*.*"))):
  53. # Remove files ending in .interp or .tokens as they are not needed.
  54. if not path.endswith(".py"):
  55. os.unlink(path)
  56. continue
  57. new_path = os.path.join(output_dir, os.path.basename(path).lower())
  58. with open(path, 'r') as f:
  59. lines = [line.rstrip() + '\n' for line in f.readlines()]
  60. os.unlink(path)
  61. with open(new_path, "w") as out_file:
  62. offset = 2
  63. out_file.write(header)
  64. out_file.writelines(lines[offset:])
  65. debug("\t{}".format(new_path))
  66. return True
  67. if __name__ == "__main__":
  68. build_parser()