getAttributes.py 185 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170
  1. from BiddingKG.dl.common.Utils import findAllIndex,debug,timeFormat,getCurrent_date,API_URL
  2. from BiddingKG.dl.interface.Entitys import PREM,Role,Entity
  3. from decimal import Decimal
  4. import re
  5. import copy
  6. import math
  7. import pandas as pd
  8. import os
  9. from scipy.optimize import linear_sum_assignment
  10. from BiddingKG.dl.interface.Entitys import Match
  11. import numpy as np
  12. def getTheRole(entity,role_list):
  13. '''
  14. @summary:根据实体名称拿到index
  15. @param:
  16. entity:实体名称
  17. role_list:角色list
  18. @return:该实体所在下标
  19. '''
  20. for role_index in range(len(role_list)):
  21. if entity in role_list[role_index]:
  22. return role_index
  23. return None
  24. dict_role_id = {"0":"tenderee",
  25. "1":"agency",
  26. "2":"win_tenderer",
  27. "3":"second_tenderer",
  28. "4":"third_tenderer"}
  29. def getPackage(packageList,sentence_index,begin_index,roleid,MAX_DIS=None,DIRECT=None):
  30. '''
  31. @param:
  32. packageList:文章的包的信息,包号-sent_index-词偏移-字偏移-[[前作用域句子,句内偏移],[后作用域句子,句内偏移]]-匹配集合
  33. sentence_index:实体所在的句子
  34. begin_index:实体所在句子的起始位置
  35. @return:公司实体所属的包
  36. @summary: 优化多标段,确定标段作用域之后,寻找作用域包含该实体的所有包,从前往后找到一个还没有该roleid的包返回,若找到的包都有roleid,则返回第一个,若没有找到包,返回None
  37. '''
  38. '''
  39. if len(packageList)==0:
  40. return None
  41. before_index = None
  42. after_index = None
  43. equal_index = None
  44. equal_count = 0
  45. for pack_index in range(len(packageList)):
  46. if packageList[pack_index][1]>sentence_index and after_index is None:
  47. after_index = pack_index
  48. if packageList[pack_index][1]<sentence_index:
  49. before_index = pack_index
  50. if packageList[pack_index][1]==sentence_index and equal_index is None:
  51. equal_index = pack_index
  52. #当前句子和之前句子未找到包
  53. if before_index is None and equal_index is None:
  54. return None
  55. else:
  56. if after_index is None:
  57. end_index = len(packageList)
  58. else:
  59. end_index = after_index
  60. #只在当前句子找到一个包号
  61. if end_index-max((before_index if before_index is not None else -1,equal_index if equal_index is not None else -1))==1:
  62. return packageList[end_index-1][0]
  63. else:
  64. for i in range(max((before_index if before_index is not None else -1,equal_index if equal_index is not None else -1)),end_index):
  65. if packageList[i][2]>int(begin_index):
  66. if packageList[i-1][4]:
  67. return packageList[i-1][0]
  68. else:
  69. if packageList[i][4]:
  70. return packageList[i-1][0]
  71. else:
  72. return packageList[i][0]
  73. return packageList[end_index-1][0]
  74. '''
  75. if len(packageList)==0:
  76. return None,False
  77. list_legalPack = []
  78. for pack_index in range(len(packageList)):
  79. if DIRECT=="L" and (packageList[pack_index]["sentence_index"]>sentence_index or (packageList[pack_index]["sentence_index"]==sentence_index and packageList[pack_index]["offsetWords_begin"]>begin_index)):
  80. continue
  81. if DIRECT=="R" and (packageList[pack_index]["sentence_index"]<sentence_index or (packageList[pack_index]["sentence_index"]==sentence_index and packageList[pack_index]["offsetwords_begin"]<begin_index)):
  82. continue
  83. if (packageList[pack_index]["scope"][0][0]<sentence_index or (packageList[pack_index]["scope"][0][0]==sentence_index and packageList[pack_index]["scope"][0][1]<=begin_index)) and (packageList[pack_index]["scope"][1][0]>sentence_index or (packageList[pack_index]["scope"][1][0]==sentence_index and packageList[pack_index]["scope"][1][1]>=begin_index)):
  84. if MAX_DIS is not None:
  85. if abs(sentence_index-packageList[pack_index]["sentence_index"])<=MAX_DIS:
  86. list_legalPack.append(pack_index)
  87. else:
  88. list_legalPack.append(pack_index)
  89. # if (packageList[pack_index]["scope"][0][0] < sentence_index
  90. # or (packageList[pack_index]["scope"][0][0] == sentence_index
  91. # and packageList[pack_index]["scope"][0][1] <= begin_index))
  92. # and (packageList[pack_index]["scope"][1][0] > sentence_index
  93. # or (packageList[pack_index]["scope"][1][0] == sentence_index
  94. # and packageList[pack_index]["scope"][1][1] >= begin_index)):
  95. # pass
  96. _flag = True
  97. for _index in list_legalPack:
  98. if roleid in packageList[_index]["hit"]:
  99. continue
  100. else:
  101. _flag = False
  102. packageList[_index]["hit"].add(roleid)
  103. return packageList[_index]["pointer"],_flag
  104. if len(list_legalPack)>0:
  105. return packageList[0]["pointer"],_flag
  106. return None,False
  107. #生成合法的组合
  108. def get_legal_comba(list_entity,dict_role_combination):
  109. #拿到一个包中所有合法的组合
  110. def circle_package(_dict_legal_combination):
  111. list_dict_role_first = []
  112. for _role in _dict_legal_combination:
  113. if len(list_dict_role_first)==0:
  114. for _entity in _dict_legal_combination[_role]:
  115. if _entity !="":
  116. list_dict_role_first.append({_role:_entity})
  117. else:
  118. list_dict_role_after = []
  119. _find_count = 0
  120. for _entity in _dict_legal_combination[_role]:
  121. if _entity !="":
  122. for _dict in list_dict_role_first:
  123. _flag = True
  124. for _key1 in _dict:
  125. if _entity==_dict[_key1]:
  126. #修改为招标人和代理人可以为同一个
  127. if str(_key1) in ["0","1"] and str(_role) in ["0","1"]:
  128. _flag = True
  129. else:
  130. _flag = False
  131. if _flag:
  132. _find_count += 1
  133. _new_dict = copy.copy(_dict)
  134. _new_dict[_role] = _entity
  135. if len(list_dict_role_after)>100000:
  136. break
  137. list_dict_role_after.append(_new_dict)
  138. else:
  139. # 2021/5/25 update,同一实体(entity_text)不同角色
  140. if len(list_dict_role_after) > 100000:
  141. break
  142. for _dict in list_dict_role_first:
  143. for _key1 in _dict:
  144. if _entity == _dict[_key1]:
  145. _new_dict = copy.copy(_dict)
  146. _new_dict.pop(_key1)
  147. _new_dict[_role] = _entity
  148. list_dict_role_after.append({_role:_entity})
  149. if len(list_dict_role_after)==0:
  150. pass
  151. else:
  152. list_dict_role_first.extend(list_dict_role_after)
  153. return list_dict_role_first
  154. def recursive_package(_dict_legal_combination,set_legal_entity,dict_one_selution,list_all_selution):
  155. last_layer = False
  156. #若是空组合则放回空
  157. if len(_dict_legal_combination.keys())==0:
  158. return []
  159. #递归到最后一层则修改状态
  160. if len(_dict_legal_combination.keys())==1:
  161. last_layer = True
  162. #取一个角色开始进行遍历
  163. _key_role = list(_dict_legal_combination.keys())[0]
  164. for item in _dict_legal_combination[_key_role]:
  165. copy_dict_one_selution = copy.copy(dict_one_selution)
  166. copy_dict_legal_combination = {}
  167. copy_set_legal_entity = copy.copy(set_legal_entity)
  168. #复制余下的所有角色,进行下一轮递归
  169. for _key in _dict_legal_combination.keys():
  170. if _key!=_key_role:
  171. copy_dict_legal_combination[_key] = _dict_legal_combination[_key]
  172. #修改为招标人和代理人可以为同一个
  173. if item !="":
  174. _flag = True
  175. if str(_key_role) in ["0","1"]:
  176. for _key_flag in copy_dict_one_selution:
  177. if _key_flag not in ["0","1"] and copy_dict_one_selution[_key_flag]==item:
  178. _flag = False
  179. else:
  180. for _key_flag in copy_dict_one_selution:
  181. if copy_dict_one_selution[_key_flag]==item:
  182. _flag = False
  183. if _flag:
  184. copy_dict_one_selution[_key_role] = item
  185. '''
  186. if item not in copy_set_legal_entity:
  187. if item !="":
  188. copy_dict_one_selution[_key_role] = item
  189. '''
  190. copy_set_legal_entity.add(item)
  191. if last_layer:
  192. list_all_selution.append(copy_dict_one_selution)
  193. else:
  194. recursive_package(copy_dict_legal_combination,copy_set_legal_entity,copy_dict_one_selution,list_all_selution)
  195. #递归匹配各个包的结果
  196. def recursive_packages(_dict_legal_combination,dict_one_selution,list_all_selution):
  197. last_layer = False
  198. if len(_dict_legal_combination.keys())==0:
  199. return []
  200. if len(_dict_legal_combination.keys())==1:
  201. last_layer = True
  202. _key_pack = list(_dict_legal_combination.keys())[0]
  203. for item in _dict_legal_combination[_key_pack]:
  204. copy_dict_one_selution = copy.copy(dict_one_selution)
  205. copy_dict_legal_combination = {}
  206. for _key in _dict_legal_combination.keys():
  207. if _key!=_key_pack:
  208. copy_dict_legal_combination[_key] = _dict_legal_combination[_key]
  209. for _key_role in item.keys():
  210. copy_dict_one_selution[_key_pack+"$$"+_key_role] = item[_key_role]
  211. if last_layer:
  212. list_all_selution.append(copy_dict_one_selution)
  213. else:
  214. recursive_packages(copy_dict_legal_combination,copy_dict_one_selution,list_all_selution)
  215. return list_all_selution
  216. #循环获取所有包组合
  217. def circle_pageages(_dict_legal_combination):
  218. list_all_selution = []
  219. for _key_pack in _dict_legal_combination.keys():
  220. list_key_selution = []
  221. for item in _dict_legal_combination[_key_pack]:
  222. _dict = dict()
  223. for _key_role in item.keys():
  224. _dict[_key_pack+"$$"+_key_role] = item[_key_role]
  225. list_key_selution.append(_dict)
  226. if len(list_all_selution)==0:
  227. list_all_selution = list_key_selution
  228. else:
  229. _list_all_selution = []
  230. for item_1 in list_all_selution:
  231. for item_2 in list_key_selution:
  232. _list_all_selution.append(dict(item_1,**item_2))
  233. list_all_selution = _list_all_selution
  234. return list_all_selution
  235. #拿到各个包解析之后的结果
  236. _dict_legal_combination = {}
  237. for packageName in dict_role_combination.keys():
  238. _list_all_selution = []
  239. # recursive_package(dict_role_combination[packageName], set(), {}, _list_all_selution)
  240. _list_all_selution = circle_package(dict_role_combination[packageName])
  241. '''
  242. # print("===1")
  243. # print(packageName)
  244. for item in _list_all_selution:
  245. # print(item)
  246. # print("===2")
  247. '''
  248. #去除包含子集
  249. list_all_selution_simple = []
  250. _list_set_all_selution = []
  251. for item_selution in _list_all_selution:
  252. item_set_selution = set()
  253. for _key in item_selution.keys():
  254. item_set_selution.add((_key,item_selution[_key]))
  255. _list_set_all_selution.append(item_set_selution)
  256. if len(_list_set_all_selution)>1000:
  257. _dict_legal_combination[packageName] = _list_all_selution
  258. continue
  259. for i in range(len(_list_set_all_selution)):
  260. be_included = False
  261. for j in range(len(_list_set_all_selution)):
  262. if i!=j:
  263. if len(set(_list_set_all_selution[i])&set(_list_set_all_selution[j]))==len(_list_set_all_selution[i]) and len(_list_set_all_selution[i])!=len(_list_set_all_selution[j]):
  264. be_included = True
  265. if not be_included:
  266. list_all_selution_simple.append(_list_all_selution[i])
  267. _dict_legal_combination[packageName] = list_all_selution_simple
  268. _list_final_comba = []
  269. #对各个包的结果进行排列组合
  270. _comba_count = 1
  271. for _key in _dict_legal_combination.keys():
  272. _comba_count *= len(_dict_legal_combination[_key])
  273. #如果过大,则每个包只取概率最大的那个
  274. dict_pack_entity_prob = get_dict_entity_prob(list_entity)
  275. if _comba_count>250:
  276. new_dict_legal_combination = dict()
  277. for _key_pack in _dict_legal_combination.keys():
  278. MAX_PROB = -1000
  279. _MAX_PROB_COMBA = None
  280. for item in _dict_legal_combination[_key_pack]:
  281. # print(_key_pack,item)
  282. _dict = dict()
  283. for _key in item.keys():
  284. _dict[str(_key_pack)+"$$"+str(_key)] = item[_key]
  285. _prob = getSumExpectation(dict_pack_entity_prob, _dict)
  286. if _prob>MAX_PROB:
  287. MAX_PROB = _prob
  288. _MAX_PROB_COMBA = [item]
  289. if _MAX_PROB_COMBA is not None:
  290. new_dict_legal_combination[_key_pack] = _MAX_PROB_COMBA
  291. _dict_legal_combination = new_dict_legal_combination
  292. #recursive_packages(_dict_legal_combination, {}, _list_final_comba)
  293. _list_final_comba = circle_pageages(_dict_legal_combination)
  294. #除了Project包(招标人和代理人),其他包是不会有冲突的
  295. #查看是否有一个实体出现在了Project包和其他包中,如有,要进行裁剪
  296. _list_real_comba = []
  297. for dict_item in _list_final_comba:
  298. set_project = set()
  299. set_other = set()
  300. for _key in list(dict_item.keys()):
  301. if _key.split("$$")[0]=="Project":
  302. set_project.add(dict_item[_key])
  303. else:
  304. set_other.add(dict_item[_key])
  305. set_common = set_project&set_other
  306. if len(set_common)>0:
  307. dict_project = {}
  308. dict_not_project = {}
  309. for _key in list(dict_item.keys()):
  310. if dict_item[_key] in set_common:
  311. if str(_key.split("$$")[0])=="Project":
  312. dict_project[_key] = dict_item[_key]
  313. else:
  314. dict_not_project[_key] = dict_item[_key]
  315. else:
  316. dict_project[_key] = dict_item[_key]
  317. dict_not_project[_key] = dict_item[_key]
  318. _list_real_comba.append(dict_project)
  319. _list_real_comba.append(dict_not_project)
  320. else:
  321. _list_real_comba.append(dict_item)
  322. return _list_real_comba
  323. def get_dict_entity_prob(list_entity,on_value=0.5):
  324. dict_pack_entity_prob = {}
  325. for in_attachment in [False,True]:
  326. identified_role = []
  327. if in_attachment==True:
  328. identified_role = [value[0] for value in dict_pack_entity_prob.values()]
  329. for entity in list_entity:
  330. if entity.entity_type in ['org','company'] and entity.in_attachment==in_attachment:
  331. values = entity.values
  332. role_prob = float(values[int(entity.label)])
  333. _key = entity.packageName+"$$"+str(entity.label)
  334. if role_prob>=on_value and str(entity.label)!="5":
  335. _key_prob = _key+"$text$"+entity.entity_text
  336. if in_attachment == True:
  337. role_prob = 0.8 if role_prob>0.8 else role_prob #附件的概率修改低点
  338. if entity.entity_text in identified_role:
  339. continue
  340. if _key_prob in dict_pack_entity_prob:
  341. # new_prob = role_prob+dict_pack_entity_prob[_key_prob][1] if role_prob>0.9 else max(role_prob, dict_pack_entity_prob[_key_prob][1])
  342. # dict_pack_entity_prob[_key_prob] = [entity.entity_text, new_prob] #公司同角色多次出现概率累计
  343. if role_prob>dict_pack_entity_prob[_key_prob][1]:
  344. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  345. else:
  346. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  347. return dict_pack_entity_prob
  348. #计算合计期望
  349. def getSumExpectation(dict_pack_entity_prob,combination,on_value=0.5):
  350. '''
  351. expect = 0
  352. for entity in list_entity:
  353. if entity.entity_type in ['org','company']:
  354. values = entity.values
  355. role_prob = float(values[int(entity.label)])
  356. _key = entity.packageName+"$$"+str(entity.label)
  357. if role_prob>on_value and str(entity.label)!="5":
  358. if _key in combination.keys() and combination[_key]==entity.entity_text:
  359. expect += math.pow(role_prob,4)
  360. else:
  361. expect -= math.pow(role_prob,4)
  362. '''
  363. #修改为同一个实体只取对应包-角色的最大的概率值
  364. expect = 0
  365. dict_entity_prob = {}
  366. for _key_pack_entity in dict_pack_entity_prob:
  367. _key_pack = _key_pack_entity.split("$text$")[0]
  368. role_prob = dict_pack_entity_prob[_key_pack_entity][1]
  369. if _key_pack in combination.keys() and combination[_key_pack]==dict_pack_entity_prob[_key_pack_entity][0]:
  370. if _key_pack_entity in dict_entity_prob.keys():
  371. if dict_entity_prob[_key_pack_entity]<role_prob:
  372. dict_entity_prob[_key_pack_entity] = role_prob
  373. else:
  374. dict_entity_prob[_key_pack_entity] = role_prob
  375. else:
  376. if _key_pack_entity in dict_entity_prob.keys():
  377. if dict_entity_prob[_key_pack_entity]>-role_prob:
  378. dict_entity_prob[_key_pack_entity] = -role_prob
  379. else:
  380. dict_entity_prob[_key_pack_entity] = -role_prob
  381. # for entity in list_entity:
  382. # if entity.entity_type in ['org','company']:
  383. # values = entity.values
  384. # role_prob = float(values[int(entity.label)])
  385. # _key = entity.packageName+"$$"+str(entity.label)
  386. # if role_prob>=on_value and str(entity.label)!="5":
  387. # if _key in combination.keys() and combination[_key]==entity.entity_text:
  388. # _key_prob = _key+entity.entity_text
  389. # if _key_prob in dict_entity_prob.keys():
  390. # if dict_entity_prob[_key_prob]<role_prob:
  391. # dict_entity_prob[_key_prob] = role_prob
  392. # else:
  393. # dict_entity_prob[_key_prob] = role_prob
  394. # else:
  395. # _key_prob = _key+entity.entity_text
  396. # if _key_prob in dict_entity_prob.keys():
  397. # if dict_entity_prob[_key_prob]>-role_prob:
  398. # dict_entity_prob[_key_prob] = -role_prob
  399. # else:
  400. # dict_entity_prob[_key_prob] = -role_prob
  401. for _key in dict_entity_prob.keys():
  402. symbol = 1 if dict_entity_prob[_key]>0 else -1
  403. expect += symbol*math.pow(dict_entity_prob[_key],2)
  404. return expect
  405. def getRoleList(list_sentence,list_entity,on_value = 0.5):
  406. '''
  407. @summary: 搜索树,得到所有不矛盾的角色组合,取合计期望值最大的作为结果返回
  408. @param:
  409. list_sentence:文章所有的sentence
  410. list_entity:文章所有的实体
  411. on_value:概率阈值
  412. @return:文章的角色list
  413. '''
  414. pack = getPackagesFromArticle(list_sentence,list_entity)
  415. if pack is None:
  416. return None
  417. PackageList,PackageSet,dict_PackageCode = pack
  418. #拿到所有可能的情况
  419. dict_role_combination = {}
  420. # print(PackageList)
  421. #拿到各个实体的packageName,packageCode
  422. for entity in list_entity:
  423. if entity.entity_type in ['org','company']:
  424. #限制附件里角色values[label]最大概率prob
  425. max_prob = 0.85
  426. if str(entity.label)!="5" and entity.in_attachment:
  427. if entity.values[entity.label]>max_prob:
  428. entity.values[entity.label] = max_prob
  429. #过滤掉字数小于3个的实体
  430. if len(entity.entity_text)<=3:
  431. continue
  432. values = entity.values
  433. role_prob = float(values[int(entity.label)])
  434. if role_prob>=on_value and str(entity.label)!="5":
  435. if str(entity.label) in ["0","1"]:
  436. packageName = "Project"
  437. else:
  438. if len(PackageSet)>0:
  439. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"role-"+str(entity.label))
  440. if packagePointer is None:
  441. #continue
  442. packageName = "Project"
  443. # print(entity.entity_text, packageName,entity.sentence_index,entity.begin_index)
  444. else:
  445. #add pointer_pack
  446. entity.pointer_pack = packagePointer
  447. packageName = packagePointer.entity_text
  448. # print(entity.entity_text, packageName)
  449. else:
  450. packageName = "Project"
  451. find_flag = False
  452. if packageName in dict_PackageCode.keys():
  453. packageCode = dict_PackageCode[packageName]
  454. else:
  455. packageCode = ""
  456. entity.packageCode = packageCode
  457. role_name = dict_role_id.get(str(entity.label))
  458. entity.roleName = role_name
  459. entity.packageName = packageName
  460. if entity.packageName in dict_role_combination.keys():
  461. if str(entity.label) in dict_role_combination[entity.packageName].keys():
  462. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  463. else:
  464. dict_role_combination[entity.packageName][str(entity.label)] = set([entity.entity_text])
  465. else:
  466. dict_role_combination[entity.packageName] = {}
  467. #初始化空值
  468. roleIds = [0,1,2,3,4]
  469. for _roleId in roleIds:
  470. dict_role_combination[entity.packageName][str(_roleId)] = set([""])
  471. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  472. list_real_comba = get_legal_comba(list_entity,dict_role_combination)
  473. # print("===role_combination",dict_role_combination)
  474. # print("== real_comba",list_real_comba)
  475. #拿到最大期望值的组合
  476. max_index = 0
  477. max_expect = -100
  478. _index = 0
  479. dict_pack_entity_prob = get_dict_entity_prob(list_entity)
  480. for item_combination in list_real_comba:
  481. expect = getSumExpectation(dict_pack_entity_prob, item_combination)
  482. if expect>max_expect:
  483. max_index = _index
  484. max_expect = expect
  485. _index += 1
  486. RoleList = []
  487. RoleSet = set()
  488. if len(list_real_comba)>0:
  489. for _key in list_real_comba[max_index].keys():
  490. packageName = _key.split("$$")[0]
  491. label = _key.split("$$")[1]
  492. role_name = dict_role_id.get(str(label))
  493. entity_text = list_real_comba[max_index][_key]
  494. if packageName in dict_PackageCode.keys():
  495. packagecode = dict_PackageCode.get(packageName)
  496. else:
  497. packagecode = ""
  498. RoleList.append(PREM(packageName,packagecode,role_name,entity_text,0,0,0.0,[]))
  499. RoleSet.add(entity_text)
  500. #根据最优树来修正list_entity中角色对包的连接
  501. for _entity in list_entity:
  502. if _entity.pointer_pack is not None:
  503. _pack_name = _entity.pointer_pack.entity_text
  504. _find_flag = False
  505. for _prem in RoleList:
  506. if _prem.packageName==_pack_name and _prem.entity_text==_entity.entity_text:
  507. _find_flag = True
  508. if not _find_flag:
  509. _entity.pointer_pack = None
  510. return RoleList,RoleSet,PackageList,PackageSet
  511. def getPackageScopePattern():
  512. '''
  513. @summary: 获取包的作用域关键词
  514. '''
  515. df = pd.read_excel(os.path.dirname(__file__)+"/end.xls")
  516. pattern = "("
  517. for item in df["list_word"]:
  518. item = str(item).replace("(","\(").replace(")","\)").replace(".","\.").replace("[","\[").replace("]","\]").replace("-","\-")
  519. pattern += item+"|"
  520. pattern = pattern[:-1]+")[::是为]|业绩.{,30}标段[0-9A-Za-z一二三四五六七八九十]{0,3}"
  521. return pattern
  522. pattern_packageScope = getPackageScopePattern()
  523. def getPackagesFromArticle(list_sentence,list_entity):
  524. '''
  525. @param:
  526. list_sentence:文章的句子list
  527. @summary: 将包的信息插入list_entity中
  528. @return: type:list if [包号,句子index,词偏移,标段号] meaning:文章的包/标段信息
  529. '''
  530. if len(list_sentence)==0:
  531. return None
  532. list_sentence.sort(key=lambda x:x.sentence_index)
  533. PackageList = []
  534. PackageList_scope = []
  535. PackageSet = set()
  536. dict_packageCode = dict()
  537. package_name_pattern = re.compile("((标[段号的包]|分包)的?(名[称单]?|包名))[::]?([^::]{3,30}?),{1}")
  538. package_N_name_pattern = re.compile("(([^承]|^)分?包|标段|标包|标|包|包组|子项目|包件|项目类型)编?号?[::]?[\((]?([0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]){1,2},{1}")
  539. package_number_pattern = re.compile("(((([^承]|^)包|标[段号的包]|分?包|包组|包件)编?号?|子项目|项目类型)[::]?[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}[^\.])[^至]?|([^\.]?第[ⅠⅡⅢⅣⅤⅥⅦ0-9A-Za-z一二三四五六七八九十]{1,4}(包号|标[段号的包]|分?包))|([^\.]?[ⅠⅡⅢⅣⅤⅥⅦ0-9A-Za-z一二三四五六七八九十]{1,4}(标[段号的包]))") # 第? 去掉问号 修复 纯木浆8包/箱复印 这种作为包号
  540. # other_package_pattern = re.compile('(项目名称|物资名称|设备名称|场次名称|标段名称)[::](.{,20}?)(,|项目)') # 新正则识别标段
  541. other_package_pattern = re.compile('((项目|物资|设备|场次|标段|标的|产品)(名称)?)[::]([^,。]{2,50}?)[,。]') # # 2020/11/23 大网站规则 调整 package_N_name_pattern, package_N_name_pattern 中的项目 改为 子项目
  542. win_tenderer_pattern = re.compile('(中标候?选?人|供应商)(名称)?[::](.{2,25})[,。]') # 2020/11/23 大网站规则 调整
  543. model_pattern = re.compile('(型号|序号)[::]([^,。]{2,20})[,。]') # 2020/11/23 大网站规则 调整
  544. number_pattern = re.compile("[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}")
  545. package_code_pattern = re.compile("(?:编号[::]?\s*)([-\dA-Za-z\(\)]+)")
  546. # 纯数字类型的包号统一,例如:'01','1'
  547. re_digital = re.compile("^\d+$")
  548. def changeIndexFromWordToWords(tokens,word_index):
  549. '''
  550. @summary:转换某个字的字偏移为词偏移
  551. '''
  552. before_index = 0
  553. after_index = 0
  554. for i in range(len(tokens)):
  555. after_index = after_index+len(tokens[i])
  556. if before_index<=word_index and after_index>=word_index:
  557. return i
  558. before_index = after_index
  559. package_names = []
  560. def extractPackageCode(tokens,word_index,size=20,pattern = package_code_pattern):
  561. '''
  562. @summary:抽取包附近的标段号
  563. @param:
  564. tokens:包所在句子的分词
  565. word_index:包所在字偏移
  566. size:左右各取多少个词
  567. pattern:提取标段号的正则
  568. @return: type:string,meaning:标段号
  569. '''
  570. index = changeIndexFromWordToWords(tokens,word_index)
  571. if index<size:
  572. begin = index
  573. else:
  574. begin = index-size
  575. if index+size>len(tokens):
  576. end = len(tokens)
  577. else:
  578. end = index+size
  579. #拿到左右两边的词语组成短语
  580. text = "".join(tokens[begin:end])
  581. #在短语中的字偏移
  582. new_word_index = word_index-len("".join(tokens[:begin]))
  583. min_distance = len(text)
  584. packageCode = None
  585. for the_iter in re.finditer(pattern,text):
  586. #算出最小距离
  587. distance = min([abs(new_word_index-the_iter.span()[0]),abs(new_word_index-the_iter.span()[1])])
  588. if distance<min_distance:
  589. min_distance = distance
  590. packageCode = the_iter.group(1)
  591. return packageCode
  592. #从标段介绍表格中提取包名和包号
  593. for i in range(len(list_sentence)):
  594. content = list_sentence[i].sentence_text
  595. names = re.findall(package_name_pattern,content)
  596. if names == []:
  597. names = re.findall(other_package_pattern, content)
  598. N_names = re.findall(package_N_name_pattern,content)
  599. if len(names)==1 and len(N_names)==1:
  600. package_names.append([names[0][-1],N_names[0][-1]])
  601. for i in range(len(list_sentence)):
  602. PackageList_item = []
  603. PackageList_item_scope = []
  604. content = list_sentence[i].sentence_text
  605. tokens = list_sentence[i].tokens
  606. _names = []
  607. # 2021/6/23 包名称去重
  608. for name in package_names:
  609. if name not in _names:
  610. _names.append(name)
  611. # for name in package_names[:20]:
  612. for name in _names[:20]:
  613. for index in findAllIndex(name[0],content):
  614. temp_package_number = re.findall(number_pattern,name[1])[0]
  615. if re.search(re_digital,temp_package_number):
  616. temp_package_number = str(int(temp_package_number))
  617. PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,index),"offsetWord_begin":index,"offsetWord_end":index+len(name[0])})
  618. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,index),index,index+len(str(temp_package_number))])
  619. code = extractPackageCode(tokens, index)
  620. if code is not None:
  621. dict_packageCode[temp_package_number] = code
  622. PackageSet.add(temp_package_number)
  623. for iter in re.finditer(package_number_pattern,content):
  624. if re.match('\d', iter.group(0)) and iter.end()<len(content) and content[iter.end()].isdigit(): # 排除2.10标段3 这种情况
  625. continue
  626. temp_package_number = re.findall(number_pattern,content[iter.span()[0]:iter.span()[1]])[0]
  627. if re.search(re_digital, temp_package_number):
  628. temp_package_number = str(int(temp_package_number))
  629. PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  630. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  631. code = extractPackageCode(tokens, iter.span()[0])
  632. if code is not None:
  633. dict_packageCode[temp_package_number] = code
  634. PackageSet.add(temp_package_number)
  635. #识别packageScope
  636. for iter in re.finditer(pattern_packageScope,content):
  637. PackageList_item_scope.append({"name":"","sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  638. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  639. PackageList_item_scope = PackageList_item +PackageList_item_scope
  640. PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  641. PackageList_scope = PackageList_scope+PackageList_item_scope
  642. PackageList_item.sort(key=lambda x:x["sentence_index"])
  643. #PackageList = PackageList+PackageList_item
  644. #不作为包
  645. # if len(PackageSet)==0:
  646. # for i in range(len(list_sentence)):
  647. # PackageList_item = []
  648. # PackageList_item_scope = []
  649. # content = list_sentence[i].sentence_text
  650. # tokens = list_sentence[i].tokens
  651. # for iter in re.finditer(other_package_pattern,content):
  652. # temp_package_number = iter.group(2)
  653. # PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  654. # # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  655. # code = extractPackageCode(tokens, iter.span()[0])
  656. # if code is not None:
  657. # dict_packageCode[temp_package_number] = code
  658. # PackageSet.add(temp_package_number)
  659. # #识别packageScope
  660. # for iter in re.finditer(pattern_packageScope,content):
  661. # PackageList_item_scope.append({"name":"","sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  662. # # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  663. # PackageList_item_scope = PackageList_item +PackageList_item_scope
  664. # PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  665. # PackageList_scope = PackageList_scope+PackageList_item_scope
  666. # PackageList_item.sort(key=lambda x:x["sentence_index"])
  667. # 2020/11/23 大网站规则 调整
  668. if len(PackageSet)==0 and len(set([it.entity_text for it in list_entity if it.entity_type in ['org', 'company'] and it.label==2]))>1:
  669. for i in range(len(list_sentence)):
  670. PackageList_item = []
  671. PackageList_item_scope = []
  672. content = list_sentence[i].sentence_text
  673. tokens = list_sentence[i].tokens
  674. names = re.findall(other_package_pattern, content)
  675. N_names = re.findall(win_tenderer_pattern, content)
  676. if len(names) != 1 or len(N_names) != 1:
  677. continue
  678. for iter in re.finditer(other_package_pattern,content):
  679. temp_package_number = iter.group(4)
  680. xinghao = re.search(model_pattern, content)
  681. if xinghao:
  682. temp_package_number = temp_package_number + '+' + xinghao.group(2)
  683. # print('新正则采购包名补充',temp_package_number)
  684. if re.search(re_digital,temp_package_number):
  685. temp_package_number = str(int(temp_package_number))
  686. PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  687. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  688. code = extractPackageCode(tokens, iter.span()[0])
  689. if code is not None:
  690. dict_packageCode[temp_package_number] = code
  691. PackageSet.add(temp_package_number)
  692. #识别packageScope
  693. for iter in re.finditer(pattern_packageScope,content):
  694. PackageList_item_scope.append({"name":"","sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  695. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  696. PackageList_item_scope = PackageList_item +PackageList_item_scope
  697. PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  698. PackageList_scope = PackageList_scope+PackageList_item_scope
  699. PackageList_item.sort(key=lambda x:x["sentence_index"])
  700. pattern_punctuation = "[::()\(\),,。;;]"
  701. # print("===packageList_scope",PackageList_scope)
  702. for i in range(len(list_sentence)):
  703. for j in range(len(PackageList_scope)):
  704. if i==PackageList_scope[j]["sentence_index"] and PackageList_scope[j]["name"]!="":
  705. _flag = False
  706. left_str = list_sentence[i].sentence_text[PackageList_scope[j]["offsetWord_begin"]-30:PackageList_scope[j]["offsetWord_begin"]+1]
  707. right_str = list_sentence[i].sentence_text[PackageList_scope[j]["offsetWord_begin"]:PackageList_scope[j]["offsetWord_begin"]+30]
  708. _left_find = re.findall(pattern_punctuation,left_str)
  709. _right_find = re.findall(pattern_punctuation,right_str)
  710. #print(left_str)
  711. if re.search("同",left_str[-1:]) is not None and PackageList_scope[j]["name"]=="一":
  712. continue
  713. if re.search("划分",right_str[:10]) is not None:
  714. continue
  715. if len(_left_find)>0 and _left_find[-1] in [":",":"]:
  716. _flag = True
  717. if len(_right_find)>0 and _right_find[0] in [":",":"]:
  718. _flag = True
  719. if _flag:
  720. scope_begin = [PackageList_scope[j]["sentence_index"],PackageList_scope[j]["offsetWords_begin"]]
  721. else:
  722. if j==0:
  723. scope_begin = [0,0]
  724. else:
  725. scope_begin = [PackageList_scope[j-1]["sentence_index"],PackageList_scope[j-1]["offsetWords_begin"]]
  726. if j==len(PackageList_scope)-1:
  727. scope_end = [list_sentence[-1].sentence_index,changeIndexFromWordToWords(list_sentence[-1].tokens, len(list_sentence[-1].sentence_text))]
  728. else:
  729. scope_end = [PackageList_scope[j+1]["sentence_index"],PackageList_scope[j+1]["offsetWords_begin"]]
  730. if PackageList_scope[j-1]["sentence_index"]==PackageList_scope[j]["sentence_index"] and PackageList_scope[j-1]["offsetWord_begin"]<=PackageList_scope[j]["offsetWord_begin"] and PackageList_scope[j-1]["offsetWord_end"]>=PackageList_scope[j]["offsetWord_end"]:
  731. continue
  732. #add package to entity
  733. _pack_entity = Entity(doc_id=list_sentence[0].doc_id,entity_id="%s_%s_%s_%s"%(list_sentence[0].doc_id,i,PackageList_scope[j]["offsetWord_begin"],PackageList_scope[j]["offsetWord_begin"]),entity_text=PackageList_scope[j]["name"],entity_type="package",sentence_index=PackageList_scope[j]["sentence_index"],begin_index=changeIndexFromWordToWords(list_sentence[i].tokens,PackageList_scope[j]["offsetWord_begin"]),end_index=changeIndexFromWordToWords(list_sentence[i].tokens,PackageList_scope[j]["offsetWord_end"]),wordOffset_begin=PackageList_scope[j]["offsetWord_begin"],wordOffset_end=PackageList_scope[j]["offsetWord_end"],in_attachment=list_sentence[i].in_attachment)
  734. list_entity.append(_pack_entity)
  735. copy_pack = copy.copy(PackageList_scope[j])
  736. copy_pack["scope"] = [scope_begin,scope_end]
  737. copy_pack["hit"] = set()
  738. copy_pack["pointer"] = _pack_entity
  739. PackageList.append(copy_pack)
  740. return PackageList,PackageSet,dict_packageCode
  741. # km配对方法
  742. def dispatch(match_list):
  743. main_roles = list(set([match.main_role for match in match_list]))
  744. attributes = list(set([match.attribute for match in match_list]))
  745. label = np.zeros(shape=(len(main_roles), len(attributes)))
  746. for match in match_list:
  747. main_role = match.main_role
  748. attribute = match.attribute
  749. value = match.value
  750. label[main_roles.index(main_role), attributes.index(attribute)] = value + 10000
  751. # print(label)
  752. gragh = -label
  753. # km算法
  754. row, col = linear_sum_assignment(gragh)
  755. max_dispatch = [(i, j) for i, j, value in zip(row, col, gragh[row, col]) if value]
  756. # return [Match(main_roles[row], attributes[col]) for row, col in max_dispatch]
  757. return [(main_roles[row], attributes[col]) for row, col in max_dispatch]
  758. from BiddingKG.dl.common.Utils import getUnifyMoney
  759. from BiddingKG.dl.interface.modelFactory import Model_relation_extraction
  760. relationExtraction_model = Model_relation_extraction()
  761. def findAttributeAfterEntity(PackDict,roleSet,PackageList,PackageSet,list_sentence,list_entity,list_outline,on_value = 0.5,on_value_person=0.5,sentence_len=4):
  762. '''
  763. @param:
  764. PackDict:文章包dict
  765. roleSet:文章所有角色的公司名称
  766. PackageList:文章的包信息
  767. PackageSet:文章所有包的名称
  768. list_entity:文章所有经过模型处理的实体
  769. on_value:金额模型的阈值
  770. on_value_person:联系人模型的阈值
  771. sentence_len:公司和属性间隔句子的最大长度
  772. @return:添加了属性信息的角色list
  773. '''
  774. #根据roleid添加金额到rolelist中
  775. def addMoneyByRoleid(packDict,packageName,roleid,money,money_prob):
  776. for i in range(len(packDict[packageName]["roleList"])):
  777. if packDict[packageName]["roleList"][i].role_name==dict_role_id.get(str(roleid)):
  778. if money_prob>packDict[packageName]["roleList"][i].money_prob:
  779. packDict[packageName]["roleList"][i].money = money
  780. packDict[packageName]["roleList"][i].money_prob = money_prob
  781. return packDict
  782. #根据实体名称添加金额到rolelist中
  783. def addMoneyByEntity(packDict,packageName,entity,money,money_prob):
  784. for i in range(len(packDict[packageName]["roleList"])):
  785. if packDict[packageName]["roleList"][i].entity_text==entity:
  786. # if money_prob>packDict[packageName]["roleList"][i].money_prob:
  787. # packDict[packageName]["roleList"][i].money = money
  788. # packDict[packageName]["roleList"][i].money_prob = money_prob
  789. if packDict[packageName]["roleList"][i].money_prob==0 : # 2021/7/20第一次更新金额
  790. packDict[packageName]["roleList"][i].money = money.entity_text
  791. packDict[packageName]["roleList"][i].money_prob = money_prob
  792. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  793. elif money_prob>packDict[packageName]["roleList"][i].money_prob+0.2 or (money.notes in ['大写'] and money.in_attachment==False): # 2021/7/20改为优先选择大写金额,
  794. # print('已连接金额概率:money_prob:',packDict[packageName]["roleList"][i].money_prob)
  795. # print('链接金额备注 ',money.notes, money.entity_text, money.values)
  796. packDict[packageName]["roleList"][i].money = money.entity_text
  797. packDict[packageName]["roleList"][i].money_prob = money_prob
  798. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  799. # print('链接中的金额:{0}, 单位:{1}'.format(money.entity_text, money.money_unit))
  800. return packDict
  801. def addRatioByEntity(packDict,packageName,entity,ratio):
  802. for i in range(len(packDict[packageName]["roleList"])):
  803. if packDict[packageName]["roleList"][i].entity_text==entity:
  804. packDict[packageName]["roleList"][i].ratio = ratio.entity_text
  805. def addServiceTimeByEntity(packDict,packageName,entity,serviceTime):
  806. for i in range(len(packDict[packageName]["roleList"])):
  807. if packDict[packageName]["roleList"][i].entity_text==entity:
  808. packDict[packageName]["roleList"][i].serviceTime = serviceTime.entity_text
  809. #根据实体名称得到角色
  810. def getRoleWithText(packDict,entity_text):
  811. for pack in packDict.keys():
  812. for i in range(len(packDict[pack]["roleList"])):
  813. if packDict[pack]["roleList"][i].entity_text==entity_text:
  814. return packDict[pack]["roleList"][i].role_name
  815. def doesEntityOrLinkedEntity_inRoleSet(entity,RoleSet):
  816. _list_entitys = [entity]+entity.linked_entitys
  817. for _entity in _list_entitys:
  818. if _entity.entity_text in RoleSet:
  819. return True
  820. p_entity = 0
  821. # 2021/7/19 顺序比较金额,前面是后面的一万倍则把前面金额/10000
  822. money_list = [it for it in list_entity if it.entity_type=="money"]
  823. for i in range(len(money_list)-1):
  824. for j in range(1, len(money_list)):
  825. if (float(money_list[i].entity_text) > 5000000000 or money_list[j].notes=='大写') and \
  826. Decimal(money_list[i].entity_text)/Decimal(money_list[j].entity_text)==10000:
  827. money_list[i].entity_text = str(Decimal(money_list[i].entity_text)/10000)
  828. # print('连接前修改大于50亿金额:前面是后面的一万倍则把前面金额/10000')
  829. #遍历所有实体
  830. # while(p_entity<len(list_entity)):
  831. # entity = list_entity[p_entity]
  832. '''
  833. #招标金额从后往前找
  834. if entity.entity_type=="money":
  835. if entity.values[entity.label]>=on_value:
  836. if str(entity.label)=="0":
  837. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  838. if packagePointer is None:
  839. packageName = "Project"
  840. else:
  841. packageName = packagePointer.entity_text
  842. addMoneyByRoleid(PackDict, packageName, "0", entity.entity_text, entity.values[entity.label])
  843. '''
  844. ''' # 2020/11/25 与下面的联系人连接步骤重复,取消
  845. if entity.entity_type=="person":
  846. if entity.values[entity.label]>=on_value_person:
  847. if str(entity.label)=="1":
  848. for i in range(len(PackDict["Project"]["roleList"])):
  849. if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  850. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  851. # add pointer_person
  852. for _entity in list_entity:
  853. if dict_role_id.get(str(_entity.label))=="tenderee":
  854. for i in range(len(PackDict["Project"]["roleList"])):
  855. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  856. _entity.pointer_person = entity
  857. elif str(entity.label)=="2":
  858. for i in range(len(PackDict["Project"]["roleList"])):
  859. if PackDict["Project"]["roleList"][i].role_name=="agency":
  860. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  861. # add pointer_person
  862. for _entity in list_entity:
  863. if dict_role_id.get(str(_entity.label))=="agency":
  864. for i in range(len(PackDict["Project"]["roleList"])):
  865. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  866. _entity.pointer_person = entity
  867. '''
  868. # #金额往前找实体
  869. # if entity.entity_type=="money":
  870. # if entity.values[entity.label]>=on_value:
  871. # p_entity_money= p_entity
  872. # entity_money = list_entity[p_entity_money]
  873. # if len(PackageSet)>0:
  874. # packagePointer,_ = getPackage(PackageList,entity_money.sentence_index,entity_money.begin_index,"money-"+str(entity_money.entity_text)+"-"+str(entity_money.label))
  875. # if packagePointer is None:
  876. # packageName_entity = "Project"
  877. # else:
  878. # packageName_entity = packagePointer.entity_text
  879. # else:
  880. # packageName_entity = "Project"
  881. # while(p_entity_money>0):
  882. # entity_before = list_entity[p_entity_money]
  883. # if entity_before.entity_type in ['org','company']:
  884. # if str(entity_before.label)=="1":
  885. # addMoneyByEntity(PackDict, packageName_entity, entity_before.entity_text, entity_money.entity_text, entity_money.values[entity_money.label])
  886. # #add pointer_money
  887. # entity_before.pointer_money = entity_money
  888. # break
  889. # p_entity_money -= 1
  890. #如果实体属于角色集合,则往后找属性
  891. # if doesEntityOrLinkedEntity_inRoleSet(entity, roleSet):
  892. #
  893. # p_entity += 1
  894. # #循环查找符合的属性
  895. # while(p_entity<len(list_entity)):
  896. #
  897. # entity_after = list_entity[p_entity]
  898. # if entity_after.sentence_index-entity.sentence_index>=sentence_len:
  899. # p_entity -= 1
  900. # break
  901. # #若是遇到公司实体,则跳出循环
  902. # if entity_after.entity_type in ['org','company']:
  903. # p_entity -= 1
  904. # break
  905. # if entity_after.values is not None:
  906. # if entity_after.entity_type=="money":
  907. # if entity_after.values[entity_after.label]>=on_value:
  908. # '''
  909. # #招标金额从后往前找
  910. # if str(entity_after.label)=="0":
  911. # packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  912. # if packagePointer is None:
  913. # packageName = "Project"
  914. # else:
  915. # packageName = packagePointer.entity_text
  916. # addMoneyByRoleid(PackDict, packageName, "0", entity_after.entity_text, entity_after.values[entity_after.label])
  917. # '''
  918. # if str(entity_after.label)=="1":
  919. # #print(entity_after.entity_text,entity.entity_text)
  920. # _list_entitys = [entity]+entity.linked_entitys
  921. # if len(PackageSet)>0:
  922. # packagePointer,_ = getPackage(PackageList,entity_after.sentence_index,entity_after.begin_index,"money-"+str(entity_after.entity_text)+"-"+str(entity_after.label))
  923. # if packagePointer is None:
  924. # packageName_entity = "Project"
  925. # else:
  926. # packageName_entity = packagePointer.entity_text
  927. # else:
  928. # packageName_entity = "Project"
  929. # if str(entity.label) in ["2","3","4"]:
  930. # # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after.entity_text, entity_after.values[entity_after.label])
  931. # if entity_after.notes == '单价' or float(entity_after.entity_text)<5000: #2021/12/17 调整小金额阈值,避免203608823.html 两次金额一次万元没提取到的情况
  932. # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  933. # 0.5)
  934. # entity.pointer_money = entity_after
  935. # # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  936. # else:
  937. # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  938. # entity_after.values[entity_after.label])
  939. # entity.pointer_money = entity_after
  940. # # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  941. # if entity_after.values[entity_after.label]>0.6:
  942. # break # 2021/7/16 新增,找到中标金额,非单价即停止,不再往后找金额
  943. # #add pointer_money
  944. # # entity.pointer_money = entity_after
  945. # # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  946. # # if entity_after.notes!='单价':
  947. # # break # 2021/7/16 新增,找到中标金额即停止,不再往后找金额
  948. # '''
  949. # if entity_after.entity_type=="person":
  950. # if entity_after.values[entity_after.label]>=on_value_person:
  951. # if str(entity_after.label)=="1":
  952. # for i in range(len(roleList)):
  953. # if roleList[i].role_name=="tenderee":
  954. # roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  955. # elif str(entity_after.label)=="2":
  956. # for i in range(len(roleList)):
  957. # if roleList[i].role_name=="agency":
  958. # roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  959. # elif str(entity_after.label)=="3":
  960. # _list_entitys = [entity]+entity.linked_entitys
  961. # for _entity in _list_entitys:
  962. # for i in range(len(roleList)):
  963. # if roleList[i].entity_text==_entity.entity_text:
  964. # if entity_after.sentence_index-_entity.sentence_index>1 and len(roleList[i].linklist)>0:
  965. # break
  966. # roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  967. # '''
  968. #
  969. # p_entity += 1
  970. #
  971. # p_entity += 1
  972. # 记录每句的分词数量
  973. tokens_num_dict = dict()
  974. last_tokens_num = 0
  975. for sentence in list_sentence:
  976. _index = sentence.sentence_index
  977. if _index == 0:
  978. tokens_num_dict[_index] = 0
  979. else:
  980. tokens_num_dict[_index] = tokens_num_dict[_index - 1] + last_tokens_num
  981. last_tokens_num = len(sentence.tokens)
  982. attribute_type = ['money','serviceTime','ratio']# 'money'仅指“中投标金额”
  983. for link_attribute in attribute_type:
  984. temp_entity_list = []
  985. if link_attribute=="money":
  986. temp_entity_list = [ent for ent in list_entity if (ent.entity_type in ['org','company'] and ent.label in [2,3,4]) or
  987. (ent.entity_type=='money' and ent.label==1 and ent.values[ent.label]>=0.5)]
  988. # 删除重复的‘中投标金额’,一般为大小写两种样式
  989. drop_tendererMoney = []
  990. for ent_idx in range(len(temp_entity_list)-1):
  991. entity = temp_entity_list[ent_idx]
  992. if entity.entity_type=='money':
  993. next_entity = temp_entity_list[ent_idx+1]
  994. if next_entity.entity_type=='money':
  995. if getUnifyMoney(entity.entity_text)==getUnifyMoney(next_entity.entity_text):
  996. if (tokens_num_dict[next_entity.sentence_index] + next_entity.begin_index) - (
  997. tokens_num_dict[entity.sentence_index] + entity.end_index) < 10:
  998. drop_tendererMoney.append(next_entity)
  999. for _drop in drop_tendererMoney:
  1000. temp_entity_list.remove(_drop)
  1001. elif link_attribute=="serviceTime":
  1002. temp_entity_list = [ent for ent in list_entity if (ent.entity_type in ['org','company'] and ent.label in [2,3,4]) or
  1003. ent.entity_type=='serviceTime']
  1004. elif link_attribute=="ratio":
  1005. temp_entity_list = [ent for ent in list_entity if (ent.entity_type in ['org','company'] and ent.label in [2,3,4]) or
  1006. ent.entity_type=='ratio']
  1007. temp_entity_list = sorted(temp_entity_list,key=lambda x: (x.sentence_index, x.begin_index))
  1008. temp_match_list = []
  1009. for ent_idx in range(len(temp_entity_list)):
  1010. entity = temp_entity_list[ent_idx]
  1011. if entity.entity_type in ['org','company']:
  1012. match_nums = 0
  1013. tenderer_nums = 0 #经过其他中投标人的数量
  1014. byNotTenderer_match_nums = 0 #跟在中投标人后面的属性
  1015. for after_index in range(ent_idx + 1, min(len(temp_entity_list), ent_idx + 4)):
  1016. after_entity = temp_entity_list[after_index]
  1017. if after_entity.entity_type == link_attribute:
  1018. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1019. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1020. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1021. value = (-1 / 2 * (distance ** 2)) / 10000
  1022. if link_attribute == "money":
  1023. if after_entity.notes == '单价':
  1024. value = value * 100
  1025. if sentence_distance == 0:
  1026. if distance < 100:
  1027. # value = (-1 / 2 * (distance ** 2)) / 10000
  1028. temp_match_list.append(Match(entity, after_entity, value))
  1029. match_nums += 1
  1030. if not tenderer_nums:
  1031. byNotTenderer_match_nums += 1
  1032. else:
  1033. break
  1034. else:
  1035. if distance < 60:
  1036. # value = (-1 / 2 * (distance ** 2)) / 10000
  1037. temp_match_list.append(Match(entity, after_entity, value))
  1038. match_nums += 1
  1039. if not tenderer_nums:
  1040. byNotTenderer_match_nums += 1
  1041. else:
  1042. break
  1043. else:
  1044. tenderer_nums += 1
  1045. #前向查找属性
  1046. if ent_idx!=0 and (not match_nums or not byNotTenderer_match_nums):
  1047. previous_entity = temp_entity_list[ent_idx - 1]
  1048. if previous_entity.entity_type == link_attribute:
  1049. # if previous_entity.sentence_index == entity.sentence_index:
  1050. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1051. tokens_num_dict[previous_entity.sentence_index] + previous_entity.end_index)
  1052. if distance < 40:
  1053. # 前向 没有 /10000
  1054. value = (-1 / 2 * (distance ** 2))
  1055. temp_match_list.append(Match(entity, previous_entity, value))
  1056. # km算法分配求解
  1057. dispatch_result = dispatch(temp_match_list)
  1058. dispatch_result = sorted(dispatch_result, key=lambda x: (x[0].sentence_index,x[0].begin_index))
  1059. for match in dispatch_result:
  1060. _entity = match[0]
  1061. _attribute = match[1]
  1062. if link_attribute=='money':
  1063. _entity.pointer_money = _attribute
  1064. packagePointer, _ = getPackage(PackageList, _attribute.sentence_index, _attribute.begin_index,
  1065. "money-" + str(_attribute.entity_text) + "-" + str(_attribute.label))
  1066. # print(_entity.entity_text,_attribute.entity_text)
  1067. if packagePointer is None:
  1068. packageName_entity = "Project"
  1069. else:
  1070. packageName_entity = packagePointer.entity_text
  1071. if _attribute.notes == '单价' or float(_attribute.entity_text) < 5000: # 2021/12/17 调整小金额阈值,避免203608823.html 两次金额一次万元没提取到的情况
  1072. # print(packageName_entity,_attribute.entity_text, _attribute.values[_attribute.label])
  1073. addMoneyByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute,0.5)
  1074. else:
  1075. # print(packageName_entity,_attribute.entity_text, _attribute.values[_attribute.label])
  1076. addMoneyByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute,
  1077. _attribute.values[_attribute.label])
  1078. elif link_attribute=='serviceTime':
  1079. _entity.pointer_serviceTime = _attribute
  1080. packagePointer, _ = getPackage(PackageList, _attribute.sentence_index, _attribute.begin_index,
  1081. "serviceTime-" + str(_attribute.entity_text) + "-" + str(_attribute.label))
  1082. if packagePointer is None:
  1083. packageName_entity = "Project"
  1084. else:
  1085. packageName_entity = packagePointer.entity_text
  1086. addServiceTimeByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute)
  1087. elif link_attribute=='ratio':
  1088. _entity.pointer_ratio = _attribute
  1089. packagePointer, _ = getPackage(PackageList, _attribute.sentence_index, _attribute.begin_index,
  1090. "ratio-" + str(_attribute.entity_text) + "-" + str(_attribute.label))
  1091. if packagePointer is None:
  1092. packageName_entity = "Project"
  1093. else:
  1094. packageName_entity = packagePointer.entity_text
  1095. addRatioByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute)
  1096. ''''''
  1097. # 通过模型分类的招标/代理联系人
  1098. list_sentence = sorted(list_sentence, key=lambda x: x.sentence_index)
  1099. person_list = [entity for entity in list_entity if entity.entity_type == 'person' and entity.label in [1, 2]]
  1100. tenderee_contact = set()
  1101. tenderee_phone = set()
  1102. agency_contact = set()
  1103. agency_phone = set()
  1104. winter_contact = set()
  1105. for _person in person_list:
  1106. if _person.label == 1:
  1107. tenderee_contact.add(_person.entity_text)
  1108. if _person.label == 2:
  1109. agency_contact.add(_person.entity_text)
  1110. # 正则匹配无 '主体/联系人' 的电话
  1111. # 例:"采购人联系方式:0833-5226788,"
  1112. phone_pattern = '(1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|' \
  1113. '\+86.?1[3-9]\d{9}|' \
  1114. '0[1-9]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|' \
  1115. '0[1-9]\d{1,2}[-—-―]\d{7,8}.?转\d{1,4}|' \
  1116. '0[1-9]\d{1,2}[-—-―]\d{7,8}[-—-―]\d{1,4}|' \
  1117. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3-9]\d{9})|' \
  1118. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|' \
  1119. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|' \
  1120. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?|' \
  1121. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|' \
  1122. '[2-9]\d{6,7})'
  1123. re_tenderee_phone = re.compile(
  1124. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,5}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,7}?)"
  1125. # 电话号码
  1126. + phone_pattern)
  1127. # 例:"采购人地址和联系方式:峨边彝族自治县教育局,0833-5226788,"
  1128. re_tenderee_phone2 = re.compile(
  1129. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,20}?)"
  1130. # 电话号码
  1131. + phone_pattern)
  1132. re_agent_phone = re.compile(
  1133. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,5}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,7}?)"
  1134. # 电话号码
  1135. + phone_pattern)
  1136. re_agent_phone2 = re.compile(
  1137. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,20}?)"
  1138. # 电话号码
  1139. + phone_pattern)
  1140. content = ""
  1141. for _sentence in list_sentence:
  1142. content += "".join(_sentence.tokens)
  1143. _content = copy.deepcopy(content)
  1144. while re.search("(.)(,)([^0-9])|([^0-9])(,)(.)", content):
  1145. content_words = list(content)
  1146. for i in re.finditer("(.)(,)([^0-9])", content):
  1147. content_words[i.span(2)[0]] = ""
  1148. for i in re.finditer("([^0-9])(,)(.)", content):
  1149. content_words[i.span(2)[0]] = ""
  1150. content = "".join(content_words)
  1151. content = re.sub("[::]|[\((]|[\))]", "", content)
  1152. _tenderee_phone = re.findall(re_tenderee_phone, content)
  1153. # 更新正则确定的角色属性
  1154. for i in range(len(PackDict["Project"]["roleList"])):
  1155. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  1156. _tenderee_phone = re.findall(re_tenderee_phone, content)
  1157. if _tenderee_phone:
  1158. for _phone in _tenderee_phone:
  1159. _phone = _phone.split("/") # 分割多个号码
  1160. for one_phone in _phone:
  1161. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1162. tenderee_phone.add(one_phone)
  1163. _tenderee_phone2 = re.findall(re_tenderee_phone2, content)
  1164. if _tenderee_phone2:
  1165. for _phone in _tenderee_phone2:
  1166. _phone = _phone.split("/")
  1167. for one_phone in _phone:
  1168. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1169. tenderee_phone.add(one_phone)
  1170. if PackDict["Project"]["roleList"][i].role_name == "agency":
  1171. _agent_phone = re.findall(re_agent_phone, content)
  1172. if _agent_phone:
  1173. for _phone in _agent_phone:
  1174. _phone = _phone.split("/")
  1175. for one_phone in _phone:
  1176. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1177. agency_phone.add(one_phone)
  1178. _agent_phone2 = re.findall(re_agent_phone2, content)
  1179. if _agent_phone2:
  1180. for _phone in _agent_phone2:
  1181. _phone = _phone.split("/")
  1182. for one_phone in _phone:
  1183. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1184. agency_phone.add(one_phone)
  1185. # 正则提取电话号码实体
  1186. # key_word = re.compile('((?:电话|联系方式|联系人).{0,4}?)([0-1]\d{6,11})')
  1187. phone = re.compile('1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1188. '\+86.?1[3-9]\d{9}|'
  1189. # '0[^0]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1190. '0[1-9]\d{1,2}[-—-―]\d{7,8}.?转\d{1,4}|'
  1191. '0[1-9]\d{1,2}[-—-―]\d{7,8}[-—-―]\d{1,4}|'
  1192. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3-9]\d{9})|'
  1193. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|'
  1194. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|'
  1195. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?|'
  1196. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1197. '[2-9]\d{6,7}')
  1198. url_pattern = re.compile("http[s]?://(?:[a-zA-Z]|[0-9]|[$\-_@.&+=\?:/]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+")
  1199. email_pattern = re.compile("[a-zA-Z0-9][a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*@"
  1200. "[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*(?:\.[a-zA-Z]{2,})")
  1201. phone_entitys = []
  1202. code_entitys = [ent for ent in list_entity if ent.entity_type=='code']
  1203. for _sentence in list_sentence:
  1204. sentence_text = _sentence.sentence_text
  1205. in_attachment = _sentence.in_attachment
  1206. list_tokenbegin = []
  1207. begin = 0
  1208. for i in range(0, len(_sentence.tokens)):
  1209. list_tokenbegin.append(begin)
  1210. begin += len(str(_sentence.tokens[i]))
  1211. list_tokenbegin.append(begin + 1)
  1212. # 排除网址、邮箱、项目编号实体
  1213. error_list = []
  1214. for i in re.finditer(url_pattern, sentence_text):
  1215. error_list.append((i.start(), i.end()))
  1216. for i in re.finditer(email_pattern, sentence_text):
  1217. error_list.append((i.start(), i.end()))
  1218. for code_ent in [ent for ent in code_entitys if ent.sentence_index==_sentence.sentence_index]:
  1219. error_list.append((code_ent.wordOffset_begin,code_ent.wordOffset_end))
  1220. res_set = set()
  1221. for i in re.finditer(phone, sentence_text):
  1222. is_continue = False
  1223. for error_ent in error_list:
  1224. if i.start()>=error_ent[0] and i.end()<=error_ent[1]:
  1225. is_continue = True
  1226. break
  1227. if is_continue:
  1228. continue
  1229. res_set.add((i.group(), i.start(), i.end()))
  1230. res_set = sorted(list(res_set),key=lambda x:x[1])
  1231. last_phone_mask = True
  1232. error_numStr_index = []
  1233. sentence_phone_list = []
  1234. for item_idx in range(len(res_set)):
  1235. item = res_set[item_idx]
  1236. phone_left = sentence_text[max(0, item[1] - 10):item[1]]
  1237. phone_right = sentence_text[item[2]:item[2] + 10]
  1238. phone_left_num = re.search("[\da-zA-Z\-—-―]+$",phone_left)
  1239. numStr_left = item[1]
  1240. if phone_left_num:
  1241. numStr_left -= len(phone_left_num.group())
  1242. phone_right_num = re.search("^[\da-zA-Z\-—-―]+",phone_right)
  1243. numStr_right = item[2]
  1244. if phone_right_num:
  1245. numStr_right += len(phone_right_num.group())
  1246. numStr_index = (numStr_left,numStr_right)
  1247. if re.search("电话|手机|联系[人方]|联系方式",re.sub(",","",phone_left)):
  1248. pass
  1249. else:
  1250. # 排除“传真号”和其它错误项
  1251. if re.search("传,?真|信,?箱|邮,?[箱件]|QQ|qq", phone_left):
  1252. if not re.search("电,?话", phone_left):
  1253. error_numStr_index.append(numStr_index)
  1254. last_phone_mask = False
  1255. continue
  1256. if re.search("身份证号?码?|注册[证号]|帐号|编[号码]|报价|标价|证号|价格|型号|附件|代码|列号|行号|税号|[\(\(]万?元[\)\)]|[a-zA-Z]+\d*$", re.sub(",","",phone_left)):
  1257. error_numStr_index.append(numStr_index)
  1258. last_phone_mask = False
  1259. continue
  1260. if re.search("^\d{0,4}[.,]\d{2,}|^[0-9a-zA-Z\.]*@|^\d*[a-zA-Z]+|元", phone_right):
  1261. error_numStr_index.append(numStr_index)
  1262. last_phone_mask = False
  1263. continue
  1264. # 号码含有0过多,不符合规则
  1265. if re.search("0{6,}",item[0]):
  1266. error_numStr_index.append(numStr_index)
  1267. last_phone_mask = False
  1268. continue
  1269. # 前后跟着字母
  1270. if re.search("[a-zA-Z/]+$", phone_left) or re.search("^[a-zA-Z/]+", phone_right):
  1271. error_numStr_index.append(numStr_index)
  1272. last_phone_mask = False
  1273. continue
  1274. # 时间日期类排除
  1275. if re.search("时间|日期", phone_left):
  1276. error_numStr_index.append(numStr_index)
  1277. last_phone_mask = False
  1278. continue
  1279. # 前后跟着长度小于一定值数字的正则排除
  1280. if re.search("\d+[-—-―]?\d*$",phone_left) or re.search("^\d+[-—-―]?\d*",phone_right):
  1281. phone_left_number = re.search("\d+[-—-―]?\d*$",phone_left)
  1282. phone_right_number = re.search("^\d+[-—-―]?\d+",phone_right)
  1283. if phone_left_number:
  1284. if len(phone_left_number.group())<7:
  1285. error_numStr_index.append(numStr_index)
  1286. last_phone_mask = False
  1287. continue
  1288. if phone_right_number:
  1289. if len(phone_right_number.group())<7:
  1290. error_numStr_index.append(numStr_index)
  1291. last_phone_mask = False
  1292. continue
  1293. # if:上一个phone实体不符合条件
  1294. if not last_phone_mask:
  1295. item_start = item[1]
  1296. last_item_end = res_set[item_idx-1][2]
  1297. if item_start - last_item_end<=1 or re.search("^[\da-zA-Z\-—-―、]+$",sentence_text[last_item_end:item_start]):
  1298. error_numStr_index.append(numStr_index)
  1299. last_phone_mask = False
  1300. continue
  1301. sentence_phone_list.append(item)
  1302. last_phone_mask = True
  1303. if error_numStr_index:
  1304. drop_list = []
  1305. for item in sentence_phone_list:
  1306. for err_index in error_numStr_index:
  1307. if (item[1]>=err_index[0] and item[1]<=err_index[1]) or (item[2]>=err_index[0] and item[2]<=err_index[1]) or (item[1]<=err_index[0] and item[2]>=err_index[1]):
  1308. drop_list.append(item)
  1309. break
  1310. for _drop_item in drop_list:
  1311. sentence_phone_list.remove(_drop_item)
  1312. for item in sentence_phone_list:
  1313. for j in range(len(list_tokenbegin)):
  1314. if list_tokenbegin[j] == item[1]:
  1315. begin_index = j
  1316. break
  1317. elif list_tokenbegin[j] > item[1]:
  1318. begin_index = j - 1
  1319. break
  1320. for j in range(begin_index, len(list_tokenbegin)):
  1321. if list_tokenbegin[j] >= item[2]:
  1322. end_index = j - 1
  1323. break
  1324. _entity = Entity(_sentence.doc_id, None, item[0], "phone", _sentence.sentence_index, begin_index, end_index, item[1],
  1325. item[2],in_attachment=in_attachment)
  1326. phone_entitys.append(_entity)
  1327. # print('phone_set:',set([ent.entity_text for ent in phone_entitys]))
  1328. def is_company(entity,text):
  1329. # 判断"公司"实体是否为地址地点
  1330. if entity.label!=5 and entity.values[entity.label]>0.5:
  1331. return True
  1332. if ent.is_tail==True:
  1333. return False
  1334. entity_left = text[max(0,entity.wordOffset_begin-10):entity.wordOffset_begin]
  1335. entity_left = re.sub(",()\(\)","",entity_left)
  1336. entity_left = entity_left[-5:]
  1337. if re.search("地址|地点|银行[::]",entity_left):
  1338. return False
  1339. else:
  1340. return True
  1341. pre_entity = []
  1342. for ent in list_entity:
  1343. if (ent.entity_type in ['company','org','phone'] and is_company(ent,list_sentence[ent.sentence_index].sentence_text)) or (ent.entity_type=='person' and ent.label in [1,2,3]) \
  1344. or (ent.entity_type=='location' and len(ent.entity_text)>5):
  1345. pre_entity.append(ent)
  1346. text_data,pre_data = relationExtraction_model.encode(pre_entity + phone_entitys, list_sentence)
  1347. # print(pre_data)
  1348. maxlen = 512
  1349. relation_list = []
  1350. if 0<len(text_data)<=maxlen:
  1351. relation_list = relationExtraction_model.predict(text_data, pre_data)
  1352. else:
  1353. # 公告大于maxlen时,分段预测
  1354. start = 0
  1355. # print("len(pre_data)",len(pre_data))
  1356. temp_data = []
  1357. deal_data = 0
  1358. while start<len(pre_data):
  1359. _pre_data = pre_data[start:start+maxlen]
  1360. _text_data = text_data[start:start+maxlen]
  1361. if relationExtraction_model.check_data(_pre_data):
  1362. temp_data.append((_text_data,_pre_data))
  1363. else:
  1364. if temp_data:
  1365. deal_data += len(temp_data)
  1366. if deal_data>4:
  1367. break
  1368. for _text_data, _pre_data in temp_data:
  1369. relation_list.extend(relationExtraction_model.predict(_text_data,_pre_data))
  1370. temp_data = []
  1371. start = start + maxlen - 120
  1372. if temp_data:
  1373. deal_data += len(temp_data)
  1374. if deal_data <= 4:
  1375. for _text_data, _pre_data in temp_data:
  1376. relation_list.extend(relationExtraction_model.predict(_text_data, _pre_data))
  1377. # print("预测数据:",len(temp_data))
  1378. # 去重结果
  1379. relation_list = list(set(relation_list))
  1380. # print(relation_list)
  1381. right_combination = [('org','person'),('company','person'),('company','location'),('org','location'),('person','phone')]
  1382. linked_company = set()
  1383. linked_person = set()
  1384. linked_connetPerson = set()
  1385. linked_phone = set()
  1386. for predicate in ["rel_address","rel_phone","rel_person"]:
  1387. _match_list = []
  1388. _match_combo = []
  1389. for relation in relation_list:
  1390. _subject = relation[0]
  1391. _object = relation[2]
  1392. if isinstance(_subject,Entity) and isinstance(_object,Entity) and (_subject.entity_type,_object.entity_type) in right_combination:
  1393. if relation[1]==predicate:
  1394. if predicate=="rel_person":
  1395. if (_subject.label==0 and _object.entity_text in agency_contact ) or (_subject.label==1 and _object.entity_text in tenderee_contact):
  1396. continue
  1397. # 角色为中标候选人,排除"质疑|投诉|监督|受理"相关的联系人
  1398. if _subject.label in [2,3,4] and re.search("质疑|投诉|监督|受理",list_sentence[_object.sentence_index].sentence_text[max(0,_object.wordOffset_begin-10):_object.wordOffset_begin]):
  1399. continue
  1400. distance = (tokens_num_dict[_object.sentence_index] + _object.begin_index) - (
  1401. tokens_num_dict[_subject.sentence_index] + _subject.end_index)
  1402. if distance>0:
  1403. value = (-1 / 2 * (distance ** 2))/10000
  1404. else:
  1405. distance = abs(distance)
  1406. value = (-1 / 2 * (distance ** 2))
  1407. _match_list.append(Match(_subject,_object,value))
  1408. _match_combo.append((_subject,_object))
  1409. match_result = dispatch(_match_list)
  1410. error_list = []
  1411. for mat in list(set(_match_combo)-set(match_result)):
  1412. for temp in match_result:
  1413. if mat[1]==temp[1] and mat[0]!=temp[0]:
  1414. error_list.append(mat)
  1415. break
  1416. result = list(set(_match_combo)-set(error_list))
  1417. if predicate=='rel_person':
  1418. # 从后往前更新状态,已近后向链接的属性不在前向链接(解决错误链接)
  1419. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1420. for combo in result:
  1421. is_continue = False
  1422. if not combo[0].pointer_person:
  1423. combo[0].pointer_person = []
  1424. if combo[1].begin_index<combo[0].begin_index:
  1425. if combo[0].pointer_person:
  1426. for temp in combo[0].pointer_person:
  1427. if temp.begin_index>combo[0].begin_index:
  1428. is_continue = True
  1429. break
  1430. if is_continue:
  1431. continue
  1432. combo[0].pointer_person.append(combo[1])
  1433. linked_company.add(combo[0])
  1434. linked_person.add(combo[1])
  1435. # print(1,combo[0].entity_text,combo[1].entity_text)
  1436. if predicate=='rel_address':
  1437. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1438. for combo in result:
  1439. if combo[0].pointer_address:
  1440. continue
  1441. combo[0].pointer_address = combo[1]
  1442. # print(2,combo[0].entity_text,combo[1].entity_text)
  1443. if predicate=='rel_phone':
  1444. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1445. for combo in result:
  1446. is_continue = False
  1447. if not combo[0].person_phone:
  1448. combo[0].person_phone = []
  1449. if combo[1].begin_index<combo[0].begin_index:
  1450. if combo[0].person_phone:
  1451. for temp in combo[0].person_phone:
  1452. if temp.begin_index>combo[0].begin_index:
  1453. is_continue = True
  1454. break
  1455. if is_continue: continue
  1456. combo[0].person_phone.append(combo[1])
  1457. linked_connetPerson.add(combo[0])
  1458. linked_phone.add(combo[1])
  1459. if combo[0].label in [1,2]:
  1460. if PackDict.get("Project"):
  1461. for i in range(len(PackDict["Project"]["roleList"])):
  1462. if (combo[0].label==1 and PackDict["Project"]["roleList"][i].role_name=='tenderee') \
  1463. or (combo[0].label==2 and PackDict["Project"]["roleList"][i].role_name=='agency'):
  1464. PackDict["Project"]["roleList"][i].linklist.append((combo[0].entity_text,combo[1].entity_text))
  1465. break
  1466. # print(3,combo[0].entity_text,combo[1].entity_text)
  1467. # "公司——地址" 链接规则补充
  1468. company_lacation_EntityList = [ent for ent in pre_entity if ent.entity_type in ['company', 'org', 'location']]
  1469. company_lacation_EntityList = sorted(company_lacation_EntityList, key=lambda x: (x.sentence_index, x.begin_index))
  1470. t_match_list = []
  1471. for ent_idx in range(len(company_lacation_EntityList)):
  1472. entity = company_lacation_EntityList[ent_idx]
  1473. if entity.entity_type in ['company', 'org']:
  1474. match_nums = 0
  1475. company_nums = 0 # 经过其他公司的数量
  1476. location_nums = 0 # 经过电话的数量
  1477. for after_index in range(ent_idx + 1, min(len(company_lacation_EntityList), ent_idx + 5)):
  1478. after_entity = company_lacation_EntityList[after_index]
  1479. if after_entity.entity_type == "location":
  1480. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1481. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1482. location_nums += 1
  1483. if distance > 100 or location_nums >= 3:
  1484. break
  1485. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1486. value = (-1 / 2 * (distance ** 2)) / 10000
  1487. if sentence_distance == 0:
  1488. if distance < 80:
  1489. t_match_list.append(Match(entity, after_entity, value))
  1490. match_nums += 1
  1491. if company_nums:
  1492. break
  1493. else:
  1494. if distance < 50:
  1495. t_match_list.append(Match(entity, after_entity, value))
  1496. match_nums += 1
  1497. if company_nums:
  1498. break
  1499. else:
  1500. # type:company/org
  1501. company_nums += 1
  1502. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  1503. break
  1504. # km算法分配求解
  1505. relate_location_result = dispatch(t_match_list)
  1506. relate_location_result = sorted(relate_location_result, key=lambda x: (x[0].sentence_index, x[0].begin_index))
  1507. for match in relate_location_result:
  1508. _company = match[0]
  1509. _relation = match[1]
  1510. if not _company.pointer_address:
  1511. _company.pointer_address = _relation
  1512. # "联系人——联系电话" 链接规则补充
  1513. person_phone_EntityList = [ent for ent in pre_entity+ phone_entitys if ent.entity_type not in ['company','org','location']]
  1514. person_phone_EntityList = sorted(person_phone_EntityList, key=lambda x: (x.sentence_index, x.begin_index))
  1515. t_match_list = []
  1516. for ent_idx in range(len(person_phone_EntityList)):
  1517. entity = person_phone_EntityList[ent_idx]
  1518. if entity.entity_type=="person":
  1519. match_nums = 0
  1520. person_nums = 0 # 经过其他中联系人的数量
  1521. byNotPerson_match_nums = 0 # 跟在联系人后面的属性
  1522. phone_nums = 0 # 经过电话的数量
  1523. for after_index in range(ent_idx + 1, min(len(person_phone_EntityList), ent_idx + 8)):
  1524. after_entity = person_phone_EntityList[after_index]
  1525. if after_entity.entity_type == "phone":
  1526. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1527. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1528. phone_nums += 1
  1529. if distance>100 or phone_nums>=4:
  1530. break
  1531. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1532. value = (-1 / 2 * (distance ** 2)) / 10000
  1533. if sentence_distance == 0:
  1534. if distance < 80:
  1535. # value = (-1 / 2 * (distance ** 2)) / 10000
  1536. t_match_list.append(Match(entity, after_entity, value))
  1537. match_nums += 1
  1538. if not person_nums:
  1539. byNotPerson_match_nums += 1
  1540. else:
  1541. break
  1542. else:
  1543. if distance < 50:
  1544. # value = (-1 / 2 * (distance ** 2)) / 10000
  1545. t_match_list.append(Match(entity, after_entity, value))
  1546. match_nums += 1
  1547. if not person_nums:
  1548. byNotPerson_match_nums += 1
  1549. else:
  1550. break
  1551. else:
  1552. person_nums += 1
  1553. # 前向查找属性
  1554. if ent_idx != 0 and (not match_nums or not byNotPerson_match_nums):
  1555. previous_entity = person_phone_EntityList[ent_idx - 1]
  1556. if previous_entity.entity_type == 'phone':
  1557. # if previous_entity.sentence_index == entity.sentence_index:
  1558. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1559. tokens_num_dict[previous_entity.sentence_index] + previous_entity.end_index)
  1560. if distance < 40:
  1561. # 前向 没有 /10000
  1562. value = (-1 / 2 * (distance ** 2))
  1563. t_match_list.append(Match(entity, previous_entity, value))
  1564. # km算法分配求解(person-phone)
  1565. t_match_list = [mat for mat in t_match_list if mat.main_role not in linked_connetPerson and mat.attribute not in linked_phone]
  1566. personphone_result = dispatch(t_match_list)
  1567. personphone_result = sorted(personphone_result, key=lambda x: (x[0].sentence_index, x[0].begin_index))
  1568. for match in personphone_result:
  1569. _person = match[0]
  1570. _phone = match[1]
  1571. if not _person.person_phone:
  1572. _person.person_phone = []
  1573. _person.person_phone.append(_phone)
  1574. # 多个招标人/代理人或者别称
  1575. for idx in range(1,len(pre_entity)):
  1576. _pre_entity = pre_entity[idx]
  1577. if _pre_entity in linked_company and _pre_entity.label==5:
  1578. last_ent = pre_entity[idx-1]
  1579. if last_ent.entity_type in ['company','org'] and last_ent.label in [0,1]:
  1580. if last_ent.sentence_index==_pre_entity.sentence_index:
  1581. mid_text = list_sentence[_pre_entity.sentence_index].sentence_text[last_ent.wordOffset_end:_pre_entity.wordOffset_begin]
  1582. if len(mid_text)<=20 and "," not in mid_text and re.search("[、\((]",mid_text):
  1583. _pre_entity.label = last_ent.label
  1584. _pre_entity.values[last_ent.label] = 0.6
  1585. # 2022/01/25 固定电话可连多个联系人
  1586. temp_person_entitys = [entity for entity in pre_entity if entity.entity_type == 'person']
  1587. temp_person_entitys2 = [] #和固定电话相连的联系人
  1588. for entity in temp_person_entitys:
  1589. if entity.person_phone:
  1590. for _phone in entity.person_phone:
  1591. if not re.search("^1[3-9]\d{9}$", _phone.entity_text):
  1592. temp_person_entitys2.append(entity)
  1593. break
  1594. for index in range(len(temp_person_entitys)):
  1595. entity = temp_person_entitys[index]
  1596. if entity in temp_person_entitys2:
  1597. last_person = entity
  1598. for after_index in range(index + 1, min(len(temp_person_entitys), index + 5)):
  1599. after_entity = temp_person_entitys[after_index]
  1600. if after_entity.sentence_index == last_person.sentence_index and after_entity.begin_index - last_person.end_index < 3:
  1601. for _phone in entity.person_phone:
  1602. if not re.search("^1[3-9]\d{9}$", _phone.entity_text):
  1603. if _phone not in after_entity.person_phone:
  1604. after_entity.person_phone.append(_phone)
  1605. last_person = after_entity
  1606. else:
  1607. break
  1608. if index==0:
  1609. continue
  1610. last_person = entity
  1611. for before_index in range(index-1, max(-1,index-5), -1):
  1612. before_entity = temp_person_entitys[before_index]
  1613. if before_entity.sentence_index == last_person.sentence_index and last_person.begin_index - before_entity.end_index < 3:
  1614. for _phone in entity.person_phone:
  1615. if not re.search("^1[3-9]\d{9}$", _phone.entity_text):
  1616. if _phone not in before_entity.person_phone:
  1617. before_entity.person_phone.append(_phone)
  1618. last_person = before_entity
  1619. else:
  1620. break
  1621. # 更新person为招标/代理联系人的联系方式
  1622. for k in PackDict.keys():
  1623. for i in range(len(PackDict[k]["roleList"])):
  1624. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1625. for _person in person_list:
  1626. if _person.label==1:#招标联系人
  1627. person_phone = [phone for phone in _person.person_phone] if _person.person_phone else []
  1628. for _p in person_phone:
  1629. PackDict[k]["roleList"][i].linklist.append((_person.entity_text, _p.entity_text))
  1630. if not person_phone:
  1631. PackDict[k]["roleList"][i].linklist.append((_person.entity_text,""))
  1632. if PackDict[k]["roleList"][i].role_name == "agency":
  1633. for _person in person_list:
  1634. if _person.label==2:#代理联系人
  1635. person_phone = [phone for phone in _person.person_phone] if _person.person_phone else []
  1636. for _p in person_phone:
  1637. PackDict[k]["roleList"][i].linklist.append((_person.entity_text, _p.entity_text))
  1638. if not person_phone:
  1639. PackDict[k]["roleList"][i].linklist.append((_person.entity_text,""))
  1640. # 更新 PackDict
  1641. not_sure_linked = []
  1642. for link_p in list(linked_company):
  1643. for k in PackDict.keys():
  1644. for i in range(len(PackDict[k]["roleList"])):
  1645. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1646. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 0:
  1647. not_sure_linked.append(link_p)
  1648. continue
  1649. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1650. for per in link_p.pointer_person:
  1651. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1652. if not person_phone:
  1653. if per.entity_text not in agency_contact:
  1654. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1655. continue
  1656. for _p in person_phone:
  1657. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1658. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1659. elif PackDict[k]["roleList"][i].role_name == "agency":
  1660. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 1:
  1661. not_sure_linked.append(link_p)
  1662. continue
  1663. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1664. for per in link_p.pointer_person:
  1665. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1666. if not person_phone:
  1667. if per.entity_text not in tenderee_contact:
  1668. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1669. continue
  1670. for _p in person_phone:
  1671. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone:
  1672. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1673. else:
  1674. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1675. for per in link_p.pointer_person:
  1676. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1677. if not person_phone:
  1678. if per.entity_text not in tenderee_contact and per.entity_text not in agency_contact:
  1679. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1680. winter_contact.add(per.entity_text)
  1681. continue
  1682. for _p in person_phone:
  1683. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and \
  1684. per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1685. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1686. winter_contact.add(per.entity_text)
  1687. # 更新org/company实体label为0,1的链接
  1688. for link_p in not_sure_linked:
  1689. for k in PackDict.keys():
  1690. for i in range(len(PackDict[k]["roleList"])):
  1691. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1692. if link_p.label == 0:
  1693. for per in link_p.pointer_person:
  1694. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1695. if not person_phone:
  1696. if per.entity_text not in agency_contact and per.entity_text not in winter_contact:
  1697. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1698. continue
  1699. for _p in person_phone:
  1700. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone and per.entity_text not in winter_contact:
  1701. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1702. elif PackDict[k]["roleList"][i].role_name == "agency":
  1703. if link_p.label == 1:
  1704. for per in link_p.pointer_person:
  1705. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1706. if not person_phone:
  1707. if per.entity_text not in tenderee_contact and per.entity_text not in winter_contact:
  1708. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1709. continue
  1710. for _p in person_phone:
  1711. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and per.entity_text not in winter_contact:
  1712. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1713. re_split = re.compile("[^\u4e00-\u9fa5、](十一|十二|十三|十四|十五|一|二|三|四|五|六|七|八|九|十)、")
  1714. split_list = [0] * 16
  1715. split_dict = {
  1716. "一、": 1,
  1717. "二、": 2,
  1718. "三、": 3,
  1719. "四、": 4,
  1720. "五、": 5,
  1721. "六、": 6,
  1722. "七、": 7,
  1723. "八、": 8,
  1724. "九、": 9,
  1725. "十、": 10,
  1726. "十一、": 11,
  1727. "十二、": 12,
  1728. "十三、": 13,
  1729. "十四、": 14,
  1730. "十五、": 15
  1731. }
  1732. for item in re.finditer(re_split, _content):
  1733. _index = split_dict.get(item.group()[1:])
  1734. if not split_list[_index]:
  1735. split_list[_index] = item.span()[0] + 1
  1736. split_list = [i for i in split_list if i != 0]
  1737. start = 0
  1738. new_split_list = []
  1739. for idx in split_list:
  1740. new_split_list.append((start, idx))
  1741. start = idx
  1742. new_split_list.append((start, len(_content)))
  1743. # 实体列表按照“公告分段”分组
  1744. words_num_dict = dict()
  1745. last_words_num = 0
  1746. for sentence in list_sentence:
  1747. _index = sentence.sentence_index
  1748. if _index == 0:
  1749. words_num_dict[_index] = 0
  1750. else:
  1751. words_num_dict[_index] = words_num_dict[_index - 1] + last_words_num
  1752. last_words_num = len(sentence.sentence_text)
  1753. # 公司-联系人连接(km算法)
  1754. re_phone = re.compile('1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1755. '\+86.?1[3-9]\d{9}|'
  1756. '0[1-9]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1757. '0[1-9]\d{1,2}[-—-―]\d{7,8}.?转\d{1,4}|'
  1758. '0[1-9]\d{1,2}[-—-―]\d{7,8}[-—-―]\d{1,4}|'
  1759. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3-9]\d{9})|'
  1760. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|'
  1761. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|'
  1762. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?|'
  1763. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1764. '[2-9]\d{6,7}')
  1765. key_phone = re.compile("联系方式|电话|联系人|负责人")
  1766. temporary_list2 = []
  1767. for entity in list_entity:
  1768. # if entity.entity_type in ['org', 'company', 'person'] and entity.is_tail==False:
  1769. if entity.entity_type in ['org', 'company', 'person']:
  1770. temporary_list2.append(entity)
  1771. temporary_list2 = sorted(temporary_list2, key=lambda x: (x.sentence_index, x.begin_index))
  1772. new_temporary_list2 = []
  1773. for _split in new_split_list:
  1774. temp_list = []
  1775. for _entity in temporary_list2:
  1776. if words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[0] and words_num_dict[
  1777. _entity.sentence_index] + _entity.wordOffset_end < _split[1]:
  1778. temp_list.append(_entity)
  1779. elif words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[1]:
  1780. break
  1781. new_temporary_list2.append(temp_list)
  1782. # print(new_temporary_list2)
  1783. match_list2 = []
  1784. for split_index in range(len(new_temporary_list2)):
  1785. split_entitys = new_temporary_list2[split_index]
  1786. is_skip = False
  1787. for index in range(len(split_entitys)):
  1788. entity = split_entitys[index]
  1789. if is_skip:
  1790. is_skip = False
  1791. continue
  1792. else:
  1793. if entity.entity_type in ['org', 'company']:
  1794. if entity.label != 5 or entity.entity_text in roleSet:
  1795. match_nums = 0
  1796. for after_index in range(index + 1, min(len(split_entitys), index + 4)):
  1797. after_entity = split_entitys[after_index]
  1798. if after_entity.entity_type in ['person']:
  1799. # 实体为中标人/候选人,联系人已确定类别【1,2】
  1800. if entity.label in [2, 3, 4] and after_entity.label in [1, 2]:
  1801. break
  1802. # 角色为中标候选人,排除"质疑|投诉|监督|受理"相关的联系人
  1803. if entity.label in [2, 3, 4] and re.search("质疑|投诉|监督|受理", list_sentence[after_entity.sentence_index].sentence_text[max(0,after_entity.wordOffset_begin - 10):after_entity.wordOffset_begin]):
  1804. break
  1805. if after_entity.label in [1, 2, 3]:
  1806. distance = (tokens_num_dict[
  1807. after_entity.sentence_index] + after_entity.begin_index) - (
  1808. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1809. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1810. if sentence_distance == 0:
  1811. if distance < 100:
  1812. if (entity.label == 0 and after_entity.label == 1) or (
  1813. entity.label == 1 and after_entity.label == 2):
  1814. distance = distance / 100
  1815. value = (-1 / 2 * (distance ** 2)) / 10000
  1816. match_list2.append(Match(entity, after_entity, value))
  1817. match_nums += 1
  1818. else:
  1819. if distance < 60:
  1820. if (entity.label == 0 and after_entity.label == 1) or (
  1821. entity.label == 1 and after_entity.label == 2):
  1822. distance = distance / 100
  1823. value = (-1 / 2 * (distance ** 2)) / 10000
  1824. match_list2.append(Match(entity, after_entity, value))
  1825. match_nums += 1
  1826. if after_entity.entity_type in ['org', 'company']:
  1827. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  1828. break
  1829. # 解决在‘地址’中识别出org/company的问题
  1830. # if entity.label in [0,1] and after_index==index+1 and after_entity.label not in [0,1]:
  1831. if entity.label != 5 and after_index == index + 1 and (
  1832. after_entity.label == entity.label or after_entity.label == 5):
  1833. distance = (tokens_num_dict[
  1834. after_entity.sentence_index] + after_entity.begin_index) - (
  1835. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1836. if distance < 20:
  1837. after_entity_left = list_sentence[after_entity.sentence_index].tokens[max(0,
  1838. after_entity.begin_index - 10):after_entity.begin_index]
  1839. after_entity_right = list_sentence[after_entity.sentence_index].tokens[
  1840. after_entity.end_index + 1:after_entity.end_index + 6]
  1841. after_entity_left = "".join(after_entity_left)
  1842. if len(after_entity_left) > 20:
  1843. after_entity_left = after_entity_left[-20:]
  1844. after_entity_right = "".join(after_entity_right)[:10]
  1845. if re.search("地,?址", after_entity_left):
  1846. is_skip = True
  1847. continue
  1848. if re.search("\(|(", after_entity_left) and re.search("\)|)",
  1849. after_entity_right):
  1850. is_skip = True
  1851. continue
  1852. if entity.label in [0, 1] and after_entity.label in [0,
  1853. 1] and entity.label == after_entity.label:
  1854. break
  1855. if entity.label in [0, 1] and after_entity.label in [0, 1] and split_entitys[
  1856. index + 1].entity_type == "person":
  1857. break
  1858. if entity.label in [0, 1] and after_entity.label in [2, 3, 4]:
  1859. break
  1860. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  1861. break
  1862. # 搜索没有联系人的电话
  1863. mid_tokens = []
  1864. is_same_sentence = False
  1865. if index == len(split_entitys) - 1:
  1866. for i in range(entity.sentence_index, len(list_sentence)):
  1867. mid_tokens += list_sentence[i].tokens
  1868. mid_tokens = mid_tokens[entity.end_index + 1:]
  1869. mid_sentence = "".join(mid_tokens)
  1870. have_phone = re.findall(re_phone, mid_sentence)
  1871. if have_phone:
  1872. if re.findall(re_phone, mid_sentence.split("。")[0]):
  1873. is_same_sentence = True
  1874. _phone = have_phone[0]
  1875. if _phone in [ent.entity_text for ent in phone_entitys]:
  1876. phone_begin = mid_sentence.find(_phone)
  1877. if words_num_dict[entity.sentence_index] + entity.wordOffset_begin + phone_begin < \
  1878. new_split_list[split_index][1]:
  1879. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  1880. if re.search(key_phone, mid_sentence):
  1881. distance = 1
  1882. if is_same_sentence:
  1883. if phone_begin <= 200:
  1884. value = (-1 / 2 * (distance ** 2)) / 10000
  1885. match_list2.append(Match(entity, (entity, _phone), value))
  1886. match_nums += 1
  1887. else:
  1888. if phone_begin <= 60:
  1889. value = (-1 / 2 * (distance ** 2)) / 10000
  1890. match_list2.append(Match(entity, (entity, _phone), value))
  1891. match_nums += 1
  1892. else:
  1893. next_entity = split_entitys[index + 1]
  1894. if next_entity.entity_type in ["org","company"]:
  1895. _entity_left = list_sentence[next_entity.sentence_index].sentence_text[max(0, next_entity.wordOffset_begin - 20):next_entity.wordOffset_begin]
  1896. _entity_left2 = re.sub(",()\(\)::", "", _entity_left)
  1897. _entity_left2 = _entity_left2[-5:]
  1898. if re.search("(地,?址|地,?点)[::][^,。]*$", _entity_left) or re.search("地址|地点", _entity_left2):
  1899. if index + 2<= len(split_entitys) - 1:
  1900. next_entity = split_entitys[index + 2]
  1901. if entity.sentence_index == next_entity.sentence_index:
  1902. mid_tokens += list_sentence[entity.sentence_index].tokens[
  1903. entity.end_index + 1:next_entity.begin_index]
  1904. else:
  1905. sentence_index = entity.sentence_index
  1906. while sentence_index <= next_entity.sentence_index:
  1907. mid_tokens += list_sentence[sentence_index].tokens
  1908. sentence_index += 1
  1909. mid_tokens = mid_tokens[entity.end_index + 1:-(len(
  1910. list_sentence[next_entity.sentence_index].tokens) - next_entity.begin_index) + 1]
  1911. mid_sentence = "".join(mid_tokens)
  1912. have_phone = re.findall(re_phone, mid_sentence)
  1913. if have_phone:
  1914. if re.findall(re_phone, mid_sentence.split("。")[0]):
  1915. is_same_sentence = True
  1916. _phone = have_phone[0]
  1917. if _phone in [ent.entity_text for ent in phone_entitys]:
  1918. phone_begin = mid_sentence.find(_phone)
  1919. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  1920. if re.search(key_phone, mid_sentence):
  1921. p_phone = [p.entity_text for p in next_entity.person_phone] if next_entity.person_phone else []
  1922. if next_entity.entity_type == 'person' and _phone in p_phone:
  1923. pass
  1924. else:
  1925. distance = (tokens_num_dict[
  1926. next_entity.sentence_index] + next_entity.begin_index) - (
  1927. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1928. distance = distance / 2
  1929. if is_same_sentence:
  1930. if phone_begin <= 200:
  1931. value = (-1 / 2 * (distance ** 2)) / 10000
  1932. match_list2.append(Match(entity, (entity, _phone), value))
  1933. match_nums += 1
  1934. else:
  1935. if phone_begin <= 60:
  1936. value = (-1 / 2 * (distance ** 2)) / 10000
  1937. match_list2.append(Match(entity, (entity, _phone), value))
  1938. match_nums += 1
  1939. # 实体无匹配时,尝试前向查找匹配
  1940. if not match_nums:
  1941. if (entity.label != 5 or entity.entity_text in roleSet) and entity.values[entity.label] >= 0.5 and index != 0:
  1942. previous_entity = split_entitys[index - 1]
  1943. if previous_entity.entity_type == 'person' and previous_entity.label in [1, 2, 3]:
  1944. if entity.label in [2, 3, 4] and previous_entity.label in [1, 2]:
  1945. continue
  1946. if previous_entity.sentence_index == entity.sentence_index:
  1947. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1948. tokens_num_dict[
  1949. previous_entity.sentence_index] + previous_entity.end_index)
  1950. if distance < 20:
  1951. # 距离相等时,前向添加处罚值
  1952. # distance += 1
  1953. # 前向 没有 /10000
  1954. value = (-1 / 2 * (distance ** 2))
  1955. match_list2.append(Match(entity, previous_entity, value))
  1956. # print(match_list2)
  1957. match_list2 = [mat for mat in match_list2 if mat.main_role not in linked_company and mat.attribute not in linked_person]
  1958. # print(match_list2)
  1959. # km算法分配求解
  1960. result2 = dispatch(match_list2)
  1961. # print(result2)
  1962. for match in result2:
  1963. entity = match[0]
  1964. # print(entity.entity_text)
  1965. # print(match.attribute)
  1966. entity_index = list_entity.index(entity)
  1967. is_update = False
  1968. if isinstance(match[1], tuple):
  1969. person_ = ''
  1970. phone_ = match[1][1].split("/") # 分割多个号码
  1971. # print(person_,phone_)
  1972. else:
  1973. person_ = match[1].entity_text
  1974. phone_ = [i.entity_text for i in match[1].person_phone] if match[1].person_phone else []
  1975. for k in PackDict.keys():
  1976. for i in range(len(PackDict[k]["roleList"])):
  1977. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1978. # if not PackDict[k]["roleList"][i].linklist:
  1979. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 0:
  1980. if person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0 and person_ not in winter_contact:
  1981. if not phone_:
  1982. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  1983. for p in phone_:
  1984. # if not person_ and len()
  1985. PackDict[k]["roleList"][i].linklist.append((person_, p))
  1986. is_update = True
  1987. elif PackDict[k]["roleList"][i].role_name == "agency":
  1988. # if not PackDict[k]["roleList"][i].linklist:
  1989. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 1 and person_ not in winter_contact:
  1990. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0:
  1991. if not phone_:
  1992. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  1993. for p in phone_:
  1994. PackDict[k]["roleList"][i].linklist.append((person_, p))
  1995. is_update = True
  1996. else:
  1997. if PackDict[k]["roleList"][i].entity_text == entity.entity_text:
  1998. if not PackDict[k]["roleList"][i].linklist:
  1999. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0 and \
  2000. person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0:
  2001. if not phone_:
  2002. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  2003. for p in phone_:
  2004. PackDict[k]["roleList"][i].linklist.append((person_, p))
  2005. is_update = True
  2006. if not person_:
  2007. is_update = False
  2008. if is_update:
  2009. # 更新 list_entity
  2010. if not list_entity[entity_index].pointer_person:
  2011. list_entity[entity_index].pointer_person = []
  2012. list_entity[entity_index].pointer_person.append(match[1])
  2013. linked_person = []
  2014. linked_persons_with = []
  2015. for company_entity in [entity for entity in list_entity if entity.entity_type in ['company','org']]:
  2016. if company_entity.pointer_person:
  2017. for _person in company_entity.pointer_person:
  2018. linked_person.append(_person)
  2019. linked_persons_with.append(company_entity)
  2020. # 一个公司对应多个联系人的补充
  2021. person_entitys = [entity for entity in list_entity if entity.entity_type=='person']
  2022. person_entitys = person_entitys[::-1]
  2023. for index in range(len(person_entitys)):
  2024. entity = person_entitys[index]
  2025. prepare_link = []
  2026. if entity not in linked_person:
  2027. prepare_link.append(entity)
  2028. last_person = entity
  2029. for after_index in range(index + 1, min(len(person_entitys), index + 5)):
  2030. after_entity = person_entitys[after_index]
  2031. if after_entity.sentence_index==last_person.sentence_index and last_person.begin_index-after_entity.end_index<5:
  2032. if after_entity in linked_person:
  2033. _index = linked_person.index(after_entity)
  2034. with_company = linked_persons_with[_index]
  2035. for i in range(len(PackDict["Project"]["roleList"])):
  2036. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  2037. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 0:
  2038. for item in prepare_link:
  2039. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  2040. for _p in person_phone:
  2041. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  2042. with_company.pointer_person.append(item)
  2043. linked_person.append(item)
  2044. elif PackDict["Project"]["roleList"][i].role_name == "agency":
  2045. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 1:
  2046. for item in prepare_link:
  2047. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  2048. for _p in person_phone:
  2049. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  2050. with_company.pointer_person.append(item)
  2051. linked_person.append(item)
  2052. else:
  2053. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text:
  2054. for item in prepare_link:
  2055. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  2056. for _p in person_phone:
  2057. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  2058. with_company.pointer_person.append(item)
  2059. linked_person.append(item)
  2060. break
  2061. else:
  2062. prepare_link.append(after_entity)
  2063. last_person = after_entity
  2064. continue
  2065. # 统一同类角色的属性
  2066. for k in PackDict.keys():
  2067. for i in range(len(PackDict[k]["roleList"])):
  2068. for _entity in list_entity:
  2069. if _entity.entity_type in ['org','company']:
  2070. is_same = False
  2071. is_similar = False
  2072. # entity_text相同
  2073. if _entity.entity_text==PackDict[k]["roleList"][i].entity_text:
  2074. is_same = True
  2075. # entity.label为【0,1】
  2076. if _entity.label in [0,1] and dict_role_id[str(_entity.label)]==PackDict[k]["roleList"][i].role_name:
  2077. is_similar = True
  2078. if is_same:
  2079. linked_entitys = _entity.linked_entitys
  2080. if linked_entitys:
  2081. for linked_entity in linked_entitys:
  2082. pointer_person = linked_entity.pointer_person if linked_entity.pointer_person else []
  2083. for _pointer_person in pointer_person:
  2084. _phone = [p.entity_text for p in _pointer_person.person_phone] if _pointer_person.person_phone else []
  2085. for _p in _phone:
  2086. if (_pointer_person.entity_text,_p) not in PackDict[k]["roleList"][i].linklist:
  2087. PackDict[k]["roleList"][i].linklist.append((_pointer_person.entity_text,_p))
  2088. elif is_similar:
  2089. pointer_person = _entity.pointer_person if _entity.pointer_person else []
  2090. for _pointer_person in pointer_person:
  2091. _phone = [p.entity_text for p in _pointer_person.person_phone] if _pointer_person.person_phone else []
  2092. for _p in _phone:
  2093. if (_pointer_person.entity_text, _p) not in PackDict[k]["roleList"][i].linklist:
  2094. PackDict[k]["roleList"][i].linklist.append(
  2095. (_pointer_person.entity_text, _p))
  2096. # "roleList"中联系人电话去重
  2097. for k in PackDict.keys():
  2098. for i in range(len(PackDict[k]["roleList"])):
  2099. # 带有联系人的电话
  2100. with_person = [person_phone[1] for person_phone in PackDict[k]["roleList"][i].linklist if person_phone[0]]
  2101. # 带有电话的联系人
  2102. with_phone = [person_phone[0] for person_phone in PackDict[k]["roleList"][i].linklist if person_phone[1]]
  2103. remove_list = []
  2104. for item in PackDict[k]["roleList"][i].linklist:
  2105. if not item[0]:
  2106. if item[1] in with_person:
  2107. # 删除重复的无联系人电话
  2108. remove_list.append(item)
  2109. elif not item[1]:
  2110. if item[0] in with_phone:
  2111. remove_list.append(item)
  2112. for _item in remove_list:
  2113. PackDict[k]["roleList"][i].linklist.remove(_item)
  2114. # PackDict更新company/org地址
  2115. for ent in pre_entity:
  2116. if ent.entity_type in ['company','org']:
  2117. if ent.pointer_address:
  2118. for k in PackDict.keys():
  2119. for i in range(len(PackDict[k]["roleList"])):
  2120. if PackDict[k]["roleList"][i].entity_text == ent.entity_text:
  2121. if not PackDict[k]["roleList"][i].address:
  2122. PackDict[k]["roleList"][i].address = ent.pointer_address.entity_text
  2123. else:
  2124. if len(ent.pointer_address.entity_text) > len(PackDict[k]["roleList"][i].address):
  2125. PackDict[k]["roleList"][i].address = ent.pointer_address.entity_text
  2126. # 联系人——电子邮箱链接
  2127. temporary_list3 = [entity for entity in list_entity if entity.entity_type=='email' or (entity.entity_type=='person' and entity.label in [1,2,3])]
  2128. temporary_list3 = sorted(temporary_list3, key=lambda x: (x.sentence_index, x.begin_index))
  2129. new_temporary_list3 = []
  2130. for _split in new_split_list:
  2131. temp_list = []
  2132. for _entity in temporary_list3:
  2133. if words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[0] and words_num_dict[
  2134. _entity.sentence_index] + _entity.wordOffset_end < _split[1]:
  2135. temp_list.append(_entity)
  2136. elif words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[1]:
  2137. break
  2138. new_temporary_list3.append(temp_list)
  2139. # print(new_temporary_list3)
  2140. match_list3 = []
  2141. for split_index in range(len(new_temporary_list3)):
  2142. split_entitys = new_temporary_list3[split_index]
  2143. for index in range(len(split_entitys)):
  2144. entity = split_entitys[index]
  2145. if entity.entity_type == 'person':
  2146. match_nums = 0
  2147. for after_index in range(index + 1, min(len(split_entitys), index + 4)):
  2148. after_entity = split_entitys[after_index]
  2149. if match_nums > 2:
  2150. break
  2151. if after_entity.entity_type == 'email':
  2152. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  2153. tokens_num_dict[entity.sentence_index] + entity.end_index)
  2154. sentence_distance = after_entity.sentence_index - entity.sentence_index
  2155. if sentence_distance == 0:
  2156. if distance < 100:
  2157. if (entity.label == 0 and after_entity.label == 1) or (
  2158. entity.label == 1 and after_entity.label == 2):
  2159. distance = distance / 100
  2160. value = (-1 / 2 * (distance ** 2)) / 10000
  2161. match_list3.append(Match(entity, after_entity, value))
  2162. match_nums += 1
  2163. else:
  2164. if distance < 60:
  2165. if (entity.label == 0 and after_entity.label == 1) or (
  2166. entity.label == 1 and after_entity.label == 2):
  2167. distance = distance / 100
  2168. value = (-1 / 2 * (distance ** 2)) / 10000
  2169. match_list3.append(Match(entity, after_entity, value))
  2170. match_nums += 1
  2171. # 前向查找匹配
  2172. # if not match_nums:
  2173. if index != 0:
  2174. previous_entity = split_entitys[index - 1]
  2175. if previous_entity.entity_type == 'email':
  2176. if previous_entity.sentence_index == entity.sentence_index:
  2177. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  2178. tokens_num_dict[
  2179. previous_entity.sentence_index] + previous_entity.end_index)
  2180. if distance < 30:
  2181. # 距离相等时,前向添加处罚值
  2182. # distance += 1
  2183. # 前向 没有 /10000
  2184. value = (-1 / 2 * (distance ** 2))
  2185. match_list3.append(Match(entity, previous_entity, value))
  2186. # print(match_list3)
  2187. # km算法分配求解
  2188. result3 = dispatch(match_list3)
  2189. for match in result3:
  2190. match_person = match[0]
  2191. match_email = match[1]
  2192. match_person.pointer_email = match_email
  2193. # # 1)第一个公司实体的招标人,则看看下一个实体是否为代理人,如果是则联系人错位连接 。2)在同一句中往后找联系人。3)连接不上在整个文章找联系人。
  2194. # temp_ent_list = [] # 临时列表,记录0,1角色及3联系人
  2195. # other_person = [] # 阈值以上的联系人列表
  2196. # link_person = [] # 有电话没联系上角色的person列表
  2197. # other_ent = []
  2198. # link_ent = []
  2199. # found_person = False
  2200. # ent_list = []
  2201. # for entity in list_entity:
  2202. # if entity.entity_type in ['org','company','person']:
  2203. # ent_list.append(entity)
  2204. # # ent_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  2205. # #for list_index in range(len(ent_list)):
  2206. # #if ent_list[list_index].entity_type in ['org','company'] and ent_list[list_index].label == 0 and list_index+2<len(ent_list) and \
  2207. # #ent_list[list_index+1].entity_type in ['org','company'] and ent_list[list_index+1].label == 1 and ent_list[list_index+2].entity_type in ['person']:
  2208. # #ent_list[list_index+1], ent_list[list_index+2] = ent_list[list_index+2], ent_list[list_index+1]
  2209. # # 2020/11/25增加确定角色联系人判断
  2210. # sure_person_set = set([entity.entity_text for entity in ent_list if entity.entity_type == 'person' and entity.label in [1, 2]])
  2211. # # 招标/代理在同一句中交叉情况的处理
  2212. # for index in range(len(ent_list)):
  2213. # entity = ent_list[index]
  2214. # if entity.entity_text in roleSet and entity.label in [0, 1] and index+3<len(ent_list):
  2215. # if entity.sentence_index==ent_list[index+1].sentence_index==ent_list[index+2].sentence_index==ent_list[index+3].sentence_index:
  2216. # if ent_list[index+1].begin_index - entity.end_index < 30:
  2217. # if ent_list[index+1].entity_text in roleSet and ent_list[index+1].label in [0, 1] and entity.label!=ent_list[index+1].label:
  2218. # if ent_list[index+2].entity_type=="person" and ent_list[index+3].entity_type=="person" and \
  2219. # ent_list[index+2].label==3 and ent_list[index+3].label==3:
  2220. # ent_list[index + 1], ent_list[index + 2] = ent_list[index + 2], ent_list[index + 1]
  2221. #
  2222. #
  2223. # for index in range(len(ent_list)):
  2224. # entity = ent_list[index]
  2225. # if entity.entity_type=="person":
  2226. # if str(entity.label) == "0": # 2020/11/25 非联系人直接跳过
  2227. # continue
  2228. # if entity.values[entity.label]>on_value_person:
  2229. # if str(entity.label)=="1":
  2230. # for i in range(len(PackDict["Project"]["roleList"])):
  2231. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  2232. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  2233. # link_person.append(entity.entity_text)
  2234. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2235. # # add pointer_person
  2236. # for _entity in list_entity:
  2237. # if dict_role_id.get(str(_entity.label))=="tenderee":
  2238. # for i in range(len(PackDict["Project"]["roleList"])):
  2239. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  2240. # _entity.pointer_person = entity
  2241. # elif str(entity.label)=="2":
  2242. # for i in range(len(PackDict["Project"]["roleList"])):
  2243. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  2244. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  2245. # link_person.append(entity.entity_text)
  2246. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2247. # # add pointer_person
  2248. # for _entity in list_entity:
  2249. # if dict_role_id.get(str(_entity.label))=="agency":
  2250. # for i in range(len(PackDict["Project"]["roleList"])):
  2251. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  2252. # _entity.pointer_person = entity
  2253. # elif str(entity.label)=="3":
  2254. # if entity.entity_text in sure_person_set: # 2020/11/25 排除已经确定角色的联系人
  2255. # continue
  2256. # #not_link_person.append((entity_after.entity_text,entity_after.person_phone))
  2257. # other_person.append(entity.entity_text)
  2258. # temp_ent_list.append((entity.entity_text,entity.person_phone,entity))
  2259. #
  2260. # #if entity.entity_text in roleSet:
  2261. # if entity.entity_text in roleSet:
  2262. # if entity.label in [0,1]:
  2263. # other_ent.append(entity.entity_text)
  2264. # temp_ent_list.append((entity.entity_text, entity.label,entity))
  2265. # for behind_index in range(index+1, len(ent_list)):
  2266. # entity_after = ent_list[behind_index]
  2267. # if entity_after.sentence_index-entity.sentence_index>=1 or entity_after.entity_type in ['org','company']: # 只在本句中找联系人
  2268. # break
  2269. # if entity_after.values is not None:
  2270. # if entity_after.entity_type=="person":
  2271. # if str(entity_after.label) == "0": # 2020/11/25角色后面为非联系人 停止继续往后找
  2272. # break
  2273. # if entity_after.values[entity_after.label]>on_value_person:
  2274. # if str(entity_after.label)=="1":
  2275. # for i in range(len(PackDict["Project"]["roleList"])):
  2276. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  2277. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  2278. # link_person.append(entity_after.entity_text)
  2279. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2280. # elif str(entity_after.label)=="2":
  2281. # for i in range(len(PackDict["Project"]["roleList"])):
  2282. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  2283. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  2284. # link_person.append(entity_after.entity_text)
  2285. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2286. # elif str(entity_after.label)=="3":
  2287. # if entity_after.entity_text in sure_person_set: # 2020/11/25 如果姓名已经出现在确定角色联系人中则停止往后找
  2288. # break
  2289. # elif entity_after.begin_index - entity.end_index > 30:#2020/10/25 如果角色实体与联系人实体间隔大于阈值停止
  2290. # break
  2291. # for pack in PackDict.keys():
  2292. # for i in range(len(PackDict[pack]["roleList"])):
  2293. # if PackDict[pack]["roleList"][i].entity_text==entity.entity_text:
  2294. # #if entity_after.sentence_index-entity.sentence_index>1 and len(roleList[i].linklist)>0:
  2295. # #break
  2296. # PackDict[pack]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  2297. # link_person.append(entity_after.entity_text)
  2298. # #add pointer_person
  2299. # entity.pointer_person = entity_after
  2300. #
  2301. # not_link_person = [person for person in other_person if person not in link_person]
  2302. # not_link_ent = [ent for ent in other_ent if ent not in link_ent]
  2303. # if len(not_link_person) > 0 and len(not_link_ent) > 0 :
  2304. # item = temp_ent_list
  2305. # for i in range(len(item)):
  2306. # if item[i][0] in not_link_ent and item[i][1] == 0 and i+3 < len(item):
  2307. # if item[i+1][0] in other_ent and item[i+1][1] == 1 and item[i+2][0] in other_person and item[i+3][0] in other_person:
  2308. # item[i+1], item[i+2] = item[i+2], item[i+1]
  2309. # for i in range(len(item)-1, -1, -1):
  2310. # if item[i][0] in not_link_ent:
  2311. # for pack in PackDict.keys():
  2312. # for role in PackDict[pack]["roleList"]:
  2313. # if role.entity_text == item[i][0] and len(role.linklist) < 1:
  2314. # for j in range(i+1, len(item)):
  2315. # if item[j][0] in not_link_person:
  2316. # role.linklist.append(item[j][:2])
  2317. # #add pointer_person
  2318. # item[i][2].pointer_person = item[j][2]
  2319. # break
  2320. # else:
  2321. # break
  2322. # # 电话没有联系人的处理
  2323. # role_with_no_phone = []
  2324. # for i in range(len(PackDict["Project"]["roleList"])):
  2325. # if PackDict["Project"]["roleList"][i].role_name in ["tenderee","agency"]:
  2326. # if len(PackDict["Project"]["roleList"][i].linklist)==0: # 找出没有联系人的招标/代理人
  2327. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  2328. # else:
  2329. # phone_nums = 0
  2330. # for link in PackDict["Project"]["roleList"][i].linklist:
  2331. # if link[1]:
  2332. # phone_nums += 1
  2333. # break
  2334. # if not phone_nums:
  2335. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  2336. # if role_with_no_phone:
  2337. # phone_with_person = [entity.person_phone for entity in list_entity if entity.entity_type == "person"]
  2338. # # phone_with_person = [phone for phone in phone_with_person if phone]
  2339. #
  2340. # dict_index_sentence = {}
  2341. # for _sentence in list_sentence:
  2342. # dict_index_sentence[_sentence.sentence_index] = _sentence
  2343. # new_entity_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  2344. # for index in range(len(new_entity_list)):
  2345. # entity = new_entity_list[index]
  2346. # if entity.entity_text in role_with_no_phone:
  2347. # e_sentence = dict_index_sentence[entity.sentence_index]
  2348. # entity_right = e_sentence.tokens[entity.end_index:entity.end_index+40]
  2349. # entity_right = "".join(entity_right)
  2350. # if index+1<len(new_entity_list) and entity_right.find(new_entity_list[index+1].entity_text)>-1:
  2351. # entity_right = entity_right[:entity_right.find(new_entity_list[index+1].entity_text)]
  2352. # have_phone = re.findall(phone,entity_right)
  2353. # if have_phone:
  2354. # _phone = have_phone[0]
  2355. # phone_begin = entity_right.find(_phone)
  2356. # if _phone not in phone_with_person and re.search(key_phone,entity_right[:phone_begin]):
  2357. # # entity.person_phone = _phone
  2358. # for i in range(len(PackDict["Project"]["roleList"])):
  2359. # if PackDict["Project"]["roleList"][i].entity_text == entity.entity_text:
  2360. # PackDict["Project"]["roleList"][i].linklist.append(('', _phone))
  2361. #寻找多标段招标金额
  2362. p_entity = len(list_entity)-1
  2363. set_tenderer_money = set()
  2364. list_tenderer_money = [] #2021/7/16 新增列表,倒序保存所有中标金额
  2365. unit_list = [] #2021/8/17 新增,保存金额单位
  2366. #遍历所有实体
  2367. while(p_entity>=0):
  2368. entity = list_entity[p_entity]
  2369. if entity.entity_type=="money":
  2370. # 2021/12/03 添加成本警戒线、保证金
  2371. if entity.notes in ['保证金', '成本警戒线']:
  2372. packagePointer, _flag = getPackage(PackageList, entity.sentence_index, entity.begin_index,
  2373. "money-" + str(entity.label), MAX_DIS=2, DIRECT="L")
  2374. if packagePointer is None:
  2375. packageName = "Project"
  2376. else:
  2377. packageName = packagePointer.entity_text
  2378. if packageName == "Project":
  2379. # if PackDict["Project"]["tendereeMoney"]<float(entity.entity_text):
  2380. # PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  2381. if entity.notes=="保证金" and "bond" not in PackDict["Project"]:
  2382. PackDict["Project"]["bond"] = float(entity.entity_text)
  2383. elif entity.notes=="成本警戒线" and "cost_warning" not in PackDict["Project"]:
  2384. PackDict["Project"]["cost_warning"] = float(entity.entity_text)
  2385. else:
  2386. if entity.notes == "保证金" and "bond" not in PackDict[packageName]:
  2387. PackDict[packageName]["bond"] = float(entity.entity_text)
  2388. elif entity.notes == "成本警戒线" and "cost_warning" not in PackDict[packageName]:
  2389. PackDict[packageName]["cost_warning"] = float(entity.entity_text)
  2390. elif entity.values[entity.label]>=on_value:
  2391. if str(entity.label)=="1":
  2392. set_tenderer_money.add(float(entity.entity_text))
  2393. list_tenderer_money.append(float(entity.entity_text)) # 2021/7/16 新增列表,倒序保存所有中标金额
  2394. unit_list.append(entity.money_unit)
  2395. # if str(entity.label)=="0":
  2396. if str(entity.label)=="0" and entity.notes!='总投资':
  2397. '''
  2398. if p_entity>0:
  2399. p_before = list_entity[p_entity-1]
  2400. if p_before.entity_type=="money" and p_before.label==entity.label and p_before.entity_text==entity.entity_text and abs(entity.begin_index-p_before.end_index)<=2:
  2401. p_entity -= 1
  2402. continue
  2403. '''
  2404. packagePointer,_flag = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label),MAX_DIS=2,DIRECT="L")
  2405. if packagePointer is None:
  2406. packageName = "Project"
  2407. else:
  2408. packageName = packagePointer.entity_text
  2409. if packageName=="Project":
  2410. # if PackDict["Project"]["tendereeMoney"]<float(entity.entity_text):
  2411. # PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  2412. if entity.values[entity.label]>on_value:
  2413. PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  2414. PackDict["Project"]["tendereeMoneyUnit"] = entity.money_unit
  2415. else:
  2416. PackDict[packageName]["tendereeMoney"] = float(entity.entity_text)
  2417. PackDict[packageName]["tendereeMoneyUnit"] = entity.money_unit
  2418. #add pointer_tendereeMoney
  2419. packagePointer.pointer_tendereeMoney = entity
  2420. p_entity -= 1
  2421. #删除一个机构有多个角色的数据
  2422. #删除重复人、概率不回传
  2423. final_roleList = []
  2424. list_pop = []
  2425. set_tenderer_role = set()
  2426. dict_pack_tenderer_money = dict()
  2427. for pack in PackDict.keys():
  2428. #删除无效包
  2429. if PackDict[pack]["code"]=="" and PackDict[pack]["tendereeMoney"]==0 and len(PackDict[pack]["roleList"])==0:
  2430. list_pop.append(pack)
  2431. for i in range(len(PackDict[pack]["roleList"])):
  2432. if PackDict[pack]["roleList"][i].role_name=="win_tenderer":
  2433. if PackDict[pack]["roleList"][i].money==0:
  2434. set_tenderer_role.add(PackDict[pack]["roleList"][i])
  2435. dict_pack_tenderer_money[pack] = [PackDict[pack]["roleList"][i],set()]
  2436. #找到包的中投标金额
  2437. for _index in range(len(PackageList)):
  2438. if "hit" in PackageList[_index]:
  2439. for _hit in list(PackageList[_index]["hit"]):
  2440. _money = float(_hit.split("-")[1]) if _hit.split("-")[0]=="money" else None
  2441. if PackageList[_index]["name"] in dict_pack_tenderer_money and _money is not None:
  2442. dict_pack_tenderer_money[PackageList[_index]["name"]][1].add(_money)
  2443. #只找到一个中标人和中标金额
  2444. if len(set_tenderer_money)==1 and len(set_tenderer_role)==1:
  2445. list(set_tenderer_role)[0].money = list(set_tenderer_money)[0]
  2446. list(set_tenderer_role)[0].money_unit = unit_list[0]
  2447. # print('一个中标人一个金额:', list(set_tenderer_money)[0])
  2448. #找到一个中标人和多个招标金额
  2449. if len(set_tenderer_money)>1 and len(set_tenderer_role)==1:
  2450. _maxMoney = 0
  2451. _sumMoney = 0
  2452. for _m in list(set_tenderer_money):
  2453. _sumMoney += _m
  2454. if _m>_maxMoney:
  2455. _maxMoney = _m
  2456. if _sumMoney/_maxMoney==2:
  2457. list(set_tenderer_role)[0].money = _maxMoney
  2458. # print('一人多金额分项合计 取最大金额:', _maxMoney)
  2459. else:
  2460. # list(set_tenderer_role)[0].money = _maxMoney
  2461. if min(list_tenderer_money)>200000 and list_tenderer_money[-1]/min(list_tenderer_money)>9000:
  2462. list(set_tenderer_role)[0].money = min(list_tenderer_money)
  2463. list(set_tenderer_role)[0].money_unit = unit_list[list_tenderer_money.index(min(list_tenderer_money))]
  2464. # print('一人多金额 且最小的大于20万第一个金额比最小金额大几千倍的最小中标金额:', min(list_tenderer_money))
  2465. else:
  2466. list(set_tenderer_role)[0].money = list_tenderer_money[-1] # 2021/7/16 修改 不是单价合计方式取第一个中标金额
  2467. list(set_tenderer_role)[0].money_unit = unit_list[-1] # 金额单位
  2468. # print('一人多金额 取第一个中标金额:', list_tenderer_money[-1])
  2469. #每个包都只找到一个金额
  2470. _flag_pack_money = True
  2471. for k,v in dict_pack_tenderer_money.items():
  2472. if len(v[1])!=1:
  2473. _flag_pack_money = False
  2474. if _flag_pack_money and len(PackageSet)==len(dict_pack_tenderer_money.keys()):
  2475. for k,v in dict_pack_tenderer_money.items():
  2476. v[0].money = list(v[1])[0]
  2477. # print('k,v in dict_pack_tenderer_money.items', k, v)
  2478. # 2021/7/16 #增加判断中标金额是否远大于招标金额逻辑
  2479. for pack in PackDict.keys():
  2480. for i in range(len(PackDict[pack]["roleList"])):
  2481. if PackDict[pack]["tendereeMoney"] > 0:
  2482. # print('金额数据类型:',type(PackDict[pack]["roleList"][i].money))
  2483. if float(PackDict[pack]["roleList"][i].money) >10000000 and \
  2484. float(PackDict[pack]["roleList"][i].money)/float(PackDict[pack]["tendereeMoney"])>=1000:
  2485. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  2486. # print('招标金额校正中标金额')
  2487. # 2022/04/01 #增加判断中标金额是否远小于招标金额逻辑,比例相差10000倍左右(中标金额“万”单位丢失或未识别)
  2488. for pack in PackDict.keys():
  2489. for i in range(len(PackDict[pack]["roleList"])):
  2490. if PackDict[pack]["tendereeMoney"] > 0 and float(PackDict[pack]["roleList"][i].money) > 0.:
  2491. if float(PackDict[pack]["roleList"][i].money) < 1000 and \
  2492. float(PackDict[pack]["tendereeMoney"])/float(PackDict[pack]["roleList"][i].money)>=9995 and \
  2493. float(PackDict[pack]["tendereeMoney"])/float(PackDict[pack]["roleList"][i].money)<11000:
  2494. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) * 10000
  2495. # 2021/7/19 #增加判断中标金额是否远大于第二三中标金额
  2496. for pack in PackDict.keys():
  2497. tmp_moneys = []
  2498. for i in range(len(PackDict[pack]["roleList"])):
  2499. if float(PackDict[pack]["roleList"][i].money) >100000:
  2500. tmp_moneys.append(float(PackDict[pack]["roleList"][i].money))
  2501. if len(tmp_moneys)>2 and max(tmp_moneys)/min(tmp_moneys)>1000:
  2502. for i in range(len(PackDict[pack]["roleList"])):
  2503. if float(PackDict[pack]["roleList"][i].money)/min(tmp_moneys)>1000:
  2504. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  2505. # print('通过其他中标人投标金额校正中标金额')
  2506. for item in list_pop:
  2507. PackDict.pop(item)
  2508. # 公告中只有"招标人"且无"联系人"链接时
  2509. if len(PackDict)==1:
  2510. k = list(PackDict.keys())[0]
  2511. if len(PackDict[k]["roleList"])==1:
  2512. if PackDict[k]["roleList"][0].role_name == "tenderee":
  2513. if not PackDict[k]["roleList"][0].linklist:
  2514. get_contacts = False
  2515. if not get_contacts:
  2516. # 根据大纲Outline类召回联系人
  2517. for outline in list_outline:
  2518. if re.search("联系人|联系方|联系方式|联系电话|电话|负责人|与.{2,4}联系",outline.outline_summary):
  2519. for t_person in [p for p in temporary_list2 if p.entity_type=='person' and p.label==3]:
  2520. if words_num_dict[t_person.sentence_index] + t_person.wordOffset_begin >= words_num_dict[outline.sentence_begin_index] + outline.wordOffset_begin and words_num_dict[
  2521. t_person.sentence_index] + t_person.wordOffset_end < words_num_dict[outline.sentence_end_index] + outline.wordOffset_end:
  2522. if t_person.person_phone:
  2523. _phone = [p.entity_text for p in t_person.person_phone]
  2524. for _p in _phone:
  2525. PackDict[k]["roleList"][0].linklist.append((t_person.entity_text, _p))
  2526. get_contacts = True
  2527. break
  2528. elif words_num_dict[t_person.sentence_index] + t_person.wordOffset_begin >= \
  2529. words_num_dict[outline.sentence_end_index] + outline.wordOffset_end:
  2530. break
  2531. if not get_contacts:
  2532. sentence_phone = phone.findall(outline.outline_text)
  2533. if sentence_phone:
  2534. PackDict[k]["roleList"][0].linklist.append(("", sentence_phone[0]))
  2535. get_contacts = True
  2536. break
  2537. if not get_contacts:
  2538. # 直接取文中倒数第一个联系人
  2539. for _entity in temporary_list2[::-1]:
  2540. if _entity.entity_type=='person' and _entity.label==3:
  2541. if _entity.person_phone:
  2542. _phone = [p.entity_text for p in _entity.person_phone]
  2543. for _p in _phone:
  2544. PackDict[k]["roleList"][0].linklist.append((_entity.entity_text, _p))
  2545. get_contacts = True
  2546. break
  2547. if not get_contacts:
  2548. # 如果文中只有一个“phone”实体,则直接取为联系人电话
  2549. if len(phone_entitys) == 1:
  2550. PackDict[k]["roleList"][0].linklist.append(("", phone_entitys[0].entity_text))
  2551. get_contacts = True
  2552. if not get_contacts:
  2553. # 通过大纲Outline类直接取电话
  2554. if len(new_split_list) > 1:
  2555. for _start, _end in new_split_list:
  2556. temp_sentence = _content[_start:_end]
  2557. sentence_outline = temp_sentence.split(",::")[0]
  2558. if re.search("联系人|联系方|联系方式|联系电话|电话|负责人|与.{2,4}联系", sentence_outline):
  2559. sentence_phone = phone.findall(temp_sentence)
  2560. if sentence_phone:
  2561. if sentence_phone[0] in [ent.entity_text for ent in phone_entitys]:
  2562. PackDict[k]["roleList"][0].linklist.append(("", sentence_phone[0]))
  2563. get_contacts = True
  2564. break
  2565. if not get_contacts:
  2566. # 通过正则提取句子段落进行提取电话
  2567. contacts_person = "(?:联系人|联系方|联系方式|负责人|电话|联系电话)[::]?"
  2568. tenderee_pattern = "(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主|业主单位)[^。]{0,5}"
  2569. contact_pattern_list = [tenderee_pattern + contacts_person,
  2570. "(?:采购[^。,]{0,2}项目|采购事项|招标)[^。,]{0,4}" + contacts_person,
  2571. "(?:项目|采购)[^。,]{0,4}" + contacts_person,
  2572. "(?:报名|报价|业务咨询|业务|投标咨询)[^。,]{0,4}" + contacts_person, ]
  2573. for _pattern in contact_pattern_list:
  2574. get_tenderee_contacts = False
  2575. for regular_match in re.finditer(_pattern, _content):
  2576. match_text = _content[regular_match.end():regular_match.end() + 40]
  2577. match_text = match_text.split("。")[0]
  2578. sentence_phone = phone.findall(match_text)
  2579. if sentence_phone:
  2580. PackDict[k]["roleList"][0].linklist.append(("", sentence_phone[0]))
  2581. get_tenderee_contacts = True
  2582. break
  2583. if get_tenderee_contacts:
  2584. break
  2585. for pack in PackDict.keys():
  2586. for i in range(len(PackDict[pack]["roleList"])):
  2587. PackDict[pack]["roleList"][i] = PackDict[pack]["roleList"][i].getString()
  2588. return PackDict
  2589. def initPackageAttr(RoleList,PackageSet):
  2590. '''
  2591. @summary: 根据拿到的roleList和packageSet初始化接口返回的数据
  2592. '''
  2593. packDict = dict()
  2594. packDict["Project"] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  2595. for item in list(PackageSet):
  2596. packDict[item] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  2597. for item in RoleList:
  2598. if packDict[item.packageName]["code"] =="":
  2599. packDict[item.packageName]["code"] = item.packageCode
  2600. # packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[]))
  2601. packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[])) #Role(角色名称,实体名称,角色阈值,金额,金额阈值,连接列表,金额单位)
  2602. return packDict
  2603. def getPackageRoleMoney(list_sentence,list_entity,list_outline):
  2604. '''
  2605. @param:
  2606. list_sentence:文章的句子list
  2607. list_entity:文章的实体list
  2608. @return: 拿到文章的包-标段号-角色-实体名称-金额-联系人-联系电话
  2609. '''
  2610. # print("=1")
  2611. theRole = getRoleList(list_sentence,list_entity)
  2612. if not theRole:
  2613. return []
  2614. RoleList,RoleSet,PackageList,PackageSet = theRole
  2615. '''
  2616. for item in PackageList:
  2617. # print(item)
  2618. '''
  2619. PackDict = initPackageAttr(RoleList, PackageSet)
  2620. PackDict = findAttributeAfterEntity(PackDict, RoleSet, PackageList, PackageSet, list_sentence, list_entity, list_outline)
  2621. return PackDict
  2622. def turnBidWay(bidway):
  2623. if bidway in ("邀请招标","采购方式:邀请"):
  2624. return "邀请招标"
  2625. elif bidway in ("询价","询单","询比","采购方式:询价"):
  2626. return "询价"
  2627. elif bidway in ("竞谈","竞争性谈判","公开竞谈"):
  2628. return "竞争性谈判"
  2629. elif bidway in ("竞争性磋商","磋商"):
  2630. return "竞争性磋商"
  2631. elif bidway in ("竞价","竞标","电子竞价","以电子竞价","电子书面竞投"):
  2632. return "竞价"
  2633. elif bidway in ("公开招标","网上电子投标","网上招标","采购方式:公开","招标为其他"):
  2634. return "公开招标"
  2635. elif bidway in ("单一来源"):
  2636. return "单一来源"
  2637. elif bidway in ("比选"):
  2638. return "比选"
  2639. else:
  2640. return "其他"
  2641. my_time_format_pattern = re.compile("((?P<year>\d{4}|\d{2})\s*[-\/年\.]\s*(?P<month>\d{1,2})\s*[-\/月\.]\s*(?P<day>\d{1,2}))")
  2642. import time
  2643. def my_timeFormat(_time):
  2644. current_year = time.strftime("%Y",time.localtime())
  2645. all_match = re.finditer(my_time_format_pattern,_time)
  2646. time_list = []
  2647. for _match in all_match:
  2648. if len(_match.group())>0:
  2649. legal = True
  2650. year = ""
  2651. month = ""
  2652. day = ""
  2653. for k,v in _match.groupdict().items():
  2654. if k=="year":
  2655. year = v
  2656. if k=="month":
  2657. month = v
  2658. if k=="day":
  2659. day = v
  2660. if year!="":
  2661. if len(year)==2:
  2662. year = "20"+year
  2663. if int(year)>int(current_year):
  2664. legal = False
  2665. else:
  2666. legal = False
  2667. if month!="":
  2668. if int(month)>12:
  2669. legal = False
  2670. else:
  2671. legal = False
  2672. if day!="":
  2673. if int(day)>31:
  2674. legal = False
  2675. else:
  2676. legal = False
  2677. if legal:
  2678. # return "%s-%s-%s"%(year,month.rjust(2,"0"),day.rjust(2,"0"))
  2679. time_list.append("%s-%s-%s"%(year,month.rjust(2,"0"),day.rjust(2,"0")))
  2680. return time_list
  2681. def getTimeAttributes(list_entity,list_sentence):
  2682. time_entitys = [i for i in list_entity if i.entity_type=='time']
  2683. time_entitys = sorted(time_entitys,key=lambda x:(x.sentence_index, x.begin_index))
  2684. list_sentence = sorted(list_sentence,key=lambda x:x.sentence_index)
  2685. dict_time = {
  2686. "time_release": [], # 1 发布时间
  2687. "time_bidopen": [], # 2 开标时间
  2688. "time_bidclose": [], # 3 截标时间
  2689. 'time_bidstart': [], # 12 投标(开始)时间、响应文件接收(开始)时间
  2690. 'time_publicityStart': [], # 4 公示开始时间(公示时间、公示期)
  2691. 'time_publicityEnd': [], # 5 公示截止时间
  2692. 'time_getFileStart': [], # 6 文件获取开始时间(文件获取时间)
  2693. 'time_getFileEnd': [], # 7 文件获取截止时间
  2694. 'time_registrationStart': [], # 8 报名开始时间(报名时间)
  2695. 'time_registrationEnd': [], # 9 报名截止时间
  2696. 'time_earnestMoneyStart': [], #10 保证金递交开始时间(保证金递交时间)
  2697. 'time_earnestMoneyEnd': [] , # 11 保证金递交截止时间
  2698. 'time_commencement':[] , #13 开工日期
  2699. 'time_completion': [] # 14 竣工日期
  2700. }
  2701. last_sentence_index = 0
  2702. last_time_type = ""
  2703. last_time_index = {
  2704. 'time_bidstart':"time_bidclose",
  2705. 'time_publicityStart':"time_publicityEnd",
  2706. 'time_getFileStart':"time_getFileEnd",
  2707. 'time_registrationStart':"time_registrationEnd",
  2708. 'time_earnestMoneyStart':"time_earnestMoneyEnd",
  2709. 'time_commencement':"time_completion",
  2710. }
  2711. for entity in time_entitys:
  2712. sentence_text = list_sentence[entity.sentence_index].sentence_text
  2713. entity_left = sentence_text[max(0, entity.wordOffset_begin - 2):entity.wordOffset_begin]
  2714. entity_right = sentence_text[entity.wordOffset_end:entity.wordOffset_end + 3]
  2715. label_prob = entity.values[entity.label]
  2716. entity_text = entity.entity_text
  2717. in_attachment = entity.in_attachment
  2718. extract_time = my_timeFormat(entity_text)
  2719. if extract_time:
  2720. if re.search("至|到", entity_left):
  2721. if entity.sentence_index == last_sentence_index:
  2722. time_type = last_time_index.get(last_time_type)
  2723. if time_type:
  2724. dict_time[time_type].append((extract_time[0], 0.5 + label_prob / 10,in_attachment))
  2725. last_time_type = ""
  2726. continue
  2727. if entity.label!=0:
  2728. if entity.label==1 and label_prob>0.5:
  2729. dict_time['time_release'].append((extract_time[0],label_prob,in_attachment))
  2730. last_time_type = 'time_release'
  2731. elif entity.label==2 and label_prob>0.5:
  2732. dict_time['time_bidopen'].append((extract_time[0],label_prob,in_attachment))
  2733. last_time_type = 'time_bidopen'
  2734. elif entity.label==3 and label_prob>0.5:
  2735. dict_time['time_bidclose'].append((extract_time[0],label_prob,in_attachment))
  2736. last_time_type = 'time_bidclose'
  2737. elif entity.label==12 and label_prob>0.5:
  2738. if len(extract_time)==1:
  2739. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  2740. dict_time['time_bidclose'].append((extract_time[0], label_prob,in_attachment))
  2741. last_time_type = 'time_bidclose'
  2742. else:
  2743. dict_time['time_bidstart'].append((extract_time[0], label_prob,in_attachment))
  2744. last_time_type = 'time_bidstart'
  2745. else:
  2746. dict_time['time_bidstart'].append((extract_time[0],label_prob,in_attachment))
  2747. dict_time['time_bidclose'].append((extract_time[1],label_prob,in_attachment))
  2748. last_time_type = ''
  2749. elif entity.label==4 and label_prob>0.5:
  2750. if len(extract_time)==1:
  2751. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  2752. dict_time['time_publicityEnd'].append((extract_time[0], label_prob,in_attachment))
  2753. last_time_type = 'time_publicityEnd'
  2754. else:
  2755. dict_time['time_publicityStart'].append((extract_time[0], label_prob,in_attachment))
  2756. last_time_type = 'time_publicityStart'
  2757. else:
  2758. dict_time['time_publicityStart'].append((extract_time[0],label_prob,in_attachment))
  2759. dict_time['time_publicityEnd'].append((extract_time[1],label_prob,in_attachment))
  2760. last_time_type = ''
  2761. elif entity.label==5 and label_prob>0.5:
  2762. if len(extract_time)==1:
  2763. dict_time['time_publicityEnd'].append((extract_time[0], label_prob,in_attachment))
  2764. last_time_type = 'time_publicityEnd'
  2765. else:
  2766. dict_time['time_publicityStart'].append((extract_time[0],label_prob,in_attachment))
  2767. dict_time['time_publicityEnd'].append((extract_time[1],label_prob,in_attachment))
  2768. last_time_type = ''
  2769. elif entity.label==6 and label_prob>0.5:
  2770. if len(extract_time)==1:
  2771. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  2772. dict_time['time_getFileEnd'].append((extract_time[0], label_prob,in_attachment))
  2773. last_time_type = 'time_getFileEnd'
  2774. else:
  2775. dict_time['time_getFileStart'].append((extract_time[0], label_prob,in_attachment))
  2776. last_time_type = 'time_getFileStart'
  2777. else:
  2778. dict_time['time_getFileStart'].append((extract_time[0],label_prob,in_attachment))
  2779. dict_time['time_getFileEnd'].append((extract_time[1],label_prob,in_attachment))
  2780. last_time_type = ''
  2781. elif entity.label==7 and label_prob>0.5:
  2782. if len(extract_time)==1:
  2783. dict_time['time_getFileEnd'].append((extract_time[0], label_prob,in_attachment))
  2784. last_time_type = 'time_getFileEnd'
  2785. else:
  2786. dict_time['time_getFileStart'].append((extract_time[0],label_prob,in_attachment))
  2787. dict_time['time_getFileEnd'].append((extract_time[1],label_prob,in_attachment))
  2788. last_time_type = ''
  2789. elif entity.label==8 and label_prob>0.5:
  2790. if len(extract_time)==1:
  2791. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  2792. dict_time['time_registrationEnd'].append((extract_time[0], label_prob,in_attachment))
  2793. last_time_type = 'time_registrationEnd'
  2794. else:
  2795. dict_time['time_registrationStart'].append((extract_time[0], label_prob,in_attachment))
  2796. last_time_type = 'time_registrationStart'
  2797. else:
  2798. dict_time['time_registrationStart'].append((extract_time[0],label_prob,in_attachment))
  2799. dict_time['time_registrationEnd'].append((extract_time[1],label_prob,in_attachment))
  2800. last_time_type = ''
  2801. elif entity.label==9 and label_prob>0.5:
  2802. if len(extract_time)==1:
  2803. dict_time['time_registrationEnd'].append((extract_time[0], label_prob,in_attachment))
  2804. last_time_type = 'time_registrationEnd'
  2805. else:
  2806. dict_time['time_registrationStart'].append((extract_time[0],label_prob,in_attachment))
  2807. dict_time['time_registrationEnd'].append((extract_time[1],label_prob,in_attachment))
  2808. last_time_type = ''
  2809. elif entity.label==10 and label_prob>0.5:
  2810. if len(extract_time)==1:
  2811. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  2812. dict_time['time_earnestMoneyEnd'].append((extract_time[0], label_prob,in_attachment))
  2813. last_time_type = 'time_earnestMoneyEnd'
  2814. else:
  2815. dict_time['time_earnestMoneyStart'].append((extract_time[0], label_prob,in_attachment))
  2816. last_time_type = 'time_earnestMoneyStart'
  2817. else:
  2818. dict_time['time_earnestMoneyStart'].append((extract_time[0],label_prob,in_attachment))
  2819. dict_time['time_earnestMoneyEnd'].append((extract_time[1],label_prob,in_attachment))
  2820. last_time_type = ''
  2821. elif entity.label==11 and label_prob>0.5:
  2822. if len(extract_time)==1:
  2823. dict_time['time_earnestMoneyEnd'].append((extract_time[0], label_prob,in_attachment))
  2824. last_time_type = 'time_earnestMoneyEnd'
  2825. else:
  2826. dict_time['time_earnestMoneyStart'].append((extract_time[0],label_prob,in_attachment))
  2827. dict_time['time_earnestMoneyEnd'].append((extract_time[1],label_prob,in_attachment))
  2828. last_time_type = ''
  2829. elif entity.label==13 and label_prob>0.5:
  2830. if len(extract_time)==1:
  2831. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  2832. dict_time['time_completion'].append((extract_time[0], label_prob,in_attachment))
  2833. last_time_type = 'time_completion'
  2834. else:
  2835. dict_time['time_commencement'].append((extract_time[0], label_prob,in_attachment))
  2836. last_time_type = 'time_commencement'
  2837. else:
  2838. dict_time['time_commencement'].append((extract_time[0],label_prob,in_attachment))
  2839. dict_time['time_completion'].append((extract_time[1],label_prob,in_attachment))
  2840. last_time_type = ''
  2841. elif entity.label==14 and label_prob>0.5:
  2842. if len(extract_time)==1:
  2843. dict_time['time_completion'].append((extract_time[0], label_prob,in_attachment))
  2844. last_time_type = 'time_completion'
  2845. else:
  2846. dict_time['time_commencement'].append((extract_time[0],label_prob,in_attachment))
  2847. dict_time['time_completion'].append((extract_time[1],label_prob,in_attachment))
  2848. last_time_type = ''
  2849. else:
  2850. last_time_type = ""
  2851. else:
  2852. last_time_type = ""
  2853. else:
  2854. last_time_type = ""
  2855. last_sentence_index = entity.sentence_index
  2856. result_dict = dict((key,"") for key in dict_time.keys())
  2857. for time_type,value in dict_time.items():
  2858. list_time = dict_time[time_type]
  2859. if list_time:
  2860. for in_attachment in [False,True]:
  2861. _list_time = [_time for _time in list_time if _time[2]==in_attachment]
  2862. if _list_time:
  2863. _list_time.sort(key=lambda x:x[1],reverse=True)
  2864. if in_attachment==True and len(result_dict[time_type])>0:
  2865. break
  2866. result_dict[time_type] = _list_time[0][0]
  2867. return result_dict
  2868. def getOtherAttributes(list_entity):
  2869. dict_other = {"moneysource":"",
  2870. "person_review":[],
  2871. "serviceTime":"",
  2872. "product":[],
  2873. "total_tendereeMoney":0,
  2874. "total_tendereeMoneyUnit":''}
  2875. list_serviceTime = []
  2876. for entity in list_entity:
  2877. if entity.entity_type == 'bidway':
  2878. dict_other["bidway"] = turnBidWay(entity.entity_text)
  2879. elif entity.entity_type=='moneysource':
  2880. dict_other["moneysource"] = entity.entity_text
  2881. elif entity.entity_type=='serviceTime':
  2882. if re.search("[^之]日|天|年|月|周|星期", entity.entity_text) or re.search("\d{4}[\-\./]\d{1,2}", entity.entity_text):
  2883. list_serviceTime.append(entity)
  2884. elif entity.entity_type=="person" and entity.label ==4:
  2885. dict_other["person_review"].append(entity.entity_text)
  2886. elif entity.entity_type=='product' and entity.entity_text not in dict_other["product"]: #顺序去重保留
  2887. dict_other["product"].append(entity.entity_text)
  2888. elif entity.entity_type=='money' and entity.notes=='总投资' and dict_other["total_tendereeMoney"]<float(entity.entity_text):
  2889. dict_other["total_tendereeMoney"] = float(entity.entity_text)
  2890. dict_other["total_tendereeMoneyUnit"] = entity.money_unit
  2891. if list_serviceTime:
  2892. list_serviceTime.sort(key=lambda x:x.prob,reverse=True)
  2893. max_prob = list_serviceTime[0].prob
  2894. max_prob_serviceTime = [ent for ent in list_serviceTime if ent.prob==max_prob]
  2895. max_prob_serviceTime.sort(key=lambda x:(x.sentence_index,x.begin_index))
  2896. dict_other["serviceTime"] = max_prob_serviceTime[0].entity_text
  2897. # dict_other["product"] = list(set(dict_other["product"])) # 已在添加时 顺序去重保留
  2898. return dict_other
  2899. def getMoneyRange(RoleList):
  2900. pass
  2901. def getPREMs(list_sentences,list_entitys,list_articles,list_outlines):
  2902. '''
  2903. @param:
  2904. list_sentence:所有文章的句子list
  2905. list_entity:所有文章的实体list
  2906. @return:list of dict which include文章的包-角色-实体名称-金额-联系人-联系电话
  2907. '''
  2908. result = []
  2909. for list_sentence,list_entity,list_article,list_outline in zip(list_sentences,list_entitys,list_articles,list_outlines):
  2910. RoleList = getPackageRoleMoney(list_sentence,list_entity,list_outline)
  2911. result.append(dict({"prem": RoleList, "docid": list_article.doc_id},
  2912. **getTimeAttributes(list_entity, list_sentence),
  2913. **{"fingerprint": list_article.fingerprint,
  2914. "match_enterprise": list_article.match_enterprise,
  2915. "match_enterprise_type": list_article.match_enterprise_type,
  2916. "process_time": getCurrent_date(),
  2917. "attachmentTypes": list_article.attachmentTypes, "bidway": list_article.bidway}))
  2918. # result.append(dict({"prem":RoleList,"docid":list_article.doc_id},**getOtherAttributes(list_entity),**getTimeAttributes(list_entity,list_sentence),
  2919. # **{"fingerprint":list_article.fingerprint,"match_enterprise":list_article.match_enterprise,
  2920. # "match_enterprise_type":list_article.match_enterprise_type,"process_time":getCurrent_date(),
  2921. # "attachmentTypes":list_article.attachmentTypes, "bidway": list_article.bidway}))
  2922. return result
  2923. def correct_rolemoney(prem, total_product_money): # 2022/9/26修改为 中标金额小于表格单价数量合计总金额十分之一时替换
  2924. if total_product_money>0 and len(prem[0]['prem'])==1:
  2925. for value in prem[0]['prem'].values():
  2926. for l in value['roleList']:
  2927. try:
  2928. # if l[0] == 'win_tenderer' and float(l[2])<total_product_money:
  2929. # l[2] = total_product_money
  2930. # log('修改中标金额为所有产品总金额')
  2931. if l["role_name"] == 'win_tenderer' and float(l["role_money"]['money'])<total_product_money/10:
  2932. l["role_money"]['money'] = total_product_money
  2933. # log('修改中标金额为所有产品总金额')
  2934. except Exception as e:
  2935. print('表格产品价格修正中标价格报错:%s'%e)
  2936. def limit_maximum_amount(prem, industry):
  2937. indu = industry['industry'].get('class_name', '')
  2938. indu_amount = {
  2939. '计算机设备': 200000000,
  2940. '办公设备': 100000000,
  2941. '家具用具': 500000000,
  2942. '办公消耗用品及类似物品': 100000000,
  2943. '日杂用品': 100000000,
  2944. '餐饮业': 1000000000,
  2945. '物业管理': 1000000000,
  2946. '工程技术与设计服务': 1000000000,
  2947. '工程评价服务': 100000000,
  2948. '其他工程服务': 100000000,
  2949. '工程监理服务': 100000000,
  2950. '工程造价服务': 100000000
  2951. }
  2952. if indu in indu_amount:
  2953. maximum_amount = indu_amount[indu]
  2954. try:
  2955. for value in prem[0]['prem'].values():
  2956. for l in value['roleList']:
  2957. if l["role_name"] == 'win_tenderer' and float(l["role_money"]['money']) > maximum_amount:
  2958. if indu in ['餐饮业', '物业管理']:
  2959. l["role_money"]['money'] = str(float(l["role_money"]['money'])/10000)
  2960. elif l["role_money"]['money_unit'] == '万元':
  2961. l["role_money"]['money'] = str(float(l["role_money"]['money'])/10000)
  2962. if float(value['tendereeMoney']) > maximum_amount:
  2963. if indu in ['餐饮业', '物业管理']:
  2964. value['tendereeMoney'] = float(value['tendereeMoney'])/10000
  2965. elif value['tendereeMoneyUnit'] == '万元':
  2966. value['tendereeMoney'] = float(value['tendereeMoney']) / 10000
  2967. except Exception as e:
  2968. print('行业分类限制最高金额抛出异常:%s' % e)
  2969. def get_win_joint(prem, list_entitys, list_sentences, list_articles):
  2970. '''
  2971. 获取联合体信息, 添加到prem
  2972. :param prem:
  2973. :param list_entitys:
  2974. :param list_sentences:
  2975. :param list_articles:
  2976. :return:
  2977. '''
  2978. try:
  2979. if 'win_tenderer' in str(prem) and re.search('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:|(联合体)|(联合体(成员|单位)方?[12345一二三四五]?)|((联合体)?成员单位[12345一二三四五]?)|(特殊普通合伙|成员?)', list_articles[0].content):
  2980. sentences = sorted(list_sentences[0], key=lambda x:x.sentence_index)
  2981. for project in prem[0].values():
  2982. if not isinstance(project, dict):
  2983. continue
  2984. for v in project.values():
  2985. for d in v['roleList']:
  2986. if d.get('role_name', '') == 'win_tenderer':
  2987. winner = d.get('role_text')
  2988. join_l = [winner]
  2989. for list_entity in list_entitys:
  2990. for i in range(len(list_entity)-1):
  2991. _entity = list_entity[i]
  2992. b = _entity.wordOffset_begin
  2993. e = _entity.wordOffset_end
  2994. if _entity.entity_type in ['org', 'company'] and _entity.label==2\
  2995. and _entity.entity_text==winner:
  2996. s = sentences[_entity.sentence_index].sentence_text
  2997. for j in range(i+1, len(list_entity)):
  2998. behind_entity = list_entity[j]
  2999. b2 = behind_entity.wordOffset_begin
  3000. e2 = behind_entity.wordOffset_end
  3001. if _entity.sentence_index == behind_entity.sentence_index and behind_entity.entity_type in ['org', 'company'] \
  3002. and b2-e<10 and re.search('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:', s[b2-e:b2]) or \
  3003. re.search('(联合体)|(联合体(成员|单位)方?[12345一二三四五]?)|((联合体)?成员单位[12345一二三四五]?)|(特殊普通合伙|成员?)', s[e2:e2+10]):
  3004. join_l.append(behind_entity.entity_text)
  3005. b = b2
  3006. e = e2
  3007. else:
  3008. break
  3009. if len(join_l)>1:
  3010. d['win_tenderer_joint'] = ','.join(join_l)
  3011. # behind_entity = list_entity[i + 1]
  3012. # if _entity.sentence_index== behind_entity.sentence_index and _entity.entity_type in ['org', 'company'] and _entity.label==2\
  3013. # and _entity.entity_text==winner and behind_entity.entity_type in ['org', 'company'] and behind_entity.label==5:
  3014. # s = sentences[_entity.sentence_index].sentence_text
  3015. # b = _entity.wordOffset_begin
  3016. # e = _entity.wordOffset_end
  3017. # b2 = behind_entity.wordOffset_begin
  3018. # e2 = behind_entity.wordOffset_end
  3019. # if re.search('(联合体)', s[e2:e2+6]) and b2-e<3:
  3020. # print('联合体:', s[max(0, b-10):e2+10])
  3021. # d['win_tenderer_joint'] = '%s,%s'%(_entity.entity_text, behind_entity.entity_text)
  3022. # break
  3023. # elif re.search('(联合体((牵头|主办)(人|方|单位)|主体)|牵头(人|方|单位))|(联合体)?成员:|特殊普通合伙:', s[e:b2]) and b2-e<10:
  3024. # d['win_tenderer_joint'] = '%s,%s' % (_entity.entity_text, behind_entity.entity_text)
  3025. # print('联合体:', s[max(0, b - 10):e2 + 10])
  3026. # break
  3027. except Exception as e:
  3028. print('获取联合体抛出异常', e)
  3029. if __name__=="__main__":
  3030. '''
  3031. conn = getConnection()
  3032. cursor = conn.cursor()
  3033. #sql = " select distinct A.doc_id from entity_mention A,test_predict_role B where A.entity_id=B.entity_id limit 200"
  3034. sql = " select B.doc_id,B.prem from articles_processed A, articles_validation B where A.id=B.doc_id "
  3035. result = []
  3036. cursor.execute(sql)
  3037. rows = cursor.fetchall()
  3038. count = 0
  3039. for row in rows:
  3040. count += 1
  3041. # print(count)
  3042. doc_id = row[0]
  3043. roleList = getPackageRoleMoney(doc_id)
  3044. result.append([doc_id,str(roleList),row[1]])
  3045. ''''''
  3046. with codecs.open("getAttribute.html","w",encoding="utf8") as f:
  3047. f.write('<html><head>\
  3048. <meta http-equiv="Content-Type"\
  3049. content="text/html; charset=UTF-8">\
  3050. </head>\
  3051. <body bgcolor="#FFFFFF">\
  3052. <table border="1">\
  3053. <tr>\
  3054. <td>doc_id</td>\
  3055. <td>角色</td>\
  3056. </tr>')
  3057. for item in result:
  3058. f.write("<tr>"+"<td>"+item[0]+"</td>"+"<td>"+item[1]+"</td>"+"<td>"+item[2]+"</td>"+"</tr>")
  3059. f.write("</table></body>")
  3060. '''