getAttributes.py 241 KB

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