getAttributes.py 244 KB

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