spm_encode.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #!/usr/bin/env python
  2. # Copyright (c) Facebook, Inc. and its affiliates.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the license found in
  6. # https://github.com/pytorch/fairseq/blob/master/LICENSE
  7. import argparse
  8. import contextlib
  9. import sys
  10. import sentencepiece as spm
  11. def main():
  12. parser = argparse.ArgumentParser()
  13. parser.add_argument("--model", required=True,
  14. help="sentencepiece model to use for encoding")
  15. parser.add_argument("--inputs", nargs="+", default=['-'],
  16. help="input files to filter/encode")
  17. parser.add_argument("--outputs", nargs="+", default=['-'],
  18. help="path to save encoded outputs")
  19. parser.add_argument("--output_format", choices=["piece", "id"], default="piece")
  20. parser.add_argument("--min-len", type=int, metavar="N",
  21. help="filter sentence pairs with fewer than N tokens")
  22. parser.add_argument("--max-len", type=int, metavar="N",
  23. help="filter sentence pairs with more than N tokens")
  24. args = parser.parse_args()
  25. assert len(args.inputs) == len(args.outputs), \
  26. "number of input and output paths should match"
  27. sp = spm.SentencePieceProcessor()
  28. sp.Load(args.model)
  29. if args.output_format == "piece":
  30. def encode(l):
  31. return sp.EncodeAsPieces(l)
  32. elif args.output_format == "id":
  33. def encode(l):
  34. return list(map(str, sp.EncodeAsIds(l)))
  35. else:
  36. raise NotImplementedError
  37. if args.min_len is not None or args.max_len is not None:
  38. def valid(line):
  39. return (
  40. (args.min_len is None or len(line) >= args.min_len) and
  41. (args.max_len is None or len(line) <= args.max_len)
  42. )
  43. else:
  44. def valid(lines):
  45. return True
  46. with contextlib.ExitStack() as stack:
  47. inputs = [
  48. stack.enter_context(open(input, "r", encoding="utf-8"))
  49. if input != "-" else sys.stdin
  50. for input in args.inputs
  51. ]
  52. outputs = [
  53. stack.enter_context(open(output, "w", encoding="utf-8"))
  54. if output != "-" else sys.stdout
  55. for output in args.outputs
  56. ]
  57. stats = {
  58. "num_empty": 0,
  59. "num_filtered": 0,
  60. }
  61. def encode_line(line):
  62. line = line.strip()
  63. if len(line) > 0:
  64. line = encode(line)
  65. if valid(line):
  66. return line
  67. else:
  68. stats["num_filtered"] += 1
  69. else:
  70. stats["num_empty"] += 1
  71. return None
  72. for i, lines in enumerate(zip(*inputs), start=1):
  73. enc_lines = list(map(encode_line, lines))
  74. if not any(enc_line is None for enc_line in enc_lines):
  75. for enc_line, output_h in zip(enc_lines, outputs):
  76. print(" ".join(enc_line), file=output_h)
  77. if i % 10000 == 0:
  78. print("processed {} lines".format(i), file=sys.stderr)
  79. print("skipped {} empty lines".format(stats["num_empty"]), file=sys.stderr)
  80. print("filtered {} lines".format(stats["num_filtered"]), file=sys.stderr)
  81. if __name__ == "__main__":
  82. main()