getAttributes.py 275 KB

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