getAttributes.py 243 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087
  1. from BiddingKG.dl.common.Utils import findAllIndex,debug,timeFormat,getCurrent_date,API_URL,uniform_package_name,money_process,getDigitsDic,isValidDate
  2. from BiddingKG.dl.interface.Entitys import PREM,Role,Entity
  3. from decimal import Decimal
  4. import re
  5. import copy
  6. import math
  7. import pandas as pd
  8. import os
  9. from scipy.optimize import linear_sum_assignment
  10. from BiddingKG.dl.interface.Entitys import Match
  11. import numpy as np
  12. def getTheRole(entity,role_list):
  13. '''
  14. @summary:根据实体名称拿到index
  15. @param:
  16. entity:实体名称
  17. role_list:角色list
  18. @return:该实体所在下标
  19. '''
  20. for role_index in range(len(role_list)):
  21. if entity in role_list[role_index]:
  22. return role_index
  23. return None
  24. dict_role_id = {"0":"tenderee",
  25. "1":"agency",
  26. "2":"win_tenderer",
  27. "3":"second_tenderer",
  28. "4":"third_tenderer"}
  29. role2id_dict = {"tenderee":0,
  30. "agency":1,
  31. "win_tenderer":2,
  32. "second_tenderer":3,
  33. "third_tenderer":4}
  34. def getPackage(packageList,sentence_index,begin_index,roleid,MAX_DIS=None,DIRECT=None):
  35. '''
  36. @param:
  37. packageList:文章的包的信息,包号-sent_index-词偏移-字偏移-[[前作用域句子,句内偏移],[后作用域句子,句内偏移]]-匹配集合
  38. sentence_index:实体所在的句子
  39. begin_index:实体所在句子的起始位置
  40. @return:公司实体所属的包
  41. @summary: 优化多标段,确定标段作用域之后,寻找作用域包含该实体的所有包,从前往后找到一个还没有该roleid的包返回,若找到的包都有roleid,则返回第一个,若没有找到包,返回None
  42. '''
  43. '''
  44. if len(packageList)==0:
  45. return None
  46. before_index = None
  47. after_index = None
  48. equal_index = None
  49. equal_count = 0
  50. for pack_index in range(len(packageList)):
  51. if packageList[pack_index][1]>sentence_index and after_index is None:
  52. after_index = pack_index
  53. if packageList[pack_index][1]<sentence_index:
  54. before_index = pack_index
  55. if packageList[pack_index][1]==sentence_index and equal_index is None:
  56. equal_index = pack_index
  57. #当前句子和之前句子未找到包
  58. if before_index is None and equal_index is None:
  59. return None
  60. else:
  61. if after_index is None:
  62. end_index = len(packageList)
  63. else:
  64. end_index = after_index
  65. #只在当前句子找到一个包号
  66. if end_index-max((before_index if before_index is not None else -1,equal_index if equal_index is not None else -1))==1:
  67. return packageList[end_index-1][0]
  68. else:
  69. for i in range(max((before_index if before_index is not None else -1,equal_index if equal_index is not None else -1)),end_index):
  70. if packageList[i][2]>int(begin_index):
  71. if packageList[i-1][4]:
  72. return packageList[i-1][0]
  73. else:
  74. if packageList[i][4]:
  75. return packageList[i-1][0]
  76. else:
  77. return packageList[i][0]
  78. return packageList[end_index-1][0]
  79. '''
  80. if len(packageList)==0:
  81. return None,False
  82. list_legalPack = []
  83. for pack_index in range(len(packageList)):
  84. if DIRECT=="L" and (packageList[pack_index]["sentence_index"]>sentence_index or (packageList[pack_index]["sentence_index"]==sentence_index and packageList[pack_index]["offsetWords_begin"]>begin_index)):
  85. continue
  86. if DIRECT=="R" and (packageList[pack_index]["sentence_index"]<sentence_index or (packageList[pack_index]["sentence_index"]==sentence_index and packageList[pack_index]["offsetwords_begin"]<begin_index)):
  87. continue
  88. if (packageList[pack_index]["scope"][0][0]<sentence_index or (packageList[pack_index]["scope"][0][0]==sentence_index and packageList[pack_index]["scope"][0][1]<=begin_index)) and (packageList[pack_index]["scope"][1][0]>sentence_index or (packageList[pack_index]["scope"][1][0]==sentence_index and packageList[pack_index]["scope"][1][1]>=begin_index)):
  89. if MAX_DIS is not None:
  90. if abs(sentence_index-packageList[pack_index]["sentence_index"])<=MAX_DIS:
  91. list_legalPack.append(pack_index)
  92. else:
  93. list_legalPack.append(pack_index)
  94. # if (packageList[pack_index]["scope"][0][0] < sentence_index
  95. # or (packageList[pack_index]["scope"][0][0] == sentence_index
  96. # and packageList[pack_index]["scope"][0][1] <= begin_index))
  97. # and (packageList[pack_index]["scope"][1][0] > sentence_index
  98. # or (packageList[pack_index]["scope"][1][0] == sentence_index
  99. # and packageList[pack_index]["scope"][1][1] >= begin_index)):
  100. # pass
  101. _flag = True
  102. for _index in list_legalPack:
  103. if roleid in packageList[_index]["hit"]:
  104. continue
  105. else:
  106. _flag = False
  107. packageList[_index]["hit"].add(roleid)
  108. return packageList[_index]["pointer"],_flag
  109. if len(list_legalPack)>0:
  110. return packageList[0]["pointer"],_flag
  111. return None,False
  112. #生成合法的组合
  113. def get_legal_comba(list_entity,dict_role_combination):
  114. #拿到一个包中所有合法的组合
  115. def circle_package(_dict_legal_combination):
  116. list_dict_role_first = []
  117. for _role in _dict_legal_combination:
  118. if len(list_dict_role_first)==0:
  119. for _entity in _dict_legal_combination[_role]:
  120. if _entity !="":
  121. list_dict_role_first.append({_role:_entity})
  122. else:
  123. list_dict_role_after = []
  124. _find_count = 0
  125. for _entity in _dict_legal_combination[_role]:
  126. if _entity !="":
  127. for _dict in list_dict_role_first:
  128. _flag = True
  129. for _key1 in _dict:
  130. if _entity==_dict[_key1]:
  131. #修改为招标人和代理人可以为同一个
  132. if str(_key1) in ["0","1"] and str(_role) in ["0","1"]:
  133. _flag = True
  134. else:
  135. _flag = False
  136. if _flag:
  137. _find_count += 1
  138. _new_dict = copy.copy(_dict)
  139. _new_dict[_role] = _entity
  140. if len(list_dict_role_after)>100000:
  141. break
  142. list_dict_role_after.append(_new_dict)
  143. else:
  144. # 2021/5/25 update,同一实体(entity_text)不同角色
  145. if len(list_dict_role_after) > 100000:
  146. break
  147. for _dict in list_dict_role_first:
  148. for _key1 in _dict:
  149. if _entity == _dict[_key1]:
  150. _new_dict = copy.copy(_dict)
  151. _new_dict.pop(_key1)
  152. _new_dict[_role] = _entity
  153. list_dict_role_after.append({_role:_entity})
  154. if len(list_dict_role_after)==0:
  155. pass
  156. else:
  157. list_dict_role_first.extend(list_dict_role_after)
  158. return list_dict_role_first
  159. def recursive_package(_dict_legal_combination,set_legal_entity,dict_one_selution,list_all_selution):
  160. last_layer = False
  161. #若是空组合则放回空
  162. if len(_dict_legal_combination.keys())==0:
  163. return []
  164. #递归到最后一层则修改状态
  165. if len(_dict_legal_combination.keys())==1:
  166. last_layer = True
  167. #取一个角色开始进行遍历
  168. _key_role = list(_dict_legal_combination.keys())[0]
  169. for item in _dict_legal_combination[_key_role]:
  170. copy_dict_one_selution = copy.copy(dict_one_selution)
  171. copy_dict_legal_combination = {}
  172. copy_set_legal_entity = copy.copy(set_legal_entity)
  173. #复制余下的所有角色,进行下一轮递归
  174. for _key in _dict_legal_combination.keys():
  175. if _key!=_key_role:
  176. copy_dict_legal_combination[_key] = _dict_legal_combination[_key]
  177. #修改为招标人和代理人可以为同一个
  178. if item !="":
  179. _flag = True
  180. if str(_key_role) in ["0","1"]:
  181. for _key_flag in copy_dict_one_selution:
  182. if _key_flag not in ["0","1"] and copy_dict_one_selution[_key_flag]==item:
  183. _flag = False
  184. else:
  185. for _key_flag in copy_dict_one_selution:
  186. if copy_dict_one_selution[_key_flag]==item:
  187. _flag = False
  188. if _flag:
  189. copy_dict_one_selution[_key_role] = item
  190. '''
  191. if item not in copy_set_legal_entity:
  192. if item !="":
  193. copy_dict_one_selution[_key_role] = item
  194. '''
  195. copy_set_legal_entity.add(item)
  196. if last_layer:
  197. list_all_selution.append(copy_dict_one_selution)
  198. else:
  199. recursive_package(copy_dict_legal_combination,copy_set_legal_entity,copy_dict_one_selution,list_all_selution)
  200. #递归匹配各个包的结果
  201. def recursive_packages(_dict_legal_combination,dict_one_selution,list_all_selution):
  202. last_layer = False
  203. if len(_dict_legal_combination.keys())==0:
  204. return []
  205. if len(_dict_legal_combination.keys())==1:
  206. last_layer = True
  207. _key_pack = list(_dict_legal_combination.keys())[0]
  208. for item in _dict_legal_combination[_key_pack]:
  209. copy_dict_one_selution = copy.copy(dict_one_selution)
  210. copy_dict_legal_combination = {}
  211. for _key in _dict_legal_combination.keys():
  212. if _key!=_key_pack:
  213. copy_dict_legal_combination[_key] = _dict_legal_combination[_key]
  214. for _key_role in item.keys():
  215. copy_dict_one_selution[_key_pack+"$$"+_key_role] = item[_key_role]
  216. if last_layer:
  217. list_all_selution.append(copy_dict_one_selution)
  218. else:
  219. recursive_packages(copy_dict_legal_combination,copy_dict_one_selution,list_all_selution)
  220. return list_all_selution
  221. #循环获取所有包组合
  222. def circle_pageages(_dict_legal_combination):
  223. list_all_selution = []
  224. for _key_pack in _dict_legal_combination.keys():
  225. list_key_selution = []
  226. for item in _dict_legal_combination[_key_pack]:
  227. _dict = dict()
  228. for _key_role in item.keys():
  229. _dict[_key_pack+"$$"+_key_role] = item[_key_role]
  230. list_key_selution.append(_dict)
  231. if len(list_all_selution)==0:
  232. list_all_selution = list_key_selution
  233. else:
  234. _list_all_selution = []
  235. for item_1 in list_all_selution:
  236. for item_2 in list_key_selution:
  237. _list_all_selution.append(dict(item_1,**item_2))
  238. list_all_selution = _list_all_selution
  239. return list_all_selution
  240. #拿到各个包解析之后的结果
  241. _dict_legal_combination = {}
  242. for packageName in dict_role_combination.keys():
  243. _list_all_selution = []
  244. # recursive_package(dict_role_combination[packageName], set(), {}, _list_all_selution)
  245. _list_all_selution = circle_package(dict_role_combination[packageName])
  246. '''
  247. # print("===1")
  248. # print(packageName)
  249. for item in _list_all_selution:
  250. # print(item)
  251. # print("===2")
  252. '''
  253. #去除包含子集
  254. list_all_selution_simple = []
  255. _list_set_all_selution = []
  256. for item_selution in _list_all_selution:
  257. item_set_selution = set()
  258. for _key in item_selution.keys():
  259. item_set_selution.add((_key,item_selution[_key]))
  260. _list_set_all_selution.append(item_set_selution)
  261. if len(_list_set_all_selution)>1000:
  262. _dict_legal_combination[packageName] = _list_all_selution
  263. continue
  264. for i in range(len(_list_set_all_selution)):
  265. be_included = False
  266. for j in range(len(_list_set_all_selution)):
  267. if i!=j:
  268. 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]):
  269. be_included = True
  270. if not be_included:
  271. list_all_selution_simple.append(_list_all_selution[i])
  272. _dict_legal_combination[packageName] = list_all_selution_simple
  273. _list_final_comba = []
  274. #对各个包的结果进行排列组合
  275. _comba_count = 1
  276. for _key in _dict_legal_combination.keys():
  277. _comba_count *= len(_dict_legal_combination[_key])
  278. #如果过大,则每个包只取概率最大的那个
  279. dict_pack_entity_prob = get_dict_entity_prob(list_entity)
  280. if _comba_count>250:
  281. new_dict_legal_combination = dict()
  282. for _key_pack in _dict_legal_combination.keys():
  283. MAX_PROB = -1000
  284. _MAX_PROB_COMBA = None
  285. for item in _dict_legal_combination[_key_pack]:
  286. # print(_key_pack,item)
  287. _dict = dict()
  288. for _key in item.keys():
  289. _dict[str(_key_pack)+"$$"+str(_key)] = item[_key]
  290. _prob = getSumExpectation(dict_pack_entity_prob, _dict)
  291. if _prob>MAX_PROB:
  292. MAX_PROB = _prob
  293. _MAX_PROB_COMBA = [item]
  294. if _MAX_PROB_COMBA is not None:
  295. new_dict_legal_combination[_key_pack] = _MAX_PROB_COMBA
  296. _dict_legal_combination = new_dict_legal_combination
  297. #recursive_packages(_dict_legal_combination, {}, _list_final_comba)
  298. _list_final_comba = circle_pageages(_dict_legal_combination)
  299. #除了Project包(招标人和代理人),其他包是不会有冲突的
  300. #查看是否有一个实体出现在了Project包和其他包中,如有,要进行裁剪
  301. _list_real_comba = []
  302. for dict_item in _list_final_comba:
  303. set_project = set()
  304. set_other = set()
  305. for _key in list(dict_item.keys()):
  306. if _key.split("$$")[0]=="Project":
  307. set_project.add(dict_item[_key])
  308. else:
  309. set_other.add(dict_item[_key])
  310. set_common = set_project&set_other
  311. if len(set_common)>0:
  312. dict_project = {}
  313. dict_not_project = {}
  314. for _key in list(dict_item.keys()):
  315. if dict_item[_key] in set_common:
  316. if str(_key.split("$$")[0])=="Project":
  317. dict_project[_key] = dict_item[_key]
  318. else:
  319. dict_not_project[_key] = dict_item[_key]
  320. else:
  321. dict_project[_key] = dict_item[_key]
  322. dict_not_project[_key] = dict_item[_key]
  323. _list_real_comba.append(dict_project)
  324. _list_real_comba.append(dict_not_project)
  325. else:
  326. _list_real_comba.append(dict_item)
  327. return _list_real_comba
  328. def get_dict_entity_prob(list_entity,on_value=0.5):
  329. dict_pack_entity_prob = {}
  330. for in_attachment in [False,True]:
  331. identified_role = []
  332. if in_attachment==True:
  333. identified_role = [value[0] for value in dict_pack_entity_prob.values()]
  334. for entity in list_entity:
  335. if entity.entity_type in ['org','company'] and entity.in_attachment==in_attachment:
  336. values = entity.values
  337. role_prob = float(values[int(entity.label)])
  338. _key = entity.packageName+"$$"+str(entity.label)
  339. if role_prob>=on_value and str(entity.label)!="5":
  340. _key_prob = _key+"$text$"+entity.entity_text
  341. if in_attachment == True:
  342. role_prob = 0.8 if role_prob>0.8 else role_prob #附件的概率修改低点
  343. # if entity.entity_text in identified_role: # 2023/7/3 注释掉,选取概率最大的作为连接概率
  344. # continue
  345. if _key_prob in dict_pack_entity_prob:
  346. # 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])
  347. # dict_pack_entity_prob[_key_prob] = [entity.entity_text, new_prob] #公司同角色多次出现概率累计
  348. if role_prob>dict_pack_entity_prob[_key_prob][1]:
  349. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  350. else:
  351. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  352. return dict_pack_entity_prob
  353. #计算合计期望
  354. def getSumExpectation(dict_pack_entity_prob,combination,on_value=0.5):
  355. '''
  356. expect = 0
  357. for entity in list_entity:
  358. if entity.entity_type in ['org','company']:
  359. values = entity.values
  360. role_prob = float(values[int(entity.label)])
  361. _key = entity.packageName+"$$"+str(entity.label)
  362. if role_prob>on_value and str(entity.label)!="5":
  363. if _key in combination.keys() and combination[_key]==entity.entity_text:
  364. expect += math.pow(role_prob,4)
  365. else:
  366. expect -= math.pow(role_prob,4)
  367. '''
  368. #修改为同一个实体只取对应包-角色的最大的概率值
  369. expect = 0
  370. dict_entity_prob = {}
  371. for _key_pack_entity in dict_pack_entity_prob:
  372. _key_pack = _key_pack_entity.split("$text$")[0]
  373. role_prob = dict_pack_entity_prob[_key_pack_entity][1]
  374. if _key_pack in combination.keys() and combination[_key_pack]==dict_pack_entity_prob[_key_pack_entity][0]:
  375. if _key_pack_entity in dict_entity_prob.keys():
  376. if dict_entity_prob[_key_pack_entity]<role_prob:
  377. dict_entity_prob[_key_pack_entity] = role_prob
  378. else:
  379. dict_entity_prob[_key_pack_entity] = role_prob
  380. else:
  381. if _key_pack_entity in dict_entity_prob.keys():
  382. if dict_entity_prob[_key_pack_entity]>-role_prob:
  383. dict_entity_prob[_key_pack_entity] = -role_prob
  384. else:
  385. dict_entity_prob[_key_pack_entity] = -role_prob
  386. # for entity in list_entity:
  387. # if entity.entity_type in ['org','company']:
  388. # values = entity.values
  389. # role_prob = float(values[int(entity.label)])
  390. # _key = entity.packageName+"$$"+str(entity.label)
  391. # if role_prob>=on_value and str(entity.label)!="5":
  392. # if _key in combination.keys() and combination[_key]==entity.entity_text:
  393. # _key_prob = _key+entity.entity_text
  394. # if _key_prob in dict_entity_prob.keys():
  395. # if dict_entity_prob[_key_prob]<role_prob:
  396. # dict_entity_prob[_key_prob] = role_prob
  397. # else:
  398. # dict_entity_prob[_key_prob] = role_prob
  399. # else:
  400. # _key_prob = _key+entity.entity_text
  401. # if _key_prob in dict_entity_prob.keys():
  402. # if dict_entity_prob[_key_prob]>-role_prob:
  403. # dict_entity_prob[_key_prob] = -role_prob
  404. # else:
  405. # dict_entity_prob[_key_prob] = -role_prob
  406. for _key in dict_entity_prob.keys():
  407. symbol = 1 if dict_entity_prob[_key]>0 else -1
  408. expect += symbol*math.pow(dict_entity_prob[_key],2)
  409. return expect
  410. def getRoleList(list_sentence,list_entity,on_value = 0.5):
  411. '''
  412. @summary: 搜索树,得到所有不矛盾的角色组合,取合计期望值最大的作为结果返回
  413. @param:
  414. list_sentence:文章所有的sentence
  415. list_entity:文章所有的实体
  416. on_value:概率阈值
  417. @return:文章的角色list
  418. '''
  419. pack = getPackagesFromArticle(list_sentence,list_entity)
  420. if pack is None:
  421. return None
  422. PackageList,PackageSet,dict_PackageCode = pack
  423. #拿到所有可能的情况
  424. dict_role_combination = {}
  425. tenderee_or_agency_set = set() # 记录所有预测为招标或代理的实体集合
  426. win_tenderer_set = set() # 记录所有预测为中标的实体集合
  427. # print(PackageList)
  428. #拿到各个实体的packageName,packageCode
  429. for entity in list_entity:
  430. if entity.entity_type in ['org','company']:
  431. #限制附件里角色values[label]最大概率prob
  432. max_prob = 0.85
  433. if str(entity.label)!="5" and entity.in_attachment:
  434. if entity.values[entity.label]>max_prob:
  435. entity.values[entity.label] = max_prob
  436. #过滤掉字数小于3个的实体
  437. if len(entity.entity_text)<=3:
  438. continue
  439. values = entity.values
  440. role_prob = float(values[int(entity.label)])
  441. if role_prob>=on_value and str(entity.label)!="5":
  442. if str(entity.label) in ["0","1"]:
  443. packageName = "Project"
  444. else:
  445. if len(PackageSet)>0:
  446. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"role-"+str(entity.label))
  447. if packagePointer is None:
  448. #continue
  449. packageName = "Project"
  450. # print(entity.entity_text, packageName,entity.sentence_index,entity.begin_index)
  451. else:
  452. #add pointer_pack
  453. entity.pointer_pack = packagePointer
  454. packageName = packagePointer.entity_text
  455. # print(entity.entity_text, packageName)
  456. else:
  457. packageName = "Project"
  458. find_flag = False
  459. if packageName in dict_PackageCode.keys():
  460. packageCode = dict_PackageCode[packageName]
  461. else:
  462. packageCode = ""
  463. entity.packageCode = packageCode
  464. role_name = dict_role_id.get(str(entity.label))
  465. entity.roleName = role_name
  466. entity.packageName = packageName
  467. if entity.packageName in dict_role_combination.keys():
  468. if str(entity.label) in dict_role_combination[entity.packageName].keys():
  469. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  470. else:
  471. dict_role_combination[entity.packageName][str(entity.label)] = set([entity.entity_text])
  472. else:
  473. dict_role_combination[entity.packageName] = {}
  474. #初始化空值
  475. roleIds = [0,1,2,3,4]
  476. for _roleId in roleIds:
  477. dict_role_combination[entity.packageName][str(_roleId)] = set([""])
  478. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  479. list_real_comba = get_legal_comba(list_entity,dict_role_combination)
  480. # print("===role_combination",dict_role_combination)
  481. # print("== real_comba",list_real_comba)
  482. #拿到最大期望值的组合
  483. max_index = 0
  484. max_expect = -100
  485. _index = 0
  486. dict_pack_entity_prob = get_dict_entity_prob(list_entity)
  487. for item_combination in list_real_comba:
  488. expect = getSumExpectation(dict_pack_entity_prob, item_combination)
  489. if expect>max_expect:
  490. max_index = _index
  491. max_expect = expect
  492. _index += 1
  493. RoleList = []
  494. RoleSet = set()
  495. if len(list_real_comba)>0:
  496. for _key in list_real_comba[max_index].keys():
  497. packageName = _key.split("$$")[0]
  498. label = _key.split("$$")[1]
  499. role_name = dict_role_id.get(str(label))
  500. entity_text = list_real_comba[max_index][_key]
  501. entity_prob = dict_pack_entity_prob.get(_key+'$text$'+entity_text, ['',0])[1]
  502. # entity_text = list_real_comba[max_index][_key][0]
  503. # entity_prob = list_real_comba[max_index][_key][1]
  504. if packageName in dict_PackageCode.keys():
  505. packagecode = dict_PackageCode.get(packageName)
  506. else:
  507. packagecode = ""
  508. RoleList.append(PREM(packageName,packagecode,role_name,entity_text,entity_prob,0,0.0,[]))
  509. if str(label) in ["0", "1"]:
  510. tenderee_or_agency_set.add(entity_text)
  511. elif str(label) in ["2"] and entity_prob > 0.8:
  512. win_tenderer_set.add(entity_text)
  513. if len(list_real_comba) > 1 and label == '2':
  514. multi_winner = []
  515. for comba in list_real_comba:
  516. tmp_ent = comba.get(_key, '')
  517. tmp_prob = dict_pack_entity_prob.get(_key+'$text$'+tmp_ent, ['',0])[1]
  518. if tmp_ent !='' and tmp_prob>0.8:
  519. multi_winner.append(comba[_key])
  520. if len(set(multi_winner)) > 1:
  521. RoleList[-1].multi_winner = multi_winner
  522. # print('RoleList: ', RoleList)
  523. RoleSet.add(entity_text)
  524. #根据最优树来修正list_entity中角色对包的连接
  525. for _entity in list_entity:
  526. if _entity.pointer_pack is not None:
  527. _pack_name = _entity.pointer_pack.entity_text
  528. _find_flag = False
  529. for _prem in RoleList:
  530. if _prem.packageName==_pack_name and _prem.entity_text==_entity.entity_text:
  531. _find_flag = True
  532. if not _find_flag:
  533. _entity.pointer_pack = None
  534. return RoleList,RoleSet,PackageList,PackageSet,win_tenderer_set,tenderee_or_agency_set
  535. def getPackageScopePattern():
  536. '''
  537. @summary: 获取包的作用域关键词
  538. '''
  539. df = pd.read_excel(os.path.dirname(__file__)+"/end.xls")
  540. pattern = "("
  541. for item in df["list_word"]:
  542. item = str(item).replace("(","\(").replace(")","\)").replace(".","\.").replace("[","\[").replace("]","\]").replace("-","\-")
  543. pattern += item+"|"
  544. pattern = pattern[:-1]+")[::是为]|业绩.{,30}标段[0-9A-Za-z一二三四五六七八九十]{0,3}"
  545. return pattern
  546. pattern_packageScope = getPackageScopePattern()
  547. def getPackagesFromArticle(list_sentence, list_entity):
  548. '''
  549. @param:
  550. list_sentence:文章的句子list
  551. @summary: 将包的信息插入list_entity中
  552. @return: type:list if [包号,句子index,词偏移,标段号] meaning:文章的包/标段信息
  553. '''
  554. if len(list_sentence) == 0:
  555. return None
  556. list_sentence.sort(key=lambda x: x.sentence_index)
  557. PackageList = []
  558. PackageList_scope = []
  559. PackageSet = set()
  560. dict_packageCode = dict()
  561. # package_number_pattern = re.compile(
  562. # '((施工|监理|监测|勘察|设计|劳务)(标段)?[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦa-zA-Z]{,4}(标段?|包))|(([a-zA-Z]包[:)]?)?第?[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦa-zA-Z]{1,4}标[段包]?)|((标[段号的包项]|([标分子]|合同|项目|采购|()包|包[组件号])[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦA-Za-z]{1,4})|(([,;。、:(]|第)[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}分?包)|([a-zA-Z][0-9]{,3}分?[包标])|.{,1}((包组|包件|包号|分?包|标[段号的包]|子项目)编?号?[::]?[a-zA-Z0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ-]+)|[,;。、:(]包[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}[^\w]') # 标号
  563. package_number_pattern = re.compile(
  564. '((施工|监理|监测|勘察|设计|劳务)(标段)?:?第?([一二三四五六七八九十]{1,3}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,3}|[a-zA-Z0-9]{1,9}\-?[a-zA-Z0-9-]{,9})?[分子]?(标[段包项]?|包[组件标]?|合同[包段]))\
  565. |(([a-zA-Z]包[:()]?)?第?([一二三四五六七八九十]{1,3}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,3}|[a-zA-Z0-9]{1,9}\-?[a-zA-Z0-9-]{,9})[分子]?(标[段包项]?|合同[包段]))\
  566. |(([,;。、:(]|第)?([一二三四五六七八九十]{1,3}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,3}|[a-zA-Z0-9]{1,9}\-?[a-zA-Z0-9-]{,9})[分子]?(标[段包项]?|包[组件标]?|合同[包段]))\
  567. |((标[段包项]|标段(包)|包[组件标]|[标分子(]包)(\[|【)?:?([一二三四五六七八九十]{1,3}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,3}|[a-zA-Z0-9]{1,9}\-?[a-zA-Z0-9-]{,9}))\
  568. |[,;。、:(](标的?|项目|子项目?)(\[|【)?:?([一二三四五六七八九十]+|[0-9]{1,9})\
  569. |((([标分子(]|合同|项目|采购)包|[,。]标的|子项目|[分子]标|标[段包项]|包[组件标]?)编?号[::]?[a-zA-Z0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ-]{1,9})\
  570. |[,;。、:(]?(合同|分|子)?包:?([一二三四五六七八九十]{1,3}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,3}|[a-zA-Z0-9]{1,9}\-?[a-zA-Z0-9-]{,9})')
  571. other_package_pattern = re.compile(
  572. '((项目|物资|设备|场次|标段|标的|产品)(名称)?)[::]([^,。]{2,50}?)[,。]') # # 2020/11/23 大网站规则 调整 package_N_name_pattern, package_N_name_pattern 中的项目 改为 子项目
  573. win_tenderer_pattern = re.compile('(中标候?选?人|供应商)(名称)?[::](.{2,25})[,。]') # 2020/11/23 大网站规则 调整
  574. model_pattern = re.compile('(型号|序号)[::]([^,。]{2,20})[,。]') # 2020/11/23 大网站规则 调整
  575. number_pattern = re.compile("[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}")
  576. package_code_pattern = re.compile("(?:编号[::]?\s*)([-\dA-Za-z\(\)]{1,20})")
  577. # 纯数字类型的包号统一,例如:'01','1'
  578. re_digital = re.compile("^\d+$")
  579. def changeIndexFromWordToWords(tokens, word_index):
  580. '''
  581. @summary:转换某个字的字偏移为词偏移
  582. '''
  583. before_index = 0
  584. after_index = 0
  585. for i in range(len(tokens)):
  586. after_index = after_index + len(tokens[i])
  587. if before_index <= word_index and after_index >= word_index:
  588. return i
  589. before_index = after_index
  590. package_names = []
  591. def extractPackageCode(tokens, word_index, size=20, pattern=package_code_pattern):
  592. '''
  593. @summary:抽取包附近的标段号
  594. @param:
  595. tokens:包所在句子的分词
  596. word_index:包所在字偏移
  597. size:左右各取多少个词
  598. pattern:提取标段号的正则
  599. @return: type:string,meaning:标段号
  600. '''
  601. index = changeIndexFromWordToWords(tokens, word_index)
  602. if index < size:
  603. begin = index
  604. else:
  605. begin = index - size
  606. if index + size > len(tokens):
  607. end = len(tokens)
  608. else:
  609. end = index + size
  610. # 拿到左右两边的词语组成短语
  611. text = "".join(tokens[begin:end])
  612. # 在短语中的字偏移
  613. new_word_index = word_index - len("".join(tokens[:begin]))
  614. min_distance = len(text)
  615. packageCode = None
  616. for the_iter in re.finditer(pattern, text):
  617. # 算出最小距离
  618. distance = min([abs(new_word_index - the_iter.span()[0]), abs(new_word_index - the_iter.span()[1])])
  619. if distance < min_distance:
  620. min_distance = distance
  621. packageCode = the_iter.group(1)
  622. return packageCode
  623. def get_package():
  624. PackageList_scope = []
  625. True_package = set()
  626. for i in range(len(list_sentence)):
  627. PackageList_item = []
  628. PackageList_item_scope = []
  629. content = list_sentence[i].sentence_text
  630. content = content.replace('号,', '号:').replace(':', ':').replace('(', '(').replace(')', ')')
  631. # .replace('-包',' 包').replace('包-', '包 ').replace('-标', ' 标').replace('标段-', '标段 ').replace('-合同包', ' 合同包') # 72760191 标段:№10
  632. content = re.sub('[一二三四五六七八九十\d](标[段包项]|包[组件标])编号', ' 标段编号', content)
  633. for it in re.finditer('CA标|(每个?|所有|相关|个|各|不分)[分子]?(标[段包项]?|包[组件标]?|合同包)|(质量|责任)三包|包[/每]|标段(划分|范围)|(承|压缩|软|皮|书|挂)包\
  634. |标[识注签贴配]|[商油]标号|第X包|第[一二三四五六七八九十]+至[一二三四五六七八九十]+(标[段包项]?|包[组件标]?|合同[包段])\
  635. |\.(docx|doc|pdf|xlsx|xls|jpg)|[一二三四五]次|五金|\d+[年月]|[\d.,]+万?元|\d+\.\d+', content):
  636. content = content.replace(it.group(0), ' ' * len(it.group(0)))
  637. tokens = list_sentence[i].tokens
  638. _names = []
  639. for iter in re.finditer(package_number_pattern, content):
  640. if re.search('(业绩|信誉要求):', content[:iter.start()]): # 前面有业绩或信誉的标段去掉
  641. continue
  642. # print('提取到标段:%s, 前后文:%s'%(iter.group(), content[iter.start()-5:iter.end()+5]))
  643. if re.match('\d', iter.group(0)) and re.search('\d\.$', content[:iter.start()]): # 排除2.10标段3 5.4标段划分 这种情况
  644. # print('过滤掉错误包:', iter.group())
  645. continue
  646. if re.search('[承每书/]包|XX|xx', iter.group(0)) or re.search('\d包[/每]\w|一包[0-9一二三四五六七八九十]+', content[iter.start():iter.end()+3]) or re.search('[a-zA-Z0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ-]{6,}', iter.group(0)):
  647. # print('过滤掉错误包:', iter.group())
  648. continue
  649. elif iter.end()+2 < len(content) and re.search('标准|标的物|标志|包装|划分|标书', content[iter.start():iter.end()+2]):
  650. # print('过滤掉错误包:',iter.group())
  651. continue
  652. elif re.search('同一(标段?|包)', content[max(0, iter.start()-2):iter.end()]): # 不得参加同一标段
  653. # print('过滤掉错误包:', iter.group())
  654. continue
  655. elif re.search('三包', content[max(0, iter.start()-2):iter.end()]) and re.search('第三包', content[max(0, iter.start()-2):iter.end()])==None: # 规规章和“三包”规定
  656. # print('过滤掉错误包:', iter.group())
  657. continue
  658. elif re.search('[1-9]\d{2,}$|\d{4,}|^[1-9]\d{2,}|合同包[A-Za-z]{2,}', iter.group(0)):
  659. # print('过滤掉错误包号5:', iter.group(0))
  660. continue
  661. temp_package_number = uniform_package_name(iter.group(0))
  662. True_package.add(temp_package_number)
  663. PackageList_item.append({"name": temp_package_number, "sentence_index": list_sentence[i].sentence_index,
  664. "offsetWords_begin": changeIndexFromWordToWords(tokens, iter.span()[0]),
  665. "offsetWord_begin": iter.span()[0], "offsetWord_end": iter.span()[1]})
  666. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  667. code = extractPackageCode(tokens, iter.span()[0])
  668. if code is not None:
  669. dict_packageCode[temp_package_number] = code
  670. PackageSet.add(temp_package_number)
  671. # 识别packageScope
  672. for iter in re.finditer(pattern_packageScope, content):
  673. PackageList_item_scope.append({"name": "", "sentence_index": list_sentence[i].sentence_index,
  674. "offsetWords_begin": changeIndexFromWordToWords(tokens, iter.span()[0]),
  675. "offsetWord_begin": iter.span()[0], "offsetWord_end": iter.span()[1]})
  676. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  677. PackageList_item_scope = PackageList_item + PackageList_item_scope
  678. PackageList_item_scope.sort(key=lambda x: x["offsetWord_begin"])
  679. PackageList_scope = PackageList_scope + PackageList_item_scope
  680. PackageList_item.sort(key=lambda x: x["sentence_index"])
  681. return PackageList_scope, True_package
  682. def get_win_project():
  683. '''获取多个项目多个中标人的项目'''
  684. PackageList_scope = []
  685. True_package = set()
  686. # 2020/11/23 大网站规则 调整
  687. if len(PackageSet) == 0 and len(
  688. set([it.entity_text for it in list_entity if
  689. it.entity_type in ['org', 'company'] and it.label == 2])) > 1:
  690. for i in range(len(list_sentence)):
  691. PackageList_item = []
  692. PackageList_item_scope = []
  693. content = list_sentence[i].sentence_text
  694. tokens = list_sentence[i].tokens
  695. names = re.findall(other_package_pattern, content)
  696. N_names = re.findall(win_tenderer_pattern, content)
  697. if len(names) != 1 or len(N_names) != 1:
  698. continue
  699. for iter in re.finditer(other_package_pattern, content):
  700. temp_package_number = iter.group(4)
  701. xinghao = re.search(model_pattern, content)
  702. if xinghao:
  703. temp_package_number = temp_package_number + '+' + xinghao.group(2)
  704. # print('新正则采购包名补充',temp_package_number)
  705. if re.search(re_digital, temp_package_number):
  706. temp_package_number = str(int(temp_package_number))
  707. True_package.add(temp_package_number)
  708. PackageList_item.append(
  709. {"name": temp_package_number, "sentence_index": list_sentence[i].sentence_index,
  710. "offsetWords_begin": changeIndexFromWordToWords(tokens, iter.span()[0]),
  711. "offsetWord_begin": iter.span()[0], "offsetWord_end": iter.span()[1]})
  712. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  713. code = extractPackageCode(tokens, iter.span()[0])
  714. if code is not None:
  715. dict_packageCode[temp_package_number] = code
  716. PackageSet.add(temp_package_number)
  717. # 识别packageScope
  718. for iter in re.finditer(pattern_packageScope, content):
  719. PackageList_item_scope.append({"name": "", "sentence_index": list_sentence[i].sentence_index,
  720. "offsetWords_begin": changeIndexFromWordToWords(tokens,
  721. iter.span()[0]),
  722. "offsetWord_begin": iter.span()[0],
  723. "offsetWord_end": iter.span()[1]})
  724. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  725. PackageList_item_scope = PackageList_item + PackageList_item_scope
  726. PackageList_item_scope.sort(key=lambda x: x["offsetWord_begin"])
  727. PackageList_scope = PackageList_scope + PackageList_item_scope
  728. PackageList_item.sort(key=lambda x: x["sentence_index"])
  729. return PackageList_scope, True_package
  730. def get_package_scope(PackageList_scope):
  731. PackageList = []
  732. pattern_punctuation = "[::()\(\),,。;;]"
  733. # print("===packageList_scope",PackageList_scope)
  734. for i in range(len(list_sentence)):
  735. for j in range(len(PackageList_scope)):
  736. if i == PackageList_scope[j]["sentence_index"] and PackageList_scope[j]["name"] != "":
  737. _flag = False
  738. left_str = list_sentence[i].sentence_text[
  739. PackageList_scope[j]["offsetWord_begin"] - 30:PackageList_scope[j][
  740. "offsetWord_begin"] + 1]
  741. right_str = list_sentence[i].sentence_text[
  742. PackageList_scope[j]["offsetWord_begin"]:PackageList_scope[j]["offsetWord_begin"] + 30]
  743. _left_find = re.findall(pattern_punctuation, left_str)
  744. _right_find = re.findall(pattern_punctuation, right_str)
  745. # print(left_str)
  746. if re.search("同", left_str[-1:]) is not None and PackageList_scope[j]["name"] == "一":
  747. continue
  748. if re.search("划分", right_str[:10]) is not None:
  749. continue
  750. if len(_left_find) > 0 and _left_find[-1] in [":", ":"]:
  751. _flag = True
  752. if len(_right_find) > 0 and _right_find[0] in [":", ":"]:
  753. _flag = True
  754. if _flag:
  755. scope_begin = [PackageList_scope[j]["sentence_index"],
  756. PackageList_scope[j]["offsetWords_begin"]]
  757. else:
  758. if j == 0:
  759. scope_begin = [0, 0]
  760. else:
  761. scope_begin = [PackageList_scope[j - 1]["sentence_index"],
  762. PackageList_scope[j - 1]["offsetWords_begin"]]
  763. if j == len(PackageList_scope) - 1:
  764. scope_end = [list_sentence[-1].sentence_index,
  765. changeIndexFromWordToWords(list_sentence[-1].tokens,
  766. len(list_sentence[
  767. -1].sentence_text))]
  768. else:
  769. scope_end = [PackageList_scope[j + 1]["sentence_index"],
  770. PackageList_scope[j + 1]["offsetWords_begin"]]
  771. if j>0 and PackageList_scope[j - 1]["sentence_index"] == PackageList_scope[j]["sentence_index"] and \
  772. PackageList_scope[j - 1]["offsetWord_begin"] <= PackageList_scope[j]["offsetWord_begin"] and \
  773. PackageList_scope[j - 1]["offsetWord_end"] >= PackageList_scope[j]["offsetWord_end"]:
  774. continue
  775. # add package to entity
  776. _pack_entity = Entity(doc_id=list_sentence[0].doc_id, entity_id="%s_%s_%s_%s" % (
  777. list_sentence[0].doc_id, i, PackageList_scope[j]["offsetWord_begin"],
  778. PackageList_scope[j]["offsetWord_begin"]), entity_text=PackageList_scope[j]["name"],
  779. entity_type="package", sentence_index=PackageList_scope[j]["sentence_index"],
  780. begin_index=changeIndexFromWordToWords(list_sentence[i].tokens,
  781. PackageList_scope[j][
  782. "offsetWord_begin"]),
  783. end_index=changeIndexFromWordToWords(list_sentence[i].tokens,
  784. PackageList_scope[j]["offsetWord_end"]),
  785. wordOffset_begin=PackageList_scope[j]["offsetWord_begin"],
  786. wordOffset_end=PackageList_scope[j]["offsetWord_end"],
  787. in_attachment=list_sentence[i].in_attachment)
  788. list_entity.append(_pack_entity)
  789. copy_pack = copy.copy(PackageList_scope[j])
  790. copy_pack["scope"] = [scope_begin, scope_end]
  791. copy_pack["hit"] = set()
  792. copy_pack["pointer"] = _pack_entity
  793. PackageList.append(copy_pack)
  794. return PackageList
  795. PackageList_scope, True_package = get_package()
  796. PackageList_scope2, True_package2 = get_win_project()
  797. if len(True_package2) > 2: # 同时包含多标段及多中标人的
  798. PackageList_scope = PackageList_scope + PackageList_scope2
  799. PackageList = get_package_scope(PackageList_scope)
  800. # if len(PackageSet)<2: # 20230922只提取到一个包号的去掉,都放在默认包project 2024/02/02 注释掉,防止多标段每篇公告只公布一个标段的没法提取标段号
  801. # return [], set(), {}
  802. return PackageList, PackageSet, dict_packageCode
  803. # km配对方法
  804. def dispatch(match_list):
  805. main_roles = list(set([match.main_role for match in match_list]))
  806. attributes = list(set([match.attribute for match in match_list]))
  807. label = np.zeros(shape=(len(main_roles), len(attributes)))
  808. for match in match_list:
  809. main_role = match.main_role
  810. attribute = match.attribute
  811. value = match.value
  812. label[main_roles.index(main_role), attributes.index(attribute)] = value + 10000
  813. # print(label)
  814. gragh = -label
  815. # km算法
  816. row, col = linear_sum_assignment(gragh)
  817. max_dispatch = [(i, j) for i, j, value in zip(row, col, gragh[row, col]) if value]
  818. # return [Match(main_roles[row], attributes[col]) for row, col in max_dispatch]
  819. return [(main_roles[row], attributes[col]) for row, col in max_dispatch]
  820. from BiddingKG.dl.common.Utils import getUnifyMoney
  821. from BiddingKG.dl.interface.modelFactory import Model_relation_extraction
  822. relationExtraction_model = Model_relation_extraction()
  823. def findAttributeAfterEntity(PackDict,roleSet,PackageList,PackageSet,list_sentence,list_entity,list_outline,on_value = 0.5,on_value_person=0.5,sentence_len=4):
  824. '''
  825. @param:
  826. PackDict:文章包dict
  827. roleSet:文章所有角色的公司名称
  828. PackageList:文章的包信息
  829. PackageSet:文章所有包的名称
  830. list_entity:文章所有经过模型处理的实体
  831. on_value:金额模型的阈值
  832. on_value_person:联系人模型的阈值
  833. sentence_len:公司和属性间隔句子的最大长度
  834. @return:添加了属性信息的角色list
  835. '''
  836. #根据roleid添加金额到rolelist中
  837. def addMoneyByRoleid(packDict,packageName,roleid,money,money_prob):
  838. for i in range(len(packDict[packageName]["roleList"])):
  839. if packDict[packageName]["roleList"][i].role_name==dict_role_id.get(str(roleid)):
  840. if money_prob>packDict[packageName]["roleList"][i].money_prob:
  841. packDict[packageName]["roleList"][i].money = money
  842. packDict[packageName]["roleList"][i].money_prob = money_prob
  843. return packDict
  844. #根据实体名称添加金额到rolelist中
  845. def addMoneyByEntity(packDict,packageName,entity,money,money_prob):
  846. for i in range(len(packDict[packageName]["roleList"])):
  847. if packDict[packageName]["roleList"][i].entity_text==entity:
  848. # if money_prob>packDict[packageName]["roleList"][i].money_prob:
  849. # packDict[packageName]["roleList"][i].money = money
  850. # packDict[packageName]["roleList"][i].money_prob = money_prob
  851. if packDict[packageName]["roleList"][i].money_prob==0 : # 2021/7/20第一次更新金额
  852. packDict[packageName]["roleList"][i].money = money.entity_text
  853. packDict[packageName]["roleList"][i].money_prob = money_prob
  854. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  855. elif money_prob>packDict[packageName]["roleList"][i].money_prob+0.2 or (money.notes in ['大写'] and money.in_attachment==False): # 2021/7/20改为优先选择大写金额,
  856. # print('已连接金额概率:money_prob:',packDict[packageName]["roleList"][i].money_prob)
  857. # print('链接金额备注 ',money.notes, money.entity_text, money.values)
  858. packDict[packageName]["roleList"][i].money = money.entity_text
  859. packDict[packageName]["roleList"][i].money_prob = money_prob
  860. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  861. # print('链接中的金额:{0}, 单位:{1}'.format(money.entity_text, money.money_unit))
  862. return packDict
  863. def addRatioByEntity(packDict,packageName,entity,ratio):
  864. for i in range(len(packDict[packageName]["roleList"])):
  865. if packDict[packageName]["roleList"][i].entity_text==entity:
  866. packDict[packageName]["roleList"][i].ratio = ratio.ratio_value
  867. def addServiceTimeByEntity(packDict,packageName,entity,serviceTime):
  868. for i in range(len(packDict[packageName]["roleList"])):
  869. if packDict[packageName]["roleList"][i].entity_text==entity:
  870. packDict[packageName]["roleList"][i].serviceTime = serviceTime.entity_text
  871. #根据实体名称得到角色
  872. def getRoleWithText(packDict,entity_text):
  873. for pack in packDict.keys():
  874. for i in range(len(packDict[pack]["roleList"])):
  875. if packDict[pack]["roleList"][i].entity_text==entity_text:
  876. return packDict[pack]["roleList"][i].role_name
  877. def doesEntityOrLinkedEntity_inRoleSet(entity,RoleSet):
  878. _list_entitys = [entity]+entity.linked_entitys
  879. for _entity in _list_entitys:
  880. if _entity.entity_text in RoleSet:
  881. return True
  882. p_entity = 0
  883. # 2021/7/19 顺序比较金额,前面是后面的一万倍则把前面金额/10000
  884. # money_list = [it for it in list_entity if it.entity_type=="money"]
  885. # for i in range(len(money_list)-1):
  886. # for j in range(1, len(money_list)):
  887. # if (float(money_list[i].entity_text) > 5000000000 or money_list[j].notes=='大写') and \
  888. # Decimal(money_list[i].entity_text)/Decimal(money_list[j].entity_text)==10000:
  889. # money_list[i].entity_text = str(Decimal(money_list[i].entity_text)/10000)
  890. # # print('连接前修改大于50亿金额:前面是后面的一万倍则把前面金额/10000')
  891. '''同样金额同时有元及万元单位的,把万元的金额改为元'''
  892. wanyuan = []
  893. yuan = []
  894. for it in list_entity:
  895. if it.entity_type == "money" and float(it.entity_text)>5000:
  896. if it.money_unit == '万元' or float(it.entity_text)>5000000000:
  897. wanyuan.append(it)
  898. if it.money_unit == '元' or float(it.entity_text)<5000000:
  899. yuan.append(it)
  900. if wanyuan != [] and yuan != []:
  901. for m1 in wanyuan:
  902. for m2 in yuan:
  903. if Decimal(m1.entity_text)/Decimal(m2.entity_text) == 10000:
  904. m1.entity_text = m2.entity_text
  905. #遍历所有实体
  906. # while(p_entity<len(list_entity)):
  907. # entity = list_entity[p_entity]
  908. '''
  909. #招标金额从后往前找
  910. if entity.entity_type=="money":
  911. if entity.values[entity.label]>=on_value:
  912. if str(entity.label)=="0":
  913. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  914. if packagePointer is None:
  915. packageName = "Project"
  916. else:
  917. packageName = packagePointer.entity_text
  918. addMoneyByRoleid(PackDict, packageName, "0", entity.entity_text, entity.values[entity.label])
  919. '''
  920. ''' # 2020/11/25 与下面的联系人连接步骤重复,取消
  921. if entity.entity_type=="person":
  922. if entity.values[entity.label]>=on_value_person:
  923. if str(entity.label)=="1":
  924. for i in range(len(PackDict["Project"]["roleList"])):
  925. if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  926. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  927. # add pointer_person
  928. for _entity in list_entity:
  929. if dict_role_id.get(str(_entity.label))=="tenderee":
  930. for i in range(len(PackDict["Project"]["roleList"])):
  931. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  932. _entity.pointer_person = entity
  933. elif str(entity.label)=="2":
  934. for i in range(len(PackDict["Project"]["roleList"])):
  935. if PackDict["Project"]["roleList"][i].role_name=="agency":
  936. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  937. # add pointer_person
  938. for _entity in list_entity:
  939. if dict_role_id.get(str(_entity.label))=="agency":
  940. for i in range(len(PackDict["Project"]["roleList"])):
  941. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  942. _entity.pointer_person = entity
  943. '''
  944. # #金额往前找实体
  945. # if entity.entity_type=="money":
  946. # if entity.values[entity.label]>=on_value:
  947. # p_entity_money= p_entity
  948. # entity_money = list_entity[p_entity_money]
  949. # if len(PackageSet)>0:
  950. # packagePointer,_ = getPackage(PackageList,entity_money.sentence_index,entity_money.begin_index,"money-"+str(entity_money.entity_text)+"-"+str(entity_money.label))
  951. # if packagePointer is None:
  952. # packageName_entity = "Project"
  953. # else:
  954. # packageName_entity = packagePointer.entity_text
  955. # else:
  956. # packageName_entity = "Project"
  957. # while(p_entity_money>0):
  958. # entity_before = list_entity[p_entity_money]
  959. # if entity_before.entity_type in ['org','company']:
  960. # if str(entity_before.label)=="1":
  961. # addMoneyByEntity(PackDict, packageName_entity, entity_before.entity_text, entity_money.entity_text, entity_money.values[entity_money.label])
  962. # #add pointer_money
  963. # entity_before.pointer_money = entity_money
  964. # break
  965. # p_entity_money -= 1
  966. #如果实体属于角色集合,则往后找属性
  967. # if doesEntityOrLinkedEntity_inRoleSet(entity, roleSet):
  968. #
  969. # p_entity += 1
  970. # #循环查找符合的属性
  971. # while(p_entity<len(list_entity)):
  972. #
  973. # entity_after = list_entity[p_entity]
  974. # if entity_after.sentence_index-entity.sentence_index>=sentence_len:
  975. # p_entity -= 1
  976. # break
  977. # #若是遇到公司实体,则跳出循环
  978. # if entity_after.entity_type in ['org','company']:
  979. # p_entity -= 1
  980. # break
  981. # if entity_after.values is not None:
  982. # if entity_after.entity_type=="money":
  983. # if entity_after.values[entity_after.label]>=on_value:
  984. # '''
  985. # #招标金额从后往前找
  986. # if str(entity_after.label)=="0":
  987. # packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  988. # if packagePointer is None:
  989. # packageName = "Project"
  990. # else:
  991. # packageName = packagePointer.entity_text
  992. # addMoneyByRoleid(PackDict, packageName, "0", entity_after.entity_text, entity_after.values[entity_after.label])
  993. # '''
  994. # if str(entity_after.label)=="1":
  995. # #print(entity_after.entity_text,entity.entity_text)
  996. # _list_entitys = [entity]+entity.linked_entitys
  997. # if len(PackageSet)>0:
  998. # packagePointer,_ = getPackage(PackageList,entity_after.sentence_index,entity_after.begin_index,"money-"+str(entity_after.entity_text)+"-"+str(entity_after.label))
  999. # if packagePointer is None:
  1000. # packageName_entity = "Project"
  1001. # else:
  1002. # packageName_entity = packagePointer.entity_text
  1003. # else:
  1004. # packageName_entity = "Project"
  1005. # if str(entity.label) in ["2","3","4"]:
  1006. # # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after.entity_text, entity_after.values[entity_after.label])
  1007. # if entity_after.notes == '单价' or float(entity_after.entity_text)<5000: #2021/12/17 调整小金额阈值,避免203608823.html 两次金额一次万元没提取到的情况
  1008. # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  1009. # 0.5)
  1010. # entity.pointer_money = entity_after
  1011. # # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  1012. # else:
  1013. # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  1014. # entity_after.values[entity_after.label])
  1015. # entity.pointer_money = entity_after
  1016. # # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  1017. # if entity_after.values[entity_after.label]>0.6:
  1018. # break # 2021/7/16 新增,找到中标金额,非单价即停止,不再往后找金额
  1019. # #add pointer_money
  1020. # # entity.pointer_money = entity_after
  1021. # # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  1022. # # if entity_after.notes!='单价':
  1023. # # break # 2021/7/16 新增,找到中标金额即停止,不再往后找金额
  1024. # '''
  1025. # if entity_after.entity_type=="person":
  1026. # if entity_after.values[entity_after.label]>=on_value_person:
  1027. # if str(entity_after.label)=="1":
  1028. # for i in range(len(roleList)):
  1029. # if roleList[i].role_name=="tenderee":
  1030. # roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1031. # elif str(entity_after.label)=="2":
  1032. # for i in range(len(roleList)):
  1033. # if roleList[i].role_name=="agency":
  1034. # roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1035. # elif str(entity_after.label)=="3":
  1036. # _list_entitys = [entity]+entity.linked_entitys
  1037. # for _entity in _list_entitys:
  1038. # for i in range(len(roleList)):
  1039. # if roleList[i].entity_text==_entity.entity_text:
  1040. # if entity_after.sentence_index-_entity.sentence_index>1 and len(roleList[i].linklist)>0:
  1041. # break
  1042. # roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1043. # '''
  1044. #
  1045. # p_entity += 1
  1046. #
  1047. # p_entity += 1
  1048. # 记录每句的分词数量
  1049. tokens_num_dict = dict()
  1050. last_tokens_num = 0
  1051. for sentence in list_sentence:
  1052. _index = sentence.sentence_index
  1053. if _index == 0:
  1054. tokens_num_dict[_index] = 0
  1055. else:
  1056. tokens_num_dict[_index] = tokens_num_dict[_index - 1] + last_tokens_num
  1057. last_tokens_num = len(sentence.tokens)
  1058. attribute_type = ['money','serviceTime','ratio']# 'money'仅指“中投标金额”
  1059. for link_attribute in attribute_type:
  1060. temp_entity_list = []
  1061. if link_attribute=="money":
  1062. temp_entity_list = [ent for ent in list_entity if (ent.entity_type in ['org','company'] and ent.label in [2,3,4]) or
  1063. (ent.entity_type=='money' and ent.label==1 and ent.values[ent.label]>=0.5)]
  1064. # 删除重复的‘中投标金额’,一般为大小写两种样式
  1065. drop_tendererMoney = []
  1066. for ent_idx in range(len(temp_entity_list)-1):
  1067. entity = temp_entity_list[ent_idx]
  1068. if entity.entity_type=='money':
  1069. next_entity = temp_entity_list[ent_idx+1]
  1070. if next_entity.entity_type=='money':
  1071. if getUnifyMoney(entity.entity_text)==getUnifyMoney(next_entity.entity_text):
  1072. if (tokens_num_dict[next_entity.sentence_index] + next_entity.begin_index) - (
  1073. tokens_num_dict[entity.sentence_index] + entity.end_index) < 10:
  1074. drop_tendererMoney.append(next_entity)
  1075. for _drop in drop_tendererMoney:
  1076. temp_entity_list.remove(_drop)
  1077. elif link_attribute=="serviceTime":
  1078. temp_entity_list = [ent for ent in list_entity if (ent.entity_type in ['org','company'] and ent.label in [2,3,4]) or
  1079. ent.entity_type=='serviceTime']
  1080. elif link_attribute=="ratio":
  1081. temp_entity_list = [ent for ent in list_entity if (ent.entity_type in ['org','company'] and ent.label in [2,3,4]) or
  1082. ent.entity_type=='ratio']
  1083. temp_entity_list = sorted(temp_entity_list,key=lambda x: (x.sentence_index, x.begin_index))
  1084. temp_match_list = []
  1085. for ent_idx in range(len(temp_entity_list)):
  1086. entity = temp_entity_list[ent_idx]
  1087. if entity.entity_type in ['org','company']:
  1088. match_nums = 0
  1089. tenderer_nums = 0 #经过其他中投标人的数量
  1090. byNotTenderer_match_nums = 0 #跟在中投标人后面的属性
  1091. for after_index in range(ent_idx + 1, min(len(temp_entity_list), ent_idx + 4)):
  1092. after_entity = temp_entity_list[after_index]
  1093. if entity.in_attachment != after_entity.in_attachment: # 正文与附件的不能相连
  1094. break
  1095. if after_entity.entity_type == link_attribute:
  1096. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1097. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1098. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1099. value = (-1 / 2 * (distance ** 2)) / 10000
  1100. if link_attribute == "money":
  1101. if after_entity.notes == '单价':
  1102. value = value * 100
  1103. if sentence_distance == 0:
  1104. if distance < 100:
  1105. # value = (-1 / 2 * (distance ** 2)) / 10000
  1106. temp_match_list.append(Match(entity, after_entity, value))
  1107. match_nums += 1
  1108. if not tenderer_nums:
  1109. byNotTenderer_match_nums += 1
  1110. else:
  1111. break
  1112. else:
  1113. if distance < 60:
  1114. # value = (-1 / 2 * (distance ** 2)) / 10000
  1115. temp_match_list.append(Match(entity, after_entity, value))
  1116. match_nums += 1
  1117. if not tenderer_nums:
  1118. byNotTenderer_match_nums += 1
  1119. else:
  1120. break
  1121. else:
  1122. tenderer_nums += 1
  1123. #前向查找属性
  1124. if ent_idx!=0 and (not match_nums or not byNotTenderer_match_nums):
  1125. previous_entity = temp_entity_list[ent_idx - 1]
  1126. if previous_entity.entity_type == link_attribute:
  1127. # if previous_entity.sentence_index == entity.sentence_index:
  1128. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1129. tokens_num_dict[previous_entity.sentence_index] + previous_entity.end_index)
  1130. if distance < 40:
  1131. # 前向 没有 /10000
  1132. value = (-1 / 2 * (distance ** 2))
  1133. temp_match_list.append(Match(entity, previous_entity, value))
  1134. # km算法分配求解
  1135. dispatch_result = dispatch(temp_match_list)
  1136. dispatch_result = sorted(dispatch_result, key=lambda x: (x[0].sentence_index,x[0].begin_index))
  1137. for match in dispatch_result:
  1138. _entity = match[0]
  1139. _attribute = match[1]
  1140. if link_attribute=='money':
  1141. _entity.pointer_money = _attribute
  1142. packagePointer, _ = getPackage(PackageList, _attribute.sentence_index, _attribute.begin_index,
  1143. "money-" + str(_attribute.entity_text) + "-" + str(_attribute.label))
  1144. # print(_entity.entity_text,_attribute.entity_text)
  1145. if packagePointer is None:
  1146. packageName_entity = "Project"
  1147. else:
  1148. packageName_entity = packagePointer.entity_text
  1149. if _attribute.notes == '单价' or float(_attribute.entity_text) < 5000: # 2021/12/17 调整小金额阈值,避免203608823.html 两次金额一次万元没提取到的情况
  1150. # print(packageName_entity,_attribute.entity_text, _attribute.values[_attribute.label])
  1151. addMoneyByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute,0.5)
  1152. else:
  1153. # print(packageName_entity,_attribute.entity_text, _attribute.values[_attribute.label])
  1154. addMoneyByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute,
  1155. _attribute.values[_attribute.label])
  1156. elif link_attribute=='serviceTime':
  1157. _entity.pointer_serviceTime = _attribute
  1158. packagePointer, _ = getPackage(PackageList, _attribute.sentence_index, _attribute.begin_index,
  1159. "serviceTime-" + str(_attribute.entity_text) + "-" + str(_attribute.label))
  1160. if packagePointer is None:
  1161. packageName_entity = "Project"
  1162. else:
  1163. packageName_entity = packagePointer.entity_text
  1164. addServiceTimeByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute)
  1165. elif link_attribute=='ratio':
  1166. _entity.pointer_ratio = _attribute
  1167. packagePointer, _ = getPackage(PackageList, _attribute.sentence_index, _attribute.begin_index,
  1168. "ratio-" + str(_attribute.entity_text) + "-" + str(_attribute.label))
  1169. if packagePointer is None:
  1170. packageName_entity = "Project"
  1171. else:
  1172. packageName_entity = packagePointer.entity_text
  1173. addRatioByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute)
  1174. ''''''
  1175. # 通过模型分类的招标/代理联系人
  1176. list_sentence = sorted(list_sentence, key=lambda x: x.sentence_index)
  1177. person_list = [entity for entity in list_entity if entity.entity_type == 'person' and entity.label in [1, 2]]
  1178. tenderee_contact = set()
  1179. tenderee_phone = set()
  1180. agency_contact = set()
  1181. agency_phone = set()
  1182. winter_contact = set()
  1183. for _person in person_list:
  1184. if _person.label == 1:
  1185. tenderee_contact.add(_person.entity_text)
  1186. if _person.label == 2:
  1187. agency_contact.add(_person.entity_text)
  1188. # 正则匹配无 '主体/联系人' 的电话
  1189. # 例:"采购人联系方式:0833-5226788,"
  1190. phone_pattern = '(1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|' \
  1191. '\+86.?1[3-9]\d{9}|' \
  1192. '0[1-9]\d{1,2}[-—-―][2-9]\d{6,7}/[1-9]\d{6,10}|' \
  1193. '0[1-9]\d{1,2}[-—-―][2-9]\d{6}\d?.?转\d{1,4}|' \
  1194. '0[1-9]\d{1,2}[-—-―][2-9]\d{6}\d?[-—-―]\d{1,4}|' \
  1195. '0[1-9]\d{1,2}[-—-―]?[2-9]\d{6}\d?(?=1[3-9]\d{9})|' \
  1196. '0[1-9]\d{1,2}[-—-―]?[2-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[2-9]\d{6}\d?)|' \
  1197. '0[1-9]\d{1,2}[-—-―]?[2-9]\d{6}\d?(?=[2-9]\d{6,7})|' \
  1198. '0[1-9]\d{1,2}[-—-―]?[2-9]\d{6}\d?|' \
  1199. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?[2-9]\d{6}\d?-?\d{,4}|' \
  1200. '[2-9]\d{6,7})'
  1201. re_tenderee_phone = re.compile(
  1202. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,5}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,7}?)"
  1203. # 电话号码
  1204. + phone_pattern)
  1205. # 例:"采购人地址和联系方式:峨边彝族自治县教育局,0833-5226788,"
  1206. re_tenderee_phone2 = re.compile(
  1207. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,20}?)"
  1208. # 电话号码
  1209. + phone_pattern)
  1210. re_agent_phone = re.compile(
  1211. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,5}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,7}?)"
  1212. # 电话号码
  1213. + phone_pattern)
  1214. re_agent_phone2 = re.compile(
  1215. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,20}?)"
  1216. # 电话号码
  1217. + phone_pattern)
  1218. content = ""
  1219. for _sentence in list_sentence:
  1220. content += "".join(_sentence.tokens)
  1221. _content = copy.deepcopy(content)
  1222. while re.search("(.)(,)([^0-9])|([^0-9])(,)(.)", content):
  1223. content_words = list(content)
  1224. for i in re.finditer("(.)(,)([^0-9])", content):
  1225. content_words[i.span(2)[0]] = ""
  1226. for i in re.finditer("([^0-9])(,)(.)", content):
  1227. content_words[i.span(2)[0]] = ""
  1228. content = "".join(content_words)
  1229. content = re.sub("[::]|[\((]|[\))]", "", content)
  1230. _tenderee_phone = re.findall(re_tenderee_phone, content)
  1231. # 更新正则确定的角色属性
  1232. for i in range(len(PackDict["Project"]["roleList"])):
  1233. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  1234. _tenderee_phone = re.findall(re_tenderee_phone, content)
  1235. if _tenderee_phone:
  1236. for _phone in _tenderee_phone:
  1237. _phone = _phone.split("/") # 分割多个号码
  1238. for one_phone in _phone:
  1239. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1240. tenderee_phone.add(one_phone)
  1241. _tenderee_phone2 = re.findall(re_tenderee_phone2, content)
  1242. if _tenderee_phone2:
  1243. for _phone in _tenderee_phone2:
  1244. _phone = _phone.split("/")
  1245. for one_phone in _phone:
  1246. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1247. tenderee_phone.add(one_phone)
  1248. if PackDict["Project"]["roleList"][i].role_name == "agency":
  1249. _agent_phone = re.findall(re_agent_phone, content)
  1250. if _agent_phone:
  1251. for _phone in _agent_phone:
  1252. _phone = _phone.split("/")
  1253. for one_phone in _phone:
  1254. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1255. agency_phone.add(one_phone)
  1256. _agent_phone2 = re.findall(re_agent_phone2, content)
  1257. if _agent_phone2:
  1258. for _phone in _agent_phone2:
  1259. _phone = _phone.split("/")
  1260. for one_phone in _phone:
  1261. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1262. agency_phone.add(one_phone)
  1263. # 正则提取电话号码实体
  1264. # key_word = re.compile('((?:电话|联系方式|联系人).{0,4}?)([0-1]\d{6,11})')
  1265. phone = re.compile('1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1266. '\+86.?1[3-9]\d{9}|'
  1267. # '0[^0]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1268. '0[1-9]\d{1,2}[-—-―][2-9]\d{6}\d?[-—-―]\d{1,4}|'
  1269. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=1[3-9]\d{9})|'
  1270. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[2-9]\d{6}\d?)|'
  1271. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=[2-9]\d{6,7})|'
  1272. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?|'
  1273. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?[2-9]\d{6}\d?-?\d{,4}|'
  1274. '400\d{7}转\d{1,4}|'
  1275. '[2-9]\d{6,7}')
  1276. url_pattern = re.compile("http[s]?://(?:[a-zA-Z]|[0-9]|[#$\-_@.&+=\?:/]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+")
  1277. email_pattern = re.compile("[a-zA-Z0-9][a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*@"
  1278. "[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*(?:\.[a-zA-Z]{2,})")
  1279. phone_entitys = []
  1280. code_entitys = [ent for ent in list_entity if ent.entity_type=='code']
  1281. for _sentence in list_sentence:
  1282. sentence_text = _sentence.sentence_text
  1283. # 过长数字串直接过滤替换
  1284. for _re in re.findall("\d{50,}",sentence_text):
  1285. sentence_text = sentence_text.replace(_re,"#"*len(_re))
  1286. in_attachment = _sentence.in_attachment
  1287. list_tokenbegin = []
  1288. begin = 0
  1289. for i in range(0, len(_sentence.tokens)):
  1290. list_tokenbegin.append(begin)
  1291. begin += len(str(_sentence.tokens[i]))
  1292. list_tokenbegin.append(begin + 1)
  1293. # 排除网址、邮箱、项目编号实体
  1294. error_list = []
  1295. for i in re.finditer(url_pattern, sentence_text):
  1296. error_list.append((i.start(), i.end()))
  1297. for i in re.finditer(email_pattern, sentence_text):
  1298. error_list.append((i.start(), i.end()))
  1299. for code_ent in [ent for ent in code_entitys if ent.sentence_index==_sentence.sentence_index]:
  1300. error_list.append((code_ent.wordOffset_begin,code_ent.wordOffset_end))
  1301. res_set = set()
  1302. for i in re.finditer(phone, sentence_text):
  1303. is_continue = False
  1304. for error_ent in error_list:
  1305. if i.start()>=error_ent[0] and i.end()<=error_ent[1]:
  1306. is_continue = True
  1307. break
  1308. if is_continue:
  1309. continue
  1310. res_set.add((i.group(), i.start(), i.end()))
  1311. res_set = sorted(list(res_set),key=lambda x:x[1])
  1312. # 限制数量,防止异常数据处理时间过长
  1313. res_set = res_set[:200]
  1314. last_phone_mask = True
  1315. error_numStr_index = []
  1316. sentence_phone_list = []
  1317. for item_idx in range(len(res_set)):
  1318. item = res_set[item_idx]
  1319. phone_left = sentence_text[max(0, item[1] - 10):item[1]]
  1320. phone_right = sentence_text[item[2]:item[2] + 10]
  1321. phone_left_num = re.search("[\da-zA-Z\-—-―]+$",phone_left)
  1322. numStr_left = item[1]
  1323. if phone_left_num:
  1324. numStr_left -= len(phone_left_num.group())
  1325. phone_right_num = re.search("^[\da-zA-Z\-—-―]+",phone_right)
  1326. numStr_right = item[2]
  1327. if phone_right_num:
  1328. numStr_right += len(phone_right_num.group())
  1329. numStr_index = (numStr_left,numStr_right)
  1330. if re.search("电话|手机|联系[人方]|联系方式",re.sub(",","",phone_left)):
  1331. pass
  1332. else:
  1333. # 排除“传真号”和其它错误项
  1334. if re.search("传,?真|信,?箱|邮,?[编箱件]|QQ|qq", phone_left):
  1335. if not re.search("电,?话", phone_left):
  1336. error_numStr_index.append(numStr_index)
  1337. last_phone_mask = False
  1338. continue
  1339. if re.search("身份证号?码?|注册[证号]|帐号|编[号码]|报价|费率|标价|证号|价格|型号|附件|代码|列号|行号|税号|[\(\(]万?元[\)\)]|[a-zA-Z]+\d*$", re.sub(",","",phone_left)):
  1340. error_numStr_index.append(numStr_index)
  1341. last_phone_mask = False
  1342. continue
  1343. if re.search("^\d{0,4}[.,]\d{2,}|^[0-9a-zA-Z\.]*@|^\d*[a-zA-Z]+|元", phone_right):
  1344. error_numStr_index.append(numStr_index)
  1345. last_phone_mask = False
  1346. continue
  1347. # 号码含有0过多,不符合规则
  1348. if re.search("0{6,}",item[0]):
  1349. error_numStr_index.append(numStr_index)
  1350. last_phone_mask = False
  1351. continue
  1352. # 前后跟着字母
  1353. if re.search("[a-zA-Z/]+$", phone_left) or re.search("^[a-zA-Z/]+", phone_right):
  1354. error_numStr_index.append(numStr_index)
  1355. last_phone_mask = False
  1356. continue
  1357. # 时间日期类排除
  1358. if re.search("时间|日期", phone_left):
  1359. error_numStr_index.append(numStr_index)
  1360. last_phone_mask = False
  1361. continue
  1362. # 排除号码实体为时间格式 ,例如:20150515
  1363. 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]):
  1364. error_numStr_index.append(numStr_index)
  1365. last_phone_mask = False
  1366. continue
  1367. # 前后跟着长度小于一定值数字的正则排除
  1368. if re.search("\d+[-—-―]?\d*$",phone_left) or re.search("^\d+[-—-―]?\d*",phone_right):
  1369. phone_left_number = re.search("\d+[-—-―]?\d*$",phone_left)
  1370. phone_right_number = re.search("^\d+[-—-―]?\d+",phone_right)
  1371. if phone_left_number:
  1372. if len(phone_left_number.group())<7:
  1373. error_numStr_index.append(numStr_index)
  1374. last_phone_mask = False
  1375. continue
  1376. if phone_right_number:
  1377. if len(phone_right_number.group())<7:
  1378. error_numStr_index.append(numStr_index)
  1379. last_phone_mask = False
  1380. continue
  1381. left_context = re.search("[\da-zA-Z\-—-―]+$",sentence_text[:item[1]])
  1382. if left_context:
  1383. if len(left_context.group()) != len("".join(re.findall(phone, left_context.group()))):
  1384. # if not re.search("(" + phone.pattern + ")$", left_context.group()):
  1385. error_numStr_index.append(numStr_index)
  1386. last_phone_mask = False
  1387. continue
  1388. right_context = re.search("^[\da-zA-Z\-—-―]+", sentence_text[item[2]:])
  1389. if right_context:
  1390. if len(right_context.group()) != len("".join(re.findall(phone, right_context.group()))):
  1391. # if not re.search("^(" + phone.pattern + ")", right_context.group()):
  1392. error_numStr_index.append(numStr_index)
  1393. last_phone_mask = False
  1394. continue
  1395. # if:上一个phone实体不符合条件
  1396. if not last_phone_mask:
  1397. item_start = item[1]
  1398. last_item_end = res_set[item_idx-1][2]
  1399. if item_start - last_item_end<=1 or re.search("^[\da-zA-Z\-—-―、]+$",sentence_text[last_item_end:item_start]):
  1400. error_numStr_index.append(numStr_index)
  1401. last_phone_mask = False
  1402. continue
  1403. sentence_phone_list.append(item)
  1404. last_phone_mask = True
  1405. if error_numStr_index:
  1406. drop_list = []
  1407. for item in sentence_phone_list:
  1408. for err_index in error_numStr_index:
  1409. 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]):
  1410. drop_list.append(item)
  1411. break
  1412. for _drop_item in drop_list:
  1413. sentence_phone_list.remove(_drop_item)
  1414. for item in sentence_phone_list:
  1415. for j in range(len(list_tokenbegin)):
  1416. if list_tokenbegin[j] == item[1]:
  1417. begin_index = j
  1418. break
  1419. elif list_tokenbegin[j] > item[1]:
  1420. begin_index = j - 1
  1421. break
  1422. for j in range(begin_index, len(list_tokenbegin)):
  1423. if list_tokenbegin[j] >= item[2]:
  1424. end_index = j - 1
  1425. break
  1426. phone_text = re.sub("[-—-―]+","-",item[0]).replace("(","(").replace(")",")")
  1427. _entity = Entity(_sentence.doc_id, None, phone_text, "phone", _sentence.sentence_index, begin_index, end_index, item[1],
  1428. item[2],in_attachment=in_attachment)
  1429. phone_entitys.append(_entity)
  1430. # print('phone_set:',set([ent.entity_text for ent in phone_entitys]))
  1431. def is_company(entity,text):
  1432. # 判断"公司"实体是否为地址地点
  1433. if entity.label!=5 and entity.values[entity.label]>0.5:
  1434. return True
  1435. if ent.is_tail==True:
  1436. return False
  1437. entity_left = text[max(0,entity.wordOffset_begin-10):entity.wordOffset_begin]
  1438. entity_left = re.sub(",()\(\)","",entity_left)
  1439. entity_left = entity_left[-5:]
  1440. if re.search("地址|地点|银行[::]",entity_left):
  1441. return False
  1442. else:
  1443. return True
  1444. pre_entity = []
  1445. for ent in list_entity:
  1446. 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]) \
  1447. or (ent.entity_type=='location' and len(ent.entity_text)>5):
  1448. pre_entity.append(ent)
  1449. text_data,pre_data = relationExtraction_model.encode(pre_entity + phone_entitys, list_sentence)
  1450. # print(pre_data)
  1451. maxlen = 512
  1452. relation_list = []
  1453. if 0<len(text_data)<=maxlen:
  1454. relation_list = relationExtraction_model.predict(text_data, pre_data)
  1455. else:
  1456. # 公告大于maxlen时,分段预测
  1457. start = 0
  1458. # print("len(pre_data)",len(pre_data))
  1459. temp_data = []
  1460. deal_data = 0
  1461. while start<len(pre_data):
  1462. _pre_data = pre_data[start:start+maxlen]
  1463. _text_data = text_data[start:start+maxlen]
  1464. if relationExtraction_model.check_data(_pre_data):
  1465. temp_data.append((_text_data,_pre_data))
  1466. else:
  1467. if temp_data:
  1468. deal_data += len(temp_data)
  1469. if deal_data>4:
  1470. break
  1471. for _text_data, _pre_data in temp_data:
  1472. relation_list.extend(relationExtraction_model.predict(_text_data,_pre_data))
  1473. temp_data = []
  1474. start = start + maxlen - 120
  1475. if temp_data:
  1476. deal_data += len(temp_data)
  1477. if deal_data <= 4:
  1478. for _text_data, _pre_data in temp_data:
  1479. relation_list.extend(relationExtraction_model.predict(_text_data, _pre_data))
  1480. # print("预测数据:",len(temp_data))
  1481. # 去重结果
  1482. relation_list = list(set(relation_list))
  1483. # print([(rel[0].entity_text,rel[2].entity_text) for rel in relation_list])
  1484. right_combination = [('org','person'),('company','person'),('company','location'),('org','location'),('person','phone')]
  1485. linked_company = set()
  1486. linked_person = set()
  1487. linked_connetPerson = set()
  1488. linked_phone = set()
  1489. for predicate in ["rel_address","rel_phone","rel_person"]:
  1490. _match_list = []
  1491. _match_combo = []
  1492. for relation in relation_list:
  1493. _subject = relation[0]
  1494. _object = relation[2]
  1495. if isinstance(_subject,Entity) and isinstance(_object,Entity) and (_subject.entity_type,_object.entity_type) in right_combination:
  1496. if _subject.in_attachment != _object.in_attachment:
  1497. continue
  1498. if relation[1]==predicate:
  1499. distance = (tokens_num_dict[_object.sentence_index] + _object.begin_index) - (
  1500. tokens_num_dict[_subject.sentence_index] + _subject.end_index)
  1501. if predicate=="rel_person":
  1502. if (_subject.label==0 and _object.entity_text in agency_contact ) or (_subject.label==1 and _object.entity_text in tenderee_contact):
  1503. continue
  1504. # 角色为中标候选人,排除"质疑|投诉|监督|受理"相关的联系人
  1505. 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]):
  1506. continue
  1507. if _object.sentence_index!=0 and _object.wordOffset_begin<=10:
  1508. if _subject.label in [2, 3, 4] and re.search("请.{0,4}联系",
  1509. list_sentence[_object.sentence_index-1].sentence_text[-10:]+
  1510. list_sentence[_object.sentence_index].sentence_text[0:_object.wordOffset_begin]):
  1511. continue
  1512. # 角色为中标候选人,排除距离过远的联系人
  1513. if _subject.label in [2, 3, 4] and distance>=40:
  1514. continue
  1515. if distance>0:
  1516. value = (-1 / 2 * (distance ** 2))/10000
  1517. else:
  1518. distance = abs(distance)
  1519. value = (-1 / 2 * (distance ** 2))
  1520. _match_list.append(Match(_subject,_object,value))
  1521. _match_combo.append((_subject,_object))
  1522. match_result = dispatch(_match_list)
  1523. error_list = []
  1524. for mat in list(set(_match_combo)-set(match_result)):
  1525. for temp in match_result:
  1526. if mat[1]==temp[1] and mat[0]!=temp[0]:
  1527. error_list.append(mat)
  1528. break
  1529. result = list(set(_match_combo)-set(error_list))
  1530. if predicate=='rel_person':
  1531. # 从后往前更新状态,已近后向链接的属性不在前向链接(解决错误链接)
  1532. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1533. for combo in result:
  1534. is_continue = False
  1535. if not combo[0].pointer_person:
  1536. combo[0].pointer_person = []
  1537. if combo[1].begin_index<combo[0].begin_index:
  1538. if combo[0].pointer_person:
  1539. for temp in combo[0].pointer_person:
  1540. if temp.begin_index>combo[0].begin_index:
  1541. is_continue = True
  1542. break
  1543. if is_continue:
  1544. continue
  1545. combo[0].pointer_person.append(combo[1])
  1546. linked_company.add(combo[0])
  1547. linked_person.add(combo[1])
  1548. # print(1,combo[0].entity_text,combo[1].entity_text)
  1549. if predicate=='rel_address':
  1550. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1551. for combo in result:
  1552. if combo[0].pointer_address:
  1553. continue
  1554. combo[0].pointer_address = combo[1]
  1555. # print(2,combo[0].entity_text,combo[1].entity_text)
  1556. if predicate=='rel_phone':
  1557. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1558. for combo in result:
  1559. is_continue = False
  1560. if not combo[0].person_phone:
  1561. combo[0].person_phone = []
  1562. if combo[1].begin_index<combo[0].begin_index:
  1563. if combo[0].person_phone:
  1564. for temp in combo[0].person_phone:
  1565. if temp.begin_index>combo[0].begin_index:
  1566. is_continue = True
  1567. break
  1568. if is_continue: continue
  1569. combo[0].person_phone.append(combo[1])
  1570. linked_connetPerson.add(combo[0])
  1571. linked_phone.add(combo[1])
  1572. if combo[0].label in [1,2]:
  1573. if PackDict.get("Project"):
  1574. for i in range(len(PackDict["Project"]["roleList"])):
  1575. if (combo[0].label==1 and PackDict["Project"]["roleList"][i].role_name=='tenderee') \
  1576. or (combo[0].label==2 and PackDict["Project"]["roleList"][i].role_name=='agency'):
  1577. PackDict["Project"]["roleList"][i].linklist.append((combo[0].entity_text,combo[1].entity_text))
  1578. break
  1579. # print(3,combo[0].entity_text,combo[1].entity_text)
  1580. # "公司——地址" 链接规则补充
  1581. company_lacation_EntityList = [ent for ent in pre_entity if ent.entity_type in ['company', 'org', 'location']]
  1582. # 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"]
  1583. company_lacation_EntityList = sorted(company_lacation_EntityList, key=lambda x: (x.sentence_index, x.begin_index))
  1584. t_match_list = []
  1585. for ent_idx in range(len(company_lacation_EntityList)):
  1586. entity = company_lacation_EntityList[ent_idx]
  1587. if entity.entity_type in ['company', 'org'] and entity.label!=5:
  1588. match_nums = 0
  1589. company_nums = 0 # 经过其他公司的数量
  1590. location_nums = 0 # 经过电话的数量
  1591. for after_index in range(ent_idx + 1, min(len(company_lacation_EntityList), ent_idx + 5)):
  1592. after_entity = company_lacation_EntityList[after_index]
  1593. if after_entity.entity_type == "location":
  1594. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1595. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1596. location_nums += 1
  1597. if distance > 100 or location_nums >= 3:
  1598. break
  1599. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1600. value = (-1 / 2 * (distance ** 2)) / 10000
  1601. if sentence_distance == 0:
  1602. if distance < 80:
  1603. t_match_list.append(Match(entity, after_entity, value))
  1604. match_nums += 1
  1605. if company_nums:
  1606. break
  1607. else:
  1608. if distance < 50:
  1609. t_match_list.append(Match(entity, after_entity, value))
  1610. match_nums += 1
  1611. if company_nums:
  1612. break
  1613. else:
  1614. # type:company/org
  1615. company_nums += 1
  1616. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  1617. break
  1618. if entity.label in [0, 1] and after_entity.label in [2, 3, 4]:
  1619. break
  1620. if entity.label in [0, 1] and after_entity.label not in [0, 1]:
  1621. break
  1622. # km算法分配求解
  1623. # for item in t_match_list:
  1624. # print("loc_rela",item.main_role.entity_text,item.attribute.entity_text)
  1625. relate_location_result = dispatch(t_match_list)
  1626. relate_location_result = sorted(relate_location_result, key=lambda x: (x[0].sentence_index, x[0].begin_index))
  1627. for match in relate_location_result:
  1628. _company = match[0]
  1629. _relation = match[1]
  1630. # print("loc_relation1", _company.entity_text, _relation.entity_text, )
  1631. if not _company.pointer_address:
  1632. # print('loc_relation2',_company.entity_text,_relation.entity_text)
  1633. _company.pointer_address = _relation
  1634. # "联系人——联系电话" 链接规则补充
  1635. person_phone_EntityList = [ent for ent in pre_entity+ phone_entitys if ent.entity_type not in ['company','org','location']]
  1636. person_phone_EntityList = sorted(person_phone_EntityList, key=lambda x: (x.sentence_index, x.begin_index))
  1637. t_match_list = []
  1638. for ent_idx in range(len(person_phone_EntityList)):
  1639. entity = person_phone_EntityList[ent_idx]
  1640. if entity.entity_type=="person":
  1641. match_nums = 0
  1642. person_nums = 0 # 经过其他中联系人的数量
  1643. byNotPerson_match_nums = 0 # 跟在联系人后面的属性
  1644. phone_nums = 0 # 经过电话的数量
  1645. for after_index in range(ent_idx + 1, min(len(person_phone_EntityList), ent_idx + 8)):
  1646. after_entity = person_phone_EntityList[after_index]
  1647. if after_entity.entity_type == "phone":
  1648. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1649. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1650. phone_nums += 1
  1651. if distance>100 or phone_nums>=4:
  1652. break
  1653. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1654. value = (-1 / 2 * (distance ** 2)) / 10000
  1655. if sentence_distance == 0:
  1656. if distance < 70:
  1657. # value = (-1 / 2 * (distance ** 2)) / 10000
  1658. t_match_list.append(Match(entity, after_entity, value))
  1659. match_nums += 1
  1660. if not person_nums:
  1661. byNotPerson_match_nums += 1
  1662. else:
  1663. break
  1664. else:
  1665. if distance < 40:
  1666. # value = (-1 / 2 * (distance ** 2)) / 10000
  1667. t_match_list.append(Match(entity, after_entity, value))
  1668. match_nums += 1
  1669. if not person_nums:
  1670. byNotPerson_match_nums += 1
  1671. else:
  1672. break
  1673. else:
  1674. person_nums += 1
  1675. # 前向查找属性
  1676. if ent_idx != 0 and (not match_nums or not byNotPerson_match_nums):
  1677. previous_entity = person_phone_EntityList[ent_idx - 1]
  1678. if previous_entity.entity_type == 'phone':
  1679. # if previous_entity.sentence_index == entity.sentence_index:
  1680. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1681. tokens_num_dict[previous_entity.sentence_index] + previous_entity.end_index)
  1682. if distance < 40:
  1683. # 前向 没有 /10000
  1684. value = (-1 / 2 * (distance ** 2))
  1685. t_match_list.append(Match(entity, previous_entity, value))
  1686. # km算法分配求解(person-phone)
  1687. 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]
  1688. personphone_result = dispatch(t_match_list)
  1689. personphone_result = sorted(personphone_result, key=lambda x: (x[0].sentence_index, x[0].begin_index))
  1690. for match in personphone_result:
  1691. _person = match[0]
  1692. _phone = match[1]
  1693. if not _person.person_phone:
  1694. _person.person_phone = []
  1695. _person.person_phone.append(_phone)
  1696. # 多个招标人/代理人或者别称
  1697. for idx in range(1,len(pre_entity)):
  1698. _pre_entity = pre_entity[idx]
  1699. if _pre_entity in linked_company and _pre_entity.label==5:
  1700. last_ent = pre_entity[idx-1]
  1701. if last_ent.entity_type in ['company','org'] and last_ent.label in [0,1]:
  1702. if last_ent.sentence_index==_pre_entity.sentence_index:
  1703. mid_text = list_sentence[_pre_entity.sentence_index].sentence_text[last_ent.wordOffset_end:_pre_entity.wordOffset_begin]
  1704. if len(mid_text)<=20 and "," not in mid_text and re.search("[、\((]",mid_text):
  1705. _pre_entity.label = last_ent.label
  1706. _pre_entity.values[last_ent.label] = 0.6
  1707. # 2022/01/25 固定电话可连多个联系人
  1708. temp_person_entitys = [entity for entity in pre_entity if entity.entity_type == 'person']
  1709. temp_person_entitys2 = [] #和固定电话相连的联系人
  1710. for entity in temp_person_entitys:
  1711. if entity.person_phone:
  1712. for _phone in entity.person_phone:
  1713. if not re.search("^1[3-9]\d{9}$", _phone.entity_text):
  1714. temp_person_entitys2.append(entity)
  1715. break
  1716. for index in range(len(temp_person_entitys)):
  1717. entity = temp_person_entitys[index]
  1718. if entity in temp_person_entitys2:
  1719. last_person = entity
  1720. for after_index in range(index + 1, min(len(temp_person_entitys), index + 5)):
  1721. after_entity = temp_person_entitys[after_index]
  1722. if after_entity.sentence_index == last_person.sentence_index and after_entity.begin_index - last_person.end_index < 3:
  1723. for _phone in entity.person_phone:
  1724. if not re.search("^1[3-9]\d{9}$", _phone.entity_text):
  1725. if _phone not in after_entity.person_phone:
  1726. after_entity.person_phone.append(_phone)
  1727. last_person = after_entity
  1728. else:
  1729. break
  1730. if index==0:
  1731. continue
  1732. last_person = entity
  1733. for before_index in range(index-1, max(-1,index-5), -1):
  1734. before_entity = temp_person_entitys[before_index]
  1735. if before_entity.sentence_index == last_person.sentence_index and last_person.begin_index - before_entity.end_index < 3:
  1736. for _phone in entity.person_phone:
  1737. if not re.search("^1[3-9]\d{9}$", _phone.entity_text):
  1738. if _phone not in before_entity.person_phone:
  1739. before_entity.person_phone.append(_phone)
  1740. last_person = before_entity
  1741. else:
  1742. break
  1743. # 更新person为招标/代理联系人的联系方式
  1744. for k in PackDict.keys():
  1745. for i in range(len(PackDict[k]["roleList"])):
  1746. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1747. for _person in person_list:
  1748. if _person.label==1:#招标联系人
  1749. person_phone = [phone for phone in _person.person_phone] if _person.person_phone else []
  1750. for _p in person_phone:
  1751. PackDict[k]["roleList"][i].linklist.append((_person.entity_text, _p.entity_text))
  1752. if not person_phone:
  1753. PackDict[k]["roleList"][i].linklist.append((_person.entity_text,""))
  1754. if PackDict[k]["roleList"][i].role_name == "agency":
  1755. for _person in person_list:
  1756. if _person.label==2:#代理联系人
  1757. person_phone = [phone for phone in _person.person_phone] if _person.person_phone else []
  1758. for _p in person_phone:
  1759. PackDict[k]["roleList"][i].linklist.append((_person.entity_text, _p.entity_text))
  1760. if not person_phone:
  1761. PackDict[k]["roleList"][i].linklist.append((_person.entity_text,""))
  1762. # 更新 PackDict
  1763. not_sure_linked = []
  1764. for link_p in list(linked_company):
  1765. for k in PackDict.keys():
  1766. for i in range(len(PackDict[k]["roleList"])):
  1767. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1768. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 0:
  1769. not_sure_linked.append(link_p)
  1770. continue
  1771. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1772. for per in link_p.pointer_person:
  1773. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1774. if not person_phone:
  1775. if per.entity_text not in agency_contact:
  1776. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1777. continue
  1778. for _p in person_phone:
  1779. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1780. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1781. elif PackDict[k]["roleList"][i].role_name == "agency":
  1782. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 1:
  1783. not_sure_linked.append(link_p)
  1784. continue
  1785. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1786. for per in link_p.pointer_person:
  1787. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1788. if not person_phone:
  1789. if per.entity_text not in tenderee_contact:
  1790. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1791. continue
  1792. for _p in person_phone:
  1793. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone:
  1794. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1795. else:
  1796. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1797. for per in link_p.pointer_person:
  1798. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1799. if not person_phone:
  1800. if per.entity_text not in tenderee_contact and per.entity_text not in agency_contact:
  1801. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1802. winter_contact.add(per.entity_text)
  1803. continue
  1804. for _p in person_phone:
  1805. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and \
  1806. per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1807. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1808. winter_contact.add(per.entity_text)
  1809. # 更新org/company实体label为0,1的链接
  1810. for link_p in not_sure_linked:
  1811. for k in PackDict.keys():
  1812. for i in range(len(PackDict[k]["roleList"])):
  1813. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1814. if link_p.label == 0:
  1815. for per in link_p.pointer_person:
  1816. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1817. if not person_phone:
  1818. if per.entity_text not in agency_contact and per.entity_text not in winter_contact:
  1819. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1820. continue
  1821. for _p in person_phone:
  1822. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone and per.entity_text not in winter_contact:
  1823. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1824. elif PackDict[k]["roleList"][i].role_name == "agency":
  1825. if link_p.label == 1:
  1826. for per in link_p.pointer_person:
  1827. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1828. if not person_phone:
  1829. if per.entity_text not in tenderee_contact and per.entity_text not in winter_contact:
  1830. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1831. continue
  1832. for _p in person_phone:
  1833. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and per.entity_text not in winter_contact:
  1834. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1835. re_split = re.compile("[^\u4e00-\u9fa5、](十一|十二|十三|十四|十五|一|二|三|四|五|六|七|八|九|十)、")
  1836. split_list = [0] * 16
  1837. split_dict = {
  1838. "一、": 1,
  1839. "二、": 2,
  1840. "三、": 3,
  1841. "四、": 4,
  1842. "五、": 5,
  1843. "六、": 6,
  1844. "七、": 7,
  1845. "八、": 8,
  1846. "九、": 9,
  1847. "十、": 10,
  1848. "十一、": 11,
  1849. "十二、": 12,
  1850. "十三、": 13,
  1851. "十四、": 14,
  1852. "十五、": 15
  1853. }
  1854. for item in re.finditer(re_split, _content):
  1855. _index = split_dict.get(item.group()[1:])
  1856. if not split_list[_index]:
  1857. split_list[_index] = item.span()[0] + 1
  1858. split_list = [i for i in split_list if i != 0]
  1859. start = 0
  1860. new_split_list = []
  1861. for idx in split_list:
  1862. new_split_list.append((start, idx))
  1863. start = idx
  1864. new_split_list.append((start, len(_content)))
  1865. # 实体列表按照“公告分段”分组
  1866. words_num_dict = dict()
  1867. last_words_num = 0
  1868. for sentence in list_sentence:
  1869. _index = sentence.sentence_index
  1870. if _index == 0:
  1871. words_num_dict[_index] = 0
  1872. else:
  1873. words_num_dict[_index] = words_num_dict[_index - 1] + last_words_num
  1874. last_words_num = len(sentence.sentence_text)
  1875. # 公司-联系人连接(km算法)
  1876. re_phone = re.compile('1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1877. '\+86.?1[3-9]\d{9}|'
  1878. # '0[1-9]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1879. '0[1-9]\d{1,2}[-—-―][2-9]\d{6,7}[^\d]?转\d{1,4}|'
  1880. '0[1-9]\d{1,2}[-—-―][2-9]\d{6}\d?[-—-―]\d{1,4}|'
  1881. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=1[3-9]\d{9})|'
  1882. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[2-9]\d{6}\d?)|'
  1883. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=[2-9]\d{6,7})|'
  1884. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?|'
  1885. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?[2-9]\d{6,7}-?\d{,4}|'
  1886. '400\d{7}转\d{1,4}|'
  1887. '[2-9]\d{6,7}')
  1888. key_phone = re.compile("联系方式|电话|联系人|负责人")
  1889. temporary_list2 = []
  1890. for entity in list_entity:
  1891. # if entity.entity_type in ['org', 'company', 'person'] and entity.is_tail==False:
  1892. if entity.entity_type in ['org', 'company', 'person']:
  1893. temporary_list2.append(entity)
  1894. temporary_list2 = sorted(temporary_list2, key=lambda x: (x.sentence_index, x.begin_index))
  1895. new_temporary_list2 = []
  1896. for _split in new_split_list:
  1897. temp_list = []
  1898. for _entity in temporary_list2:
  1899. if words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[0] and words_num_dict[
  1900. _entity.sentence_index] + _entity.wordOffset_end < _split[1]:
  1901. temp_list.append(_entity)
  1902. elif words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[1]:
  1903. break
  1904. new_temporary_list2.append(temp_list)
  1905. # print(new_temporary_list2)
  1906. match_list2 = []
  1907. for split_index in range(len(new_temporary_list2)):
  1908. split_entitys = new_temporary_list2[split_index]
  1909. if len(split_entitys)<=1:
  1910. continue
  1911. is_skip = False
  1912. for index in range(len(split_entitys)):
  1913. entity = split_entitys[index]
  1914. if is_skip:
  1915. is_skip = False
  1916. continue
  1917. else:
  1918. if entity.entity_type in ['org', 'company']:
  1919. if entity.label != 5 or entity.entity_text in roleSet:
  1920. match_nums = 0
  1921. for after_index in range(index + 1, min(len(split_entitys), index + 4)):
  1922. after_entity = split_entitys[after_index]
  1923. if entity.in_attachment != after_entity.in_attachment:
  1924. break
  1925. if after_entity.entity_type in ['person']:
  1926. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1927. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1928. # 实体为中标人/候选人,联系人已确定类别【1,2】
  1929. if entity.label in [2, 3, 4] and after_entity.label in [1, 2]:
  1930. break
  1931. if entity.label in [2, 3, 4] and distance>=20:
  1932. break
  1933. # 角色为中标候选人,排除"质疑|投诉|监督|受理"相关的联系人
  1934. if entity.label in [2, 3, 4] and re.search("质疑|投诉|监督|受理|项目(单位)?联系", list_sentence[after_entity.sentence_index].sentence_text[max(0,after_entity.wordOffset_begin - 10):after_entity.wordOffset_begin]):
  1935. break
  1936. if after_entity.sentence_index != 0 and after_entity.wordOffset_begin <= 10:
  1937. if entity.label in [2, 3, 4] and re.search("请.{0,5}联系",
  1938. list_sentence[after_entity.sentence_index - 1].sentence_text[-10:] +
  1939. list_sentence[after_entity.sentence_index].sentence_text[0:after_entity.wordOffset_begin]):
  1940. continue
  1941. if after_entity.label in [1, 2, 3]:
  1942. # distance = (tokens_num_dict[
  1943. # after_entity.sentence_index] + after_entity.begin_index) - (
  1944. # tokens_num_dict[entity.sentence_index] + entity.end_index)
  1945. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1946. if sentence_distance == 0:
  1947. if distance < 100:
  1948. if entity.label in [2, 3, 4] and distance>40:
  1949. break
  1950. if (entity.label == 0 and after_entity.label == 1) or (
  1951. entity.label == 1 and after_entity.label == 2):
  1952. distance = distance / 100
  1953. value = (-1 / 2 * (distance ** 2)) / 10000
  1954. match_list2.append(Match(entity, after_entity, value))
  1955. match_nums += 1
  1956. else:
  1957. if distance < 60:
  1958. if entity.label in [2, 3, 4] and distance>20:
  1959. break
  1960. if (entity.label == 0 and after_entity.label == 1) or (
  1961. entity.label == 1 and after_entity.label == 2):
  1962. distance = distance / 100
  1963. value = (-1 / 2 * (distance ** 2)) / 10000
  1964. match_list2.append(Match(entity, after_entity, value))
  1965. match_nums += 1
  1966. if after_entity.entity_type in ['org', 'company']:
  1967. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  1968. break
  1969. # 解决在‘地址’中识别出org/company的问题
  1970. # if entity.label in [0,1] and after_index==index+1 and after_entity.label not in [0,1]:
  1971. if entity.label != 5 and after_index == index + 1 and (
  1972. after_entity.label == entity.label or after_entity.label == 5):
  1973. distance = (tokens_num_dict[
  1974. after_entity.sentence_index] + after_entity.begin_index) - (
  1975. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1976. if distance < 20:
  1977. after_entity_left = list_sentence[after_entity.sentence_index].tokens[max(0,
  1978. after_entity.begin_index - 10):after_entity.begin_index]
  1979. after_entity_right = list_sentence[after_entity.sentence_index].tokens[
  1980. after_entity.end_index + 1:after_entity.end_index + 6]
  1981. after_entity_left = "".join(after_entity_left)
  1982. if len(after_entity_left) > 20:
  1983. after_entity_left = after_entity_left[-20:]
  1984. after_entity_right = "".join(after_entity_right)[:10]
  1985. if re.search("地,?址", after_entity_left):
  1986. is_skip = True
  1987. continue
  1988. if re.search("\(|(", after_entity_left) and re.search("\)|)",after_entity_right):
  1989. is_skip = True
  1990. continue
  1991. if entity.label in [0, 1] and after_entity.label in [0, 1] and entity.label == after_entity.label:
  1992. break
  1993. if entity.label in [0, 1] and after_entity.label in [0, 1] and split_entitys[
  1994. index + 1].entity_type == "person":
  1995. break
  1996. if entity.label in [0, 1 ,5] and after_entity.label in [2, 3, 4]:
  1997. break
  1998. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  1999. break
  2000. # 搜索没有联系人的电话
  2001. mid_tokens = []
  2002. is_same_sentence = False
  2003. if index == len(split_entitys) - 1:
  2004. for i in range(entity.sentence_index, len(list_sentence)):
  2005. mid_tokens += list_sentence[i].tokens
  2006. mid_tokens = mid_tokens[entity.end_index + 1:]
  2007. mid_sentence = "".join(mid_tokens)
  2008. have_phone = re.findall(re_phone, mid_sentence)
  2009. if have_phone:
  2010. if re.findall(re_phone, mid_sentence.split("。")[0]):
  2011. is_same_sentence = True
  2012. _phone = have_phone[0]
  2013. if _phone in [ent.entity_text for ent in phone_entitys]:
  2014. phone_begin = mid_sentence.find(_phone)
  2015. if words_num_dict[entity.sentence_index] + entity.wordOffset_begin + phone_begin < \
  2016. new_split_list[split_index][1]:
  2017. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  2018. if re.search(key_phone, mid_sentence):
  2019. if entity.label in [2, 3, 4] and re.search("质疑|投诉|监督|受理|项目(单位)?联系",mid_sentence[-8:]):
  2020. pass
  2021. else:
  2022. distance = 1
  2023. if is_same_sentence:
  2024. if phone_begin <= 200:
  2025. if entity.label in [2,3,4] and phone_begin>80:
  2026. break
  2027. value = (-1 / 2 * (distance ** 2)) / 10000
  2028. match_list2.append(Match(entity, (entity, _phone), value))
  2029. match_nums += 1
  2030. else:
  2031. if phone_begin <= 60:
  2032. if entity.label in [2,3,4] and phone_begin>40:
  2033. break
  2034. value = (-1 / 2 * (distance ** 2)) / 10000
  2035. match_list2.append(Match(entity, (entity, _phone), value))
  2036. match_nums += 1
  2037. else:
  2038. next_entity = split_entitys[index + 1]
  2039. if next_entity.entity_type in ["org","company"]:
  2040. _entity_left = list_sentence[next_entity.sentence_index].sentence_text[entity.wordOffset_end:next_entity.wordOffset_begin]
  2041. _entity_left2 = re.sub(",()\(\)::", "", _entity_left)
  2042. _entity_left2 = _entity_left2[-5:]
  2043. if re.search("(地,?址|地,?点)[::][^,。]*$", _entity_left) or re.search("地址|地点", _entity_left2):
  2044. if index + 2<= len(split_entitys) - 1:
  2045. next_entity = split_entitys[index + 2]
  2046. if len(_entity_left)<=2 and re.search("[、(\(]",_entity_left):
  2047. if index + 2 <= len(split_entitys) - 1:
  2048. next_entity = split_entitys[index + 2]
  2049. if entity.sentence_index == next_entity.sentence_index:
  2050. mid_tokens += list_sentence[entity.sentence_index].tokens[
  2051. entity.end_index + 1:next_entity.begin_index]
  2052. else:
  2053. sentence_index = entity.sentence_index
  2054. while sentence_index <= next_entity.sentence_index:
  2055. mid_tokens += list_sentence[sentence_index].tokens
  2056. sentence_index += 1
  2057. mid_tokens = mid_tokens[entity.end_index + 1:-(len(
  2058. list_sentence[next_entity.sentence_index].tokens) - next_entity.begin_index) + 1]
  2059. mid_sentence = "".join(mid_tokens)
  2060. have_phone = re.findall(re_phone, mid_sentence)
  2061. if have_phone:
  2062. if re.findall(re_phone, mid_sentence.split("。")[0]):
  2063. is_same_sentence = True
  2064. _phone = have_phone[0]
  2065. if _phone in [ent.entity_text for ent in phone_entitys]:
  2066. phone_begin = mid_sentence.find(_phone)
  2067. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  2068. if re.search(key_phone, mid_sentence):
  2069. p_phone = [p.entity_text for p in next_entity.person_phone] if next_entity.person_phone else []
  2070. if next_entity.entity_type == 'person' and _phone in p_phone:
  2071. pass
  2072. elif entity.label in [2, 3, 4] and re.search("质疑|投诉|监督|受理|项目(单位)?联系", mid_sentence[-8:]):
  2073. pass
  2074. else:
  2075. distance = (tokens_num_dict[
  2076. next_entity.sentence_index] + next_entity.begin_index) - (
  2077. tokens_num_dict[entity.sentence_index] + entity.end_index)
  2078. distance = distance / 2
  2079. if is_same_sentence:
  2080. if phone_begin <= 200:
  2081. value = (-1 / 2 * (distance ** 2)) / 10000
  2082. match_list2.append(Match(entity, (entity, _phone), value))
  2083. match_nums += 1
  2084. else:
  2085. if phone_begin <= 60:
  2086. value = (-1 / 2 * (distance ** 2)) / 10000
  2087. match_list2.append(Match(entity, (entity, _phone), value))
  2088. match_nums += 1
  2089. # 实体无匹配时,尝试前向查找匹配
  2090. if not match_nums:
  2091. if (entity.label != 5 or entity.entity_text in roleSet) and entity.values[entity.label] >= 0.5 and index != 0:
  2092. previous_entity = split_entitys[index - 1]
  2093. if previous_entity.entity_type == 'person' and previous_entity.label in [1, 2, 3]:
  2094. if entity.label in [2, 3, 4] and previous_entity.label in [1, 2]:
  2095. continue
  2096. if previous_entity.sentence_index == entity.sentence_index:
  2097. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  2098. tokens_num_dict[
  2099. previous_entity.sentence_index] + previous_entity.end_index)
  2100. if distance < 20:
  2101. # 距离相等时,前向添加处罚值
  2102. # distance += 1
  2103. # 前向 没有 /10000
  2104. value = (-1 / 2 * (distance ** 2))
  2105. match_list2.append(Match(entity, previous_entity, value))
  2106. # print(match_list2)
  2107. match_list2 = [mat for mat in match_list2 if mat.main_role not in linked_company and mat.attribute not in linked_person]
  2108. # print(match_list2)
  2109. # km算法分配求解
  2110. result2 = dispatch(match_list2)
  2111. # print(result2)
  2112. for match in result2:
  2113. entity = match[0]
  2114. # print(entity.entity_text)
  2115. # print(match.attribute)
  2116. entity_index = list_entity.index(entity)
  2117. is_update = False
  2118. if isinstance(match[1], tuple):
  2119. person_ = ''
  2120. phone_ = match[1][1].split("/") # 分割多个号码
  2121. # print(person_,phone_)
  2122. else:
  2123. person_ = match[1].entity_text
  2124. phone_ = [i.entity_text for i in match[1].person_phone] if match[1].person_phone else []
  2125. for k in PackDict.keys():
  2126. for i in range(len(PackDict[k]["roleList"])):
  2127. if PackDict[k]["roleList"][i].role_name == "tenderee":
  2128. # if not PackDict[k]["roleList"][i].linklist:
  2129. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 0:
  2130. if person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0 and person_ not in winter_contact:
  2131. if not phone_:
  2132. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  2133. for p in phone_:
  2134. # if not person_ and len()
  2135. PackDict[k]["roleList"][i].linklist.append((person_, p))
  2136. is_update = True
  2137. elif PackDict[k]["roleList"][i].role_name == "agency":
  2138. # if not PackDict[k]["roleList"][i].linklist:
  2139. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 1 and person_ not in winter_contact:
  2140. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0:
  2141. if not phone_:
  2142. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  2143. for p in phone_:
  2144. PackDict[k]["roleList"][i].linklist.append((person_, p))
  2145. is_update = True
  2146. else:
  2147. if PackDict[k]["roleList"][i].entity_text == entity.entity_text:
  2148. if not PackDict[k]["roleList"][i].linklist:
  2149. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0 and \
  2150. person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0:
  2151. if not phone_:
  2152. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  2153. for p in phone_:
  2154. PackDict[k]["roleList"][i].linklist.append((person_, p))
  2155. is_update = True
  2156. if not person_:
  2157. is_update = False
  2158. if is_update:
  2159. # 更新 list_entity
  2160. if not list_entity[entity_index].pointer_person:
  2161. list_entity[entity_index].pointer_person = []
  2162. list_entity[entity_index].pointer_person.append(match[1])
  2163. linked_person = []
  2164. linked_persons_with = []
  2165. for company_entity in [entity for entity in list_entity if entity.entity_type in ['company','org']]:
  2166. if company_entity.pointer_person:
  2167. for _person in company_entity.pointer_person:
  2168. linked_person.append(_person)
  2169. linked_persons_with.append(company_entity)
  2170. # 一个公司对应多个联系人的补充
  2171. person_entitys = [entity for entity in list_entity if entity.entity_type=='person']
  2172. person_entitys = person_entitys[::-1]
  2173. for index in range(len(person_entitys)):
  2174. entity = person_entitys[index]
  2175. prepare_link = []
  2176. if entity not in linked_person:
  2177. prepare_link.append(entity)
  2178. last_person = entity
  2179. for after_index in range(index + 1, min(len(person_entitys), index + 5)):
  2180. after_entity = person_entitys[after_index]
  2181. if after_entity.sentence_index==last_person.sentence_index and last_person.begin_index-after_entity.end_index<5:
  2182. if after_entity in linked_person:
  2183. _index = linked_person.index(after_entity)
  2184. with_company = linked_persons_with[_index]
  2185. for i in range(len(PackDict["Project"]["roleList"])):
  2186. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  2187. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 0:
  2188. for item in prepare_link:
  2189. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  2190. for _p in person_phone:
  2191. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  2192. with_company.pointer_person.append(item)
  2193. linked_person.append(item)
  2194. elif PackDict["Project"]["roleList"][i].role_name == "agency":
  2195. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 1:
  2196. for item in prepare_link:
  2197. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  2198. for _p in person_phone:
  2199. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  2200. with_company.pointer_person.append(item)
  2201. linked_person.append(item)
  2202. else:
  2203. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text:
  2204. for item in prepare_link:
  2205. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  2206. for _p in person_phone:
  2207. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  2208. with_company.pointer_person.append(item)
  2209. linked_person.append(item)
  2210. break
  2211. else:
  2212. prepare_link.append(after_entity)
  2213. last_person = after_entity
  2214. continue
  2215. # 统一同类角色的属性
  2216. for k in PackDict.keys():
  2217. for i in range(len(PackDict[k]["roleList"])):
  2218. for _entity in list_entity:
  2219. if _entity.entity_type in ['org','company']:
  2220. is_same = False
  2221. is_similar = False
  2222. # entity_text相同
  2223. if _entity.entity_text==PackDict[k]["roleList"][i].entity_text:
  2224. is_same = True
  2225. # entity.label为【0,1】
  2226. if _entity.label in [0,1] and dict_role_id[str(_entity.label)]==PackDict[k]["roleList"][i].role_name:
  2227. is_similar = True
  2228. if is_same:
  2229. linked_entitys = _entity.linked_entitys
  2230. if linked_entitys:
  2231. for linked_entity in linked_entitys:
  2232. pointer_person = linked_entity.pointer_person if linked_entity.pointer_person else []
  2233. for _pointer_person in pointer_person:
  2234. _phone = [p.entity_text for p in _pointer_person.person_phone] if _pointer_person.person_phone else []
  2235. for _p in _phone:
  2236. if (_pointer_person.entity_text,_p) not in PackDict[k]["roleList"][i].linklist:
  2237. PackDict[k]["roleList"][i].linklist.append((_pointer_person.entity_text,_p))
  2238. elif is_similar:
  2239. pointer_person = _entity.pointer_person if _entity.pointer_person else []
  2240. for _pointer_person in pointer_person:
  2241. _phone = [p.entity_text for p in _pointer_person.person_phone] if _pointer_person.person_phone else []
  2242. for _p in _phone:
  2243. if (_pointer_person.entity_text, _p) not in PackDict[k]["roleList"][i].linklist:
  2244. PackDict[k]["roleList"][i].linklist.append(
  2245. (_pointer_person.entity_text, _p))
  2246. # "roleList"中联系人电话去重
  2247. tenderee_agency_phone = []
  2248. for k in PackDict.keys():
  2249. for i in range(len(PackDict[k]["roleList"])):
  2250. if PackDict[k]["roleList"][i].role_name in ['agency','tenderee']:
  2251. tenderee_agency_phone.extend([person_phone[1] for person_phone in PackDict[k]["roleList"][i].linklist if person_phone[1]])
  2252. # 带有联系人的电话
  2253. with_person = [person_phone[1] for person_phone in PackDict[k]["roleList"][i].linklist if person_phone[0]]
  2254. # 带有电话的联系人
  2255. with_phone = [person_phone[0] for person_phone in PackDict[k]["roleList"][i].linklist if person_phone[1]]
  2256. remove_list = []
  2257. for item in PackDict[k]["roleList"][i].linklist:
  2258. if not item[0]:
  2259. if item[1] in with_person:
  2260. # 删除重复的无联系人电话
  2261. remove_list.append(item)
  2262. elif not item[1]:
  2263. if item[0] in with_phone:
  2264. remove_list.append(item)
  2265. for _item in remove_list:
  2266. PackDict[k]["roleList"][i].linklist.remove(_item)
  2267. # 中标候选人联系方式异常排除
  2268. for k in PackDict.keys():
  2269. for i in range(len(PackDict[k]["roleList"])):
  2270. if PackDict[k]["roleList"][i].role_name in ['win_tenderer', 'second_tenderer','third_tenderer']:
  2271. if tenderee_agency_phone:
  2272. remove_list = []
  2273. for item in PackDict[k]["roleList"][i].linklist:
  2274. if item[1] and item[1] in tenderee_agency_phone:
  2275. remove_list.append(item)
  2276. for _item in remove_list:
  2277. PackDict[k]["roleList"][i].linklist.remove(_item)
  2278. # else:
  2279. # # 公告中无招标代理联系方式时,可排除中标联系方式
  2280. # remove_list = []
  2281. # for _item in PackDict[k]["roleList"][i].linklist:
  2282. # # 有联系方式
  2283. # if _item[1]:
  2284. # remove_list.append(_item)
  2285. # for _item in remove_list:
  2286. # PackDict[k]["roleList"][i].linklist.remove(_item)
  2287. # PackDict更新company/org地址
  2288. last_role_prob = {}
  2289. for ent in pre_entity:
  2290. if ent.entity_type in ['company','org']:
  2291. if ent.pointer_address:
  2292. for k in PackDict.keys():
  2293. for i in range(len(PackDict[k]["roleList"])):
  2294. if PackDict[k]["roleList"][i].entity_text == ent.entity_text:
  2295. if not PackDict[k]["roleList"][i].address:
  2296. PackDict[k]["roleList"][i].address = ent.pointer_address.entity_text
  2297. last_role_prob[PackDict[k]["roleList"][i].role_name] = ent.values[role2id_dict[PackDict[k]["roleList"][i].role_name]]
  2298. else:
  2299. if PackDict[k]["roleList"][i].role_name in ['tenderee','agency']:
  2300. # 角色为招标/代理人时,取其实体概率高的链接地址作为角色address
  2301. if ent.values[role2id_dict[PackDict[k]["roleList"][i].role_name]] > last_role_prob[PackDict[k]["roleList"][i].role_name]:
  2302. PackDict[k]["roleList"][i].address = ent.pointer_address.entity_text
  2303. last_role_prob[PackDict[k]["roleList"][i].role_name] = ent.values[role2id_dict[PackDict[k]["roleList"][i].role_name]]
  2304. else:
  2305. if len(ent.pointer_address.entity_text) > len(PackDict[k]["roleList"][i].address):
  2306. PackDict[k]["roleList"][i].address = ent.pointer_address.entity_text
  2307. # 联系人——电子邮箱链接
  2308. 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])]
  2309. temporary_list3 = sorted(temporary_list3, key=lambda x: (x.sentence_index, x.begin_index))
  2310. new_temporary_list3 = []
  2311. for _split in new_split_list:
  2312. temp_list = []
  2313. for _entity in temporary_list3:
  2314. if words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[0] and words_num_dict[
  2315. _entity.sentence_index] + _entity.wordOffset_end < _split[1]:
  2316. temp_list.append(_entity)
  2317. elif words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[1]:
  2318. break
  2319. new_temporary_list3.append(temp_list)
  2320. # print(new_temporary_list3)
  2321. match_list3 = []
  2322. for split_index in range(len(new_temporary_list3)):
  2323. split_entitys = new_temporary_list3[split_index]
  2324. for index in range(len(split_entitys)):
  2325. entity = split_entitys[index]
  2326. if entity.entity_type == 'person':
  2327. match_nums = 0
  2328. for after_index in range(index + 1, min(len(split_entitys), index + 4)):
  2329. after_entity = split_entitys[after_index]
  2330. if match_nums > 2:
  2331. break
  2332. if after_entity.entity_type == 'email':
  2333. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  2334. tokens_num_dict[entity.sentence_index] + entity.end_index)
  2335. sentence_distance = after_entity.sentence_index - entity.sentence_index
  2336. if sentence_distance == 0:
  2337. if distance < 100:
  2338. if (entity.label == 0 and after_entity.label == 1) or (
  2339. entity.label == 1 and after_entity.label == 2):
  2340. distance = distance / 100
  2341. value = (-1 / 2 * (distance ** 2)) / 10000
  2342. match_list3.append(Match(entity, after_entity, value))
  2343. match_nums += 1
  2344. else:
  2345. if distance < 60:
  2346. if (entity.label == 0 and after_entity.label == 1) or (
  2347. entity.label == 1 and after_entity.label == 2):
  2348. distance = distance / 100
  2349. value = (-1 / 2 * (distance ** 2)) / 10000
  2350. match_list3.append(Match(entity, after_entity, value))
  2351. match_nums += 1
  2352. # 前向查找匹配
  2353. # if not match_nums:
  2354. if index != 0:
  2355. previous_entity = split_entitys[index - 1]
  2356. if previous_entity.entity_type == 'email':
  2357. if previous_entity.sentence_index == entity.sentence_index:
  2358. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  2359. tokens_num_dict[
  2360. previous_entity.sentence_index] + previous_entity.end_index)
  2361. if distance < 30:
  2362. # 距离相等时,前向添加处罚值
  2363. # distance += 1
  2364. # 前向 没有 /10000
  2365. value = (-1 / 2 * (distance ** 2))
  2366. match_list3.append(Match(entity, previous_entity, value))
  2367. # print(match_list3)
  2368. # km算法分配求解
  2369. result3 = dispatch(match_list3)
  2370. for match in result3:
  2371. match_person = match[0]
  2372. match_email = match[1]
  2373. match_person.pointer_email = match_email
  2374. # # 1)第一个公司实体的招标人,则看看下一个实体是否为代理人,如果是则联系人错位连接 。2)在同一句中往后找联系人。3)连接不上在整个文章找联系人。
  2375. # temp_ent_list = [] # 临时列表,记录0,1角色及3联系人
  2376. # other_person = [] # 阈值以上的联系人列表
  2377. # link_person = [] # 有电话没联系上角色的person列表
  2378. # other_ent = []
  2379. # link_ent = []
  2380. # found_person = False
  2381. # ent_list = []
  2382. # for entity in list_entity:
  2383. # if entity.entity_type in ['org','company','person']:
  2384. # ent_list.append(entity)
  2385. # # ent_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  2386. # #for list_index in range(len(ent_list)):
  2387. # #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 \
  2388. # #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']:
  2389. # #ent_list[list_index+1], ent_list[list_index+2] = ent_list[list_index+2], ent_list[list_index+1]
  2390. # # 2020/11/25增加确定角色联系人判断
  2391. # sure_person_set = set([entity.entity_text for entity in ent_list if entity.entity_type == 'person' and entity.label in [1, 2]])
  2392. # # 招标/代理在同一句中交叉情况的处理
  2393. # for index in range(len(ent_list)):
  2394. # entity = ent_list[index]
  2395. # if entity.entity_text in roleSet and entity.label in [0, 1] and index+3<len(ent_list):
  2396. # if entity.sentence_index==ent_list[index+1].sentence_index==ent_list[index+2].sentence_index==ent_list[index+3].sentence_index:
  2397. # if ent_list[index+1].begin_index - entity.end_index < 30:
  2398. # 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:
  2399. # if ent_list[index+2].entity_type=="person" and ent_list[index+3].entity_type=="person" and \
  2400. # ent_list[index+2].label==3 and ent_list[index+3].label==3:
  2401. # ent_list[index + 1], ent_list[index + 2] = ent_list[index + 2], ent_list[index + 1]
  2402. #
  2403. #
  2404. # for index in range(len(ent_list)):
  2405. # entity = ent_list[index]
  2406. # if entity.entity_type=="person":
  2407. # if str(entity.label) == "0": # 2020/11/25 非联系人直接跳过
  2408. # continue
  2409. # if entity.values[entity.label]>on_value_person:
  2410. # if str(entity.label)=="1":
  2411. # for i in range(len(PackDict["Project"]["roleList"])):
  2412. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  2413. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  2414. # link_person.append(entity.entity_text)
  2415. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2416. # # add pointer_person
  2417. # for _entity in list_entity:
  2418. # if dict_role_id.get(str(_entity.label))=="tenderee":
  2419. # for i in range(len(PackDict["Project"]["roleList"])):
  2420. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  2421. # _entity.pointer_person = entity
  2422. # elif str(entity.label)=="2":
  2423. # for i in range(len(PackDict["Project"]["roleList"])):
  2424. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  2425. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  2426. # link_person.append(entity.entity_text)
  2427. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2428. # # add pointer_person
  2429. # for _entity in list_entity:
  2430. # if dict_role_id.get(str(_entity.label))=="agency":
  2431. # for i in range(len(PackDict["Project"]["roleList"])):
  2432. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  2433. # _entity.pointer_person = entity
  2434. # elif str(entity.label)=="3":
  2435. # if entity.entity_text in sure_person_set: # 2020/11/25 排除已经确定角色的联系人
  2436. # continue
  2437. # #not_link_person.append((entity_after.entity_text,entity_after.person_phone))
  2438. # other_person.append(entity.entity_text)
  2439. # temp_ent_list.append((entity.entity_text,entity.person_phone,entity))
  2440. #
  2441. # #if entity.entity_text in roleSet:
  2442. # if entity.entity_text in roleSet:
  2443. # if entity.label in [0,1]:
  2444. # other_ent.append(entity.entity_text)
  2445. # temp_ent_list.append((entity.entity_text, entity.label,entity))
  2446. # for behind_index in range(index+1, len(ent_list)):
  2447. # entity_after = ent_list[behind_index]
  2448. # if entity_after.sentence_index-entity.sentence_index>=1 or entity_after.entity_type in ['org','company']: # 只在本句中找联系人
  2449. # break
  2450. # if entity_after.values is not None:
  2451. # if entity_after.entity_type=="person":
  2452. # if str(entity_after.label) == "0": # 2020/11/25角色后面为非联系人 停止继续往后找
  2453. # break
  2454. # if entity_after.values[entity_after.label]>on_value_person:
  2455. # if str(entity_after.label)=="1":
  2456. # for i in range(len(PackDict["Project"]["roleList"])):
  2457. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  2458. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  2459. # link_person.append(entity_after.entity_text)
  2460. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2461. # elif str(entity_after.label)=="2":
  2462. # for i in range(len(PackDict["Project"]["roleList"])):
  2463. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  2464. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  2465. # link_person.append(entity_after.entity_text)
  2466. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2467. # elif str(entity_after.label)=="3":
  2468. # if entity_after.entity_text in sure_person_set: # 2020/11/25 如果姓名已经出现在确定角色联系人中则停止往后找
  2469. # break
  2470. # elif entity_after.begin_index - entity.end_index > 30:#2020/10/25 如果角色实体与联系人实体间隔大于阈值停止
  2471. # break
  2472. # for pack in PackDict.keys():
  2473. # for i in range(len(PackDict[pack]["roleList"])):
  2474. # if PackDict[pack]["roleList"][i].entity_text==entity.entity_text:
  2475. # #if entity_after.sentence_index-entity.sentence_index>1 and len(roleList[i].linklist)>0:
  2476. # #break
  2477. # PackDict[pack]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  2478. # link_person.append(entity_after.entity_text)
  2479. # #add pointer_person
  2480. # entity.pointer_person = entity_after
  2481. #
  2482. # not_link_person = [person for person in other_person if person not in link_person]
  2483. # not_link_ent = [ent for ent in other_ent if ent not in link_ent]
  2484. # if len(not_link_person) > 0 and len(not_link_ent) > 0 :
  2485. # item = temp_ent_list
  2486. # for i in range(len(item)):
  2487. # if item[i][0] in not_link_ent and item[i][1] == 0 and i+3 < len(item):
  2488. # 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:
  2489. # item[i+1], item[i+2] = item[i+2], item[i+1]
  2490. # for i in range(len(item)-1, -1, -1):
  2491. # if item[i][0] in not_link_ent:
  2492. # for pack in PackDict.keys():
  2493. # for role in PackDict[pack]["roleList"]:
  2494. # if role.entity_text == item[i][0] and len(role.linklist) < 1:
  2495. # for j in range(i+1, len(item)):
  2496. # if item[j][0] in not_link_person:
  2497. # role.linklist.append(item[j][:2])
  2498. # #add pointer_person
  2499. # item[i][2].pointer_person = item[j][2]
  2500. # break
  2501. # else:
  2502. # break
  2503. # # 电话没有联系人的处理
  2504. # role_with_no_phone = []
  2505. # for i in range(len(PackDict["Project"]["roleList"])):
  2506. # if PackDict["Project"]["roleList"][i].role_name in ["tenderee","agency"]:
  2507. # if len(PackDict["Project"]["roleList"][i].linklist)==0: # 找出没有联系人的招标/代理人
  2508. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  2509. # else:
  2510. # phone_nums = 0
  2511. # for link in PackDict["Project"]["roleList"][i].linklist:
  2512. # if link[1]:
  2513. # phone_nums += 1
  2514. # break
  2515. # if not phone_nums:
  2516. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  2517. # if role_with_no_phone:
  2518. # phone_with_person = [entity.person_phone for entity in list_entity if entity.entity_type == "person"]
  2519. # # phone_with_person = [phone for phone in phone_with_person if phone]
  2520. #
  2521. # dict_index_sentence = {}
  2522. # for _sentence in list_sentence:
  2523. # dict_index_sentence[_sentence.sentence_index] = _sentence
  2524. # new_entity_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  2525. # for index in range(len(new_entity_list)):
  2526. # entity = new_entity_list[index]
  2527. # if entity.entity_text in role_with_no_phone:
  2528. # e_sentence = dict_index_sentence[entity.sentence_index]
  2529. # entity_right = e_sentence.tokens[entity.end_index:entity.end_index+40]
  2530. # entity_right = "".join(entity_right)
  2531. # if index+1<len(new_entity_list) and entity_right.find(new_entity_list[index+1].entity_text)>-1:
  2532. # entity_right = entity_right[:entity_right.find(new_entity_list[index+1].entity_text)]
  2533. # have_phone = re.findall(phone,entity_right)
  2534. # if have_phone:
  2535. # _phone = have_phone[0]
  2536. # phone_begin = entity_right.find(_phone)
  2537. # if _phone not in phone_with_person and re.search(key_phone,entity_right[:phone_begin]):
  2538. # # entity.person_phone = _phone
  2539. # for i in range(len(PackDict["Project"]["roleList"])):
  2540. # if PackDict["Project"]["roleList"][i].entity_text == entity.entity_text:
  2541. # PackDict["Project"]["roleList"][i].linklist.append(('', _phone))
  2542. #寻找多标段招标金额
  2543. p_entity = len(list_entity)-1
  2544. set_tenderer_money = set()
  2545. list_tenderer_money = [] #2021/7/16 新增列表,倒序保存所有中标金额
  2546. unit_list = [] #2021/8/17 新增,保存金额单位
  2547. #遍历所有实体
  2548. max_prob = 0 # 保存招标金额最大概率
  2549. while(p_entity>=0):
  2550. entity = list_entity[p_entity]
  2551. if entity.entity_type=="money":
  2552. # 2021/12/03 添加成本警戒线、保证金
  2553. if entity.notes in ['保证金', '成本警戒线']:
  2554. packagePointer, _flag = getPackage(PackageList, entity.sentence_index, entity.begin_index,
  2555. "money-" + str(entity.label), MAX_DIS=2, DIRECT="L")
  2556. if packagePointer is None:
  2557. packageName = "Project"
  2558. else:
  2559. packageName = packagePointer.entity_text
  2560. if packageName == "Project":
  2561. # if PackDict["Project"]["tendereeMoney"]<float(entity.entity_text):
  2562. # PackDict["Project"]["tendereeMoney"] = str(Decimal(entity.entity_text))
  2563. if entity.notes=="保证金" and "bond" not in PackDict["Project"]:
  2564. PackDict["Project"]["bond"] = str(Decimal(entity.entity_text))
  2565. elif entity.notes=="成本警戒线" and "cost_warning" not in PackDict["Project"]:
  2566. PackDict["Project"]["cost_warning"] = str(Decimal(entity.entity_text))
  2567. else:
  2568. if entity.notes == "保证金" and "bond" not in PackDict[packageName]:
  2569. PackDict[packageName]["bond"] = str(Decimal(entity.entity_text))
  2570. elif entity.notes == "成本警戒线" and "cost_warning" not in PackDict[packageName]:
  2571. PackDict[packageName]["cost_warning"] = str(Decimal(entity.entity_text))
  2572. elif entity.values[entity.label]>=on_value:
  2573. if str(entity.label)=="1":
  2574. set_tenderer_money.add(float(entity.entity_text))
  2575. list_tenderer_money.append(float(entity.entity_text)) # 2021/7/16 新增列表,倒序保存所有中标金额
  2576. unit_list.append(entity.money_unit)
  2577. # if str(entity.label)=="0":
  2578. if str(entity.label)=="0" and entity.notes!='总投资':
  2579. '''
  2580. if p_entity>0:
  2581. p_before = list_entity[p_entity-1]
  2582. 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:
  2583. p_entity -= 1
  2584. continue
  2585. '''
  2586. packagePointer,_flag = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label),MAX_DIS=2,DIRECT="L")
  2587. if packagePointer is None:
  2588. packageName = "Project"
  2589. else:
  2590. packageName = packagePointer.entity_text
  2591. if packageName=="Project":
  2592. # if PackDict["Project"]["tendereeMoney"]<float(entity.entity_text):
  2593. # PackDict["Project"]["tendereeMoney"] = str(Decimal(entity.entity_text))
  2594. # if entity.values[entity.label]>on_value:
  2595. if entity.values[entity.label]>max_prob: # 选择最大概率招标金额
  2596. PackDict["Project"]["tendereeMoney"] = str(Decimal(entity.entity_text))
  2597. PackDict["Project"]["tendereeMoneyUnit"] = entity.money_unit
  2598. max_prob = entity.values[entity.label]
  2599. else:
  2600. PackDict[packageName]["tendereeMoney"] = str(Decimal(entity.entity_text))
  2601. PackDict[packageName]["tendereeMoneyUnit"] = entity.money_unit
  2602. #add pointer_tendereeMoney
  2603. packagePointer.pointer_tendereeMoney = entity
  2604. p_entity -= 1
  2605. #删除一个机构有多个角色的数据
  2606. #删除重复人、概率不回传
  2607. final_roleList = []
  2608. list_pop = []
  2609. set_tenderer_role = set()
  2610. dict_pack_tenderer_money = dict()
  2611. for pack in PackDict.keys():
  2612. #删除无效包
  2613. if PackDict[pack]["code"]=="" and PackDict[pack]["tendereeMoney"]==0 and len(PackDict[pack]["roleList"])==0:
  2614. list_pop.append(pack)
  2615. for i in range(len(PackDict[pack]["roleList"])):
  2616. if PackDict[pack]["roleList"][i].role_name=="win_tenderer":
  2617. if PackDict[pack]["roleList"][i].money==0:
  2618. set_tenderer_role.add(PackDict[pack]["roleList"][i])
  2619. dict_pack_tenderer_money[pack] = [PackDict[pack]["roleList"][i],set()]
  2620. #找到包的中投标金额
  2621. for _index in range(len(PackageList)):
  2622. if "hit" in PackageList[_index]:
  2623. for _hit in list(PackageList[_index]["hit"]):
  2624. if len(_hit.split("-"))==3:
  2625. _money = float(_hit.split("-")[1]) if _hit.split("-")[0]=="money" else None
  2626. # 补充金额前新增负号‘-’导致错误的规则
  2627. elif len(_hit.split("-"))==4:
  2628. _money = float(_hit.split("-")[2]) if _hit.split("-")[0] == "money" else None
  2629. else:
  2630. _money = None
  2631. if PackageList[_index]["name"] in dict_pack_tenderer_money and _money is not None:
  2632. dict_pack_tenderer_money[PackageList[_index]["name"]][1].add(_money)
  2633. #只找到一个中标人和中标金额
  2634. if len(set_tenderer_money)==1 and len(set_tenderer_role)==1:
  2635. list(set_tenderer_role)[0].money = list(set_tenderer_money)[0]
  2636. list(set_tenderer_role)[0].money_unit = unit_list[0]
  2637. # print('一个中标人一个金额:', list(set_tenderer_money)[0])
  2638. #找到一个中标人和多个招标金额
  2639. if len(set_tenderer_money)>1 and len(set_tenderer_role)==1:
  2640. _maxMoney = list(set_tenderer_money)[0]
  2641. _sumMoney = 0
  2642. for _m in list(set_tenderer_money):
  2643. _sumMoney += _m
  2644. if _m>_maxMoney:
  2645. _maxMoney = _m
  2646. if _sumMoney/_maxMoney==2:
  2647. list(set_tenderer_role)[0].money = _maxMoney
  2648. # print('一人多金额分项合计 取最大金额:', _maxMoney)
  2649. else:
  2650. # list(set_tenderer_role)[0].money = _maxMoney
  2651. if min(list_tenderer_money)>200000 and list_tenderer_money[-1]/min(list_tenderer_money)>9000:
  2652. list(set_tenderer_role)[0].money = min(list_tenderer_money)
  2653. list(set_tenderer_role)[0].money_unit = unit_list[list_tenderer_money.index(min(list_tenderer_money))]
  2654. # print('一人多金额 且最小的大于20万第一个金额比最小金额大几千倍的最小中标金额:', min(list_tenderer_money))
  2655. else:
  2656. list(set_tenderer_role)[0].money = list_tenderer_money[-1] # 2021/7/16 修改 不是单价合计方式取第一个中标金额
  2657. list(set_tenderer_role)[0].money_unit = unit_list[-1] # 金额单位
  2658. # print('一人多金额 取第一个中标金额:', list_tenderer_money[-1])
  2659. #每个包都只找到一个金额
  2660. _flag_pack_money = True
  2661. for k,v in dict_pack_tenderer_money.items():
  2662. if len(v[1])!=1:
  2663. _flag_pack_money = False
  2664. if _flag_pack_money and len(PackageSet)==len(dict_pack_tenderer_money.keys()):
  2665. for k,v in dict_pack_tenderer_money.items():
  2666. v[0].money = list(v[1])[0]
  2667. # print('k,v in dict_pack_tenderer_money.items', k, v)
  2668. # 2021/7/16 #增加判断中标金额是否远大于招标金额逻辑
  2669. for pack in PackDict.keys():
  2670. for i in range(len(PackDict[pack]["roleList"])):
  2671. if float(PackDict[pack]["tendereeMoney"]) > 0:
  2672. # print('金额数据类型:',type(PackDict[pack]["roleList"][i].money))
  2673. if float(PackDict[pack]["roleList"][i].money) >10000000 and \
  2674. float(PackDict[pack]["roleList"][i].money)/float(PackDict[pack]["tendereeMoney"])>=1000:
  2675. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  2676. # print('招标金额校正中标金额')
  2677. # 2022/04/01 #增加判断中标金额是否远小于招标金额逻辑,比例相差10000倍左右(中标金额“万”单位丢失或未识别)
  2678. for pack in PackDict.keys():
  2679. for i in range(len(PackDict[pack]["roleList"])):
  2680. if float(PackDict[pack]["tendereeMoney"]) > 0 and float(PackDict[pack]["roleList"][i].money) > 0.:
  2681. if float(PackDict[pack]["roleList"][i].money) < 1000 and \
  2682. float(PackDict[pack]["tendereeMoney"])/float(PackDict[pack]["roleList"][i].money)>=9995 and \
  2683. float(PackDict[pack]["tendereeMoney"])/float(PackDict[pack]["roleList"][i].money)<11000:
  2684. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) * 10000
  2685. # 2021/7/19 #增加判断中标金额是否远大于第二三中标金额
  2686. for pack in PackDict.keys():
  2687. tmp_moneys = []
  2688. for i in range(len(PackDict[pack]["roleList"])):
  2689. if float(PackDict[pack]["roleList"][i].money) >100000:
  2690. tmp_moneys.append(float(PackDict[pack]["roleList"][i].money))
  2691. if len(tmp_moneys)>2 and max(tmp_moneys)/min(tmp_moneys)>1000:
  2692. for i in range(len(PackDict[pack]["roleList"])):
  2693. if float(PackDict[pack]["roleList"][i].money)/min(tmp_moneys)>1000:
  2694. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  2695. # print('通过其他中标人投标金额校正中标金额')
  2696. for item in list_pop:
  2697. PackDict.pop(item)
  2698. # 公告中只有"招标人"且无"联系人"链接时
  2699. if len(PackDict)==1:
  2700. k = list(PackDict.keys())[0]
  2701. tenderee_agency_role = [role for role in PackDict[k]["roleList"] if role.role_name in ['tenderee','agency']]
  2702. if len(tenderee_agency_role)==1:
  2703. exist_person = []
  2704. exist_phone = []
  2705. for role in PackDict[k]["roleList"]:
  2706. for group in role.linklist:
  2707. if group[0]:
  2708. exist_person.append(group[0])
  2709. if group[1]:
  2710. exist_phone.append(group[1])
  2711. if tenderee_agency_role[0].role_name == "tenderee":
  2712. if not tenderee_agency_role[0].linklist:
  2713. get_contacts = False
  2714. if not get_contacts:
  2715. # 根据大纲Outline类召回联系人
  2716. for outline in list_outline:
  2717. if re.search("联系人|联系方|联系方式|联系电话|电话|负责人|与.{2,4}联系",outline.outline_summary):
  2718. for t_person in [p for p in temporary_list2 if p.entity_type=='person' and p.label==3]:
  2719. 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[
  2720. t_person.sentence_index] + t_person.wordOffset_end < words_num_dict[outline.sentence_end_index] + outline.wordOffset_end:
  2721. if t_person.person_phone:
  2722. _phone = [p.entity_text for p in t_person.person_phone]
  2723. for _p in _phone:
  2724. if t_person.entity_text not in exist_person and _p not in exist_phone:
  2725. tenderee_agency_role[0].linklist.append((t_person.entity_text, _p))
  2726. get_contacts = True
  2727. break
  2728. elif words_num_dict[t_person.sentence_index] + t_person.wordOffset_begin >= \
  2729. words_num_dict[outline.sentence_end_index] + outline.wordOffset_end:
  2730. break
  2731. if not get_contacts:
  2732. sentence_phone = phone.findall(outline.outline_text)
  2733. if sentence_phone:
  2734. if sentence_phone[0] not in exist_phone:
  2735. tenderee_agency_role[0].linklist.append(("", sentence_phone[0]))
  2736. get_contacts = True
  2737. break
  2738. if not get_contacts:
  2739. # 直接取文中倒数第一个联系人
  2740. for _entity in temporary_list2[::-1]:
  2741. if _entity.entity_type=='person' and _entity.label==3:
  2742. if _entity.person_phone:
  2743. _phone = [p.entity_text for p in _entity.person_phone]
  2744. for _p in _phone:
  2745. if _entity.entity_text not in exist_person and _p not in exist_phone:
  2746. tenderee_agency_role[0].linklist.append((_entity.entity_text, _p))
  2747. get_contacts = True
  2748. break
  2749. if not get_contacts:
  2750. # 如果文中只有一个“phone”实体,则直接取为联系人电话
  2751. if len(phone_entitys) == 1:
  2752. if phone_entitys[0].entity_text not in exist_phone:
  2753. tenderee_agency_role[0].linklist.append(("", phone_entitys[0].entity_text))
  2754. get_contacts = True
  2755. if not get_contacts:
  2756. # 通过大纲Outline类直接取电话
  2757. if len(new_split_list) > 1:
  2758. for _start, _end in new_split_list:
  2759. temp_sentence = _content[_start:_end]
  2760. sentence_outline = temp_sentence.split(",::")[0]
  2761. if re.search("联系人|联系方|联系方式|联系电话|电话|负责人|与.{2,4}联系", sentence_outline):
  2762. sentence_phone = phone.findall(temp_sentence)
  2763. if sentence_phone:
  2764. if sentence_phone[0] in [ent.entity_text for ent in phone_entitys] and sentence_phone[0] not in exist_phone:
  2765. tenderee_agency_role[0].linklist.append(("", sentence_phone[0]))
  2766. get_contacts = True
  2767. break
  2768. if not get_contacts:
  2769. # 通过正则提取句子段落进行提取电话
  2770. contacts_person = "(?:联系人|联系方|联系方式|负责人|电话|联系电话)[::]?"
  2771. tenderee_pattern = "(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主|业主单位)[^。]{0,5}"
  2772. contact_pattern_list = [tenderee_pattern + contacts_person,
  2773. "(?:采购[^。,]{0,2}项目|采购事项|招标)[^。,]{0,4}" + contacts_person,
  2774. "(?:项目|采购)[^。,]{0,4}" + contacts_person,
  2775. "(?:报名|报价|业务咨询|业务|投标咨询)[^。,]{0,4}" + contacts_person, ]
  2776. for _pattern in contact_pattern_list:
  2777. get_tenderee_contacts = False
  2778. for regular_match in re.finditer(_pattern, _content):
  2779. match_text = _content[regular_match.end():regular_match.end() + 40]
  2780. match_text = match_text.split("。")[0]
  2781. sentence_phone = phone.findall(match_text)
  2782. if sentence_phone:
  2783. if sentence_phone[0] not in exist_phone:
  2784. tenderee_agency_role[0].linklist.append(("", sentence_phone[0]))
  2785. get_tenderee_contacts = True
  2786. break
  2787. if get_tenderee_contacts:
  2788. break
  2789. for pack in PackDict.keys():
  2790. for i in range(len(PackDict[pack]["roleList"])):
  2791. PackDict[pack]["roleList"][i] = PackDict[pack]["roleList"][i].getString()
  2792. return PackDict
  2793. def initPackageAttr(RoleList,PackageSet,win_tenderer_set,tenderee_or_agency_set):
  2794. '''
  2795. @summary: 根据拿到的roleList和packageSet初始化接口返回的数据
  2796. '''
  2797. packDict = dict()
  2798. packDict["Project"] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  2799. for item in list(PackageSet):
  2800. packDict[item] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  2801. for item in RoleList:
  2802. if packDict[item.packageName]["code"] =="":
  2803. packDict[item.packageName]["code"] = item.packageCode
  2804. # packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[]))
  2805. # packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[])) #Role(角色名称,实体名称,角色阈值,金额,金额阈值,连接列表,金额单位)
  2806. 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(角色名称,实体名称,角色阈值,金额,金额阈值,连接列表,多中标人)
  2807. return packDict
  2808. def getPackageRoleMoney(list_sentence,list_entity,list_outline):
  2809. '''
  2810. @param:
  2811. list_sentence:文章的句子list
  2812. list_entity:文章的实体list
  2813. @return: 拿到文章的包-标段号-角色-实体名称-金额-联系人-联系电话
  2814. '''
  2815. # print("=1")
  2816. theRole = getRoleList(list_sentence,list_entity)
  2817. if not theRole:
  2818. return []
  2819. # RoleList,RoleSet,PackageList,PackageSet = theRole
  2820. RoleList,RoleSet,PackageList,PackageSet,win_tenderer_set,tenderee_or_agency_set = theRole
  2821. '''
  2822. for item in PackageList:
  2823. # print(item)
  2824. '''
  2825. # PackDict = initPackageAttr(RoleList, PackageSet)
  2826. PackDict = initPackageAttr(RoleList, PackageSet, win_tenderer_set,tenderee_or_agency_set)
  2827. PackDict = findAttributeAfterEntity(PackDict, RoleSet, PackageList, PackageSet, list_sentence, list_entity, list_outline)
  2828. return PackDict
  2829. def turnBidWay(bidway):
  2830. if bidway in ("邀请招标","采购方式:邀请"):
  2831. return "邀请招标"
  2832. elif bidway in ("询价","询单","询比","采购方式:询价"):
  2833. return "询价"
  2834. elif bidway in ("竞谈","竞争性谈判","公开竞谈"):
  2835. return "竞争性谈判"
  2836. elif bidway in ("竞争性磋商","磋商"):
  2837. return "竞争性磋商"
  2838. elif bidway in ("竞价","竞标","电子竞价","以电子竞价","电子书面竞投"):
  2839. return "竞价"
  2840. elif bidway in ("公开招标","网上电子投标","网上招标","采购方式:公开","招标为其他"):
  2841. return "公开招标"
  2842. elif bidway in ("单一来源"):
  2843. return "单一来源"
  2844. elif bidway in ("比选"):
  2845. return "比选"
  2846. else:
  2847. return "其他"
  2848. def turnMoneySource(moneysource):
  2849. result_list = []
  2850. if re.search("自筹|业主筹集|筹资|自有",moneysource):
  2851. result_list.append("自筹")
  2852. if re.search("财政",moneysource) and not re.search("非财政",moneysource):
  2853. result_list.append("财政资金")
  2854. if re.search("拨款|补助|划拨|拨付|国拨|上级资金",moneysource):
  2855. result_list.append("上级拨款")
  2856. if re.search("社会资本|社会资金",moneysource):
  2857. result_list.append("社会资本")
  2858. if re.search("贷款|借款|借贷",moneysource):
  2859. result_list.append("贷款资金")
  2860. if re.search("债券|债|国债",moneysource):
  2861. result_list.append("债券资金")
  2862. if re.search("专项|项目资金",moneysource):
  2863. result_list.append("项目专项资金")
  2864. if re.search("配套",moneysource):
  2865. result_list.append("配套资金")
  2866. if re.search("外资",moneysource):
  2867. result_list.append("外资")
  2868. if re.search("国有资金|国企资金|国资|国家投资",moneysource):
  2869. result_list.append("国有资金")
  2870. if re.search("投资|融资",moneysource):
  2871. result_list.append("投资资金")
  2872. if re.search("预算(?<!外)|预算内",moneysource):
  2873. result_list.append("预算内资金")
  2874. if re.search("预算外",moneysource):
  2875. result_list.append("预算外资金")
  2876. result_list = sorted(result_list,key = lambda x:x)
  2877. if len(result_list)>0 and len(result_list)<5:
  2878. return ",".join(result_list)
  2879. else:
  2880. return "其他资金"
  2881. my_time_format_pattern = re.compile("((?P<year>20\d{2}|\d{2}|二[零〇0][零〇一二三四五六七八九0]{2})\s*[-/年.]\s*(?P<month>\d{1,2}|[一二三四五六七八九十]{1,3})\s*[-/月.]\s*(?P<day>\d{1,2}|[一二三四五六七八九十]{1,3}))")
  2882. from BiddingKG.dl.ratio.re_ratio import getUnifyNum
  2883. import time,datetime
  2884. def my_timeFormat(_time,page_time):
  2885. if page_time:
  2886. current_year = time.strftime("%Y",time.localtime(int(datetime.datetime.strptime(page_time, '%Y-%m-%d').timestamp())))
  2887. else:
  2888. current_year = time.strftime("%Y",time.localtime())
  2889. all_match = re.finditer(my_time_format_pattern,_time)
  2890. time_list = []
  2891. for _match in all_match:
  2892. if len(_match.group())>0:
  2893. legal = True
  2894. year = ""
  2895. month = ""
  2896. day = ""
  2897. for k,v in _match.groupdict().items():
  2898. if k=="year":
  2899. year = v
  2900. if k=="month":
  2901. month = v
  2902. if k=="day":
  2903. day = v
  2904. if year!="":
  2905. if re.search("^\d+$", year):
  2906. if len(year) == 2:
  2907. year = "20" + year
  2908. if int(year) - int(current_year) > 5 or int(year) - int(current_year) < -1:
  2909. legal = False
  2910. else:
  2911. if int(year) - int(current_year)>10 or int(year) - int(current_year) < -1:
  2912. legal = False
  2913. else:
  2914. _year = ""
  2915. for word in year:
  2916. if word == '0':
  2917. _year += word
  2918. else:
  2919. _year += str(getDigitsDic(word))
  2920. year = _year
  2921. else:
  2922. legal = False
  2923. if month!="":
  2924. if re.search("^\d+$", month):
  2925. if int(month) > 12:
  2926. legal = False
  2927. else:
  2928. month = int(getUnifyNum(month))
  2929. if month >= 1 and month <= 12:
  2930. month = str(month)
  2931. else:
  2932. legal = False
  2933. else:
  2934. legal = False
  2935. if day!="":
  2936. if re.search("^\d+$", day):
  2937. if int(day) > 31:
  2938. legal = False
  2939. else:
  2940. day = int(getUnifyNum(day))
  2941. if day >= 1 and day <= 31:
  2942. day = str(day)
  2943. else:
  2944. legal = False
  2945. else:
  2946. legal = False
  2947. if not isValidDate(int(year),int(month),int(day)):
  2948. legal = False
  2949. if legal:
  2950. # 数字字符格式化
  2951. year = str(int(year))
  2952. month = str(int(month))
  2953. day = str(int(day))
  2954. time_list.append("%s-%s-%s"%(year,month.rjust(2,"0"),day.rjust(2,"0")))
  2955. return time_list
  2956. def getTimeAttributes(list_entity,list_sentence,page_time):
  2957. time_entitys = [i for i in list_entity if i.entity_type=='time']
  2958. time_entitys = sorted(time_entitys,key=lambda x:(x.sentence_index, x.begin_index))
  2959. list_sentence = sorted(list_sentence,key=lambda x:x.sentence_index)
  2960. dict_time = {
  2961. "time_release": [], # 1 发布时间
  2962. "time_bidopen": [], # 2 开标时间
  2963. "time_bidclose": [], # 3 截标时间
  2964. 'time_bidstart': [], # 12 投标(开始)时间、响应文件接收(开始)时间
  2965. 'time_publicityStart': [], # 4 公示开始时间(公示时间、公示期)
  2966. 'time_publicityEnd': [], # 5 公示截止时间
  2967. 'time_getFileStart': [], # 6 文件获取开始时间(文件获取时间)
  2968. 'time_getFileEnd': [], # 7 文件获取截止时间
  2969. 'time_registrationStart': [], # 8 报名开始时间(报名时间)
  2970. 'time_registrationEnd': [], # 9 报名截止时间
  2971. 'time_earnestMoneyStart': [], #10 保证金递交开始时间(保证金递交时间)
  2972. 'time_earnestMoneyEnd': [] , # 11 保证金递交截止时间
  2973. 'time_commencement':[] , #13 开工日期
  2974. 'time_completion': [], # 14 竣工日期
  2975. 'time_listingStart': [], # 15 挂牌开始日期(挂牌时间)
  2976. 'time_listingEnd': [], # 16 挂牌结束日期、挂牌截止日期
  2977. 'time_signContract': [], # 17 合同签订时间
  2978. 'time_contractStart': [], # 18 合同开始时间
  2979. 'time_contractEnd': [] # 19 合同结束时间
  2980. }
  2981. dict_time2label = {
  2982. "time_release": 1, # 1 发布时间
  2983. "time_bidopen": 2, # 2 开标时间
  2984. "time_bidclose": 3, # 3 截标时间
  2985. 'time_bidstart': 12, # 12 投标(开始)时间、响应文件接收(开始)时间
  2986. 'time_publicityStart': 4, # 4 公示开始时间(公示时间、公示期)
  2987. 'time_publicityEnd': 5, # 5 公示截止时间
  2988. 'time_getFileStart': 6, # 6 文件获取开始时间(文件获取时间)
  2989. 'time_getFileEnd': 7, # 7 文件获取截止时间
  2990. 'time_registrationStart': 8, # 8 报名开始时间(报名时间)
  2991. 'time_registrationEnd': 9, # 9 报名截止时间
  2992. 'time_earnestMoneyStart': 10, # 10 保证金递交开始时间(保证金递交时间)
  2993. 'time_earnestMoneyEnd': 11, # 11 保证金递交截止时间
  2994. 'time_commencement': 13, # 13 开工日期
  2995. 'time_completion': 14, # 14 竣工日期
  2996. 'time_listingStart': 15, # 15 挂牌开始日期(挂牌时间)
  2997. 'time_listingEnd': 16, # 16 挂牌结束日期、挂牌截止日期
  2998. 'time_signContract': 17, # 17 合同签订时间
  2999. 'time_contractStart': 18, # 18 合同开始时间
  3000. 'time_contractEnd': 19 # 19 合同结束时间
  3001. }
  3002. last_sentence_index = 0
  3003. last_time_type = ""
  3004. last_time_index = {
  3005. 'time_bidstart':"time_bidclose",
  3006. 'time_publicityStart':"time_publicityEnd",
  3007. 'time_getFileStart':"time_getFileEnd",
  3008. 'time_registrationStart':"time_registrationEnd",
  3009. 'time_earnestMoneyStart':"time_earnestMoneyEnd",
  3010. 'time_commencement':"time_completion",
  3011. 'time_listingStart':"time_listingEnd",
  3012. 'time_contractStart':"time_contractEnd"
  3013. }
  3014. for entity in time_entitys:
  3015. sentence_text = list_sentence[entity.sentence_index].sentence_text
  3016. if entity.sentence_index!=last_sentence_index:
  3017. # sentence_index 不同句子重置last_time_type
  3018. last_time_type = ""
  3019. entity_left = sentence_text[max(0, entity.wordOffset_begin - 2):entity.wordOffset_begin]
  3020. entity_left2 = sentence_text[max(0, entity.wordOffset_begin - 10):entity.wordOffset_begin]
  3021. entity_left3 = sentence_text[max(0, entity.wordOffset_begin - 25):entity.wordOffset_begin]
  3022. entity_right = sentence_text[entity.wordOffset_end:entity.wordOffset_end + 3]
  3023. label_prob = entity.values[entity.label]
  3024. entity_text = entity.entity_text
  3025. in_attachment = entity.in_attachment
  3026. extract_time = my_timeFormat(entity_text,page_time)
  3027. # print(entity_text,entity_left2)
  3028. if extract_time:
  3029. definite_time_list = []
  3030. t = re.compile("(北京时间)?(?P<day>下午|上午|早上)?(?P<hour>\d{1,2})[::时点](?P<half_hour>半)?(?P<minute>\d{1,2})?[::分]?(?P<second>\d{2})?秒?")
  3031. _entity_text = re.sub(" (?=[^\d])|(?<=[^\d]) ","",entity_text)
  3032. _entity_text_len = len(_entity_text)
  3033. _entity_text = _entity_text + sentence_text[entity.wordOffset_end:entity.wordOffset_end+20]
  3034. t_in_word_num = len(re.findall(t,_entity_text))
  3035. # t_out_of_word = re.search("^[^\d]{,2}"+t.pattern,re.sub(" (?=[^\d])|(?<=[^\d]) ","",sentence_text[entity.wordOffset_end:]))
  3036. begin_index = 0
  3037. for _num in range(t_in_word_num):
  3038. if begin_index> _entity_text_len + 8:
  3039. break
  3040. t_in_word = re.search(t, _entity_text[begin_index:])
  3041. if t_in_word:
  3042. if _num==0 and t_in_word.start() > _entity_text_len + 8:
  3043. break
  3044. begin_index = t_in_word.end()
  3045. # print('t_in_word',entity_text,t_in_word.groupdict())
  3046. day = t_in_word.groupdict().get('day',"")
  3047. hour = t_in_word.groupdict().get('hour',"")
  3048. half_hour = t_in_word.groupdict().get('half_hour',"")
  3049. minute = t_in_word.groupdict().get('minute',"")
  3050. second = t_in_word.groupdict().get('second',"")
  3051. if hour:
  3052. if day=='下午' and int(hour)<12:
  3053. hour = str(int(hour)+12)
  3054. if int(hour)>24:
  3055. continue
  3056. else:
  3057. hour = "00"
  3058. if not minute:
  3059. if half_hour:
  3060. minute = "30"
  3061. else:
  3062. minute = "00"
  3063. if int(minute)>60:
  3064. continue
  3065. if not second:
  3066. second = "00"
  3067. if int(second)>60:
  3068. continue
  3069. definite_time = "%s:%s:%s"%(hour.rjust(2,"0"),minute.rjust(2,"0"),second.rjust(2,"0"))
  3070. # print(definite_time)
  3071. definite_time_list.append(definite_time)
  3072. # if t_out_of_word:
  3073. # # print('t_out_of_word', entity_text+sentence_text[entity.wordOffset_end:], t_out_of_word.groupdict())
  3074. # day = t_out_of_word.groupdict().get('day', "")
  3075. # hour = t_out_of_word.groupdict().get('hour', "")
  3076. # half_hour = t_out_of_word.groupdict().get('half_hour', "")
  3077. # minute = t_out_of_word.groupdict().get('minute', "")
  3078. # second = t_out_of_word.groupdict().get('second', "")
  3079. # if hour:
  3080. # if day == '下午' and int(hour) < 12:
  3081. # hour = str(int(hour) + 12)
  3082. # if int(hour) > 24:
  3083. # continue
  3084. # else:
  3085. # hour = "00"
  3086. # if not minute:
  3087. # if half_hour:
  3088. # minute = "30"
  3089. # else:
  3090. # minute = "00"
  3091. # if int(minute) > 60:
  3092. # continue
  3093. # if not second:
  3094. # second = "00"
  3095. # if int(second) > 60:
  3096. # continue
  3097. # definite_time = "%s:%s:%s" % (hour.rjust(2, "0"), minute.rjust(2, "0"), second.rjust(2, "0"))
  3098. # # print(definite_time)
  3099. # definite_time_list.append(definite_time)
  3100. #
  3101. min_len = min(len(extract_time),len(definite_time_list))
  3102. for i in range(min_len):
  3103. if definite_time_list[i] != "00:00:00":
  3104. extract_time[i] = extract_time[i] + " " + definite_time_list[i]
  3105. if extract_time:
  3106. # 时间变更prob优化
  3107. if re.search("原",entity_left2):
  3108. last_index = 0
  3109. for item in re.finditer("原",entity_left2):
  3110. last_index = item.start() + 1
  3111. label_prob = label_prob - 0.2 * last_index / len(entity_left2)
  3112. # print('prob优化',label_prob,extract_time)
  3113. elif re.search("改正|更正|修正|更改|延期",entity_left2):
  3114. new_label = dict_time2label.get(last_time_type,None)
  3115. if new_label and entity.label==0:
  3116. entity.label = new_label
  3117. label_prob = 1
  3118. # 优化多个并列的时间,如:开标时间和截标时间,截标时间和报名结束时间
  3119. if entity.label in [2,3,9]:
  3120. if entity.label==2 and re.search("截标|投标.{,2}截止|([递提]交|接收)(?:文件)?.{,2}截止|报价.{,2}截止|响应.{,2}截止|文件.{,2}([递提]交|接收)",entity_left3):
  3121. dict_time['time_bidclose'].append((extract_time[0], label_prob, in_attachment))
  3122. if entity.label==3 and re.search("开标|评审.{,2}(?:开始)?时间|选取.{,2}时间",entity_left3):
  3123. dict_time['time_bidopen'].append((extract_time[0], label_prob, in_attachment))
  3124. if entity.label==3 and re.search("报名",entity_left3):
  3125. dict_time['time_registrationEnd'].append((extract_time[0], 0.5, in_attachment))
  3126. if entity.label==9 and re.search("截标|投标.{,2}截止|([递提]交|接收)(?:文件)?.{,2}截止|报价.{,2}截止|响应.{,2}截止|文件.{,2}([递提]交|接收)",entity_left3):
  3127. dict_time['time_bidclose'].append((extract_time[0], label_prob, in_attachment))
  3128. if entity.label in [11, 3]:
  3129. if entity.label==11 and re.search("文件.{,2}([递提]交|接收)|截标|投标.{,2}截止|([递提]交|接收)(?:文件)?.{,2}截止|报价.{,2}截止|响应.{,2}截止",entity_left3):
  3130. dict_time['time_bidclose'].append((extract_time[0], 0.5, in_attachment))
  3131. if entity.label==3 and re.search("保证金.{,2}(接受|收取)|(接受|收取).{,2}保证金",entity_left3):
  3132. dict_time['time_earnestMoneyEnd'].append((extract_time[0], 0.5, in_attachment))
  3133. if entity.label in [6, 7]:
  3134. if re.search("文件.{,2}([递提]交|接收)|截标|投标.{,2}截止|([递提]交|接收)(?:文件)?.{,2}截止|报价.{,2}截止|响应.{,2}截止",entity_left3):
  3135. dict_time['time_bidclose'].append((extract_time[0], 0.5, in_attachment))
  3136. if entity.label==0:
  3137. if re.search("文件.{,2}([递提]交|接收)|截标|投标.{,2}截止|([递提]交|接收)(?:文件)?.{,2}截止|报价.{,2}截止|响应.{,2}截止",entity_left3):
  3138. dict_time['time_bidclose'].append((extract_time[0], 0.45, in_attachment))
  3139. # 补充公告末尾处的发布时间
  3140. if entity.label==0:
  3141. if entity.is_tail:
  3142. entity.label = 1
  3143. entity.values[1] = 0.5
  3144. dict_time['time_release'].append((extract_time[0], 0.5, in_attachment))
  3145. # 2022/12/12 新增挂牌时间正则
  3146. if re.search("挂牌.{,4}(?:时间|日期)",entity_left2):
  3147. if re.search("挂牌.{,4}(?:时间|日期)",entity_left2).end()>len(entity_left2)/2:
  3148. if len(extract_time) == 1:
  3149. if re.search("挂牌.?(开始|起始).?(?:时间|日期)",entity_left2):
  3150. dict_time['time_listingStart'].append((extract_time[0], 0.5, in_attachment))
  3151. last_time_type = 'time_listingStart'
  3152. elif re.search("挂牌.?(截[止至]|结束).?(?:时间|日期)",entity_left2):
  3153. dict_time['time_listingEnd'].append((extract_time[0], 0.5, in_attachment))
  3154. last_time_type = 'time_listingEnd'
  3155. elif re.search("挂牌.?(?:时间|日期)",entity_left2):
  3156. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3157. dict_time['time_listingEnd'].append((extract_time[0], 0.5, in_attachment))
  3158. last_time_type = 'time_listingEnd'
  3159. else:
  3160. dict_time['time_listingStart'].append((extract_time[0], 0.5, in_attachment))
  3161. last_time_type = 'time_listingStart'
  3162. else:
  3163. dict_time['time_listingStart'].append((extract_time[0], 0.5, in_attachment))
  3164. dict_time['time_listingEnd'].append((extract_time[1], 0.5, in_attachment))
  3165. last_time_type = ''
  3166. last_sentence_index = entity.sentence_index
  3167. continue
  3168. # 2023/9/13 新增合同相关时间
  3169. if re.search("合同|服务|履[约行]", entity_left2):
  3170. if len(extract_time) == 1:
  3171. if re.search("(合同.{,2}签[订定署].{,2}|签[订定署].{,2}合同.{,2})(?:时间|日期)|合同签[订定署].{,1}$", entity_left2):
  3172. dict_time['time_signContract'].append((extract_time[0], 0.5, in_attachment))
  3173. last_time_type = 'time_signContract'
  3174. elif re.search("(合同|服务|履约|(合同|服务)履行).{,2}(?:起始|开始)(?:时间|日期)", entity_left2):
  3175. dict_time['time_contractStart'].append((extract_time[0], 0.55, in_attachment))
  3176. last_time_type = 'time_contractStart'
  3177. elif re.search("(合同|服务|履约).{,2}(?:完成|截止|结束)(?:时间|日期|时限)", entity_left2):
  3178. dict_time['time_contractEnd'].append((extract_time[0], 0.55, in_attachment))
  3179. last_time_type = 'time_contractEnd'
  3180. elif re.search("(?:合同|服务|履约|(合同|服务)履行)(?:期限?|有效期)|(?:服务|履约|(合同|服务)履行)(?:时间|日期|周期)|服务[时年]限|合同周期", entity_left2):
  3181. if re.search("到|至|截[至止]",entity_left) or re.search("前|止|截止",entity_right) or re.search("前",entity_text[-2:]):
  3182. dict_time['time_contractEnd'].append((extract_time[0], 0.5, in_attachment))
  3183. last_time_type = 'time_contractEnd'
  3184. else:
  3185. dict_time['time_contractStart'].append((extract_time[0], 0.5, in_attachment))
  3186. last_time_type = 'time_contractStart'
  3187. else:
  3188. if re.search("(?:合同|服务|履约|(合同|服务)履行)(?:期限?|有效期)|(?:服务|履约|(合同|服务)履行)(?:时间|日期|周期)|服务[时年]限|合同周期", entity_left2):
  3189. # 排除开始和借宿时间一样的错误模板,例:“履约期限:2023年02月15日至2023年02月15日”
  3190. if extract_time[0]!=extract_time[1]:
  3191. dict_time['time_contractStart'].append((extract_time[0], 0.6, in_attachment))
  3192. dict_time['time_contractEnd'].append((extract_time[1], 0.6, in_attachment))
  3193. last_time_type = ''
  3194. # 服务期限表达补充
  3195. if entity.label==0:
  3196. re_service = '合同期限|工期/交货期/服务期|工期\(交货期\)|合格工期|服务期限|工期' \
  3197. '|工期要求|项目周期|工期\(交货期\)|计划工期\(服务期限\)|服务时限|履行期限|服务周期|供货期限' \
  3198. '|合格工期|计划工期\(服务期\)|服务期|服务,期|交货\(完工\)时间|交付\(服务、完工\)时间' \
  3199. '|交货时间|工期承诺|(服务|合同|施工|实施|工程|设计)的?(年限|期限|周期|期:)' \
  3200. '|服务期限为|计划工期|工期要求|服务期限|服务期' \
  3201. '|投标工期|设计工期|合格服务周期|总工期|服务时间(范围)?|流转期限|维护期限|服务时限|交货期' \
  3202. '|完成时间|服务期限|中标工期|项目周期|期限要求|供货期|合同履行日期|计划的?周期' \
  3203. '|履约期限|合同约定完成时限|合同完成日期|承诺完成日期' \
  3204. '|合同起始日起|合同履约期|履约截止日期|承包期限|合同完成日期' \
  3205. '|服务期间|服务履行期|委托(管理)?期限'
  3206. if len(extract_time)==2:
  3207. if re.search(re_service,entity_left2):
  3208. dict_time['time_contractStart'].append((extract_time[0], 0.5, in_attachment))
  3209. dict_time['time_contractEnd'].append((extract_time[1], 0.5, in_attachment))
  3210. last_time_type = ''
  3211. # 报价/投标时间补充
  3212. if entity.label == 0:
  3213. if re.search("[报竞]价.{,2}(开始|起始).{,2}时间",entity_left2):
  3214. entity.label = 12
  3215. label_prob = 0.8
  3216. elif re.search("[报竞]价.{,2}起止.{,2}时间",entity_left2):
  3217. entity.label = 12
  3218. label_prob = 0.6
  3219. elif re.search("响应.{,2}文件([递提]交|接收).{,2}时间[::]|([递提]交|接收).{,2}响应.{,2}文件.{,2}时间[::]",entity_left2):
  3220. entity.label = 3
  3221. label_prob = 0.501
  3222. elif re.search("响应.{,2}文件([递提]交|接收).{,2}时间|([递提]交|接收).{,2}响应.{,2}文件.{,2}时间",entity_left2) and not re.search("截[止至]",entity_left2):
  3223. entity.label = 12
  3224. label_prob = 0.51
  3225. elif re.search("[报竞]价.{,2}截[止至].{,2}时间",entity_left2):
  3226. entity.label = 3
  3227. label_prob = 0.8
  3228. if re.search("至|到|[日\d][-—]$|[~~]", entity_left):
  3229. if entity.sentence_index == last_sentence_index:
  3230. time_type = last_time_index.get(last_time_type)
  3231. if time_type:
  3232. dict_time[time_type].append((extract_time[0], 0.5 + label_prob / 10,in_attachment))
  3233. last_time_type = ""
  3234. last_sentence_index = entity.sentence_index
  3235. continue
  3236. if entity.label!=0:
  3237. if entity.label==1 and label_prob>0.5:
  3238. dict_time['time_release'].append((extract_time[0],label_prob,in_attachment))
  3239. last_time_type = 'time_release'
  3240. elif entity.label==2 and label_prob>0.5:
  3241. dict_time['time_bidopen'].append((extract_time[0],label_prob,in_attachment))
  3242. last_time_type = 'time_bidopen'
  3243. elif entity.label==3 and label_prob>0.5:
  3244. if len(extract_time)==1:
  3245. dict_time['time_bidclose'].append((extract_time[0],label_prob,in_attachment))
  3246. last_time_type = 'time_bidclose'
  3247. elif len(extract_time)==2:
  3248. dict_time['time_bidstart'].append((extract_time[0], 0.6, in_attachment))
  3249. dict_time['time_bidclose'].append((extract_time[1], label_prob, in_attachment))
  3250. last_time_type = 'time_bidclose'
  3251. elif entity.label==12 and label_prob>0.5:
  3252. if len(extract_time)==1:
  3253. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3254. dict_time['time_bidclose'].append((extract_time[0], label_prob,in_attachment))
  3255. last_time_type = 'time_bidclose'
  3256. else:
  3257. dict_time['time_bidstart'].append((extract_time[0], label_prob,in_attachment))
  3258. last_time_type = 'time_bidstart'
  3259. else:
  3260. dict_time['time_bidstart'].append((extract_time[0],label_prob,in_attachment))
  3261. dict_time['time_bidclose'].append((extract_time[1],label_prob,in_attachment))
  3262. last_time_type = ''
  3263. elif entity.label==4 and label_prob>0.5:
  3264. if len(extract_time)==1:
  3265. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3266. dict_time['time_publicityEnd'].append((extract_time[0], label_prob,in_attachment))
  3267. last_time_type = 'time_publicityEnd'
  3268. else:
  3269. dict_time['time_publicityStart'].append((extract_time[0], label_prob,in_attachment))
  3270. last_time_type = 'time_publicityStart'
  3271. else:
  3272. dict_time['time_publicityStart'].append((extract_time[0],label_prob,in_attachment))
  3273. dict_time['time_publicityEnd'].append((extract_time[1],label_prob,in_attachment))
  3274. last_time_type = ''
  3275. elif entity.label==5 and label_prob>0.5:
  3276. if len(extract_time)==1:
  3277. dict_time['time_publicityEnd'].append((extract_time[0], label_prob,in_attachment))
  3278. last_time_type = 'time_publicityEnd'
  3279. else:
  3280. dict_time['time_publicityStart'].append((extract_time[0],label_prob,in_attachment))
  3281. dict_time['time_publicityEnd'].append((extract_time[1],label_prob,in_attachment))
  3282. last_time_type = ''
  3283. elif entity.label==6 and label_prob>0.5:
  3284. if len(extract_time)==1:
  3285. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3286. dict_time['time_getFileEnd'].append((extract_time[0], label_prob,in_attachment))
  3287. last_time_type = 'time_getFileEnd'
  3288. else:
  3289. dict_time['time_getFileStart'].append((extract_time[0], label_prob,in_attachment))
  3290. last_time_type = 'time_getFileStart'
  3291. else:
  3292. dict_time['time_getFileStart'].append((extract_time[0],label_prob,in_attachment))
  3293. dict_time['time_getFileEnd'].append((extract_time[1],label_prob,in_attachment))
  3294. last_time_type = ''
  3295. elif entity.label==7 and label_prob>0.5:
  3296. if len(extract_time)==1:
  3297. dict_time['time_getFileEnd'].append((extract_time[0], label_prob,in_attachment))
  3298. last_time_type = 'time_getFileEnd'
  3299. else:
  3300. dict_time['time_getFileStart'].append((extract_time[0],label_prob,in_attachment))
  3301. dict_time['time_getFileEnd'].append((extract_time[1],label_prob,in_attachment))
  3302. last_time_type = ''
  3303. elif entity.label==8 and label_prob>0.5:
  3304. if len(extract_time)==1:
  3305. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3306. dict_time['time_registrationEnd'].append((extract_time[0], label_prob,in_attachment))
  3307. last_time_type = 'time_registrationEnd'
  3308. else:
  3309. dict_time['time_registrationStart'].append((extract_time[0], label_prob,in_attachment))
  3310. last_time_type = 'time_registrationStart'
  3311. else:
  3312. dict_time['time_registrationStart'].append((extract_time[0],label_prob,in_attachment))
  3313. dict_time['time_registrationEnd'].append((extract_time[1],label_prob,in_attachment))
  3314. last_time_type = ''
  3315. elif entity.label==9 and label_prob>0.5:
  3316. if len(extract_time)==1:
  3317. dict_time['time_registrationEnd'].append((extract_time[0], label_prob,in_attachment))
  3318. last_time_type = 'time_registrationEnd'
  3319. else:
  3320. dict_time['time_registrationStart'].append((extract_time[0],label_prob,in_attachment))
  3321. dict_time['time_registrationEnd'].append((extract_time[1],label_prob,in_attachment))
  3322. last_time_type = ''
  3323. elif entity.label==10 and label_prob>0.5:
  3324. if len(extract_time)==1:
  3325. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3326. dict_time['time_earnestMoneyEnd'].append((extract_time[0], label_prob,in_attachment))
  3327. last_time_type = 'time_earnestMoneyEnd'
  3328. else:
  3329. dict_time['time_earnestMoneyStart'].append((extract_time[0], label_prob,in_attachment))
  3330. last_time_type = 'time_earnestMoneyStart'
  3331. else:
  3332. dict_time['time_earnestMoneyStart'].append((extract_time[0],label_prob,in_attachment))
  3333. dict_time['time_earnestMoneyEnd'].append((extract_time[1],label_prob,in_attachment))
  3334. last_time_type = ''
  3335. elif entity.label==11 and label_prob>0.5:
  3336. if len(extract_time)==1:
  3337. dict_time['time_earnestMoneyEnd'].append((extract_time[0], label_prob,in_attachment))
  3338. last_time_type = 'time_earnestMoneyEnd'
  3339. else:
  3340. dict_time['time_earnestMoneyStart'].append((extract_time[0],label_prob,in_attachment))
  3341. dict_time['time_earnestMoneyEnd'].append((extract_time[1],label_prob,in_attachment))
  3342. last_time_type = ''
  3343. elif entity.label==13 and label_prob>0.5:
  3344. if len(extract_time)==1:
  3345. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3346. dict_time['time_completion'].append((extract_time[0], label_prob,in_attachment))
  3347. last_time_type = 'time_completion'
  3348. else:
  3349. dict_time['time_commencement'].append((extract_time[0], label_prob,in_attachment))
  3350. last_time_type = 'time_commencement'
  3351. else:
  3352. dict_time['time_commencement'].append((extract_time[0],label_prob,in_attachment))
  3353. dict_time['time_completion'].append((extract_time[1],label_prob,in_attachment))
  3354. last_time_type = ''
  3355. elif entity.label==14 and label_prob>0.5:
  3356. if len(extract_time)==1:
  3357. dict_time['time_completion'].append((extract_time[0], label_prob,in_attachment))
  3358. last_time_type = 'time_completion'
  3359. else:
  3360. dict_time['time_commencement'].append((extract_time[0],label_prob,in_attachment))
  3361. dict_time['time_completion'].append((extract_time[1],label_prob,in_attachment))
  3362. last_time_type = ''
  3363. else:
  3364. last_time_type = ""
  3365. else:
  3366. last_time_type = ""
  3367. else:
  3368. last_time_type = ""
  3369. last_sentence_index = entity.sentence_index
  3370. # print(dict_time)
  3371. result_dict = dict((key,"") for key in dict_time.keys())
  3372. for time_type,value in dict_time.items():
  3373. list_time = dict_time[time_type]
  3374. if list_time:
  3375. for in_attachment in [False,True]:
  3376. _list_time = [_time for _time in list_time if _time[2]==in_attachment]
  3377. if _list_time:
  3378. _list_time.sort(key=lambda x:x[1],reverse=True)
  3379. if in_attachment==True and len(result_dict[time_type])>0:
  3380. break
  3381. result_dict[time_type] = _list_time[0][0]
  3382. # result_dict 纠错
  3383. if not result_dict['time_bidclose']:
  3384. if result_dict['time_bidstart']: # 无截标时间,投标开始和开标时间一样
  3385. if result_dict['time_bidstart'][:10] in result_dict['time_bidopen']:
  3386. result_dict['time_bidstart'] = ""
  3387. result_dict['time_bidclose'] = result_dict['time_bidopen']
  3388. if not result_dict['time_bidclose']:
  3389. if result_dict['time_getFileEnd']: # 无截标时间,获取文件截止时间和开标时间一样
  3390. if result_dict['time_getFileEnd'][:10] in result_dict['time_bidopen']:
  3391. result_dict['time_bidclose'] = result_dict['time_bidopen']
  3392. else:
  3393. if result_dict['time_bidopen']: # 截标时间 和 开标时间 时分秒互补
  3394. if len(result_dict['time_bidclose'])<len(result_dict['time_bidopen']) and result_dict['time_bidclose'] in result_dict['time_bidopen']:
  3395. result_dict['time_bidclose'] = result_dict['time_bidopen']
  3396. elif len(result_dict['time_bidclose'])>len(result_dict['time_bidopen']) and result_dict['time_bidopen'] in result_dict['time_bidclose']:
  3397. result_dict['time_bidopen'] = result_dict['time_bidclose']
  3398. return result_dict
  3399. def getOtherAttributes(list_entity,page_time):
  3400. dict_other = {"moneysource":"",
  3401. "person_review":[],
  3402. "serviceTime":"",
  3403. "product":[],
  3404. "total_tendereeMoney":0,
  3405. "total_tendereeMoneyUnit":''}
  3406. list_serviceTime = []
  3407. last_moneysource_prob = 0
  3408. for entity in list_entity:
  3409. if entity.entity_type == 'bidway':
  3410. dict_other["bidway"] = turnBidWay(entity.entity_text)
  3411. elif entity.entity_type=='moneysource':
  3412. if dict_other["moneysource"] and entity.in_attachment:
  3413. continue
  3414. if not dict_other["moneysource"]:
  3415. dict_other["moneysource"] = entity.entity_text
  3416. last_moneysource_prob = entity.prob
  3417. elif entity.prob>last_moneysource_prob:
  3418. dict_other["moneysource"] = entity.entity_text
  3419. last_moneysource_prob = entity.prob
  3420. elif entity.entity_type=='serviceTime':
  3421. # print(entity.entity_text)
  3422. # if list_serviceTime and entity.in_attachment:
  3423. # continue
  3424. if re.search("[^之]日|天|年|月|周|星期", entity.entity_text) or re.search("\d{4}[\-\./]\d{1,2}", entity.entity_text):
  3425. list_serviceTime.append(entity)
  3426. elif entity.entity_type=="person" and entity.label ==4:
  3427. dict_other["person_review"].append(entity.entity_text)
  3428. elif entity.entity_type=='product' and entity.entity_text not in dict_other["product"]: #顺序去重保留
  3429. dict_other["product"].append(entity.entity_text)
  3430. elif entity.entity_type=='money' and entity.notes=='总投资' and float(dict_other["total_tendereeMoney"])<float(entity.entity_text):
  3431. dict_other["total_tendereeMoney"] = str(Decimal(entity.entity_text))
  3432. dict_other["total_tendereeMoneyUnit"] = entity.money_unit
  3433. if list_serviceTime:
  3434. list_serviceTime_inAtt = [serviceTime for serviceTime in list_serviceTime if serviceTime.in_attachment==1]
  3435. list_serviceTime = [serviceTime for serviceTime in list_serviceTime if serviceTime.in_attachment==0]
  3436. # if not list_serviceTime:
  3437. # list_serviceTime = list_serviceTime_inAtt
  3438. error_serviceTime = []
  3439. for list_time in [list_serviceTime,list_serviceTime_inAtt]:
  3440. if not dict_other["serviceTime"]:
  3441. list_time.sort(key=lambda x: (x.prob,-x.sentence_index,-x.begin_index), reverse=True)
  3442. for _serviceTime in list_time:
  3443. # 优先取具体时间(20XX年x月x日-20XX年x月x日)
  3444. if re.search("20\d{2}[年/.\-]\d{1,2}[月/.\-]\d{1,2}日?[^。\d半一二三四五六七八九十壹两叁贰肆伍陆柒捌玖拾;;]{,4}20\d{2}[年/.\-]\d{1,2}[月/.\-]\d{1,2}日?",_serviceTime.entity_text):
  3445. _extract_time = my_timeFormat(_serviceTime.entity_text,page_time)
  3446. if _extract_time and len(_extract_time)==2:
  3447. # 排除开始和结束时间一样的错误模板,例:“履约期限:2023年02月15日至2023年02月15日”
  3448. if _extract_time[0]!=_extract_time[1]:
  3449. dict_other["serviceTime"] = _serviceTime.entity_text
  3450. break
  3451. else:
  3452. error_serviceTime.append(_serviceTime.entity_text)
  3453. if not dict_other["serviceTime"]:
  3454. for _serviceTime in list_time:
  3455. # 优先取具体时间(20XX年x月-20XX年x月)
  3456. if re.search("20\d{2}[年/.\-]\d{1,2}月?[^。\d半一二三四五六七八九十壹两叁贰肆伍陆柒捌玖拾;;]{,3}20\d{2}[年/.\-]\d{1,2}月?", _serviceTime.entity_text):
  3457. dict_other["serviceTime"] = _serviceTime.entity_text
  3458. break
  3459. if not dict_other["serviceTime"]:
  3460. for _serviceTime in list_time:
  3461. # 优先取具体时间(20XX年x月x日)
  3462. if re.search("20\d{2}[年/.\-]\d{1,2}[月/.\-]\d{1,2}日?",_serviceTime.entity_text):
  3463. if _serviceTime.entity_text not in error_serviceTime:
  3464. dict_other["serviceTime"] = _serviceTime.entity_text
  3465. break
  3466. if not dict_other["serviceTime"]:
  3467. for _serviceTime in list_time:
  3468. if _serviceTime.entity_text not in error_serviceTime:
  3469. dict_other["serviceTime"] = _serviceTime.entity_text
  3470. break
  3471. if dict_other['moneysource']:
  3472. dict_other['moneysource'] = turnMoneySource(dict_other['moneysource'])
  3473. # dict_other["product"] = list(set(dict_other["product"])) # 已在添加时 顺序去重保留
  3474. return dict_other
  3475. def getMoneyRange(RoleList):
  3476. pass
  3477. def getPREMs(list_sentences,list_entitys,list_articles,list_outlines,page_time):
  3478. '''
  3479. @param:
  3480. list_sentence:所有文章的句子list
  3481. list_entity:所有文章的实体list
  3482. @return:list of dict which include文章的包-角色-实体名称-金额-联系人-联系电话
  3483. '''
  3484. result = []
  3485. for list_sentence,list_entity,list_article,list_outline in zip(list_sentences,list_entitys,list_articles,list_outlines):
  3486. RoleList = getPackageRoleMoney(list_sentence,list_entity,list_outline)
  3487. result.append(dict({"prem": RoleList, "docid": list_article.doc_id},
  3488. **getTimeAttributes(list_entity, list_sentence,page_time),
  3489. **{"fingerprint": list_article.fingerprint,
  3490. "match_enterprise": list_article.match_enterprise,
  3491. "match_enterprise_type": list_article.match_enterprise_type,
  3492. "process_time": getCurrent_date(),
  3493. "attachmentTypes": list_article.attachmentTypes, "bidway": list_article.bidway}))
  3494. # result.append(dict({"prem":RoleList,"docid":list_article.doc_id},**getOtherAttributes(list_entity),**getTimeAttributes(list_entity,list_sentence),
  3495. # **{"fingerprint":list_article.fingerprint,"match_enterprise":list_article.match_enterprise,
  3496. # "match_enterprise_type":list_article.match_enterprise_type,"process_time":getCurrent_date(),
  3497. # "attachmentTypes":list_article.attachmentTypes, "bidway": list_article.bidway}))
  3498. return result
  3499. def correct_rolemoney(prem, total_product_money, list_articles): # 2022/9/26修改为 中标金额小于表格单价数量合计总金额十分之一时替换
  3500. '''
  3501. 最后根据表格提取的单价数量合计对比更新中标金额,或中标金额为0全文只有一个总价或合计时,作为中标金额
  3502. :param prem: 列表
  3503. :param total_product_money: 表格统计金额
  3504. :param list_articles: 文章对象
  3505. :return:
  3506. '''
  3507. if '##attachment##' in list_articles[0].content:
  3508. content, attachment = list_articles[0].content.split('##attachment##')
  3509. if len(content) < 200:
  3510. content += attachment
  3511. else:
  3512. content = list_articles[0].content
  3513. if len(re.findall('win_tenderer|second_tenderer|third_tenderer', str(prem[0]['prem'])))==1 and re.search('(中标|成交|合同|投标))?(总?金额|[报总]?价):', content) == None: # 只有一个中标角色且没有明确中标金额表达的
  3514. if total_product_money>0 and total_product_money<5000000000:
  3515. for value in prem[0]['prem'].values():
  3516. ree_money = float(value['tendereeMoney'])
  3517. for l in value['roleList']:
  3518. try:
  3519. # if l[0] == 'win_tenderer' and float(l[2])<total_product_money:
  3520. # l[2] = total_product_money
  3521. # log('修改中标金额为所有产品总金额')
  3522. # if l["role_name"] == 'win_tenderer' and float(l["role_money"]['money']) == 0 and float(l["role_money"]['money'])<total_product_money/10:
  3523. if l["role_name"] == 'win_tenderer' and (float(l["role_money"]['money']) == 0 or float(l["role_money"]['money'])<ree_money/2): # 改为小于一半招标金额或为0时替换为合计金额
  3524. l["role_money"]['money'] = total_product_money
  3525. # print('修改中标金额为所有产品总金额')
  3526. except Exception as e:
  3527. print('表格产品价格修正中标价格报错:%s'%e)
  3528. elif (len(re.findall('合计', content)) == 1 or len(re.findall('总价', content)) == 1):
  3529. ser = re.search('(?P<header>合计((万?元))?:)(?P<money>[\d,.]+(万?元)?)', content) if len(re.findall('合计', content)) == 1 else re.search('(?P<header>总价((万?元))?:)(?P<money>[\d,.]+(万?元)?)', content)
  3530. if ser:
  3531. money_text = ser.group('money')
  3532. header = ser.group('header')
  3533. money, money_unit = money_process(money_text, header)
  3534. if 100<money<8000000:
  3535. for value in prem[0]['prem'].values():
  3536. for l in value['roleList']:
  3537. try: # 如果原中标金额为0 或 金额小于合计金额0.1倍且正文没中标金额关键词 替换为 合计金额
  3538. if l["role_name"] == 'win_tenderer' and (float(l["role_money"]['money'])==0 or (float(l["role_money"]['money']) < money / 10 and re.search('(中标|成交|合同)(总?金额|[单报总]?价)', content) == None)):
  3539. l["role_money"]['money'] = str(money)
  3540. l["role_money"]['money_unit'] = money_unit
  3541. # print('修改中标金额为总价或合计金额')
  3542. except Exception as e:
  3543. print('修正中标价格报错:%s' % e)
  3544. def limit_maximum_amount(dic, list_entity):
  3545. '''
  3546. 通过关键词、行业、公告类别等设置最高最低角色金额
  3547. :param dic: 最终返回所有字段结果字典
  3548. :param list_entity: 实体列表
  3549. :return:
  3550. '''
  3551. indu_amount = {
  3552. '计算机设备': 200000000,
  3553. '办公设备': 100000000,
  3554. '家具用具': 500000000,
  3555. '办公消耗用品及类似物品': 100000000,
  3556. '日杂用品': 100000000,
  3557. '餐饮业': 1000000000,
  3558. '物业管理': 1000000000,
  3559. '工程技术与设计服务': 1000000000,
  3560. '工程评价服务': 100000000,
  3561. '其他工程服务': 100000000,
  3562. '工程监理服务': 100000000,
  3563. '工程造价服务': 100000000,
  3564. '会计、审计及税务服务': 100000000,
  3565. }
  3566. title = dic.get('doctitle_refine', '')
  3567. name = dic.get('name', '')
  3568. product = ','.join(dic.get('product', []))
  3569. text = "%s;%s;%s"%(title, name, product)
  3570. doctype = dic.get('docchannel', {}).get('doctype', '') # 公告类型
  3571. industry = dic['industry'].get('class_name', '')
  3572. category = dic['industry'].get('class', '') # 行业门类
  3573. moneys = [float(it.entity_text) for it in list_entity if it.entity_type=='money' and re.search('^\d+(\.\d+)?', it.entity_text) and 5000<float(it.entity_text)<5000000]
  3574. maximum_amount = 10000000000
  3575. minximum_amount = 100
  3576. if re.search('监理|造价咨询|设计|勘察|招标代理中介服务|工程审计', text) and re.search('施工|总承包|ppp', text.replace('施工监理', '监理'))==None:
  3577. # print('监理设计等限额')
  3578. maximum_amount = 1000000000
  3579. minximum_amount = 200
  3580. elif re.search('施工|总承包|ppp|公路|道路|桥梁|铁路|土地使用权|地块|棚改|征地拆迁|棚户区改造|土地征收|建设用地|社会保险', text) or category in ['金融业', '建筑业'] or doctype == '土地矿产':
  3581. # print('施工、铁路等限额')
  3582. if industry in ['科研、医疗、教育用房', '住宅、商业用房', '场馆、站港用房','工业、生产用房','专业施工']:
  3583. maximum_amount = 20000000000
  3584. minximum_amount = 200
  3585. elif industry in ['修缮工程', '电气安装', '管道和设备安装', '建筑装饰和装修业', '建筑物拆除和场地准备活动']:
  3586. maximum_amount = 10000000000
  3587. minximum_amount = 100
  3588. else:
  3589. maximum_amount = 50000000000
  3590. minximum_amount = 500
  3591. elif re.search('(办公|体育)(用品|设备|器材)|耗材|打印机|复印机|打印纸|粉盒|墨粉|复印纸|网上超市|电子卖场|家电|配电箱采购|配件|备件', text):
  3592. # print('商品采购限额')
  3593. maximum_amount = 80000000
  3594. minximum_amount = 10
  3595. elif re.search('修理|维修|(安保|保安|安全|保洁|物业|后勤|管理|代理|中介|印刷)服务', text):
  3596. # print('维修限额')
  3597. maximum_amount = 50000000
  3598. elif re.search('(速递|快递|邮政|邮寄)(物流)?服务', text):
  3599. # print('快递限额')
  3600. maximum_amount = 80000000
  3601. minximum_amount = 10
  3602. elif industry in indu_amount:
  3603. maximum_amount = indu_amount[industry]
  3604. # print('maximum_amount:', maximum_amount)
  3605. for value in dic['prem'].values():
  3606. for l in value['roleList']:
  3607. if l["role_name"] in ['win_tenderer', 'second_tenderer', 'third_tenderer']:
  3608. date = float(re.search('(\d+)天', l.get('serviceTime', '')).group(1)) if re.search('(\d+)天', l.get('serviceTime', '')) else 0
  3609. if 0 < date < 180 and float(l["role_money"]['money']) > 10000000000: # 工期小于180天且金额大于百亿的,错误
  3610. l["role_money"]['money'] = str(Decimal(l["role_money"]['money']) / 10000)
  3611. # print('工期纠正百亿以上金额 ')
  3612. elif float(l["role_money"]['money']) > maximum_amount:
  3613. flag = 1
  3614. for money in moneys:
  3615. if float(l["role_money"]['money'])/money == 10000 and l['role_money']['money_unit'] == '万元':
  3616. l["role_money"]['money'] = str(Decimal(l["role_money"]['money']) / 10000)
  3617. # print('万倍关系纠正连接金额')
  3618. flag = 0
  3619. break
  3620. if flag and l["role_money"]['money_unit'] == '万元' or re.search('^\d{11,}(\.0)?$', str(l["role_money"]['money'])):
  3621. l["role_money"]['money'] = str(Decimal(l["role_money"]['money']) / 10000)
  3622. # print('行业限额纠正连接金额')
  3623. elif industry in ['餐饮业', '物业管理'] and maximum_amount == indu_amount[industry]:
  3624. l["role_money"]['money'] = str(Decimal(l["role_money"]['money']) / 10000)
  3625. # elif flag and l["role_money"]['money_unit'] == '元':
  3626. # l["role_money"]['money'] = 0
  3627. elif 0<float(l["role_money"]['money']) < minximum_amount:
  3628. if l["role_money"]['money_unit'] == '元' and re.search('^\d{1,2}\.\d{4,6}$', str(l["role_money"]['money'])):
  3629. # print('单位元小金额且格式类似万元的乘以万倍')
  3630. l["role_money"]['money'] = str(Decimal(l["role_money"]['money']) * 10000)
  3631. else:
  3632. # print('中标金额小于限额:%d元 去除' % minximum_amount)
  3633. l["role_money"]['money'] = 0
  3634. if float(value['tendereeMoney']) > maximum_amount:
  3635. flag = 1
  3636. for money in moneys:
  3637. if float(value['tendereeMoney'])/money == 10000 and l['role_money']['money_unit'] == '万元':
  3638. value['tendereeMoney'] = str(Decimal(value['tendereeMoney'])/10000)
  3639. # print('万倍关系纠正连接金额')
  3640. flag = 0
  3641. break
  3642. if flag and value['tendereeMoneyUnit'] == '万元' or re.search('^\d{11,}(\.0)?$', str(value['tendereeMoney'])):
  3643. value['tendereeMoney'] = str(Decimal(value['tendereeMoney']) / 10000)
  3644. # print('行业限额纠正连接金额')
  3645. elif industry in ['餐饮业', '物业管理'] and maximum_amount == indu_amount[industry]:
  3646. value['tendereeMoney'] = str(Decimal(value['tendereeMoney']) / 10000)
  3647. # elif flag and value['tendereeMoneyUnit'] == '元':
  3648. # value['tendereeMoney'] = 0
  3649. elif 0<float(value['tendereeMoney']) < minximum_amount:
  3650. if value['tendereeMoneyUnit'] == '元' and re.search('^\d{1,2}\.\d{4,6}$', str(value['tendereeMoney'])):
  3651. # print('单位元小金额且格式类似万元的乘以万倍')
  3652. value['tendereeMoney'] = str(Decimal(value['tendereeMoney']) * 10000)
  3653. else:
  3654. # print('招标金额小于限额:%d元 去除' % minximum_amount)
  3655. value['tendereeMoney'] = 0
  3656. def limit_maximum_amount_backup(prem, industry):
  3657. indu = industry['industry'].get('class_name', '')
  3658. indu_amount = {
  3659. '计算机设备': 200000000,
  3660. '办公设备': 100000000,
  3661. '家具用具': 500000000,
  3662. '办公消耗用品及类似物品': 100000000,
  3663. '日杂用品': 100000000,
  3664. '餐饮业': 1000000000,
  3665. '物业管理': 1000000000,
  3666. '工程技术与设计服务': 1000000000,
  3667. '工程评价服务': 100000000,
  3668. '其他工程服务': 100000000,
  3669. '工程监理服务': 100000000,
  3670. '工程造价服务': 100000000,
  3671. '会计、审计及税务服务': 100000000,
  3672. }
  3673. if indu in indu_amount:
  3674. maximum_amount = indu_amount[indu]
  3675. try:
  3676. for value in prem[0]['prem'].values():
  3677. for l in value['roleList']:
  3678. if l["role_name"] == 'win_tenderer' and float(l["role_money"]['money']) > maximum_amount:
  3679. if indu in ['餐饮业', '物业管理']:
  3680. l["role_money"]['money'] = str(float(l["role_money"]['money'])/10000)
  3681. elif l["role_money"]['money_unit'] == '万元':
  3682. l["role_money"]['money'] = str(float(l["role_money"]['money'])/10000)
  3683. if float(value['tendereeMoney']) > maximum_amount:
  3684. if indu in ['餐饮业', '物业管理']:
  3685. value['tendereeMoney'] = float(value['tendereeMoney'])/10000
  3686. elif value['tendereeMoneyUnit'] == '万元':
  3687. value['tendereeMoney'] = float(value['tendereeMoney']) / 10000
  3688. except Exception as e:
  3689. print('行业分类限制最高金额抛出异常:%s' % e)
  3690. def get_win_joint(prem, list_entitys, list_sentences, list_articles):
  3691. '''
  3692. 获取联合体信息, 添加到prem
  3693. :param prem:
  3694. :param list_entitys:
  3695. :param list_sentences:
  3696. :param list_articles:
  3697. :return:
  3698. '''
  3699. try:
  3700. if 'win_tenderer' in str(prem) and re.search('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:|(联合体)|(联合体(成员|单位)方?[12345一二三四五]?)|((联合体)?成员单位[12345一二三四五]?)|(特殊普通合伙|成员?)', list_articles[0].content):
  3701. sentences = sorted(list_sentences[0], key=lambda x:x.sentence_index)
  3702. for project in prem[0].values():
  3703. if not isinstance(project, dict):
  3704. continue
  3705. for v in project.values():
  3706. for d in v['roleList']:
  3707. if d.get('role_name', '') == 'win_tenderer':
  3708. winner = d.get('role_text')
  3709. join_l = [winner]
  3710. for list_entity in list_entitys:
  3711. for i in range(len(list_entity)-1):
  3712. _entity = list_entity[i]
  3713. b = _entity.wordOffset_begin
  3714. e = _entity.wordOffset_end
  3715. if _entity.entity_type in ['org', 'company'] and _entity.label==2\
  3716. and _entity.entity_text==winner:
  3717. s = sentences[_entity.sentence_index].sentence_text
  3718. for j in range(i+1, len(list_entity)):
  3719. behind_entity = list_entity[j]
  3720. b2 = behind_entity.wordOffset_begin
  3721. e2 = behind_entity.wordOffset_end
  3722. if _entity.sentence_index == behind_entity.sentence_index and behind_entity.entity_type in ['org', 'company'] \
  3723. and b2-e<10 and re.search('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:', s[b2-e:b2]) or \
  3724. re.search('(联合体)|(联合体(成员|单位)方?[12345一二三四五]?)|((联合体)?成员单位[12345一二三四五]?)|(特殊普通合伙|成员?)', s[e2:e2+10]):
  3725. join_l.append(behind_entity.entity_text)
  3726. b = b2
  3727. e = e2
  3728. else:
  3729. break
  3730. if len(join_l)>1:
  3731. d['win_tenderer_joint'] = ','.join(join_l)
  3732. # behind_entity = list_entity[i + 1]
  3733. # if _entity.sentence_index== behind_entity.sentence_index and _entity.entity_type in ['org', 'company'] and _entity.label==2\
  3734. # and _entity.entity_text==winner and behind_entity.entity_type in ['org', 'company'] and behind_entity.label==5:
  3735. # s = sentences[_entity.sentence_index].sentence_text
  3736. # b = _entity.wordOffset_begin
  3737. # e = _entity.wordOffset_end
  3738. # b2 = behind_entity.wordOffset_begin
  3739. # e2 = behind_entity.wordOffset_end
  3740. # if re.search('(联合体)', s[e2:e2+6]) and b2-e<3:
  3741. # print('联合体:', s[max(0, b-10):e2+10])
  3742. # d['win_tenderer_joint'] = '%s,%s'%(_entity.entity_text, behind_entity.entity_text)
  3743. # break
  3744. # elif re.search('(联合体((牵头|主办)(人|方|单位)|主体)|牵头(人|方|单位))|(联合体)?成员:|特殊普通合伙:', s[e:b2]) and b2-e<10:
  3745. # d['win_tenderer_joint'] = '%s,%s' % (_entity.entity_text, behind_entity.entity_text)
  3746. # print('联合体:', s[max(0, b - 10):e2 + 10])
  3747. # break
  3748. except Exception as e:
  3749. print('获取联合体抛出异常', e)
  3750. def get_multi_winner_and_money(channel_dic, prem, list_entitys,list_sentences):
  3751. '''
  3752. 获取多中标人及正文、附件所有金额,多中标人multi_winner写入prem,返回金额列表
  3753. :param channel_dic:
  3754. :param prem:
  3755. :param list_entitys:
  3756. :param list_sentences:
  3757. :return:
  3758. '''
  3759. moneys = []
  3760. moneys_attachment = []
  3761. if channel_dic['docchannel']['docchannel'] in ['中标信息','候选人公示','合同公告'] and 'win_tenderer' in str(prem):
  3762. sentences = sorted(list_sentences[0], key=lambda x: x.sentence_index)
  3763. finalists = [] # 入围供应商
  3764. i = 0
  3765. while i < len(list_entitys[0])-1:
  3766. ent = list_entitys[0][i]
  3767. b_idx_fr = ent.wordOffset_begin
  3768. e_idx_fr = ent.wordOffset_end
  3769. multi_winner_l = []
  3770. i += 1
  3771. if ent.entity_type in ['money']:
  3772. money = float(ent.entity_text)
  3773. if ent.in_attachment:
  3774. moneys_attachment.append(money)
  3775. else:
  3776. moneys.append(money)
  3777. if ent.entity_type in ['org', 'company'] and ent.label == 2 and ent.values[ent.label]>0.8:
  3778. multi_winner_l.append(ent.entity_text)
  3779. sentence_text = sentences[ent.sentence_index].sentence_text
  3780. pre_text = sentence_text[max(0, b_idx_fr-10):b_idx_fr]
  3781. if re.search('入围', pre_text) and re.search('未入围', pre_text)==None and ent.entity_text not in finalists:
  3782. finalists.append(ent.entity_text)
  3783. for j in range(i, len(list_entitys[0])):
  3784. ent_bh = list_entitys[0][j]
  3785. b_idx_bh = ent_bh.wordOffset_begin
  3786. e_idx_bh = ent_bh.wordOffset_end
  3787. if ent_bh.entity_type in ['org', 'company'] and ent_bh.label == 5 and ent_bh.sentence_index == ent.sentence_index and b_idx_bh-e_idx_fr==1:
  3788. sentence_text = sentences[ent_bh.sentence_index].sentence_text
  3789. if sentence_text[e_idx_fr:b_idx_bh] in [';','、','&',','] and (len(sentence_text)==e_idx_bh or sentence_text[e_idx_bh] in [';','、','&', ',', '。']): # 修复多中标人刚好在文末index超出报错,例子 407126558
  3790. multi_winner_l.append(ent_bh.entity_text)
  3791. e_idx_fr = e_idx_bh
  3792. i = j + 1
  3793. else:
  3794. break
  3795. elif ent_bh.entity_type in ['org', 'company'] and ent_bh.label == 5 and ent_bh.sentence_index == ent.sentence_index and b_idx_bh==e_idx_fr:
  3796. multi_winner_l.append(ent_bh.entity_text)
  3797. e_idx_fr = e_idx_bh
  3798. i = j + 1
  3799. else:
  3800. break
  3801. if len(multi_winner_l)>=2:
  3802. for project in prem[0].values():
  3803. if not isinstance(project, dict):
  3804. continue
  3805. for v in project.values():
  3806. for d in v['roleList']:
  3807. if d.get('role_name', '') == 'win_tenderer' and d.get('role_text', '') == multi_winner_l[0]:
  3808. d['multi_winner'] = ','.join(set(multi_winner_l))
  3809. break
  3810. if len(finalists)>=2:
  3811. for project in prem[0].values():
  3812. if not isinstance(project, dict):
  3813. continue
  3814. for v in project.values():
  3815. for d in v['roleList']:
  3816. if d.get('role_name', '') == 'win_tenderer':
  3817. winner = d.get('role_text')
  3818. if winner in finalists:
  3819. d['multi_winner'] = ','.join(finalists)
  3820. else:
  3821. for i in range(len(list_entitys[0])):
  3822. ent = list_entitys[0][i]
  3823. if ent.entity_type in ['money']:
  3824. money = float(ent.entity_text)
  3825. if ent.in_attachment:
  3826. moneys_attachment.append(money)
  3827. else:
  3828. moneys.append(money)
  3829. return {'moneys': list(set(moneys)), 'moneys_attachment': list(set(moneys_attachment))}
  3830. def update_prem(old_prem, new_prem):
  3831. '''
  3832. 根据新旧对比,更新数据
  3833. :param old_prem:
  3834. :param new_prem: 表格提取的要素
  3835. :return:
  3836. '''
  3837. if len(new_prem) >= 1 :
  3838. '''如果表格提取的包大于2,原来的包比表格提取的包多则删除原来多余的包,以表格的为准'''
  3839. if len(new_prem) > 2 and len(old_prem) > len(new_prem):
  3840. del_k = []
  3841. for k in old_prem:
  3842. if k not in new_prem and k != 'Project':
  3843. del_k.append(k)
  3844. for k in del_k:
  3845. old_prem.pop(k)
  3846. multi_tendereeMoney = [] # 多包招标金额
  3847. for k, v in new_prem.items():
  3848. if k == 'Project':
  3849. if 'Project' in old_prem:
  3850. tmp_l = [] # 保存新旧同时包含的角色
  3851. if v.get('code', "") != "":
  3852. old_prem['Project']['code'] = v.get('code', "")
  3853. if v.get('name', "") != "":
  3854. old_prem['Project']['name'] = v.get('name', "")
  3855. for d in old_prem['Project']['roleList']:
  3856. for d2 in v['roleList']:
  3857. if d['role_name'] == d2['role_name']: # 同时包含的角色用表格的替换
  3858. tmp_l.append(d2)
  3859. if d2['role_text'] != "":
  3860. d['role_text'] = d2['role_text']
  3861. if float(d2['role_money']['money']) != 0: # 如果表格提取的金额不为0才替换
  3862. d['role_money']['money'] = d2['role_money']['money']
  3863. d['role_money']['money_unit'] = d2['role_money']['money_unit']
  3864. for d2 in v['roleList']:
  3865. if d2 not in tmp_l: # 把新预测有,旧没有的角色添加上去
  3866. old_prem['Project']['roleList'].append(d2)
  3867. else:
  3868. old_prem[k] = v
  3869. else:
  3870. if v['tendereeMoney'] != 0:
  3871. multi_tendereeMoney.append(v['tendereeMoney'])
  3872. if k not in old_prem: # 新有旧没有的包直接添加
  3873. old_prem[k] = v
  3874. else:
  3875. tmp_l = [] # 保存新旧同时包含的角色
  3876. if v.get('code', "") != "":
  3877. old_prem[k]['code'] = v.get('code', "")
  3878. if v.get('name', "") != "":
  3879. old_prem[k]['name'] = v.get('name', "")
  3880. for d in old_prem[k]['roleList']:
  3881. for d2 in v['roleList']:
  3882. if d['role_name'] == d2['role_name']:
  3883. tmp_l.append(d2)
  3884. if d2['role_text'] != "":
  3885. d['role_text'] = d2['role_text']
  3886. if float(d2['role_money']['money']) != 0: # 如果表格提取的金额不为0才替换
  3887. d['role_money']['money'] = d2['role_money']['money']
  3888. d['role_money']['money_unit'] = d2['role_money']['money_unit']
  3889. for d2 in v['roleList']:
  3890. if d2 not in tmp_l: # 把新预测有,旧没有的角色添加上去
  3891. old_prem[k]['roleList'].append(d2)
  3892. if len(old_prem)>1 and 'Project' in old_prem and 'win_tenderer' in str(new_prem): # 表格提取到中标人的,去掉project包中标人
  3893. pro_winner = set()
  3894. other_winner = set()
  3895. for k in old_prem:
  3896. for d in old_prem[k]['roleList']:
  3897. if d['role_name'] in ['win_tenderer', 'pre_win_tenderer']:
  3898. if k == 'Project':
  3899. pro_winner.add(d['role_text'])
  3900. else:
  3901. other_winner.add(d['role_text'])
  3902. if pro_winner & other_winner != set():
  3903. # print('过滤掉多包相同中标人在不同包')
  3904. for d in old_prem['Project']['roleList']:
  3905. if d['role_name'] in ['win_tenderer', 'second_tenderer', 'third_tenderer']:
  3906. old_prem['Project']['roleList'].remove(d) # 提取到其他包,去掉 project 里面的中标角色
  3907. if multi_tendereeMoney and 'Project' in old_prem and float(old_prem['Project']['tendereeMoney'])!=0: # 表格提取到多标段招标金额,去掉Project包招标金额
  3908. old_prem['Project']['tendereeMoney'] = 0
  3909. # return old_prem
  3910. def fix_single_source(prem, channel_dic, original_docchannel):
  3911. if prem.get('bidway', '') == '单一来源' and channel_dic['docchannel']['docchannel'] == '招标公告' and original_docchannel==52:
  3912. for l in prem['prem'].values():
  3913. for d in l['roleList']:
  3914. if d['role_name'] == "win_tenderer":
  3915. d['role_name'] = 'pre_win_tenderer'
  3916. if __name__=="__main__":
  3917. '''
  3918. conn = getConnection()
  3919. cursor = conn.cursor()
  3920. #sql = " select distinct A.doc_id from entity_mention A,test_predict_role B where A.entity_id=B.entity_id limit 200"
  3921. sql = " select B.doc_id,B.prem from articles_processed A, articles_validation B where A.id=B.doc_id "
  3922. result = []
  3923. cursor.execute(sql)
  3924. rows = cursor.fetchall()
  3925. count = 0
  3926. for row in rows:
  3927. count += 1
  3928. # print(count)
  3929. doc_id = row[0]
  3930. roleList = getPackageRoleMoney(doc_id)
  3931. result.append([doc_id,str(roleList),row[1]])
  3932. ''''''
  3933. with codecs.open("getAttribute.html","w",encoding="utf8") as f:
  3934. f.write('<html><head>\
  3935. <meta http-equiv="Content-Type"\
  3936. content="text/html; charset=UTF-8">\
  3937. </head>\
  3938. <body bgcolor="#FFFFFF">\
  3939. <table border="1">\
  3940. <tr>\
  3941. <td>doc_id</td>\
  3942. <td>角色</td>\
  3943. </tr>')
  3944. for item in result:
  3945. f.write("<tr>"+"<td>"+item[0]+"</td>"+"<td>"+item[1]+"</td>"+"<td>"+item[2]+"</td>"+"</tr>")
  3946. f.write("</table></body>")
  3947. '''