getAttributes.py 288 KB

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