sscli 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #!/usr/bin/env python3
  2. __doc__ = """ Scriptshifter command line interface. """
  3. import click
  4. from glob import glob
  5. from os import path
  6. from scriptshifter import DB_PATH
  7. from scriptshifter.tables import init_db as _init_db
  8. from scriptshifter.trans import transliterate as _transliterate
  9. from test.integration import test_sample
  10. @click.group()
  11. def cli():
  12. """ Scriptshifter CLI. """
  13. pass
  14. @cli.group(name="admin")
  15. def admin_grp():
  16. """ Admin operations. """
  17. pass
  18. @admin_grp.command()
  19. def init_db():
  20. """ Initialize SS database. """
  21. _init_db()
  22. click.echo(f"Initialized Scriptshifter DB in {DB_PATH}")
  23. @cli.group(name="test")
  24. def test_grp():
  25. """ Test operations. """
  26. pass
  27. @test_grp.command()
  28. def list_samples():
  29. """ List string sample sets that can be tested. """
  30. path_ptn = path.join(
  31. path.dirname(path.realpath(__file__)),
  32. "tests", "data", "script_samples", "*.csv")
  33. click.echo("Sample string sets available for batch testing:")
  34. for fn in glob(path_ptn):
  35. click.echo(path.splitext(path.basename(fn))[0])
  36. @test_grp.command()
  37. @click.argument("lang")
  38. def samples(lang):
  39. """
  40. Test sample strings for language LANG.
  41. LANG must match one of the names obtained with `test list-samples` command.
  42. The command will generate a test report file.
  43. """
  44. return test_sample(lang)
  45. @cli.command(name="trans")
  46. @click.argument("lang")
  47. @click.argument("src", type=click.File("r"), default="-")
  48. @click.option(
  49. "-c", "--capitalize", default=None,
  50. help="Capitalize output: `first`, `all`, ot none (the default).")
  51. @click.option(
  52. "-d", "--t-dir", default="s2r",
  53. help="Transliteration direction: `s2r' (default)) or `r2s'")
  54. @click.option(
  55. "-o", "--option", multiple=True,
  56. help=(
  57. "Language=specific option. Format: key=value. Multiple -o entries "
  58. "are possible."))
  59. def trans_(src, lang, t_dir, capitalize, option):
  60. """
  61. Transliterate text from standard input.
  62. e.g.: `echo "王正强" | /path/to/sscli trans chinese -o "marc_field=100"'
  63. """
  64. options = {}
  65. for opt in option:
  66. k, v = opt.split("=", 1)
  67. options[k] = v
  68. trans, warnings = _transliterate(
  69. src.read(), lang, t_dir, capitalize, options)
  70. for w in warnings:
  71. click.echo(click.style("WARNING: ", fg="yellow") + w)
  72. click.echo(trans)
  73. if __name__ == "__main__":
  74. cli()