getAttributes.py 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  1. from BiddingKG.dl.common.Utils import findAllIndex,debug,timeFormat,getCurrent_date
  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 entity in list_entity:
  326. if entity.entity_type in ['org','company']:
  327. values = entity.values
  328. role_prob = float(values[int(entity.label)])
  329. _key = entity.packageName+"$$"+str(entity.label)
  330. if role_prob>=on_value and str(entity.label)!="5":
  331. _key_prob = _key+"$text$"+entity.entity_text
  332. if _key_prob in dict_pack_entity_prob:
  333. if role_prob>dict_pack_entity_prob[_key_prob][1]:
  334. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  335. else:
  336. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  337. return dict_pack_entity_prob
  338. #计算合计期望
  339. def getSumExpectation(dict_pack_entity_prob,combination,on_value=0.5):
  340. '''
  341. expect = 0
  342. for entity in list_entity:
  343. if entity.entity_type in ['org','company']:
  344. values = entity.values
  345. role_prob = float(values[int(entity.label)])
  346. _key = entity.packageName+"$$"+str(entity.label)
  347. if role_prob>on_value and str(entity.label)!="5":
  348. if _key in combination.keys() and combination[_key]==entity.entity_text:
  349. expect += math.pow(role_prob,4)
  350. else:
  351. expect -= math.pow(role_prob,4)
  352. '''
  353. #修改为同一个实体只取对应包-角色的最大的概率值
  354. expect = 0
  355. dict_entity_prob = {}
  356. for _key_pack_entity in dict_pack_entity_prob:
  357. _key_pack = _key_pack_entity.split("$text$")[0]
  358. role_prob = dict_pack_entity_prob[_key_pack_entity][1]
  359. if _key_pack in combination.keys() and combination[_key_pack]==dict_pack_entity_prob[_key_pack_entity][0]:
  360. if _key_pack_entity in dict_entity_prob.keys():
  361. if dict_entity_prob[_key_pack_entity]<role_prob:
  362. dict_entity_prob[_key_pack_entity] = role_prob
  363. else:
  364. dict_entity_prob[_key_pack_entity] = role_prob
  365. else:
  366. if _key_pack_entity in dict_entity_prob.keys():
  367. if dict_entity_prob[_key_pack_entity]>-role_prob:
  368. dict_entity_prob[_key_pack_entity] = -role_prob
  369. else:
  370. dict_entity_prob[_key_pack_entity] = -role_prob
  371. # for entity in list_entity:
  372. # if entity.entity_type in ['org','company']:
  373. # values = entity.values
  374. # role_prob = float(values[int(entity.label)])
  375. # _key = entity.packageName+"$$"+str(entity.label)
  376. # if role_prob>=on_value and str(entity.label)!="5":
  377. # if _key in combination.keys() and combination[_key]==entity.entity_text:
  378. # _key_prob = _key+entity.entity_text
  379. # if _key_prob in dict_entity_prob.keys():
  380. # if dict_entity_prob[_key_prob]<role_prob:
  381. # dict_entity_prob[_key_prob] = role_prob
  382. # else:
  383. # dict_entity_prob[_key_prob] = role_prob
  384. # else:
  385. # _key_prob = _key+entity.entity_text
  386. # if _key_prob in dict_entity_prob.keys():
  387. # if dict_entity_prob[_key_prob]>-role_prob:
  388. # dict_entity_prob[_key_prob] = -role_prob
  389. # else:
  390. # dict_entity_prob[_key_prob] = -role_prob
  391. for _key in dict_entity_prob.keys():
  392. symbol = 1 if dict_entity_prob[_key]>0 else -1
  393. expect += symbol*math.pow(dict_entity_prob[_key],2)
  394. return expect
  395. def getRoleList(list_sentence,list_entity,on_value = 0.5):
  396. '''
  397. @summary: 搜索树,得到所有不矛盾的角色组合,取合计期望值最大的作为结果返回
  398. @param:
  399. list_sentence:文章所有的sentence
  400. list_entity:文章所有的实体
  401. on_value:概率阈值
  402. @return:文章的角色list
  403. '''
  404. pack = getPackagesFromArticle(list_sentence,list_entity)
  405. if pack is None:
  406. return None
  407. PackageList,PackageSet,dict_PackageCode = pack
  408. #拿到所有可能的情况
  409. dict_role_combination = {}
  410. # print(PackageList)
  411. #拿到各个实体的packageName,packageCode
  412. for entity in list_entity:
  413. if entity.entity_type in ['org','company']:
  414. #过滤掉字数小于3个的实体
  415. if len(entity.entity_text)<=3:
  416. continue
  417. values = entity.values
  418. role_prob = float(values[int(entity.label)])
  419. if role_prob>=on_value and str(entity.label)!="5":
  420. if str(entity.label) in ["0","1"]:
  421. packageName = "Project"
  422. else:
  423. if len(PackageSet)>0:
  424. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"role-"+str(entity.label))
  425. if packagePointer is None:
  426. #continue
  427. packageName = "Project"
  428. # print(entity.entity_text, packageName,entity.sentence_index,entity.begin_index)
  429. else:
  430. #add pointer_pack
  431. entity.pointer_pack = packagePointer
  432. packageName = packagePointer.entity_text
  433. # print(entity.entity_text, packageName)
  434. else:
  435. packageName = "Project"
  436. find_flag = False
  437. if packageName in dict_PackageCode.keys():
  438. packageCode = dict_PackageCode[packageName]
  439. else:
  440. packageCode = ""
  441. entity.packageCode = packageCode
  442. role_name = dict_role_id.get(str(entity.label))
  443. entity.roleName = role_name
  444. entity.packageName = packageName
  445. if entity.packageName in dict_role_combination.keys():
  446. if str(entity.label) in dict_role_combination[entity.packageName].keys():
  447. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  448. else:
  449. dict_role_combination[entity.packageName][str(entity.label)] = set([entity.entity_text])
  450. else:
  451. dict_role_combination[entity.packageName] = {}
  452. #初始化空值
  453. roleIds = [0,1,2,3,4]
  454. for _roleId in roleIds:
  455. dict_role_combination[entity.packageName][str(_roleId)] = set([""])
  456. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  457. list_real_comba = get_legal_comba(list_entity,dict_role_combination)
  458. # print("===role_combination",dict_role_combination)
  459. # print("== real_comba",list_real_comba)
  460. #拿到最大期望值的组合
  461. max_index = 0
  462. max_expect = -100
  463. _index = 0
  464. dict_pack_entity_prob = get_dict_entity_prob(list_entity)
  465. for item_combination in list_real_comba:
  466. expect = getSumExpectation(dict_pack_entity_prob, item_combination)
  467. if expect>max_expect:
  468. max_index = _index
  469. max_expect = expect
  470. _index += 1
  471. RoleList = []
  472. RoleSet = set()
  473. if len(list_real_comba)>0:
  474. for _key in list_real_comba[max_index].keys():
  475. packageName = _key.split("$$")[0]
  476. label = _key.split("$$")[1]
  477. role_name = dict_role_id.get(str(label))
  478. entity_text = list_real_comba[max_index][_key]
  479. if packageName in dict_PackageCode.keys():
  480. packagecode = dict_PackageCode.get(packageName)
  481. else:
  482. packagecode = ""
  483. RoleList.append(PREM(packageName,packagecode,role_name,entity_text,0,0,0.0,[]))
  484. RoleSet.add(entity_text)
  485. #根据最优树来修正list_entity中角色对包的连接
  486. for _entity in list_entity:
  487. if _entity.pointer_pack is not None:
  488. _pack_name = _entity.pointer_pack.entity_text
  489. _find_flag = False
  490. for _prem in RoleList:
  491. if _prem.packageName==_pack_name and _prem.entity_text==_entity.entity_text:
  492. _find_flag = True
  493. if not _find_flag:
  494. _entity.pointer_pack = None
  495. return RoleList,RoleSet,PackageList,PackageSet
  496. def getPackageScopePattern():
  497. '''
  498. @summary: 获取包的作用域关键词
  499. '''
  500. df = pd.read_excel(os.path.dirname(__file__)+"/end.xls")
  501. pattern = "("
  502. for item in df["list_word"]:
  503. item = str(item).replace("(","\(").replace(")","\)").replace(".","\.").replace("[","\[").replace("]","\]").replace("-","\-")
  504. pattern += item+"|"
  505. pattern = pattern[:-1]+")[::是为]|业绩.{,30}标段[0-9A-Za-z一二三四五六七八九十]{0,3}"
  506. return pattern
  507. pattern_packageScope = getPackageScopePattern()
  508. def getPackagesFromArticle(list_sentence,list_entity):
  509. '''
  510. @param:
  511. list_sentence:文章的句子list
  512. @summary: 将包的信息插入list_entity中
  513. @return: type:list if [包号,句子index,词偏移,标段号] meaning:文章的包/标段信息
  514. '''
  515. if len(list_sentence)==0:
  516. return None
  517. list_sentence.sort(key=lambda x:x.sentence_index)
  518. PackageList = []
  519. PackageList_scope = []
  520. PackageSet = set()
  521. dict_packageCode = dict()
  522. package_name_pattern = re.compile("((标[段号的包]|分包)的?(名[称单]?|包名))[::]?([^::]{3,30}?),{1}")
  523. package_N_name_pattern = re.compile("[^承](分?包|标段|标包|标|包|包组|子项目|包件|项目类型)编?号?[::]?[\((]?([0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]){1,2},{1}")
  524. package_number_pattern = re.compile("(([^承](包|标[段号的包]|分?包|包组|包件)编?号?|子项目|项目类型)[::]?[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}[^\.])[^至]?|([^\.]?第?[ⅠⅡⅢⅣⅤⅥⅦ0-9A-Za-z一二三四五六七八九十]{1,4}(包号|标[段号的包]|分?包))")
  525. # other_package_pattern = re.compile('(项目名称|物资名称|设备名称|场次名称|标段名称)[::](.{,20}?)(,|项目)') # 新正则识别标段
  526. other_package_pattern = re.compile('((项目|物资|设备|场次|标段|标的|产品)(名称))[::]([^,。]{2,50}?)[,。]') # # 2020/11/23 大网站规则 调整 package_N_name_pattern, package_N_name_pattern 中的项目 改为 子项目
  527. win_tenderer_pattern = re.compile('(中标人|供应商)[::](.{2,25})[,。]') # 2020/11/23 大网站规则 调整
  528. model_pattern = re.compile('(型号|序号)[::]([^,。]{2,20})[,。]') # 2020/11/23 大网站规则 调整
  529. number_pattern = re.compile("[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}")
  530. package_code_pattern = re.compile("(?:编号[::]?\s*)([-\dA-Za-z\(\)]+)")
  531. # 纯数字类型的包号统一,例如:'01','1'
  532. re_digital = re.compile("^\d+$")
  533. def changeIndexFromWordToWords(tokens,word_index):
  534. '''
  535. @summary:转换某个字的字偏移为词偏移
  536. '''
  537. before_index = 0
  538. after_index = 0
  539. for i in range(len(tokens)):
  540. after_index = after_index+len(tokens[i])
  541. if before_index<=word_index and after_index>=word_index:
  542. return i
  543. before_index = after_index
  544. package_names = []
  545. def extractPackageCode(tokens,word_index,size=20,pattern = package_code_pattern):
  546. '''
  547. @summary:抽取包附近的标段号
  548. @param:
  549. tokens:包所在句子的分词
  550. word_index:包所在字偏移
  551. size:左右各取多少个词
  552. pattern:提取标段号的正则
  553. @return: type:string,meaning:标段号
  554. '''
  555. index = changeIndexFromWordToWords(tokens,word_index)
  556. if index<size:
  557. begin = index
  558. else:
  559. begin = index-size
  560. if index+size>len(tokens):
  561. end = len(tokens)
  562. else:
  563. end = index+size
  564. #拿到左右两边的词语组成短语
  565. text = "".join(tokens[begin:end])
  566. #在短语中的字偏移
  567. new_word_index = word_index-len("".join(tokens[:begin]))
  568. min_distance = len(text)
  569. packageCode = None
  570. for the_iter in re.finditer(pattern,text):
  571. #算出最小距离
  572. distance = min([abs(new_word_index-the_iter.span()[0]),abs(new_word_index-the_iter.span()[1])])
  573. if distance<min_distance:
  574. min_distance = distance
  575. packageCode = the_iter.group(1)
  576. return packageCode
  577. #从标段介绍表格中提取包名和包号
  578. for i in range(len(list_sentence)):
  579. content = list_sentence[i].sentence_text
  580. names = re.findall(package_name_pattern,content)
  581. if names == []:
  582. names = re.findall(other_package_pattern, content)
  583. N_names = re.findall(package_N_name_pattern,content)
  584. if len(names)==1 and len(N_names)==1:
  585. package_names.append([names[0][-1],N_names[0][-1]])
  586. for i in range(len(list_sentence)):
  587. PackageList_item = []
  588. PackageList_item_scope = []
  589. content = list_sentence[i].sentence_text
  590. tokens = list_sentence[i].tokens
  591. _names = []
  592. # 2021/6/23 包名称去重
  593. for name in package_names:
  594. if name not in _names:
  595. _names.append(name)
  596. # for name in package_names[:20]:
  597. for name in _names[:20]:
  598. for index in findAllIndex(name[0],content):
  599. temp_package_number = re.findall(number_pattern,name[1])[0]
  600. if re.search(re_digital,temp_package_number):
  601. temp_package_number = str(int(temp_package_number))
  602. 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])})
  603. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,index),index,index+len(str(temp_package_number))])
  604. code = extractPackageCode(tokens, index)
  605. if code is not None:
  606. dict_packageCode[temp_package_number] = code
  607. PackageSet.add(temp_package_number)
  608. for iter in re.finditer(package_number_pattern,content):
  609. temp_package_number = re.findall(number_pattern,content[iter.span()[0]:iter.span()[1]])[0]
  610. if re.search(re_digital, temp_package_number):
  611. temp_package_number = str(int(temp_package_number))
  612. 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]})
  613. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  614. code = extractPackageCode(tokens, iter.span()[0])
  615. if code is not None:
  616. dict_packageCode[temp_package_number] = code
  617. PackageSet.add(temp_package_number)
  618. #识别packageScope
  619. for iter in re.finditer(pattern_packageScope,content):
  620. 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]})
  621. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  622. PackageList_item_scope = PackageList_item +PackageList_item_scope
  623. PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  624. PackageList_scope = PackageList_scope+PackageList_item_scope
  625. PackageList_item.sort(key=lambda x:x["sentence_index"])
  626. #PackageList = PackageList+PackageList_item
  627. #不作为包
  628. # if len(PackageSet)==0:
  629. # for i in range(len(list_sentence)):
  630. # PackageList_item = []
  631. # PackageList_item_scope = []
  632. # content = list_sentence[i].sentence_text
  633. # tokens = list_sentence[i].tokens
  634. # for iter in re.finditer(other_package_pattern,content):
  635. # temp_package_number = iter.group(2)
  636. # 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]})
  637. # # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  638. # code = extractPackageCode(tokens, iter.span()[0])
  639. # if code is not None:
  640. # dict_packageCode[temp_package_number] = code
  641. # PackageSet.add(temp_package_number)
  642. # #识别packageScope
  643. # for iter in re.finditer(pattern_packageScope,content):
  644. # 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]})
  645. # # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  646. # PackageList_item_scope = PackageList_item +PackageList_item_scope
  647. # PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  648. # PackageList_scope = PackageList_scope+PackageList_item_scope
  649. # PackageList_item.sort(key=lambda x:x["sentence_index"])
  650. # 2020/11/23 大网站规则 调整
  651. 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:
  652. for i in range(len(list_sentence)):
  653. PackageList_item = []
  654. PackageList_item_scope = []
  655. content = list_sentence[i].sentence_text
  656. tokens = list_sentence[i].tokens
  657. names = re.findall(other_package_pattern, content)
  658. N_names = re.findall(win_tenderer_pattern, content)
  659. if len(names) != 1 or len(N_names) != 1:
  660. continue
  661. for iter in re.finditer(other_package_pattern,content):
  662. temp_package_number = iter.group(4)
  663. xinghao = re.search(model_pattern, content)
  664. if xinghao:
  665. temp_package_number = temp_package_number + '+' + xinghao.group(2)
  666. # print('新正则采购包名补充',temp_package_number)
  667. if re.search(re_digital,temp_package_number):
  668. temp_package_number = str(int(temp_package_number))
  669. 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]})
  670. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  671. code = extractPackageCode(tokens, iter.span()[0])
  672. if code is not None:
  673. dict_packageCode[temp_package_number] = code
  674. PackageSet.add(temp_package_number)
  675. #识别packageScope
  676. for iter in re.finditer(pattern_packageScope,content):
  677. 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]})
  678. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  679. PackageList_item_scope = PackageList_item +PackageList_item_scope
  680. PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  681. PackageList_scope = PackageList_scope+PackageList_item_scope
  682. PackageList_item.sort(key=lambda x:x["sentence_index"])
  683. pattern_punctuation = "[::()\(\),,。;;]"
  684. # print("===packageList_scope",PackageList_scope)
  685. for i in range(len(list_sentence)):
  686. for j in range(len(PackageList_scope)):
  687. if i==PackageList_scope[j]["sentence_index"] and PackageList_scope[j]["name"]!="":
  688. _flag = False
  689. left_str = list_sentence[i].sentence_text[PackageList_scope[j]["offsetWord_begin"]-30:PackageList_scope[j]["offsetWord_begin"]+1]
  690. right_str = list_sentence[i].sentence_text[PackageList_scope[j]["offsetWord_begin"]:PackageList_scope[j]["offsetWord_begin"]+30]
  691. _left_find = re.findall(pattern_punctuation,left_str)
  692. _right_find = re.findall(pattern_punctuation,right_str)
  693. #print(left_str)
  694. if re.search("同",left_str[-1:]) is not None and PackageList_scope[j]["name"]=="一":
  695. continue
  696. if re.search("划分",right_str[:10]) is not None:
  697. continue
  698. if len(_left_find)>0 and _left_find[-1] in [":",":"]:
  699. _flag = True
  700. if len(_right_find)>0 and _right_find[0] in [":",":"]:
  701. _flag = True
  702. if _flag:
  703. scope_begin = [PackageList_scope[j]["sentence_index"],PackageList_scope[j]["offsetWords_begin"]]
  704. else:
  705. if j==0:
  706. scope_begin = [0,0]
  707. else:
  708. scope_begin = [PackageList_scope[j-1]["sentence_index"],PackageList_scope[j-1]["offsetWords_begin"]]
  709. if j==len(PackageList_scope)-1:
  710. scope_end = [list_sentence[-1].sentence_index,changeIndexFromWordToWords(list_sentence[-1].tokens, len(list_sentence[-1].sentence_text))]
  711. else:
  712. scope_end = [PackageList_scope[j+1]["sentence_index"],PackageList_scope[j+1]["offsetWords_begin"]]
  713. 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"]:
  714. continue
  715. #add package to entity
  716. _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"])
  717. list_entity.append(_pack_entity)
  718. copy_pack = copy.copy(PackageList_scope[j])
  719. copy_pack["scope"] = [scope_begin,scope_end]
  720. copy_pack["hit"] = set()
  721. copy_pack["pointer"] = _pack_entity
  722. PackageList.append(copy_pack)
  723. return PackageList,PackageSet,dict_packageCode
  724. from BiddingKG.dl.interface.modelFactory import Model_relation_extraction
  725. relationExtraction_model = Model_relation_extraction()
  726. def findAttributeAfterEntity(PackDict,roleSet,PackageList,PackageSet,list_entity,list_sentence,on_value = 0.5,on_value_person=0.5,sentence_len=4):
  727. '''
  728. @param:
  729. PackDict:文章包dict
  730. roleSet:文章所有角色的公司名称
  731. PackageList:文章的包信息
  732. PackageSet:文章所有包的名称
  733. list_entity:文章所有经过模型处理的实体
  734. on_value:金额模型的阈值
  735. on_value_person:联系人模型的阈值
  736. sentence_len:公司和属性间隔句子的最大长度
  737. @return:添加了属性信息的角色list
  738. '''
  739. #根据roleid添加金额到rolelist中
  740. def addMoneyByRoleid(packDict,packageName,roleid,money,money_prob):
  741. for i in range(len(packDict[packageName]["roleList"])):
  742. if packDict[packageName]["roleList"][i].role_name==dict_role_id.get(str(roleid)):
  743. if money_prob>packDict[packageName]["roleList"][i].money_prob:
  744. packDict[packageName]["roleList"][i].money = money
  745. packDict[packageName]["roleList"][i].money_prob = money_prob
  746. return packDict
  747. #根据实体名称添加金额到rolelist中
  748. def addMoneyByEntity(packDict,packageName,entity,money,money_prob):
  749. for i in range(len(packDict[packageName]["roleList"])):
  750. if packDict[packageName]["roleList"][i].entity_text==entity:
  751. # if money_prob>packDict[packageName]["roleList"][i].money_prob:
  752. # packDict[packageName]["roleList"][i].money = money
  753. # packDict[packageName]["roleList"][i].money_prob = money_prob
  754. if packDict[packageName]["roleList"][i].money_prob==0 : # 2021/7/20第一次更新金额
  755. packDict[packageName]["roleList"][i].money = money.entity_text
  756. packDict[packageName]["roleList"][i].money_prob = money_prob
  757. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  758. elif money_prob>packDict[packageName]["roleList"][i].money_prob+0.2 or money.notes in ['大写']: # 2021/7/20改为优先选择大写金额,
  759. # print('已连接金额概率:money_prob:',packDict[packageName]["roleList"][i].money_prob)
  760. # print('链接金额备注 ',money.notes, money.entity_text, money.values)
  761. packDict[packageName]["roleList"][i].money = money.entity_text
  762. packDict[packageName]["roleList"][i].money_prob = money_prob
  763. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  764. # print('链接中的金额:{0}, 单位:{1}'.format(money.entity_text, money.money_unit))
  765. return packDict
  766. #根据实体名称得到角色
  767. def getRoleWithText(packDict,entity_text):
  768. for pack in packDict.keys():
  769. for i in range(len(packDict[pack]["roleList"])):
  770. if packDict[pack]["roleList"][i].entity_text==entity_text:
  771. return packDict[pack]["roleList"][i].role_name
  772. def doesEntityOrLinkedEntity_inRoleSet(entity,RoleSet):
  773. _list_entitys = [entity]+entity.linked_entitys
  774. for _entity in _list_entitys:
  775. if _entity.entity_text in RoleSet:
  776. return True
  777. p_entity = 0
  778. # 2021/7/19 顺序比较金额,前面是后面的一万倍则把前面金额/10000
  779. money_list = [it for it in list_entity if it.entity_type=="money"]
  780. for i in range(len(money_list)-1):
  781. for j in range(1, len(money_list)):
  782. if (float(money_list[i].entity_text) > 5000000000 or money_list[j].notes=='大写') and \
  783. Decimal(money_list[i].entity_text)/Decimal(money_list[j].entity_text)==10000:
  784. money_list[i].entity_text = str(Decimal(money_list[i].entity_text)/10000)
  785. # print('连接前修改大于50亿金额:前面是后面的一万倍则把前面金额/10000')
  786. #遍历所有实体
  787. while(p_entity<len(list_entity)):
  788. entity = list_entity[p_entity]
  789. '''
  790. #招标金额从后往前找
  791. if entity.entity_type=="money":
  792. if entity.values[entity.label]>=on_value:
  793. if str(entity.label)=="0":
  794. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  795. if packagePointer is None:
  796. packageName = "Project"
  797. else:
  798. packageName = packagePointer.entity_text
  799. addMoneyByRoleid(PackDict, packageName, "0", entity.entity_text, entity.values[entity.label])
  800. '''
  801. ''' # 2020/11/25 与下面的联系人连接步骤重复,取消
  802. if entity.entity_type=="person":
  803. if entity.values[entity.label]>=on_value_person:
  804. if str(entity.label)=="1":
  805. for i in range(len(PackDict["Project"]["roleList"])):
  806. if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  807. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  808. # add pointer_person
  809. for _entity in list_entity:
  810. if dict_role_id.get(str(_entity.label))=="tenderee":
  811. for i in range(len(PackDict["Project"]["roleList"])):
  812. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  813. _entity.pointer_person = entity
  814. elif str(entity.label)=="2":
  815. for i in range(len(PackDict["Project"]["roleList"])):
  816. if PackDict["Project"]["roleList"][i].role_name=="agency":
  817. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  818. # add pointer_person
  819. for _entity in list_entity:
  820. if dict_role_id.get(str(_entity.label))=="agency":
  821. for i in range(len(PackDict["Project"]["roleList"])):
  822. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  823. _entity.pointer_person = entity
  824. '''
  825. # #金额往前找实体
  826. # if entity.entity_type=="money":
  827. # if entity.values[entity.label]>=on_value:
  828. # p_entity_money= p_entity
  829. # entity_money = list_entity[p_entity_money]
  830. # if len(PackageSet)>0:
  831. # packagePointer,_ = getPackage(PackageList,entity_money.sentence_index,entity_money.begin_index,"money-"+str(entity_money.entity_text)+"-"+str(entity_money.label))
  832. # if packagePointer is None:
  833. # packageName_entity = "Project"
  834. # else:
  835. # packageName_entity = packagePointer.entity_text
  836. # else:
  837. # packageName_entity = "Project"
  838. # while(p_entity_money>0):
  839. # entity_before = list_entity[p_entity_money]
  840. # if entity_before.entity_type in ['org','company']:
  841. # if str(entity_before.label)=="1":
  842. # addMoneyByEntity(PackDict, packageName_entity, entity_before.entity_text, entity_money.entity_text, entity_money.values[entity_money.label])
  843. # #add pointer_money
  844. # entity_before.pointer_money = entity_money
  845. # break
  846. # p_entity_money -= 1
  847. #如果实体属于角色集合,则往后找属性
  848. if doesEntityOrLinkedEntity_inRoleSet(entity, roleSet):
  849. p_entity += 1
  850. #循环查找符合的属性
  851. while(p_entity<len(list_entity)):
  852. entity_after = list_entity[p_entity]
  853. if entity_after.sentence_index-entity.sentence_index>=sentence_len:
  854. p_entity -= 1
  855. break
  856. #若是遇到公司实体,则跳出循环
  857. if entity_after.entity_type in ['org','company']:
  858. p_entity -= 1
  859. break
  860. if entity_after.values is not None:
  861. if entity_after.entity_type=="money":
  862. if entity_after.values[entity_after.label]>=on_value:
  863. '''
  864. #招标金额从后往前找
  865. if str(entity_after.label)=="0":
  866. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  867. if packagePointer is None:
  868. packageName = "Project"
  869. else:
  870. packageName = packagePointer.entity_text
  871. addMoneyByRoleid(PackDict, packageName, "0", entity_after.entity_text, entity_after.values[entity_after.label])
  872. '''
  873. if str(entity_after.label)=="1":
  874. #print(entity_after.entity_text,entity.entity_text)
  875. _list_entitys = [entity]+entity.linked_entitys
  876. if len(PackageSet)>0:
  877. packagePointer,_ = getPackage(PackageList,entity_after.sentence_index,entity_after.begin_index,"money-"+str(entity_after.entity_text)+"-"+str(entity_after.label))
  878. if packagePointer is None:
  879. packageName_entity = "Project"
  880. else:
  881. packageName_entity = packagePointer.entity_text
  882. else:
  883. packageName_entity = "Project"
  884. if str(entity.label) in ["2","3","4"]:
  885. # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after.entity_text, entity_after.values[entity_after.label])
  886. if entity_after.notes == '单价':
  887. addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  888. 0.5)
  889. entity.pointer_money = entity_after
  890. # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  891. else:
  892. addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  893. entity_after.values[entity_after.label])
  894. entity.pointer_money = entity_after
  895. # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  896. break # 2021/7/16 新增,找到中标金额,非单价即停止,不再往后找金额
  897. #add pointer_money
  898. # entity.pointer_money = entity_after
  899. # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  900. # if entity_after.notes!='单价':
  901. # break # 2021/7/16 新增,找到中标金额即停止,不再往后找金额
  902. '''
  903. if entity_after.entity_type=="person":
  904. if entity_after.values[entity_after.label]>=on_value_person:
  905. if str(entity_after.label)=="1":
  906. for i in range(len(roleList)):
  907. if roleList[i].role_name=="tenderee":
  908. roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  909. elif str(entity_after.label)=="2":
  910. for i in range(len(roleList)):
  911. if roleList[i].role_name=="agency":
  912. roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  913. elif str(entity_after.label)=="3":
  914. _list_entitys = [entity]+entity.linked_entitys
  915. for _entity in _list_entitys:
  916. for i in range(len(roleList)):
  917. if roleList[i].entity_text==_entity.entity_text:
  918. if entity_after.sentence_index-_entity.sentence_index>1 and len(roleList[i].linklist)>0:
  919. break
  920. roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  921. '''
  922. p_entity += 1
  923. p_entity += 1
  924. ''''''
  925. # 通过模型分类的招标/代理联系人
  926. list_sentence = sorted(list_sentence, key=lambda x: x.sentence_index)
  927. person_list = [entity for entity in list_entity if entity.entity_type == 'person' and entity.label in [1, 2]]
  928. tenderee_contact = set()
  929. tenderee_phone = set()
  930. agency_contact = set()
  931. agency_phone = set()
  932. winter_contact = set()
  933. for _person in person_list:
  934. if _person.label == 1:
  935. tenderee_contact.add(_person.entity_text)
  936. if _person.label == 2:
  937. agency_contact.add(_person.entity_text)
  938. # 正则匹配无 '主体/联系人' 的电话
  939. # 例:"采购人联系方式:0833-5226788,"
  940. re_tenderee_phone = re.compile(
  941. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,5}(?:电话|联系方式|联系人)[::]?[^。]{0,7}?)"
  942. # 电话号码
  943. "(1[3-9][0-9][-—-]?\d{4}[-—-]?\d{4}|0\d{2,3}[-—-][1-9]\d{6,7}/[1-9]\d{6,7}|0\d{2,3}[-—-][1-9]\d{6,7}转\d{1,4}|0\d{2,3}[-—-]?[1-9]\d{6,7}|[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|[1-9]\d{6,7})(?:[^\.]|$)")
  944. # 例:"采购人地址和联系方式:峨边彝族自治县教育局,0833-5226788,"
  945. re_tenderee_phone2 = re.compile(
  946. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人)[::]?[^。]{0,20}?)"
  947. # 电话号码
  948. "(1[3-9][0-9][-—-]?\d{4}[-—-]?\d{4}|0\d{2,3}[-—-][1-9]\d{6,7}/[1-9]\d{6,7}|0\d{2,3}[-—-][1-9]\d{6,7}转\d{1,4}|0\d{2,3}[-—-]?[1-9]\d{6,7}|[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|[1-9]\d{6,7})(?:[^\.]|$)")
  949. re_agent_phone = re.compile(
  950. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,5}(?:电话|联系方式|联系人)[::]?[^。]{0,7}?)"
  951. # 电话号码
  952. "(1[3-9][0-9][-—-]?\d{4}[-—-]?\d{4}|0\d{2,3}[-—-][1-9]\d{6,7}/[1-9]\d{6,7}|0\d{2,3}[-—-][1-9]\d{6,7}转\d{1,4}|0\d{2,3}[-—-]?[1-9]\d{6,7}|[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|[1-9]\d{6,7})(?:[^\.]|$)")
  953. re_agent_phone2 = re.compile(
  954. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人)[::]?[^。]{0,20}?)"
  955. # 电话号码
  956. "(1[3-9][0-9][-—-]?\d{4}[-—-]?\d{4}|0\d{2,3}[-—-][1-9]\d{6,7}/[1-9]\d{6,7}|0\d{2,3}[-—-][1-9]\d{6,7}转\d{1,4}|0\d{2,3}[-—-]?[1-9]\d{6,7}|[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|[1-9]\d{6,7})(?:[^\.]|$)")
  957. content = ""
  958. for _sentence in list_sentence:
  959. content += "".join(_sentence.tokens)
  960. _content = copy.deepcopy(content)
  961. while re.search("(.)(,)([^0-9])|([^0-9])(,)(.)", content):
  962. content_words = list(content)
  963. for i in re.finditer("(.)(,)([^0-9])", content):
  964. content_words[i.span(2)[0]] = ""
  965. for i in re.finditer("([^0-9])(,)(.)", content):
  966. content_words[i.span(2)[0]] = ""
  967. content = "".join(content_words)
  968. content = re.sub("[::]|[\((]|[\))]", "", content)
  969. _tenderee_phone = re.findall(re_tenderee_phone, content)
  970. # 更新正则确定的角色属性
  971. for i in range(len(PackDict["Project"]["roleList"])):
  972. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  973. _tenderee_phone = re.findall(re_tenderee_phone, content)
  974. if _tenderee_phone:
  975. for _phone in _tenderee_phone:
  976. PackDict["Project"]["roleList"][i].linklist.append(("", _phone))
  977. tenderee_phone.add(_phone)
  978. _tenderee_phone2 = re.findall(re_tenderee_phone2, content)
  979. if _tenderee_phone2:
  980. for _phone in _tenderee_phone2:
  981. PackDict["Project"]["roleList"][i].linklist.append(("", _phone))
  982. tenderee_phone.add(_phone)
  983. if PackDict["Project"]["roleList"][i].role_name == "agency":
  984. _agent_phone = re.findall(re_agent_phone, content)
  985. if _agent_phone:
  986. for _phone in _agent_phone:
  987. PackDict["Project"]["roleList"][i].linklist.append(("", _phone))
  988. agency_phone.add(_phone)
  989. _agent_phone2 = re.findall(re_agent_phone2, content)
  990. if _agent_phone2:
  991. for _phone in _agent_phone2:
  992. PackDict["Project"]["roleList"][i].linklist.append(("", _phone))
  993. agency_phone.add(_phone)
  994. # km配对方法
  995. def dispatch(match_list):
  996. main_roles = list(set([match.main_role for match in match_list]))
  997. attributes = list(set([match.attribute for match in match_list]))
  998. label = np.zeros(shape=(len(main_roles), len(attributes)))
  999. for match in match_list:
  1000. main_role = match.main_role
  1001. attribute = match.attribute
  1002. value = match.value
  1003. label[main_roles.index(main_role), attributes.index(attribute)] = value + 10000
  1004. # print(label)
  1005. gragh = -label
  1006. # km算法
  1007. row, col = linear_sum_assignment(gragh)
  1008. max_dispatch = [(i, j) for i, j, value in zip(row, col, gragh[row, col]) if value]
  1009. # return [Match(main_roles[row], attributes[col]) for row, col in max_dispatch]
  1010. return [(main_roles[row], attributes[col]) for row, col in max_dispatch]
  1011. # 正则提取电话号码实体
  1012. key_word = re.compile('((?:电话|联系方式|联系人).{0,4}?)([0-1]\d{6,11})')
  1013. phone = re.compile('1[3|4|5|6|7|8|9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1014. '\+86.?1[3|4|5|6|7|8|9]\d{9}|'
  1015. '0[^0]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1016. '0[^0]\d{1,2}[-—-―]\d{7,8}转\d{1,4}|'
  1017. '0[^0]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3|4|5|6|7|8|9]\d{9})|'
  1018. '0[^0]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[^0]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|'
  1019. '0[^0]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|'
  1020. '0[^0]\d{1,2}[-—-―]?[1-9]\d{6}\d?|'
  1021. '[\(|\(]0[^0]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1022. '[2-9]\d{6,7}')
  1023. phone_entitys = []
  1024. for _sentence in list_sentence:
  1025. sentence_text = _sentence.sentence_text
  1026. list_tokenbegin = []
  1027. begin = 0
  1028. for i in range(0, len(_sentence.tokens)):
  1029. list_tokenbegin.append(begin)
  1030. begin += len(str(_sentence.tokens[i]))
  1031. list_tokenbegin.append(begin + 1)
  1032. res_set = set()
  1033. for i in re.finditer(phone, sentence_text):
  1034. res_set.add((i.group(), i.start(), i.end()))
  1035. # for i in re.finditer(key_word, sentence_text):
  1036. # res_set.add((i.group(2), i.start() + len(i.group(1)), i.end()))
  1037. for item in list(res_set):
  1038. phone_left = sentence_text[max(0, item[1] - 10):item[1]]
  1039. phone_right = sentence_text[item[2]:item[2] + 8]
  1040. # 排除“传真号”和其它错误项
  1041. if re.search("传,?真|信,?箱|邮,?箱", phone_left):
  1042. if not re.search("电,?话", phone_left):
  1043. continue
  1044. if re.search("帐,?号|编,?号|报,?价|证,?号|价,?格|[\((]万?元[\))]", phone_left):
  1045. continue
  1046. if re.search("[.,]\d{2,}", phone_right):
  1047. continue
  1048. for j in range(len(list_tokenbegin)):
  1049. if list_tokenbegin[j] == item[1]:
  1050. begin_index = j
  1051. break
  1052. elif list_tokenbegin[j] > item[1]:
  1053. begin_index = j - 1
  1054. break
  1055. for j in range(begin_index, len(list_tokenbegin)):
  1056. if list_tokenbegin[j] >= item[2]:
  1057. end_index = j - 1
  1058. break
  1059. _entity = Entity(_sentence.doc_id, None, item[0], "phone", _sentence.sentence_index, begin_index, end_index, item[1],
  1060. item[2])
  1061. phone_entitys.append(_entity)
  1062. def is_company(entity,text):
  1063. # 判断"公司"实体是否为地址地点
  1064. if entity.label!=5 and entity.values[entity.label]>0.5:
  1065. return True
  1066. if ent.is_tail==True:
  1067. return False
  1068. entity_left = text[max(0,entity.wordOffset_begin-10):entity.wordOffset_begin]
  1069. entity_left = re.sub(",()\(\)::","",entity_left)
  1070. entity_left = entity_left[-5:]
  1071. if re.search("地址|地点",entity_left):
  1072. return False
  1073. else:
  1074. return True
  1075. pre_entity = []
  1076. for ent in list_entity:
  1077. 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]) \
  1078. or (ent.entity_type=='location' and len(ent.entity_text)>5):
  1079. pre_entity.append(ent)
  1080. text_data,pre_data = relationExtraction_model.encode(pre_entity + phone_entitys, list_sentence)
  1081. # print(pre_data)
  1082. maxlen = 512
  1083. relation_list = []
  1084. if 0<len(text_data)<=maxlen:
  1085. relation_list = relationExtraction_model.predict(text_data, pre_data)
  1086. else:
  1087. # 公告大于maxlen时,分段预测
  1088. start = 0
  1089. while start<len(pre_data):
  1090. _pre_data = pre_data[start:start+maxlen]
  1091. _text_data = text_data[start:start+maxlen]
  1092. relation_list.extend(relationExtraction_model.predict(_text_data,_pre_data))
  1093. start = start + maxlen - 100
  1094. # 去重结果
  1095. relation_list = list(set(relation_list))
  1096. # print(relation_list)
  1097. tokens_num_dict = dict()
  1098. last_tokens_num = 0
  1099. for sentence in list_sentence:
  1100. _index = sentence.sentence_index
  1101. if _index == 0:
  1102. tokens_num_dict[_index] = 0
  1103. else:
  1104. tokens_num_dict[_index] = tokens_num_dict[_index - 1] + last_tokens_num
  1105. last_tokens_num = len(sentence.tokens)
  1106. right_combination = [('org','person'),('company','person'),('company','location'),('org','location'),('person','phone')]
  1107. linked_company = set()
  1108. linked_person = set()
  1109. for predicate in ["rel_address","rel_phone","rel_person"]:
  1110. _match_list = []
  1111. _match_combo = []
  1112. for relation in relation_list:
  1113. _subject = relation[0]
  1114. _object = relation[2]
  1115. if isinstance(_subject,Entity) and isinstance(_object,Entity) and (_subject.entity_type,_object.entity_type) in right_combination:
  1116. if relation[1]==predicate:
  1117. if predicate=="rel_person":
  1118. if (_subject.label==0 and _object.entity_text in agency_contact ) or (_subject.label==1 and _object.entity_text in tenderee_contact):
  1119. continue
  1120. distance = (tokens_num_dict[_object.sentence_index] + _object.begin_index) - (
  1121. tokens_num_dict[_subject.sentence_index] + _subject.end_index)
  1122. if distance>0:
  1123. value = (-1 / 2 * (distance ** 2))/10000
  1124. else:
  1125. distance = abs(distance)
  1126. value = (-1 / 2 * (distance ** 2))
  1127. _match_list.append(Match(_subject,_object,value))
  1128. _match_combo.append((_subject,_object))
  1129. match_result = dispatch(_match_list)
  1130. error_list = []
  1131. for mat in list(set(_match_combo)-set(match_result)):
  1132. for temp in match_result:
  1133. if mat[1]==temp[1] and mat[0]!=temp[0]:
  1134. error_list.append(mat)
  1135. break
  1136. result = list(set(_match_combo)-set(error_list))
  1137. if predicate=='rel_person':
  1138. # 从后往前更新状态,已近后向链接的属性不在前向链接(解决错误链接)
  1139. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1140. for combo in result:
  1141. is_continue = False
  1142. if not combo[0].pointer_person:
  1143. combo[0].pointer_person = []
  1144. if combo[1].begin_index<combo[0].begin_index:
  1145. if combo[0].pointer_person:
  1146. for temp in combo[0].pointer_person:
  1147. if temp.begin_index>combo[0].begin_index:
  1148. is_continue = True
  1149. break
  1150. if is_continue: continue
  1151. combo[0].pointer_person.append(combo[1])
  1152. linked_company.add(combo[0])
  1153. linked_person.add(combo[1])
  1154. # print(1,combo[0].entity_text,combo[1].entity_text)
  1155. if predicate=='rel_address':
  1156. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1157. for combo in result:
  1158. if combo[0].pointer_address:
  1159. continue
  1160. combo[0].pointer_address = combo[1]
  1161. # print(2,combo[0].entity_text,combo[1].entity_text)
  1162. if predicate=='rel_phone':
  1163. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1164. for combo in result:
  1165. is_continue = False
  1166. if not combo[0].person_phone:
  1167. combo[0].person_phone = []
  1168. if combo[1].begin_index<combo[0].begin_index:
  1169. if combo[0].person_phone:
  1170. for temp in combo[0].person_phone:
  1171. if temp.begin_index>combo[0].begin_index:
  1172. is_continue = True
  1173. break
  1174. if is_continue: continue
  1175. combo[0].person_phone.append(combo[1])
  1176. if combo[0].label in [1,2]:
  1177. if PackDict.get("Project"):
  1178. for i in range(len(PackDict["Project"]["roleList"])):
  1179. if (combo[0].label==1 and PackDict["Project"]["roleList"][i].role_name=='tenderee') \
  1180. or (combo[0].label==2 and PackDict["Project"]["roleList"][i].role_name=='agency'):
  1181. PackDict["Project"]["roleList"][i].linklist.append((combo[0].entity_text,combo[1].entity_text))
  1182. break
  1183. # print(3,combo[0].entity_text,combo[1].entity_text)
  1184. # 更新 PackDict
  1185. not_sure_linked = []
  1186. for link_p in list(linked_company):
  1187. for k in PackDict.keys():
  1188. for i in range(len(PackDict[k]["roleList"])):
  1189. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1190. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 0:
  1191. not_sure_linked.append(link_p)
  1192. continue
  1193. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1194. for per in link_p.pointer_person:
  1195. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1196. if not person_phone:
  1197. if per.entity_text not in agency_contact:
  1198. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1199. continue
  1200. for _p in person_phone:
  1201. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1202. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1203. elif PackDict[k]["roleList"][i].role_name == "agency":
  1204. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 1:
  1205. not_sure_linked.append(link_p)
  1206. continue
  1207. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1208. for per in link_p.pointer_person:
  1209. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1210. if not person_phone:
  1211. if per.entity_text not in tenderee_contact:
  1212. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1213. continue
  1214. for _p in person_phone:
  1215. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone:
  1216. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1217. else:
  1218. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1219. for per in link_p.pointer_person:
  1220. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1221. if not person_phone:
  1222. if per.entity_text not in tenderee_contact and per.entity_text not in agency_contact:
  1223. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1224. winter_contact.add(per.entity_text)
  1225. continue
  1226. for _p in person_phone:
  1227. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and \
  1228. per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1229. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1230. winter_contact.add(per.entity_text)
  1231. # 更新org/company实体label为0,1的链接
  1232. for link_p in not_sure_linked:
  1233. for k in PackDict.keys():
  1234. for i in range(len(PackDict[k]["roleList"])):
  1235. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1236. if link_p.label == 0:
  1237. for per in link_p.pointer_person:
  1238. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1239. if not person_phone:
  1240. if per.entity_text not in agency_contact and per.entity_text not in winter_contact:
  1241. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1242. continue
  1243. for _p in person_phone:
  1244. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone and per.entity_text not in winter_contact:
  1245. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1246. elif PackDict[k]["roleList"][i].role_name == "agency":
  1247. if link_p.label == 1:
  1248. for per in link_p.pointer_person:
  1249. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1250. if not person_phone:
  1251. if per.entity_text not in tenderee_contact and per.entity_text not in winter_contact:
  1252. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1253. continue
  1254. for _p in person_phone:
  1255. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and per.entity_text not in winter_contact:
  1256. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1257. re_split = re.compile("[^\u4e00-\u9fa5、](十一|十二|十三|十四|十五|一|二|三|四|五|六|七|八|九|十)、")
  1258. split_list = [0] * 16
  1259. split_dict = {
  1260. "一、": 1,
  1261. "二、": 2,
  1262. "三、": 3,
  1263. "四、": 4,
  1264. "五、": 5,
  1265. "六、": 6,
  1266. "七、": 7,
  1267. "八、": 8,
  1268. "九、": 9,
  1269. "十、": 10,
  1270. "十一、": 11,
  1271. "十二、": 12,
  1272. "十三、": 13,
  1273. "十四、": 14,
  1274. "十五、": 15
  1275. }
  1276. for item in re.finditer(re_split, _content):
  1277. _index = split_dict.get(item.group()[1:])
  1278. if not split_list[_index]:
  1279. split_list[_index] = item.span()[0] + 1
  1280. split_list = [i for i in split_list if i != 0]
  1281. start = 0
  1282. new_split_list = []
  1283. for idx in split_list:
  1284. new_split_list.append((start, idx))
  1285. start = idx
  1286. new_split_list.append((start, len(_content)))
  1287. # 实体列表按照“公告分段”分组
  1288. words_num_dict = dict()
  1289. last_words_num = 0
  1290. for sentence in list_sentence:
  1291. _index = sentence.sentence_index
  1292. if _index == 0:
  1293. words_num_dict[_index] = 0
  1294. else:
  1295. words_num_dict[_index] = words_num_dict[_index - 1] + last_words_num
  1296. last_words_num = len(sentence.sentence_text)
  1297. # 公司-联系人连接(km算法)
  1298. re_phone = re.compile('1[3-9][0-9][-—-]?\d{4}[-—-]?\d{4}|'
  1299. '0\d{2,3}[-—-][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1300. '0\d{2,3}[-—-][1-9]\d{6,7}转\d{1,4}|'
  1301. '0\d{2,3}[-—-]?[1-9]\d{6,7}|'
  1302. '[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1303. '[1-9]\d{6,7}')
  1304. key_phone = re.compile("联系方式|电话|联系人|负责人")
  1305. temporary_list2 = []
  1306. for entity in list_entity:
  1307. # if entity.entity_type in ['org', 'company', 'person'] and entity.is_tail==False:
  1308. if entity.entity_type in ['org', 'company', 'person']:
  1309. temporary_list2.append(entity)
  1310. temporary_list2 = sorted(temporary_list2, key=lambda x: (x.sentence_index, x.begin_index))
  1311. new_temporary_list2 = []
  1312. for _split in new_split_list:
  1313. temp_list = []
  1314. for _entity in temporary_list2:
  1315. if words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[0] and words_num_dict[
  1316. _entity.sentence_index] + _entity.wordOffset_end < _split[1]:
  1317. temp_list.append(_entity)
  1318. elif words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[1]:
  1319. break
  1320. new_temporary_list2.append(temp_list)
  1321. # print(new_temporary_list2)
  1322. match_list2 = []
  1323. for split_index in range(len(new_temporary_list2)):
  1324. split_entitys = new_temporary_list2[split_index]
  1325. is_skip = False
  1326. for index in range(len(split_entitys)):
  1327. entity = split_entitys[index]
  1328. if is_skip:
  1329. is_skip = False
  1330. continue
  1331. else:
  1332. if entity.entity_type in ['org', 'company']:
  1333. if entity.label != 5 or entity.entity_text in roleSet:
  1334. match_nums = 0
  1335. for after_index in range(index + 1, min(len(split_entitys), index + 4)):
  1336. after_entity = split_entitys[after_index]
  1337. if after_entity.entity_type in ['person']:
  1338. # 实体为中标人/候选人,联系人已确定类别【1,2】
  1339. if entity.label in [2, 3, 4] and after_entity.label in [1, 2]:
  1340. break
  1341. if after_entity.label in [1, 2, 3]:
  1342. distance = (tokens_num_dict[
  1343. after_entity.sentence_index] + after_entity.begin_index) - (
  1344. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1345. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1346. if sentence_distance == 0:
  1347. if distance < 100:
  1348. if (entity.label == 0 and after_entity.label == 1) or (
  1349. entity.label == 1 and after_entity.label == 2):
  1350. distance = distance / 100
  1351. value = (-1 / 2 * (distance ** 2)) / 10000
  1352. match_list2.append(Match(entity, after_entity, value))
  1353. match_nums += 1
  1354. else:
  1355. if distance < 60:
  1356. if (entity.label == 0 and after_entity.label == 1) or (
  1357. entity.label == 1 and after_entity.label == 2):
  1358. distance = distance / 100
  1359. value = (-1 / 2 * (distance ** 2)) / 10000
  1360. match_list2.append(Match(entity, after_entity, value))
  1361. match_nums += 1
  1362. if after_entity.entity_type in ['org', 'company']:
  1363. # 解决在‘地址’中识别出org/company的问题
  1364. # if entity.label in [0,1] and after_index==index+1 and after_entity.label not in [0,1]:
  1365. if entity.label != 5 and after_index == index + 1 and (
  1366. after_entity.label == entity.label or after_entity.label == 5):
  1367. distance = (tokens_num_dict[
  1368. after_entity.sentence_index] + after_entity.begin_index) - (
  1369. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1370. if distance < 20:
  1371. after_entity_left = list_sentence[after_entity.sentence_index].tokens[max(0,
  1372. after_entity.begin_index - 10):after_entity.begin_index]
  1373. after_entity_right = list_sentence[after_entity.sentence_index].tokens[
  1374. after_entity.end_index + 1:after_entity.end_index + 6]
  1375. after_entity_left = "".join(after_entity_left)
  1376. if len(after_entity_left) > 20:
  1377. after_entity_left = after_entity_left[-20:]
  1378. after_entity_right = "".join(after_entity_right)[:10]
  1379. if re.search("地,?址", after_entity_left):
  1380. is_skip = True
  1381. continue
  1382. if re.search("\(|(", after_entity_left) and re.search("\)|)",
  1383. after_entity_right):
  1384. is_skip = True
  1385. continue
  1386. if entity.label in [0, 1] and after_entity.label in [0,
  1387. 1] and entity.label == after_entity.label:
  1388. break
  1389. if entity.label in [0, 1] and after_entity.label in [0, 1] and split_entitys[
  1390. index + 1].entity_type == "person":
  1391. break
  1392. if entity.label in [0, 1] and after_entity.label in [2, 3, 4]:
  1393. break
  1394. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  1395. break
  1396. # 搜索没有联系人的电话
  1397. mid_tokens = []
  1398. is_same_sentence = False
  1399. if index == len(split_entitys) - 1:
  1400. for i in range(entity.sentence_index, len(list_sentence)):
  1401. mid_tokens += list_sentence[i].tokens
  1402. mid_tokens = mid_tokens[entity.end_index + 1:]
  1403. mid_sentence = "".join(mid_tokens)
  1404. have_phone = re.findall(re_phone, mid_sentence)
  1405. if have_phone:
  1406. if re.findall(re_phone, mid_sentence.split("。")[0]):
  1407. is_same_sentence = True
  1408. _phone = have_phone[0]
  1409. phone_begin = mid_sentence.find(_phone)
  1410. if words_num_dict[entity.sentence_index] + entity.wordOffset_begin + phone_begin < \
  1411. new_split_list[split_index][1]:
  1412. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  1413. if re.search(key_phone, mid_sentence):
  1414. distance = 1
  1415. if is_same_sentence:
  1416. if phone_begin <= 200:
  1417. value = (-1 / 2 * (distance ** 2)) / 10000
  1418. match_list2.append(Match(entity, (entity, _phone), value))
  1419. match_nums += 1
  1420. else:
  1421. if phone_begin <= 60:
  1422. value = (-1 / 2 * (distance ** 2)) / 10000
  1423. match_list2.append(Match(entity, (entity, _phone), value))
  1424. match_nums += 1
  1425. else:
  1426. next_entity = split_entitys[index + 1]
  1427. if entity.sentence_index == next_entity.sentence_index:
  1428. mid_tokens += list_sentence[entity.sentence_index].tokens[
  1429. entity.end_index + 1:next_entity.begin_index]
  1430. else:
  1431. sentence_index = entity.sentence_index
  1432. while sentence_index <= next_entity.sentence_index:
  1433. mid_tokens += list_sentence[sentence_index].tokens
  1434. sentence_index += 1
  1435. mid_tokens = mid_tokens[entity.end_index + 1:-(len(
  1436. list_sentence[next_entity.sentence_index].tokens) - next_entity.begin_index) + 1]
  1437. mid_sentence = "".join(mid_tokens)
  1438. have_phone = re.findall(re_phone, mid_sentence)
  1439. if have_phone:
  1440. if re.findall(re_phone, mid_sentence.split("。")[0]):
  1441. is_same_sentence = True
  1442. _phone = have_phone[0]
  1443. phone_begin = mid_sentence.find(_phone)
  1444. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  1445. if re.search(key_phone, mid_sentence):
  1446. p_phone = [p.entity_text for p in next_entity.person_phone] if next_entity.person_phone else []
  1447. if next_entity.entity_type == 'person' and _phone in p_phone:
  1448. pass
  1449. else:
  1450. distance = (tokens_num_dict[
  1451. next_entity.sentence_index] + next_entity.begin_index) - (
  1452. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1453. distance = distance / 2
  1454. if is_same_sentence:
  1455. if phone_begin <= 200:
  1456. value = (-1 / 2 * (distance ** 2)) / 10000
  1457. match_list2.append(Match(entity, (entity, _phone), value))
  1458. match_nums += 1
  1459. else:
  1460. if phone_begin <= 60:
  1461. value = (-1 / 2 * (distance ** 2)) / 10000
  1462. match_list2.append(Match(entity, (entity, _phone), value))
  1463. match_nums += 1
  1464. # 实体无匹配时,尝试前向查找匹配
  1465. if not match_nums:
  1466. if entity.label != 5 and entity.values[entity.label] > 0.5 and index != 0:
  1467. previous_entity = split_entitys[index - 1]
  1468. if previous_entity.entity_type == 'person' and previous_entity.label in [1, 2, 3]:
  1469. if entity.label in [2, 3, 4] and previous_entity.label in [1, 2]:
  1470. continue
  1471. if previous_entity.sentence_index == entity.sentence_index:
  1472. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1473. tokens_num_dict[
  1474. previous_entity.sentence_index] + previous_entity.end_index)
  1475. if distance < 20:
  1476. # 距离相等时,前向添加处罚值
  1477. # distance += 1
  1478. # 前向 没有 /10000
  1479. value = (-1 / 2 * (distance ** 2))
  1480. match_list2.append(Match(entity, previous_entity, value))
  1481. # print(match_list2)
  1482. match_list2 = [mat for mat in match_list2 if mat.main_role not in linked_company and mat.attribute not in linked_person]
  1483. # print(match_list2)
  1484. # km算法分配求解
  1485. result2 = dispatch(match_list2)
  1486. # print(result2)
  1487. linked_person = []
  1488. linked_persons_with = []
  1489. for match in result2:
  1490. entity = match[0]
  1491. # print(entity.entity_text)
  1492. # print(match.attribute)
  1493. entity_index = list_entity.index(entity)
  1494. is_update = False
  1495. if isinstance(match[1], tuple):
  1496. person_ = ''
  1497. phone_ = [match[1][1]]
  1498. else:
  1499. person_ = match[1].entity_text
  1500. phone_ = [i.entity_text for i in match[1].person_phone] if match[1].person_phone else []
  1501. for k in PackDict.keys():
  1502. for i in range(len(PackDict[k]["roleList"])):
  1503. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1504. if not PackDict[k]["roleList"][i].linklist:
  1505. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 0:
  1506. if person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0 and person_ not in winter_contact:
  1507. if not phone_:
  1508. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  1509. for p in phone_:
  1510. PackDict[k]["roleList"][i].linklist.append((person_, p))
  1511. is_update = True
  1512. elif PackDict[k]["roleList"][i].role_name == "agency":
  1513. if not PackDict[k]["roleList"][i].linklist:
  1514. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 1 and person_ not in winter_contact:
  1515. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0:
  1516. if not phone_:
  1517. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  1518. for p in phone_:
  1519. PackDict[k]["roleList"][i].linklist.append((person_, p))
  1520. is_update = True
  1521. else:
  1522. if PackDict[k]["roleList"][i].entity_text == entity.entity_text:
  1523. if not PackDict[k]["roleList"][i].linklist:
  1524. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0 and \
  1525. person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0:
  1526. if not phone_:
  1527. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  1528. for p in phone_:
  1529. PackDict[k]["roleList"][i].linklist.append((person_, p))
  1530. is_update = True
  1531. if not person_:
  1532. is_update = False
  1533. if is_update:
  1534. # 更新 list_entity
  1535. if not list_entity[entity_index].pointer_person:
  1536. list_entity[entity_index].pointer_person = []
  1537. list_entity[entity_index].pointer_person.append(match[1])
  1538. linked_person.append(match[1])
  1539. linked_persons_with.append(entity)
  1540. # 一个公司对应多个联系人的补充
  1541. person_entitys = [entity for entity in list_entity if entity.entity_type=='person']
  1542. person_entitys = person_entitys[::-1]
  1543. for index in range(len(person_entitys)):
  1544. entity = person_entitys[index]
  1545. prepare_link = []
  1546. if entity not in linked_person:
  1547. prepare_link.append(entity)
  1548. last_person = entity
  1549. for after_index in range(index + 1, min(len(person_entitys), index + 5)):
  1550. after_entity = person_entitys[after_index]
  1551. if after_entity.sentence_index==last_person.sentence_index and last_person.begin_index-after_entity.end_index<5:
  1552. if after_entity in linked_person:
  1553. _index = linked_person.index(after_entity)
  1554. with_company = linked_persons_with[_index]
  1555. for i in range(len(PackDict["Project"]["roleList"])):
  1556. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  1557. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 0:
  1558. for item in prepare_link:
  1559. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  1560. for _p in person_phone:
  1561. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  1562. with_company.pointer_person.append(item)
  1563. linked_person.append(item)
  1564. elif PackDict["Project"]["roleList"][i].role_name == "agency":
  1565. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 1:
  1566. for item in prepare_link:
  1567. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  1568. for _p in person_phone:
  1569. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  1570. with_company.pointer_person.append(item)
  1571. linked_person.append(item)
  1572. else:
  1573. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text:
  1574. for item in prepare_link:
  1575. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  1576. for _p in person_phone:
  1577. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  1578. with_company.pointer_person.append(item)
  1579. linked_person.append(item)
  1580. break
  1581. else:
  1582. prepare_link.append(after_entity)
  1583. last_person = after_entity
  1584. continue
  1585. # 统一同类角色的属性
  1586. if PackDict.get("Project"):
  1587. for i in range(len(PackDict["Project"]["roleList"])):
  1588. # if PackDict["Project"]["roleList"][i].role_name in ["tenderee","agency"]:
  1589. for _entity in list_entity:
  1590. if _entity.entity_type in ['org','company']:
  1591. is_similar = False
  1592. # entity_text相同
  1593. if _entity.entity_text==PackDict["Project"]["roleList"][i].entity_text:
  1594. is_similar = True
  1595. # entity.label为【0,1】
  1596. if _entity.label in [0,1] and dict_role_id[str(_entity.label)]==PackDict["Project"]["roleList"][i].role_name:
  1597. is_similar = True
  1598. if is_similar:
  1599. linked_entitys = _entity.linked_entitys
  1600. if linked_entitys:
  1601. for linked_entity in linked_entitys:
  1602. pointer_person = linked_entity.pointer_person if linked_entity.pointer_person else []
  1603. for _pointer_person in pointer_person:
  1604. _phone = [p.entity_text for p in _pointer_person.person_phone] if _pointer_person.person_phone else []
  1605. for _p in _phone:
  1606. if (_pointer_person.entity_text,_p) not in PackDict["Project"]["roleList"][i].linklist:
  1607. PackDict["Project"]["roleList"][i].linklist.append((_pointer_person.entity_text,_p))
  1608. # "roleList"中联系人电话去重
  1609. for i in range(len(PackDict["Project"]["roleList"])):
  1610. # print(123, PackDict["Project"]["roleList"][i].linklist)
  1611. # 带有联系人的电话
  1612. with_person = [person_phone[1] for person_phone in PackDict["Project"]["roleList"][i].linklist if person_phone[0]]
  1613. # 带有电话的联系人
  1614. with_phone = [person_phone[0] for person_phone in PackDict["Project"]["roleList"][i].linklist if person_phone[1]]
  1615. remove_list = []
  1616. for item in PackDict["Project"]["roleList"][i].linklist:
  1617. if not item[0]:
  1618. if item[1] in with_person:
  1619. # 删除重复的无联系人电话
  1620. remove_list.append(item)
  1621. elif not item[1]:
  1622. if item[0] in with_phone:
  1623. remove_list.append(item)
  1624. for _item in remove_list:
  1625. PackDict["Project"]["roleList"][i].linklist.remove(_item)
  1626. # # 1)第一个公司实体的招标人,则看看下一个实体是否为代理人,如果是则联系人错位连接 。2)在同一句中往后找联系人。3)连接不上在整个文章找联系人。
  1627. # temp_ent_list = [] # 临时列表,记录0,1角色及3联系人
  1628. # other_person = [] # 阈值以上的联系人列表
  1629. # link_person = [] # 有电话没联系上角色的person列表
  1630. # other_ent = []
  1631. # link_ent = []
  1632. # found_person = False
  1633. # ent_list = []
  1634. # for entity in list_entity:
  1635. # if entity.entity_type in ['org','company','person']:
  1636. # ent_list.append(entity)
  1637. # # ent_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  1638. # #for list_index in range(len(ent_list)):
  1639. # #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 \
  1640. # #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']:
  1641. # #ent_list[list_index+1], ent_list[list_index+2] = ent_list[list_index+2], ent_list[list_index+1]
  1642. # # 2020/11/25增加确定角色联系人判断
  1643. # sure_person_set = set([entity.entity_text for entity in ent_list if entity.entity_type == 'person' and entity.label in [1, 2]])
  1644. # # 招标/代理在同一句中交叉情况的处理
  1645. # for index in range(len(ent_list)):
  1646. # entity = ent_list[index]
  1647. # if entity.entity_text in roleSet and entity.label in [0, 1] and index+3<len(ent_list):
  1648. # if entity.sentence_index==ent_list[index+1].sentence_index==ent_list[index+2].sentence_index==ent_list[index+3].sentence_index:
  1649. # if ent_list[index+1].begin_index - entity.end_index < 30:
  1650. # 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:
  1651. # if ent_list[index+2].entity_type=="person" and ent_list[index+3].entity_type=="person" and \
  1652. # ent_list[index+2].label==3 and ent_list[index+3].label==3:
  1653. # ent_list[index + 1], ent_list[index + 2] = ent_list[index + 2], ent_list[index + 1]
  1654. #
  1655. #
  1656. # for index in range(len(ent_list)):
  1657. # entity = ent_list[index]
  1658. # if entity.entity_type=="person":
  1659. # if str(entity.label) == "0": # 2020/11/25 非联系人直接跳过
  1660. # continue
  1661. # if entity.values[entity.label]>on_value_person:
  1662. # if str(entity.label)=="1":
  1663. # for i in range(len(PackDict["Project"]["roleList"])):
  1664. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  1665. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  1666. # link_person.append(entity.entity_text)
  1667. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  1668. # # add pointer_person
  1669. # for _entity in list_entity:
  1670. # if dict_role_id.get(str(_entity.label))=="tenderee":
  1671. # for i in range(len(PackDict["Project"]["roleList"])):
  1672. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  1673. # _entity.pointer_person = entity
  1674. # elif str(entity.label)=="2":
  1675. # for i in range(len(PackDict["Project"]["roleList"])):
  1676. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  1677. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  1678. # link_person.append(entity.entity_text)
  1679. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  1680. # # add pointer_person
  1681. # for _entity in list_entity:
  1682. # if dict_role_id.get(str(_entity.label))=="agency":
  1683. # for i in range(len(PackDict["Project"]["roleList"])):
  1684. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  1685. # _entity.pointer_person = entity
  1686. # elif str(entity.label)=="3":
  1687. # if entity.entity_text in sure_person_set: # 2020/11/25 排除已经确定角色的联系人
  1688. # continue
  1689. # #not_link_person.append((entity_after.entity_text,entity_after.person_phone))
  1690. # other_person.append(entity.entity_text)
  1691. # temp_ent_list.append((entity.entity_text,entity.person_phone,entity))
  1692. #
  1693. # #if entity.entity_text in roleSet:
  1694. # if entity.entity_text in roleSet:
  1695. # if entity.label in [0,1]:
  1696. # other_ent.append(entity.entity_text)
  1697. # temp_ent_list.append((entity.entity_text, entity.label,entity))
  1698. # for behind_index in range(index+1, len(ent_list)):
  1699. # entity_after = ent_list[behind_index]
  1700. # if entity_after.sentence_index-entity.sentence_index>=1 or entity_after.entity_type in ['org','company']: # 只在本句中找联系人
  1701. # break
  1702. # if entity_after.values is not None:
  1703. # if entity_after.entity_type=="person":
  1704. # if str(entity_after.label) == "0": # 2020/11/25角色后面为非联系人 停止继续往后找
  1705. # break
  1706. # if entity_after.values[entity_after.label]>on_value_person:
  1707. # if str(entity_after.label)=="1":
  1708. # for i in range(len(PackDict["Project"]["roleList"])):
  1709. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  1710. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1711. # link_person.append(entity_after.entity_text)
  1712. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  1713. # elif str(entity_after.label)=="2":
  1714. # for i in range(len(PackDict["Project"]["roleList"])):
  1715. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  1716. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1717. # link_person.append(entity_after.entity_text)
  1718. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  1719. # elif str(entity_after.label)=="3":
  1720. # if entity_after.entity_text in sure_person_set: # 2020/11/25 如果姓名已经出现在确定角色联系人中则停止往后找
  1721. # break
  1722. # elif entity_after.begin_index - entity.end_index > 30:#2020/10/25 如果角色实体与联系人实体间隔大于阈值停止
  1723. # break
  1724. # for pack in PackDict.keys():
  1725. # for i in range(len(PackDict[pack]["roleList"])):
  1726. # if PackDict[pack]["roleList"][i].entity_text==entity.entity_text:
  1727. # #if entity_after.sentence_index-entity.sentence_index>1 and len(roleList[i].linklist)>0:
  1728. # #break
  1729. # PackDict[pack]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1730. # link_person.append(entity_after.entity_text)
  1731. # #add pointer_person
  1732. # entity.pointer_person = entity_after
  1733. #
  1734. # not_link_person = [person for person in other_person if person not in link_person]
  1735. # not_link_ent = [ent for ent in other_ent if ent not in link_ent]
  1736. # if len(not_link_person) > 0 and len(not_link_ent) > 0 :
  1737. # item = temp_ent_list
  1738. # for i in range(len(item)):
  1739. # if item[i][0] in not_link_ent and item[i][1] == 0 and i+3 < len(item):
  1740. # 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:
  1741. # item[i+1], item[i+2] = item[i+2], item[i+1]
  1742. # for i in range(len(item)-1, -1, -1):
  1743. # if item[i][0] in not_link_ent:
  1744. # for pack in PackDict.keys():
  1745. # for role in PackDict[pack]["roleList"]:
  1746. # if role.entity_text == item[i][0] and len(role.linklist) < 1:
  1747. # for j in range(i+1, len(item)):
  1748. # if item[j][0] in not_link_person:
  1749. # role.linklist.append(item[j][:2])
  1750. # #add pointer_person
  1751. # item[i][2].pointer_person = item[j][2]
  1752. # break
  1753. # else:
  1754. # break
  1755. # # 电话没有联系人的处理
  1756. # role_with_no_phone = []
  1757. # for i in range(len(PackDict["Project"]["roleList"])):
  1758. # if PackDict["Project"]["roleList"][i].role_name in ["tenderee","agency"]:
  1759. # if len(PackDict["Project"]["roleList"][i].linklist)==0: # 找出没有联系人的招标/代理人
  1760. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  1761. # else:
  1762. # phone_nums = 0
  1763. # for link in PackDict["Project"]["roleList"][i].linklist:
  1764. # if link[1]:
  1765. # phone_nums += 1
  1766. # break
  1767. # if not phone_nums:
  1768. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  1769. # if role_with_no_phone:
  1770. # phone_with_person = [entity.person_phone for entity in list_entity if entity.entity_type == "person"]
  1771. # # phone_with_person = [phone for phone in phone_with_person if phone]
  1772. #
  1773. # dict_index_sentence = {}
  1774. # for _sentence in list_sentence:
  1775. # dict_index_sentence[_sentence.sentence_index] = _sentence
  1776. # new_entity_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  1777. # for index in range(len(new_entity_list)):
  1778. # entity = new_entity_list[index]
  1779. # if entity.entity_text in role_with_no_phone:
  1780. # e_sentence = dict_index_sentence[entity.sentence_index]
  1781. # entity_right = e_sentence.tokens[entity.end_index:entity.end_index+40]
  1782. # entity_right = "".join(entity_right)
  1783. # if index+1<len(new_entity_list) and entity_right.find(new_entity_list[index+1].entity_text)>-1:
  1784. # entity_right = entity_right[:entity_right.find(new_entity_list[index+1].entity_text)]
  1785. # have_phone = re.findall(phone,entity_right)
  1786. # if have_phone:
  1787. # _phone = have_phone[0]
  1788. # phone_begin = entity_right.find(_phone)
  1789. # if _phone not in phone_with_person and re.search(key_phone,entity_right[:phone_begin]):
  1790. # # entity.person_phone = _phone
  1791. # for i in range(len(PackDict["Project"]["roleList"])):
  1792. # if PackDict["Project"]["roleList"][i].entity_text == entity.entity_text:
  1793. # PackDict["Project"]["roleList"][i].linklist.append(('', _phone))
  1794. #寻找多标段招标金额
  1795. p_entity = len(list_entity)-1
  1796. set_tenderer_money = set()
  1797. list_tenderer_money = [] #2021/7/16 新增列表,倒序保存所有中标金额
  1798. unit_list = [] #2021/8/17 新增,保存金额单位
  1799. #遍历所有实体
  1800. while(p_entity>=0):
  1801. entity = list_entity[p_entity]
  1802. if entity.entity_type=="money":
  1803. if entity.values[entity.label]>=on_value:
  1804. if str(entity.label)=="1":
  1805. set_tenderer_money.add(float(entity.entity_text))
  1806. list_tenderer_money.append(float(entity.entity_text)) # 2021/7/16 新增列表,倒序保存所有中标金额
  1807. unit_list.append(entity.money_unit)
  1808. # if str(entity.label)=="0":
  1809. if str(entity.label)=="0" and entity.notes!='总投资':
  1810. '''
  1811. if p_entity>0:
  1812. p_before = list_entity[p_entity-1]
  1813. 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:
  1814. p_entity -= 1
  1815. continue
  1816. '''
  1817. packagePointer,_flag = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label),MAX_DIS=2,DIRECT="L")
  1818. if packagePointer is None:
  1819. packageName = "Project"
  1820. else:
  1821. packageName = packagePointer.entity_text
  1822. if packageName=="Project":
  1823. # if PackDict["Project"]["tendereeMoney"]<float(entity.entity_text):
  1824. # PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  1825. if entity.values[entity.label]>on_value:
  1826. PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  1827. PackDict["Project"]["tendereeMoneyUnit"] = entity.money_unit
  1828. else:
  1829. PackDict[packageName]["tendereeMoney"] = float(entity.entity_text)
  1830. PackDict[packageName]["tendereeMoneyUnit"] = entity.money_unit
  1831. #add pointer_tendereeMoney
  1832. packagePointer.pointer_tendereeMoney = entity
  1833. p_entity -= 1
  1834. #删除一个机构有多个角色的数据
  1835. #删除重复人、概率不回传
  1836. final_roleList = []
  1837. list_pop = []
  1838. set_tenderer_role = set()
  1839. dict_pack_tenderer_money = dict()
  1840. for pack in PackDict.keys():
  1841. #删除无效包
  1842. if PackDict[pack]["code"]=="" and PackDict[pack]["tendereeMoney"]==0 and len(PackDict[pack]["roleList"])==0:
  1843. list_pop.append(pack)
  1844. for i in range(len(PackDict[pack]["roleList"])):
  1845. if PackDict[pack]["roleList"][i].role_name=="win_tenderer":
  1846. if PackDict[pack]["roleList"][i].money==0:
  1847. set_tenderer_role.add(PackDict[pack]["roleList"][i])
  1848. dict_pack_tenderer_money[pack] = [PackDict[pack]["roleList"][i],set()]
  1849. #找到包的中投标金额
  1850. for _index in range(len(PackageList)):
  1851. if "hit" in PackageList[_index]:
  1852. for _hit in list(PackageList[_index]["hit"]):
  1853. _money = float(_hit.split("-")[1]) if _hit.split("-")[0]=="money" else None
  1854. if PackageList[_index]["name"] in dict_pack_tenderer_money and _money is not None:
  1855. dict_pack_tenderer_money[PackageList[_index]["name"]][1].add(_money)
  1856. #只找到一个中标人和中标金额
  1857. if len(set_tenderer_money)==1 and len(set_tenderer_role)==1:
  1858. list(set_tenderer_role)[0].money = list(set_tenderer_money)[0]
  1859. list(set_tenderer_role)[0].money_unit = unit_list[0]
  1860. # print('一个中标人一个金额:', list(set_tenderer_money)[0])
  1861. #找到一个中标人和多个招标金额
  1862. if len(set_tenderer_money)>1 and len(set_tenderer_role)==1:
  1863. _maxMoney = 0
  1864. _sumMoney = 0
  1865. for _m in list(set_tenderer_money):
  1866. _sumMoney += _m
  1867. if _m>_maxMoney:
  1868. _maxMoney = _m
  1869. if _sumMoney/_maxMoney==2:
  1870. list(set_tenderer_role)[0].money = _maxMoney
  1871. # print('一人多金额分项合计 取最大金额:', _maxMoney)
  1872. else:
  1873. # list(set_tenderer_role)[0].money = _maxMoney
  1874. if min(list_tenderer_money)>200000 and list_tenderer_money[-1]/min(list_tenderer_money)>9000:
  1875. list(set_tenderer_role)[0].money = min(list_tenderer_money)
  1876. list(set_tenderer_role)[0].money_unit = unit_list[list_tenderer_money.index(min(list_tenderer_money))]
  1877. # print('一人多金额 且最小的大于20万第一个金额比最小金额大几千倍的最小中标金额:', min(list_tenderer_money))
  1878. else:
  1879. list(set_tenderer_role)[0].money = list_tenderer_money[-1] # 2021/7/16 修改 不是单价合计方式取第一个中标金额
  1880. list(set_tenderer_role)[0].money_unit = unit_list[-1] # 金额单位
  1881. # print('一人多金额 取第一个中标金额:', list_tenderer_money[-1])
  1882. #每个包都只找到一个金额
  1883. _flag_pack_money = True
  1884. for k,v in dict_pack_tenderer_money.items():
  1885. if len(v[1])!=1:
  1886. _flag_pack_money = False
  1887. if _flag_pack_money and len(PackageSet)==len(dict_pack_tenderer_money.keys()):
  1888. for k,v in dict_pack_tenderer_money.items():
  1889. v[0].money = list(v[1])[0]
  1890. # print('k,v in dict_pack_tenderer_money.items', k, v)
  1891. # 2021/7/16 #增加判断中标金额是否远大于招标金额逻辑
  1892. for pack in PackDict.keys():
  1893. for i in range(len(PackDict[pack]["roleList"])):
  1894. if PackDict[pack]["tendereeMoney"] > 0:
  1895. # print('金额数据类型:',type(PackDict[pack]["roleList"][i].money))
  1896. if float(PackDict[pack]["roleList"][i].money) >10000000 and \
  1897. float(PackDict[pack]["roleList"][i].money)/float(PackDict[pack]["tendereeMoney"])>=1000:
  1898. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  1899. # print('招标金额校正中标金额')
  1900. # 2021/7/19 #增加判断中标金额是否远大于第二三中标金额
  1901. for pack in PackDict.keys():
  1902. tmp_moneys = []
  1903. for i in range(len(PackDict[pack]["roleList"])):
  1904. if float(PackDict[pack]["roleList"][i].money) >100000:
  1905. tmp_moneys.append(float(PackDict[pack]["roleList"][i].money))
  1906. if len(tmp_moneys)>2 and max(tmp_moneys)/min(tmp_moneys)>1000:
  1907. for i in range(len(PackDict[pack]["roleList"])):
  1908. if float(PackDict[pack]["roleList"][i].money)/min(tmp_moneys)>1000:
  1909. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  1910. # print('通过其他中标人投标金额校正中标金额')
  1911. for pack in PackDict.keys():
  1912. for i in range(len(PackDict[pack]["roleList"])):
  1913. PackDict[pack]["roleList"][i] = PackDict[pack]["roleList"][i].getString()
  1914. for item in list_pop:
  1915. PackDict.pop(item)
  1916. return PackDict
  1917. def initPackageAttr(RoleList,PackageSet):
  1918. '''
  1919. @summary: 根据拿到的roleList和packageSet初始化接口返回的数据
  1920. '''
  1921. packDict = dict()
  1922. packDict["Project"] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  1923. for item in list(PackageSet):
  1924. packDict[item] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  1925. for item in RoleList:
  1926. if packDict[item.packageName]["code"] =="":
  1927. packDict[item.packageName]["code"] = item.packageCode
  1928. # packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[]))
  1929. packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[])) #Role(角色名称,实体名称,角色阈值,金额,金额阈值,连接列表,金额单位)
  1930. return packDict
  1931. def getPackageRoleMoney(list_sentence,list_entity):
  1932. '''
  1933. @param:
  1934. list_sentence:文章的句子list
  1935. list_entity:文章的实体list
  1936. @return: 拿到文章的包-标段号-角色-实体名称-金额-联系人-联系电话
  1937. '''
  1938. # print("=1")
  1939. theRole = getRoleList(list_sentence,list_entity)
  1940. if not theRole:
  1941. return []
  1942. RoleList,RoleSet,PackageList,PackageSet = theRole
  1943. '''
  1944. for item in PackageList:
  1945. # print(item)
  1946. '''
  1947. # print("=2")
  1948. PackDict = initPackageAttr(RoleList, PackageSet)
  1949. # print("=3")
  1950. PackDict = findAttributeAfterEntity(PackDict, RoleSet, PackageList, PackageSet, list_entity, list_sentence)
  1951. # print("=4")
  1952. return PackDict
  1953. def turnBidWay(bidway):
  1954. if bidway in ("邀请招标","采购方式:邀请"):
  1955. return "邀请招标"
  1956. elif bidway in ("询价","询单","询比","采购方式:询价"):
  1957. return "询价"
  1958. elif bidway in ("竞谈","竞争性谈判","公开竞谈"):
  1959. return "竞争性谈判"
  1960. elif bidway in ("竞争性磋商","磋商"):
  1961. return "竞争性磋商"
  1962. elif bidway in ("竞价","竞标","电子竞价","以电子竞价","电子书面竞投"):
  1963. return "竞价"
  1964. elif bidway in ("公开招标","网上电子投标","网上招标","采购方式:公开","招标为其他"):
  1965. return "公开招标"
  1966. elif bidway in ("单一来源"):
  1967. return "单一来源"
  1968. elif bidway in ("比选"):
  1969. return "比选"
  1970. else:
  1971. return "其他"
  1972. def getOtherAttributes(list_entity):
  1973. dict_other = {"bidway":"",
  1974. "moneysource":"",
  1975. "person_review":[],
  1976. "time_release":"",
  1977. "time_bidopen":"",
  1978. "time_bidclose":"",
  1979. "serviceTime":"",
  1980. "product":[],
  1981. "total_tendereeMoney":0,
  1982. "total_tendereeMoneyUnit":''}
  1983. for entity in list_entity:
  1984. if entity.entity_type == 'bidway':
  1985. dict_other["bidway"] = turnBidWay(entity.entity_text)
  1986. elif entity.entity_type=='moneysource':
  1987. dict_other["moneysource"] = entity.entity_text
  1988. elif entity.entity_type=='serviceTime':
  1989. dict_other["serviceTime"] = entity.entity_text
  1990. elif entity.entity_type == 'time' and entity.label==1:
  1991. dict_other["time_release"] = timeFormat(entity.entity_text)
  1992. elif entity.entity_type == 'time' and entity.label==2:
  1993. dict_other["time_bidopen"] = timeFormat(entity.entity_text)
  1994. elif entity.entity_type == 'time' and entity.label == 3:
  1995. dict_other["time_bidclose"] = timeFormat(entity.entity_text)
  1996. elif entity.entity_type=="person" and entity.label ==4:
  1997. dict_other["person_review"].append(entity.entity_text)
  1998. elif entity.entity_type=='product':
  1999. dict_other["product"].append(entity.entity_text)
  2000. elif entity.entity_type=='money' and entity.notes=='总投资' and dict_other["total_tendereeMoney"]<float(entity.entity_text):
  2001. dict_other["total_tendereeMoney"] = float(entity.entity_text)
  2002. dict_other["total_tendereeMoneyUnit"] = entity.money_unit
  2003. dict_other["product"] = list(set(dict_other["product"]))
  2004. return dict_other
  2005. def getMoneyRange(RoleList):
  2006. pass
  2007. def getPREMs(list_sentences,list_entitys,list_articles):
  2008. '''
  2009. @param:
  2010. list_sentence:所有文章的句子list
  2011. list_entity:所有文章的实体list
  2012. @return:list of dict which include文章的包-角色-实体名称-金额-联系人-联系电话
  2013. '''
  2014. result = []
  2015. for list_sentence,list_entity,list_article in zip(list_sentences,list_entitys,list_articles):
  2016. RoleList = getPackageRoleMoney(list_sentence,list_entity)
  2017. result.append(dict({"prem":RoleList,"docid":list_article.doc_id},**getOtherAttributes(list_entity),
  2018. **{"fingerprint":list_article.fingerprint,"match_enterprise":list_article.match_enterprise,
  2019. "match_enterprise_type":list_article.match_enterprise_type,"process_time":getCurrent_date(),
  2020. "attachmentTypes":list_article.attachmentTypes}))
  2021. return result
  2022. if __name__=="__main__":
  2023. '''
  2024. conn = getConnection()
  2025. cursor = conn.cursor()
  2026. #sql = " select distinct A.doc_id from entity_mention A,test_predict_role B where A.entity_id=B.entity_id limit 200"
  2027. sql = " select B.doc_id,B.prem from articles_processed A, articles_validation B where A.id=B.doc_id "
  2028. result = []
  2029. cursor.execute(sql)
  2030. rows = cursor.fetchall()
  2031. count = 0
  2032. for row in rows:
  2033. count += 1
  2034. # print(count)
  2035. doc_id = row[0]
  2036. roleList = getPackageRoleMoney(doc_id)
  2037. result.append([doc_id,str(roleList),row[1]])
  2038. ''''''
  2039. with codecs.open("getAttribute.html","w",encoding="utf8") as f:
  2040. f.write('<html><head>\
  2041. <meta http-equiv="Content-Type"\
  2042. content="text/html; charset=UTF-8">\
  2043. </head>\
  2044. <body bgcolor="#FFFFFF">\
  2045. <table border="1">\
  2046. <tr>\
  2047. <td>doc_id</td>\
  2048. <td>角色</td>\
  2049. </tr>')
  2050. for item in result:
  2051. f.write("<tr>"+"<td>"+item[0]+"</td>"+"<td>"+item[1]+"</td>"+"<td>"+item[2]+"</td>"+"</tr>")
  2052. f.write("</table></body>")
  2053. '''