role_money.py 181 KB

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