-
Notifications
You must be signed in to change notification settings - Fork 0
/
trans_emb_utils.py
409 lines (350 loc) · 12.3 KB
/
trans_emb_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
### use py38
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import pandas as pd
import os
from functools import reduce
import pathlib
#import seaborn as sns
from copy import deepcopy
import jionlp as jio
#from zhon import hanzi
#from zhon.hanzi import non_stops
#import zhon
import networkx as nx
import argparse
import json
import re
from collections import defaultdict
import numpy as np
#from fuzzywuzzy import fuzz
from tqdm import tqdm
#import dedupe
from easynmt import EasyNMT
import jieba.posseg as posseg
# In[2]:
import os
import csv
import re
import logging
import optparse
#import dedupe
#from unidecode import unidecode
import shutil
from functools import lru_cache
from timer import timer
from sentence_transformers import SentenceTransformer
from time import time
from urllib.request import urlopen
import json
import requests
import jieba
import pickle as pkl
##### Give json output
#### search with post
port = "8899"
url_format = "http://localhost:{}/{}/{}"
search_task = "search"
#### add with post
add_task = "add"
searcht_task = "search_trans"
#### add with post
addt_task = "add_trans"
#### pass
def load_pickle(path):
with open(path, "rb") as f:
return pkl.load(f)
def save_pickle(obj, path):
with open(path, "wb") as f:
return pkl.dump(obj, f)
@timer()
def batch_as_list(a, batch_size = int(100000)):
req = []
for ele in a:
if not req:
req.append([])
if len(req[-1]) < batch_size:
req[-1].append(ele)
else:
req.append([])
req[-1].append(ele)
return req
@timer()
def embedding_produce_wrapper(input_sent_list, model, pool = None,
batch = True, batch_threshold = 1000,
):
def sent_emb_to_dict(req ,emb, exists_dict):
if not req:
assert emb is None
return exists_dict
if hasattr(emb, "numpy"):
emb = emb.numpy()
sent_array_map = map(lambda t2:(req[t2[0]], emb[t2[0]]) ,enumerate(req))
final = list(sent_array_map) + list(exists_dict.items())
final_dict = dict(final)
return final_dict
req = []
exists_dict = {}
if not batch:
for ele in input_sent_list:
#url = url_format.format(search_task, ele)
url = url_format.format(port ,search_task, "")[:-1]
response = requests.post(url, data = {'k_list': json.dumps([k])})
#search_result = urlopen(url).read()
search_result = response.content
search_json = json.loads(search_result)
'''
{
"embedding": [None or np.array obj] (list of, ) same length with k_list
}
'''
assert "embedding" in search_json
embedding = search_json["embedding"][0]
assert hasattr(ele, "__len__")
if not len(embedding):
req.append(ele)
else:
#assert hasattr(ele, "__len__")
exists_dict[ele] = embedding
else:
url = url_format.format(port ,search_task, "")[:-1]
response = requests.post(url, data = {'k_list': json.dumps(input_sent_list)})
#search_result = urlopen(url).read()
search_result = response.content
search_json = json.loads(search_result)
embedding_list = search_json["embedding"]
assert len(embedding_list) == len(input_sent_list)
for idx ,embedding in enumerate(embedding_list):
ele = input_sent_list[idx]
assert hasattr(ele, "__len__")
if not len(embedding):
req.append(ele)
else:
#assert hasattr(ele, "__len__")
exists_dict[ele] = embedding
if pool is None or len(req) <= batch_threshold:
if req:
embedding = model.encode(req)
else:
embedding = None
else:
if req:
embedding = model.encode_multi_process(req, pool, chunk_size=50)
else:
embedding = None
final_dict = sent_emb_to_dict(req ,embedding, exists_dict)
#print("final_dict :", final_dict)
##### this also should add check in server side.
add_dict = dict(filter(lambda t2: t2[0] not in exists_dict, final_dict.items()))
#print("add_dict :", add_dict)
if not batch:
for k, v in add_dict.items():
url = url_format.format(port ,add_task, "")[:-1]
assert hasttr(v, "size")
post_content = v.tolist()
#### check if not exists then add (insert)
requests.post(url, data = {'k_list': json.dumps([k]), 'arr_list': json.dumps([post_content])})
else:
url = url_format.format(port ,add_task, "")[:-1]
k_list = []
arr_list = []
for k, v in add_dict.items():
assert hasattr(v, "size")
k_list.append(k)
post_content = v.tolist()
arr_list.append(post_content)
##### limit every add section DATA_UPLOAD_MAX_MEMORY_SIZE
for k_, arr_ in zip(
batch_as_list(k_list, batch_threshold),
batch_as_list(arr_list, batch_threshold)
):
requests.post(url, data = {'k_list': json.dumps(k_), 'arr_list': json.dumps(arr_)})
#requests.post(url, data = {'k_list': json.dumps(k_list), 'arr_list': json.dumps(arr_list)})
l = []
for ele in input_sent_list:
l.append(final_dict[ele])
stack_emb = np.vstack(l)
assert len(stack_emb.shape) == 2 and stack_emb.shape[0] == len(input_sent_list)
return stack_emb
@timer()
def repeat_to_one_f(x):
req = None
for token in jieba.lcut(x):
#print("req :", req)
if len(set(token)) == 1:
token = token[0]
if req is None:
req = token
else:
if token in req:
continue
else:
while req.endswith(token[0]):
token = token[1:]
req = req + token
return req.strip()
@timer()
def repeat_to_one_fb(x):
return sorted(map(repeat_to_one_f, [x, "".join(jieba.lcut(x)[::-1])]),
key = len
)[0]
repeat_to_one = repeat_to_one_fb
@timer()
def do_one_trans_produce_wrapper(input_sent_list, model, pool = None,
batch = True, batch_threshold = 1000,
):
assert hasattr(model, "translate")
def sent_emb_to_dict(req ,emb, exists_dict):
if not req:
assert emb is None
return exists_dict
assert type(emb) == type([])
sent_array_map = map(lambda t2:(req[t2[0]], emb[t2[0]]) ,enumerate(req))
final = list(sent_array_map) + list(exists_dict.items())
final_dict = dict(final)
return final_dict
req = []
exists_dict = {}
if not batch:
for ele in input_sent_list:
#url = url_format.format(search_task, ele)
url = url_format.format(port ,searcht_task, "")[:-1]
response = requests.post(url, data = {'k_list': json.dumps([k])})
#search_result = urlopen(url).read()
search_result = response.content
search_json = json.loads(search_result)
'''
{
"embedding": [None or np.array obj] (list of, ) same length with k_list
}
'''
#assert "embedding" in search_json
assert "trans" in search_json
#embedding = search_json["embedding"][0]
embedding = search_json["trans"][0]
assert type(embedding) == type("")
assert hasattr(ele, "__len__")
if not len(embedding):
req.append(ele)
else:
#assert hasattr(ele, "__len__")
exists_dict[ele] = embedding
else:
url = url_format.format(port ,searcht_task, "")[:-1]
response = requests.post(url, data = {'k_list': json.dumps(input_sent_list)})
#search_result = urlopen(url).read()
search_result = response.content
search_json = json.loads(search_result)
#embedding_list = search_json["embedding"]
embedding_list = search_json["trans"]
assert len(embedding_list) == len(input_sent_list)
for idx ,embedding in enumerate(embedding_list):
ele = input_sent_list[idx]
assert hasattr(ele, "__len__")
assert type(embedding) == type("")
if not len(embedding):
req.append(ele)
else:
#assert hasattr(ele, "__len__")
exists_dict[ele] = embedding
if pool is None or len(req) <= batch_threshold:
if req:
trans_list = model.translate(req,
source_lang="en", target_lang = "zh")
trans_list = list(map(lambda x: repeat_to_one(x) if x else x ,trans_list))
else:
trans_list = None
else:
# model.translate_multi_process(process_pool,
# sentences, source_lang='en', target_lang='de', show_progress_bar=True)
if req:
trans_list = model.translate_multi_process(pool ,req,
source_lang="en", target_lang = "zh")
trans_list = list(map(lambda x: repeat_to_one(x) if x else x ,trans_list))
else:
trans_list = None
#final_dict = sent_emb_to_dict(req ,embedding, exists_dict)
final_dict = sent_emb_to_dict(req ,trans_list, exists_dict)
#print("final_dict :", final_dict)
##### this also should add check in server side.
add_dict = dict(filter(lambda t2: t2[0] not in exists_dict, final_dict.items()))
#print("add_dict :", add_dict)
if not batch:
for k, v in add_dict.items():
url = url_format.format(port ,addt_task, "")[:-1]
assert type(v) == type("")
post_content = v
#### check if not exists then add (insert)
requests.post(url, data = {'k_list': json.dumps([k]), 'arr_list': json.dumps([post_content])})
else:
url = url_format.format(port ,addt_task, "")[:-1]
k_list = []
arr_list = []
for k, v in add_dict.items():
#assert hasattr(v, "size")
assert type(v) == type("")
k_list.append(k)
#post_content = v.tolist()
post_content = v
arr_list.append(post_content)
##### limit every add section DATA_UPLOAD_MAX_MEMORY_SIZE
for k_, arr_ in zip(
batch_as_list(k_list, batch_threshold),
batch_as_list(arr_list, batch_threshold)
):
requests.post(url, data = {'k_list': json.dumps(k_), 'arr_list': json.dumps(arr_)})
#requests.post(url, data = {'k_list': json.dumps(k_list), 'arr_list': json.dumps(arr_list)})
l = []
for ele in input_sent_list:
l.append(final_dict[ele])
assert len(l) == len(input_sent_list)
return l
@timer()
def find_max_len_cut_b_with_entity_maintain_j(a, b, b_entity_list):
assert type(b_entity_list) == type([])
ner = jio.ner.LexiconNER(
{"Un_tokenize": list(set(b_entity_list))}
)
b_nered = ner(b)
def offset_len_split(b ,b_bered):
if not b_bered:
return [0, len(b)]
req = reduce(lambda a, b : a + b ,map(lambda x: x["offset"], b_bered))
return sorted(set(req + [0, len(b)]))
offset_indexes = offset_len_split(b, b_nered)
offset_indexes_nested = []
for i in range(len(offset_indexes) - 1):
offset_indexes_nested.append(
(offset_indexes[i], offset_indexes[i + 1])
)
def change_bucket(b_sliced):
assert type(b_sliced) == type("")
#print("b_scliced: {} {}".format(b_sliced, len(b_sliced)))
if len(b_sliced) >= 8:
bucket_func=lambda x: ["".join(x)]
elif len(b_sliced) >= 4:
bucket_func = lambda x: jieba.lcut("".join(x))
else:
bucket_func = lambda x: x
return bucket_func
#print("offset_indexes_nested :")
#print(offset_indexes_nested)
slice_map = map(lambda t2: [b[t2[0]: t2[1]]]
if b[t2[0]: t2[1]] in b_entity_list else
jieba.lcut("".join(b[t2[0]: t2[1]]))
, offset_indexes_nested)
slice_reduced = reduce(lambda a, b: a + b, slice_map)
return b_nered, slice_reduced
@timer()
def batch_as_list(a, batch_size = int(100000)):
req = []
for ele in a:
if not req:
req.append([])
if len(req[-1]) < batch_size:
req[-1].append(ele)
else:
req.append([])
req[-1].append(ele)
return req