pre_process.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import psycopg2
  2. import numpy as np
  3. from BiddingKG.dl.common.Utils import embedding_word
  4. def get_sentence_index_list(sentence, dict_path='utils/ppocr_keys_v1.txt'):
  5. with open(dict_path, 'r') as f:
  6. character_list = f.readlines()
  7. for i in range(len(character_list)):
  8. character_list[i] = character_list[i][:-1]
  9. index_list = []
  10. for character in sentence:
  11. if character == '':
  12. index_list.append(0)
  13. elif character in character_list:
  14. _index = character_list.index(character) + 1
  15. index_list.append(_index)
  16. else:
  17. index_list.append(0)
  18. return index_list
  19. def postgresql_util(sql, limit):
  20. conn = psycopg2.connect(dbname="table_head_label", user="postgres", password="postgres",
  21. host="192.168.2.103")
  22. cursor = conn.cursor()
  23. cursor.execute(sql)
  24. print(sql)
  25. rows = cursor.fetchmany(1000)
  26. cnt = 0
  27. all_rows = []
  28. while rows:
  29. if cnt >= limit:
  30. break
  31. all_rows += rows
  32. cnt += len(rows)
  33. rows = cursor.fetchmany(1000)
  34. return all_rows
  35. def get_data_from_sql(dim=10):
  36. sql = """
  37. select table_text, pre_label, post_label, id
  38. from label_table_head_info
  39. where update_user <> 'test27' and table_box_cnt >= 4 and table_box_cnt <= 200
  40. ;
  41. """
  42. # sql = """
  43. # select table_text, pre_label, post_label, id
  44. # from label_table_head_info
  45. # where id = 843
  46. # """
  47. result_list = postgresql_util(sql, limit=1000000)
  48. all_data_list = []
  49. all_data_label_list = []
  50. i = 0
  51. # 一行就是一篇表格
  52. for table in result_list:
  53. i += 1
  54. if i % 100 == 0:
  55. print("Loop", i)
  56. pre_label = eval(table[1])
  57. post_label = eval(table[2])
  58. _id = table[3]
  59. # table_text需要特殊处理
  60. try:
  61. table_text = table[0]
  62. if table_text[0] == '"':
  63. table_text = eval(table_text)
  64. else:
  65. table_text = table_text
  66. table_text = table_text.replace('\\', '/')
  67. table_text = eval(table_text)
  68. except:
  69. print("无法识别table_text", _id)
  70. continue
  71. # 只有一行的也不要
  72. if len(post_label) >= 2:
  73. data_list, data_label_list = table_process(table_text, post_label, _id)
  74. elif len(pre_label) >= 2:
  75. data_list, data_label_list = table_process(table_text, pre_label, _id)
  76. else:
  77. data_list, data_label_list = [], []
  78. all_data_list += data_list
  79. all_data_label_list += data_label_list
  80. print("len(all_data_list)", len(all_data_list))
  81. #
  82. # new_data_list = []
  83. # for data in data_list:
  84. # # 中文字符映射为index
  85. # # data[0] = get_sentence_index_list(data[0])
  86. # # data[1] = get_sentence_index_list(data[1])
  87. # # 维度不够,填充掩码0
  88. # # if len(data[0]) < dim:
  89. # # data[0] = data[0] + [0]*(dim-len(data[0]))
  90. # # elif len(data[0]) > dim:
  91. # # data[0] = data[0][:dim]
  92. # # if len(data[1]) < dim:
  93. # # data[1] = data[1] + [0]*(dim-len(data[1]))
  94. # # elif len(data[1]) > dim:
  95. # # data[1] = data[1][:dim]
  96. #
  97. # # 中文字符映射为Embedding
  98. # data = embedding_word(data, input_shape)
  99. # new_data_list.append(data)
  100. #
  101. # new_data_list = np.array(new_data_list)
  102. # data_label_list = np.array(data_label_list)
  103. # if np.array(new_data_list).shape[1:] == input_shape:
  104. # all_data_list.append(new_data_list)
  105. # all_data_label_list.append(data_label_list)
  106. # # 防止concat太慢
  107. # split_len = 1000
  108. # _len = int(len(all_data_list) / split_len)
  109. # all_data_list_1 = []
  110. # all_data_list_2 = []
  111. # for i in range(_len):
  112. # if i == _len - 1:
  113. # array1 = np.concatenate(all_data_list[i*split_len:])
  114. # array2 = np.concatenate(all_data_label_list[i*split_len:])
  115. # else:
  116. # array1 = np.concatenate(all_data_list[i*split_len:i*split_len+split_len])
  117. # array2 = np.concatenate(all_data_label_list[i*split_len:i*split_len+split_len])
  118. # all_data_list_1.append(array1)
  119. # all_data_list_2.append(array2)
  120. # all_data_list = np.concatenate(all_data_list_1)
  121. # all_data_label_list = np.concatenate(all_data_list_2)
  122. return all_data_list, all_data_label_list
  123. def table_process(text_list, label_list, _id):
  124. if len(text_list) != len(label_list):
  125. print("文字单元格与标注单元格数量不匹配!", _id)
  126. print("len(text_list)", len(text_list), "len(label_list)", len(label_list))
  127. return [], []
  128. data_list = []
  129. data_label_list = []
  130. for i in range(len(text_list)):
  131. row = text_list[i]
  132. row_label = label_list[i]
  133. if i > 0:
  134. last_row = text_list[i-1]
  135. last_row_label = label_list[i-1]
  136. else:
  137. last_row = []
  138. last_row_label = []
  139. if i < len(text_list) - 1:
  140. next_row = text_list[i+1]
  141. next_row_label = label_list[i+1]
  142. else:
  143. next_row = []
  144. next_row_label = []
  145. for j in range(len(row)):
  146. col = row[j]
  147. col_label = row_label[j]
  148. # 超出表格置为None, 0
  149. if j > 0:
  150. last_col = row[j-1]
  151. last_col_label = row_label[j-1]
  152. else:
  153. last_col = None
  154. last_col_label = 0
  155. if j < len(row) - 1:
  156. next_col = row[j+1]
  157. next_col_label = row_label[j+1]
  158. else:
  159. next_col = None
  160. next_col_label = 0
  161. if last_row:
  162. last_row_col = last_row[j]
  163. last_row_col_label = last_row_label[j]
  164. else:
  165. last_row_col = None
  166. last_row_col_label = 0
  167. if next_row:
  168. next_row_col = next_row[j]
  169. next_row_col_label = next_row_label[j]
  170. else:
  171. next_row_col = None
  172. next_row_col_label = 0
  173. # 三元组有一对不相等就作为数据
  174. # if col != next_col or col != last_col:
  175. data_list.append([last_col, col, next_col])
  176. data_label_list.append([int(last_col_label), int(col_label),
  177. int(next_col_label)])
  178. # if col != next_row_col or col != last_row_col:
  179. data_list.append([last_row_col, col, next_row_col])
  180. data_label_list.append([int(last_row_col_label), int(col_label),
  181. int(next_row_col_label)])
  182. return data_list, data_label_list
  183. def get_data_from_file(file_type):
  184. if file_type == 'np':
  185. data_path = 'train_data/data_3.npy'
  186. data_label_path = 'train_data/data_label_3.npy'
  187. array1 = np.load(data_path)
  188. array2 = np.load(data_label_path)
  189. return array1, array2
  190. elif file_type == 'txt':
  191. data_path = 'train_data/data.txt'
  192. data_label_path = 'train_data/data_label.txt'
  193. with open(data_path, 'r') as f:
  194. data_list = f.readlines()
  195. with open(data_label_path, 'r') as f:
  196. data_label_list = f.readlines()
  197. # for i in range(len(data_list)):
  198. # data_list[i] = eval(data_list[i][:-1])
  199. # data_label_list[i] = eval(data_label_list[i][:-1])
  200. return data_list, data_label_list
  201. else:
  202. print("file type error! only np and txt supported")
  203. raise Exception
  204. def processed_save_to_np():
  205. array1, array2 = get_data_from_sql()
  206. np.save('train_data/data_3.npy', array1)
  207. np.save('train_data/data_label_3.npy', array2)
  208. # with open('train_data/data.txt', 'w') as f:
  209. # for line in list1:
  210. # f.write(str(line) + "\n")
  211. # with open('train_data/data_label.txt', 'w') as f:
  212. # for line in list2:
  213. # f.write(str(line) + "\n")
  214. def processed_save_to_txt():
  215. list1, list2 = get_data_from_sql()
  216. with open('train_data/data.txt', 'w') as f:
  217. for line in list1:
  218. f.write(str(line) + "\n")
  219. with open('train_data/data_label.txt', 'w') as f:
  220. for line in list2:
  221. f.write(str(line) + "\n")
  222. def data_balance():
  223. array1, array2 = get_data_from_file()
  224. data_list = array2.tolist()
  225. all_cnt = len(data_list)
  226. cnt_0 = 0
  227. cnt_1 = 0
  228. for data in data_list:
  229. if data[0] == 1 or data[1] == 1:
  230. cnt_1 += 1
  231. else:
  232. cnt_0 += 1
  233. print("all_cnt", all_cnt)
  234. print("label has 1", cnt_1)
  235. print("label all 0", cnt_0)
  236. def test_embedding():
  237. output_shape = (2, 1, 60)
  238. data = [[None], [None]]
  239. result = embedding_word(data, output_shape)
  240. print(result)
  241. def my_data_loader(data_list, data_label_list, batch_size):
  242. data_num = len(data_list)
  243. # 定义Embedding输出
  244. output_shape = (3, 10, 60)
  245. # batch循环取数据
  246. i = 0
  247. while True:
  248. new_data_list = []
  249. for j in range(batch_size):
  250. if i >= data_num:
  251. i = 0
  252. # 中文字符映射为Embedding
  253. data = eval(data_list[i][:-1])
  254. data = embedding_word(data, output_shape)
  255. if data.shape == output_shape:
  256. new_data_list.append(data)
  257. i += 1
  258. new_data_list = np.array(new_data_list)
  259. data_label_list = np.array(data_label_list)
  260. X = new_data_list
  261. Y = data_label_list
  262. # (table_num, 3 sentences, dim characters, embedding) -> (3, table_num, dim, embedding)
  263. X = np.transpose(X, (1, 0, 2, 3))
  264. yield [X[0], X[1], X[2]], Y
  265. if __name__ == '__main__':
  266. processed_save_to_txt()
  267. # data_balance()
  268. # test_embedding()