predictor.py 131 KB

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