forked from PaddlePaddle/PaddleNLP
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
Latest commit
409 lines (353 loc) Β· 15 KB
/
Copy pathutils.py
File metadata and controls
409 lines (353 loc) Β· 15 KB
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
# coding=utf-8
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
importjson
importmath
importrandom
importtime
fromurllib.errorimportURLError
fromurllib.parseimporturlencode
fromurllib.requestimportRequest, urlopen
importnumpyasnp
importpaddle
fromtqdmimporttqdm
defset_seed(seed):
paddle.seed(seed)
random.seed(seed)
np.random.seed(seed)
classASRError(Exception):
pass
defmandarin_asr_api(api_key, secret_key, audio_file, audio_format="wav"):
"""Mandarin ASR
Args:
audio_file (str):
Audio file of Mandarin with sampling rate 16000.
audio_format (str):
The file extension of audio_file, 'wav' by default.
Please refer to https://github.com/Baidu-AIP/speech-demo for more demos.
"""
# Configurations.
TOKEN_URL="http://aip.baidubce.com/oauth/2.0/token"
ASR_URL="http://vop.baidu.com/server_api"
SCOPE="audio_voice_assistant_get"
API_KEY=api_key
SECRET_KEY=secret_key
# Fetch tokens from TOKEN_URL.
post_data=urlencode(
{"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
).encode("utf-8")
request=Request(TOKEN_URL, post_data)
try:
result_str=urlopen(request).read()
exceptURLErroraserror:
print("token http response http code : "+str(error.code))
result_str=error.read()
result_str=result_str.decode()
result=json.loads(result_str)
if"access_token"inresult.keys() and"scope"inresult.keys():
ifSCOPEand (SCOPEnotinresult["scope"].split(" ")):
raiseASRError("scope is not correct!")
token=result["access_token"]
else:
raiseASRError(
"MAYBE API_KEY or SECRET_KEY not correct: "+"access_token or scope not found in token response"
)
# Fetch results by ASR api.
withopen(audio_file, "rb") asspeech_file:
speech_data=speech_file.read()
length=len(speech_data)
iflength==0:
raiseASRError("file %s length read 0 bytes"%audio_file)
params_query=urlencode({"cuid": "ASR", "token": token, "dev_pid": 1537})
headers= {"Content-Type": "audio/%s; rate=16000"%audio_format, "Content-Length": length}
url=ASR_URL+"?"+params_query
request=Request(url, speech_data, headers)
try:
begin=time.time()
result_str=urlopen(request).read()
print("Request time cost %f"% (time.time() -begin))
exceptURLErroraserror:
print("asr http response http code : "+str(error.code))
result_str=error.read()
result_str=str(result_str, "utf-8")
result=json.loads(result_str)
returnresult["result"][0]
@paddle.no_grad()
defevaluate(model, metric, data_loader):
"""
Given a dataset, it evals model and computes the metric.
Args:
model(obj:`paddle.nn.Layer`): A model to classify texts.
metric(obj:`paddle.metric.Metric`): The evaluation metric.
data_loader(obj:`paddle.io.DataLoader`): The dataset loader which generates batches.
"""
model.eval()
metric.reset()
forbatchindata_loader:
input_ids, token_type_ids, att_mask, pos_ids, start_ids, end_ids=batch
start_prob, end_prob=model(input_ids, token_type_ids, att_mask, pos_ids)
start_ids=paddle.cast(start_ids, "float32")
end_ids=paddle.cast(end_ids, "float32")
num_correct, num_infer, num_label=metric.compute(start_prob, end_prob, start_ids, end_ids)
metric.update(num_correct, num_infer, num_label)
precision, recall, f1=metric.accumulate()
model.train()
returnprecision, recall, f1
defconvert_example(example, tokenizer, max_seq_len):
"""
example: {
title
prompt
content
result_list
}
"""
encoded_inputs=tokenizer(
text=[example["prompt"]],
text_pair=[example["content"]],
stride=len(example["prompt"]),
truncation=True,
max_seq_len=max_seq_len,
pad_to_max_seq_len=True,
return_attention_mask=True,
return_position_ids=True,
return_dict=False,
)
encoded_inputs=encoded_inputs[0]
offset_mapping= [list(x) forxinencoded_inputs["offset_mapping"]]
bias=0
forindexinrange(len(offset_mapping)):
ifindex==0:
continue
mapping=offset_mapping[index]
ifmapping[0] ==0andmapping[1] ==0andbias==0:
bias=index
ifmapping[0] ==0andmapping[1] ==0:
continue
offset_mapping[index][0] +=bias
offset_mapping[index][1] +=bias
start_ids= [0forxinrange(max_seq_len)]
end_ids= [0forxinrange(max_seq_len)]
foriteminexample["result_list"]:
start=map_offset(item["start"] +bias, offset_mapping)
end=map_offset(item["end"] -1+bias, offset_mapping)
start_ids[start] =1.0
end_ids[end] =1.0
tokenized_output= [
encoded_inputs["input_ids"],
encoded_inputs["token_type_ids"],
encoded_inputs["position_ids"],
encoded_inputs["attention_mask"],
start_ids,
end_ids,
]
tokenized_output= [np.array(x, dtype="int64") forxintokenized_output]
returntuple(tokenized_output)
defmap_offset(ori_offset, offset_mapping):
"""
map ori offset to token offset
"""
forindex, spaninenumerate(offset_mapping):
ifspan[0] <=ori_offset<span[1]:
returnindex
return-1
defreader(data_path, max_seq_len=512):
"""
read json
"""
withopen(data_path, "r", encoding="utf-8") asf:
forlineinf:
json_line=json.loads(line)
content=json_line["content"]
prompt=json_line["prompt"]
# Model Input is aslike: [CLS] Prompt [SEP] Content [SEP]
# It include three summary tokens.
ifmax_seq_len<=len(prompt) +3:
raiseValueError("The value of max_seq_len is too small, please set a larger value")
max_content_len=max_seq_len-len(prompt) -3
iflen(content) <=max_content_len:
yieldjson_line
else:
result_list=json_line["result_list"]
json_lines= []
accumulate=0
whileTrue:
cur_result_list= []
forresultinresult_list:
ifresult["start"] +1<=max_content_len<result["end"]:
max_content_len=result["start"]
break
cur_content=content[:max_content_len]
res_content=content[max_content_len:]
whileTrue:
iflen(result_list) ==0:
break
elifresult_list[0]["end"] <=max_content_len:
ifresult_list[0]["end"] >0:
cur_result=result_list.pop(0)
cur_result_list.append(cur_result)
else:
cur_result_list= [resultforresultinresult_list]
break
else:
break
json_line= {"content": cur_content, "result_list": cur_result_list, "prompt": prompt}
json_lines.append(json_line)
forresultinresult_list:
ifresult["end"] <=0:
break
result["start"] -=max_content_len
result["end"] -=max_content_len
accumulate+=max_content_len
max_content_len=max_seq_len-len(prompt) -3
iflen(res_content) ==0:
break
eliflen(res_content) <max_content_len:
json_line= {"content": res_content, "result_list": result_list, "prompt": prompt}
json_lines.append(json_line)
break
else:
content=res_content
forjson_lineinjson_lines:
yieldjson_line
defadd_negative_example(examples, texts, prompts, label_set, negative_ratio):
withtqdm(total=len(prompts)) aspbar:
fori, promptinenumerate(prompts):
negtive_sample= []
redundants_list=list(set(label_set) ^set(prompt))
redundants_list.sort()
iflen(examples[i]) ==0:
continue
else:
actual_ratio=math.ceil(len(redundants_list) /len(examples[i]))
ifactual_ratio<=negative_ratio:
idxs= [kforkinrange(len(redundants_list))]
else:
idxs=random.sample(range(0, len(redundants_list)), negative_ratio*len(examples[i]))
foridxinidxs:
negtive_result= {"content": texts[i], "result_list": [], "prompt": redundants_list[idx]}
negtive_sample.append(negtive_result)
examples[i].extend(negtive_sample)
pbar.update(1)
returnexamples
defconstruct_relation_prompt_set(entity_name_set, predicate_set):
relation_prompt_set=set()
forentity_nameinentity_name_set:
forpredicateinpredicate_set:
# The relation prompt is constructed as follows:
# subject + "η" + predicate
relation_prompt=entity_name+"η"+predicate
relation_prompt_set.add(relation_prompt)
returnsorted(list(relation_prompt_set))
defconvert_ext_examples(raw_examples, negative_ratio):
texts= []
entity_examples= []
relation_examples= []
entity_prompts= []
relation_prompts= []
entity_label_set= []
entity_name_set= []
predicate_set= []
print("Converting doccano data...")
withtqdm(total=len(raw_examples)) aspbar:
forlineinraw_examples:
items=json.loads(line)
entity_id=0
if"data"initems.keys():
text=items["data"]
entities= []
foriteminitems["label"]:
entity= {"id": entity_id, "start_offset": item[0], "end_offset": item[1], "label": item[2]}
entities.append(entity)
entity_id+=1
relations= []
else:
text, relations, entities=items["text"], items["relations"], items["entities"]
texts.append(text)
entity_example= []
entity_prompt= []
entity_example_map= {}
entity_map= {} # id to entity name
forentityinentities:
entity_name=text[entity["start_offset"] : entity["end_offset"]]
entity_map[entity["id"]] = {
"name": entity_name,
"start": entity["start_offset"],
"end": entity["end_offset"],
}
entity_label=entity["label"]
result= {"text": entity_name, "start": entity["start_offset"], "end": entity["end_offset"]}
ifentity_labelnotinentity_example_map.keys():
entity_example_map[entity_label] = {
"content": text,
"result_list": [result],
"prompt": entity_label,
}
else:
entity_example_map[entity_label]["result_list"].append(result)
ifentity_labelnotinentity_label_set:
entity_label_set.append(entity_label)
ifentity_namenotinentity_name_set:
entity_name_set.append(entity_name)
entity_prompt.append(entity_label)
forvinentity_example_map.values():
entity_example.append(v)
entity_examples.append(entity_example)
entity_prompts.append(entity_prompt)
relation_example= []
relation_prompt= []
relation_example_map= {}
forrelationinrelations:
predicate=relation["type"]
subject_id=relation["from_id"]
object_id=relation["to_id"]
# The relation prompt is constructed as follows:
# subject + "η" + predicate
prompt=entity_map[subject_id]["name"] +"η"+predicate
result= {
"text": entity_map[object_id]["name"],
"start": entity_map[object_id]["start"],
"end": entity_map[object_id]["end"],
}
ifpromptnotinrelation_example_map.keys():
relation_example_map[prompt] = {"content": text, "result_list": [result], "prompt": prompt}
else:
relation_example_map[prompt]["result_list"].append(result)
ifpredicatenotinpredicate_set:
predicate_set.append(predicate)
relation_prompt.append(prompt)
forvinrelation_example_map.values():
relation_example.append(v)
relation_examples.append(relation_example)
relation_prompts.append(relation_prompt)
pbar.update(1)
print("Adding negative samples for first stage prompt...")
entity_examples=add_negative_example(entity_examples, texts, entity_prompts, entity_label_set, negative_ratio)
iflen(predicate_set) !=0:
print("Constructing relation prompts...")
relation_prompt_set=construct_relation_prompt_set(entity_name_set, predicate_set)
print("Adding negative samples for second stage prompt...")
relation_examples=add_negative_example(
relation_examples, texts, relation_prompts, relation_prompt_set, negative_ratio
)
returnentity_examples, relation_examples
defcreate_dataloader(dataset, mode="train", batch_size=1, batchify_fn=None, trans_fn=None):
iftrans_fn:
dataset=dataset.map(trans_fn)
shuffle=Trueifmode=="train"elseFalse
ifmode=="train":
batch_sampler=paddle.io.DistributedBatchSampler(dataset, batch_size=batch_size, shuffle=shuffle)
else:
batch_sampler=paddle.io.BatchSampler(dataset, batch_size=batch_size, shuffle=shuffle)
returnpaddle.io.DataLoader(dataset=dataset, batch_sampler=batch_sampler, collate_fn=batchify_fn, return_list=True)