getAttributes.py 248 KB

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