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

util_minddataset.py 8.3 kB

4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. # Copyright 2022 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """
  16. This module contains common utility functions for minddataset tests.
  17. """
  18. import os
  19. import re
  20. import string
  21. import collections
  22. import pytest
  23. import numpy as np
  24. from mindspore.mindrecord import FileWriter
  25. FILES_NUM = 4
  26. CV_DIR_NAME = "../data/mindrecord/testImageNetData"
  27. def get_data(dir_name):
  28. """
  29. usage: get data from imagenet dataset
  30. params:
  31. dir_name: directory containing folder images and annotation information
  32. """
  33. if not os.path.isdir(dir_name):
  34. raise IOError("Directory {} does not exist".format(dir_name))
  35. img_dir = os.path.join(dir_name, "images")
  36. ann_file = os.path.join(dir_name, "annotation.txt")
  37. with open(ann_file, "r") as file_reader:
  38. lines = file_reader.readlines()
  39. data_list = []
  40. for i, line in enumerate(lines):
  41. try:
  42. filename, label = line.split(",")
  43. label = label.strip("\n")
  44. with open(os.path.join(img_dir, filename), "rb") as file_reader:
  45. img = file_reader.read()
  46. data_json = {"id": i,
  47. "file_name": filename,
  48. "data": img,
  49. "label": int(label)}
  50. data_list.append(data_json)
  51. except FileNotFoundError:
  52. continue
  53. return data_list
  54. def inputs(vectors, maxlen=50):
  55. length = len(vectors)
  56. if length > maxlen:
  57. return vectors[0:maxlen], [1] * maxlen, [0] * maxlen
  58. input_ = vectors + [0] * (maxlen - length)
  59. mask = [1] * length + [0] * (maxlen - length)
  60. segment = [0] * maxlen
  61. return input_, mask, segment
  62. def convert_to_uni(text):
  63. if isinstance(text, str):
  64. return text
  65. if isinstance(text, bytes):
  66. return text.decode('utf-8', 'ignore')
  67. raise Exception("The type %s does not convert!" % type(text))
  68. def load_vocab(vocab_file):
  69. """load vocabulary to translate statement."""
  70. vocab = collections.OrderedDict()
  71. vocab.setdefault('blank', 2)
  72. index = 0
  73. with open(vocab_file) as reader:
  74. while True:
  75. tmp = reader.readline()
  76. if not tmp:
  77. break
  78. token = convert_to_uni(tmp)
  79. token = token.strip()
  80. vocab[token] = index
  81. index += 1
  82. return vocab
  83. def get_nlp_data(dir_name, vocab_file, num):
  84. """
  85. Return raw data of aclImdb dataset.
  86. Args:
  87. dir_name (str): String of aclImdb dataset's path.
  88. vocab_file (str): String of dictionary's path.
  89. num (int): Number of sample.
  90. Returns:
  91. List
  92. """
  93. if not os.path.isdir(dir_name):
  94. raise IOError("Directory {} not exists".format(dir_name))
  95. for root, _, files in os.walk(dir_name):
  96. for index, file_name_extension in enumerate(files):
  97. if index < num:
  98. file_path = os.path.join(root, file_name_extension)
  99. file_name, _ = file_name_extension.split('.', 1)
  100. id_, rating = file_name.split('_', 1)
  101. with open(file_path, 'r') as f:
  102. raw_content = f.read()
  103. dictionary = load_vocab(vocab_file)
  104. vectors = [dictionary.get('[CLS]')]
  105. vectors += [dictionary.get(i) if i in dictionary
  106. else dictionary.get('[UNK]')
  107. for i in re.findall(r"[\w']+|[{}]"
  108. .format(string.punctuation),
  109. raw_content)]
  110. vectors += [dictionary.get('[SEP]')]
  111. input_, mask, segment = inputs(vectors)
  112. input_ids = np.reshape(np.array(input_), [-1])
  113. input_mask = np.reshape(np.array(mask), [1, -1])
  114. segment_ids = np.reshape(np.array(segment), [2, -1])
  115. data = {
  116. "label": 1,
  117. "id": id_,
  118. "rating": float(rating),
  119. "input_ids": input_ids,
  120. "input_mask": input_mask,
  121. "segment_ids": segment_ids
  122. }
  123. yield data
  124. @pytest.fixture
  125. def add_and_remove_cv_file():
  126. """add/remove cv file"""
  127. file_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]
  128. paths = ["{}{}".format(file_name, str(x).rjust(1, '0'))
  129. for x in range(FILES_NUM)]
  130. try:
  131. for x in paths:
  132. if os.path.exists("{}".format(x)):
  133. os.remove("{}".format(x))
  134. if os.path.exists("{}.db".format(x)):
  135. os.remove("{}.db".format(x))
  136. writer = FileWriter(file_name, FILES_NUM)
  137. data = get_data(CV_DIR_NAME)
  138. cv_schema_json = {"id": {"type": "int32"},
  139. "file_name": {"type": "string"},
  140. "label": {"type": "int32"},
  141. "data": {"type": "bytes"}}
  142. writer.add_schema(cv_schema_json, "img_schema")
  143. writer.add_index(["file_name", "label"])
  144. writer.write_raw_data(data)
  145. writer.commit()
  146. yield "yield_cv_data"
  147. except Exception as error:
  148. for x in paths:
  149. os.remove("{}".format(x))
  150. os.remove("{}.db".format(x))
  151. raise error
  152. else:
  153. for x in paths:
  154. os.remove("{}".format(x))
  155. os.remove("{}.db".format(x))
  156. @pytest.fixture
  157. def add_and_remove_file():
  158. """add/remove file"""
  159. file_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]
  160. paths = ["{}{}".format(file_name + "_cv", str(x).rjust(1, '0'))
  161. for x in range(FILES_NUM)]
  162. paths += ["{}{}".format(file_name + "_nlp", str(x).rjust(1, '0'))
  163. for x in range(FILES_NUM)]
  164. try:
  165. for x in paths:
  166. if os.path.exists("{}".format(x)):
  167. os.remove("{}".format(x))
  168. if os.path.exists("{}.db".format(x)):
  169. os.remove("{}.db".format(x))
  170. writer = FileWriter(file_name + "_nlp", FILES_NUM)
  171. data = list(get_nlp_data("../data/mindrecord/testAclImdbData/pos",
  172. "../data/mindrecord/testAclImdbData/vocab.txt",
  173. 10))
  174. nlp_schema_json = {"id": {"type": "string"}, "label": {"type": "int32"},
  175. "rating": {"type": "float32"},
  176. "input_ids": {"type": "int64",
  177. "shape": [1, -1]},
  178. "input_mask": {"type": "int64",
  179. "shape": [1, -1]},
  180. "segment_ids": {"type": "int64",
  181. "shape": [1, -1]}
  182. }
  183. writer.add_schema(nlp_schema_json, "nlp_schema")
  184. writer.add_index(["id", "rating"])
  185. writer.write_raw_data(data)
  186. writer.commit()
  187. writer = FileWriter(file_name + "_cv", FILES_NUM)
  188. data = get_data(CV_DIR_NAME)
  189. cv_schema_json = {"id": {"type": "int32"},
  190. "file_name": {"type": "string"},
  191. "label": {"type": "int32"},
  192. "data": {"type": "bytes"}}
  193. writer.add_schema(cv_schema_json, "img_schema")
  194. writer.add_index(["file_name", "label"])
  195. writer.write_raw_data(data)
  196. writer.commit()
  197. yield "yield_data"
  198. except Exception as error:
  199. for x in paths:
  200. os.remove("{}".format(x))
  201. os.remove("{}.db".format(x))
  202. raise error
  203. else:
  204. for x in paths:
  205. os.remove("{}".format(x))
  206. os.remove("{}.db".format(x))