add_id.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # coding=utf-8
  2. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import json
  17. import os
  18. import time
  19. """
  20. This code adds id to each json object in a json file. User can add prefix
  21. to the ids.
  22. """
  23. if __name__ == '__main__':
  24. print('parsing the arguments ...')
  25. parser = argparse.ArgumentParser()
  26. parser.add_argument('--input-file', type=str, default=None, help='Input'\
  27. ' json file where id needs to be added')
  28. parser.add_argument('--output-file', type=str, default=None, help=\
  29. 'Output file name with id')
  30. parser.add_argument('--id-prefix', type=str, default=None, help=\
  31. 'Id prefix')
  32. parser.add_argument('--log-interval', type=int, default=100,
  33. help='Log interval')
  34. args = parser.parse_args()
  35. print('Adding ids to dataset ...')
  36. f_input = open(args.input_file, 'r', encoding='utf-8')
  37. f_output = open(args.output_file, 'wb')
  38. unique_ids = 1
  39. start_time = time.time()
  40. for row in f_input:
  41. each_row = json.loads(row)
  42. adlr_id_string = args.id_prefix + '-{:010d}'.format(int(unique_ids))
  43. each_row['adlr_id'] = adlr_id_string
  44. myjson = json.dumps(each_row, ensure_ascii=False)
  45. f_output.write(myjson.encode('utf-8'))
  46. f_output.write('\n'.encode('utf-8'))
  47. if unique_ids % args.log_interval == 0:
  48. print(' processed {:9d} documents in {:.2f} seconds ...'.format( \
  49. unique_ids, time.time() - start_time), flush=True)
  50. unique_ids += 1
  51. # Close the file.
  52. f_input.close()
  53. f_output.close()
  54. print('done :-)', flush=True)