|
from transformers import TokenClassificationPipeline |
|
|
|
class UniversalDependenciesPipeline(TokenClassificationPipeline): |
|
def _forward(self,model_input): |
|
import torch |
|
v=model_input["input_ids"][0].tolist() |
|
with torch.no_grad(): |
|
e=self.model(input_ids=torch.tensor([v[0:i]+[self.tokenizer.mask_token_id]+v[i+1:]+[j] for i,j in enumerate(v[1:-1],1)])) |
|
return {"logits":e.logits[:,1:-2,:],**model_input} |
|
def postprocess(self,model_output,**kwargs): |
|
import numpy |
|
import ufal.chu_liu_edmonds |
|
e=model_output["logits"].numpy() |
|
r=[1 if i==0 else -1 if j.endswith("|root") else 0 for i,j in sorted(self.model.config.id2label.items())] |
|
e+=numpy.where(numpy.add.outer(numpy.identity(e.shape[0]),r)==0,0,numpy.nan) |
|
m=numpy.full((e.shape[0]+1,e.shape[1]+1),numpy.nan) |
|
m[1:,1:]=numpy.nanmax(e,axis=2).transpose() |
|
p=numpy.zeros(m.shape) |
|
p[1:,1:]=numpy.nanargmax(e,axis=2).transpose() |
|
for i in range(1,m.shape[0]): |
|
m[i,0],m[i,i],p[i,0]=m[i,i],numpy.nan,p[i,i] |
|
h=ufal.chu_liu_edmonds.chu_liu_edmonds(m)[0] |
|
if [0 for i in h if i==0]!=[0]: |
|
m[:,0]+=numpy.where(m[:,0]<numpy.nanmax(m[:,0]),numpy.nan,0) |
|
h=ufal.chu_liu_edmonds.chu_liu_edmonds(m)[0] |
|
v=[(s,e) for s,e in model_output["offset_mapping"][0].tolist() if s<e] |
|
q=[self.model.config.id2label[p[i,j]].split("|") for i,j in enumerate(h)] |
|
if "aggregation_strategy" in kwargs and kwargs["aggregation_strategy"]!="none": |
|
for i,j in reversed(list(enumerate(q[2:],2))): |
|
if j[-1]=="goeswith": |
|
h=[b if i>b else b-1 for a,b in enumerate(h) if i!=a] |
|
v[i-2]=(v[i-2][0],v.pop(i-1)[1]) |
|
q.pop(i) |
|
t=model_output["sentence"].replace("\n"," ") |
|
u="# text = "+t+"\n" |
|
for i,(s,e) in enumerate(v,1): |
|
u+="\t".join([str(i),t[s:e],"_",q[i][0],"_","|".join(q[i][1:-1]),str(h[i]),q[i][-1],"_","_" if i<len(v) and e<v[i][0] else "SpaceAfter=No"])+"\n" |
|
return u+"\n" |
|
|