getAttributes.py 273 KB

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