predictor.py 121 KB

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