predictor.py 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988
  1. '''
  2. Created on 2018年12月26日
  3. @author: User
  4. '''
  5. import os
  6. import sys
  7. from BiddingKG.dl.common.nerUtils import *
  8. sys.path.append(os.path.abspath("../.."))
  9. # from keras.engine import topology
  10. # from keras import models
  11. # from keras import layers
  12. # from keras_contrib.layers.crf import CRF
  13. # from keras.preprocessing.sequence import pad_sequences
  14. # from keras import optimizers,losses,metrics
  15. from BiddingKG.dl.common.Utils import *
  16. from BiddingKG.dl.interface.modelFactory import *
  17. import tensorflow as tf
  18. from BiddingKG.dl.product.data_util import decode, process_data
  19. from BiddingKG.dl.interface.Entitys import Entity
  20. from BiddingKG.dl.complaint.punish_predictor import Punish_Extract
  21. from threading import RLock
  22. dict_predictor = {"codeName":{"predictor":None,"Lock":RLock()},
  23. "prem":{"predictor":None,"Lock":RLock()},
  24. "epc":{"predictor":None,"Lock":RLock()},
  25. "roleRule":{"predictor":None,"Lock":RLock()},
  26. "form":{"predictor":None,"Lock":RLock()},
  27. "time":{"predictor":None,"Lock":RLock()},
  28. "punish":{"predictor":None,"Lock":RLock()},
  29. "product":{"predictor":None,"Lock":RLock()},
  30. "channel": {"predictor": None, "Lock": RLock()}}
  31. def getPredictor(_type):
  32. if _type in dict_predictor:
  33. with dict_predictor[_type]["Lock"]:
  34. if dict_predictor[_type]["predictor"] is None:
  35. if _type=="codeName":
  36. dict_predictor[_type]["predictor"] = CodeNamePredict()
  37. if _type=="prem":
  38. dict_predictor[_type]["predictor"] = PREMPredict()
  39. if _type=="epc":
  40. dict_predictor[_type]["predictor"] = EPCPredict()
  41. if _type=="roleRule":
  42. dict_predictor[_type]["predictor"] = RoleRulePredictor()
  43. if _type=="form":
  44. dict_predictor[_type]["predictor"] = FormPredictor()
  45. if _type=="time":
  46. dict_predictor[_type]["predictor"] = TimePredictor()
  47. if _type=="punish":
  48. dict_predictor[_type]["predictor"] = Punish_Extract()
  49. if _type=="product":
  50. dict_predictor[_type]["predictor"] = ProductPredictor()
  51. if _type == "channel":
  52. dict_predictor[_type]["predictor"] = DocChannel()
  53. return dict_predictor[_type]["predictor"]
  54. raise NameError("no this type of predictor")
  55. #编号名称模型
  56. class CodeNamePredict():
  57. def __init__(self,EMBED_DIM=None,BiRNN_UNITS=None,lazyLoad=getLazyLoad()):
  58. self.model = None
  59. self.MAX_LEN = None
  60. self.model_code = None
  61. if EMBED_DIM is None:
  62. self.EMBED_DIM = 60
  63. else:
  64. self.EMBED_DIM = EMBED_DIM
  65. if BiRNN_UNITS is None:
  66. self.BiRNN_UNITS = 200
  67. else:
  68. self.BiRNN_UNITS = BiRNN_UNITS
  69. self.filepath = os.path.dirname(__file__)+"/../projectCode/models/model_project_"+str(self.EMBED_DIM)+"_"+str(self.BiRNN_UNITS)+".hdf5"
  70. #self.filepath = "../projectCode/models/model_project_60_200_200ep017-loss6.456-val_loss7.852-val_acc0.969.hdf5"
  71. self.filepath_code = os.path.dirname(__file__)+"/../projectCode/models/model_code.hdf5"
  72. vocabpath = os.path.dirname(__file__)+"/codename_vocab.pk"
  73. classlabelspath = os.path.dirname(__file__)+"/codename_classlabels.pk"
  74. self.vocab = load(vocabpath)
  75. self.class_labels = load(classlabelspath)
  76. #生成提取编号和名称的正则
  77. id_PC_B = self.class_labels.index("PC_B")
  78. id_PC_M = self.class_labels.index("PC_M")
  79. id_PC_E = self.class_labels.index("PC_E")
  80. id_PN_B = self.class_labels.index("PN_B")
  81. id_PN_M = self.class_labels.index("PN_M")
  82. id_PN_E = self.class_labels.index("PN_E")
  83. self.PC_pattern = re.compile(str(id_PC_B)+str(id_PC_M)+"*"+str(id_PC_E))
  84. self.PN_pattern = re.compile(str(id_PN_B)+str(id_PN_M)+"*"+str(id_PN_E))
  85. print("pc",self.PC_pattern)
  86. print("pn",self.PN_pattern)
  87. self.word2index = dict((w,i) for i,w in enumerate(np.array(self.vocab)))
  88. self.inputs = None
  89. self.outputs = None
  90. self.sess_codename = tf.Session(graph=tf.Graph())
  91. self.sess_codesplit = tf.Session(graph=tf.Graph())
  92. self.inputs_code = None
  93. self.outputs_code = None
  94. if not lazyLoad:
  95. self.getModel()
  96. self.getModel_code()
  97. def getModel(self):
  98. '''
  99. @summary: 取得编号和名称模型
  100. '''
  101. if self.inputs is None:
  102. log("get model of codename")
  103. with self.sess_codename.as_default():
  104. with self.sess_codename.graph.as_default():
  105. meta_graph_def = tf.saved_model.loader.load(self.sess_codename, ["serve"], export_dir=os.path.dirname(__file__)+"/codename_savedmodel_tf")
  106. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  107. signature_def = meta_graph_def.signature_def
  108. self.inputs = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].inputs["inputs"].name)
  109. self.inputs_length = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].inputs["inputs_length"].name)
  110. self.keepprob = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].inputs["keepprob"].name)
  111. self.logits = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].outputs["logits"].name)
  112. self.trans = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].outputs["trans"].name)
  113. return self.inputs,self.inputs_length,self.keepprob,self.logits,self.trans
  114. else:
  115. return self.inputs,self.inputs_length,self.keepprob,self.logits,self.trans
  116. '''
  117. if self.model is None:
  118. self.model = self.getBiLSTMCRFModel(self.MAX_LEN, self.vocab, self.EMBED_DIM, self.BiRNN_UNITS, self.class_labels,weights=None)
  119. self.model.load_weights(self.filepath)
  120. return self.model
  121. '''
  122. def getModel_code(self):
  123. if self.inputs_code is None:
  124. log("get model of code")
  125. with self.sess_codesplit.as_default():
  126. with self.sess_codesplit.graph.as_default():
  127. meta_graph_def = tf.saved_model.loader.load(self.sess_codesplit, ["serve"], export_dir=os.path.dirname(__file__)+"/codesplit_savedmodel")
  128. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  129. signature_def = meta_graph_def.signature_def
  130. self.inputs_code = []
  131. self.inputs_code.append(self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].inputs["input0"].name))
  132. self.inputs_code.append(self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].inputs["input1"].name))
  133. self.inputs_code.append(self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].inputs["input2"].name))
  134. self.outputs_code = self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].outputs["outputs"].name)
  135. self.sess_codesplit.graph.finalize()
  136. return self.inputs_code,self.outputs_code
  137. else:
  138. return self.inputs_code,self.outputs_code
  139. '''
  140. if self.model_code is None:
  141. log("get model of model_code")
  142. with self.sess_codesplit.as_default():
  143. with self.sess_codesplit.graph.as_default():
  144. self.model_code = models.load_model(self.filepath_code, custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score})
  145. return self.model_code
  146. '''
  147. def getBiLSTMCRFModel(self,MAX_LEN,vocab,EMBED_DIM,BiRNN_UNITS,chunk_tags,weights):
  148. '''
  149. model = models.Sequential()
  150. model.add(layers.Embedding(len(vocab), EMBED_DIM, mask_zero=True)) # Random embedding
  151. model.add(layers.Bidirectional(layers.LSTM(BiRNN_UNITS // 2, return_sequences=True)))
  152. crf = CRF(len(chunk_tags), sparse_target=True)
  153. model.add(crf)
  154. model.summary()
  155. model.compile('adam', loss=crf.loss_function, metrics=[crf.accuracy])
  156. return model
  157. '''
  158. input = layers.Input(shape=(None,))
  159. if weights is not None:
  160. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True,weights=[weights],trainable=True)(input)
  161. else:
  162. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True)(input)
  163. bilstm = layers.Bidirectional(layers.LSTM(BiRNN_UNITS//2,return_sequences=True))(embedding)
  164. bilstm_dense = layers.TimeDistributed(layers.Dense(len(chunk_tags)))(bilstm)
  165. crf = CRF(len(chunk_tags),sparse_target=True)
  166. crf_out = crf(bilstm_dense)
  167. model = models.Model(input=[input],output = [crf_out])
  168. model.summary()
  169. model.compile(optimizer = 'adam', loss = crf.loss_function, metrics = [crf.accuracy])
  170. return model
  171. #根据规则补全编号或名称两边的符号
  172. def fitDataByRule(self,data):
  173. symbol_dict = {"(":")",
  174. "(":")",
  175. "[":"]",
  176. "【":"】",
  177. ")":"(",
  178. ")":"(",
  179. "]":"[",
  180. "】":"【"}
  181. leftSymbol_pattern = re.compile("[\((\[【]")
  182. rightSymbol_pattern = re.compile("[\))\]】]")
  183. leftfinds = re.findall(leftSymbol_pattern,data)
  184. rightfinds = re.findall(rightSymbol_pattern,data)
  185. result = data
  186. if len(leftfinds)+len(rightfinds)==0:
  187. return data
  188. elif len(leftfinds)==len(rightfinds):
  189. return data
  190. elif abs(len(leftfinds)-len(rightfinds))==1:
  191. if len(leftfinds)>len(rightfinds):
  192. if symbol_dict.get(data[0]) is not None:
  193. result = data[1:]
  194. else:
  195. #print(symbol_dict.get(leftfinds[0]))
  196. result = data+symbol_dict.get(leftfinds[0])
  197. else:
  198. if symbol_dict.get(data[-1]) is not None:
  199. result = data[:-1]
  200. else:
  201. result = symbol_dict.get(rightfinds[0])+data
  202. return result
  203. def decode(self,logits, trans, sequence_lengths, tag_num):
  204. viterbi_sequences = []
  205. for logit, length in zip(logits, sequence_lengths):
  206. score = logit[:length]
  207. viterbi_seq, viterbi_score = viterbi_decode(score, trans)
  208. viterbi_sequences.append(viterbi_seq)
  209. return viterbi_sequences
  210. def predict(self,list_sentences,list_entitys=None,MAX_AREA = 5000):
  211. #@summary: 获取每篇文章的code和name
  212. pattern_score = re.compile("工程|服务|采购|施工|项目|系统|招标|中标|公告|学校|[大中小]学校?|医院|公司|分公司|研究院|政府采购中心|学院|中心校?|办公室|政府|财[政务]局|办事处|委员会|[部总支]队|警卫局|幼儿园|党委|党校|银行|分行|解放军|发电厂|供电局|管理所|供电公司|卷烟厂|机务段|研究[院所]|油厂|调查局|调查中心|出版社|电视台|监狱|水厂|服务站|信用合作联社|信用社|交易所|交易中心|交易中心党校|科学院|测绘所|运输厅|管理处|局|中心|机关|部门?|处|科|厂|集团|图书馆|馆|所|厅|楼|区|酒店|场|基地|矿|餐厅|酒店")
  213. result = []
  214. index_unk = self.word2index.get("<unk>")
  215. # index_pad = self.word2index.get("<pad>")
  216. if list_entitys is None:
  217. list_entitys = [[] for _ in range(len(list_sentences))]
  218. for list_sentence,list_entity in zip(list_sentences,list_entitys):
  219. if len(list_sentence)==0:
  220. result.append([{"code":[],"name":""}])
  221. continue
  222. doc_id = list_sentence[0].doc_id
  223. # sentences = []
  224. # for sentence in list_sentence:
  225. # if len(sentence.sentence_text)>MAX_AREA:
  226. # for _sentence_comma in re.split("[;;,\n]",sentence):
  227. # _comma_index = 0
  228. # while(_comma_index<len(_sentence_comma)):
  229. # sentences.append(_sentence_comma[_comma_index:_comma_index+MAX_AREA])
  230. # _comma_index += MAX_AREA
  231. # else:
  232. # sentences.append(sentence+"。")
  233. list_sentence.sort(key=lambda x:len(x.sentence_text),reverse=True)
  234. _begin_index = 0
  235. item = {"code":[],"name":""}
  236. code_set = set()
  237. dict_name_freq_score = dict()
  238. while(True):
  239. MAX_LEN = len(list_sentence[_begin_index].sentence_text)
  240. if MAX_LEN>MAX_AREA:
  241. MAX_LEN = MAX_AREA
  242. _LEN = MAX_AREA//MAX_LEN
  243. #预测
  244. x = [[self.word2index.get(word,index_unk)for word in sentence.sentence_text[:MAX_AREA]]for sentence in list_sentence[_begin_index:_begin_index+_LEN]]
  245. # x = [[getIndexOfWord(word) for word in sentence.sentence_text[:MAX_AREA]]for sentence in list_sentence[_begin_index:_begin_index+_LEN]]
  246. x_len = [len(_x) if len(_x) < MAX_LEN else MAX_LEN for _x in x]
  247. x = pad_sequences(x,maxlen=MAX_LEN,padding="post",truncating="post")
  248. if USE_PAI_EAS:
  249. request = tf_predict_pb2.PredictRequest()
  250. request.inputs["inputs"].dtype = tf_predict_pb2.DT_INT32
  251. request.inputs["inputs"].array_shape.dim.extend(np.shape(x))
  252. request.inputs["inputs"].int_val.extend(np.array(x,dtype=np.int32).reshape(-1))
  253. request_data = request.SerializeToString()
  254. list_outputs = ["outputs"]
  255. _result = vpc_requests(codename_url, codename_authorization, request_data, list_outputs)
  256. if _result is not None:
  257. predict_y = _result["outputs"]
  258. else:
  259. with self.sess_codename.as_default():
  260. t_input,t_output = self.getModel()
  261. predict_y = self.sess_codename.run(t_output,feed_dict={t_input:x})
  262. else:
  263. with self.sess_codename.as_default():
  264. t_input,t_input_length,t_keepprob,t_logits,t_trans = self.getModel()
  265. _logits,_trans = self.sess_codename.run([t_logits,t_trans],feed_dict={t_input:x,
  266. t_input_length:x_len,
  267. t_keepprob:1.0})
  268. predict_y = self.decode(_logits,_trans,x_len,7)
  269. # print('==========',_logits)
  270. '''
  271. for item11 in np.argmax(predict_y,-1):
  272. print(item11)
  273. print(predict_y)
  274. '''
  275. # print(predict_y)
  276. for sentence,predict in zip(list_sentence[_begin_index:_begin_index+_LEN],np.array(predict_y)):
  277. pad_sentence = sentence.sentence_text[:MAX_LEN]
  278. join_predict = "".join([str(s) for s in predict])
  279. # print(pad_sentence)
  280. # print(join_predict)
  281. code_x = []
  282. code_text = []
  283. temp_entitys = []
  284. for iter in re.finditer(self.PC_pattern,join_predict):
  285. get_len = 40
  286. if iter.span()[0]<get_len:
  287. begin = 0
  288. else:
  289. begin = iter.span()[0]-get_len
  290. end = iter.span()[1]+get_len
  291. code_x.append(embedding_word([pad_sentence[begin:iter.span()[0]],pad_sentence[iter.span()[0]:iter.span()[1]],pad_sentence[iter.span()[1]:end]],shape=(3,get_len,60)))
  292. code_text.append(pad_sentence[iter.span()[0]:iter.span()[1]])
  293. _entity = Entity(doc_id=sentence.doc_id,entity_id="%s_%s_%s_%s"%(sentence.doc_id,sentence.sentence_index,iter.span()[0],iter.span()[1]),entity_text=pad_sentence[iter.span()[0]:iter.span()[1]],entity_type="code",sentence_index=sentence.sentence_index,begin_index=0,end_index=0,wordOffset_begin=iter.span()[0],wordOffset_end=iter.span()[1])
  294. temp_entitys.append(_entity)
  295. #print("code",code_text)
  296. if len(code_x)>0:
  297. code_x = np.transpose(np.array(code_x,dtype=np.float32),(1,0,2,3))
  298. if USE_PAI_EAS:
  299. request = tf_predict_pb2.PredictRequest()
  300. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  301. request.inputs["input0"].array_shape.dim.extend(np.shape(code_x[0]))
  302. request.inputs["input0"].float_val.extend(np.array(code_x[0],dtype=np.float64).reshape(-1))
  303. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  304. request.inputs["input1"].array_shape.dim.extend(np.shape(code_x[1]))
  305. request.inputs["input1"].float_val.extend(np.array(code_x[1],dtype=np.float64).reshape(-1))
  306. request.inputs["input2"].dtype = tf_predict_pb2.DT_FLOAT
  307. request.inputs["input2"].array_shape.dim.extend(np.shape(code_x[2]))
  308. request.inputs["input2"].float_val.extend(np.array(code_x[2],dtype=np.float64).reshape(-1))
  309. request_data = request.SerializeToString()
  310. list_outputs = ["outputs"]
  311. _result = vpc_requests(codeclasses_url, codeclasses_authorization, request_data, list_outputs)
  312. if _result is not None:
  313. predict_code = _result["outputs"]
  314. else:
  315. with self.sess_codesplit.as_default():
  316. with self.sess_codesplit.graph.as_default():
  317. predict_code = self.getModel_code().predict([code_x[0],code_x[1],code_x[2]])
  318. else:
  319. with self.sess_codesplit.as_default():
  320. with self.sess_codesplit.graph.as_default():
  321. inputs_code,outputs_code = self.getModel_code()
  322. predict_code = limitRun(self.sess_codesplit,[outputs_code],feed_dict={inputs_code[0]:code_x[0],inputs_code[1]:code_x[1],inputs_code[2]:code_x[2]},MAX_BATCH=2)[0]
  323. #predict_code = self.sess_codesplit.run(outputs_code,feed_dict={inputs_code[0]:code_x[0],inputs_code[1]:code_x[1],inputs_code[2]:code_x[2]})
  324. #predict_code = self.getModel_code().predict([code_x[0],code_x[1],code_x[2]])
  325. for h in range(len(predict_code)):
  326. if predict_code[h][0]>0.5:
  327. the_code = self.fitDataByRule(code_text[h])
  328. #add code to entitys
  329. list_entity.append(temp_entitys[h])
  330. if the_code not in code_set:
  331. code_set.add(the_code)
  332. item['code'] = list(code_set)
  333. for iter in re.finditer(self.PN_pattern,join_predict):
  334. _name = self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  335. #add name to entitys
  336. _entity = Entity(doc_id=sentence.doc_id,entity_id="%s_%s_%s_%s"%(sentence.doc_id,sentence.sentence_index,iter.span()[0],iter.span()[1]),entity_text=_name,entity_type="name",sentence_index=sentence.sentence_index,begin_index=0,end_index=0,wordOffset_begin=iter.span()[0],wordOffset_end=iter.span()[1])
  337. list_entity.append(_entity)
  338. w = 1 if re.search('(项目|工程|招标|合同|标项|标的|计划|询价|询价单|询价通知书|申购)(名称|标题|主题)[::\s]', pad_sentence[iter.span()[0]-10:iter.span()[0]])!=None else 0.5
  339. if _name not in dict_name_freq_score:
  340. # dict_name_freq_score[_name] = [1,len(re.findall(pattern_score,_name))+len(_name)*0.1]
  341. dict_name_freq_score[_name] = [1, (len(re.findall(pattern_score, _name)) + len(_name) * 0.05)*w]
  342. else:
  343. dict_name_freq_score[_name][0] += 1
  344. '''
  345. for iter in re.finditer(self.PN_pattern,join_predict):
  346. print("name-",self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]]))
  347. if item[1]['name']=="":
  348. for iter in re.finditer(self.PN_pattern,join_predict):
  349. #item[1]['name']=item[1]['name']+";"+self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  350. item[1]['name']=self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  351. break
  352. '''
  353. if _begin_index+_LEN>=len(list_sentence):
  354. break
  355. _begin_index += _LEN
  356. list_name_freq_score = []
  357. # 2020/11/23 大网站规则调整
  358. if len(dict_name_freq_score) == 0:
  359. name_re1 = '(项目|工程|招标|合同|标项|标的|计划|询价|询价单|询价通知书|申购)(名称|标题|主题)[::\s]+([^,。:;]{2,60})[,。]'
  360. for sentence in list_sentence:
  361. # pad_sentence = sentence.sentence_text
  362. othername = re.search(name_re1, sentence.sentence_text)
  363. if othername != None:
  364. project_name = othername.group(3)
  365. beg = find_index([project_name], sentence.sentence_text)[0]
  366. end = beg + len(project_name)
  367. _name = self.fitDataByRule(sentence.sentence_text[beg:end])
  368. # add name to entitys
  369. _entity = Entity(doc_id=sentence.doc_id, entity_id="%s_%s_%s_%s" % (
  370. sentence.doc_id, sentence.sentence_index, beg, end), entity_text=_name,
  371. entity_type="name", sentence_index=sentence.sentence_index, begin_index=0,
  372. end_index=0, wordOffset_begin=beg, wordOffset_end=end)
  373. list_entity.append(_entity)
  374. w = 1
  375. if _name not in dict_name_freq_score:
  376. # dict_name_freq_score[_name] = [1,len(re.findall(pattern_score,_name))+len(_name)*0.1]
  377. dict_name_freq_score[_name] = [1, (len(re.findall(pattern_score, _name)) + len(_name) * 0.05) * w]
  378. else:
  379. dict_name_freq_score[_name][0] += 1
  380. # othername = re.search(name_re1, sentence.sentence_text)
  381. # if othername != None:
  382. # _name = othername.group(3)
  383. # if _name not in dict_name_freq_score:
  384. # dict_name_freq_score[_name] = [1, len(re.findall(pattern_score, _name)) + len(_name) * 0.1]
  385. # else:
  386. # dict_name_freq_score[_name][0] += 1
  387. for _name in dict_name_freq_score.keys():
  388. list_name_freq_score.append([_name,dict_name_freq_score[_name]])
  389. # print(list_name_freq_score)
  390. if len(list_name_freq_score)>0:
  391. list_name_freq_score.sort(key=lambda x:x[1][0]*x[1][1],reverse=True)
  392. item['name'] = list_name_freq_score[0][0]
  393. # if list_name_freq_score[0][1][0]>1:
  394. # item[1]['name'] = list_name_freq_score[0][0]
  395. # else:
  396. # list_name_freq_score.sort(key=lambda x:x[1][1],reverse=True)
  397. # item[1]["name"] = list_name_freq_score[0][0]
  398. #下面代码加上去用正则添加某些识别不到的项目编号
  399. if item['code'] == []:
  400. for sentence in list_sentence:
  401. # othercode = re.search('(采购计划编号|询价编号)[\))]?[::]?([\[\]a-zA-Z0-9\-]{5,30})', sentence.sentence_text)
  402. # if othercode != None:
  403. # item[1]['code'].append(othercode.group(2))
  404. # 2020/11/23 大网站规则调整
  405. othercode = re.search('(项目|采购|招标|品目|询价|竞价|询价单|磋商|订单|账单|交易|文件|计划|场次|标的|标段|标包|分包|标段\(包\)|招标文件|合同|通知书|公告)(单号|编号|标号|编码|代码|备案号|号)[::\s]+([^,。;:、]{8,30}[a-zA-Z0-9\号])[\),。]', sentence.sentence_text)
  406. if othercode != None:
  407. item['code'].append(othercode.group(3))
  408. item['code'].sort(key=lambda x:len(x),reverse=True)
  409. result.append(item)
  410. list_sentence.sort(key=lambda x: x.sentence_index,reverse=False)
  411. return result
  412. '''
  413. #当数据量过大时会报错
  414. def predict(self,articles,MAX_LEN = None):
  415. sentences = []
  416. for article in articles:
  417. for sentence in article.content.split("。"):
  418. sentences.append([sentence,article.id])
  419. if MAX_LEN is None:
  420. sent_len = [len(sentence[0]) for sentence in sentences]
  421. MAX_LEN = max(sent_len)
  422. #print(MAX_LEN)
  423. #若为空,则直接返回空
  424. result = []
  425. if MAX_LEN==0:
  426. for article in articles:
  427. result.append([article.id,{"code":[],"name":""}])
  428. return result
  429. index_unk = self.word2index.get("<unk>")
  430. index_pad = self.word2index.get("<pad>")
  431. x = [[self.word2index.get(word,index_unk)for word in sentence[0]]for sentence in sentences]
  432. x = pad_sequences(x,maxlen=MAX_LEN,padding="post",truncating="post")
  433. predict_y = self.getModel().predict(x)
  434. last_doc_id = ""
  435. item = []
  436. for sentence,predict in zip(sentences,np.argmax(predict_y,-1)):
  437. pad_sentence = sentence[0][:MAX_LEN]
  438. doc_id = sentence[1]
  439. join_predict = "".join([str(s) for s in predict])
  440. if doc_id!=last_doc_id:
  441. if last_doc_id!="":
  442. result.append(item)
  443. item = [doc_id,{"code":[],"name":""}]
  444. code_set = set()
  445. code_x = []
  446. code_text = []
  447. for iter in re.finditer(self.PC_pattern,join_predict):
  448. get_len = 40
  449. if iter.span()[0]<get_len:
  450. begin = 0
  451. else:
  452. begin = iter.span()[0]-get_len
  453. end = iter.span()[1]+get_len
  454. code_x.append(embedding_word([pad_sentence[begin:iter.span()[0]],pad_sentence[iter.span()[0]:iter.span()[1]],pad_sentence[iter.span()[1]:end]],shape=(3,get_len,60)))
  455. code_text.append(pad_sentence[iter.span()[0]:iter.span()[1]])
  456. if len(code_x)>0:
  457. code_x = np.transpose(np.array(code_x),(1,0,2,3))
  458. predict_code = self.getModel_code().predict([code_x[0],code_x[1],code_x[2]])
  459. for h in range(len(predict_code)):
  460. if predict_code[h][0]>0.5:
  461. the_code = self.fitDataByRule(code_text[h])
  462. if the_code not in code_set:
  463. code_set.add(the_code)
  464. item[1]['code'] = list(code_set)
  465. if item[1]['name']=="":
  466. for iter in re.finditer(self.PN_pattern,join_predict):
  467. #item[1]['name']=item[1]['name']+";"+self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  468. item[1]['name']=self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  469. break
  470. last_doc_id = doc_id
  471. result.append(item)
  472. return result
  473. '''
  474. #角色金额模型
  475. class PREMPredict():
  476. def __init__(self):
  477. #self.model_role_file = os.path.abspath("../role/models/model_role.model.hdf5")
  478. self.model_role_file = os.path.dirname(__file__)+"/../role/log/new_biLSTM-ep012-loss0.028-val_loss0.040-f10.954.h5"
  479. self.model_role = Model_role_classify_word()
  480. self.model_money = Model_money_classify()
  481. return
  482. def search_role_data(self,list_sentences,list_entitys):
  483. '''
  484. @summary:根据句子list和实体list查询角色模型的输入数据
  485. @param:
  486. list_sentences:文章的sentences
  487. list_entitys:文章的entitys
  488. @return:角色模型的输入数据
  489. '''
  490. data_x = []
  491. points_entitys = []
  492. for list_entity,list_sentence in zip(list_entitys,list_sentences):
  493. list_entity.sort(key=lambda x:x.sentence_index)
  494. list_sentence.sort(key=lambda x:x.sentence_index)
  495. p_entitys = 0
  496. p_sentences = 0
  497. while(p_entitys<len(list_entity)):
  498. entity = list_entity[p_entitys]
  499. if entity.entity_type in ['org','company']:
  500. while(p_sentences<len(list_sentence)):
  501. sentence = list_sentence[p_sentences]
  502. if entity.doc_id==sentence.doc_id and entity.sentence_index==sentence.sentence_index:
  503. #item_x = embedding(spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=settings.MODEL_ROLE_INPUT_SHAPE[1]),shape=settings.MODEL_ROLE_INPUT_SHAPE)
  504. item_x = self.model_role.encode(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,entity_text=entity.entity_text)
  505. data_x.append(item_x)
  506. points_entitys.append(entity)
  507. break
  508. p_sentences += 1
  509. p_entitys += 1
  510. if len(points_entitys)==0:
  511. return None
  512. return [data_x,points_entitys]
  513. def search_money_data(self,list_sentences,list_entitys):
  514. '''
  515. @summary:根据句子list和实体list查询金额模型的输入数据
  516. @param:
  517. list_sentences:文章的sentences
  518. list_entitys:文章的entitys
  519. @return:金额模型的输入数据
  520. '''
  521. data_x = []
  522. points_entitys = []
  523. for list_entity,list_sentence in zip(list_entitys,list_sentences):
  524. list_entity.sort(key=lambda x:x.sentence_index)
  525. list_sentence.sort(key=lambda x:x.sentence_index)
  526. p_entitys = 0
  527. while(p_entitys<len(list_entity)):
  528. entity = list_entity[p_entitys]
  529. if entity.entity_type=="money":
  530. p_sentences = 0
  531. while(p_sentences<len(list_sentence)):
  532. sentence = list_sentence[p_sentences]
  533. if entity.doc_id==sentence.doc_id and entity.sentence_index==sentence.sentence_index:
  534. #item_x = embedding(spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=settings.MODEL_MONEY_INPUT_SHAPE[1]),shape=settings.MODEL_MONEY_INPUT_SHAPE)
  535. #item_x = embedding_word(spanWindow(tokens=sentence.tokens, begin_index=entity.begin_index, end_index=entity.end_index, size=10, center_include=True, word_flag=True),shape=settings.MODEL_MONEY_INPUT_SHAPE)
  536. item_x = self.model_money.encode(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index)
  537. data_x.append(item_x)
  538. points_entitys.append(entity)
  539. break
  540. p_sentences += 1
  541. p_entitys += 1
  542. if len(points_entitys)==0:
  543. return None
  544. return [data_x,points_entitys]
  545. def predict_role(self,list_sentences, list_entitys):
  546. datas = self.search_role_data(list_sentences, list_entitys)
  547. if datas is None:
  548. return
  549. points_entitys = datas[1]
  550. if USE_PAI_EAS:
  551. _data = datas[0]
  552. _data = np.transpose(np.array(_data),(1,0,2))
  553. request = tf_predict_pb2.PredictRequest()
  554. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  555. request.inputs["input0"].array_shape.dim.extend(np.shape(_data[0]))
  556. request.inputs["input0"].float_val.extend(np.array(_data[0],dtype=np.float64).reshape(-1))
  557. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  558. request.inputs["input1"].array_shape.dim.extend(np.shape(_data[1]))
  559. request.inputs["input1"].float_val.extend(np.array(_data[1],dtype=np.float64).reshape(-1))
  560. request.inputs["input2"].dtype = tf_predict_pb2.DT_FLOAT
  561. request.inputs["input2"].array_shape.dim.extend(np.shape(_data[2]))
  562. request.inputs["input2"].float_val.extend(np.array(_data[2],dtype=np.float64).reshape(-1))
  563. request_data = request.SerializeToString()
  564. list_outputs = ["outputs"]
  565. _result = vpc_requests(role_url, role_authorization, request_data, list_outputs)
  566. if _result is not None:
  567. predict_y = _result["outputs"]
  568. else:
  569. predict_y = self.model_role.predict(datas[0])
  570. else:
  571. predict_y = self.model_role.predict(np.array(datas[0],dtype=np.float64))
  572. for i in range(len(predict_y)):
  573. entity = points_entitys[i]
  574. label = np.argmax(predict_y[i])
  575. values = []
  576. for item in predict_y[i]:
  577. values.append(item)
  578. entity.set_Role(label,values)
  579. def predict_money(self,list_sentences,list_entitys):
  580. datas = self.search_money_data(list_sentences, list_entitys)
  581. if datas is None:
  582. return
  583. points_entitys = datas[1]
  584. _data = datas[0]
  585. if USE_PAI_EAS:
  586. _data = np.transpose(np.array(_data),(1,0,2,3))
  587. request = tf_predict_pb2.PredictRequest()
  588. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  589. request.inputs["input0"].array_shape.dim.extend(np.shape(_data[0]))
  590. request.inputs["input0"].float_val.extend(np.array(_data[0],dtype=np.float64).reshape(-1))
  591. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  592. request.inputs["input1"].array_shape.dim.extend(np.shape(_data[1]))
  593. request.inputs["input1"].float_val.extend(np.array(_data[1],dtype=np.float64).reshape(-1))
  594. request.inputs["input2"].dtype = tf_predict_pb2.DT_FLOAT
  595. request.inputs["input2"].array_shape.dim.extend(np.shape(_data[2]))
  596. request.inputs["input2"].float_val.extend(np.array(_data[2],dtype=np.float64).reshape(-1))
  597. request_data = request.SerializeToString()
  598. list_outputs = ["outputs"]
  599. _result = vpc_requests(money_url, money_authorization, request_data, list_outputs)
  600. if _result is not None:
  601. predict_y = _result["outputs"]
  602. else:
  603. predict_y = self.model_money.predict(_data)
  604. else:
  605. predict_y = self.model_money.predict(_data)
  606. for i in range(len(predict_y)):
  607. entity = points_entitys[i]
  608. label = np.argmax(predict_y[i])
  609. values = []
  610. for item in predict_y[i]:
  611. values.append(item)
  612. entity.set_Money(label,values)
  613. def predict(self,list_sentences,list_entitys):
  614. self.predict_role(list_sentences,list_entitys)
  615. self.predict_money(list_sentences,list_entitys)
  616. #联系人模型
  617. class EPCPredict():
  618. def __init__(self):
  619. self.model_person = Model_person_classify()
  620. def search_person_data(self,list_sentences,list_entitys):
  621. '''
  622. @summary:根据句子list和实体list查询联系人模型的输入数据
  623. @param:
  624. list_sentences:文章的sentences
  625. list_entitys:文章的entitys
  626. @return:联系人模型的输入数据
  627. '''
  628. data_x = []
  629. points_entitys = []
  630. for list_entity,list_sentence in zip(list_entitys,list_sentences):
  631. p_entitys = 0
  632. dict_index_sentence = {}
  633. for _sentence in list_sentence:
  634. dict_index_sentence[_sentence.sentence_index] = _sentence
  635. _list_entity = [entity for entity in list_entity if entity.entity_type=="person"]
  636. while(p_entitys<len(_list_entity)):
  637. entity = _list_entity[p_entitys]
  638. if entity.entity_type=="person":
  639. sentence = dict_index_sentence[entity.sentence_index]
  640. item_x = self.model_person.encode(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index)
  641. data_x.append(item_x)
  642. points_entitys.append(entity)
  643. p_entitys += 1
  644. if len(points_entitys)==0:
  645. return None
  646. # return [data_x,points_entitys,dianhua]
  647. return [data_x,points_entitys]
  648. def predict_person(self,list_sentences, list_entitys):
  649. datas = self.search_person_data(list_sentences, list_entitys)
  650. if datas is None:
  651. return
  652. points_entitys = datas[1]
  653. # phone = datas[2]
  654. if USE_PAI_EAS:
  655. _data = datas[0]
  656. _data = np.transpose(np.array(_data),(1,0,2,3))
  657. request = tf_predict_pb2.PredictRequest()
  658. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  659. request.inputs["input0"].array_shape.dim.extend(np.shape(_data[0]))
  660. request.inputs["input0"].float_val.extend(np.array(_data[0],dtype=np.float64).reshape(-1))
  661. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  662. request.inputs["input1"].array_shape.dim.extend(np.shape(_data[1]))
  663. request.inputs["input1"].float_val.extend(np.array(_data[1],dtype=np.float64).reshape(-1))
  664. request_data = request.SerializeToString()
  665. list_outputs = ["outputs"]
  666. _result = vpc_requests(person_url, person_authorization, request_data, list_outputs)
  667. if _result is not None:
  668. predict_y = _result["outputs"]
  669. else:
  670. predict_y = self.model_person.predict(datas[0])
  671. else:
  672. predict_y = self.model_person.predict(datas[0])
  673. # assert len(predict_y)==len(points_entitys)==len(phone)
  674. assert len(predict_y)==len(points_entitys)
  675. for i in range(len(predict_y)):
  676. entity = points_entitys[i]
  677. label = np.argmax(predict_y[i])
  678. values = []
  679. for item in predict_y[i]:
  680. values.append(item)
  681. # phone_number = phone[i]
  682. # entity.set_Person(label,values,phone_number)
  683. entity.set_Person(label,values,None)
  684. # 为联系人匹配电话
  685. # self.person_search_phone(list_sentences, list_entitys)
  686. def person_search_phone(self,list_sentences, list_entitys):
  687. def phoneFromList(phones):
  688. # for phone in phones:
  689. # if len(phone)==11:
  690. # return re.sub('电话[:|:]|联系方式[:|:]','',phone)
  691. return re.sub('电话[:|:]|联系方式[:|:]', '', phones[0])
  692. for list_entity, list_sentence in zip(list_entitys, list_sentences):
  693. # p_entitys = 0
  694. # p_sentences = 0
  695. #
  696. # key_word = re.compile('电话[:|:].{0,4}\d{7,12}|联系方式[:|:].{0,4}\d{7,12}')
  697. # # phone = re.compile('1[3|4|5|7|8][0-9][-—-]?\d{4}[-—-]?\d{4}|\d{3,4}[-—-]\d{7,8}/\d{3,8}|\d{3,4}[-—-]\d{7,8}转\d{1,4}|\d{3,4}[-—-]\d{7,8}|[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}') # 联系电话
  698. # # 2020/11/25 增加发现的号码段
  699. # phone = re.compile('1[3|4|5|6|7|8|9][0-9][-—-]?\d{4}[-—-]?\d{4}|'
  700. # '\d{3,4}[-—-][1-9]\d{6,7}/\d{3,8}|'
  701. # '\d{3,4}[-—-]\d{7,8}转\d{1,4}|'
  702. # '\d{3,4}[-—-]?[1-9]\d{6,7}|'
  703. # '[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|'
  704. # '[1-9]\d{6,7}') # 联系电话
  705. # dict_index_sentence = {}
  706. # for _sentence in list_sentence:
  707. # dict_index_sentence[_sentence.sentence_index] = _sentence
  708. #
  709. # dict_context_itemx = {}
  710. # last_person = "####****++++$$^"
  711. # last_person_phone = "####****++++$^"
  712. # _list_entity = [entity for entity in list_entity if entity.entity_type == "person"]
  713. # while (p_entitys < len(_list_entity)):
  714. # entity = _list_entity[p_entitys]
  715. # if entity.entity_type == "person" and entity.label in [1,2,3]:
  716. # sentence = dict_index_sentence[entity.sentence_index]
  717. # # item_x = embedding(spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=settings.MODEL_PERSON_INPUT_SHAPE[1]),shape=settings.MODEL_PERSON_INPUT_SHAPE)
  718. #
  719. # # s = spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=20)
  720. #
  721. # # 2021/5/8 取上下文的句子,解决表格处理的分句问题
  722. # left_sentence = dict_index_sentence.get(entity.sentence_index - 1)
  723. # left_sentence_tokens = left_sentence.tokens if left_sentence else []
  724. # right_sentence = dict_index_sentence.get(entity.sentence_index + 1)
  725. # right_sentence_tokens = right_sentence.tokens if right_sentence else []
  726. # entity_beginIndex = entity.begin_index + len(left_sentence_tokens)
  727. # entity_endIndex = entity.end_index + len(left_sentence_tokens)
  728. # context_sentences_tokens = left_sentence_tokens + sentence.tokens + right_sentence_tokens
  729. # s = spanWindow(tokens=context_sentences_tokens, begin_index=entity_beginIndex,
  730. # end_index=entity_endIndex, size=20)
  731. #
  732. # _key = "".join(["".join(x) for x in s])
  733. # if _key in dict_context_itemx:
  734. # _dianhua = dict_context_itemx[_key][0]
  735. # else:
  736. # s1 = ''.join(s[1])
  737. # # s1 = re.sub(',)', '-', s1)
  738. # s1 = re.sub('\s', '', s1)
  739. # have_key = re.findall(key_word, s1)
  740. # have_phone = re.findall(phone, s1)
  741. # s0 = ''.join(s[0])
  742. # # s0 = re.sub(',)', '-', s0)
  743. # s0 = re.sub('\s', '', s0)
  744. # have_key2 = re.findall(key_word, s0)
  745. # have_phone2 = re.findall(phone, s0)
  746. #
  747. # s3 = ''.join(s[1])
  748. # # s0 = re.sub(',)', '-', s0)
  749. # s3 = re.sub(',|,|\s', '', s3)
  750. # have_key3 = re.findall(key_word, s3)
  751. # have_phone3 = re.findall(phone, s3)
  752. #
  753. # s4 = ''.join(s[0])
  754. # # s0 = re.sub(',)', '-', s0)
  755. # s4 = re.sub(',|,|\s', '', s0)
  756. # have_key4 = re.findall(key_word, s4)
  757. # have_phone4 = re.findall(phone, s4)
  758. #
  759. # _dianhua = ""
  760. # if have_phone:
  761. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s1.find(
  762. # last_person_phone) != -1:
  763. # if len(have_phone) > 1:
  764. # _dianhua = phoneFromList(have_phone[1:])
  765. # else:
  766. # _dianhua = phoneFromList(have_phone)
  767. # elif have_key:
  768. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s1.find(
  769. # last_person_phone) != -1:
  770. # if len(have_key) > 1:
  771. # _dianhua = phoneFromList(have_key[1:])
  772. # else:
  773. # _dianhua = phoneFromList(have_key)
  774. # elif have_phone2:
  775. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s0.find(
  776. # last_person_phone) != -1:
  777. # if len(have_phone2) > 1:
  778. # _dianhua = phoneFromList(have_phone2[1:])
  779. # else:
  780. # _dianhua = phoneFromList(have_phone2)
  781. # elif have_key2:
  782. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s0.find(
  783. # last_person_phone) != -1:
  784. # if len(have_key2) > 1:
  785. # _dianhua = phoneFromList(have_key2[1:])
  786. # else:
  787. # _dianhua = phoneFromList(have_key2)
  788. # elif have_phone3:
  789. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s3.find(
  790. # last_person_phone) != -1:
  791. # if len(have_phone3) > 1:
  792. # _dianhua = phoneFromList(have_phone3[1:])
  793. # else:
  794. # _dianhua = phoneFromList(have_phone3)
  795. # elif have_key3:
  796. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s3.find(
  797. # last_person_phone) != -1:
  798. # if len(have_key3) > 1:
  799. # _dianhua = phoneFromList(have_key3[1:])
  800. # else:
  801. # _dianhua = phoneFromList(have_key3)
  802. # elif have_phone4:
  803. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s4.find(
  804. # last_person_phone) != -1:
  805. # if len(have_phone4) > 1:
  806. # _dianhua = phoneFromList(have_phone4)
  807. # else:
  808. # _dianhua = phoneFromList(have_phone4)
  809. # elif have_key4:
  810. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s4.find(
  811. # last_person_phone) != -1:
  812. # if len(have_key4) > 1:
  813. # _dianhua = phoneFromList(have_key4)
  814. # else:
  815. # _dianhua = phoneFromList(have_key4)
  816. # else:
  817. # _dianhua = ""
  818. # # dict_context_itemx[_key] = [item_x, _dianhua]
  819. # dict_context_itemx[_key] = [_dianhua]
  820. # # points_entitys.append(entity)
  821. # # dianhua.append(_dianhua)
  822. # last_person = entity.entity_text
  823. # if _dianhua:
  824. # # 更新联系人entity联系方式(person_phone)
  825. # entity.person_phone = _dianhua
  826. # last_person_phone = _dianhua
  827. # else:
  828. # last_person_phone = "####****++++$^"
  829. # p_entitys += 1
  830. from scipy.optimize import linear_sum_assignment
  831. from BiddingKG.dl.interface.Entitys import Match
  832. def dispatch(match_list):
  833. main_roles = list(set([match.main_role for match in match_list]))
  834. attributes = list(set([match.attribute for match in match_list]))
  835. label = np.zeros(shape=(len(main_roles), len(attributes)))
  836. for match in match_list:
  837. main_role = match.main_role
  838. attribute = match.attribute
  839. value = match.value
  840. label[main_roles.index(main_role), attributes.index(attribute)] = value + 10000
  841. # print(label)
  842. gragh = -label
  843. # km算法
  844. row, col = linear_sum_assignment(gragh)
  845. max_dispatch = [(i, j) for i, j, value in zip(row, col, gragh[row, col]) if value]
  846. return [Match(main_roles[row], attributes[col]) for row, col in max_dispatch]
  847. # km算法
  848. key_word = re.compile('((?:电话|联系方式|联系人).{0,4}?)(\d{7,12})')
  849. phone = re.compile('1[3|4|5|6|7|8|9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  850. '\+86.?1[3|4|5|6|7|8|9]\d{9}|'
  851. '0\d{2,3}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  852. '0\d{2,3}[-—-―]\d{7,8}转\d{1,4}|'
  853. '0\d{2,3}[-—-―]?[1-9]\d{6,7}|'
  854. '[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|'
  855. '[1-9]\d{6,7}')
  856. phone_entitys = []
  857. for _sentence in list_sentence:
  858. sentence_text = _sentence.sentence_text
  859. res_set = set()
  860. for i in re.finditer(phone,sentence_text):
  861. res_set.add((i.group(),i.start(),i.end()))
  862. for i in re.finditer(key_word,sentence_text):
  863. res_set.add((i.group(2),i.start()+len(i.group(1)),i.end()))
  864. for item in list(res_set):
  865. phone_left = sentence_text[max(0,item[1]-10):item[1]]
  866. phone_right = sentence_text[item[2]:item[2]+8]
  867. # 排除传真号 和 其它错误项
  868. if re.search("传,?真|信,?箱|邮,?箱",phone_left):
  869. if not re.search("电,?话",phone_left):
  870. continue
  871. if re.search("帐,?号|编,?号|报,?价|证,?号|价,?格|[\((]万?元[\))]",phone_left):
  872. continue
  873. if re.search("[.,]\d{2,}",phone_right):
  874. continue
  875. _entity = Entity(_sentence.doc_id, None, item[0], "phone", _sentence.sentence_index, None, None,item[1], item[2])
  876. phone_entitys.append(_entity)
  877. person_entitys = []
  878. for entity in list_entity:
  879. if entity.entity_type == "person":
  880. entity.person_phone = ""
  881. person_entitys.append(entity)
  882. _list_entity = phone_entitys + person_entitys
  883. _list_entity = sorted(_list_entity,key=lambda x:(x.sentence_index,x.wordOffset_begin))
  884. words_num_dict = dict()
  885. last_words_num = 0
  886. list_sentence = sorted(list_sentence, key=lambda x: x.sentence_index)
  887. for sentence in list_sentence:
  888. _index = sentence.sentence_index
  889. if _index == 0:
  890. words_num_dict[_index] = 0
  891. else:
  892. words_num_dict[_index] = words_num_dict[_index - 1] + last_words_num
  893. last_words_num = len(sentence.sentence_text)
  894. match_list = []
  895. for index in range(len(_list_entity)):
  896. entity = _list_entity[index]
  897. if entity.entity_type=="person" and entity.label in [1,2,3]:
  898. match_nums = 0
  899. for after_index in range(index + 1, min(len(_list_entity), index + 5)):
  900. after_entity = _list_entity[after_index]
  901. if after_entity.entity_type=="phone":
  902. sentence_distance = after_entity.sentence_index - entity.sentence_index
  903. distance = (words_num_dict[after_entity.sentence_index] + after_entity.wordOffset_begin) - (
  904. words_num_dict[entity.sentence_index] + entity.wordOffset_end)
  905. if sentence_distance < 2 and distance < 50:
  906. value = (-1 / 2 * (distance ** 2)) / 10000
  907. match_list.append(Match(entity, after_entity, value))
  908. match_nums += 1
  909. else:
  910. break
  911. if after_entity.entity_type=="person":
  912. if after_entity.label not in [1,2,3]:
  913. break
  914. if not match_nums:
  915. for previous_index in range(index-1, max(0,index-5), -1):
  916. previous_entity = _list_entity[previous_index]
  917. if previous_entity.entity_type == "phone":
  918. sentence_distance = entity.sentence_index - previous_entity.sentence_index
  919. distance = (words_num_dict[entity.sentence_index] + entity.wordOffset_begin) - (
  920. words_num_dict[previous_entity.sentence_index] + previous_entity.wordOffset_end)
  921. if sentence_distance < 1 and distance<30:
  922. # 前向 没有 /10000
  923. value = (-1 / 2 * (distance ** 2))
  924. match_list.append(Match(entity, previous_entity, value))
  925. else:
  926. break
  927. result = dispatch(match_list)
  928. for match in result:
  929. entity = match.main_role
  930. # 更新 list_entity
  931. entity_index = list_entity.index(entity)
  932. list_entity[entity_index].person_phone = match.attribute.entity_text
  933. def predict(self,list_sentences,list_entitys):
  934. self.predict_person(list_sentences,list_entitys)
  935. #表格预测
  936. class FormPredictor():
  937. def __init__(self,lazyLoad=getLazyLoad()):
  938. self.model_file_line = os.path.dirname(__file__)+"/../form/model/model_form.model_line.hdf5"
  939. self.model_file_item = os.path.dirname(__file__)+"/../form/model/model_form.model_item.hdf5"
  940. self.model_form_item = Model_form_item()
  941. self.model_form_context = Model_form_context()
  942. self.model_dict = {"line":[None,self.model_file_line]}
  943. def getModel(self,type):
  944. if type=="item":
  945. return self.model_form_item
  946. elif type=="context":
  947. return self.model_form_context
  948. else:
  949. return self.getModel(type)
  950. def encode(self,data,**kwargs):
  951. return encodeInput([data], word_len=50, word_flag=True,userFool=False)[0]
  952. return encodeInput_form(data)
  953. def predict(self,form_datas,type):
  954. if type=="item":
  955. return self.model_form_item.predict(form_datas)
  956. elif type=="context":
  957. return self.model_form_context.predict(form_datas)
  958. else:
  959. return self.getModel(type).predict(form_datas)
  960. #角色规则
  961. #依据正则给所有无角色的实体赋予角色,给予等于阈值的最低概率
  962. class RoleRulePredictor():
  963. def __init__(self):
  964. self.pattern_tenderee_left = "(?P<tenderee_left>((遴选|采购|招标|项目|竞价|议价|需求|最终|建设|转让|招租|甲|议标|合同主体|比选)(?:人|公司|单位|组织|用户|业主|方|部门)|文章来源|业主名称|需方|询价单位)(是|为|信息|:|:|\s*$))"
  965. self.pattern_tenderee_center = "(?P<tenderee_center>(受.{,20}委托))"
  966. self.pattern_tenderee_right = "(?P<tenderee_right>(\((以下简称)?[\"”]?(招标|采购)(人|单位|机构)\)?)|(^[^.。,,::](采购|竞价|招标|施工|监理|中标|物资)(公告|公示|项目|结果|招标))|的.*正在进行询比价)"
  967. self.pattern_agency_left = "(?P<agency_left>(代理(?:人|机构|公司|单位|组织)|专业采购机构|集中采购机构|集采机构|招标机构)(.{,4}名,?称|全称|是|为|:|:|[,,]?\s*$)|(受.{,20}委托))"
  968. self.pattern_agency_right = "(?P<agency_right>(\((以下简称)?[\"”]?(代理)(人|单位|机构)\))|受.*委托)"
  969. # 2020//11/24 大网站规则 中标关键词添加 选定单位|指定的中介服务机构
  970. self.pattern_winTenderer_left = "(?P<winTenderer_left>((中标|中选|中价|乙|成交|承做|施工|供货|承包|竞得|受让)(候选)?(人|单位|机构|供应商|方|公司|厂商|商)[^必须]{,4}[::是为]|(供应商|供货商|服务商|选定单位|指定的中介服务机构))[^必须]{,4}[::是为].{,2}|(第[一1](名|((中标|中选|中价|成交)?(候选)?(人|单位|机构|供应商))))(是|为|:|:|\s*$)|((评审结果|名次|排名)[::]第?[一1]名?)|(单一来源(采购)?方式向.?$)|((中标|成交)(结果|信息))(是|为|:|:|\s*$)|(单一来源采购(供应商|供货商|服务商))|((分包|标包).*供应商|供应商名称|服务机构|供方[::]))"
  971. self.pattern_winTenderer_center = "(?P<winTenderer_center>第[一1].{,20}[是为]((中标|中选|中价|成交|施工)(人|单位|机构|供应商|公司)|供应商)[^必须]{,4}[::是为])"
  972. self.pattern_winTenderer_right = "(?P<winTenderer_right>[是为\(]((采购(供应商|供货商|服务商)|(第[一1]|预)?(拟?(中标|中选|中价|成交)(候选)?(人|单位|机构|供应商|公司|厂商)))))"
  973. self.pattern_winTenderer_whole = "(?P<winTenderer_whole>贵公司.*以.*中标|最终由.*竞买成功|经.*[以由].*中标|成交供应商,成交供应商名称:|谈判结果:由.{5,20}供货)" # 2020//11/24 大网站规则 中标关键词添加 谈判结果:由.{5,20}供货
  974. self.pattern_winTenderer_location = "(中标|中选|中价|乙|成交|承做|施工|供货|承包|竞得|受让)(候选)?(人|单位|机构|供应商|方|公司|厂商|商)|(供应商|供货商|服务商)[^必须]{,4}[::]?$|(第[一1](名|((中标|中选|中价|成交)?(候选)?(人|单位|机构|供应商))))(是|为|:|:|\s*$)|((评审结果|名次|排名)[::]第?[一1]名?)|(单一来源(采购)?方式向.?$)"
  975. self.pattern_secondTenderer_left = "(?P<secondTenderer_left>((第[二2](名|((中标|中选|中价|成交)(候选)?(人|单位|机构|供应商|公司))))(是|为|:|:|\s*$))|((评审结果|名次|排名)[::]第?[二2]名?))"
  976. self.pattern_secondTenderer_right = "(?P<secondTenderer_right>[是为\(]第[二2](名|(中标|中选|中价|成交)(候选)?(人|单位|机构|供应商|公司)))"
  977. self.pattern_thirdTenderer_left = "(?P<thirdTenderer_left>(第[三3](名|((中标|中选|中价|成交)(候选)?(人|单位|机构|供应商|公司))))|((评审结果|名次|排名)[::]第?[三3]名?))"
  978. self.pattern_thirdTenderer_right = "(?P<thirdTenderer_right>[是为\(]第[三3](名|(中标|中选|中价|成交)(候选)?(人|单位|机构|供应商|公司)))"
  979. self.dict_list_pattern = {"0":[["L",self.pattern_tenderee_left],
  980. ["C",self.pattern_tenderee_center],
  981. ["R",self.pattern_tenderee_right]],
  982. "1":[["L",self.pattern_agency_left],
  983. ["R",self.pattern_agency_right]],
  984. "2":[["L",self.pattern_winTenderer_left],
  985. ["C",self.pattern_winTenderer_center],
  986. ["R",self.pattern_winTenderer_right],
  987. ["W",self.pattern_winTenderer_whole]],
  988. "3":[["L",self.pattern_secondTenderer_left],
  989. ["R",self.pattern_secondTenderer_right]],
  990. "4":[["L",self.pattern_thirdTenderer_left],
  991. ["R",self.pattern_thirdTenderer_right]]}
  992. self.pattern_whole = []
  993. for _k,_v in self.dict_list_pattern.items():
  994. for _d,_p in _v:
  995. self.pattern_whole.append(_p)
  996. # self.pattern_whole = "|".join(list_pattern)
  997. self.SET_NOT_TENDERER = set(["人民政府","人民法院","中华人民共和国","人民检察院","评标委员会","中国政府","中国海关","中华人民共和国政府"])
  998. self.pattern_money_tenderee = re.compile("投标最高限价|采购计划金额|项目预算|招标金额|采购金额|项目金额|建安费用|采购(单位|人)委托价|限价|拦标价|预算金额")
  999. self.pattern_money_tenderer = re.compile("((合同|成交|中标|应付款|交易|投标|验收)[)\)]?(总?金额|结果|[单报]?价))|总价|标的基本情况")
  1000. self.pattern_money_tenderer_whole = re.compile("(以金额.*中标)|中标供应商.*单价|以.*元中标")
  1001. self.pattern_money_other = re.compile("代理费|服务费")
  1002. self.pattern_pack = "(([^承](包|标[段号的包]|分?包|包组)编?号?|项目)[::]?[\((]?[0-9A-Za-z一二三四五六七八九十]{1,4})[^至]?|(第?[0-9A-Za-z一二三四五六七八九十]{1,4}(包号|标[段号的包]|分?包))|[0-9]个(包|标[段号的包]|分?包|包组)"
  1003. def _check_input(self,text, ignore=False):
  1004. if not text:
  1005. return []
  1006. if not isinstance(text, list):
  1007. text = [text]
  1008. null_index = [i for i, t in enumerate(text) if not t]
  1009. if null_index and not ignore:
  1010. raise Exception("null text in input ")
  1011. return text
  1012. def predict(self,list_articles,list_sentences,list_entitys,list_codenames,on_value = 0.5):
  1013. for article,list_entity,list_sentence,list_codename in zip(list_articles,list_entitys,list_sentences,list_codenames):
  1014. list_name = list_codename["name"]
  1015. list_name = self._check_input(list_name)+[article.title]
  1016. for p_entity in list_entity:
  1017. if p_entity.entity_type in ["org","company"]:
  1018. #将上下文包含标题的实体概率置为0.6,因为标题中的实体不一定是招标人
  1019. if str(p_entity.label)=="0":
  1020. find_flag = False
  1021. for _sentence in list_sentence:
  1022. if _sentence.sentence_index==p_entity.sentence_index:
  1023. _span = spanWindow(tokens=_sentence.tokens,begin_index=p_entity.begin_index,end_index=p_entity.end_index,size=20,center_include=True,word_flag=True,text=p_entity.entity_text)
  1024. for _name in list_name:
  1025. if _name!="" and str(_span[1]+_span[2][:len(str(_name))]).find(_name)>=0:
  1026. find_flag = True
  1027. if p_entity.values[0]>on_value:
  1028. p_entity.values[0] = 0.6+(p_entity.values[0]-0.6)/10
  1029. if find_flag:
  1030. continue
  1031. #只解析角色为无的或者概率低于阈值的
  1032. if p_entity.label is None:
  1033. continue
  1034. role_prob = float(p_entity.values[int(p_entity.label)])
  1035. if role_prob<on_value or str(p_entity.label)=="5":
  1036. #将标题中的实体置为招标人
  1037. _list_name = self._check_input(list_name,ignore=True)
  1038. find_flag = False
  1039. for _name in _list_name:
  1040. if str(_name).find(p_entity.entity_text)>=0:
  1041. find_flag = True
  1042. _label = 0
  1043. p_entity.label = _label
  1044. p_entity.values[int(_label)] = on_value
  1045. break
  1046. #若是实体在标题中,默认为招标人,不进行以下的规则匹配
  1047. if find_flag:
  1048. continue
  1049. for s_index in range(len(list_sentence)):
  1050. if p_entity.doc_id==list_sentence[s_index].doc_id and p_entity.sentence_index==list_sentence[s_index].sentence_index:
  1051. tokens = list_sentence[s_index].tokens
  1052. begin_index = p_entity.begin_index
  1053. end_index = p_entity.end_index
  1054. size = 15
  1055. spans = spanWindow(tokens, begin_index, end_index, size, center_include=True, word_flag=True, use_text=False)
  1056. #距离
  1057. list_distance = [100,100,100,100,100]
  1058. _flag = False
  1059. #使用正则+距离解决冲突
  1060. # 2021/6/11update center: spans[1] --> spans[0][-30:]+spans[1]
  1061. list_spans = [spans[0][-30:],spans[0][-20:]+spans[1],spans[2]]
  1062. for _i_span in range(len(list_spans)):
  1063. # print(list_spans[_i_span],p_entity.entity_text)
  1064. for _pattern in self.pattern_whole:
  1065. for _iter in re.finditer(_pattern,list_spans[_i_span]):
  1066. for _group,_v_group in _iter.groupdict().items():
  1067. if _v_group is not None and _v_group!="":
  1068. _role = _group.split("_")[0]
  1069. _direct = _group.split("_")[1]
  1070. _label = {"tenderee":0,"agency":1,"winTenderer":2,"secondTenderer":3,"thirdTenderer":4}.get(_role)
  1071. if _i_span==0 and _direct=="left":
  1072. _flag = True
  1073. _distance = abs((len(list_spans[_i_span])-_iter.span()[1]))
  1074. list_distance[int(_label)] = min(_distance,list_distance[int(_label)])
  1075. if _i_span==1 and _direct=="center":
  1076. _flag = True
  1077. _distance = abs((len(list_spans[_i_span])-_iter.span()[1]))
  1078. list_distance[int(_label)] = min(_distance,list_distance[int(_label)])
  1079. if _i_span==2 and _direct=="right":
  1080. _flag = True
  1081. _distance = _iter.span()[0]
  1082. list_distance[int(_label)] = min(_distance,list_distance[int(_label)])
  1083. # print(list_distance)
  1084. # for _key in self.dict_list_pattern.keys():
  1085. #
  1086. # for pattern in self.dict_list_pattern[_key]:
  1087. # if pattern[0]=="L":
  1088. # for _iter in re.finditer(pattern[1], spans[0][-30:]):
  1089. # _flag = True
  1090. # if len(spans[0])-_iter.span()[1]<list_distance[int(_key)]:
  1091. # list_distance[int(_key)] = len(spans[0])-_iter.span()[1]-(_iter.span()[1]-_iter.span()[0])
  1092. #
  1093. # if pattern[0]=="C":
  1094. # if re.search(pattern[1],spans[0]) is None and re.search(pattern[1],spans[2]) is None and re.search(pattern[1],spans[0]+spans[1]+spans[2]) is not None:
  1095. # _flag = True
  1096. # list_distance[int(_key)] = 0
  1097. #
  1098. # if pattern[0]=="R":
  1099. # for _iter in re.finditer(pattern[1], spans[2][:30]):
  1100. # _flag = True
  1101. # if _iter.span()[0]<list_distance[int(_key)]:
  1102. # list_distance[int(_key)] = _iter.span()[0]
  1103. # if pattern[0]=="W":
  1104. # spans = spanWindow(tokens, begin_index, end_index, size=20, center_include=True, word_flag=True, use_text=False)
  1105. # for _iter in re.finditer(pattern[1], "".join(spans)):
  1106. # _flag = True
  1107. # if _iter.span()[0]<list_distance[int(_key)]:
  1108. # list_distance[int(_key)] = _iter.span()[0]
  1109. # print("==",list_distance)
  1110. #得到结果
  1111. _label = np.argmin(list_distance)
  1112. if _flag:
  1113. # if _label==2 and min(list_distance[3:])<100:
  1114. # _label += np.argmin(list_distance[3:])+1
  1115. if _label in [2,3,4]:
  1116. if p_entity.entity_type in ["company","org"]:
  1117. p_entity.label = _label
  1118. p_entity.values[int(_label)] = on_value+p_entity.values[int(_label)]/10
  1119. else:
  1120. p_entity.label = _label
  1121. p_entity.values[int(_label)] = on_value+p_entity.values[int(_label)]/10
  1122. # if p_entity.entity_type=="location":
  1123. # for _sentence in list_sentence:
  1124. # if _sentence.sentence_index==p_entity.sentence_index:
  1125. # _span = spanWindow(tokens=_sentence.tokens,begin_index=p_entity.begin_index,end_index=p_entity.end_index,size=5,center_include=True,word_flag=True,text=p_entity.entity_text)
  1126. # if re.search(self.pattern_winTenderer_location,_span[0][-10:]) is not None and re.search("地址|地点",_span[0]) is None:
  1127. # p_entity.entity_type="company"
  1128. # _label = "2"
  1129. # p_entity.label = _label
  1130. # p_entity.values = [0]*6
  1131. # p_entity.values[int(_label)] = on_value
  1132. #确定性强的特殊修改
  1133. if p_entity.entity_type in ["company","org"]:
  1134. for s_index in range(len(list_sentence)):
  1135. if p_entity.doc_id==list_sentence[s_index].doc_id and p_entity.sentence_index==list_sentence[s_index].sentence_index:
  1136. tokens = list_sentence[s_index].tokens
  1137. begin_index = p_entity.begin_index
  1138. end_index = p_entity.end_index
  1139. size = 15
  1140. spans = spanWindow(tokens, begin_index, end_index, size, center_include=True, word_flag=True, use_text=False)
  1141. #距离
  1142. list_distance = [100,100,100,100,100]
  1143. _flag = False
  1144. for _key in self.dict_list_pattern.keys():
  1145. for pattern in self.dict_list_pattern[_key]:
  1146. if pattern[0]=="W":
  1147. spans = spanWindow(tokens, begin_index, end_index, size=30, center_include=True, word_flag=True, use_text=False)
  1148. for _iter in re.finditer(pattern[1], spans[0][-10:]+spans[1]+spans[2]):
  1149. _flag = True
  1150. if _iter.span()[0]<list_distance[int(_key)]:
  1151. list_distance[int(_key)] = _iter.span()[0]
  1152. #得到结果
  1153. _label = np.argmin(list_distance)
  1154. if _flag:
  1155. if _label==2 and min(list_distance[3:])<100:
  1156. _label += np.argmin(list_distance[3:])+1
  1157. if _label in [2,3,4]:
  1158. p_entity.label = _label
  1159. p_entity.values[int(_label)] = on_value+p_entity.values[int(_label)]/10
  1160. else:
  1161. p_entity.label = _label
  1162. p_entity.values[int(_label)] = on_value+p_entity.values[int(_label)]/10
  1163. if p_entity.entity_type in ["money"]:
  1164. if str(p_entity.label)=="2":
  1165. for _sentence in list_sentence:
  1166. if _sentence.sentence_index==p_entity.sentence_index:
  1167. _span = spanWindow(tokens=_sentence.tokens,begin_index=p_entity.begin_index,end_index=p_entity.end_index,size=20,center_include=True,word_flag=True,text=p_entity.entity_text)
  1168. if re.search(self.pattern_money_tenderee,_span[0]) is not None and re.search(self.pattern_money_other,_span[0]) is None:
  1169. p_entity.values[0] = 0.8+p_entity.values[0]/10
  1170. p_entity.label = 0
  1171. if re.search(self.pattern_money_tenderer,_span[0]) is not None:
  1172. if re.search(self.pattern_money_other,_span[0]) is not None:
  1173. if re.search(self.pattern_money_tenderer,_span[0]).span()[1]>re.search(self.pattern_money_other,_span[0]).span()[1]:
  1174. p_entity.values[1] = 0.8+p_entity.values[1]/10
  1175. p_entity.label = 1
  1176. else:
  1177. p_entity.values[1] = 0.8+p_entity.values[1]/10
  1178. p_entity.label = 1
  1179. if re.search(self.pattern_money_tenderer_whole,"".join(_span)) is not None and re.search(self.pattern_money_other,_span[0]) is None:
  1180. p_entity.values[1] = 0.8+p_entity.values[1]/10
  1181. p_entity.label = 1
  1182. #增加招标金额扩展,招标金额+连续的未识别金额,并且都可以匹配到标段信息,则将为识别的金额设置为招标金额
  1183. list_p = []
  1184. state = 0
  1185. for p_entity in list_entity:
  1186. for _sentence in list_sentence:
  1187. if _sentence.sentence_index==p_entity.sentence_index:
  1188. _span = spanWindow(tokens=_sentence.tokens,begin_index=p_entity.begin_index,end_index=p_entity.end_index,size=20,center_include=True,word_flag=True,text=p_entity.entity_text)
  1189. if state==2:
  1190. for _p in list_p[1:]:
  1191. _p.values[0] = 0.8+_p.values[0]/10
  1192. _p.label = 0
  1193. state = 0
  1194. list_p = []
  1195. if state==0:
  1196. if p_entity.entity_type in ["money"]:
  1197. if str(p_entity.label)=="0" and re.search(self.pattern_pack,_span[0]+"-"+_span[2]) is not None:
  1198. state = 1
  1199. list_p.append(p_entity)
  1200. elif state==1:
  1201. if p_entity.entity_type in ["money"]:
  1202. if str(p_entity.label) in ["0","2"] and re.search(self.pattern_pack,_span[0]+"-"+_span[2]) is not None and re.search(self.pattern_money_other,_span[0]+"-"+_span[2]) is None and p_entity.sentence_index==list_p[0].sentence_index:
  1203. list_p.append(p_entity)
  1204. else:
  1205. state = 2
  1206. if len(list_p)>1:
  1207. for _p in list_p[1:]:
  1208. #print("==",_p.entity_text,_p.sentence_index,_p.label)
  1209. _p.values[0] = 0.8+_p.values[0]/10
  1210. _p.label = 0
  1211. state = 0
  1212. list_p = []
  1213. for p_entity in list_entity:
  1214. #将属于集合中的不可能是中标人的标签置为无
  1215. if p_entity.entity_text in self.SET_NOT_TENDERER:
  1216. p_entity.label=5
  1217. # 时间类别
  1218. class TimePredictor():
  1219. def __init__(self):
  1220. self.sess = tf.Session(graph=tf.Graph())
  1221. self.inputs_code = None
  1222. self.outputs_code = None
  1223. self.input_shape = (2,10,128)
  1224. self.load_model()
  1225. def load_model(self):
  1226. model_path = os.path.dirname(__file__)+'/timesplit_model'
  1227. if self.inputs_code is None:
  1228. log("get model of time")
  1229. with self.sess.as_default():
  1230. with self.sess.graph.as_default():
  1231. meta_graph_def = tf.saved_model.loader.load(self.sess, tags=["serve"], export_dir=model_path)
  1232. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  1233. signature_def = meta_graph_def.signature_def
  1234. self.inputs_code = []
  1235. self.inputs_code.append(
  1236. self.sess.graph.get_tensor_by_name(signature_def[signature_key].inputs["input0"].name))
  1237. self.inputs_code.append(
  1238. self.sess.graph.get_tensor_by_name(signature_def[signature_key].inputs["input1"].name))
  1239. self.outputs_code = self.sess.graph.get_tensor_by_name(signature_def[signature_key].outputs["outputs"].name)
  1240. return self.inputs_code, self.outputs_code
  1241. else:
  1242. return self.inputs_code, self.outputs_code
  1243. def search_time_data(self,list_sentences,list_entitys):
  1244. data_x = []
  1245. points_entitys = []
  1246. for list_sentence, list_entity in zip(list_sentences, list_entitys):
  1247. p_entitys = 0
  1248. p_sentences = 0
  1249. while(p_entitys<len(list_entity)):
  1250. entity = list_entity[p_entitys]
  1251. if entity.entity_type in ['time']:
  1252. while(p_sentences<len(list_sentence)):
  1253. sentence = list_sentence[p_sentences]
  1254. if entity.doc_id == sentence.doc_id and entity.sentence_index == sentence.sentence_index:
  1255. # left = sentence.sentence_text[max(0,entity.wordOffset_begin-self.input_shape[1]):entity.wordOffset_begin]
  1256. # right = sentence.sentence_text[entity.wordOffset_end:entity.wordOffset_end+self.input_shape[1]]
  1257. s = spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=self.input_shape[1])
  1258. left = s[0]
  1259. right = s[1]
  1260. context = [left, right]
  1261. x = embedding(context, shape=self.input_shape)
  1262. data_x.append(x)
  1263. points_entitys.append(entity)
  1264. break
  1265. p_sentences += 1
  1266. p_entitys += 1
  1267. if len(points_entitys)==0:
  1268. return None
  1269. data_x = np.transpose(np.array(data_x), (1, 0, 2, 3))
  1270. return [data_x, points_entitys]
  1271. def predict(self, list_sentences,list_entitys):
  1272. datas = self.search_time_data(list_sentences, list_entitys)
  1273. if datas is None:
  1274. return
  1275. points_entitys = datas[1]
  1276. with self.sess.as_default():
  1277. predict_y = limitRun(self.sess,[self.outputs_code], feed_dict={self.inputs_code[0]:datas[0][0]
  1278. ,self.inputs_code[1]:datas[0][1]})[0]
  1279. for i in range(len(predict_y)):
  1280. entity = points_entitys[i]
  1281. label = np.argmax(predict_y[i])
  1282. values = []
  1283. for item in predict_y[i]:
  1284. values.append(item)
  1285. entity.set_Role(label, values)
  1286. # 产品字段提取
  1287. class ProductPredictor():
  1288. def __init__(self):
  1289. self.sess = tf.Session(graph=tf.Graph())
  1290. self.load_model()
  1291. def load_model(self):
  1292. model_path = os.path.dirname(__file__)+'/product_savedmodel/product.pb'
  1293. with self.sess.as_default():
  1294. with self.sess.graph.as_default():
  1295. output_graph_def = tf.GraphDef()
  1296. with open(model_path, 'rb') as f:
  1297. output_graph_def.ParseFromString(f.read())
  1298. tf.import_graph_def(output_graph_def, name='')
  1299. self.sess.run(tf.global_variables_initializer())
  1300. self.char_input = self.sess.graph.get_tensor_by_name('CharInputs:0')
  1301. self.length = self.sess.graph.get_tensor_by_name("Sum:0")
  1302. self.dropout = self.sess.graph.get_tensor_by_name("Dropout:0")
  1303. self.logit = self.sess.graph.get_tensor_by_name("logits/Reshape:0")
  1304. self.tran = self.sess.graph.get_tensor_by_name("crf_loss/transitions:0")
  1305. def predict(self, list_sentences,list_entitys=None, MAX_AREA=5000):
  1306. '''
  1307. 预测实体代码,每个句子最多取MAX_AREA个字,超过截断
  1308. :param list_sentences: 多篇公告句子列表,[[一篇公告句子列表],[公告句子列表]]
  1309. :param list_entitys: 多篇公告实体列表
  1310. :param MAX_AREA: 每个句子最多截取多少字
  1311. :return: 把预测出来的实体放进实体类
  1312. '''
  1313. with self.sess.as_default() as sess:
  1314. with self.sess.graph.as_default():
  1315. result = []
  1316. if list_entitys is None:
  1317. list_entitys = [[] for _ in range(len(list_sentences))]
  1318. for list_sentence, list_entity in zip(list_sentences,list_entitys):
  1319. if len(list_sentence)==0:
  1320. result.append({"product":[]})
  1321. continue
  1322. list_sentence.sort(key=lambda x:len(x.sentence_text), reverse=True)
  1323. _begin_index = 0
  1324. item = {"product":[]}
  1325. temp_list = []
  1326. while True:
  1327. MAX_LEN = len(list_sentence[_begin_index].sentence_text)
  1328. if MAX_LEN > MAX_AREA:
  1329. MAX_LEN = MAX_AREA
  1330. _LEN = MAX_AREA//MAX_LEN
  1331. chars = process_data([sentence.sentence_text[:MAX_LEN] for sentence in list_sentence[_begin_index:_begin_index+_LEN]])
  1332. lengths, scores, tran_ = sess.run([self.length, self.logit, self.tran],
  1333. feed_dict={
  1334. self.char_input: np.asarray(chars),
  1335. self.dropout: 1.0
  1336. })
  1337. batch_paths = decode(scores, lengths, tran_)
  1338. for sentence, path, length in zip(list_sentence[_begin_index:_begin_index+_LEN],batch_paths, lengths):
  1339. tags = ''.join([str(it) for it in path[:length]])
  1340. for it in re.finditer("12*3", tags):
  1341. start = it.start()
  1342. end = it.end()
  1343. _entity = Entity(doc_id=sentence.doc_id, entity_id="%s_%s_%s_%s" % (
  1344. sentence.doc_id, sentence.sentence_index, start, end),
  1345. entity_text=sentence.sentence_text[start:end],
  1346. entity_type="product", sentence_index=sentence.sentence_index,
  1347. begin_index=0, end_index=0, wordOffset_begin=start,
  1348. wordOffset_end=end)
  1349. list_entity.append(_entity)
  1350. temp_list.append(sentence.sentence_text[start:end])
  1351. # item["product"] = list(set(temp_list))
  1352. # result.append(item)
  1353. if _begin_index+_LEN >= len(list_sentence):
  1354. break
  1355. _begin_index += _LEN
  1356. item["product"] = list(set(temp_list))
  1357. result.append(item) # 修正bug
  1358. return result
  1359. # docchannel类型提取
  1360. class DocChannel():
  1361. def __init__(self, life_model='/channel_savedmodel/channel.pb', type_model='/channel_savedmodel/doctype.pb'):
  1362. self.lift_sess, self.lift_title, self.lift_content, self.lift_prob, self.lift_softmax,\
  1363. self.mask, self.mask_title = self.load_life(life_model)
  1364. self.type_sess, self.type_title, self.type_content, self.type_prob, self.type_softmax,\
  1365. self.type_mask, self.type_mask_title = self.load_type(type_model)
  1366. self.sequen_len = 200 # 150 200
  1367. self.title_len = 30
  1368. self.sentence_num = 10
  1369. self.kws = '供货商|候选人|供应商|入选人|项目|选定|预告|中标|成交|补遗|延期|报名|暂缓|结果|意向|出租|补充|合同|限价|比选|指定|工程|废标|取消|中止|流标|资质|资格|地块|招标|采购|货物|租赁|计划|宗地|需求|来源|土地|澄清|失败|探矿|预审|变更|变卖|遴选|撤销|意见|恢复|采矿|更正|终止|废置|报建|流拍|供地|登记|挂牌|答疑|中选|受让|拍卖|竞拍|审查|入围|更改|条件|洽谈|乙方|后审|控制|暂停|用地|询价|预'
  1370. lb_type = ['采招数据', '土地矿产', '拍卖出让', '产权交易', '新闻资讯']
  1371. lb_life = ['采购意向', '招标预告', '招标公告', '招标答疑', '公告变更', '资审结果', '中标信息', '合同公告', '废标公告']
  1372. self.id2type = {k: v for k, v in enumerate(lb_type)}
  1373. self.id2life = {k: v for k, v in enumerate(lb_life)}
  1374. def load_life(self,life_model):
  1375. with tf.Graph().as_default() as graph:
  1376. output_graph_def = graph.as_graph_def()
  1377. with open(os.path.dirname(__file__)+life_model, 'rb') as f:
  1378. output_graph_def.ParseFromString(f.read())
  1379. tf.import_graph_def(output_graph_def, name='')
  1380. print("%d ops in the final graph" % len(output_graph_def.node))
  1381. del output_graph_def
  1382. sess = tf.Session(graph=graph)
  1383. sess.run(tf.global_variables_initializer())
  1384. inputs = sess.graph.get_tensor_by_name('inputs/inputs:0')
  1385. prob = sess.graph.get_tensor_by_name('inputs/dropout:0')
  1386. title = sess.graph.get_tensor_by_name('inputs/title:0')
  1387. mask = sess.graph.get_tensor_by_name('inputs/mask:0')
  1388. mask_title = sess.graph.get_tensor_by_name('inputs/mask_title:0')
  1389. # logit = sess.graph.get_tensor_by_name('output/logit:0')
  1390. softmax = sess.graph.get_tensor_by_name('output/softmax:0')
  1391. return sess, title, inputs, prob, softmax, mask, mask_title
  1392. def load_type(self,type_model):
  1393. with tf.Graph().as_default() as graph:
  1394. output_graph_def = graph.as_graph_def()
  1395. with open(os.path.dirname(__file__)+type_model, 'rb') as f:
  1396. output_graph_def.ParseFromString(f.read())
  1397. tf.import_graph_def(output_graph_def, name='')
  1398. print("%d ops in the final graph" % len(output_graph_def.node))
  1399. del output_graph_def
  1400. sess = tf.Session(graph=graph)
  1401. sess.run(tf.global_variables_initializer())
  1402. inputs = sess.graph.get_tensor_by_name('inputs/inputs:0')
  1403. prob = sess.graph.get_tensor_by_name('inputs/dropout:0')
  1404. title = sess.graph.get_tensor_by_name('inputs/title:0')
  1405. mask = sess.graph.get_tensor_by_name('inputs/mask:0')
  1406. mask_title = sess.graph.get_tensor_by_name('inputs/mask_title:0')
  1407. # logit = sess.graph.get_tensor_by_name('output/logit:0')
  1408. softmax = sess.graph.get_tensor_by_name('output/softmax:0')
  1409. return sess, title, inputs, prob, softmax, mask, mask_title
  1410. def predict_process(self, docid='', doctitle='', dochtmlcon=''):
  1411. # print('准备预处理')
  1412. def get_kw_senten(s, span=10):
  1413. doc_sens = []
  1414. tmp = 0
  1415. num = 0
  1416. end_idx = 0
  1417. for it in re.finditer(self.kws, s): # '|'.join(keywordset)
  1418. left = s[end_idx:it.end()].split()
  1419. right = s[it.end():].split()
  1420. tmp_seg = s[tmp:it.start()].split()
  1421. if len(tmp_seg) > span or tmp == 0:
  1422. doc_sens.append(' '.join(left[-span:] + right[:span]))
  1423. end_idx = it.end() + 1 + len(' '.join(right[:span]))
  1424. tmp = it.end()
  1425. num += 1
  1426. if num >= self.sentence_num:
  1427. break
  1428. if doc_sens == []:
  1429. doc_sens.append(s)
  1430. return doc_sens
  1431. def word2id(wordlist, max_len=self.sequen_len):
  1432. ids = [getIndexOfWords(w) for w in wordlist]
  1433. ids = ids[:max_len] if len(ids) >= max_len else ids + [0] * (max_len - len(ids))
  1434. assert len(ids) == max_len
  1435. return ids
  1436. cost_time = dict()
  1437. datas = []
  1438. datas_title = []
  1439. try:
  1440. segword_title = ' '.join(selffool.cut(doctitle)[0])
  1441. segword_content = dochtmlcon
  1442. except:
  1443. segword_content = ''
  1444. segword_title = ''
  1445. if isinstance(segword_content, float):
  1446. segword_content = ''
  1447. if isinstance(segword_title, float):
  1448. segword_title = ''
  1449. segword_content = segword_content.replace(' 中 选 ', ' 中选 ').replace(' 中 标 ', ' 中标 ').replace(' 补 遗 ', ' 补遗 '). \
  1450. replace(' 更 多', '').replace(' 更多', '').replace(' 中 号 ', ' 中标 ').replace(' 中 选人 ', ' 中选人 '). \
  1451. replace(' 点击 下载 查看', '').replace(' 咨询 报价 请 点击', '').replace('终结', '终止')
  1452. segword_title = re.sub('[^\s\u4e00-\u9fa5]', '', segword_title)
  1453. segword_content = re.sub('[^\s\u4e00-\u9fa5]', '', segword_content)
  1454. doc_word_list = segword_content.split()
  1455. if len(doc_word_list) > self.sequen_len / 2:
  1456. doc_sens = get_kw_senten(' '.join(doc_word_list[100:500]))
  1457. doc_sens = ' '.join(doc_word_list[:100]) + '\n' + '\n'.join(doc_sens)
  1458. else:
  1459. doc_sens = ' '.join(doc_word_list[:self.sequen_len])
  1460. datas.append(doc_sens.split())
  1461. datas_title.append(segword_title.split())
  1462. # print('完成预处理')
  1463. return datas, datas_title
  1464. def is_houxuan(self, title, content):
  1465. '''
  1466. 通过标题和中文内容判断是否属于候选人公示类别
  1467. :param title: 公告标题
  1468. :param content: 公告正文文本内容
  1469. :return: 1 是候选人公示 ;0 不是
  1470. '''
  1471. if re.search('候选人的?公示|评标结果|评审结果|中标公示', title): # (中标|成交|中选|入围)
  1472. if re.search('变更公告|更正公告|废标|终止|答疑|澄清', title):
  1473. return 0
  1474. return 1
  1475. if re.search('候选人的?公示', content[:100]):
  1476. if re.search('公示(期|活动)?已经?结束|公示期已满|中标结果公告|中标结果公示|变更公告|更正公告|废标|终止|答疑|澄清', content[:100]):
  1477. return 0
  1478. return 1
  1479. else:
  1480. return 0
  1481. def predict(self, title='', content=''):
  1482. # print('准备预测')
  1483. if isinstance(content, list):
  1484. token_l = [it.tokens for it in content]
  1485. tokens = [it for l in token_l for it in l]
  1486. content = ' '.join(tokens[:500])
  1487. data_content, data_title = self.predict_process(docid='', doctitle=title[:50], dochtmlcon=content) # 标题最多取50字
  1488. text_len = len(data_content[0]) if len(data_content[0])<self.sequen_len else self.sequen_len
  1489. title_len = len(data_title[0]) if len(data_title[0])<self.title_len else self.title_len
  1490. array_content = embedding(data_content, shape=(len(data_content), self.sequen_len, 128))
  1491. array_title = embedding(data_title, shape=(len(data_title), self.title_len, 128))
  1492. pred = self.type_sess.run(self.type_softmax,
  1493. feed_dict={
  1494. self.type_title: array_title,
  1495. self.type_content: array_content,
  1496. self.type_mask:[[0]*text_len+[1]*(self.sequen_len-text_len)],
  1497. self.type_mask_title:[[0]*title_len+[1]*(self.title_len-title_len)],
  1498. self.type_prob:1}
  1499. )
  1500. id = np.argmax(pred, axis=1)[0]
  1501. prob = pred[0][id]
  1502. if id == 0:
  1503. pred = self.lift_sess.run(self.lift_softmax,
  1504. feed_dict={
  1505. self.lift_title: array_title,
  1506. self.lift_content: array_content,
  1507. self.mask: [[0] * text_len + [1] * (self.sequen_len - text_len)],
  1508. self.mask_title: [[0] * title_len + [1] * (self.title_len - title_len)],
  1509. self.lift_prob:1}
  1510. )
  1511. id = np.argmax(pred, axis=1)[0]
  1512. prob = pred[0][id]
  1513. if id == 6:
  1514. if self.is_houxuan(''.join([it for it in title if it.isalpha()]), ''.join([it for it in content if it.isalpha()])):
  1515. # return '候选人公示', prob
  1516. return [{'docchannel': '候选人公示'}]
  1517. # return self.id2life[id], prob
  1518. return [{'docchannel':self.id2life[id]}]
  1519. else:
  1520. # return self.id2type[id], prob
  1521. return [{'docchannel':self.id2type[id]}]
  1522. def getSavedModel():
  1523. #predictor = FormPredictor()
  1524. graph = tf.Graph()
  1525. with graph.as_default():
  1526. model = tf.keras.models.load_model("../form/model/model_form.model_item.hdf5",custom_objects={"precision":precision,"recall":recall,"f1_score":f1_score})
  1527. #print(tf.graph_util.remove_training_nodes(model))
  1528. tf.saved_model.simple_save(
  1529. tf.keras.backend.get_session(),
  1530. "./h5_savedmodel/",
  1531. inputs={"image": model.input},
  1532. outputs={"scores": model.output}
  1533. )
  1534. def getBiLSTMCRFModel(MAX_LEN,vocab,EMBED_DIM,BiRNN_UNITS,chunk_tags,weights):
  1535. '''
  1536. model = models.Sequential()
  1537. model.add(layers.Embedding(len(vocab), EMBED_DIM, mask_zero=True)) # Random embedding
  1538. model.add(layers.Bidirectional(layers.LSTM(BiRNN_UNITS // 2, return_sequences=True)))
  1539. crf = CRF(len(chunk_tags), sparse_target=True)
  1540. model.add(crf)
  1541. model.summary()
  1542. model.compile('adam', loss=crf.loss_function, metrics=[crf.accuracy])
  1543. return model
  1544. '''
  1545. input = layers.Input(shape=(None,),dtype="int32")
  1546. if weights is not None:
  1547. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True,weights=[weights],trainable=True)(input)
  1548. else:
  1549. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True)(input)
  1550. bilstm = layers.Bidirectional(layers.LSTM(BiRNN_UNITS//2,return_sequences=True))(embedding)
  1551. bilstm_dense = layers.TimeDistributed(layers.Dense(len(chunk_tags)))(bilstm)
  1552. crf = CRF(len(chunk_tags),sparse_target=True)
  1553. crf_out = crf(bilstm_dense)
  1554. model = models.Model(input=[input],output = [crf_out])
  1555. model.summary()
  1556. model.compile(optimizer = 'adam', loss = crf.loss_function, metrics = [crf.accuracy])
  1557. return model
  1558. import h5py
  1559. def h5_to_graph(sess,graph,h5file):
  1560. f = h5py.File(h5file,'r') #打开h5文件
  1561. def getValue(v):
  1562. _value = f["model_weights"]
  1563. list_names = str(v.name).split("/")
  1564. for _index in range(len(list_names)):
  1565. print(v.name)
  1566. if _index==1:
  1567. _value = _value[list_names[0]]
  1568. _value = _value[list_names[_index]]
  1569. return _value.value
  1570. def _load_attributes_from_hdf5_group(group, name):
  1571. """Loads attributes of the specified name from the HDF5 group.
  1572. This method deals with an inherent problem
  1573. of HDF5 file which is not able to store
  1574. data larger than HDF5_OBJECT_HEADER_LIMIT bytes.
  1575. # Arguments
  1576. group: A pointer to a HDF5 group.
  1577. name: A name of the attributes to load.
  1578. # Returns
  1579. data: Attributes data.
  1580. """
  1581. if name in group.attrs:
  1582. data = [n.decode('utf8') for n in group.attrs[name]]
  1583. else:
  1584. data = []
  1585. chunk_id = 0
  1586. while ('%s%d' % (name, chunk_id)) in group.attrs:
  1587. data.extend([n.decode('utf8')
  1588. for n in group.attrs['%s%d' % (name, chunk_id)]])
  1589. chunk_id += 1
  1590. return data
  1591. def readGroup(gr,parent_name,data):
  1592. for subkey in gr:
  1593. print(subkey)
  1594. if parent_name!=subkey:
  1595. if parent_name=="":
  1596. _name = subkey
  1597. else:
  1598. _name = parent_name+"/"+subkey
  1599. else:
  1600. _name = parent_name
  1601. if str(type(gr[subkey]))=="<class 'h5py._hl.group.Group'>":
  1602. readGroup(gr[subkey],_name,data)
  1603. else:
  1604. data.append([_name,gr[subkey].value])
  1605. print(_name,gr[subkey].shape)
  1606. layer_names = _load_attributes_from_hdf5_group(f["model_weights"], 'layer_names')
  1607. list_name_value = []
  1608. readGroup(f["model_weights"], "", list_name_value)
  1609. '''
  1610. for k, name in enumerate(layer_names):
  1611. g = f["model_weights"][name]
  1612. weight_names = _load_attributes_from_hdf5_group(g, 'weight_names')
  1613. #weight_values = [np.asarray(g[weight_name]) for weight_name in weight_names]
  1614. for weight_name in weight_names:
  1615. list_name_value.append([weight_name,np.asarray(g[weight_name])])
  1616. '''
  1617. for name_value in list_name_value:
  1618. name = name_value[0]
  1619. '''
  1620. if re.search("dense",name) is not None:
  1621. name = name[:7]+"_1"+name[7:]
  1622. '''
  1623. value = name_value[1]
  1624. print(name,graph.get_tensor_by_name(name),np.shape(value))
  1625. sess.run(tf.assign(graph.get_tensor_by_name(name),value))
  1626. def initialize_uninitialized(sess):
  1627. global_vars = tf.global_variables()
  1628. is_not_initialized = sess.run([tf.is_variable_initialized(var) for var in global_vars])
  1629. not_initialized_vars = [v for (v, f) in zip(global_vars, is_not_initialized) if not f]
  1630. adam_vars = []
  1631. for _vars in not_initialized_vars:
  1632. if re.search("Adam",_vars.name) is not None:
  1633. adam_vars.append(_vars)
  1634. print([str(i.name) for i in adam_vars]) # only for testing
  1635. if len(adam_vars):
  1636. sess.run(tf.variables_initializer(adam_vars))
  1637. def save_codename_model():
  1638. # filepath = "../projectCode/models/model_project_"+str(60)+"_"+str(200)+".hdf5"
  1639. filepath = "../projectCode/models_tf/59-L0.471516189943-F0.8802154826344823-P0.8789179683459191-R0.8815168335321886/model.ckpt"
  1640. vocabpath = "../projectCode/models/vocab.pk"
  1641. classlabelspath = "../projectCode/models/classlabels.pk"
  1642. # vocab = load(vocabpath)
  1643. # class_labels = load(classlabelspath)
  1644. w2v_matrix = load('codename_w2v_matrix.pk')
  1645. graph = tf.get_default_graph()
  1646. with graph.as_default() as g:
  1647. ''''''
  1648. # model = getBiLSTMCRFModel(None, vocab, 60, 200, class_labels,weights=None)
  1649. #model = models.load_model(filepath,custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score,"CRF":CRF,"loss":CRF.loss_function})
  1650. sess = tf.Session(graph=g)
  1651. # sess = tf.keras.backend.get_session()
  1652. char_input, logits, target, keepprob, length, crf_loss, trans, train_op = BiLSTM_CRF_tfmodel(sess, w2v_matrix)
  1653. #with sess.as_default():
  1654. sess.run(tf.global_variables_initializer())
  1655. # print(sess.run("time_distributed_1/kernel:0"))
  1656. # model.load_weights(filepath)
  1657. saver = tf.train.Saver()
  1658. saver.restore(sess, filepath)
  1659. # print("logits",sess.run(logits))
  1660. # print("#",sess.run("time_distributed_1/kernel:0"))
  1661. # x = load("codename_x.pk")
  1662. #y = model.predict(x)
  1663. # y = sess.run(model.output,feed_dict={model.input:x})
  1664. # for item in np.argmax(y,-1):
  1665. # print(item)
  1666. tf.saved_model.simple_save(
  1667. sess,
  1668. "./codename_savedmodel_tf/",
  1669. inputs={"inputs": char_input,
  1670. "inputs_length":length,
  1671. 'keepprob':keepprob},
  1672. outputs={"logits": logits,
  1673. "trans":trans}
  1674. )
  1675. def save_role_model():
  1676. '''
  1677. @summary: 保存model为savedModel,部署到PAI平台上调用
  1678. '''
  1679. model_role = PREMPredict().model_role
  1680. with model_role.graph.as_default():
  1681. model = model_role.getModel()
  1682. sess = tf.Session(graph=model_role.graph)
  1683. print(type(model.input))
  1684. sess.run(tf.global_variables_initializer())
  1685. h5_to_graph(sess, model_role.graph, model_role.model_role_file)
  1686. model = model_role.getModel()
  1687. tf.saved_model.simple_save(sess,
  1688. "./role_savedmodel/",
  1689. inputs={"input0":model.input[0],
  1690. "input1":model.input[1],
  1691. "input2":model.input[2]},
  1692. outputs={"outputs":model.output}
  1693. )
  1694. def save_money_model():
  1695. model_file = os.path.dirname(__file__)+"/../money/models/model_money_word.h5"
  1696. graph = tf.Graph()
  1697. with graph.as_default():
  1698. sess = tf.Session(graph=graph)
  1699. with sess.as_default():
  1700. # model = model_money.getModel()
  1701. # model.summary()
  1702. # sess.run(tf.global_variables_initializer())
  1703. # h5_to_graph(sess, model_money.graph, model_money.model_money_file)
  1704. model = models.load_model(model_file,custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score})
  1705. model.summary()
  1706. print(model.weights)
  1707. tf.saved_model.simple_save(sess,
  1708. "./money_savedmodel2/",
  1709. inputs = {"input0":model.input[0],
  1710. "input1":model.input[1],
  1711. "input2":model.input[2]},
  1712. outputs = {"outputs":model.output}
  1713. )
  1714. def save_person_model():
  1715. model_person = EPCPredict().model_person
  1716. with model_person.graph.as_default():
  1717. x = load("person_x.pk")
  1718. _data = np.transpose(np.array(x),(1,0,2,3))
  1719. model = model_person.getModel()
  1720. sess = tf.Session(graph=model_person.graph)
  1721. with sess.as_default():
  1722. sess.run(tf.global_variables_initializer())
  1723. model_person.load_weights()
  1724. #h5_to_graph(sess, model_person.graph, model_person.model_person_file)
  1725. predict_y = sess.run(model.output,feed_dict={model.input[0]:_data[0],model.input[1]:_data[1]})
  1726. #predict_y = model.predict([_data[0],_data[1]])
  1727. print(np.argmax(predict_y,-1))
  1728. tf.saved_model.simple_save(sess,
  1729. "./person_savedmodel/",
  1730. inputs={"input0":model.input[0],
  1731. "input1":model.input[1]},
  1732. outputs = {"outputs":model.output})
  1733. def save_form_model():
  1734. model_form = FormPredictor()
  1735. with model_form.graph.as_default():
  1736. model = model_form.getModel("item")
  1737. sess = tf.Session(graph=model_form.graph)
  1738. sess.run(tf.global_variables_initializer())
  1739. h5_to_graph(sess, model_form.graph, model_form.model_file_item)
  1740. tf.saved_model.simple_save(sess,
  1741. "./form_savedmodel/",
  1742. inputs={"inputs":model.input},
  1743. outputs = {"outputs":model.output})
  1744. def save_codesplit_model():
  1745. filepath_code = "../projectCode/models/model_code.hdf5"
  1746. graph = tf.Graph()
  1747. with graph.as_default():
  1748. model_code = models.load_model(filepath_code, custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score})
  1749. sess = tf.Session()
  1750. sess.run(tf.global_variables_initializer())
  1751. h5_to_graph(sess, graph, filepath_code)
  1752. tf.saved_model.simple_save(sess,
  1753. "./codesplit_savedmodel/",
  1754. inputs={"input0":model_code.input[0],
  1755. "input1":model_code.input[1],
  1756. "input2":model_code.input[2]},
  1757. outputs={"outputs":model_code.output})
  1758. def save_timesplit_model():
  1759. filepath = '../time/model_label_time_classify.model.hdf5'
  1760. with tf.Graph().as_default() as graph:
  1761. time_model = models.load_model(filepath, custom_objects={'precision': precision, 'recall': recall, 'f1_score': f1_score})
  1762. with tf.Session() as sess:
  1763. sess.run(tf.global_variables_initializer())
  1764. h5_to_graph(sess, graph, filepath)
  1765. tf.saved_model.simple_save(sess,
  1766. "./timesplit_model/",
  1767. inputs={"input0":time_model.input[0],
  1768. "input1":time_model.input[1]},
  1769. outputs={"outputs":time_model.output})
  1770. if __name__=="__main__":
  1771. #save_role_model()
  1772. # save_codename_model()
  1773. save_money_model()
  1774. #save_person_model()
  1775. #save_form_model()
  1776. #save_codesplit_model()
  1777. # save_timesplit_model()
  1778. '''
  1779. # with tf.Session(graph=tf.Graph()) as sess:
  1780. # from tensorflow.python.saved_model import tag_constants
  1781. # meta_graph_def = tf.saved_model.loader.load(sess, [tag_constants.SERVING], "./person_savedModel")
  1782. # graph = tf.get_default_graph()
  1783. # signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  1784. # signature = meta_graph_def.signature_def
  1785. # input0 = sess.graph.get_tensor_by_name(signature[signature_key].inputs["input0"].name)
  1786. # input1 = sess.graph.get_tensor_by_name(signature[signature_key].inputs["input1"].name)
  1787. # outputs = sess.graph.get_tensor_by_name(signature[signature_key].outputs["outputs"].name)
  1788. # x = load("person_x.pk")
  1789. # _data = np.transpose(x,[1,0,2,3])
  1790. # y = sess.run(outputs,feed_dict={input0:_data[0],input1:_data[1]})
  1791. # print(np.argmax(y,-1))
  1792. '''