sscli 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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.group(name="trans")
  46. def trans_grp():
  47. """ Transliteration and transcription operations. """
  48. pass
  49. @trans_grp.command()
  50. @click.argument("src", type=click.File("r"))
  51. @click.argument("lang")
  52. @click.option(
  53. "-c", "--capitalize", default=None,
  54. help="Capitalize output: `first`, `all`, ot none (the default).")
  55. @click.option(
  56. "-d", "--t-dir", default="s2r",
  57. help="Transliteration direction: `s2r' (default)) or `r2s'")
  58. @click.option(
  59. "-o", "--option", multiple=True,
  60. help=(
  61. "Language=specific option. Format: key=value. Multiple -o entries "
  62. "are possible."))
  63. def transliterate(src, lang, t_dir, capitalize, option):
  64. """
  65. Transliterate text from standard input.
  66. e.g.: `echo "王正强" | /path/to/sscli trans transliterate chinese
  67. -o "marc_field=100"'
  68. """
  69. options = {}
  70. for opt in option:
  71. k, v = opt.split("=", 1)
  72. options[k] = v
  73. trans, warnings = _transliterate(
  74. src.read(), lang, t_dir, capitalize, options)
  75. for w in warnings:
  76. click.echo(click.style("WARNING: ", fg="yellow") + w)
  77. click.echo(trans)
  78. if __name__ == "__main__":
  79. cli()