predictor.py 542 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399
  1. '''
  2. Created on 2018年12月26日
  3. @author: User
  4. '''
  5. import os
  6. import sys
  7. from BiddingKG.dl.common.nerUtils import *
  8. sys.path.append(os.path.abspath("../.."))
  9. # from keras.engine import topology
  10. # from keras import models
  11. # from keras import layers
  12. # from keras_contrib.layers.crf import CRF
  13. # from keras.preprocessing.sequence import pad_sequences
  14. # from keras import optimizers,losses,metrics
  15. from BiddingKG.dl.common.Utils import *
  16. from BiddingKG.dl.interface.modelFactory import *
  17. import tensorflow as tf
  18. import pandas as pd
  19. from BiddingKG.dl.product.data_util import decode, process_data
  20. from BiddingKG.dl.interface.Entitys import Entity
  21. from BiddingKG.dl.complaint.punish_predictor import Punish_Extract
  22. from BiddingKG.dl.money.re_money_total_unit import extract_total_money, extract_unit_money
  23. from bs4 import BeautifulSoup
  24. import copy
  25. import calendar
  26. import datetime
  27. from BiddingKG.dl.entityLink.entityLink import get_business_data
  28. from BiddingKG.dl.proposed_building.pb_extract import PBPredictor
  29. # from BiddingKG.dl.interface.getAttributes import turnMoneySource
  30. from BiddingKG.dl.common.Utils import del_tabel_achievement
  31. from BiddingKG.dl.interface.getAttributes import turnMoneySource, extract_serviceTime
  32. from BiddingKG.dl.time.re_servicetime import extract_servicetime
  33. # import fool # 统一用 selffool ,阿里云上只有selffool 包
  34. cpu_num = int(os.environ.get("CPU_NUM",0))
  35. sess_config = tf.ConfigProto(
  36. inter_op_parallelism_threads = cpu_num,
  37. intra_op_parallelism_threads = cpu_num,
  38. log_device_placement=True)
  39. sess_config = None
  40. file = os.path.dirname(__file__) + '/agency_set.pkl'
  41. with open(file, 'rb') as f:
  42. agency_set = pickle.load(f)
  43. def is_agency(entity_text):
  44. if re.search('(招投?标|采购|代理|咨询|管理|物资|事务所?|顾问|监理|拍卖)[()\w]{,4}(有限)?(责任)?公司|(采购|招投?标|交易|代理|咨询)[()\w]{,4}(中心|服务所)|法院$',
  45. entity_text) or entity_text in agency_set:
  46. return True
  47. return False
  48. from threading import RLock
  49. dict_predictor = {"codeName":{"predictor":None,"Lock":RLock()},
  50. "prem":{"predictor":None,"Lock":RLock()},
  51. "epc":{"predictor":None,"Lock":RLock()},
  52. "roleRule":{"predictor":None,"Lock":RLock()},
  53. "roleRuleFinal":{"predictor":None,"Lock":RLock()},
  54. "tendereeRuleRecall":{"predictor":None,"Lock":RLock()},
  55. "form":{"predictor":None,"Lock":RLock()},
  56. "time":{"predictor":None,"Lock":RLock()},
  57. "punish":{"predictor":None,"Lock":RLock()},
  58. "product":{"predictor":None,"Lock":RLock()},
  59. "product_attrs":{"predictor":None,"Lock":RLock()},
  60. "channel": {"predictor": None, "Lock": RLock()},
  61. "deposit_payment_way": {"predictor": None, "Lock": RLock()},
  62. "total_unit_money": {"predictor": None, "Lock": RLock()},
  63. "industry": {"predictor": None, "Lock": RLock()},
  64. "rolegrade": {"predictor": None, "Lock": RLock()},
  65. "moneygrade": {"predictor": None, "Lock": RLock()},
  66. "district": {"predictor": None, "Lock": RLock()},
  67. 'tableprem': {"predictor": None, "Lock": RLock()},
  68. 'candidate': {"predictor": None, "Lock": RLock()},
  69. 'websource_tenderee': {"predictor": None, "Lock": RLock()},
  70. 'project_label': {"predictor": None, "Lock": RLock()},
  71. 'pb_extract': {"predictor": None, "Lock": RLock()},
  72. 'property_label': {"predictor": None, "Lock": RLock()},
  73. 'approval': {"predictor": None, "Lock": RLock()} # 审批项目预测
  74. }
  75. def getPredictor(_type):
  76. if _type in dict_predictor:
  77. with dict_predictor[_type]["Lock"]:
  78. if dict_predictor[_type]["predictor"] is None:
  79. if _type == "codeName":
  80. dict_predictor[_type]["predictor"] = CodeNamePredict(config=sess_config)
  81. if _type == "prem":
  82. dict_predictor[_type]["predictor"] = PREMPredict(config=sess_config)
  83. if _type == "epc":
  84. dict_predictor[_type]["predictor"] = EPCPredict(config=sess_config)
  85. if _type == "roleRule":
  86. dict_predictor[_type]["predictor"] = RoleRulePredictor()
  87. if _type == "roleRuleFinal":
  88. dict_predictor[_type]["predictor"] = RoleRuleFinalAdd()
  89. if _type == "tendereeRuleRecall":
  90. dict_predictor[_type]["predictor"] = TendereeRuleRecall()
  91. if _type == "form":
  92. dict_predictor[_type]["predictor"] = FormPredictor(config=sess_config)
  93. if _type == "time":
  94. dict_predictor[_type]["predictor"] = TimePredictor(config=sess_config)
  95. if _type == "punish":
  96. dict_predictor[_type]["predictor"] = Punish_Extract()
  97. if _type == "product":
  98. dict_predictor[_type]["predictor"] = ProductPredictor(config=sess_config)
  99. if _type == "product_attrs":
  100. dict_predictor[_type]["predictor"] = ProductAttributesPredictor()
  101. if _type == "channel":
  102. dict_predictor[_type]["predictor"] = DocChannel(config=sess_config)
  103. if _type == 'deposit_payment_way':
  104. dict_predictor[_type]["predictor"] = DepositPaymentWay()
  105. if _type == 'total_unit_money':
  106. dict_predictor[_type]["predictor"] = TotalUnitMoney()
  107. if _type == 'industry':
  108. dict_predictor[_type]["predictor"] = IndustryPredictor()
  109. if _type == 'rolegrade':
  110. dict_predictor[_type]["predictor"] = RoleGrade()
  111. if _type == 'moneygrade':
  112. dict_predictor[_type]["predictor"] = MoneyGrade()
  113. if _type == 'district':
  114. dict_predictor[_type]["predictor"] = DistrictPredictor()
  115. if _type == 'tableprem':
  116. dict_predictor[_type]["predictor"] = TablePremExtractor()
  117. if _type == 'candidate':
  118. dict_predictor[_type]["predictor"] = CandidateExtractor()
  119. if _type == 'websource_tenderee':
  120. dict_predictor[_type]['predictor'] = WebsourceTenderee()
  121. if _type == 'project_label':
  122. dict_predictor[_type]['predictor'] = ProjectLabel()
  123. if _type == 'pb_extract':
  124. dict_predictor[_type]['predictor'] = PBPredictor()
  125. if _type == 'property_label':
  126. dict_predictor[_type]['predictor'] = PropertyLabel()
  127. if _type == 'approval':
  128. dict_predictor[_type]['predictor'] = ApprovalPredictor()
  129. return dict_predictor[_type]["predictor"]
  130. raise NameError("no this type of predictor")
  131. # 编号名称模型
  132. class CodeNamePredict():
  133. def __init__(self,EMBED_DIM=None,BiRNN_UNITS=None,lazyLoad=getLazyLoad(),config=None):
  134. self.model = None
  135. self.MAX_LEN = None
  136. self.model_code = None
  137. if EMBED_DIM is None:
  138. self.EMBED_DIM = 60
  139. else:
  140. self.EMBED_DIM = EMBED_DIM
  141. if BiRNN_UNITS is None:
  142. self.BiRNN_UNITS = 200
  143. else:
  144. self.BiRNN_UNITS = BiRNN_UNITS
  145. self.filepath = os.path.dirname(__file__)+"/../projectCode/models/model_project_"+str(self.EMBED_DIM)+"_"+str(self.BiRNN_UNITS)+".hdf5"
  146. #self.filepath = "../projectCode/models/model_project_60_200_200ep017-loss6.456-val_loss7.852-val_acc0.969.hdf5"
  147. self.filepath_code = os.path.dirname(__file__)+"/../projectCode/models/model_code.hdf5"
  148. vocabpath = os.path.dirname(__file__)+"/codename_vocab.pk"
  149. classlabelspath = os.path.dirname(__file__)+"/codename_classlabels.pk"
  150. self.vocab = load(vocabpath)
  151. self.class_labels = load(classlabelspath)
  152. #生成提取编号和名称的正则
  153. id_PC_B = self.class_labels.index("PC_B")
  154. id_PC_M = self.class_labels.index("PC_M")
  155. id_PC_E = self.class_labels.index("PC_E")
  156. id_PN_B = self.class_labels.index("PN_B")
  157. id_PN_M = self.class_labels.index("PN_M")
  158. id_PN_E = self.class_labels.index("PN_E")
  159. self.PC_pattern = re.compile(str(id_PC_B)+str(id_PC_M)+"*"+str(id_PC_E))
  160. self.PN_pattern = re.compile(str(id_PN_B)+str(id_PN_M)+"*"+str(id_PN_E))
  161. # print("pc",self.PC_pattern)
  162. # print("pn",self.PN_pattern)
  163. self.word2index = dict((w,i) for i,w in enumerate(np.array(self.vocab)))
  164. self.inputs = None
  165. self.outputs = None
  166. self.sess_codename = tf.Session(graph=tf.Graph(),config=config)
  167. self.sess_codesplit = tf.Session(graph=tf.Graph(),config=config)
  168. self.inputs_code = None
  169. self.outputs_code = None
  170. if not lazyLoad:
  171. self.getModel()
  172. self.getModel_code()
  173. def getModel(self):
  174. '''
  175. @summary: 取得编号和名称模型
  176. '''
  177. if self.inputs is None:
  178. log("get model of codename")
  179. with self.sess_codename.as_default():
  180. with self.sess_codename.graph.as_default():
  181. meta_graph_def = tf.saved_model.loader.load(self.sess_codename, ["serve"], export_dir=os.path.dirname(__file__)+"/codename_savedmodel_tf")
  182. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  183. signature_def = meta_graph_def.signature_def
  184. self.inputs = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].inputs["inputs"].name)
  185. self.inputs_length = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].inputs["inputs_length"].name)
  186. self.keepprob = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].inputs["keepprob"].name)
  187. self.logits = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].outputs["logits"].name)
  188. self.trans = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].outputs["trans"].name)
  189. return self.inputs,self.inputs_length,self.keepprob,self.logits,self.trans
  190. else:
  191. return self.inputs,self.inputs_length,self.keepprob,self.logits,self.trans
  192. '''
  193. if self.model is None:
  194. self.model = self.getBiLSTMCRFModel(self.MAX_LEN, self.vocab, self.EMBED_DIM, self.BiRNN_UNITS, self.class_labels,weights=None)
  195. self.model.load_weights(self.filepath)
  196. return self.model
  197. '''
  198. def getModel_code(self):
  199. if self.inputs_code is None:
  200. log("get model of code")
  201. with self.sess_codesplit.as_default():
  202. with self.sess_codesplit.graph.as_default():
  203. meta_graph_def = tf.saved_model.loader.load(self.sess_codesplit, ["serve"], export_dir=os.path.dirname(__file__)+"/codesplit_savedmodel")
  204. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  205. signature_def = meta_graph_def.signature_def
  206. self.inputs_code = []
  207. self.inputs_code.append(self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].inputs["input0"].name))
  208. self.inputs_code.append(self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].inputs["input1"].name))
  209. self.inputs_code.append(self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].inputs["input2"].name))
  210. self.outputs_code = self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].outputs["outputs"].name)
  211. self.sess_codesplit.graph.finalize()
  212. return self.inputs_code,self.outputs_code
  213. else:
  214. return self.inputs_code,self.outputs_code
  215. '''
  216. if self.model_code is None:
  217. log("get model of model_code")
  218. with self.sess_codesplit.as_default():
  219. with self.sess_codesplit.graph.as_default():
  220. self.model_code = models.load_model(self.filepath_code, custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score})
  221. return self.model_code
  222. '''
  223. def getBiLSTMCRFModel(self,MAX_LEN,vocab,EMBED_DIM,BiRNN_UNITS,chunk_tags,weights):
  224. '''
  225. model = models.Sequential()
  226. model.add(layers.Embedding(len(vocab), EMBED_DIM, mask_zero=True)) # Random embedding
  227. model.add(layers.Bidirectional(layers.LSTM(BiRNN_UNITS // 2, return_sequences=True)))
  228. crf = CRF(len(chunk_tags), sparse_target=True)
  229. model.add(crf)
  230. model.summary()
  231. model.compile('adam', loss=crf.loss_function, metrics=[crf.accuracy])
  232. return model
  233. '''
  234. input = layers.Input(shape=(None,))
  235. if weights is not None:
  236. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True,weights=[weights],trainable=True)(input)
  237. else:
  238. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True)(input)
  239. bilstm = layers.Bidirectional(layers.LSTM(BiRNN_UNITS//2,return_sequences=True))(embedding)
  240. bilstm_dense = layers.TimeDistributed(layers.Dense(len(chunk_tags)))(bilstm)
  241. crf = CRF(len(chunk_tags),sparse_target=True)
  242. crf_out = crf(bilstm_dense)
  243. model = models.Model(input=[input],output = [crf_out])
  244. model.summary()
  245. model.compile(optimizer = 'adam', loss = crf.loss_function, metrics = [crf.accuracy])
  246. return model
  247. #根据规则补全编号或名称两边的符号
  248. def fitDataByRule(self,data):
  249. symbol_dict = {"(":")",
  250. "(":")",
  251. "[":"]",
  252. "【":"】",
  253. ")":"(",
  254. ")":"(",
  255. "]":"[",
  256. "】":"【"}
  257. leftSymbol_pattern = re.compile("[\((\[【]")
  258. rightSymbol_pattern = re.compile("[\))\]】]")
  259. leftfinds = re.findall(leftSymbol_pattern,data)
  260. rightfinds = re.findall(rightSymbol_pattern,data)
  261. result = data
  262. if len(leftfinds)+len(rightfinds)==0:
  263. return data
  264. elif len(leftfinds)==len(rightfinds):
  265. return data
  266. elif abs(len(leftfinds)-len(rightfinds))==1:
  267. if len(leftfinds)>len(rightfinds):
  268. if symbol_dict.get(data[0]) is not None:
  269. result = data[1:]
  270. else:
  271. #print(symbol_dict.get(leftfinds[0]))
  272. result = data+symbol_dict.get(leftfinds[0])
  273. else:
  274. if symbol_dict.get(data[-1]) is not None:
  275. result = data[:-1]
  276. else:
  277. result = symbol_dict.get(rightfinds[0])+data
  278. return result
  279. def decode(self,logits, trans, sequence_lengths, tag_num):
  280. viterbi_sequences = []
  281. for logit, length in zip(logits, sequence_lengths):
  282. score = logit[:length]
  283. viterbi_seq, viterbi_score = viterbi_decode(score, trans)
  284. viterbi_sequences.append(viterbi_seq)
  285. return viterbi_sequences
  286. def predict(self,list_sentences,list_entitys=None,MAX_AREA = 5000):
  287. #@summary: 获取每篇文章的code和name
  288. # pattern_score = re.compile("工程|服务|采购|施工|项目|系统|招标|中标|公告|学校|[大中小]学校?|医院|公司|分公司|研究院|政府采购中心|学院|中心校?|办公室|政府|财[政务]局|办事处|委员会|[部总支]队|警卫局|幼儿园|党委|党校|银行|分行|解放军|发电厂|供电局|管理所|供电公司|卷烟厂|机务段|研究[院所]|油厂|调查局|调查中心|出版社|电视台|监狱|水厂|服务站|信用合作联社|信用社|交易所|交易中心|交易中心党校|科学院|测绘所|运输厅|管理处|局|中心|机关|部门?|处|科|厂|集团|图书馆|馆|所|厅|楼|区|酒店|场|基地|矿|餐厅|酒店")
  289. pattern_score = re.compile('建设项目|服务项目|工程项目|工程施工|建设工程|服务中心|基础设施|物业管理|工程设计|妇幼保健|咨询服务|管理系统|管理中心|改建工程|配套工程|公安局|幼儿园|管理局|使用权|办公楼|教育局|管理处|图书馆|经营权|项目|采购|工程|改造|服务|设备|中心|医院|系统|建设|监理|施工|维修|学院|安装|设计|关于|标段|招标|技术|询价|管理|学校|小学|中学|平台|提升|设施|检测|整治|社区|装修|政府|绿化|物资|租赁|地块|医疗|编制|公开|规划|监控|教育|维护|校区|治理|升级|安置|竞价|购置|评估|勘察|承包|实验|大学|材料|生产|耗材|招租|硬化|维保|用地|消防|审计|拍卖|物业|入围|养护|机关|企业|用房|出让|资产|分局|验收|宣传|处置|校园|研究|咨询|修缮|更换|装饰|劳务|保养|物流|出租|局|院')
  290. result = []
  291. index_unk = self.word2index.get("<unk>")
  292. # index_pad = self.word2index.get("<pad>")
  293. if list_entitys is None:
  294. list_entitys = [[] for _ in range(len(list_sentences))]
  295. for list_sentence,list_entity in zip(list_sentences,list_entitys):
  296. if len(list_sentence)==0:
  297. result.append([{"code":[],"name":""}])
  298. continue
  299. doc_id = list_sentence[0].doc_id
  300. # sentences = []
  301. # for sentence in list_sentence:
  302. # if len(sentence.sentence_text)>MAX_AREA:
  303. # for _sentence_comma in re.split("[;;,\n]",sentence):
  304. # _comma_index = 0
  305. # while(_comma_index<len(_sentence_comma)):
  306. # sentences.append(_sentence_comma[_comma_index:_comma_index+MAX_AREA])
  307. # _comma_index += MAX_AREA
  308. # else:
  309. # sentences.append(sentence+"。")
  310. list_sentence.sort(key=lambda x:len(x.sentence_text),reverse=True)
  311. _begin_index = 0
  312. item = {"code":[],"name":""}
  313. code_set = set()
  314. dict_name_freq_score = dict()
  315. while(True):
  316. MAX_LEN = len(list_sentence[_begin_index].sentence_text)
  317. if MAX_LEN>MAX_AREA:
  318. MAX_LEN = MAX_AREA
  319. _LEN = MAX_AREA//MAX_LEN
  320. #预测
  321. x = [[self.word2index.get(word,index_unk)for word in sentence.sentence_text[:MAX_AREA]]for sentence in list_sentence[_begin_index:_begin_index+_LEN]]
  322. # x = [[getIndexOfWord(word) for word in sentence.sentence_text[:MAX_AREA]]for sentence in list_sentence[_begin_index:_begin_index+_LEN]]
  323. x_len = [len(_x) if len(_x) < MAX_LEN else MAX_LEN for _x in x]
  324. x = pad_sequences(x,maxlen=MAX_LEN,padding="post",truncating="post")
  325. if USE_API:
  326. requests_result = requests.post(API_URL + "/predict_codeName", json={"inouts": x.tolist(), "inouts_len": x_len},verify=True)
  327. predict_y = json.loads(requests_result.text)['result']
  328. # print("cost_time:", json.loads(requests_result.text)['cost_time'])
  329. # print(MAX_LEN,_LEN,_begin_index)
  330. else:
  331. with self.sess_codename.as_default():
  332. t_input,t_input_length,t_keepprob,t_logits,t_trans = self.getModel()
  333. _logits,_trans = self.sess_codename.run([t_logits,t_trans],feed_dict={t_input:x,
  334. t_input_length:x_len,
  335. t_keepprob:1.0})
  336. predict_y = self.decode(_logits,_trans,x_len,7)
  337. # print('==========',_logits)
  338. '''
  339. for item11 in np.argmax(predict_y,-1):
  340. print(item11)
  341. print(predict_y)
  342. '''
  343. # print(predict_y)
  344. for sentence,predict in zip(list_sentence[_begin_index:_begin_index+_LEN],np.array(predict_y)):
  345. pad_sentence = sentence.sentence_text[:MAX_LEN]
  346. join_predict = "".join([str(s) for s in predict])
  347. # print(pad_sentence)
  348. # print(join_predict)
  349. code_x = []
  350. code_text = []
  351. pre_text = []
  352. temp_entitys = []
  353. for iter in re.finditer(self.PC_pattern,join_predict):
  354. get_len = 40
  355. if iter.span()[0]<get_len:
  356. begin = 0
  357. else:
  358. begin = iter.span()[0]-get_len
  359. end = iter.span()[1]+get_len
  360. code_x.append(embedding_word([pad_sentence[begin:iter.span()[0]],pad_sentence[iter.span()[0]:iter.span()[1]].replace(",",""),pad_sentence[iter.span()[1]:end]],shape=(3,get_len,60)))
  361. code_text.append(pad_sentence[iter.span()[0]:iter.span()[1]].replace(",", ""))
  362. pre_text.append(pad_sentence[begin:iter.span()[0]])
  363. _entity = Entity(doc_id=sentence.doc_id,entity_id="%s_%s_%s_%s"%(sentence.doc_id,sentence.sentence_index,iter.span()[0],iter.span()[1]),entity_text=pad_sentence[iter.span()[0]:iter.span()[1]].replace(",",""),entity_type="code",sentence_index=sentence.sentence_index,begin_index=0,end_index=0,wordOffset_begin=iter.span()[0],wordOffset_end=iter.span()[1],in_attachment=sentence.in_attachment)
  364. temp_entitys.append(_entity)
  365. #print("code",code_text)
  366. if len(code_x)>0:
  367. code_x = np.transpose(np.array(code_x,dtype=np.float32),(1,0,2,3))
  368. if USE_PAI_EAS:
  369. request = tf_predict_pb2.PredictRequest()
  370. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  371. request.inputs["input0"].array_shape.dim.extend(np.shape(code_x[0]))
  372. request.inputs["input0"].float_val.extend(np.array(code_x[0],dtype=np.float64).reshape(-1))
  373. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  374. request.inputs["input1"].array_shape.dim.extend(np.shape(code_x[1]))
  375. request.inputs["input1"].float_val.extend(np.array(code_x[1],dtype=np.float64).reshape(-1))
  376. request.inputs["input2"].dtype = tf_predict_pb2.DT_FLOAT
  377. request.inputs["input2"].array_shape.dim.extend(np.shape(code_x[2]))
  378. request.inputs["input2"].float_val.extend(np.array(code_x[2],dtype=np.float64).reshape(-1))
  379. request_data = request.SerializeToString()
  380. list_outputs = ["outputs"]
  381. _result = vpc_requests(codeclasses_url, codeclasses_authorization, request_data, list_outputs)
  382. if _result is not None:
  383. predict_code = _result["outputs"]
  384. else:
  385. with self.sess_codesplit.as_default():
  386. with self.sess_codesplit.graph.as_default():
  387. predict_code = self.getModel_code().predict([code_x[0],code_x[1],code_x[2]])
  388. else:
  389. with self.sess_codesplit.as_default():
  390. with self.sess_codesplit.graph.as_default():
  391. inputs_code,outputs_code = self.getModel_code()
  392. predict_code = limitRun(self.sess_codesplit,[outputs_code],feed_dict={inputs_code[0]:code_x[0],inputs_code[1]:code_x[1],inputs_code[2]:code_x[2]})[0]
  393. #predict_code = self.sess_codesplit.run(outputs_code,feed_dict={inputs_code[0]:code_x[0],inputs_code[1]:code_x[1],inputs_code[2]:code_x[2]})
  394. #predict_code = self.getModel_code().predict([code_x[0],code_x[1],code_x[2]])
  395. for h in range(len(predict_code)):
  396. if predict_code[h][0]>0.5:
  397. the_code = self.fitDataByRule(code_text[h])
  398. # print(the_code)
  399. #add code to entitys
  400. list_entity.append(temp_entitys[h])
  401. if re.search(',|/|;|、|,', the_code) and len(the_code)>25:
  402. for it in re.split(',|/|;|、|,', the_code):
  403. if len(it) > 8:
  404. if it not in code_set:
  405. code_set.add(it)
  406. # item['code'].append(it)
  407. if re.search("(项目编号|招标编号):?$", pre_text[h]):
  408. item['code'].append((it, 0, sentence.sentence_index))
  409. elif re.search('采购(计划)?编号:?$', pre_text[h]):
  410. item['code'].append((it, 1, sentence.sentence_index))
  411. elif re.search('(询价|合同)编号:?$', pre_text[h]):
  412. item['code'].append((it, 2, sentence.sentence_index))
  413. elif re.search('(询价|合同|采购|招标|项目)标号:?$', pre_text[h]):
  414. item['code'].append((it, 2.5, sentence.sentence_index))
  415. else:
  416. item['code'].append((it, 3, sentence.sentence_index))
  417. elif len(item['code']) > 0:
  418. new_it = item['code'][-1][0] + re.search(',|/|;|、|,', the_code).group(0) + it
  419. if new_it not in code_set:
  420. code_set.add(new_it)
  421. # item['code'][-1] = new_it
  422. if re.search("(项目编号|招标编号):?$", pre_text[h]):
  423. item['code'][-1] = (new_it, 0, sentence.sentence_index)
  424. elif re.search('采购(计划)?编号:?$', pre_text[h]):
  425. item['code'][-1] = (new_it, 1, sentence.sentence_index)
  426. elif re.search('(询价|合同)编号:?$', pre_text[h]):
  427. item['code'][-1] = (new_it, 2, sentence.sentence_index)
  428. elif re.search('(询价|合同|采购|招标|项目)标号:?$', pre_text[h]):
  429. item['code'].append((new_it, 2.5, sentence.sentence_index))
  430. else:
  431. item['code'][-1] = (new_it, 3, sentence.sentence_index)
  432. else:
  433. if the_code not in code_set:
  434. code_set.add(the_code)
  435. # item['code'].append(the_code)
  436. if re.search("(项目编号|招标编号):?$", pre_text[h]):
  437. item['code'].append((the_code, 0, sentence.sentence_index))
  438. elif re.search('采购(计划)?编号:?$', pre_text[h]):
  439. item['code'].append((the_code, 1, sentence.sentence_index))
  440. elif re.search('(询价|合同)编号:?$', pre_text[h]):
  441. item['code'].append((the_code, 2, sentence.sentence_index))
  442. elif re.search('(询价|合同|采购|招标|项目)标号:?$', pre_text[h]):
  443. item['code'].append((the_code, 2.5, sentence.sentence_index))
  444. else:
  445. item['code'].append((the_code, 3, sentence.sentence_index))
  446. break
  447. elif the_code not in code_set:
  448. if len(the_code)<5: # 避免510545935 这种把 招标项目编号:2024年第二期 只提取2024
  449. continue
  450. code_set.add(the_code)
  451. # item['code'].append(the_code)
  452. if re.search("(项目编号|招标编号):?$", pre_text[h]):
  453. item['code'].append((the_code, 0, sentence.sentence_index))
  454. elif re.search('采购(计划)?编号:?$', pre_text[h]):
  455. item['code'].append((the_code, 1, sentence.sentence_index))
  456. elif re.search('(询价|合同)编号:?$', pre_text[h]):
  457. item['code'].append((the_code, 2, sentence.sentence_index))
  458. elif re.search('(询价|合同|采购|招标|项目)标号:?$', pre_text[h]):
  459. item['code'].append((the_code, 2.5, sentence.sentence_index))
  460. else:
  461. item['code'].append((the_code, 3, sentence.sentence_index))
  462. # if the_code not in code_set:
  463. # code_set.add(the_code)
  464. # item['code'] = list(code_set)
  465. for iter in re.finditer(self.PN_pattern,join_predict):
  466. _name = self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  467. if len(_name)>200: # 避免模型预测类似 202750503 这种很长重复字很多的错误项目名称
  468. continue
  469. elif '公司:你单位在' in _name: # 避免类似 339900030 这种作为项目名称,导致中标角色作为招标角色
  470. continue
  471. elif _name.endswith('公司') and len(_name)<20: # 修复 456957250 雄县辉茂纸塑包装制品销售有限公司 作为项目名称
  472. continue
  473. #add name to entitys
  474. _entity = Entity(doc_id=sentence.doc_id,entity_id="%s_%s_%s_%s"%(sentence.doc_id,sentence.sentence_index,iter.span()[0],iter.span()[1]),entity_text=_name,entity_type="name",sentence_index=sentence.sentence_index,begin_index=0,end_index=0,wordOffset_begin=iter.span()[0],wordOffset_end=iter.span()[1],in_attachment=sentence.in_attachment)
  475. list_entity.append(_entity)
  476. # w = 1 if re.search('(项目|工程|招标|合同|标项|标的|计划|询价|询价单|询价通知书|申购)(名称|标题|主题)[::\s]', pad_sentence[iter.span()[0]-10:iter.span()[0]])!=None else 0.5
  477. w = 1 if re.search('(项目|工程|招标|采购|合同|标项|标的|计划|询价|询价单|询价通知书|申购)(名称|标题|主题|项目)[::\s]', pad_sentence[iter.span()[0]-10:iter.span()[0]])!=None else 0.5
  478. if _name not in dict_name_freq_score:
  479. # dict_name_freq_score[_name] = [1,len(re.findall(pattern_score,_name))+len(_name)*0.1]
  480. len_name = len(_name) if len(_name) <50 else 100-len(_name) # 2023/03/02 超出50长度的逐渐递减
  481. dict_name_freq_score[_name] = [1, (len(re.findall(pattern_score, _name)) + len_name * 0.05)*w+(5-sentence.sentence_index)*0.2]
  482. else:
  483. dict_name_freq_score[_name][0] += 1
  484. '''
  485. for iter in re.finditer(self.PN_pattern,join_predict):
  486. print("name-",self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]]))
  487. if item[1]['name']=="":
  488. for iter in re.finditer(self.PN_pattern,join_predict):
  489. #item[1]['name']=item[1]['name']+";"+self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  490. item[1]['name']=self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  491. break
  492. '''
  493. if _begin_index+_LEN>=len(list_sentence):
  494. break
  495. _begin_index += _LEN
  496. list_name_freq_score = []
  497. # print('模型预测项目名称:', dict_name_freq_score)
  498. # 2020/11/23 大网站规则调整
  499. if len(dict_name_freq_score) == 0:
  500. # name_re1 = '(项目|工程|招标|合同|标项|标的|计划|询价|询价单|询价通知书|申购)(名称|标题|主题)[::\s]+([^,。:;]{2,60})[,。]'
  501. name_re1 = '(项目|工程|招标|采购(条目)?|合同|标项|标的|计划|询价|询价单|询价通知书|申购单|申购)(名称|标名|标题|主题)[::\s]+(?P<name>[^,。:;]{2,60})[,。]'
  502. name_re2 = '(合同|采购)包\d((?P<name>[^,。:;]{2,60}))[:,。]' # 20241202 补充合同包 包名表达 558410976
  503. for sentence in list_sentence:
  504. # pad_sentence = sentence.sentence_text
  505. othername = re.search(name_re1, sentence.sentence_text)
  506. if othername == None:
  507. othername = re.search(name_re2, sentence.sentence_text)
  508. if othername != None:
  509. project_name = othername.group('name')
  510. if re.search('[\u4e00-\u9fa5]+', project_name) == None: # 没有中文的项目名称去除
  511. # log('没有中文的项目名称去除')
  512. continue
  513. beg = find_index([project_name], sentence.sentence_text)[0]
  514. end = beg + len(project_name)
  515. _name = self.fitDataByRule(sentence.sentence_text[beg:end])
  516. # print('规则召回项目名称:', _name)
  517. # add name to entitys
  518. _entity = Entity(doc_id=sentence.doc_id, entity_id="%s_%s_%s_%s" % (
  519. sentence.doc_id, sentence.sentence_index, beg, end), entity_text=_name,
  520. entity_type="name", sentence_index=sentence.sentence_index, begin_index=0,
  521. end_index=0, wordOffset_begin=beg, wordOffset_end=end,in_attachment=sentence.in_attachment)
  522. list_entity.append(_entity)
  523. w = 1
  524. if _name not in dict_name_freq_score:
  525. # dict_name_freq_score[_name] = [1,len(re.findall(pattern_score,_name))+len(_name)*0.1]
  526. dict_name_freq_score[_name] = [1, (len(re.findall(pattern_score, _name)) + len(_name) * 0.05) * w+(5-sentence.sentence_index)*0.2]
  527. else:
  528. dict_name_freq_score[_name][0] += 1
  529. # othername = re.search(name_re1, sentence.sentence_text)
  530. # if othername != None:
  531. # _name = othername.group(3)
  532. # if _name not in dict_name_freq_score:
  533. # dict_name_freq_score[_name] = [1, len(re.findall(pattern_score, _name)) + len(_name) * 0.1]
  534. # else:
  535. # dict_name_freq_score[_name][0] += 1
  536. for _name in dict_name_freq_score.keys():
  537. list_name_freq_score.append([_name,dict_name_freq_score[_name]])
  538. # print(list_name_freq_score)
  539. if len(list_name_freq_score)>0:
  540. list_name_freq_score.sort(key=lambda x:x[1][0]*x[1][1],reverse=True)
  541. item['name'] = list_name_freq_score[0][0]
  542. # for it in list_name_freq_score:
  543. # print('项目名称及分值:',it[0],it[1], it[1][0]*it[1][1])
  544. # if list_name_freq_score[0][1][0]>1:
  545. # item[1]['name'] = list_name_freq_score[0][0]
  546. # else:
  547. # list_name_freq_score.sort(key=lambda x:x[1][1],reverse=True)
  548. # item[1]["name"] = list_name_freq_score[0][0]
  549. #下面代码加上去用正则添加某些识别不到的项目编号
  550. if item['code'] == []:
  551. for sentence in list_sentence:
  552. # othercode = re.search('(采购计划编号|询价编号)[\))]?[::]?([\[\]a-zA-Z0-9\-]{5,30})', sentence.sentence_text)
  553. # if othercode != None:
  554. # item[1]['code'].append(othercode.group(2))
  555. # 2020/11/23 大网站规则调整
  556. othercode = re.search('(项目|采购|招标|品目|询价|竞价|询价[单书]|磋商|订单|账单|交易|文件|计划|场次|标的|标段|标包|分包|标段\(包\)|招标文件|合同|通知书|公告|工程|寻源|标书|包件|谈判|申购)(单据?号|编号|标号|编码|代码|备案号|号)[::\s]+(?P<code>[^,。;:、]{6,30}[a-zA-Z0-9\号期])[\),。\u4e00-\u9fa5]', sentence.sentence_text)
  557. if othercode != None:
  558. # item['code'].append(othercode.group('code'))
  559. if re.search("(项目编号|招标编号):?$", othercode.group(0)):
  560. item['code'].append((othercode.group('code'), 0, sentence.sentence_index))
  561. elif re.search('采购(计划)?编号:?$', othercode.group(0)):
  562. item['code'].append((othercode.group('code'), 1, sentence.sentence_index))
  563. elif re.search('(询价|合同)编号:?$', othercode.group(0)):
  564. item['code'].append((othercode.group('code'), 2, sentence.sentence_index))
  565. elif re.search('(询价|合同|采购|招标|项目)标号:?$', othercode.group(0)):
  566. item['code'].append((othercode.group('code'), 2.5, sentence.sentence_index))
  567. else:
  568. item['code'].append((othercode.group('code'), 3, sentence.sentence_index))
  569. # print('规则召回项目编号:', othercode.group('code'))
  570. # item['code'] = [code for code in item['code'] if len(code)<500]
  571. # item['code'].sort(key=lambda x:len(x),reverse=True)
  572. item['code'] = [code for code in item['code'] if len(code[0]) < 500]
  573. item['code'].sort(key=lambda x: [x[1],x[2]])
  574. item['code'] = [it[0] for it in item['code']]
  575. result.append(item)
  576. list_sentence.sort(key=lambda x: x.sentence_index,reverse=False)
  577. return result
  578. '''
  579. #当数据量过大时会报错
  580. def predict(self,articles,MAX_LEN = None):
  581. sentences = []
  582. for article in articles:
  583. for sentence in article.content.split("。"):
  584. sentences.append([sentence,article.id])
  585. if MAX_LEN is None:
  586. sent_len = [len(sentence[0]) for sentence in sentences]
  587. MAX_LEN = max(sent_len)
  588. #print(MAX_LEN)
  589. #若为空,则直接返回空
  590. result = []
  591. if MAX_LEN==0:
  592. for article in articles:
  593. result.append([article.id,{"code":[],"name":""}])
  594. return result
  595. index_unk = self.word2index.get("<unk>")
  596. index_pad = self.word2index.get("<pad>")
  597. x = [[self.word2index.get(word,index_unk)for word in sentence[0]]for sentence in sentences]
  598. x = pad_sequences(x,maxlen=MAX_LEN,padding="post",truncating="post")
  599. predict_y = self.getModel().predict(x)
  600. last_doc_id = ""
  601. item = []
  602. for sentence,predict in zip(sentences,np.argmax(predict_y,-1)):
  603. pad_sentence = sentence[0][:MAX_LEN]
  604. doc_id = sentence[1]
  605. join_predict = "".join([str(s) for s in predict])
  606. if doc_id!=last_doc_id:
  607. if last_doc_id!="":
  608. result.append(item)
  609. item = [doc_id,{"code":[],"name":""}]
  610. code_set = set()
  611. code_x = []
  612. code_text = []
  613. for iter in re.finditer(self.PC_pattern,join_predict):
  614. get_len = 40
  615. if iter.span()[0]<get_len:
  616. begin = 0
  617. else:
  618. begin = iter.span()[0]-get_len
  619. end = iter.span()[1]+get_len
  620. code_x.append(embedding_word([pad_sentence[begin:iter.span()[0]],pad_sentence[iter.span()[0]:iter.span()[1]],pad_sentence[iter.span()[1]:end]],shape=(3,get_len,60)))
  621. code_text.append(pad_sentence[iter.span()[0]:iter.span()[1]])
  622. if len(code_x)>0:
  623. code_x = np.transpose(np.array(code_x),(1,0,2,3))
  624. predict_code = self.getModel_code().predict([code_x[0],code_x[1],code_x[2]])
  625. for h in range(len(predict_code)):
  626. if predict_code[h][0]>0.5:
  627. the_code = self.fitDataByRule(code_text[h])
  628. if the_code not in code_set:
  629. code_set.add(the_code)
  630. item[1]['code'] = list(code_set)
  631. if item[1]['name']=="":
  632. for iter in re.finditer(self.PN_pattern,join_predict):
  633. #item[1]['name']=item[1]['name']+";"+self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  634. item[1]['name']=self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  635. break
  636. last_doc_id = doc_id
  637. result.append(item)
  638. return result
  639. '''
  640. #角色金额模型
  641. class PREMPredict():
  642. def __init__(self,config=None):
  643. #self.model_role_file = os.path.abspath("../role/models/model_role.model.hdf5")
  644. # self.model_role_file = os.path.dirname(__file__)+"/../role/log/new_biLSTM-ep012-loss0.028-val_loss0.040-f10.954.h5"
  645. self.model_role = Model_role_classify_word(config=config)
  646. self.model_money = Model_money_classify(config=config)
  647. # self.role_file = open('/data/python/lsm/role_model_predict.txt', 'a', encoding='utf-8')
  648. # self.money_file = open('/data/python/lsm/money_model_predict.txt', 'a', encoding='utf-8')
  649. return
  650. def search_role_data(self,list_sentences,list_entitys):
  651. '''
  652. @summary:根据句子list和实体list查询角色模型的输入数据
  653. @param:
  654. list_sentences:文章的sentences
  655. list_entitys:文章的entitys
  656. @return:角色模型的输入数据
  657. '''
  658. text_list = []
  659. data_x = []
  660. points_entitys = []
  661. for list_entity,list_sentence in zip(list_entitys,list_sentences):
  662. list_entity.sort(key=lambda x:x.sentence_index)
  663. list_sentence.sort(key=lambda x:x.sentence_index)
  664. p_entitys = 0
  665. p_sentences = 0
  666. while(p_entitys<len(list_entity)):
  667. entity = list_entity[p_entitys]
  668. if entity.entity_type in ['org','company']:
  669. while(p_sentences<len(list_sentence)):
  670. sentence = list_sentence[p_sentences]
  671. if entity.doc_id==sentence.doc_id and entity.sentence_index==sentence.sentence_index:
  672. # text_list.append(sentence.sentence_text[max(0, entity.wordOffset_begin-13):entity.wordOffset_end+10])
  673. text_sen = sentence.sentence_text
  674. b = entity.wordOffset_begin
  675. e = entity.wordOffset_end
  676. text_list.append((text_sen[max(0, b-13):b], text_sen[b:e], text_sen[e:e+15]))
  677. # item_x = embedding(spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=settings.MODEL_ROLE_INPUT_SHAPE[1]),shape=settings.MODEL_ROLE_INPUT_SHAPE)
  678. # item_x = self.model_role.encode(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,entity_text=entity.entity_text)
  679. item_x = self.model_role.encode_word(sentence_text=text_sen, begin_index=entity.wordOffset_begin, end_index=entity.wordOffset_end, size=30)
  680. data_x.append(item_x)
  681. points_entitys.append(entity)
  682. break
  683. p_sentences += 1
  684. p_entitys += 1
  685. if len(points_entitys)==0:
  686. return None
  687. return [data_x,points_entitys, text_list]
  688. def search_money_data(self,list_sentences,list_entitys):
  689. '''
  690. @summary:根据句子list和实体list查询金额模型的输入数据
  691. @param:
  692. list_sentences:文章的sentences
  693. list_entitys:文章的entitys
  694. @return:金额模型的输入数据
  695. '''
  696. text_list = []
  697. data_x = []
  698. points_entitys = []
  699. for list_entity,list_sentence in zip(list_entitys,list_sentences):
  700. list_entity.sort(key=lambda x:x.sentence_index)
  701. list_sentence.sort(key=lambda x:x.sentence_index)
  702. p_entitys = 0
  703. while(p_entitys<len(list_entity)):
  704. entity = list_entity[p_entitys]
  705. if entity.entity_type=="money":
  706. p_sentences = 0
  707. while(p_sentences<len(list_sentence)):
  708. sentence = list_sentence[p_sentences]
  709. if entity.doc_id==sentence.doc_id and entity.sentence_index==sentence.sentence_index:
  710. # text_list.append(sentence.sentence_text[max(0, entity.wordOffset_begin - 13):entity.wordOffset_begin])
  711. text_sen = sentence.sentence_text
  712. b = entity.wordOffset_begin
  713. e = entity.wordOffset_end
  714. text_list.append((text_sen[max(0, b - 13):b], text_sen[b:e], text_sen[e:e + 10]))
  715. #item_x = embedding(spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=settings.MODEL_MONEY_INPUT_SHAPE[1]),shape=settings.MODEL_MONEY_INPUT_SHAPE)
  716. #item_x = embedding_word(spanWindow(tokens=sentence.tokens, begin_index=entity.begin_index, end_index=entity.end_index, size=10, center_include=True, word_flag=True),shape=settings.MODEL_MONEY_INPUT_SHAPE)
  717. item_x = self.model_money.encode(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index)
  718. data_x.append(item_x)
  719. points_entitys.append(entity)
  720. break
  721. p_sentences += 1
  722. p_entitys += 1
  723. if len(points_entitys)==0:
  724. return None
  725. return [data_x,points_entitys, text_list]
  726. def predict_role(self,list_sentences, list_entitys):
  727. datas = self.search_role_data(list_sentences, list_entitys)
  728. if datas is None:
  729. return
  730. points_entitys = datas[1]
  731. text_list = datas[2]
  732. if USE_PAI_EAS:
  733. _data = datas[0]
  734. _data = np.transpose(np.array(_data),(1,0,2))
  735. request = tf_predict_pb2.PredictRequest()
  736. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  737. request.inputs["input0"].array_shape.dim.extend(np.shape(_data[0]))
  738. request.inputs["input0"].float_val.extend(np.array(_data[0],dtype=np.float64).reshape(-1))
  739. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  740. request.inputs["input1"].array_shape.dim.extend(np.shape(_data[1]))
  741. request.inputs["input1"].float_val.extend(np.array(_data[1],dtype=np.float64).reshape(-1))
  742. request.inputs["input2"].dtype = tf_predict_pb2.DT_FLOAT
  743. request.inputs["input2"].array_shape.dim.extend(np.shape(_data[2]))
  744. request.inputs["input2"].float_val.extend(np.array(_data[2],dtype=np.float64).reshape(-1))
  745. request_data = request.SerializeToString()
  746. list_outputs = ["outputs"]
  747. _result = vpc_requests(role_url, role_authorization, request_data, list_outputs)
  748. if _result is not None:
  749. predict_y = _result["outputs"]
  750. else:
  751. predict_y = self.model_role.predict(datas[0])
  752. else:
  753. predict_y = self.model_role.predict(np.array(datas[0],dtype=np.float64))
  754. for i in range(len(predict_y)):
  755. entity = points_entitys[i]
  756. label = np.argmax(predict_y[i])
  757. values = predict_y[i]
  758. # text = text_list[i]
  759. text_tup = text_list[i]
  760. front, middle, behind = text_tup
  761. whole = "".join(text_tup)
  762. # print('模型预测角色:', front, entity.entity_text, behind,label, values)
  763. # if label in [0, 1, 2, 3, 4]:
  764. # self.role_file.write("{0}#split#{1}#split#{2}#split#{3}#split#{4}\n".format(front, entity.entity_text, behind,label, entity.doc_id))
  765. if re.search('^以\d+[\d,.]+万?元中标', behind) and label != 2: # 优化244261884预测错误 大连长之琳科技发展有限公司以7.63277万元中标
  766. label = 2
  767. values[label] = 0.8
  768. if label in [0, 1, 2, 3, 4] and values[label] < 0.5: # 小于阈值的设为其他,让后面的规则召回重新判断
  769. # print(' # 小于阈值的设为其他,让后面的规则召回重新判断', values[label])
  770. label = 5
  771. elif label in [2,3,4] and re.search('序号:\d+,\w{,2}候选', front):
  772. label = 5
  773. elif label == 0:
  774. if re.search('拟邀请$|受邀谈判方', front):
  775. label = 2
  776. values[label] = 0.501
  777. elif re.search('(发布(人|方|单位|机构|组织|用户|业主|主体|部门|公司|企业)|组织(单位|人|方|机构)?|(采购|招标|发布)机构)(名称)?[是为:]+', front) and is_agency(entity.entity_text):
  778. label = 1
  779. values[label] = 0.501
  780. elif re.search('受托人((盖章))?:$', front):
  781. label = 1
  782. values[label] = 0.501
  783. elif re.search('采用$|异议受理部门|本次招标有:$|直购企业:$', front): # 368177736 因本项目招标采用广西壮族自治区公共资源交易平台系统- 标公告,本次招标有:内黄县汇融钢材有限公司、安阳正元建筑工程有限公司、内黄县鸿业贸易有限责任公司三家合格供应商进行报名投标。 438880541 直购企业可能为多个,其中一个中标
  784. label = 5
  785. elif re.search(',单位名称:$', front) and re.search('^,(中标|中选)价格', behind):
  786. label = 2
  787. values[label] = 0.501
  788. elif label == 2:
  789. if re.search('中标单位和.{,25}签订合同', whole):
  790. label = 0
  791. values[label] = 0.501
  792. elif re.search('尊敬的供应商:.{,25}我公司', whole):
  793. label = 0
  794. values[label] = 0.801
  795. elif re.search('尊敬的供应商:$', front):
  796. label = 0
  797. values[label] = 0.501
  798. elif re.search('第[4-9四五六]中标候选人|(提交单位|竞投单位):$|第[4-9四五六七八九十]名', front): #修复第4以上的预测错为中标人
  799. label = 5
  800. values[2] = 0.5
  801. elif re.search('(排名|排序|名次):([4-9]|\d{2,}),', front): # or re.search('序号:\d+,(供应商|投标|候选)', front): # 293225236 附件中 排名预测错误
  802. values[2] = 0.5
  803. label = 5
  804. elif re.search('税费', front) and re.search('^承担', behind):
  805. label = 5
  806. elif re.search('第一候补|第一后备|备选', front):
  807. label = 3
  808. values[label] = 0.6
  809. elif re.search('^放弃中标资格|是否中标:否|^(中标|成交)(公示|公告)', behind):
  810. values[2] = 0.5
  811. label = 5
  812. elif re.search('^,?(投标报价|(资格性审查:|符合性审查:)?(不通过|不符合))', behind) and re.search('中标|成交|中选|排名|排序|名次|第[一1]', front)==None and values[2]<0.7: #20241126补充条件避免漏提 560768263 第一候选人:单位名称: 上海理想信息产业(集团)有限公司 ,投标报价:
  813. values[2] = 0.5
  814. label = 5
  815. elif re.search('(承包权人|帐户名称|债务人|推荐预审合格投标人名单):$|确定为标的的受让方,$|[主次出]入口?,?$|确定(项目|\w{,2})成交供应商,$|,承刻单位:$|乙方接受为$|丙方:$', front): # 234501112 民币元,序号:1,债务人: 东营市海宁工贸有限责任公司 ,债权本金: 262414286 八、中标后签约单位,合同签约单位: 241929628 1月9,承刻单位: 肃宁县超凡网络光敏印章刻印部 ,印章预留印模
  816. label = 5
  817. elif re.search(',来源:$', front) and re.search('^,', behind): # 修复 472062585 项目采购-关于定制手机询比价采购中标公告,来源:深圳市网联安瑞网络科技有限公司 预测为中标
  818. label = 0
  819. values[label] = 0.5
  820. elif re.search('合同供方:?$|合同签约单位', front):
  821. label = 0
  822. values[label] = 0.5
  823. elif re.search('现由$', front) and re.search('^作为\d个单位的牵头(单位|公司)?', behind): # 修复 469369884 站源批量预测错误 现由第七合同段保利长大工程有限公司作为6个单位的牵头单位,
  824. label = 5
  825. elif re.search('是否中标:是,供应商', front) and label == 5:
  826. label = 2
  827. values[label] = 0.9
  828. elif label == 1:
  829. if re.search('委托(单位|人|方)[是为:]+',front) and re.search('受委托(单位|人|方)[是为:]+', front)==None:
  830. label = 0
  831. values[label] = 0.501
  832. elif re.search('([,。:]|^)(第一)?(服务|中选|中标)(中介服务|代理)?(公司|机构)(名称)?', front):
  833. label = 2
  834. values[label] = 0.501
  835. elif re.search('在中介超市委托$', front) and re.search('^负责', behind):
  836. label = 2
  837. values[label] = 0.501
  838. elif re.search('^:受', behind): # 354009560 附件格式问题 ,中选中介服务机构通知书,编号:HZ2305120541,中汕项目管理有限公司:受惠东县人民政府大岭街道办事处委托
  839. label = 5
  840. elif re.search('发布机构', front) and not is_agency(entity.entity_text):
  841. label = 0
  842. values[label] = 0.501
  843. elif re.search('开户银行:$|环境影响评价机构|环评机构|评价机构', front): # 368214232 法定代表人:委托代理人:开户银行:鸡东建行
  844. label = 5
  845. elif re.search('委托$', front) and re.search('^(抽样|送检|看样)', behind):
  846. label = 5
  847. elif re.search('推荐入围的招标代理单位:$', front): # 20240709 修复302505502预测错为代理
  848. label = 2
  849. values[label] = 0.501
  850. elif label in [3,4]:
  851. if re.search('第[二三]分(公司|店),中标(人|供应商|单位|公司):$', front):
  852. label = 2
  853. values[label] = 0.7
  854. elif re.search('决定选择第[二三]名', front) and re.search('^作为(中标|成交)(人|供应商|单位|公司)', behind):
  855. label = 2
  856. values[label] = 0.8
  857. elif re.search('\d+\.\d+,供应商名称:', front): # 341385226 30.2,供应商名称: 预测为第二名
  858. label = 2
  859. values[label] = 0.501
  860. elif re.search('\d+\.\d+[,、]?(中标|成交)候选人|[;,][23]、(中标|中选|成交)候选人:', front):
  861. label = 5
  862. values[label] = 0.501
  863. elif re.search('第一名:$', front):
  864. label = 2
  865. values[label] = 0.7
  866. elif re.search('(中标|成交)通知书[,:]$', front) and re.search('^:', behind) and label != 2:
  867. label = 2
  868. values[label] = 0.8
  869. elif label==5 and re.search('^拟(招标|采购)一批|^须购置一批', front):
  870. label = 0
  871. values[label] = 0.7
  872. entity.set_Role(label, values)
  873. def predict_money(self,list_sentences,list_entitys):
  874. datas = self.search_money_data(list_sentences, list_entitys)
  875. if datas is None:
  876. return
  877. points_entitys = datas[1]
  878. _data = datas[0]
  879. text_list = datas[2]
  880. if USE_PAI_EAS:
  881. _data = np.transpose(np.array(_data),(1,0,2,3))
  882. request = tf_predict_pb2.PredictRequest()
  883. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  884. request.inputs["input0"].array_shape.dim.extend(np.shape(_data[0]))
  885. request.inputs["input0"].float_val.extend(np.array(_data[0],dtype=np.float64).reshape(-1))
  886. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  887. request.inputs["input1"].array_shape.dim.extend(np.shape(_data[1]))
  888. request.inputs["input1"].float_val.extend(np.array(_data[1],dtype=np.float64).reshape(-1))
  889. request.inputs["input2"].dtype = tf_predict_pb2.DT_FLOAT
  890. request.inputs["input2"].array_shape.dim.extend(np.shape(_data[2]))
  891. request.inputs["input2"].float_val.extend(np.array(_data[2],dtype=np.float64).reshape(-1))
  892. request_data = request.SerializeToString()
  893. list_outputs = ["outputs"]
  894. _result = vpc_requests(money_url, money_authorization, request_data, list_outputs)
  895. if _result is not None:
  896. predict_y = _result["outputs"]
  897. else:
  898. predict_y = self.model_money.predict(_data)
  899. else:
  900. predict_y = self.model_money.predict(_data)
  901. for i in range(len(predict_y)):
  902. entity = points_entitys[i]
  903. label = np.argmax(predict_y[i])
  904. values = predict_y[i]
  905. # text = text_list[i]
  906. text_tup = text_list[i]
  907. front, middle, behind = text_tup
  908. whole = "".join(text_tup)
  909. # print('金额: ', entity.entity_text, label, values, front, middle, behind)
  910. # if label in [0, 1]:
  911. # self.money_file.write("{0} {1} {2} {3}\n".format(front, entity.entity_text, behind, label))
  912. if label in [0, 1] and values[label] < 0.5: # 小于阈值的设为其他金额,让后面的规则召回重新判断
  913. # print('模型预测金额: ', entity.entity_text, label, values, front, middle, behind)
  914. label = 2
  915. elif label == 1: # 错误中标金额处理
  916. if re.search('[::,。](总金额|总价|单价|合价)((万?元))?:?$', front) and re.search('(中标|投标|成交|中价)', front)==None:
  917. values[label] = 0.5
  918. elif re.search('[\+=]((中标|成交)(金?额|价格?)|[若如]果?(中标|成交)(金?额|价格?)为?', front): # 处理例如 241561780 如中标金额为 500-1000万元,则代理服务费=100 万元×0.5%+400万元×0.35%+(中标金额-500)万元
  919. values[label] = 0.49
  920. elif re.search('^(以[上下])?按[\d.%]+收取|^及?以[上下]|^[()]?[+×*-][\d.%]+', behind):
  921. values[label] = 0.49
  922. elif re.search('(含|在|包括|[大小等高低]于|达到)$|[\d.%]+[+×*-]$', front):
  923. values[label] = 0.49
  924. # elif entity.notes == '单价' and float(entity.entity_text)<5000: # 20241128 注释,单价单独存放
  925. # label = 2
  926. elif label ==0: # 错误招标金额处理
  927. if re.search('投资(金额|规模):$', front): # 545988699 金额不大的投资金额作为备选招标金额
  928. values[label] = 0.51
  929. elif entity.notes in ["投资", "总投资","工程造价"] or re.search('最低限价:?$|注册资本', front) or re.search('服务内容:([\d,.]+万?亿?元?-?)$', front):
  930. values[label] = 0.49
  931. label = 2
  932. elif re.search('^(以[上下])?按[\d.%]+收取|^及?以[上下]|^[()]?[+×*-][\d.%]+|(含)', behind):
  933. values[label] = 0.49
  934. # elif re.search('(含|在|包括|[大小等高低]于|如预算金额为)$|[\d.%]+((含))?[+×*-]$', front): # 2024/10/30 注销,避免漏提 预算金额:控制在26000元以内由合作银行出资 ;投资金额不低于人民币500万元
  935. # values[label] = 0.49
  936. # elif entity.notes == '单价' and float(entity.entity_text)<5000: # 20241128 注释,单价单独存放
  937. # label = 2
  938. elif re.search('报价:预估不?含税总价[为:]$', front) and (label != 1 or values[label]<0.5):
  939. label = 1
  940. values[label] = 0.8
  941. entity.set_Money(label, values)
  942. def correct_money_by_rule(self, title, list_entitys, list_articles):
  943. if (len(re.findall('监理|施工|设计|勘察', title)) == 1 and re.search('施工|总承包|epc|EPC', title) == None) or re.search('服务金额', list_articles[0].content):
  944. # keyword = re.search('监理|设计|勘察', title).group(0)
  945. for list_entity in list_entitys:
  946. for _entity in list_entity:
  947. # print('keyword:',keyword, '_entity.notes :',_entity.notes)
  948. # if _entity.entity_type == "money" and _entity.notes == keyword and _entity.label == 2:
  949. if _entity.entity_type == "money" and _entity.notes == '招标或中标金额' and _entity.label == 2:
  950. # if channel_dic['docchannel'] == "招标公告":
  951. if re.search('中标|成交|中选|中价|中租|结果|入围', title + list_articles[0].content[:100]) == None:
  952. _entity.values[0] = 0.51
  953. _entity.set_Money(0, _entity.values) # 2021/11/18 根据公告类别把费用改为招标或中投标金额
  954. else:
  955. _entity.values[1] = 0.51
  956. _entity.set_Money(1, _entity.values)
  957. def predict(self,list_sentences,list_entitys):
  958. self.predict_role(list_sentences,list_entitys)
  959. self.predict_money(list_sentences,list_entitys)
  960. #联系人模型
  961. class EPCPredict():
  962. def __init__(self,config=None):
  963. self.model_person = Model_person_classify(config=config)
  964. def search_person_data(self,list_sentences,list_entitys):
  965. '''
  966. @summary:根据句子list和实体list查询联系人模型的输入数据
  967. @param:
  968. list_sentences:文章的sentences
  969. list_entitys:文章的entitys
  970. @return:联系人模型的输入数据
  971. '''
  972. data_x = []
  973. points_entitys = []
  974. pre_texts = []
  975. for list_entity,list_sentence in zip(list_entitys,list_sentences):
  976. p_entitys = 0
  977. dict_index_sentence = {}
  978. for _sentence in list_sentence:
  979. dict_index_sentence[_sentence.sentence_index] = _sentence
  980. _list_entity = [entity for entity in list_entity if entity.entity_type=="person"]
  981. while(p_entitys<len(_list_entity)):
  982. entity = _list_entity[p_entitys]
  983. if entity.entity_type=="person":
  984. sentence = dict_index_sentence[entity.sentence_index]
  985. item_x = self.model_person.encode(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index)
  986. data_x.append(item_x)
  987. points_entitys.append(entity)
  988. pre_texts.append(spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=20))
  989. p_entitys += 1
  990. if len(points_entitys)==0:
  991. return None
  992. # return [data_x,points_entitys,dianhua]
  993. return [data_x,points_entitys, pre_texts]
  994. def predict_person(self,list_sentences, list_entitys):
  995. datas = self.search_person_data(list_sentences, list_entitys)
  996. if datas is None:
  997. return
  998. points_entitys = datas[1]
  999. pre_texts = datas[2]
  1000. # phone = datas[2]
  1001. if USE_PAI_EAS:
  1002. _data = datas[0]
  1003. _data = np.transpose(np.array(_data),(1,0,2,3))
  1004. request = tf_predict_pb2.PredictRequest()
  1005. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  1006. request.inputs["input0"].array_shape.dim.extend(np.shape(_data[0]))
  1007. request.inputs["input0"].float_val.extend(np.array(_data[0],dtype=np.float64).reshape(-1))
  1008. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  1009. request.inputs["input1"].array_shape.dim.extend(np.shape(_data[1]))
  1010. request.inputs["input1"].float_val.extend(np.array(_data[1],dtype=np.float64).reshape(-1))
  1011. request_data = request.SerializeToString()
  1012. list_outputs = ["outputs"]
  1013. _result = vpc_requests(person_url, person_authorization, request_data, list_outputs)
  1014. if _result is not None:
  1015. predict_y = _result["outputs"]
  1016. else:
  1017. predict_y = self.model_person.predict(datas[0])
  1018. else:
  1019. predict_y = self.model_person.predict(datas[0])
  1020. # assert len(predict_y)==len(points_entitys)==len(phone)
  1021. assert len(predict_y)==len(points_entitys)
  1022. for i in range(len(predict_y)):
  1023. entity = points_entitys[i]
  1024. label = np.argmax(predict_y[i])
  1025. pre_text = ''.join(pre_texts[i][0])
  1026. # print('pre_text', pre_text)
  1027. if label==0 and re.search('(谈判|磋商|询价|资格审查|评审专家|(评选|议标|评标|评审)委员会?|专家|评委)(小?组|小?组成员)?(成员|名单)[:,](\w{2,4}((组长)|(成员))?[、,,])*$', pre_text):
  1028. # print(entity.entity_text, re.search('(谈判|磋商|询价|资格审查|评审专家|(评选|议标|评标|评审)委员会?|专家|评委)(小?组|小?组成员)?(成员|名单)[:,](\w{2,4}((组长)|(成员))?[、,,])*$', pre_text).group(0))
  1029. label = 4
  1030. values = []
  1031. for item in predict_y[i]:
  1032. values.append(item)
  1033. # phone_number = phone[i]
  1034. # entity.set_Person(label,values,phone_number)
  1035. entity.set_Person(label,values,[])
  1036. # 为联系人匹配电话
  1037. # self.person_search_phone(list_sentences, list_entitys)
  1038. def person_search_phone(self,list_sentences, list_entitys):
  1039. def phoneFromList(phones):
  1040. # for phone in phones:
  1041. # if len(phone)==11:
  1042. # return re.sub('电话[:|:]|联系方式[:|:]','',phone)
  1043. return re.sub('电话[:|:]|联系方式[:|:]', '', phones[0])
  1044. for list_entity, list_sentence in zip(list_entitys, list_sentences):
  1045. # p_entitys = 0
  1046. # p_sentences = 0
  1047. #
  1048. # key_word = re.compile('电话[:|:].{0,4}\d{7,12}|联系方式[:|:].{0,4}\d{7,12}')
  1049. # # phone = re.compile('1[3|4|5|7|8][0-9][-—-]?\d{4}[-—-]?\d{4}|\d{3,4}[-—-]\d{7,8}/\d{3,8}|\d{3,4}[-—-]\d{7,8}转\d{1,4}|\d{3,4}[-—-]\d{7,8}|[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}') # 联系电话
  1050. # # 2020/11/25 增加发现的号码段
  1051. # phone = re.compile('1[3|4|5|6|7|8|9][0-9][-—-]?\d{4}[-—-]?\d{4}|'
  1052. # '\d{3,4}[-—-][1-9]\d{6,7}/\d{3,8}|'
  1053. # '\d{3,4}[-—-]\d{7,8}转\d{1,4}|'
  1054. # '\d{3,4}[-—-]?[1-9]\d{6,7}|'
  1055. # '[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1056. # '[1-9]\d{6,7}') # 联系电话
  1057. # dict_index_sentence = {}
  1058. # for _sentence in list_sentence:
  1059. # dict_index_sentence[_sentence.sentence_index] = _sentence
  1060. #
  1061. # dict_context_itemx = {}
  1062. # last_person = "####****++++$$^"
  1063. # last_person_phone = "####****++++$^"
  1064. # _list_entity = [entity for entity in list_entity if entity.entity_type == "person"]
  1065. # while (p_entitys < len(_list_entity)):
  1066. # entity = _list_entity[p_entitys]
  1067. # if entity.entity_type == "person" and entity.label in [1,2,3]:
  1068. # sentence = dict_index_sentence[entity.sentence_index]
  1069. # # item_x = embedding(spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=settings.MODEL_PERSON_INPUT_SHAPE[1]),shape=settings.MODEL_PERSON_INPUT_SHAPE)
  1070. #
  1071. # # s = spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=20)
  1072. #
  1073. # # 2021/5/8 取上下文的句子,解决表格处理的分句问题
  1074. # left_sentence = dict_index_sentence.get(entity.sentence_index - 1)
  1075. # left_sentence_tokens = left_sentence.tokens if left_sentence else []
  1076. # right_sentence = dict_index_sentence.get(entity.sentence_index + 1)
  1077. # right_sentence_tokens = right_sentence.tokens if right_sentence else []
  1078. # entity_beginIndex = entity.begin_index + len(left_sentence_tokens)
  1079. # entity_endIndex = entity.end_index + len(left_sentence_tokens)
  1080. # context_sentences_tokens = left_sentence_tokens + sentence.tokens + right_sentence_tokens
  1081. # s = spanWindow(tokens=context_sentences_tokens, begin_index=entity_beginIndex,
  1082. # end_index=entity_endIndex, size=20)
  1083. #
  1084. # _key = "".join(["".join(x) for x in s])
  1085. # if _key in dict_context_itemx:
  1086. # _dianhua = dict_context_itemx[_key][0]
  1087. # else:
  1088. # s1 = ''.join(s[1])
  1089. # # s1 = re.sub(',)', '-', s1)
  1090. # s1 = re.sub('\s', '', s1)
  1091. # have_key = re.findall(key_word, s1)
  1092. # have_phone = re.findall(phone, s1)
  1093. # s0 = ''.join(s[0])
  1094. # # s0 = re.sub(',)', '-', s0)
  1095. # s0 = re.sub('\s', '', s0)
  1096. # have_key2 = re.findall(key_word, s0)
  1097. # have_phone2 = re.findall(phone, s0)
  1098. #
  1099. # s3 = ''.join(s[1])
  1100. # # s0 = re.sub(',)', '-', s0)
  1101. # s3 = re.sub(',|,|\s', '', s3)
  1102. # have_key3 = re.findall(key_word, s3)
  1103. # have_phone3 = re.findall(phone, s3)
  1104. #
  1105. # s4 = ''.join(s[0])
  1106. # # s0 = re.sub(',)', '-', s0)
  1107. # s4 = re.sub(',|,|\s', '', s0)
  1108. # have_key4 = re.findall(key_word, s4)
  1109. # have_phone4 = re.findall(phone, s4)
  1110. #
  1111. # _dianhua = ""
  1112. # if have_phone:
  1113. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s1.find(
  1114. # last_person_phone) != -1:
  1115. # if len(have_phone) > 1:
  1116. # _dianhua = phoneFromList(have_phone[1:])
  1117. # else:
  1118. # _dianhua = phoneFromList(have_phone)
  1119. # elif have_key:
  1120. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s1.find(
  1121. # last_person_phone) != -1:
  1122. # if len(have_key) > 1:
  1123. # _dianhua = phoneFromList(have_key[1:])
  1124. # else:
  1125. # _dianhua = phoneFromList(have_key)
  1126. # elif have_phone2:
  1127. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s0.find(
  1128. # last_person_phone) != -1:
  1129. # if len(have_phone2) > 1:
  1130. # _dianhua = phoneFromList(have_phone2[1:])
  1131. # else:
  1132. # _dianhua = phoneFromList(have_phone2)
  1133. # elif have_key2:
  1134. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s0.find(
  1135. # last_person_phone) != -1:
  1136. # if len(have_key2) > 1:
  1137. # _dianhua = phoneFromList(have_key2[1:])
  1138. # else:
  1139. # _dianhua = phoneFromList(have_key2)
  1140. # elif have_phone3:
  1141. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s3.find(
  1142. # last_person_phone) != -1:
  1143. # if len(have_phone3) > 1:
  1144. # _dianhua = phoneFromList(have_phone3[1:])
  1145. # else:
  1146. # _dianhua = phoneFromList(have_phone3)
  1147. # elif have_key3:
  1148. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s3.find(
  1149. # last_person_phone) != -1:
  1150. # if len(have_key3) > 1:
  1151. # _dianhua = phoneFromList(have_key3[1:])
  1152. # else:
  1153. # _dianhua = phoneFromList(have_key3)
  1154. # elif have_phone4:
  1155. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s4.find(
  1156. # last_person_phone) != -1:
  1157. # if len(have_phone4) > 1:
  1158. # _dianhua = phoneFromList(have_phone4)
  1159. # else:
  1160. # _dianhua = phoneFromList(have_phone4)
  1161. # elif have_key4:
  1162. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s4.find(
  1163. # last_person_phone) != -1:
  1164. # if len(have_key4) > 1:
  1165. # _dianhua = phoneFromList(have_key4)
  1166. # else:
  1167. # _dianhua = phoneFromList(have_key4)
  1168. # else:
  1169. # _dianhua = ""
  1170. # # dict_context_itemx[_key] = [item_x, _dianhua]
  1171. # dict_context_itemx[_key] = [_dianhua]
  1172. # # points_entitys.append(entity)
  1173. # # dianhua.append(_dianhua)
  1174. # last_person = entity.entity_text
  1175. # if _dianhua:
  1176. # # 更新联系人entity联系方式(person_phone)
  1177. # entity.person_phone = _dianhua
  1178. # last_person_phone = _dianhua
  1179. # else:
  1180. # last_person_phone = "####****++++$^"
  1181. # p_entitys += 1
  1182. from scipy.optimize import linear_sum_assignment
  1183. from BiddingKG.dl.interface.Entitys import Match
  1184. def dispatch(match_list):
  1185. main_roles = list(set([match.main_role for match in match_list]))
  1186. attributes = list(set([match.attribute for match in match_list]))
  1187. label = np.zeros(shape=(len(main_roles), len(attributes)))
  1188. for match in match_list:
  1189. main_role = match.main_role
  1190. attribute = match.attribute
  1191. value = match.value
  1192. label[main_roles.index(main_role), attributes.index(attribute)] = value + 10000
  1193. # print(label)
  1194. gragh = -label
  1195. # km算法
  1196. row, col = linear_sum_assignment(gragh)
  1197. max_dispatch = [(i, j) for i, j, value in zip(row, col, gragh[row, col]) if value]
  1198. return [Match(main_roles[row], attributes[col]) for row, col in max_dispatch]
  1199. # km算法
  1200. key_word = re.compile('((?:电话|联系方式|联系人).{0,4}?)(\d{7,12})')
  1201. phone = re.compile('1[3|4|5|6|7|8|9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1202. '\+86.?1[3|4|5|6|7|8|9]\d{9}|'
  1203. '0\d{2,3}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1204. '0\d{2,3}[-—-―]\d{7,8}转\d{1,4}|'
  1205. '0\d{2,3}[-—-―]?[1-9]\d{6,7}|'
  1206. '[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1207. '[1-9]\d{6,7}')
  1208. phone_entitys = []
  1209. for _sentence in list_sentence:
  1210. sentence_text = _sentence.sentence_text
  1211. res_set = set()
  1212. for i in re.finditer(phone,sentence_text):
  1213. res_set.add((i.group(),i.start(),i.end()))
  1214. for i in re.finditer(key_word,sentence_text):
  1215. res_set.add((i.group(2),i.start()+len(i.group(1)),i.end()))
  1216. for item in list(res_set):
  1217. phone_left = sentence_text[max(0,item[1]-10):item[1]]
  1218. phone_right = sentence_text[item[2]:item[2]+8]
  1219. # 排除传真号 和 其它错误项
  1220. if re.search("传,?真|信,?箱|邮,?箱",phone_left):
  1221. if not re.search("电,?话",phone_left):
  1222. continue
  1223. if re.search("帐,?号|编,?号|报,?价|证,?号|价,?格|[\((]万?元[\))]",phone_left):
  1224. continue
  1225. if re.search("[.,]\d{2,}",phone_right):
  1226. continue
  1227. _entity = Entity(_sentence.doc_id, None, item[0], "phone", _sentence.sentence_index, None, None,item[1], item[2],in_attachment=_sentence.in_attachment)
  1228. phone_entitys.append(_entity)
  1229. person_entitys = []
  1230. for entity in list_entity:
  1231. if entity.entity_type == "person":
  1232. entity.person_phone = ""
  1233. person_entitys.append(entity)
  1234. _list_entity = phone_entitys + person_entitys
  1235. _list_entity = sorted(_list_entity,key=lambda x:(x.sentence_index,x.wordOffset_begin))
  1236. words_num_dict = dict()
  1237. last_words_num = 0
  1238. list_sentence = sorted(list_sentence, key=lambda x: x.sentence_index)
  1239. for sentence in list_sentence:
  1240. _index = sentence.sentence_index
  1241. if _index == 0:
  1242. words_num_dict[_index] = 0
  1243. else:
  1244. words_num_dict[_index] = words_num_dict[_index - 1] + last_words_num
  1245. last_words_num = len(sentence.sentence_text)
  1246. match_list = []
  1247. for index in range(len(_list_entity)):
  1248. entity = _list_entity[index]
  1249. if entity.entity_type=="person" and entity.label in [1,2,3]:
  1250. match_nums = 0
  1251. for after_index in range(index + 1, min(len(_list_entity), index + 5)):
  1252. after_entity = _list_entity[after_index]
  1253. if after_entity.entity_type=="phone":
  1254. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1255. distance = (words_num_dict[after_entity.sentence_index] + after_entity.wordOffset_begin) - (
  1256. words_num_dict[entity.sentence_index] + entity.wordOffset_end)
  1257. if sentence_distance < 2 and distance < 50:
  1258. value = (-1 / 2 * (distance ** 2)) / 10000
  1259. match_list.append(Match(entity, after_entity, value))
  1260. match_nums += 1
  1261. else:
  1262. break
  1263. if after_entity.entity_type=="person":
  1264. if after_entity.label not in [1,2,3]:
  1265. break
  1266. if not match_nums:
  1267. for previous_index in range(index-1, max(0,index-5), -1):
  1268. previous_entity = _list_entity[previous_index]
  1269. if previous_entity.entity_type == "phone":
  1270. sentence_distance = entity.sentence_index - previous_entity.sentence_index
  1271. distance = (words_num_dict[entity.sentence_index] + entity.wordOffset_begin) - (
  1272. words_num_dict[previous_entity.sentence_index] + previous_entity.wordOffset_end)
  1273. if sentence_distance < 1 and distance<30:
  1274. # 前向 没有 /10000
  1275. value = (-1 / 2 * (distance ** 2))
  1276. match_list.append(Match(entity, previous_entity, value))
  1277. else:
  1278. break
  1279. result = dispatch(match_list)
  1280. for match in result:
  1281. entity = match.main_role
  1282. # 更新 list_entity
  1283. entity_index = list_entity.index(entity)
  1284. list_entity[entity_index].person_phone = match.attribute.entity_text
  1285. def predict(self,list_sentences,list_entitys):
  1286. self.predict_person(list_sentences,list_entitys)
  1287. #表格预测
  1288. class FormPredictor():
  1289. def __init__(self,lazyLoad=getLazyLoad(),config=None):
  1290. self.model_file_line = os.path.dirname(__file__)+"/../form/model/model_form.model_line.hdf5"
  1291. self.model_file_item = os.path.dirname(__file__)+"/../form/model/model_form.model_item.hdf5"
  1292. self.model_form_item = Model_form_item(config=config)
  1293. self.model_dict = {"line":[None,self.model_file_line]}
  1294. self.model_form_context = Model_form_context(config=config)
  1295. def getModel(self,type):
  1296. if type=="item":
  1297. return self.model_form_item
  1298. elif type=="context":
  1299. return self.model_form_context
  1300. else:
  1301. return self.getModel(type)
  1302. def encode(self,data,**kwargs):
  1303. return encodeInput([data], word_len=50, word_flag=True,userFool=False)[0]
  1304. return encodeInput_form(data)
  1305. def predict(self,form_datas,type):
  1306. if type=="item":
  1307. return self.model_form_item.predict(form_datas)
  1308. elif type=="context":
  1309. return self.model_form_context.predict(form_datas)
  1310. else:
  1311. return self.getModel(type).predict(form_datas)
  1312. #角色规则
  1313. #依据正则给所有无角色的实体赋予角色,给予等于阈值的最低概率
  1314. class RoleRulePredictor():
  1315. def __init__(self):
  1316. # (?P<tenderee_left_w1> 正则组名 后面的 w1 为概率权重关键词
  1317. self.pattern_tenderee_left_55 = "(?P<tenderee_left_55>((遴选|寻源|采购|招标|竞价|议价|比选|委托|询比?价|比价|评选|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选|项目|需求|甲方?|转让|招租|议标|合同主体|挂牌|出租|出让|出售|标卖|处置|发包|最终|建设|业主|竞卖|申购|公选)" \
  1318. "(人|方|单位|组织|用户|业主|主体|部门|公司|企业|工厂|银行)|需求?方|买方|业主|权属人|甲方当事人|询价书企业|比选发起人|采购(执行|实施)单位)"\
  1319. "[))]?(信息|联系方式|概况)?[,,::]?([((](1|2|1.1|1.2)[))])?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|为|:|:|\s*)+$)"
  1320. self.pattern_tenderee_left_60 = "(?P<tenderee_left_60>(,|。|^)(项目)?((遴选|寻源|采购|招标|竞价|议价|比选|委托|询比?价|比价|评选|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选|项目|需求|甲|转让|招租|议标|合同主体|挂牌|出租|出让|出售|标卖|处置|发包)" \
  1321. "(人|方|单位|组织|用户|业主|主体|部门|公司|企业|工厂|银行))"\
  1322. "[))]?(信息|联系方式|概况)?[,,。::]?([((]?(1|2|1.1|1.2)[))]?)?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|为|:|:|,|\s*)+$)" # 367784094 隆道-大企业采购平台 采购商:C5石油树脂-中国建材集团有限公司-四川省/成都市/市辖区
  1323. self.pattern_tenderee_left_50 = "(?P<tenderee_left_50>((所需|需[用求]|购货|征集|发布|交易发起|开户|申报|填报|开票|收货)" \
  1324. "(人|方|单位|组织|用户|业主|主体|部门|公司|企业|工厂)|[转流]出方|文章来源|委托机构|产权所有人|承包权人|结算单位|收货地址)" \
  1325. "[))]?(信息|联系方式|概况)?[,,::]?([((](1|2|1.1|1.2)[))])?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|为|:|:|\s*)+$|(采购商|招标人):(\w{2,10}-)?$)"
  1326. self.pattern_tenderee_center = "(?P<tenderee_center>(受.{5,20}的?委托|现将[\w()()]{5,20}[\d年月季度至()]+采购意向|尊敬的供应商(伙伴)?:\w{5,20}(以下简称“\w{2,5}”)))"
  1327. self.pattern_tenderee_right = "(?P<tenderee_right>^(机关)?([((](以下简称)?[,\"“]*((招标|采购)(人|单位|机构)|(服务)?购买方)[,\"”]*[))]|^委托|^将于[\d年月日,::]+进行|^现委托|^的\w{2,10}正在进行|[\d年月季度至]+采购意向|^)?的招标工作已圆满结束)|^([拟须需]|计划)(采购|招标|购置|购买)|^须购[买置]一批|作为(采购|招标)(人|单位)|^关于)" #|(^[^.。,,::](采购|竞价|招标|施工|监理|中标|物资)(公告|公示|项目|结果|招标))|的.*正在进行询比价)
  1328. self.pattern_tendereeORagency_right = "(?P<tendereeORagency_right>(^拟对|^现?就|^现对))"
  1329. self.pattern_agency_left = "(?P<agency_left>((代理|拍卖)(?:人|机构|公司|企业|单位|组织)|专业采购机构|集中采购机构|招标组织机构|交易机构|集采机构|[招议))]+标机构|(采购|招标)代理)(名称|.{,4}名,?称|全称)?(是|为|:|:|[,,]?\s*)$|(受.{5,20}委托,?$))"
  1330. self.pattern_agency_right = "(?P<agency_right>^([((](以下简称)?[,\"“]*(代理)(人|单位|机构)[,\"”]*[))])|^受.{5,20}委托|^受委?托,)" # |^受托 会与 受托生产等冲突,代理表达一般会在后面有逗号
  1331. # 2020//11/24 大网站规则 中标关键词添加 选定单位|指定的中介服务机构
  1332. self.pattern_winTenderer_left_50 = "(?P<winTenderer_left_51>" \
  1333. "(乙|竞得|受让|买受|签约|供货|供应?|合作|承做|承包|承建|承销|承保|承接|承制|承担|承修|承租((包))?|入围|入选|竞买)(候选|投标)?(人|单位|机构|供应商|方|公司|企业|厂商|商|社会资本方?|银行)(:?单位名称|:?名称|盖章)?[::是为]+$" \
  1334. "|(选定单位|指定的中介服务机构|实施主体|中标银行|中标通知书,致|征集结果|选择中介|选择结果|成交对象|勘察人|(,|审计|处置|勘察|设计)服务单位|受托[人方])[::是为]+$" \
  1335. "|((评审结果|名次|排名|中标结果)[::]*第?[一1]名?)[::是为]+$|成交供应商信息[,:]?(序号1)?:?|供应商名称$|竞争性选择申请人名称:$" \
  1336. "|单一来源(采购)?(供应商|供货商|服务商|方式向)$|((中标|成交)(结果|信息))[::是为]+$|(中标|成交)供应商、(中标|成交)(金额|价格),$" \
  1337. "|现(公布|宣布|公示)中标单位如下:$|现将中标单位(公布|公示)如下:$|现宣布以下(企业|单位|公司)中标:$|经讨论,决定采用$)" # 承办单位:不作为中标 83914772 |施工 单位不作为中标人 例:386692187
  1338. self.pattern_winTenderer_left_60 = "(?P<winTenderer_left_60>" \
  1339. "(,|。|:|^)((中标(投标)?|[拟预]中标|中选|中价|中签|成交)(人|单位|机构|中介(服务)?机构|供应商|客户|方|公司|企业|厂商|商家?|社会资本方?|银行)|(中标候选人)?第?[一1]名|第[一1](中标|中选|成交)?候选人|服务机构)" \
  1340. "(:?单位名称|:?名称|盖章)?[,,]?([((]按综合排名排序[))]|:择优选取)?[::,,]$|选取(情况|说明):中选,中介机构名称:$|排名如下:1、$|第[一1]名,?投标(人|单位|银行|公司):$)" # 解决表头识别不到加逗号情况,需前面为,。空 20240621补充 中选 云南省投资审批中介超市 补充排名如下 南阳师范学院
  1341. self.pattern_winTenderer_left_55 = "(?P<winTenderer_left_55>(中标(投标)?|[拟预]中标|中选|中价|中签|成交|入选)(人|单位|机构|中介(服务)?机构|供应商|客户|方|公司|企业|厂商|商家?|社会资本方?|银行)" \
  1342. "(:?单位名称|:?名称|盖章)?([((]按综合排名排序[))]|:择优选取)?[::是为]+$" \
  1343. "|结果公示如下:摇出球号:\d+号,中介机构:$)" # 取消逗号 并拒绝执行改进计划的供应商,华新水泥将可能终止与其合作关系 # 中标候选人不能作为中标 # |直购企业:$不能作为中标人,看到有些公告会又多个公司,然后还会发布中选结果的公告,其中一个公司中标
  1344. self.pattern_winTenderer_right = "(?P<winTenderer_right>(^[是为](首选)?((采购|中标|成交)(供应商|供货商|服务商)|(第[一1]|预)?(拟?(中标|中选|中价|成交)(候选|排序)?(人|单位|机构|供应商|公司|企业|厂商|银行)))|" \
  1345. "^((报价|价格)最低,|以\w{5,10})?(确定|成|作)?为[\w“”()]{3,25}((成交|中选|中标|服务)(人|单位|供应商|企业|公司)|供货单位|供应商|第一中标候选人)[,。]" \
  1346. "|^:贵公司参与|^:?你方于|^(胜出)?中标。|^取得中标(单位)?资格|^以\d+[\d,.]+万?元(中标|成交|中选)" \
  1347. "|^通过(挂牌|拍卖)方式(以[\d.,]+万?元)?竞得|^[((](中标|成交|承包)人名?称?[))]))" # 去掉 |\w{,20} 修复 460216955 网上公布的与本次采购项目有关的信息视为已送达各响应供应商。 作为中标
  1348. self.pattern_winTenderer_whole = "(?P<winTenderer_center>(贵公司|由).{,15}以\w{,15}中标|确定[\w()]{5,20}为[^,。;]{5,50}的?中标单位" \
  1349. "|选定报价最低的[“”\w()]{5,25}为[^,。;]{5,50}的?(服务|中标|成交)单位" \
  1350. "|拟邀请[\w()]{5,20}(进行)?单一来源谈判|(承办单位|报价人|投标人|中介机构)(名称)?:[\w()]{5,20},(中标|承办|中选)(价格|金额)" \
  1351. "|(谈判结果:|结果|最终|确定|决定)[以由为][^,。;]{5,25}(向我单位)?(供货|承担|承接|中标|竞买成功)|中标通知书.{,15}你方|单一来源方?式?[从向][()\w]{5,20}采购|供应商名称:[()\w]{5,20},独家采购原因)" # 2020//11/24 大网站规则 中标关键词添加 谈判结果:由.{5,20}供货
  1352. self.pattern_secondTenderer_left = "(?P<secondTenderer_left>((第[二2]名?(名|((中标|中选|中价|成交|候选)(候选)?(人|单位|机构|供应商|公司|银行))))(名称)?[::是为]+$)|((评审结果|名次|排名|排序)[::]第?[二2]名?,?(投标(供应)?商|供应商)(名称)?[::]+$))"
  1353. self.pattern_secondTenderer_right = "(?P<secondTenderer_right>^[是为\(]第[二2](名|(中标|中选|中价|成交)(候选)?(人|单位|机构|供应商|公司|银行)))"
  1354. self.pattern_thirdTenderer_left = "(?P<thirdTenderer_left>(第[三3]名?(名|((中标|中选|中价|成交|候选)(候选)?(人|单位|机构|供应商|公司|银行))))(名称)?[::是为]+$|((评审结果|名次|排名|排序)[::]第?[三3]名?,?(投标(供应)?商|供应商)(名称)?[::]+$))"
  1355. self.pattern_thirdTenderer_right = "(?P<thirdTenderer_right>^[是为\(]第[三3](名|(中标|中选|中价|成交)(候选)?(人|单位|机构|供应商|公司|银行)))"
  1356. self.condadate_left = "(?P<candidate_left>(((中[标选商]|成交|入围|入选)候选|投标)(人|单位|机构|中介(服务)?机构|供应商|客户|方|公司|厂商|商家?|社会资本方?|银行)|服务单位)(:?单位名称|:?名称|全称|(?盖\w{,5}章)?|如下|:?牵头人|[及与和](成交|中标)金额)?[::是为]+$)"
  1357. self.pattern_left = [
  1358. self.pattern_tenderee_left_60,
  1359. self.pattern_tenderee_left_55,
  1360. self.pattern_tenderee_left_50,
  1361. self.pattern_agency_left,
  1362. self.pattern_secondTenderer_left,
  1363. self.pattern_thirdTenderer_left,
  1364. self.pattern_winTenderer_left_60,
  1365. self.pattern_winTenderer_left_55,
  1366. self.pattern_winTenderer_left_50,
  1367. ]
  1368. self.pattern_whole = [
  1369. self.pattern_winTenderer_whole,
  1370. self.pattern_tenderee_center,
  1371. ]
  1372. self.pattern_right = [
  1373. self.pattern_thirdTenderer_right,
  1374. self.pattern_secondTenderer_right,
  1375. self.pattern_agency_right,
  1376. self.pattern_tendereeORagency_right,
  1377. self.pattern_tenderee_right,
  1378. self.pattern_winTenderer_right,
  1379. ]
  1380. self.SET_NOT_TENDERER = set(["人民政府","人民法院","中华人民共和国","人民检察院","评标委员会","中国政府","中国海关","中华人民共和国政府"])
  1381. self.pattern_money_tenderee = re.compile("投?标?最高限价|采购计划金额|项目预算|招标金额|采购金额|项目金额|投资估算|采购(单位|人)委托价|招标限价|拦标价|预算金额|标底|总计|限额|资金来源,?[为:]+\w{2,4}资金|采购成本价|总费用约?为|(招标|采购)总?(规模|额度|资金)|资金来源") # |建安费用 不作为招标金额
  1382. self.pattern_money_tenderer = re.compile("((合同|成交|中标|应付款|交易|投标|验收|订单)[)\)]?(综合)?(总?金额|结果|[单报总]?价))|标的基本情况|承包价|报酬(含税):|经评审的价格") # 单写 总价 不能作为中标金额,很多表格有单价、总价
  1383. self.pattern_money_tenderer_whole = re.compile("(以金额.*中标)|中标供应商.*单价|以.*元(报价)?(中标|中选|成交)")
  1384. self.pattern_money_other = re.compile("代理费|服务费")
  1385. self.pattern_money_bank_tenderee = "存[款放](操作)?,?总?(金额|总额|规模|额度|资金)|招标的?资金总量|(项目|资金)总?(规模|额度)|现金管理的?(操作)?(额度|规模|总额)|定期存款|存款大?约|定期存储|竞争性存放|项目资金|日均存款|资金现状|存量金额|招标分配的资金量|资金总[量额]|总(规模|额度|金额)|投资金额" # 存款类招标金额
  1386. self.pattern_money_bank_tenderee_right = "^,?(提供定期存放服务|存[款放](期限|时间)|存期|结构性存款|期限|\w{,4}(定期存款|公款存放|资金存放))" # 存款类招标金额
  1387. self.pattern_pack = "(([^承](包|标[段号的包]|分?包|包组)编?号?|项目)[::]?[\((]?[0-9A-Za-z一二三四五六七八九十]{1,4})[^至]?|(第?[0-9A-Za-z一二三四五六七八九十]{1,4}(包号|标[段号的包]|分?包))|[0-9]个(包|标[段号的包]|分?包|包组)"
  1388. # self.role_file = open('/data/python/lsm/role_rule_predict.txt', 'a', encoding='utf-8')
  1389. def _check_input(self,text, ignore=False):
  1390. if not text:
  1391. return []
  1392. if not isinstance(text, list):
  1393. text = [text]
  1394. null_index = [i for i, t in enumerate(text) if not t]
  1395. if null_index and not ignore:
  1396. raise Exception("null text in input ")
  1397. return text
  1398. def ser_role(self, pattern_list, text, entity_text):
  1399. for _pattern in pattern_list:
  1400. for _iter in re.finditer(_pattern, text):
  1401. for _group, _v_group in _iter.groupdict().items():
  1402. if _v_group is not None and _v_group != "":
  1403. _role = _group.split("_")[0]
  1404. if _role == "tendereeORagency": # 2022/3/9 新增不确定招标代理判断逻辑
  1405. # print('p_entity_sentenceindex:', p_entity.sentence_index)
  1406. # if re.search('医院|学校|大学|中学|小学|幼儿园|政府|部|委员会|署|行|局|厅|处|室|科|股|站', entity_text) \
  1407. # or re.search('(采购|招标|投标|交易|代理|拍卖|咨询|顾问|管理)', entity_text) == None:
  1408. if is_agency(entity_text):
  1409. _role = 'tenderee'
  1410. else:
  1411. _role = "agency"
  1412. _direct = _group.split("_")[1]
  1413. # _weight = _group.split("_")[2] if len(_group.split("_")) == 3 else ""
  1414. prob = int(_group.split("_")[2])/100 if len(_group.split("_")) == 3 else 0.55
  1415. # print('实体召回概率:', prob)
  1416. _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1417. "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1418. return (_label, prob, _iter.group(0))
  1419. return (5, 0.5, '')
  1420. def rule_predict(self, before, center, after, entity_text):
  1421. # before = before if isinstance(before, str) else ""
  1422. # center = center if isinstance(center, str) else ""
  1423. # after = after if isinstance(after, str) else ""
  1424. _label, _prob, keyword = self.ser_role(self.pattern_left, before, entity_text) # 前文匹配
  1425. keyword = "left_" + keyword if keyword!="" else keyword
  1426. if _label == 2 and re.search(
  1427. '各.{,5}供应商|尊敬的供应商|[^\w]候选供应商|业绩|拟招|(交易|采购|招标|建设)服务(单位|机构)|第[四五六七4567]|是否中标:否|序号:\d+,\w{,2}候选|(排名|排序|名次):([4-9]|\d{2,})|未(中[标选]|入围)|不得确定为|(响应|参[加与]报价|通过资格审查)的?供应商',
  1428. # 135463002 拟招一家供应商为宜宾市第三人民医院、李庄同济医院院区提供消防维保服务
  1429. before) != None:
  1430. _label = 5
  1431. elif _label == 2 and re.search('为$', before) and re.match('\w', after): # 排除错误 前文为结尾,后文不是标点符号结尾的,如 353824459 供应商为社会团体的, 供应商为玉田县中医医院提供安保服务
  1432. _label = 5
  1433. elif _label == 2 and re.search('评委|未中标', after[:5]): # 397194341 过滤掉错误召回中标人
  1434. _label = 5
  1435. elif _label == 2 and re.search('^,?(投标报价|(资格性审查:|符合性审查:)?(不通过|不符合))', after) and re.search('中标|成交|中选|排名|排序|名次|第[一1]名', before[-10:])==None: #20240705 处理类似 493939047 错误
  1436. _label = 5
  1437. if _label == 5:
  1438. _label, _prob, keyword = self.ser_role(self.pattern_whole, before + center + after, entity_text) # 前后文匹配
  1439. keyword = 'whole_'+ keyword[:keyword.find(entity_text)] if keyword!="" else keyword
  1440. if _label == 2 and re.search('以[^,。;]{10,30}为准', before + center + after)!=None:
  1441. _label = 5
  1442. if _label != 5 and self.ser_role(self.pattern_whole, before, entity_text)[0] != 5 or \
  1443. self.ser_role(self.pattern_whole, after, entity_text)[0] != 5:
  1444. _label = 5
  1445. if _label == 5:
  1446. _label, _prob, keyword = self.ser_role(self.pattern_right, after, entity_text) # 后文匹配
  1447. keyword = "right_" + keyword if keyword!="" else keyword
  1448. if _label==5 and re.search('(中标|中选|成交)?)(结果)?(公告|公示|通知书?),', before) and re.match(':', after):
  1449. _label = 2
  1450. _prob = 0.5
  1451. _flag = False if _label==5 else True
  1452. return (_label, _prob, _flag, keyword)
  1453. def predict(self, list_articles, list_sentences, list_entitys, list_codenames, channel_dic, on_value=0.5, all_winner=False, req_scope=[], deposit_project=False):
  1454. '''
  1455. :param list_articles:
  1456. :param list_sentences:
  1457. :param list_entitys:
  1458. :param list_codenames:
  1459. :param channel_dic:
  1460. :param on_value: 最低阈值
  1461. :param all_winner: 是否存款、入围等公告,不分排名作为中标人
  1462. :param req_scope: 大纲采购内容开始结束位置[((开头句子index, 开头位置), (结束句子index, 结束句子位置)]
  1463. :param is_deposit_project: 是否为银行存款类项目
  1464. :return:
  1465. '''
  1466. for article, list_entity, list_sentence, list_codename in zip(list_articles, list_entitys, list_sentences,
  1467. list_codenames):
  1468. list_sentence.sort(key=lambda x: x.sentence_index) # 2022/1/5 按句子顺序排序
  1469. # list_name = list_codename["name"]
  1470. list_name = [] # 2022/1/5 改为实体列表内所有项目名称
  1471. name_entitys = [] # 2023/6/30 保存项目名称实体,直接通过位置判断角色是否在项目名称里面
  1472. candidates = [] # 保存不能确定为第几的候选人 2023/04/14
  1473. notfound_tenderer = True # 未找到前三候选人
  1474. deposit_moneys = [] # 保存存款类项目采购内容中大于百万的其他金额实体
  1475. for entity in list_entity:
  1476. if entity.entity_type == 'name':
  1477. list_name.append(entity.entity_text)
  1478. name_entitys.append(entity)
  1479. list_name = self._check_input(list_name) + [article.title]
  1480. for p_entity in list_entity:
  1481. if p_entity.entity_type in ["org", "company"]:
  1482. # 只解析角色为无的或者概率低于阈值的
  1483. if p_entity.label is None:
  1484. continue
  1485. # 将上下文包含标题的实体概率置为0.6,因为标题中的实体不一定是招标人
  1486. if str(p_entity.label) == "0":
  1487. find_flag = False
  1488. for _sentence in list_sentence:
  1489. if _sentence.sentence_index == p_entity.sentence_index:
  1490. # _span = spanWindow(tokens=_sentence.tokens, begin_index=p_entity.begin_index,
  1491. # end_index=p_entity.end_index, size=20, center_include=True,
  1492. # word_flag=True, use_text=True,
  1493. # text=re.sub(")", ")", re.sub("(", "(", p_entity.entity_text)))
  1494. _span = get_context(_sentence.sentence_text, p_entity.wordOffset_begin,
  1495. p_entity.wordOffset_end, size=20, center_include=True)
  1496. if re.search(self.pattern_tenderee_left_50, _span[0]) or re.search(self.pattern_tenderee_left_55, _span[0]): # 前面有关键词的实体不判断是否在项目名称中出现
  1497. find_flag = True
  1498. break
  1499. if re.search('(项目|工程|招标|采购(条目)?|合同|标项|标的|计划|询价|询价单|询价通知书|申购单|申购)(名称|标名|标题|主题):$', _span[0]):
  1500. find_flag = True
  1501. if re.search('(局|院|府|学|处|站|会|所|校|馆|队|厅|室|司|心|园|厂)$', p_entity.entity_text):
  1502. p_entity.values[0] = 0.6 if p_entity.values[0]>0.6 else 0.55
  1503. else:
  1504. p_entity.values[0] = on_value # 项目名称里面实体修改为最低概率
  1505. break
  1506. for _name in name_entitys:
  1507. if _name.sentence_index == p_entity.sentence_index and p_entity.wordOffset_begin >=_name.wordOffset_begin and p_entity.wordOffset_end < _name.wordOffset_end:
  1508. find_flag = True
  1509. if re.search('(局|院|府|学|处|站|会|所|校|馆|队|厅|室|司|心|园|厂)$', p_entity.entity_text):
  1510. p_entity.values[0] = 0.6 if p_entity.values[0] > 0.6 else 0.55
  1511. else:
  1512. p_entity.values[0] = on_value # 项目名称里面实体修改为最低概率
  1513. break
  1514. # if p_entity.values[0] > on_value:
  1515. # p_entity.values[0] = 0.5 + (p_entity.values[0] - 0.5) / 10
  1516. # else:
  1517. # p_entity.values[0] = on_value # 2022/03/08 修正类似 223985179 公司在文章开头的项目名称概率又没达到0.5的情况
  1518. # for _name in list_name:
  1519. # if _name != "" and str(_span[0][-10:]+_span[1] + _span[2][:len(str(_name))]).find(_name) >= 0: #加上前面一些信息,修复公司不在项目名称开头的,检测不到
  1520. # find_flag = True
  1521. # if p_entity.values[0] > on_value:
  1522. # p_entity.values[0] = 0.5 + (p_entity.values[0] - 0.5) / 10
  1523. # else:
  1524. # p_entity.values[0] = on_value # 2022/03/08 修正类似 223985179 公司在文章开头的项目名称概率又没达到0.5的情况
  1525. if find_flag:
  1526. continue
  1527. # 正则从概率低于阈值或其他类别中召回角色
  1528. role_prob = float(p_entity.values[int(p_entity.label)])
  1529. if role_prob < on_value or str(p_entity.label) == "5":
  1530. # 将标题中的实体置为招标人
  1531. _list_name = self._check_input(list_name, ignore=True)
  1532. find_flag = False
  1533. for _name in _list_name: # 2022/1/5修正只要项目名称出现过的角色,所有位置都标注为招标人
  1534. if str(_name).find(p_entity.entity_text) >= 0 and p_entity.sentence_index < 4:
  1535. for _sentence in list_sentence:
  1536. if _sentence.sentence_index == p_entity.sentence_index:
  1537. # _span = spanWindow(tokens=_sentence.tokens, begin_index=p_entity.begin_index,
  1538. # end_index=p_entity.end_index, size=20, center_include=True,
  1539. # word_flag=True, use_text=True, text=p_entity.entity_text)
  1540. _span = get_context(_sentence.sentence_text, p_entity.wordOffset_begin,
  1541. p_entity.wordOffset_end, size=20, center_include=True)
  1542. if _span[2].startswith(":"): # 实体后面为冒号的不作为招标人,避免项目名称出错中标变招标 368122675 陇西兴恒建建筑有限责任公司:线路安全保护区内环境治理专项整改(第二标段)项目
  1543. break
  1544. if str(_span[0][-len(str(_name)):]+_span[1] + _span[2][:len(str(_name))]).find(
  1545. _name) >= 0 or str(_name).startswith(p_entity.entity_text): # 20240621 补充公司开头的项目名称召回,避免name太长召回失败 例 367033697
  1546. # if p_entity.entity_text in agency_set or re.search('(代理|管理|咨询|招投?标|采购)\w{,6}公司', p_entity.entity_text): # 在代理人集合的作为代理人
  1547. if is_agency(p_entity.entity_text): # 2024/3/29 统一方法判断是否为代理
  1548. find_flag = True
  1549. _label = 1
  1550. p_entity.label = _label
  1551. p_entity.values[int(_label)] = on_value
  1552. break
  1553. else:
  1554. find_flag = True
  1555. _label = 0
  1556. p_entity.label = _label
  1557. p_entity.values[int(_label)] = on_value + p_entity.values[int(_label)] / 10
  1558. if 6<len(p_entity.entity_text) < 20 and p_entity.entity_type == 'org': # 标题中角色长度在一定范围内的加分 优化类似367720967 标题中两个实体选择错误问题
  1559. p_entity.values[int(_label)] += 0.005
  1560. break
  1561. if p_entity.sentence_index >= 4:
  1562. break
  1563. if find_flag:
  1564. break
  1565. # 若是实体在标题中,默认为招标人,不进行以下的规则匹配
  1566. if find_flag:
  1567. continue
  1568. for s_index in range(len(list_sentence)):
  1569. if p_entity.doc_id == list_sentence[s_index].doc_id and p_entity.sentence_index == \
  1570. list_sentence[s_index].sentence_index:
  1571. tokens = list_sentence[s_index].tokens
  1572. begin_index = p_entity.begin_index
  1573. end_index = p_entity.end_index
  1574. size = 40 #15
  1575. spans = spanWindow(tokens, begin_index, end_index, size, center_include=True,
  1576. word_flag=True, use_text=False)
  1577. # _flag = False
  1578. # 添加中标通知书类型特殊处理
  1579. try:
  1580. if s_index == 0 and re.search('中标通知书.{,30}[,:]%s:'%p_entity.entity_text.replace('(', '').replace(')', ''),
  1581. list_sentence[s_index].sentence_text.replace('(', '').replace(')', '')[:100]):
  1582. p_entity.label = 2
  1583. p_entity.values[2] = 0.5
  1584. notfound_tenderer = False
  1585. # log('正则召回实体: %s, %s, %s, %d, %.4f, %s'%(_group, _v_group, p_entity.entity_text, p_entity.label, p_entity.values[p_entity.label], list_spans[_i_span]))
  1586. break
  1587. except Exception as e:
  1588. print('正则报错:', e)
  1589. before, center, after = spans[0], spans[1], spans[2]
  1590. entity_text = p_entity.entity_text
  1591. _label, _prob, _flag, kw = self.rule_predict(before, center, after, entity_text)
  1592. if _label == 5 and re.search(':(1[.、])?$', before) and re.search('^[、;,&/。]', after) and re.search('(监督|管理)(机构|部门|单位):', before)==None and re.search(
  1593. '(中标|成交|中选))?(人|单位|供应商|银行|合作伙伴)?(公示)?(信息|情况|结果|如下)(公[示告]如下)?:|(遴选|寻源|采购|招标|竞价|议价|比选|委托|询比?价|比价|评选|谈判|邀标|邀请|洽谈|约谈|选取|抽取)结果(如下)(公[示告]如下)?:', list_sentence[s_index].sentence_text[:p_entity.wordOffset_begin]): # 补充召回 例:514053647 标段1:中国建设银行西安南大街支行,标段2:中国农业银行股份有限公司西安分行,
  1594. _flag = True
  1595. _label = 2
  1596. _prob = 0.5
  1597. elif _label == 5 and all_winner==1 or (all_winner==2 and re.search('(排[名序]|名次|顺序|第):?[0-9一二三四五六七八九十]+', before)==None):
  1598. if re.search('(中标|中选|成交|入围|入选)(人|单位|供应商|银行)(名称)?:', before) and re.search('未(中标|中选|成交|入围|入选)', before)==None:
  1599. _flag = True
  1600. _label = 2
  1601. _prob = 0.55
  1602. elif re.search('(:|[::,]\d{1,2}[.、])$', before) and re.search('^[、;,&/。]', after) and re.search('(监督|管理)(机构|部门|单位):', before)==None and re.search('(入围|合格)(人|单位|供应商|银行|候选人|合作伙伴)?(信息|情况|结果|如下)(公[示告]如下)?(:|,?((入围)?排名不分先后))', list_sentence[s_index].sentence_text[:p_entity.wordOffset_begin]):
  1603. _flag = True
  1604. _label = 2
  1605. _prob = 0.51
  1606. elif re.search('(候选|投标|应答|响应)(人|单位|供应商|银行)(名称)?:', before):
  1607. _flag = True
  1608. _label = 2
  1609. _prob = 0.5
  1610. # if _label in [0, 1, 2, 3, 4]:
  1611. # self.role_file.write("{0}#split#{1}#split#{2}#split#{3}#split#{4}\n".format(before,
  1612. # entity.entity_text,
  1613. # after,
  1614. # _label,
  1615. # entity.doc_id))
  1616. # 得到结果
  1617. if _flag:
  1618. if _label in [2, 3, 4]:
  1619. notfound_tenderer = False
  1620. p_entity.label = _label
  1621. # p_entity.values[int(_label)] = on_value + p_entity.values[
  1622. # int(_label)] / 10
  1623. p_entity.values[_label] = _prob + p_entity.values[int(_label)] / 10
  1624. # log('正则召回实体: %s, %s, %d, %.4f, %s'%(kw, p_entity.entity_text, p_entity.label, p_entity.values[p_entity.label], before+" "+after))
  1625. break
  1626. if re.search(self.condadate_left, before) and re.search('尊敬的|各', before[-10:])==None:
  1627. candidates.append(p_entity)
  1628. # # 使用正则+距离解决冲突
  1629. # # 2021/6/11update center: spans[1] --> spans[0][-30:]+spans[1]
  1630. # list_spans = [spans[0][-30:], spans[0][-10:] + spans[1] + spans[2][:25], spans[2]] # 实体左、中、右 信息
  1631. # for _i_span in range(len(list_spans)):
  1632. # _flag = False
  1633. # _prob_weight = 1
  1634. #
  1635. # # print(list_spans[_i_span],p_entity.entity_text)
  1636. # for _pattern in self.pattern_whole:
  1637. # for _iter in re.finditer(_pattern, list_spans[_i_span]):
  1638. # for _group, _v_group in _iter.groupdict().items():
  1639. # if _v_group is not None and _v_group != "":
  1640. # _role = _group.split("_")[0]
  1641. # if _role == "tendereeORagency": # 2022/3/9 新增不确定招标代理判断逻辑
  1642. # # print('p_entity_sentenceindex:', p_entity.sentence_index)
  1643. # if p_entity.sentence_index>=1: # 只在第一句进行这种模糊匹配
  1644. # continue
  1645. # if re.search('医院|学校|大学|中学|小学|幼儿园|政府|部|委员会|署|行|局|厅|处|室|科|股|站', p_entity.entity_text)\
  1646. # or re.search('(采购|招标|投标|交易|代理|拍卖|咨询|顾问|管理)', p_entity.entity_text) == None:
  1647. # _role = 'tenderee'
  1648. # else:
  1649. # _role = "agency"
  1650. # _direct = _group.split("_")[1]
  1651. # _weight = _group.split("_")[2] if len(_group.split("_"))==3 else ""
  1652. # # _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1653. # # "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1654. # if _i_span == 0 and _direct == "left" and re.search('各.{,5}供应商|尊敬的供应商|业绩|拟招|(交易|采购|招标|建设)服务(单位|机构)|第[四五六七4567]|是否中标:否|序号:\d+,\w{,2}候选|(排名|排序|名次):([4-9]|\d{2,})', #135463002 拟招一家供应商为宜宾市第三人民医院、李庄同济医院院区提供消防维保服务
  1655. # list_spans[0]) == None: # 2021/12/22 修正错误中标召回 例子208668937
  1656. # _flag = True
  1657. # _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1658. # "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1659. # _prob_weight = 1.2 if _weight=='w1' else 1
  1660. # # print('_v_group:',_group, _v_group, p_entity.entity_text)
  1661. #
  1662. # if _i_span == 1 and _direct == "center" and _v_group.find(p_entity.entity_text) != -1 and re.search('以[^,。;]{10,30}为准', list_spans[1])==None:
  1663. # _flag = True
  1664. # _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1665. # "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1666. # _prob_weight = 1.2 if _weight == 'w1' else 1
  1667. # # print('_v_group:', _group, _v_group, p_entity.entity_text)
  1668. #
  1669. # if _i_span == 2 and _direct == "right":
  1670. # _flag = True
  1671. # _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1672. # "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1673. # _prob_weight = 1.2 if _weight == 'w1' else 1
  1674. # # print('_v_group:', _group, _v_group, p_entity.entity_text)
  1675. # # 得到结果
  1676. # if _flag:
  1677. # if _label in [2, 3, 4]:
  1678. # notfound_tenderer = False
  1679. # p_entity.label = _label
  1680. # p_entity.values[int(_label)] = on_value*_prob_weight + p_entity.values[int(_label)] / 10
  1681. # # log('正则召回实体: %s, %s, %s, %d, %.4f, %s'%(_group, _v_group, p_entity.entity_text, p_entity.label, p_entity.values[p_entity.label], list_spans[_i_span]))
  1682. # break
  1683. # if _i_span == 0 and re.search(self.condadate_left, list_spans[_i_span]):
  1684. # candidates.append(p_entity)
  1685. elif str(p_entity.label) in ['2', '3', '4']:
  1686. notfound_tenderer = False
  1687. # 其他金额通过正则召回可能是招标或中投标的金额
  1688. if p_entity.entity_type in ["money"]:
  1689. if str(p_entity.label) == "2":
  1690. for _sentence in list_sentence:
  1691. if _sentence.sentence_index == p_entity.sentence_index:
  1692. # _span = spanWindow(tokens=_sentence.tokens, begin_index=p_entity.begin_index,
  1693. # end_index=p_entity.end_index, size=10, center_include=True,
  1694. # word_flag=True, text=p_entity.entity_text)
  1695. _span = get_context(_sentence.sentence_text, p_entity.wordOffset_begin, p_entity.wordOffset_end, size=20, center_include=True) # 20241101 修复spanWindow方法取词错误, ['金额(万元:', '27000,存', '期:3个月,四、投标人资格:1.在嘉兴']
  1696. if re.search('(含|在|包括)(\d+)?$', _span[0]):
  1697. continue
  1698. if re.search(self.pattern_money_tenderee, _span[0]) is not None and re.search(
  1699. self.pattern_money_other, _span[0]) is None:
  1700. front_text = _span[0][re.search(self.pattern_money_tenderee, _span[0]).end():]
  1701. if re.search('\d[万亿]?元|元)?:?\d', front_text): # 当前金额与关键词中间有金额的过滤掉
  1702. break
  1703. p_entity.values[0] = 0.62 + p_entity.values[0] / 10
  1704. p_entity.label = 0
  1705. elif deposit_project:
  1706. if re.search(self.pattern_money_bank_tenderee,
  1707. _span[0]) is not None and re.search(
  1708. self.pattern_money_other, _span[0]) is None:
  1709. front_text = _span[0][re.search(self.pattern_money_bank_tenderee, _span[0]).end():]
  1710. if re.search('\d[万亿]?元|元)?:?\d', front_text): # 当前金额与关键词中间有金额的过滤掉
  1711. break
  1712. p_entity.values[0] = 0.6 + p_entity.values[0] / 10
  1713. p_entity.label = 0
  1714. elif re.search(self.pattern_money_bank_tenderee_right, _span[2]):
  1715. p_entity.values[0] = 0.55 + p_entity.values[0] / 10
  1716. p_entity.label = 0
  1717. elif (re.search('存款|总额度', _span[0]) or re.search('存[款放]|专项债资金', _span[2])):
  1718. front_text = _span[0][(re.search('存款|总额度', _span[0]) or re.search('存[款放]|专项债资金', _span[2])).end():]
  1719. if re.search('\d[万亿]?元|元)?:?\d', front_text): # 当前金额与关键词中间有金额的过滤掉
  1720. break
  1721. p_entity.values[0] = 0.55
  1722. p_entity.label = 0
  1723. # print('规则召回预算金额 4:', p_entity.entity_text, _span[0],p_entity.values[0])
  1724. if re.search(self.pattern_money_tenderer, _span[0]) is not None:
  1725. front_text = _span[0][re.search(self.pattern_money_tenderer, _span[0]).end():]
  1726. if re.search('\d[万亿]?元|元)?:?\d', front_text): # 当前金额与关键词中间有金额的过滤掉
  1727. break
  1728. if re.search(self.pattern_money_other, _span[0]) is not None:
  1729. if re.search(self.pattern_money_tenderer, _span[0]).span()[1] > \
  1730. re.search(self.pattern_money_other, _span[0]).span()[1]:
  1731. p_entity.values[1] = 0.6 + p_entity.values[1] / 10
  1732. p_entity.label = 1
  1733. else:
  1734. p_entity.values[1] = 0.6 + p_entity.values[1] / 10
  1735. p_entity.label = 1
  1736. if re.search(self.pattern_money_tenderer_whole,"".join(_span)) and re.search(self.pattern_money_tenderer_whole, _span[0])==None \
  1737. and re.search(self.pattern_money_tenderer_whole, _span[2])==None and re.search(self.pattern_money_other,_span[0])==None:
  1738. p_entity.values[1] = 0.6 + p_entity.values[1] / 10
  1739. p_entity.label = 1
  1740. elif re.search('(预算金额|最高(投标)?上?限[价额]?格?|招标控制价))?:?([\d.,]+万?元[,(]其中)?(第?[一二三四五0-9](标[段|包]|[分子]包):?[\d.,]+万?元,)*第?[一二三四五0-9](标[段|包]|[分子]包):?$'
  1741. , _sentence.sentence_text[:p_entity.wordOffset_begin]): # 处理几个标段金额相邻情况 例子:191705231
  1742. p_entity.values[0] = 0.6 + p_entity.values[0] / 10
  1743. p_entity.label = 0
  1744. if deposit_project and p_entity.label in [1,2]:
  1745. if req_scope and float(p_entity.entity_text)>1000000 and (p_entity.sentence_index>req_scope[0][0]\
  1746. or (p_entity.sentence_index==req_scope[0][0] and p_entity.wordOffset_begin>req_scope[0][1])) and (p_entity.sentence_index<req_scope[1][0]\
  1747. or (p_entity.sentence_index==req_scope[1][0] and p_entity.wordOffset_end<=req_scope[1][1])):
  1748. deposit_moneys.append(p_entity)
  1749. if deposit_moneys:
  1750. moneys = [float(p.entity_text) for p in deposit_moneys]
  1751. for p in deposit_moneys:
  1752. if float(p.entity_text)==max(moneys):
  1753. p.values[0] = 0.55
  1754. p.label = 0
  1755. else:
  1756. p.values[0] = 0.5
  1757. p.label = 0
  1758. if notfound_tenderer and len(set([ent.entity_text for ent in candidates])) == 1 and channel_dic['docchannel']['docchannel'] in ['中标信息', '候选人公示', '合同公告']:
  1759. for p_entity in candidates:
  1760. # print('只有一个候选人的作为中标人', p_entity.entity_text)
  1761. p_entity.label = 2
  1762. p_entity.values[2] = on_value
  1763. # 增加招标金额扩展,招标金额+连续的未识别金额,并且都可以匹配到标段信息,则将为识别的金额设置为招标金额
  1764. list_p = []
  1765. state = 0
  1766. for p_entity in list_entity:
  1767. for _sentence in list_sentence:
  1768. if _sentence.sentence_index == p_entity.sentence_index:
  1769. # _span = spanWindow(tokens=_sentence.tokens, begin_index=p_entity.begin_index,
  1770. # end_index=p_entity.end_index, size=20, center_include=True, word_flag=True,
  1771. # text=p_entity.entity_text)
  1772. _span = get_context(_sentence.sentence_text, p_entity.wordOffset_begin, p_entity.wordOffset_end,
  1773. size=30, center_include=True)
  1774. if state == 2:
  1775. for _p in list_p[1:]:
  1776. if _p.label == 2:
  1777. _p.values[0] = 0.5 + _p.values[0] / 10
  1778. _p.label = 0
  1779. state = 0
  1780. list_p = []
  1781. if state == 0:
  1782. if p_entity.entity_type in ["money"]:
  1783. if str(p_entity.label) == "0" and re.search(self.pattern_pack,
  1784. _span[0] + "-" + _span[2]) is not None:
  1785. state = 1
  1786. list_p.append(p_entity)
  1787. elif state == 1:
  1788. if p_entity.entity_type in ["money"]:
  1789. if str(p_entity.label) in ["0", "2"] and re.search(self.pattern_pack,
  1790. _span[0] + "-" + _span[
  1791. 2]) is not None and re.search(
  1792. self.pattern_money_other,
  1793. _span[0] + "-" + _span[2]) is None and p_entity.sentence_index == list_p[
  1794. 0].sentence_index:
  1795. list_p.append(p_entity)
  1796. else:
  1797. state = 2
  1798. if len(list_p) > 1:
  1799. for _p in list_p[1:]:
  1800. # print("==",_p.entity_text,_p.sentence_index,_p.label)
  1801. if _p.label == 2:
  1802. _p.values[0] = 0.5 + _p.values[0] / 10
  1803. _p.label = 0
  1804. state = 0
  1805. list_p = []
  1806. for p_entity in list_entity:
  1807. # 将属于集合中的不可能是中标人的标签置为无
  1808. if p_entity.entity_text in self.SET_NOT_TENDERER:
  1809. p_entity.label = 5
  1810. '''正则补充最后一句实体日期格式为招标或代理 2021/12/30'''
  1811. class RoleRuleFinalAdd():
  1812. def predict(self, list_articles,list_sentences, list_entitys, list_codenames):
  1813. '''
  1814. 最终规则召回角色
  1815. :param list_articles:
  1816. :param list_sentences:
  1817. :param list_entitys:
  1818. :param list_codenames:
  1819. :return:
  1820. '''
  1821. # text_end = list_articles[0].content.split('##attachment##')[0][-40:]
  1822. main_sentences = [sentence for sentence in list_sentences[0] if not sentence.in_attachment]
  1823. if len(list_sentences[0])>0 and list_sentences[0][-1].in_attachment:
  1824. main_sentences = list_sentences[0][-1:] + main_sentences[-2:]
  1825. if len(main_sentences)==0:
  1826. return 0
  1827. # end_tokens = []
  1828. for sentence in main_sentences[-5:][::-1]: # 402073799 最后五句由后往前,匹配文末角色,日期
  1829. # end_tokens.extend(sentence.tokens)
  1830. # text_end = "".join(end_tokens[-30:])
  1831. # text_end = "".join(end_tokens)
  1832. text_end = "".join(sentence.tokens)
  1833. text_end = re.sub(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", '', text_end) # 去除网址
  1834. text_end = re.sub(',?(招标办|招投标管理中心|国有资产管理处|采办共享中心|采购与招标管理办公室|附件\d*:[^附件,。]{5,100}\.(docx|doc|rar|xlsx|xls|jpg|pdf)|附件\d*:.{,100})', '', text_end)[-200:] # 处理 类似 285264698 传真:0512-62690315,苏州卫生职业技术学院,国有资产管理处,2022年11月24日, 这种情况
  1835. # sear_ent = re.search('[,。]([\u4e00-\u9fa5()()]{5,20}),?\s*[.]{2,4}年.{1,2}月.{1,2}日', text_end)
  1836. sear_ent = re.search('([,。;]|^)(?P<entity>[\u4e00-\u9fa5()()]{5,20}(,?[\u4e00-\u9fa5]{,8})?),?\s*(公告日期:)?[0-9零一二三四五六七八九十〇]{2,4}[年\-/][0-9零一二三四五六七八九十]{1,2}[月\-/][0-9零一二三四五六七八九十]{1,2}日?', text_end)
  1837. if sear_ent:
  1838. b, e = sear_ent.span()
  1839. if re.search('报价记录|竞价成交', text_end[max(b-10, 0):b] + text_end[e:]):
  1840. sear_ent = None
  1841. break
  1842. if sear_ent == None:
  1843. text_end = list_articles[0].content[-100:]
  1844. sear_ent = re.search(
  1845. '([,。;]|^)(?P<entity>[\u4e00-\u9fa5()()]{5,20}(,?[\u4e00-\u9fa5]{,8})?),?\s*(公告日期:)?[0-9零一二三四五六七八九十〇]{2,4}[年\-/][0-9零一二三四五六七八九十]{1,2}[月\-/][0-9零一二三四五六七八九十]{1,2}日?',
  1846. text_end)
  1847. if sear_ent:
  1848. b, e = sear_ent.span()
  1849. if re.search('报价记录|竞价成交', text_end[max(b-10, 0):b] + text_end[e:]):
  1850. sear_ent = None
  1851. sear_ent1 = re.search('((招标|采购)联系人)[,::][A-Za-z0-9_]*(?P<entity>[\u4e00-\u9fa5()()]{4,20})', list_articles[0].content[:5000])
  1852. sear_ent2 = re.search('[,:](户名|开户名称|发票抬头|单位名称|名称)[::](?P<entity>[\u4e00-\u9fa5()()]{5,20})[,。]', list_articles[0].content[:5000])
  1853. if sear_ent2 and sear_ent2.group(1) in ['单位名称','名称'] and re.search('投标报价|(中标|成交|结果|候选人|评标|开标)(公告|公示)', list_articles[0].content[:5000]): # 排除 341354479 这种作为招标人
  1854. sear_ent2 = None
  1855. sear_ent3 = re.search('(买家信息|所有权人|土地权属单位|报名咨询|[收送交]货地点)[,:](?P<entity>[\u4e00-\u9fa5()()]{5,20})[0-9\-]*[,。]', list_articles[0].content[:5000])
  1856. sear_ent4 = re.search('(发布(?:人|单位|机构|企业)|项目业主|所属公司|寻源单位)[,::][A-Za-z0-9_]*(?P<entity>[\u4e00-\u9fa5()()]{4,20})[,。]', list_articles[0].content[:5000])
  1857. sear_list = [sear_ent4 , sear_ent3 , sear_ent2 ,sear_ent1, sear_ent]
  1858. tenderee_notfound = True
  1859. agency_notfound = True
  1860. tenderee_list = []
  1861. agency_list = []
  1862. ents = []
  1863. for ent in list_entitys[0]:
  1864. if ent.entity_type in ['org', 'company']:
  1865. if ent.label == 0 and ent.values[ent.label]>0.55:
  1866. if '公共资源交易中心' in ent.entity_text: # 公共资源交易中心不算招标或代理,只算平台
  1867. # ent.label = 5
  1868. ent.values[ent.label] = 0.6 if ent.values[ent.label]>0.6 else 0.5 # 改为降低概率,不改类别,防止 382573066 明显招标人表达不提取
  1869. continue
  1870. tenderee_list.append(ent.entity_text)
  1871. tenderee_notfound = False
  1872. elif ent.label == 1 and ent.values[ent.label]>0.55:
  1873. agency_list.append(ent.entity_text)
  1874. agency_notfound = False
  1875. elif ent.label == 5:
  1876. if '公共资源交易中心' in ent.entity_text:
  1877. continue
  1878. ents.append(ent)
  1879. if sear_ent or sear_ent1 or sear_ent2 or sear_ent3 or sear_ent4:
  1880. for _sear_ent in [_sear for _sear in sear_list if _sear]:
  1881. ent_re = _sear_ent.group('entity')
  1882. ent_re = ent_re.replace(',', '').replace("(","(").replace(")",")")
  1883. if tenderee_notfound or agency_notfound:
  1884. n = 0
  1885. for i in range(len(ents) - 1, -1, -1):
  1886. if not ents[i].in_attachment:
  1887. n += 1
  1888. if n > 3 and _sear_ent==sear_ent: # 文章末尾角色加日期这种只找后三个实体
  1889. break
  1890. elif _sear_ent==sear_ent and ents[i].label != 5: # 后面有角色的实体的停止继续往前
  1891. break
  1892. if ents[i].entity_text == ent_re or (ents[i].entity_text in ent_re and re.search('(大学|中学|小学|幼儿园|医院)$', ents[i].entity_text)) or (ents[i].entity_text in ent_re and len(ents[i].entity_text)/len(ent_re)>0.6):
  1893. if agency_notfound and is_agency(ents[i].entity_text) and ents[i].entity_text not in tenderee_list:
  1894. ents[i].label = 1
  1895. ents[i].values[1] = 0.51 # 修改为比标题概率略高
  1896. agency_notfound = False
  1897. elif tenderee_notfound and not is_agency(ents[i].entity_text) and ents[i].entity_text not in agency_list:
  1898. ents[i].label = 0
  1899. ents[i].values[0] = 0.51 # 修改为比标题概率略高
  1900. tenderee_notfound = False
  1901. # log('正则最后补充实体: %s'%(ent_re))
  1902. break
  1903. if not tenderee_notfound:
  1904. break
  1905. # 招标人角色召回规则
  1906. class TendereeRuleRecall():
  1907. def __init__(self):
  1908. # self.tenderee_left = re.compile("(发布(人|单位|机构)|需求方(信息[,:])?(单位|公司)?名称|购买主体|收货单位|项目申请单位|发起组织|联系单位|"
  1909. # "询价(机构|企业)|联系(人|方式),?(单位|公司)(名称)?|联系(人|方式),名称)[::是为][^。;,]{,5}$")
  1910. # self.tenderee_left_1 = re.compile("采购商公司|询价单位|项目法人单位|项目法人|项目业主名称|申购单位|预算单位|预算单位名称|预算单位单位名称|买方单位|需求公司|寻源单位|项目业主|采购商|业主单位咨询电话|需用单位|采购工厂|征集单位")
  1911. self.tenderee_left_1 = re.compile("((?:采购商|项目法人|项目业主)(名称)?|(?:采购商|询价|项目法人|项目业主|申购|预算|买方|需求|寻源|需用|征集)(单位|公司)((?:单位|公司)?名称)?|询价企业|"
  1912. "业主单位咨询电话|购买主体|采购工厂|需求方(信息[,:])?(单位|公司)?名称|采购单位[\((].{1,6}[\))])[::是为][^。;,]{,2}$")
  1913. self.tenderee_left_2 = re.compile("(招标承办单位|交易人(?:名称)?|招标人代表|(采购|招标)联系人|交易单位|发起(单位|组织)|收货单位|使用方|买家信息)[::是为][^。;,]{,2}$")
  1914. self.tenderee_left_3 = re.compile("[本我](?:公司|单位)[\(\[(【]?$")
  1915. # self.tenderee_left_4 = re.compile("(采购机构|组织机构|组织方|执行单位|采购组织单位|招标组织单位|招标组织部门|采购执行方|采购执行单位|询价执行组织|组织单位|联系单位|联系部门)[::是为][^。;,]{,2}$")
  1916. self.tenderee_left_4 = re.compile("(采购机构|(?:采购|招标|询价)?(组织|执行)(机构|方|单位|部门|组织)|联系(单位|部门)|联系(人|方式),?(单位|公司)(名称)?|联系(人|方式),名称)[::是为][^。;,]{,2}$")
  1917. self.tenderee_left_5 = re.compile("(撰写单位|发布(?:人|单位|机构|公司|部门|企业))[^。;,]{,2}$")
  1918. self.tenderee_right = re.compile("^[^。;::]{,5}[((](以?下简?称)?,?[,\"“]*[我本][\u4e00-\u9fa5]{1,2}[,\"”]*[))]|"
  1919. "^[\((][^。;::\))]{,5}称(?:招标|采购)(?:人|单位)|"
  1920. "^[^。;::]{,10}[对就][^。;,]+,?[^。;,]{,20}进行[^。;,]*(采购|询比?价|遴选|招投?标|征集)|"
  1921. "^[^。;::]{,10}关于[^。;,]+,?[^。;,]{,20}的[^。;,]{,20}公告|"
  1922. "^[^。;,::]{,10}的[^。;,]+,?[^。;,]{,20}正在[^。;,]{,5}进行|"
  1923. "^[^。;,::]{,10}的[^。;,]+,?[^。,;]{,20}已?[^。;,]{,20}批准|"
  1924. "^[^。;,::]{,15}(选定|选取|征集|遴选)[^。;,]{,20}(供应商|(代理|咨询|设计)[^。;,]{,5}机构|代理人)")
  1925. self.tenderee_right2 = re.compile("^[^。;,::]{,10}(招标办|采购部|办事处|采购小?组)")
  1926. self.tenderee_right3 = re.compile("^[^。;,::]{,10}(对|就|关于|的)(?P<project>[^。;,?!::]{4,40})")
  1927. # 公告主语判断规则
  1928. self.subject = re.compile("[我本][院校局]")
  1929. # 未识别实体召回正则
  1930. self.unrecognized1 = re.compile("(?P<tenderee_left>((遴选|采购|招标|竞价|议价|比选|委托|询比?价|评选|谈判|邀标|邀请|洽谈|约谈)" \
  1931. "(人|商|公司|单位|组织|用户|业主|主体|方|部门))" \
  1932. "(信息[,:]?)?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|:|:)+)(?P<unrecognized>[^,。::;]+)[,。;::]")
  1933. self.unrecognized2 = re.compile("(?P<tenderee_left>((项目|需求|最终|建设|业主|转让|招租|甲|议标|合同主体|挂牌|出租|出让|选取|抽取|抽选|出售|标卖|比价|处置)" \
  1934. "(人|公司|单位|组织|用户|业主|主体|方|部门)|文章来源|委托机构|产权所有人|需求?方|买方|业主|(业主|采购人|招标人)联系方式[,:]公司名称:|权属人|甲方当事人|询价书企业|比选发起人|项目单位[,:]单位名称|结算单位)"\
  1935. "[))]?(信息[,:])?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|:|:)+)(?P<unrecognized>[^,。::;]+)[,。;::]")
  1936. # 未识别实体尾部判断
  1937. # self.unrecognized_end1 = re.compile(
  1938. # "^[\u4e00-\u9fa5]{2,}?(?:公司|医院|学校|学院|大学|中学|小学|幼儿园|政府|指挥部|办公室|项目部|业主大会|监狱|教育局|委员会|研究所|招标办|采购部|办事处|水利局|公墓|中心|联合社|合作社)")
  1939. # self.unrecognized_end2 = re.compile("^[\u4e00-\u9fa5]{4,}(?:署|局|厅|处|室|科|部|站|所|股|行|园)")
  1940. def predict(self, list_articles,list_sentences, list_entitys, list_codenames):
  1941. self.get_tenderee = False
  1942. ents = []
  1943. list_name = []
  1944. agency_set = set()
  1945. for ent in list_entitys[0]:
  1946. if ent.entity_type == 'name':
  1947. list_name.append(ent.entity_text)
  1948. if ent.entity_type in ['org', 'company']:
  1949. if ent.label == 0 and ent.values[ent.label]>=0.5:
  1950. self.get_tenderee = True
  1951. break
  1952. elif ent.label == 1:
  1953. if ent.values[ent.label]>0.5:
  1954. agency_set.add(ent.entity_text)
  1955. elif ent.label == 5:
  1956. if len(ent.entity_text)>=4:
  1957. ents.append(ent)
  1958. if not self.get_tenderee:
  1959. self.entity_context_rule(ents,list_name,list_sentences,list(agency_set))
  1960. if not self.get_tenderee:
  1961. self.subject_rule(ents,list_articles,list_sentences)
  1962. # if not self.get_tenderee:
  1963. # self.unrecognized_entity_rule(self.unrecognized1,list_sentences,list_entitys,0.55)
  1964. # if not self.get_tenderee:
  1965. # self.unrecognized_entity_rule(self.unrecognized2,list_sentences,list_entitys,0.5)
  1966. #entity上下文正则判断
  1967. def entity_context_rule(self,entitys,list_name,list_sentences,list_agency):
  1968. list_sentences[0].sort(key=lambda x:x.sentence_index)
  1969. entity_data = []
  1970. for ent in entitys:
  1971. _sentence = list_sentences[0][ent.sentence_index]
  1972. _span = spanWindow(tokens=_sentence.tokens, begin_index=ent.begin_index,
  1973. end_index=ent.end_index, size=40, center_include=True,
  1974. word_flag=True, use_text=True,
  1975. text=re.sub(")", ")", re.sub("(", "(", ent.entity_text)))
  1976. entity_data.append((ent,_span))
  1977. if not self.get_tenderee:
  1978. for _data in entity_data:
  1979. ent = _data[0]
  1980. _span = _data[1]
  1981. if re.search(self.tenderee_left_1,_span[0]):
  1982. ent.label = 0
  1983. ent.values[0] = 0.5 + ent.values[0] / 10
  1984. self.get_tenderee = True
  1985. if not self.get_tenderee:
  1986. for _data in entity_data:
  1987. ent = _data[0]
  1988. _span = _data[1]
  1989. if re.search(self.tenderee_left_2,_span[0]):
  1990. ent.label = 0
  1991. ent.values[0] = 0.5 + ent.values[0] / 10
  1992. self.get_tenderee = True
  1993. if not self.get_tenderee:
  1994. for _data in entity_data:
  1995. ent = _data[0]
  1996. _span = _data[1]
  1997. if re.search(self.tenderee_left_3,_span[0]):
  1998. ent.label = 0
  1999. ent.values[0] = 0.5 + ent.values[0] / 10
  2000. self.get_tenderee = True
  2001. if not self.get_tenderee:
  2002. for _data in entity_data:
  2003. ent = _data[0]
  2004. _span = _data[1]
  2005. if re.search(self.tenderee_left_4,_span[0]):
  2006. if len(list_agency)>0:
  2007. _same = False
  2008. for agency in list_agency:
  2009. if ent.entity_text in agency or agency in ent.entity_text:
  2010. _same = True
  2011. break
  2012. if not _same:
  2013. ent.label = 0
  2014. ent.values[0] = 0.5 + ent.values[0] / 10
  2015. self.get_tenderee = True
  2016. else:
  2017. if re.search('医院|学校|大学|中学|小学|幼儿园|政府|部|委员会|署|行|局|厅|处|室|科|股|站', ent.entity_text
  2018. ) or not re.search('(采购|招标|投标|交易|代理|拍卖|咨询|顾问|管理)', ent.entity_text) or re.search("自行.?采购",list_sentences[0][ent.sentence_index].sentence_text):
  2019. ent.label = 0
  2020. ent.values[0] = 0.5 + ent.values[0] / 10
  2021. self.get_tenderee = True
  2022. if not self.get_tenderee:
  2023. for _data in entity_data:
  2024. ent = _data[0]
  2025. _span = _data[1]
  2026. if re.search(self.tenderee_left_5,_span[0]):
  2027. if len(list_agency)>0:
  2028. _same = False
  2029. for agency in list_agency:
  2030. if ent.entity_text in agency or agency in ent.entity_text:
  2031. _same = True
  2032. break
  2033. if not _same:
  2034. ent.label = 0
  2035. ent.values[0] = 0.5 + ent.values[0] / 10
  2036. self.get_tenderee = True
  2037. else:
  2038. if re.search('医院|学校|大学|中学|小学|幼儿园|政府|部|委员会|署|行|局|厅|处|室|科|股|站', ent.entity_text
  2039. ) or not re.search('(采购|招标|投标|交易|代理|拍卖|咨询|顾问|管理)', ent.entity_text):
  2040. ent.label = 0
  2041. ent.values[0] = 0.5 + ent.values[0] / 10
  2042. self.get_tenderee = True
  2043. if not self.get_tenderee:
  2044. for _data in entity_data:
  2045. ent = _data[0]
  2046. _span = _data[1]
  2047. if re.search(self.tenderee_right, _span[2]):
  2048. ent.label = 0
  2049. ent.values[0] = 0.5 + ent.values[0] / 10
  2050. self.get_tenderee = True
  2051. if not self.get_tenderee:
  2052. for _data in entity_data:
  2053. ent = _data[0]
  2054. _span = _data[1]
  2055. if re.search(self.tenderee_right2, _span[2]):
  2056. ent.label = 0
  2057. ent.values[0] = 0.5 + ent.values[0] / 10
  2058. self.get_tenderee = True
  2059. if not self.get_tenderee:
  2060. if list_name:
  2061. for _data in entity_data:
  2062. ent = _data[0]
  2063. _span = _data[1]
  2064. pj_name = re.search(self.tenderee_right3, _span[2])
  2065. if pj_name:
  2066. pj_name = pj_name.groupdict()["project"]
  2067. for _name in list_name:
  2068. if _name in pj_name:
  2069. ent.label = 0
  2070. ent.values[0] = 0.5
  2071. self.get_tenderee = True
  2072. break
  2073. # for _data in entity_data:
  2074. # ent = _data[0]
  2075. # _span = _data[1]
  2076. # if re.search(self.tenderee_left,_span[0]):
  2077. # ent.label = 0
  2078. # ent.values[0] = 0.5 + ent.values[0] / 10
  2079. # self.get_tenderee = True
  2080. # elif re.search(self.tenderee_right,_span[2]):
  2081. # ent.label = 0
  2082. # ent.values[0] = 0.5 + ent.values[0] / 10
  2083. # self.get_tenderee = True
  2084. # elif re.search(self.tenderee_right2, _span[2]):
  2085. # ent.label = 0
  2086. # ent.values[0] = 0.5 + ent.values[0] / 10
  2087. # self.get_tenderee = True
  2088. # elif list_name:
  2089. # pj_name = re.search(self.tenderee_right3, _span[2])
  2090. # if pj_name:
  2091. # pj_name = pj_name.groupdict()["project"]
  2092. # for _name in list_name:
  2093. # if _name in pj_name:
  2094. # ent.label = 0
  2095. # ent.values[0] = 0.5
  2096. # self.get_tenderee = True
  2097. # break
  2098. # 公告主语判断
  2099. def subject_rule(self, entitys,list_articles,list_sentences):
  2100. content = list_articles[0].content.split('##attachment##')[0]
  2101. if re.search(self.subject,content):
  2102. _subject = re.search(self.subject,content).group()
  2103. for ent in entitys:
  2104. if re.search("院",_subject) and re.search("医院|学院",ent.entity_text):
  2105. ent.label = 0
  2106. ent.values[0] = 0.5 + ent.values[0] / 10
  2107. self.get_tenderee = True
  2108. elif re.search("校",_subject) and re.search("学校|学院|大学|高中|初中|中学|小学",ent.entity_text):
  2109. ent.label = 0
  2110. ent.values[0] = 0.5 + ent.values[0] / 10
  2111. self.get_tenderee = True
  2112. elif re.search("局", _subject) and re.search("局", ent.entity_text):
  2113. _sentence = list_sentences[0][ent.sentence_index]
  2114. _span = spanWindow(tokens=_sentence.tokens, begin_index=ent.begin_index,
  2115. end_index=ent.end_index, size=20, center_include=True,
  2116. word_flag=True, use_text=True,
  2117. text=re.sub(")", ")", re.sub("(", "(", ent.entity_text)))
  2118. if not re.search("监督|投诉",_span[0][-10:]):
  2119. ent.label = 0
  2120. ent.values[0] = 0.5 + ent.values[0] / 10
  2121. self.get_tenderee = True
  2122. # 正则召回未识别实体
  2123. # def unrecognized_entity_rule(self,pattern,list_sentences,list_entitys,on_value=0.5):
  2124. # list_sentence = list_sentences[0]
  2125. # for in_attachment in [False,True]:
  2126. # for sentence in [sentence for sentence in list_sentence if sentence.in_attachment==in_attachment]:
  2127. # sentence_text = sentence.sentence_text
  2128. # tokens = sentence.tokens
  2129. # doc_id = sentence.doc_id
  2130. # in_attachment = sentence.in_attachment
  2131. # list_tokenbegin = []
  2132. # begin = 0
  2133. # for i in range(0, len(tokens)):
  2134. # list_tokenbegin.append(begin)
  2135. # begin += len(str(tokens[i]))
  2136. # list_tokenbegin.append(begin + 1)
  2137. # for _match in re.finditer(pattern,sentence_text):
  2138. # _groupdict = _match.groupdict()
  2139. # _match_text = _match.group()
  2140. # _unrecognized_text = _groupdict["unrecognized"]
  2141. # _unrecognized = re.search(self.unrecognized_end1,_unrecognized_text)
  2142. # if not _unrecognized:
  2143. # _unrecognized = re.search(self.unrecognized_end2, _unrecognized_text)
  2144. # if _unrecognized:
  2145. # _unrecognized = _unrecognized.group()
  2146. # else:
  2147. # continue
  2148. # # print(_unrecognized)
  2149. # if re.search("某|乙方|代理",_unrecognized) or len(_unrecognized)>15:
  2150. # continue
  2151. # begin_index_temp = _match.start()+len(_groupdict['tenderee_left'])
  2152. # for j in range(len(list_tokenbegin)):
  2153. # if list_tokenbegin[j] == begin_index_temp:
  2154. # begin_index = j
  2155. # break
  2156. # elif list_tokenbegin[j] > begin_index_temp:
  2157. # begin_index = j - 1
  2158. # break
  2159. # index = begin_index_temp + len(_unrecognized)
  2160. # end_index_temp = index
  2161. # for j in range(begin_index, len(list_tokenbegin)):
  2162. # if list_tokenbegin[j] >= index:
  2163. # end_index = j - 1
  2164. # break
  2165. # entity_id = "%s_%d_%d_%d" % (doc_id, sentence.sentence_index, begin_index, end_index)
  2166. # entity_text = _unrecognized
  2167. # new_entity = Entity(doc_id, entity_id, entity_text, 'company', sentence.sentence_index, begin_index, end_index,
  2168. # begin_index_temp, end_index_temp, in_attachment=in_attachment)
  2169. # new_entity.label = 0
  2170. # new_entity.values = [on_value,0,0,0,0,0]
  2171. # list_entitys[0].append(new_entity)
  2172. # self.get_tenderee = True
  2173. # if self.get_tenderee:
  2174. # list_entitys[0] = sorted(list_entitys[0], key=lambda x: (x.sentence_index, x.begin_index))
  2175. # break
  2176. class RoleGrade():
  2177. def __init__(self):
  2178. self.tenderee_left_9 = "(?P<tenderee_left_9>(招标|采购|遴选|寻源|竞价|议价|比选|询比?价|比价|评选|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选)(人|方|单位))"
  2179. self.tenderee_center_8 = "(?P<tenderee_center_8>受.{5,20}委托)"
  2180. self.tenderee_left_8 = "(?P<tenderee_left_8>(尊敬的供应商|项目法人|(需求|最终|发包|征集|甲|转让|出租|处置)(人|方|单位|组织|用户|业主|主体|部门|公司)))"
  2181. self.tenderee_left_6 = "(?P<tenderee_left_6>(业主|建设|委托)(人|方|单位|组织|用户|业主|主体|部门|公司|企业)|业主|买方)"
  2182. self.tenderee_left_5 = "(?P<tenderee_left_5>(发布)(人|方|单位|组织|用户|业主|主体|部门|公司|企业)|买方|发布机构)"
  2183. self.agency_left_9 = "(?P<agency_left_9>代理)"
  2184. self.winTenderer_left_9 = "(?P<winTenderer_left_9>(中标|中选|中价|成交|竞得)|第[1一](名|候选)|排[名序]:1|名次:1)"
  2185. self.winTenderer_left_8 = "(?P<winTenderer_left_8>(入选供应商|供货商|乙方|最[终后]选[择取]))" # 229435497 最后选择西平,县中原彩印有限公司,作为此项目中标供应商,
  2186. self.winTenderer_left_6 = "(?P<winTenderer_left_6>(入围|承[接建包修做制担租销]))"
  2187. self.winTenderer_right_9 = "(?P<winTenderer_right_9>^(为(中标|成交|中选)(人|单位|供应商|公司)|以\d+[\d.,]+万?元中标))"
  2188. self.secondTenderer_left_9 = "(?P<secondTenderer_left_9>(第[二2](中标|中选|中价|成交)?候选(人|单位|供应商|公司)|第[二2](名|候选)|排[名序]:2|名次:2))"
  2189. self.thirdTenderer_left_9 = "(?P<thirdTenderer_left_9>(第[三3](中标|中选|中价|成交)?候选(人|单位|供应商|公司)|第[三3](名|候选)|排[名序]:3|名次:3))"
  2190. self.pattern_list = [self.tenderee_left_9,self.tenderee_center_8, self.tenderee_left_8,self.tenderee_left_6,self.tenderee_left_5,self.agency_left_9,
  2191. self.winTenderer_left_9,self.winTenderer_left_8, self.winTenderer_right_9, self.winTenderer_left_6, self.secondTenderer_left_9, self.thirdTenderer_left_9] # 概率要由高到低 274941849
  2192. def predict(self, list_sentences, list_entitys, original_docchannel, span=15, min_prob=0.7):
  2193. '''
  2194. 根据规则给角色分配不同等级概率;分三级:0.9-1,0.8-0.9,0.7-0.8;附件0.7-0.8,0.6-0.7,0.5-0.6
  2195. 修改概率小于0.6的且在大数据代理集合里面的招标人为代理人
  2196. :param list_articles:
  2197. :param list_sentences:
  2198. :param list_entitys:
  2199. :param codeName:
  2200. :return:
  2201. '''
  2202. sentences = sorted(list_sentences[0], key=lambda x:x.sentence_index)
  2203. role2id = {"tenderee": 0, "agency": 1, "winTenderer": 2, "secondTenderer": 3, "thirdTenderer": 4}
  2204. org_winner = []
  2205. company_winner = []
  2206. org_tenderee = []
  2207. agency_l = []
  2208. agency_like_tenderee = [] # 类似招标人的代理人实体列表
  2209. low_prob_agency = []
  2210. low_prob_tenderee = []
  2211. low_prob_winner = []
  2212. all_tenderee_agency = []
  2213. for entity in list_entitys[0]:
  2214. if entity.entity_type in ['org', 'company'] and entity.label in [0, 1, 2, 3, 4] and entity.values[entity.label]> min_prob:
  2215. text = sentences[entity.sentence_index].sentence_text
  2216. in_att = sentences[entity.sentence_index].in_attachment
  2217. pre_prob = entity.values[entity.label] # 模型预测角色概率
  2218. b = entity.wordOffset_begin
  2219. e = entity.wordOffset_end
  2220. not_found = 1
  2221. if re.search('(乙方:甲方:|甲方:乙方:)$', text[max(0, b-span):b]):
  2222. entity.label = 0 if entity.entity_type == 'org' else 5 # 修复 290777022 乙方:甲方: 重庆机场集团有限公司 错分为中标
  2223. entity.values[entity.label] = 0.55
  2224. continue
  2225. elif re.search('(采购|招标)人(?或其?(采购|招标)?代理机构)?', text[max(0, b-span-2):b]): # 修复 275206588 招标人或其招标代理机构:(盖章)
  2226. entity.label = 1 if is_agency(entity.entity_text) else 0
  2227. entity.values[entity.label] = 0.8
  2228. continue
  2229. elif re.search('(采购|招标|询比?价|遴选|寻源|比选)机构[是为:]+', text[max(0, b-span):b]) and not is_agency(entity.entity_text):
  2230. agency_like_tenderee.append(entity)
  2231. for pattern in self.pattern_list:
  2232. if 'left' in pattern:
  2233. context = text[max(0, b-span):b]
  2234. elif 'right' in pattern:
  2235. context = text[e:e+span]
  2236. elif 'center' in pattern:
  2237. context = text[max(0, b-span):e+span]
  2238. else:
  2239. print('规则错误', pattern)
  2240. ser = re.search(pattern, context)
  2241. if ser:
  2242. groupdict = pattern.split('>')[0].replace('(?P<', '')
  2243. _role, _direct, _prob = groupdict.split('_')
  2244. _label = role2id.get(_role)
  2245. if _label != entity.label:
  2246. continue
  2247. _prob = int(_prob)*0.1
  2248. # print('规则修改角色概率前:', entity.entity_text, entity.label, entity.values)
  2249. if in_att:
  2250. _prob = _prob - 0.1 # 0.2
  2251. if pre_prob < _prob: # 如果模型预测概率小于关键词概率
  2252. _prob = 0.65
  2253. if len(entity.entity_text) < 6 and re.search('大学|医院', entity.entity_text)==None: # 如果实体名称小于6个字,概率再降0.05
  2254. _prob -= 0.05
  2255. if re.search('(地址|联系方式):$', context): # 地址结尾的概率 概率降低
  2256. _prob -= 0.05
  2257. entity.values[_label] = _prob + entity.values[_label] / 20
  2258. not_found = 0
  2259. # print('规则修改角色概率后:', entity.entity_text, entity.label, entity.values)
  2260. break
  2261. if not_found and entity.values[entity.label]> min_prob:
  2262. _prob = min_prob - 0.1 if in_att else min_prob
  2263. entity.values[entity.label] = _prob + entity.values[entity.label] / 20
  2264. # print('找不到规则修改角色概率:', entity.entity_text, entity.label, entity.values)
  2265. if entity.label == 2 and entity.values[entity.label]> min_prob:
  2266. if entity.entity_type == 'org':
  2267. org_winner.append(entity)
  2268. elif entity.entity_type == 'company':
  2269. company_winner.append(entity) # 保存中标人实体
  2270. if entity.label == 0 and entity.values[entity.label]> min_prob:
  2271. org_tenderee.append(entity.entity_text) # 保存所有招标人名称
  2272. elif entity.label == 1 and entity.values[entity.label]> min_prob:
  2273. agency_l.append(entity.entity_text)
  2274. # if entity.entity_type in ['org', 'company'] and entity.label == 0 and entity.entity_text in agency_set and entity.values[entity.label]<0.6: # 修改概率小于0.6的且在大数据代理集合里面的招标人为代理人
  2275. # # log('修改概率小于0.6的且在大数据代理集合里面的招标人为代理人%s:'%entity.entity_text)
  2276. # entity.label = 1
  2277. # entity.values[entity.label] = 0.5
  2278. elif entity.entity_type in ['org', 'company'] and entity.label in [1, 0] and 0.5<=entity.values[entity.label]<0.6:
  2279. if entity.label == 1:
  2280. low_prob_agency.append(entity)
  2281. else:
  2282. low_prob_tenderee.append(entity)
  2283. elif entity.entity_type in ['org', 'company'] and entity.label == 2 and 0.5<=entity.values[entity.label]<0.6:
  2284. low_prob_winner.append(entity)
  2285. if entity.entity_type in ['org', 'company'] and entity.label in [1, 0] and 0.6<entity.values[entity.label]: # 由0.5调为0.6,避免367217504 同时为低概率招标、中标被改
  2286. all_tenderee_agency.append(entity.entity_text)
  2287. if org_tenderee == [] and agency_like_tenderee:
  2288. for entity in agency_like_tenderee:
  2289. entity.label = 0
  2290. entity.values[entity.label] = 0.6
  2291. for entity in low_prob_agency: # 如果低概率代理在招标人列表,改为招标人
  2292. if entity.entity_text in org_tenderee:
  2293. entity.label = 0
  2294. entity.values[entity.label] = 0.6
  2295. for entity in low_prob_tenderee:
  2296. if entity.entity_text in agency_l:
  2297. entity.label = 1
  2298. entity.values[entity.label] = 0.6
  2299. for entity in low_prob_winner: # 如果低概率中标人在招标或代理列表,改为非角色
  2300. if entity.entity_text in all_tenderee_agency:
  2301. entity.label = 5
  2302. # elif entity.in_attachment: # 附件低概率中标角色不要 避免:516109391 桂林银行崇左宁明支行,宁明县城中镇兴宁大道中70号,预测为中标 20241126 注释掉,558294326 附件单个候选人漏提取
  2303. # entity.label = 5
  2304. if org_winner != []:
  2305. flag = 0
  2306. if org_tenderee != []:
  2307. for ent in org_winner:
  2308. if ent.entity_text in org_tenderee:
  2309. # log('如果org中标人同时为招标人角色,降低中标概率:%s, %s' % (ent.entity_text, ent.label))
  2310. ent.values[2] = 0.6
  2311. flag = 1
  2312. # if flag == 0 and company_winner != []: # 2024/04/18 注释掉 避免提取不到 273351465 供应商(乙方:湖南省第二测绘院
  2313. # for ent in org_winner:
  2314. # if ent.label == 2 and ent.values[2] > 0.6:
  2315. # # log('如果同时包含org和company中标人,降低org中标人概率为0.6:%s, %s' % (ent.entity_text, ent.values[2]))
  2316. # ent.values[2] = 0.6
  2317. class MoneyGrade():
  2318. def __init__(self):
  2319. self.tenderee_money_left_9 = "(?P<tenderee_left_9>最高(投标)?限价)|控制价|拦标价"
  2320. self.tenderee_money_left_8 = "(?P<tenderee_left_8>预算|限价|起始|起拍|底价|标底)"
  2321. self.tenderer_money_left_9 = "(?P<tenderer_left_9>(中标|成交|合同|总报价))"
  2322. self.tenderer_money_left_8 = "(?P<tenderer_left_8>(投标|总价))"
  2323. self.pattern_list = [self.tenderee_money_left_8, self.tenderer_money_left_8, self.tenderee_money_left_9, self.tenderer_money_left_9]
  2324. def predict(self, list_sentences, list_entitys, span=10, min_prob=0.7):
  2325. sentences = sorted(list_sentences[0], key=lambda x:x.sentence_index)
  2326. role2id = {"tenderee": 0, "tenderer": 1}
  2327. for entity in list_entitys[0]:
  2328. if entity.entity_type in ['money'] and entity.label in [0, 1] and entity.values[entity.label]> 0.6:
  2329. text = sentences[entity.sentence_index].sentence_text
  2330. in_att = sentences[entity.sentence_index].in_attachment
  2331. b = entity.wordOffset_begin
  2332. e = entity.wordOffset_end
  2333. context = text[max(0, b - span):b]
  2334. not_found = 1
  2335. for pattern in self.pattern_list:
  2336. ser = re.search(pattern, context)
  2337. if ser:
  2338. groupdict = pattern.split('>')[0].replace('(?P<', '')
  2339. _role, _direct, _prob = groupdict.split('_')
  2340. if re.search('单价', context[-4:]) or re.search('(最低|风险)控制价', context) or entity.notes == '总投资':# or float(entity.entity_text)<100:
  2341. _prob = 6
  2342. _label = role2id.get(_role)
  2343. if _label != entity.label:
  2344. continue
  2345. _prob = int(_prob) * 0.1
  2346. # print('规则修改金额概率前:', entity.entity_text, entity.label, entity.values)
  2347. if in_att:
  2348. _prob = max(0.5, _prob - 0.2)
  2349. entity.values[_label] = _prob + entity.values[_label] / 20
  2350. not_found = 0
  2351. # print('规则修改金额概率后:', entity.entity_text, entity.label, entity.values)
  2352. break
  2353. if not_found and entity.values[entity.label] > min_prob:
  2354. if re.search('单价', context[-4:]) or re.search('(最低|风险)控制价', context) or float(entity.entity_text)<100:
  2355. _prob = 0.6
  2356. elif in_att:
  2357. _prob = max(0.5, min_prob - 0.1)
  2358. else:
  2359. _prob = min_prob
  2360. # _prob = min_prob - 0.1 if in_att else min_prob
  2361. entity.values[entity.label] = _prob + entity.values[entity.label] / 20
  2362. # print('找不到规则修改金额概率:', entity.entity_text, entity.label, entity.values)
  2363. # if entity.entity_type in ['money'] and entity.label in [0, 1] and 0.5<=entity.values[entity.label]<0.75 and float(entity.entity_text)<100: # 20241011 低概率小金额改为其他金额 # 20241128 小金额可能为单价,放单价存放
  2364. # entity.label = 2
  2365. # 时间类别
  2366. class TimePredictor():
  2367. def __init__(self,config=None):
  2368. self.sess = tf.Session(graph=tf.Graph(),config=config)
  2369. self.inputs_code = None
  2370. self.outputs_code = None
  2371. self.input_shape = (2,40,128)
  2372. self.load_model()
  2373. def load_model(self):
  2374. model_path = os.path.dirname(__file__)+'/timesplit_model'
  2375. if self.inputs_code is None:
  2376. log("get model of time")
  2377. with self.sess.as_default():
  2378. with self.sess.graph.as_default():
  2379. meta_graph_def = tf.saved_model.loader.load(self.sess, tags=["serve"], export_dir=model_path)
  2380. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  2381. signature_def = meta_graph_def.signature_def
  2382. self.inputs_code = []
  2383. self.inputs_code.append(
  2384. self.sess.graph.get_tensor_by_name(signature_def[signature_key].inputs["input0"].name))
  2385. self.inputs_code.append(
  2386. self.sess.graph.get_tensor_by_name(signature_def[signature_key].inputs["input1"].name))
  2387. self.outputs_code = self.sess.graph.get_tensor_by_name(signature_def[signature_key].outputs["outputs"].name)
  2388. return self.inputs_code, self.outputs_code
  2389. else:
  2390. return self.inputs_code, self.outputs_code
  2391. def search_time_data(self,list_sentences,list_entitys):
  2392. data_x = []
  2393. points_entitys = []
  2394. for list_sentence, list_entity in zip(list_sentences, list_entitys):
  2395. p_entitys = 0
  2396. p_sentences = 0
  2397. list_sentence.sort(key=lambda x: x.sentence_index)
  2398. while(p_entitys<len(list_entity)):
  2399. entity = list_entity[p_entitys]
  2400. if entity.entity_type in ['time']:
  2401. while(p_sentences<len(list_sentence)):
  2402. sentence = list_sentence[p_sentences]
  2403. if entity.doc_id == sentence.doc_id and entity.sentence_index == sentence.sentence_index:
  2404. # left = sentence.sentence_text[max(0,entity.wordOffset_begin-self.input_shape[1]):entity.wordOffset_begin]
  2405. # right = sentence.sentence_text[entity.wordOffset_end:entity.wordOffset_end+self.input_shape[1]]
  2406. s = spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=self.input_shape[1])
  2407. left = s[0]
  2408. right = s[1]
  2409. context = [left, right]
  2410. x = self.embedding_words(context, shape=self.input_shape)
  2411. data_x.append(x)
  2412. points_entitys.append(entity)
  2413. break
  2414. p_sentences += 1
  2415. p_entitys += 1
  2416. if len(points_entitys)==0:
  2417. return None
  2418. data_x = np.transpose(np.array(data_x), (1, 0, 2, 3))
  2419. return [data_x, points_entitys]
  2420. def embedding_words(self, datas, shape):
  2421. '''
  2422. @summary:查找词汇对应的词向量
  2423. @param:
  2424. datas:词汇的list
  2425. shape:结果的shape
  2426. @return: array,返回对应shape的词嵌入
  2427. '''
  2428. model_w2v = getModel_w2v()
  2429. embed = np.zeros(shape)
  2430. length = shape[1]
  2431. out_index = 0
  2432. for data in datas:
  2433. index = 0
  2434. for item in data:
  2435. item_not_space = re.sub("\s*", "", item)
  2436. if index >= length:
  2437. break
  2438. if item_not_space in model_w2v.vocab:
  2439. embed[out_index][index] = model_w2v[item_not_space]
  2440. index += 1
  2441. else:
  2442. embed[out_index][index] = model_w2v['unk']
  2443. index += 1
  2444. out_index += 1
  2445. return embed
  2446. def predict(self, list_sentences,list_entitys):
  2447. datas = self.search_time_data(list_sentences, list_entitys)
  2448. if datas is None:
  2449. return
  2450. points_entitys = datas[1]
  2451. with self.sess.as_default():
  2452. predict_y = limitRun(self.sess,[self.outputs_code], feed_dict={self.inputs_code[0]:datas[0][0]
  2453. ,self.inputs_code[1]:datas[0][1]})[0]
  2454. for i in range(len(predict_y)):
  2455. entity = points_entitys[i]
  2456. label = np.argmax(predict_y[i])
  2457. values = []
  2458. for item in predict_y[i]:
  2459. values.append(item)
  2460. if label != 0:
  2461. if not timeFormat(entity.entity_text):
  2462. label = 0
  2463. values[0] = 0.5
  2464. entity.set_Role(label, values)
  2465. # 产品字段提取
  2466. class ProductPredictor():
  2467. def __init__(self,config=None):
  2468. vocabpath = os.path.dirname(__file__) + "/codename_vocab.pk"
  2469. self.vocab = load(vocabpath)
  2470. self.word2index = dict((w, i) for i, w in enumerate(np.array(self.vocab)))
  2471. self.sess = tf.Session(graph=tf.Graph(),config=config)
  2472. self.load_model()
  2473. def load_model(self):
  2474. # model_path = os.path.dirname(__file__)+'/product_savedmodel/product.pb'
  2475. model_path = os.path.dirname(__file__)+'/product_savedmodel/productAndfailreason.pb'
  2476. with self.sess.as_default():
  2477. with self.sess.graph.as_default():
  2478. output_graph_def = tf.GraphDef()
  2479. with open(model_path, 'rb') as f:
  2480. output_graph_def.ParseFromString(f.read())
  2481. tf.import_graph_def(output_graph_def, name='')
  2482. self.sess.run(tf.global_variables_initializer())
  2483. self.char_input = self.sess.graph.get_tensor_by_name('CharInputs:0')
  2484. self.length = self.sess.graph.get_tensor_by_name("Sum:0")
  2485. self.dropout = self.sess.graph.get_tensor_by_name("Dropout:0")
  2486. self.logit = self.sess.graph.get_tensor_by_name("logits/Reshape:0")
  2487. self.tran = self.sess.graph.get_tensor_by_name("crf_loss/transitions:0")
  2488. def decode(self,logits, lengths, matrix):
  2489. paths = []
  2490. small = -1000.0
  2491. # start = np.asarray([[small] * 4 + [0]])
  2492. start = np.asarray([[small]*7+[0]])
  2493. for score, length in zip(logits, lengths):
  2494. score = score[:length]
  2495. pad = small * np.ones([length, 1])
  2496. logits = np.concatenate([score, pad], axis=1)
  2497. logits = np.concatenate([start, logits], axis=0)
  2498. path, _ = viterbi_decode(logits, matrix)
  2499. paths.append(path[1:])
  2500. return paths
  2501. def predict(self, list_sentences,list_entitys=None,list_articles=[], fail=False, MAX_AREA=5000, out_lines=[]):
  2502. '''
  2503. 预测实体代码,每个句子最多取MAX_AREA个字,超过截断
  2504. :param list_sentences: 多篇公告句子列表,[[一篇公告句子列表],[公告句子列表]]
  2505. :param list_entitys: 多篇公告实体列表
  2506. :param MAX_AREA: 每个句子最多截取多少字
  2507. :return: 把预测出来的实体放进实体类
  2508. '''
  2509. p = "(采购需求|需求分析|项目说明|(采购|合同|招标|询比?价|项目|服务|工程|标的|需求|建设|分包)(的?(主要|简要|基本|具体|名称及))?" \
  2510. "(内容|概况|概述|范围|信息|规模|简介|介绍|说明|摘要|情况|名称)([及与和]((其它|\w{,2})[要需]求|发包范围|数量))?" \
  2511. "|招标项目技术要求|服务要求|服务需求|项目目标|需求内容如下|建设规模|(设备|材料|仪器|需求|产品|采购单?)(清单|名称|信息))为?([::,]|$)"
  2512. # sentence_range = [] #20240827 取消,修复线上接口产品耗时长问题
  2513. # if len(out_lines) >= 3: # 三个以上大纲
  2514. # for i in range(len(out_lines)-1):
  2515. # text, s1, b1 = out_lines[i]
  2516. # _, s2, b2 = out_lines[i+1]
  2517. # if 3<text.find(':')<20:
  2518. # text = text.split(':')[0]
  2519. # if re.search(p, text[:15]):
  2520. # sentence_range.append((s1, s2))
  2521. with self.sess.as_default() as sess:
  2522. with self.sess.graph.as_default():
  2523. result = []
  2524. product_list = []
  2525. if fail and list_articles!=[]:
  2526. text_list = [list_articles[0].content[:MAX_AREA]]
  2527. chars = [[self.word2index.get(it, self.word2index.get('<unk>')) for it in text] for text in text_list]
  2528. if USE_API:
  2529. requests_result = requests.post(API_URL + "/predict_product",
  2530. json={"inputs": chars}, verify=True)
  2531. batch_paths = json.loads(requests_result.text)['result']
  2532. lengths = json.loads(requests_result.text)['lengths']
  2533. else:
  2534. lengths, scores, tran_ = sess.run([self.length, self.logit, self.tran],
  2535. feed_dict={
  2536. self.char_input: np.asarray(chars),
  2537. self.dropout: 1.0
  2538. })
  2539. batch_paths = self.decode(scores, lengths, tran_)
  2540. for text, path, length in zip(text_list, batch_paths, lengths):
  2541. tags = ''.join([str(it) for it in path[:length]])
  2542. # 提取产品
  2543. for it in re.finditer("12*3", tags):
  2544. start = it.start()
  2545. end = it.end()
  2546. _entity = Entity(doc_id=list_articles[0].id, entity_id="%s_%s_%s_%s" % (
  2547. list_articles[0].doc_id, 0, start, end),
  2548. entity_text=text[start:end],
  2549. entity_type="product", sentence_index=0,
  2550. begin_index=0, end_index=0, wordOffset_begin=start,
  2551. wordOffset_end=end)
  2552. list_entitys[0].append(_entity)
  2553. product_list.append(text[start:end])
  2554. # 提取失败原因
  2555. for it in re.finditer("45*6", tags):
  2556. start = it.start()
  2557. end = it.end()
  2558. result.append(text[start:end].replace('?', '').strip())
  2559. reasons = []
  2560. for it in result:
  2561. if "(√)" in it or "(√)" in it:
  2562. reasons = [it]
  2563. break
  2564. if reasons != [] and (it not in reasons[-1] and it not in reasons):
  2565. reasons.append(it)
  2566. elif reasons == []:
  2567. reasons.append(it)
  2568. if reasons == []: # 如果模型识别不到失败原因 就用规则补充
  2569. for text in text_list:
  2570. ser1 = re.search('\w{,4}(理由|原因):\s*((第\d+包|标项\d+|原因类型)?[::]?[\s*\w,]{2,30}((不满?足|少于|未达)((法定)?[123一二三两]家|(规定)?要求)|(项目|采购)(终止|废标)),?)+',text)
  2571. ser2 = re.search(
  2572. '\w{,4}(理由|原因):\s*(第\d+包|标项\d+|原因类型)?[::]?[\s*\w]{4,30},', text)
  2573. if ser1:
  2574. reasons.append(ser1.group(0))
  2575. break
  2576. elif ser2:
  2577. reasons.append(ser2.group(0))
  2578. break
  2579. return {'fail_reason':';'.join(reasons)}, product_list
  2580. if list_entitys is None:
  2581. list_entitys = [[] for _ in range(len(list_sentences))]
  2582. for list_sentence, list_entity in zip(list_sentences,list_entitys):
  2583. if len(list_sentence)==0:
  2584. result.append({"product":[]})
  2585. continue
  2586. # 20240827 取消,修复线上接口产品耗时长问题
  2587. # if sentence_range: # 20240815 如果有招标内容大纲,只从前两句及大纲内提取产品,避免类似 514920213 提取错其他内容 银行流水
  2588. # new_list = []
  2589. # word_num = 0
  2590. # for sentence in list_sentence:
  2591. # if sentence.sentence_index<2:
  2592. # new_list.append(sentence)
  2593. # continue
  2594. # for s1, s2 in sentence_range:
  2595. # if sentence.sentence_index < s1:
  2596. # continue
  2597. # elif s1<=sentence.sentence_index <=s2:
  2598. # new_list.append(sentence)
  2599. # word_num += len(sentence.sentence_text)
  2600. # elif sentence.sentence_index >= s2:
  2601. # break
  2602. # if word_num > 100:
  2603. # list_sentence = new_list
  2604. list_sentence.sort(key=lambda x:len(x.sentence_text), reverse=True)
  2605. _begin_index = 0
  2606. item = {"product":[]}
  2607. temp_list = []
  2608. while True:
  2609. MAX_LEN = len(list_sentence[_begin_index].sentence_text)
  2610. if MAX_LEN > MAX_AREA:
  2611. MAX_LEN = MAX_AREA
  2612. _LEN = MAX_AREA//MAX_LEN
  2613. chars = [sentence.sentence_text[:MAX_LEN] for sentence in list_sentence[_begin_index:_begin_index+_LEN]]
  2614. chars = [[self.word2index.get(it, self.word2index.get('<unk>')) for it in l] for l in chars]
  2615. chars = pad_sequences(chars, maxlen=MAX_LEN, padding="post", truncating="post")
  2616. if USE_API:
  2617. requests_result = requests.post(API_URL + "/predict_product",
  2618. json={"inputs": chars.tolist()}, verify=True)
  2619. batch_paths = json.loads(requests_result.text)['result']
  2620. lengths = json.loads(requests_result.text)['lengths']
  2621. else:
  2622. lengths, scores, tran_ = sess.run([self.length, self.logit, self.tran],
  2623. feed_dict={
  2624. self.char_input: np.asarray(chars),
  2625. self.dropout: 1.0
  2626. })
  2627. batch_paths = self.decode(scores, lengths, tran_)
  2628. for sentence, path, length in zip(list_sentence[_begin_index:_begin_index+_LEN],batch_paths, lengths):
  2629. tags = ''.join([str(it) for it in path[:length]])
  2630. for it in re.finditer("12*3", tags):
  2631. start = it.start()
  2632. end = it.end()
  2633. _entity = Entity(doc_id=sentence.doc_id, entity_id="%s_%s_%s_%s" % (
  2634. sentence.doc_id, sentence.sentence_index, start, end),
  2635. entity_text=sentence.sentence_text[start:end],
  2636. entity_type="product", sentence_index=sentence.sentence_index,
  2637. begin_index=0, end_index=0, wordOffset_begin=start,
  2638. wordOffset_end=end,in_attachment=sentence.in_attachment)
  2639. list_entity.append(_entity)
  2640. temp_list.append(sentence.sentence_text[start:end])
  2641. product_list.append(sentence.sentence_text[start:end])
  2642. # item["product"] = list(set(temp_list))
  2643. # result.append(item)
  2644. if _begin_index+_LEN >= len(list_sentence):
  2645. break
  2646. _begin_index += _LEN
  2647. item["product"] = list(set(temp_list))
  2648. result.append(item) # 修正bug
  2649. return {'fail_reason': ""},product_list
  2650. # 产品数量单价品牌规格提取 #2021/11/10 添加表格中的项目、需求、预算、时间要素提取
  2651. class ProductAttributesPredictor():
  2652. def __init__(self,):
  2653. self.p0 = '(类别|类型|物类|目录|类目|分类)(名称|$)|^品名|^品类|^品目|(标项|分项|项目|计划|包组|标段|[分子]?包|子目|服务|招标|中标|成交|工程|招标内容)(名称|内容|描述)'
  2654. self.p1 = '(标的|维修|系统|报价构成|商品|产品|物料|物资|货物|设备|采购品|采购条目|物品|材料|印刷品?|采购|物装|配件|资产|耗材|清单|器材|仪器|器械|备件|拍卖物|标的物|物件|药品|药材|药械|货品|食品|食材|品目|^品名|气体)[\))的]?([、\w]{,4}名称|内容|描述)'
  2655. self.p2 = '标的|标项|项目$|商品|产品|物料|物资|货物|设备|采购品|采购条目|物品|材料|印刷品|物装|配件|资产|招标内容|耗材|清单|器材|仪器|器械|备件|拍卖物|标的物|物件|药品|药材|药械|货品|食品|食材|菜名|^品目$|^品名$|^名称|^内容$|(标项|分项|项目|计划|包组|标段|[分子]?包|子目|服务|招标|中标|成交|工程|招标内容)(名称|内容|描述)'
  2656. # self.p1 = '(设备|货物|商品|产品|物品|货品|材料|物资|物料|物件|耗材|备件|食材|食品|品目|标的|标的物|标项|资产|拍卖物|仪器|器材|器械|药械|药品|药材|采购品?|项目|招标|工程|服务)[\))]?(名称|内容|描述)'
  2657. # self.p2 = '设备|货物|商品|产品|物品|货品|材料|物资|物料|物件|耗材|备件|食材|食品|品目|标的|标的物|资产|拍卖物|仪器|器材|器械|药械|药品|药材|采购品|项目|品名|菜名|内容|名称'
  2658. with open(os.path.dirname(__file__)+'/header_set.pkl', 'rb') as f:
  2659. self.header_set = pickle.load(f)
  2660. self.tb = TableTag2List()
  2661. def isTrueTable(self, table):
  2662. '''真假表格规则:
  2663. 1、包含<caption>或<th>标签为真
  2664. 2、包含大量链接、表单、图片或嵌套表格为假
  2665. 3、表格尺寸太小为假
  2666. 4、外层<table>嵌套子<table>,一般子为真,外为假'''
  2667. if table.find_all(['caption', 'th']) != []:
  2668. return True
  2669. elif len(table.find_all(['form', 'a', 'img'])) > 5:
  2670. # print('过滤表格:包含链接图片等大于5的为假表格')
  2671. return False
  2672. elif len(table.find_all(['tr'])) < 2:
  2673. # print('过滤表格:行数小于2的为假表格')
  2674. return False
  2675. elif len(table.find_all(['table'])) >= 1:
  2676. # print('过滤表格:包含多个表格的为假表格')
  2677. return False
  2678. else:
  2679. return True
  2680. def getTrs(self, tbody):
  2681. # 获取所有的tr
  2682. trs = []
  2683. objs = tbody.find_all(recursive=False)
  2684. for obj in objs:
  2685. if obj.name == "tr":
  2686. trs.append(obj)
  2687. if obj.name == "tbody":
  2688. for tr in obj.find_all("tr", recursive=False):
  2689. trs.append(tr)
  2690. return trs
  2691. def getTable(self, tbody):
  2692. trs = self.getTrs(tbody)
  2693. inner_table = []
  2694. if len(trs) < 2:
  2695. return inner_table
  2696. for tr in trs:
  2697. tr_line = []
  2698. tds = tr.findChildren(['td', 'th'], recursive=False)
  2699. if len(tds) < 2:
  2700. continue
  2701. for td in tds:
  2702. # td_text = re.sub('\s+|…', ' ', td.get_text()).strip()
  2703. td_text = re.sub('…', '', td.get_text()).strip()
  2704. td_text = td_text.replace("\x06", "").replace("\x05", "").replace("\x07", "").replace('\\', '/').replace('"', '') # 修复272144312 # 产品单价数量提取结果有特殊符号\ 气动执行装置备件\密封组件\NBR+PT
  2705. td_text = td_text.replace("(", "(").replace(")", ")").replace(':', ':')
  2706. tr_line.append(td_text)
  2707. inner_table.append(tr_line)
  2708. return inner_table
  2709. def fixSpan(self, tbody):
  2710. # 处理colspan, rowspan信息补全问题
  2711. trs = self.getTrs(tbody)
  2712. ths_len = 0
  2713. ths = list()
  2714. trs_set = set()
  2715. # 修改为先进行列补全再进行行补全,否则可能会出现表格解析混乱
  2716. # 遍历每一个tr
  2717. for indtr, tr in enumerate(trs):
  2718. ths_tmp = tr.findChildren('th', recursive=False)
  2719. # 不补全含有表格的tr
  2720. if len(tr.findChildren('table')) > 0:
  2721. continue
  2722. if len(ths_tmp) > 0:
  2723. ths_len = ths_len + len(ths_tmp)
  2724. for th in ths_tmp:
  2725. ths.append(th)
  2726. trs_set.add(tr)
  2727. # 遍历每行中的element
  2728. tds = tr.findChildren(recursive=False)
  2729. if len(tds) < 3:
  2730. continue # 列数太少的不补全
  2731. for indtd, td in enumerate(tds):
  2732. # 若有colspan 则补全同一行下一个位置
  2733. if 'colspan' in td.attrs and str(re.sub("[^0-9]", "", str(td['colspan']))) != "":
  2734. col = int(re.sub("[^0-9]", "", str(td['colspan'])))
  2735. if col < 10 and len(td.get_text()) < 500:
  2736. td['colspan'] = 1
  2737. for i in range(1, col, 1):
  2738. td.insert_after(copy.copy(td))
  2739. for indtr, tr in enumerate(trs):
  2740. ths_tmp = tr.findChildren('th', recursive=False)
  2741. # 不补全含有表格的tr
  2742. if len(tr.findChildren('table')) > 0:
  2743. continue
  2744. if len(ths_tmp) > 0:
  2745. ths_len = ths_len + len(ths_tmp)
  2746. for th in ths_tmp:
  2747. ths.append(th)
  2748. trs_set.add(tr)
  2749. # 遍历每行中的element
  2750. tds = tr.findChildren(recursive=False)
  2751. same_span = 0
  2752. if len(tds) > 1 and 'rowspan' in tds[0].attrs:
  2753. span0 = tds[0].attrs['rowspan']
  2754. for td in tds:
  2755. if 'rowspan' in td.attrs and td.attrs['rowspan'] == span0:
  2756. same_span += 1
  2757. if same_span == len(tds):
  2758. continue
  2759. for indtd, td in enumerate(tds):
  2760. # 若有rowspan 则补全下一行同样位置
  2761. if 'rowspan' in td.attrs and str(re.sub("[^0-9]", "", str(td['rowspan']))) != "":
  2762. row = int(re.sub("[^0-9]", "", str(td['rowspan'])))
  2763. td['rowspan'] = 1
  2764. for i in range(1, row, 1):
  2765. # 获取下一行的所有td, 在对应的位置插入
  2766. if indtr + i < len(trs):
  2767. tds1 = trs[indtr + i].findChildren(['td', 'th'], recursive=False)
  2768. if len(tds1) >= (indtd) and len(tds1) > 0:
  2769. if indtd > 0:
  2770. tds1[indtd - 1].insert_after(copy.copy(td))
  2771. else:
  2772. tds1[0].insert_before(copy.copy(td))
  2773. elif len(tds1) > 0 and len(tds1) == indtd - 1:
  2774. tds1[indtd - 2].insert_after(copy.copy(td))
  2775. def get_monthlen(self, year, month):
  2776. '''输入年份、月份 int类型 得到该月份天数'''
  2777. try:
  2778. weekday, num = calendar.monthrange(int(year), int(month))
  2779. except:
  2780. num = 30
  2781. return str(num)
  2782. def fix_time(self, text, html, page_time):
  2783. '''输入日期字段返回格式化日期'''
  2784. for it in [('十二', '12'),('十一', '11'),('十','10'),('九','9'),('八','8'),('七','7'),
  2785. ('六','6'),('五','5'),('四','4'),('三','3'),('二','2'),('一','1')]:
  2786. if it[0] in text:
  2787. text = text.replace(it[0], it[1])
  2788. if re.search('^\d{1,2}月$', text):
  2789. m = re.search('^(\d{1,2})月$', text).group(1)
  2790. if len(m) < 2:
  2791. m = '0' + m
  2792. year = re.search('(\d{4})年(.{,12}采购意向)?', html)
  2793. if year:
  2794. y = year.group(1)
  2795. num = self.get_monthlen(y, m)
  2796. if len(num) < 2:
  2797. num = '0' + num
  2798. order_begin = "%s-%s-01" % (y, m)
  2799. order_end = "%s-%s-%s" % (y, m, num)
  2800. elif page_time != "":
  2801. year = re.search('\d{4}', page_time)
  2802. if year:
  2803. y = year.group(0)
  2804. num = self.get_monthlen(y, m)
  2805. if len(num) < 2:
  2806. num = '0' + num
  2807. order_begin = "%s-%s-01" % (y, m)
  2808. order_end = "%s-%s-%s" % (y, m, num)
  2809. else:
  2810. y = str(datetime.datetime.now().year)
  2811. num = self.get_monthlen(y, m)
  2812. if len(num) < 2:
  2813. num = '0' + num
  2814. order_begin = "%s-%s-01" % (y, m)
  2815. order_end = "%s-%s-%s" % (y, m, num)
  2816. else:
  2817. y = str(datetime.datetime.now().year)
  2818. num = self.get_monthlen(y, m)
  2819. if len(num) < 2:
  2820. num = '0' + num
  2821. order_begin = "%s-%s-01" % (y, m)
  2822. order_end = "%s-%s-%s" % (y, m, num)
  2823. return order_begin, order_end
  2824. t1 = re.search('^(\d{4})(年|/|\.|-)(\d{1,2})月?$', text)
  2825. if t1:
  2826. year = t1.group(1)
  2827. month = t1.group(3)
  2828. num = self.get_monthlen(year, month)
  2829. if len(month)<2:
  2830. month = '0'+month
  2831. if len(num) < 2:
  2832. num = '0'+num
  2833. order_begin = "%s-%s-01" % (year, month)
  2834. order_end = "%s-%s-%s" % (year, month, num)
  2835. return order_begin, order_end
  2836. t2 = re.search('^(\d{4})(年|/|\.|-)(\d{1,2})(月|/|\.|-)(\d{1,2})日?$', text)
  2837. if t2:
  2838. y = t2.group(1)
  2839. m = t2.group(3)
  2840. d = t2.group(5)
  2841. m = '0'+ m if len(m)<2 else m
  2842. d = '0'+d if len(d)<2 else d
  2843. order_begin = order_end = "%s-%s-%s"%(y,m,d)
  2844. return order_begin, order_end
  2845. # 时间样式:"202105"
  2846. t3 = re.search("^(20\d{2})(\d{1,2})$",text)
  2847. if t3:
  2848. year = t3.group(1)
  2849. month = t3.group(2)
  2850. if int(month)>0 and int(month)<=12:
  2851. num = self.get_monthlen(year, month)
  2852. if len(month) < 2:
  2853. month = '0' + month
  2854. if len(num) < 2:
  2855. num = '0' + num
  2856. order_begin = "%s-%s-01" % (year, month)
  2857. order_end = "%s-%s-%s" % (year, month, num)
  2858. return order_begin, order_end
  2859. # 时间样式:"20210510"
  2860. t4 = re.search("^(20\d{2})(\d{2})(\d{2})$", text)
  2861. if t4:
  2862. year = t4.group(1)
  2863. month = t4.group(2)
  2864. day = t4.group(3)
  2865. if int(month) > 0 and int(month) <= 12 and int(day)>0 and int(day)<=31:
  2866. order_begin = order_end = "%s-%s-%s"%(year,month,day)
  2867. return order_begin, order_end
  2868. all_match = re.finditer('^(?P<y1>\d{4})(年|/|\.)(?P<m1>\d{1,2})(?:(月|/|\.)(?:(?P<d1>\d{1,2})日)?)?'
  2869. '(到|至|-)(?:(?P<y2>\d{4})(年|/|\.))?(?P<m2>\d{1,2})(?:(月|/|\.)'
  2870. '(?:(?P<d2>\d{1,2})日)?)?$', text)
  2871. y1 = m1 = d1 = y2 = m2 = d2 = ""
  2872. found_math = False
  2873. for _match in all_match:
  2874. if len(_match.group()) > 0:
  2875. found_math = True
  2876. for k, v in _match.groupdict().items():
  2877. if v!="" and v is not None:
  2878. if k == 'y1':
  2879. y1 = v
  2880. elif k == 'm1':
  2881. m1 = v
  2882. elif k == 'd1':
  2883. d1 = v
  2884. elif k == 'y2':
  2885. y2 = v
  2886. elif k == 'm2':
  2887. m2 = v
  2888. elif k == 'd2':
  2889. d2 = v
  2890. if not found_math:
  2891. return "", ""
  2892. y2 = y1 if y2 == "" else y2
  2893. d1 = '1' if d1 == "" else d1
  2894. d2 = self.get_monthlen(y2, m2) if d2 == "" else d2
  2895. m1 = '0' + m1 if len(m1) < 2 else m1
  2896. m2 = '0' + m2 if len(m2) < 2 else m2
  2897. d1 = '0' + d1 if len(d1) < 2 else d1
  2898. d2 = '0' + d2 if len(d2) < 2 else d2
  2899. order_begin = "%s-%s-%s"%(y1,m1,d1)
  2900. order_end = "%s-%s-%s"%(y2,m2,d2)
  2901. return order_begin, order_end
  2902. def fix_quantity(self, quantity_text, header_quan_unit):
  2903. '''
  2904. 产品数量标准化,统一为数值型字符串
  2905. :param quantity_text: 原始数量字符串
  2906. :param header_quan_unit: 表头数量单位字符串
  2907. :return: 返回数量及单位
  2908. '''
  2909. quantity = quantity_text
  2910. quantity = re.sub('[一壹]', '1', quantity)
  2911. quantity = re.sub('[,,约]|(\d+)', '', quantity)
  2912. ser = re.search('^(\d+\.?\d*)(?([㎡\w/]{,5})', quantity)
  2913. if ser:
  2914. quantity = str(ser.group(1))
  2915. quantity_unit = ser.group(2)
  2916. if quantity_unit == "" and header_quan_unit != "":
  2917. quantity_unit = header_quan_unit
  2918. else:
  2919. quantity = ""
  2920. quantity_unit = ""
  2921. return quantity, quantity_unit
  2922. def find_header(self, items,p0, p1, p2):
  2923. '''
  2924. inner_table 每行正则检查是否为表头,是则返回表头所在列序号,及表头内容
  2925. :param items: 列表,内容为每个td 文本内容
  2926. :param p1: 优先表头正则
  2927. :param p2: 第二表头正则
  2928. :return: 表头所在列序号,是否表头,表头内容
  2929. '''
  2930. items = [re.sub('\s', '', it) for it in items]
  2931. flag = False
  2932. header_dic = {'名称': '', '数量': '', '单位': '', '单价': '', '品牌': '', '规格': '', '需求': '', '预算': '', '时间': '', '总价': '', '品目': '', '参数': '', '采购人':'', '备注':'','发布日期':'', '品目号':'', '品目名':''}
  2933. product = "" # 产品
  2934. quantity = "" # 数量
  2935. quantity_unit = "" # 数量单位
  2936. unitPrice = "" # 单价
  2937. brand = "" # 品牌
  2938. specs = "" # 规格
  2939. demand = "" # 采购需求
  2940. budget = "" # 预算金额
  2941. order_time = "" # 采购时间
  2942. total_price = "" # 总价
  2943. category = "" # 品目
  2944. parameter = "" # 参数
  2945. tenderee = "" # 采购人
  2946. notes = "" # 备注 2024/3/27 达仁 需求
  2947. issue_date = "" # 发布日期 2024/3/27 达仁 需求
  2948. pinmu_no = "" # 品目号
  2949. pinmu_name = "" # 品目名称
  2950. # for i in range(min(6, len(items))):
  2951. for i in range(len(items)):
  2952. it = items[i]
  2953. if len(it) < 15 and re.search(p0, it) != None:
  2954. flag = True
  2955. if category != "" and category != it:
  2956. continue
  2957. category = it
  2958. header_dic['品目'] = i
  2959. elif len(it) < 15 and re.search(p1, it) != None:
  2960. flag = True
  2961. if product !='' and product != it:
  2962. break
  2963. product = it
  2964. header_dic['名称'] = i
  2965. # break
  2966. # if not flag:
  2967. if product == "":
  2968. # for i in range(min(4, len(items))):
  2969. for i in range(len(items)):
  2970. it = items[i]
  2971. if len(it) < 15 and it != category and re.search(p2, it) and (re.search('^名称|^品名|^品目', it) or re.search(
  2972. '编号|编码|号|情况|报名|单位|位置|地址|数量|单价|价格|金额|品牌|规格类型|型号|公司|中标人|企业|供应商|候选人', it) == None):
  2973. flag = True
  2974. product = it
  2975. header_dic['名称'] = i
  2976. break
  2977. if flag == False and len(items)>3 and re.search('^第[一二三四五六七八九十](包|标段)$', items[0]):
  2978. product = items[0]
  2979. header_dic['名称'] = 0
  2980. flag = True
  2981. if flag:
  2982. # for j in range(i + 1, len(items)):
  2983. for j in range(len(items)):
  2984. if header_dic['品目号'] == "" and re.search('(品目|品类)(编?号|编码|序号)', items[j]):
  2985. header_dic['品目号'] = j
  2986. pinmu_no = items[j]
  2987. elif header_dic['品目名'] == "" and re.search('(品目|品类)名称|采购(品目|品类)$', items[j]):
  2988. header_dic['品目名'] = j
  2989. pinmu_name = items[j]
  2990. if items[j] in [product, category]:
  2991. continue
  2992. if len(items[j]) > 20 and len(re.sub('[\((].*[)\)]|[^\u4e00-\u9fa5]', '', items[j])) > 10:
  2993. continue
  2994. if header_dic['数量']=="" and re.search('数量|采购量', items[j]) and re.search('单价|用途|要求|规格|型号|运输|承运', items[j])==None:
  2995. header_dic['数量'] = j
  2996. quantity = items[j]
  2997. elif header_dic['单位']=="" and re.search('^(数量单位|计量单位|单位)$', items[j]):
  2998. header_dic['单位'] = j
  2999. quantity_unit = items[j]
  3000. elif re.search('单价', items[j]) and re.search('数量|规格|型号|品牌|供应商', items[j])==None:
  3001. header_dic['单价'] = j
  3002. unitPrice = items[j]
  3003. elif re.search('品牌', items[j]):
  3004. header_dic['品牌'] = j
  3005. brand = items[j]
  3006. elif re.search('规格|型号', items[j]):
  3007. header_dic['规格'] = j
  3008. specs = items[j]
  3009. elif re.search('参数', items[j]):
  3010. header_dic['参数'] = j
  3011. parameter = items[j]
  3012. elif re.search('预算单位|(采购|招标|购买)(单位|人|方|主体)|项目业主|采购商|申购单位|需求单位|业主单位',items[j]) and len(items[j])<=8:
  3013. header_dic['采购人'] = j
  3014. tenderee = items[j]
  3015. elif re.search('需求|服务要求|服务标准', items[j]):
  3016. header_dic['需求'] = j
  3017. demand = items[j]
  3018. elif re.search('预算|控制金额', items[j]) and not re.search('预算单位',items[j]):
  3019. header_dic['预算'] = j
  3020. budget = items[j]
  3021. elif re.search('时间|采购实施月份|采购月份|采购日期', items[j]):
  3022. header_dic['时间'] = j
  3023. order_time = items[j]
  3024. elif re.search('总价|(成交|中标|验收|合同|预算|控制|总|合计))?([金总]额|价格?)|最高限价|价格|金额', items[j]) and re.search('数量|规格|型号|品牌|供应商', items[j])==None:
  3025. header_dic['总价'] = j
  3026. total_price = items[j]
  3027. elif re.search('^备\s*注$|资质要求|预留面向中小企业|是否适宜中小企业采购预算预留|公开征集信息', items[j]):
  3028. header_dic['备注'] = j
  3029. notes = items[j]
  3030. elif re.search('^\w{,4}发布(时间|日期)$', items[j]):
  3031. header_dic['发布日期'] = j
  3032. issue_date = items[j]
  3033. if header_dic.get('名称', "") != "" or header_dic.get('品目', "") != "":
  3034. # num = 0
  3035. # for it in (quantity, unitPrice, brand, specs, product, demand, budget, order_time, total_price):
  3036. # if it != "":
  3037. # num += 1
  3038. # if num >=2:
  3039. # return header_dic, flag, (product, quantity, quantity_unit, unitPrice, brand, specs, total_price, category, parameter), (product, demand, budget, order_time)
  3040. if set([quantity, brand, specs, unitPrice, total_price])!=set([""]) or set([demand, budget])!=set([""]):
  3041. return header_dic, flag, (product, quantity, quantity_unit, unitPrice, brand, specs, total_price, category, parameter, pinmu_no, pinmu_name), (product, demand, budget, order_time,tenderee, notes,issue_date)
  3042. flag = False
  3043. return header_dic, flag, (product, quantity, quantity_unit, unitPrice, brand, specs, total_price, category, parameter, pinmu_no, pinmu_name), (product, demand, budget, order_time,tenderee,notes,issue_date)
  3044. def predict(self, docid='', html='', page_time=""):
  3045. '''
  3046. 正则寻找table表格内 产品相关信息
  3047. :param html:公告HTML原文
  3048. :return:公告表格内 产品、数量、单价、品牌、规格 ,表头,表头列等信息
  3049. '''
  3050. html = html.replace('<br>', '\n').replace('<br/>', '\n')
  3051. html = re.sub("<html>|</html>|<body>|</body>","",html)
  3052. html = re.sub("##attachment##","",html)
  3053. soup = BeautifulSoup(html, 'lxml')
  3054. # flag_yx = True if re.search('采购意向', html) else False
  3055. flag_yx = True if re.search('采购意向|招标意向|选取意向|意向公告|意向公示|意向公开', html) else False
  3056. tables = soup.find_all(['table'])
  3057. headers = []
  3058. headers_demand = []
  3059. header_col = []
  3060. product_link = []
  3061. demand_link = []
  3062. product_set = set()
  3063. total_product_money = 0
  3064. unit_price_list = [] # 单价列表,用于判断是否重复单价,避免多个表格重复提取造成合计产品价格错误。
  3065. total_price_list = [] # 总价列表,拥有判断是否为几行产品合计总价
  3066. # print('表格数:', len(tables))
  3067. for i in range(len(tables)): # (len(tables)-1, -1, -1) 由从最后到前改为 前到后
  3068. table = tables[i]
  3069. if table.parent.name == 'td' and len(table.find_all('td')) <= 3:
  3070. table.string = table.get_text()
  3071. table.name = 'turntable'
  3072. # print('过滤表格:表格父节点为td,且表格td数量小于等于3')
  3073. continue
  3074. if not self.isTrueTable(table):
  3075. continue
  3076. # self.fixSpan(table)
  3077. # inner_table = self.getTable(table)
  3078. inner_table = self.tb.table2list(table)
  3079. table.extract()
  3080. # print(inner_table)
  3081. i = 0
  3082. found_header = False
  3083. header_quan_unit = "" # 数量表头 包含单位
  3084. header_colnum = 0
  3085. if flag_yx:
  3086. # print('意向公告, 提取意向信息')
  3087. col0_l = []
  3088. col1_l = []
  3089. for tds in inner_table:
  3090. if len(tds) == 2:
  3091. col0_l.append(re.sub('[::]', '', tds[0])) # 处理只有两列的情况
  3092. col1_l.append(tds[1])
  3093. elif len(tds)>=4 and len(inner_table)==2: # 处理只有两行的情况
  3094. col0_l = inner_table[0]
  3095. col1_l = inner_table[1]
  3096. break
  3097. # print(set(col0_l))
  3098. # print('head: ',set(col0_l) & self.header_set)
  3099. if len(set(col0_l) & self.header_set) > len(col0_l) * 0.2 and len(col0_l)==len(col1_l): # 保证两个列数一致
  3100. header_list2 = []
  3101. product = demand = budget = order_begin = order_end = ""
  3102. tenderee = ""
  3103. notes = ''
  3104. issue_date = ''
  3105. for i in range(len(col0_l)):
  3106. if re.search('项目名称', col0_l[i]):
  3107. header_list2.append(col0_l[i])
  3108. product = col1_l[i]
  3109. elif re.search('采购需求|需求概况|招标内容|项目概况', col0_l[i]):
  3110. header_list2.append(col0_l[i])
  3111. demand = col1_l[i]
  3112. elif re.search('采购预算|预算金额|控制金额', col0_l[i]):
  3113. header_list2.append(col0_l[i])
  3114. _budget = col1_l[i]
  3115. re_price = re.findall("[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,}|\d[\d,]*(?:\.\d+)?万?", _budget)
  3116. if re_price:
  3117. # _budget = re_price[0]
  3118. # if '万元' in col0_l[i] and '万' not in _budget:
  3119. # _budget += '万元'
  3120. # budget = str(getUnifyMoney(_budget))
  3121. _budget, _money_unit = money_process(_budget, col0_l[i])
  3122. budget = str(_budget)
  3123. if '.' in budget:
  3124. budget = budget.rstrip('0').rstrip('.')
  3125. if float(budget)>= 500*100000000:
  3126. budget = ""
  3127. elif re.search('预算单位|(采购|招标|购买)(单位|人|方|主体)|项目业主|采购商|申购单位|需求单位|业主单位', col0_l[i]):
  3128. header_list2.append(col0_l[i])
  3129. tenderee = re.sub("\s","",col1_l[i])
  3130. if len(tenderee) > 20:
  3131. tenderee = ""
  3132. elif re.search('采购时间|采购实施月份|采购月份|采购日期|预计招标时间', col0_l[i]):
  3133. header_list2.append(col0_l[i])
  3134. order_time = col1_l[i].strip()
  3135. order_begin, order_end = self.fix_time(order_time, html, page_time)
  3136. elif re.search('^备\s*注$|资质要求|预留面向中小企业|是否适宜中小企业采购预算预留|公开征集信息', col0_l[i]):
  3137. header_list2.append(col0_l[i])
  3138. notes = col1_l[i].strip()
  3139. elif re.search('^\w{,4}发布(时间|日期)$', col0_l[i]):
  3140. header_list2.append(col0_l[i])
  3141. issue_date = self.fix_time(col1_l[i].strip(), '', '')[0]
  3142. if order_begin != "" and order_end!="":
  3143. order_begin_year = int(order_begin.split("-")[0])
  3144. order_end_year = int(order_end.split("-")[0])
  3145. # 限制附件错误识别时间
  3146. if order_begin_year>=2050 or order_end_year>=2050:
  3147. order_begin = order_end = ""
  3148. # print(product,demand,budget,order_begin)
  3149. if product!= "" and demand != "" and budget!="" and order_begin != "":
  3150. link = {'project_name': product, 'product': [], 'demand': demand, 'budget': budget,
  3151. 'order_begin': order_begin, 'order_end': order_end ,'tenderee':tenderee, 'notes':notes, 'issue_date':issue_date}
  3152. if link not in demand_link:
  3153. demand_link.append(link)
  3154. headers_demand.append('_'.join(header_list2))
  3155. continue
  3156. if len(inner_table)>3 and len(inner_table[0])==2 and len(inner_table[1])==2: # 只有两列且第一列为表头的,行列切换
  3157. col0_l = []
  3158. col1_l = []
  3159. for tds in inner_table:
  3160. if len(tds) == 2:
  3161. col0_l.append(re.sub('[::]', '', tds[0])) # 处理只有两列的情况
  3162. col1_l.append(tds[1])
  3163. else:
  3164. break
  3165. if len(set(col0_l) & self.header_set) > len(col0_l) * 0.5 and len(col0_l) == len(col1_l):
  3166. inner_table = [col0_l, col1_l]
  3167. elif len(inner_table)>2 and len(inner_table[0])==4 and len(inner_table[1])==4 and len(set(inner_table[0]) & self.header_set)==2: # 只有两列且第一列为表头的,行列切换
  3168. col0_l = []
  3169. col1_l = []
  3170. col2_l = []
  3171. col3_l = []
  3172. for tds in inner_table:
  3173. if len(tds) == 4 and len(set(tds))>2:
  3174. col0_l.append(re.sub('[::]', '', tds[0])) # 处理只有两列的情况
  3175. col1_l.append(tds[1])
  3176. col2_l.append(re.sub('[::]', '', tds[2])) # 处理只有两列的情况
  3177. col3_l.append(tds[3])
  3178. else:
  3179. break
  3180. if len(set(col0_l) & self.header_set) > len(col0_l) * 0.5 and len(set(col2_l) & self.header_set) > len(col2_l) * 0.5:
  3181. inner_table = [col0_l+col2_l, col1_l+col3_l]
  3182. while i < (len(inner_table)):
  3183. tds = inner_table[i]
  3184. not_empty = [it for it in tds if re.sub('\s', '', it) != ""]
  3185. if len(set(not_empty))<2 or len(set(tds))<2 or (len(set(tds))==2 and re.search('总计|合计|汇总', tds[0])): # 非空列或者不重复内容小于两列的 继续
  3186. i += 1
  3187. # print('表格产品提取:非空列或者不重复内容小于两列的 继续', i, tds)
  3188. continue
  3189. product = "" # 产品
  3190. quantity = "" # 数量
  3191. quantity_unit = "" # 数量单位
  3192. unitPrice = "" # 单价
  3193. brand = "" # 品牌
  3194. specs = "" # 规格
  3195. demand = "" # 采购需求
  3196. budget = "" # 预算金额
  3197. order_time = "" # 采购时间
  3198. order_begin = ""
  3199. order_end = ""
  3200. total_price = "" # 总金额
  3201. parameter = "" # 参数
  3202. tenderee = "" # 采购人
  3203. notes = '' # 备注
  3204. issue_date = '' # 发布日期
  3205. pinmu_no = '' # 品目号
  3206. pinmu_name = '' # 品目名称
  3207. if len(set([re.sub('[::\s]','',td) for td in tds]) & self.header_set) > len(tds) * 0.4:
  3208. # if len(set(tds) & self.header_set) > len(tds) * 0.2:
  3209. header_dic, found_header, header_list, header_list2 = self.find_header(tds, self.p0, self.p1, self.p2)
  3210. if found_header:
  3211. header_colnum = len(tds) # 保存表头所在行列数
  3212. if found_header and isinstance(header_list, tuple) and len(header_list) > 2: # 获取表头中的 数量单位
  3213. quantity_header = header_list[1].replace('单位:', '')
  3214. if re.search('(([\w/]{,5}))', quantity_header):
  3215. header_quan_unit = re.search('(([\w/]{,5}))', quantity_header).group(1)
  3216. else:
  3217. header_quan_unit = ""
  3218. if found_header and ('_'.join(header_list) not in headers or '_'.join(header_list2) not in headers_demand):# and len(headers)<1: # 只保留出现的第一个表头
  3219. headers.append('_'.join(header_list))
  3220. headers_demand.append('_'.join(header_list2))
  3221. header_col.append('_'.join(tds))
  3222. i += 1
  3223. # print('表头数量占行列数0.4倍不做内容匹配', set([re.sub('[::]','',td) for td in tds]) & self.header_set, tds)
  3224. continue
  3225. elif found_header:
  3226. if len(tds) > header_colnum or len(tds)-1<max([it for it in header_dic.values() if it!=""]): # 表头、属性列数不一致跳过
  3227. i += 1
  3228. # print('表头、属性列数不一致跳过', len(tds), header_colnum, tds)
  3229. continue
  3230. id0 = header_dic.get('品目', "")
  3231. id1 = header_dic.get('名称', "")
  3232. id2 = header_dic.get('数量', "")
  3233. id2_2 = header_dic.get('单位', "")
  3234. id3 = header_dic.get('单价', "")
  3235. id4 = header_dic.get('品牌', "")
  3236. id5 = header_dic.get('规格', "")
  3237. id6 = header_dic.get('需求', "")
  3238. id7 = header_dic.get('预算', "")
  3239. id8 = header_dic.get('时间', "")
  3240. id9 = header_dic.get("总价", "")
  3241. id10 = header_dic.get('参数', "")
  3242. id11 = header_dic.get('采购人', "")
  3243. id12 = header_dic.get('备注', "")
  3244. id13 = header_dic.get('发布日期', "")
  3245. id14 = header_dic.get('品目号', "")
  3246. id15 = header_dic.get('品目名', "")
  3247. not_attr = 0
  3248. for k, v in header_dic.items():
  3249. if isinstance(v, int):
  3250. if v >= len(tds) or tds[v] in self.header_set:
  3251. # print('内容属性在表头集合里面', tds[v], v >= len(tds))
  3252. not_attr = 1
  3253. # break
  3254. if not_attr>=2: # 只要属性里面有两项为表头,停止匹配
  3255. i += 1
  3256. found_header = False
  3257. # print('只要属性里面有两项为表头,停止匹配')
  3258. continue
  3259. if id1!="" and re.search('[a-zA-Z\u4e00-\u9fa5]', tds[id1]) and tds[id1] not in self.header_set and \
  3260. re.search('备注|汇总|合计|总价|价格|金额|^详见|无$|xxx', tds[id1]) == None:
  3261. product = tds[id1]
  3262. if id0!="" and re.search('[a-zA-Z\u4e00-\u9fa5]', tds[id0]) and tds[id0] not in self.header_set and \
  3263. re.search('备注|汇总|合计|总价|价格|金额|^详见|无$|xxx', tds[id0]) == None:
  3264. category = tds[id0]
  3265. product = "%s_%s"%(category, product) if product!="" and product!=category else category
  3266. if product != "" and product not in ['工程类', '服务类', '货物类', '工程', '服务', '货物']:
  3267. # print('匹配产品内容: ', product)
  3268. if id2 != "":
  3269. if re.search('\d+|[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十]', tds[id2]):
  3270. # if re.search('(^\d{,3}(,?\d{3}){2,}(\.\d{2,7},?)$)|万?元', tds[id2]): # 254816100 这篇数量很大,貌似正常
  3271. # i += 1
  3272. # print('过滤:数量包含金额单位或值很大类似金额', tds[id2])
  3273. # continue
  3274. quantity = tds[id2]
  3275. elif re.search('\w{5,}', tds[id2]) and re.search('^详见|^详情', tds[id2])==None:
  3276. i += 1
  3277. # print('过滤:数量包含五个字符以上且不包含^详见|^详情等字符', tds[id2])
  3278. continue
  3279. if id2_2 != "":
  3280. if re.search('^\w{1,4}$', tds[id2_2]) and re.search('元', tds[id2_2])==None:
  3281. quantity_unit = tds[id2_2]
  3282. if id3 != "":
  3283. if re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', tds[id3]):
  3284. unitPrice = tds[id3]
  3285. elif re.search('^[\d,.亿万元人民币欧美日金额:()();;、,\n]+$|¥|¥|RMB|USD|EUR|JPY|CNY|元$', tds[id3].strip()):
  3286. unitPrice = tds[id3]
  3287. elif len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\d,.]', '', tds[id3])) > 5 and re.search('^详见|^详情', tds[id3])==None:
  3288. i += 1
  3289. # print('过滤:产品单价包含金额外的字符数大于5个', tds[id3])
  3290. continue
  3291. if id4 != "":
  3292. if re.search('\w', tds[id4]):
  3293. brand = tds[id4]
  3294. if re.match('^详见|^详情', brand.strip()):
  3295. brand = ""
  3296. else:
  3297. brand = ""
  3298. if id5 != "":
  3299. if re.search('\w', tds[id5]):
  3300. specs = tds[id5][:500] # 限制最多500字
  3301. if re.match('^详见|^详情', specs.strip()):
  3302. specs = ""
  3303. else:
  3304. specs = ""
  3305. if id6 != "":
  3306. if re.search('\w', tds[id6]):
  3307. demand = tds[id6]
  3308. else:
  3309. demand = ""
  3310. if id7 != "":
  3311. if re.search('\d+|[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', tds[id7]):
  3312. budget = tds[id7]
  3313. if id8 != "":
  3314. if re.search('\w', tds[id8]):
  3315. order_time = tds[id8].strip()
  3316. order_begin, order_end = self.fix_time(order_time, html, page_time)
  3317. if id9 != "":
  3318. if re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', tds[id9]):
  3319. total_price = tds[id9]
  3320. elif re.search('^[\d,.亿万元人民币欧美日金额:()();;、,\n]+$|¥|¥|RMB|USD|EUR|JPY|CNY|元$', tds[id9].strip()):
  3321. total_price = tds[id9]
  3322. elif len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\d,.]', '', tds[id9])) > 5 and re.search('^详见|^详情', tds[id9])==None:
  3323. i += 1
  3324. # print('过滤:产品总价包含金额外的字符数大于5个', tds[id9])
  3325. continue
  3326. if id10 != "":
  3327. parameter = tds[id10][:500]
  3328. if re.match('^详见|^详情', parameter.strip()):
  3329. parameter = ""
  3330. if id11 != "":
  3331. tenderee = re.sub("\s","",tds[id11])
  3332. if len(tenderee) > 30:
  3333. tenderee = ""
  3334. if id12 != "":
  3335. notes = tds[id12].strip()
  3336. if id13 != "":
  3337. issue_date = self.fix_time(tds[id13].strip(), '', '')[0]
  3338. if id14 != "":
  3339. pinmu_no = tds[id14].strip()
  3340. if id15 != "":
  3341. pinmu_name = tds[id15].strip()
  3342. # print('数量:{0}, 单价:{1}, 品牌:{2}, 规格:{3},总价:{4}'.format(quantity ,unitPrice, brand, specs, total_price))
  3343. if quantity != "" or unitPrice != "" or brand != "" or specs != "" or total_price or '单价' in header_dic or '总价' in header_dic:
  3344. if id1!="" and id2 != "" and id3 != "" and len(re.split('[;;、,\n]+', tds[id2])) > 1 and len(re.split('[;;、,\n]+', tds[id1])) == len(re.split('[;;、,\n]+', tds[id2])): # 处理一个空格包含多个产品,逗号或空格分割情况 例子 292846806 292650743
  3345. products = re.split('[;;、,\n]+', tds[id1])
  3346. quantitys = re.split('[;;、,\n]+', tds[id2])
  3347. unitPrices = re.split('[;;、,\n]+', tds[id3])
  3348. total_prices = re.split('[;;、,\n]+', total_price)
  3349. brands = re.split('[;;、,\n]+', brand) if re.search('等$', brand)==None else [brand]
  3350. specses = re.split('[;;、,\n]+', specs) if re.search('等$', specs)==None else [specs]
  3351. parameters = re.split('[;;、,\n]+', parameter) if re.search('等$', parameter)==None else [parameter]
  3352. unitPrices = [""]*len(products) if len(unitPrices)==1 else unitPrices
  3353. total_prices = [""]*len(products) if len(total_prices)==1 else total_prices
  3354. brands = brands*len(products) if len(brands)==1 else brands
  3355. specses = specses*len(products) if len(specses)==1 else specses
  3356. brands = [brand]*len(products) if len(brands) < len(products) else brands
  3357. specses = [specs] * len(products) if len(specses) < len(products) else specses
  3358. parameters = parameters*len(products) if len(parameters)==1 else parameters
  3359. # print('产品拆分:', len(products),len(quantitys) , len(unitPrices),len(brands),len(specses))
  3360. if len(products) == len(quantitys) == len(unitPrices) == len(brands) == len(specses):
  3361. for product, quantity, unitPrice, brand, specs, total_price, parameter in zip(products,quantitys,unitPrices, brands, specses, total_prices, parameters):
  3362. if quantity != "":
  3363. quantity, quantity_unit_ = self.fix_quantity(quantity, header_quan_unit)
  3364. quantity_unit = quantity_unit_ if quantity_unit_ != "" else quantity_unit
  3365. if unitPrice != "":
  3366. unitPrice, _money_unit = money_process(unitPrice, header_list[3])
  3367. unitPrice = str(unitPrice) if unitPrice != 0 and unitPrice<100000000 else ""
  3368. if budget != "":
  3369. budget, _money_unit = money_process(budget, header_list2[2])
  3370. budget = str(budget) if budget != 0 and budget<50000000000 else ''
  3371. if total_price != "":
  3372. total_price, _money_unit = money_process(total_price, header_list[6])
  3373. total_price_list.append(total_price)
  3374. total_price = str(total_price) if total_price != 0 and total_price<50000000000 else ""
  3375. link = {'product': product, 'quantity': quantity,
  3376. 'quantity_unit': quantity_unit, 'unitPrice': unitPrice,
  3377. 'brand': brand[:50], 'specs': specs, 'total_price': total_price, 'parameter': parameter}
  3378. # if link not in product_link:
  3379. # product_link.append(link)
  3380. # mat = re.match('([0-9.,]+)[((]?\w{,3}[))]?$', link['quantity'])
  3381. # if link['unitPrice'] != "" and mat:
  3382. # try:
  3383. # total_product_money += float(link['unitPrice']) * float(
  3384. # mat.group(1).replace(',', '')) if float(
  3385. # mat.group(1).replace(',', '')) < 50000 else 0
  3386. # except:
  3387. # log('产品属性单价数量相乘出错, 单价: %s, 数量: %s' % (
  3388. # link['unitPrice'], link['quantity']))
  3389. if (product, specs, unitPrice, quantity) not in product_set:
  3390. product_set.add((product, specs, unitPrice, quantity))
  3391. product_link.append(link)
  3392. if link['unitPrice'] != "" and link['quantity'] != '':
  3393. try:
  3394. total_product_money += float(link['unitPrice']) * float(
  3395. link['quantity']) if float(link['quantity']) < 50000 else 0
  3396. except:
  3397. log('产品属性单价数量相乘出错, 单价: %s, 数量: %s' % (
  3398. link['unitPrice'], link['quantity']))
  3399. elif len(product)>100: # 产品名称长于100字
  3400. i += 1
  3401. # print('过滤: 产品名称长于100字',)
  3402. continue
  3403. else:
  3404. if quantity != "":
  3405. quantity, quantity_unit_ = self.fix_quantity(quantity, header_quan_unit)
  3406. quantity_unit = quantity_unit_ if quantity_unit_ != "" else quantity_unit
  3407. if unitPrice != "":
  3408. unitPrice, _money_unit = money_process(unitPrice, header_list[3])
  3409. unitPrice = str(unitPrice) if unitPrice != 0 and unitPrice<100000000 else ""
  3410. if budget != "":
  3411. budget, _money_unit = money_process(budget, header_list2[2])
  3412. budget = str(budget) if budget != 0 and budget<50000000000 else ''
  3413. if total_price != "":
  3414. total_price, _money_unit = money_process(total_price, header_list[6])
  3415. total_price_list.append(total_price)
  3416. total_price = str(total_price) if total_price != 0 and total_price<50000000000 else ""
  3417. link = {'product': product, 'quantity': quantity, 'quantity_unit': quantity_unit, 'unitPrice': unitPrice,
  3418. 'brand': brand[:50], 'specs':specs, 'total_price': total_price, 'parameter': parameter,
  3419. 'pinmu_no': pinmu_no, 'pinmu_name': pinmu_name}
  3420. # if link not in product_link:
  3421. # product_link.append(link)
  3422. # mat = re.match('([0-9.,]+)[((]?\w{,3}[))]?$', link['quantity'])
  3423. # if link['unitPrice'] != "" and mat:
  3424. # try:
  3425. # total_product_money += float(link['unitPrice'])*float(mat.group(1).replace(',', '')) if float(mat.group(1).replace(',', ''))<50000 else 0
  3426. # except:
  3427. # log('产品属性单价数量相乘出错, 单价: %s, 数量: %s'%(link['unitPrice'], link['quantity']))
  3428. # if (product, unitPrice, quantity) not in product_set:
  3429. # product_set.add((product, unitPrice, quantity))
  3430. if (product, unitPrice,) not in product_set: # 2023/09/22 改为只判断产品/单价,只要两个一样就不作为新产品 避免多个表格重复表达有些没数量造成重复提取 353858683
  3431. product_set.add((product, unitPrice))
  3432. product_link.append(link)
  3433. if link['unitPrice']:
  3434. unit_price_list.append(link['unitPrice'])
  3435. if link['unitPrice'] != "" and link['quantity'] != '':
  3436. try:
  3437. total_product_money += float(link['unitPrice'])*float(link['quantity']) if float(link['quantity'])<50000 else 0
  3438. if float(link['unitPrice'])>10000 and float(link['quantity'])>100: # 修复 325105750 总价做单价 造成中标金额错误
  3439. total_product_money = 0
  3440. except:
  3441. log('产品属性单价数量相乘出错, 单价: %s, 数量: %s'%(link['unitPrice'], link['quantity']))
  3442. if order_begin != "" and order_end != "":
  3443. order_begin_year = int(order_begin.split("-")[0])
  3444. order_end_year = int(order_end.split("-")[0])
  3445. # 限制附件错误识别时间
  3446. if order_begin_year >= 2050 or order_end_year >= 2050:
  3447. order_begin = order_end = ""
  3448. # print(budget,order_time)
  3449. if budget != "" and order_time != "":
  3450. link = {'project_name': product, 'product':[], 'demand': demand, 'budget': budget, 'order_begin':order_begin, 'order_end':order_end, 'tenderee':tenderee,'notes':notes,'issue_date':issue_date}
  3451. if link not in demand_link:
  3452. demand_link.append(link)
  3453. i += 1
  3454. else:
  3455. i += 1
  3456. if len(total_price_list)>1 and len(set(total_price_list))/len(total_price_list)<=0.5: # 2023/7/27 总价一半以上重复的为多行一个总价,需去掉
  3457. # print('总价一半以上重复的为多行一个总价,需去掉', total_price_list)
  3458. for link in product_link: # 预防最后一列总价为所有产品总价,列补全后所有产品总价一样情况
  3459. if 'total_price' in link:
  3460. link['total_price'] = ""
  3461. if len(unit_price_list)>0 and len(unit_price_list)==len(product_link) and len(set(unit_price_list))/len(unit_price_list)<=0.5: # 2023/7/18 如果单价重复率高不算总产品价避免错误
  3462. # print('如果单价重复率高不算总产品价避免错误')
  3463. total_product_money = 0
  3464. # for link in product_link:
  3465. # if 'unitPrice' in link:
  3466. # link['unitPrice'] = ""
  3467. if len(product_link)>0:
  3468. product_link = [{k:v for k,v in d.items() if v!=''} for d in product_link]
  3469. attr_dic = {'product_attrs':{'data':product_link, 'header':headers, 'header_col':header_col}}
  3470. else:
  3471. attr_dic = {'product_attrs': {'data': [], 'header': [], 'header_col': []}}
  3472. if len(demand_link)>0:
  3473. demand_link = [{k: v for k, v in d.items() if v != ''} for d in demand_link]
  3474. demand_dic = {'demand_info':{'data':demand_link, 'header':headers_demand, 'header_col':header_col}}
  3475. else:
  3476. demand_dic = {'demand_info':{'data':[], 'header':[], 'header_col':[]}}
  3477. # print('表格产品属性提取:', attr_dic)
  3478. return [attr_dic, demand_dic], total_product_money
  3479. def predict_without_table(self,product_attrs,list_sentences,list_entitys,codeName,prem, html='', page_time=""):
  3480. if len(prem[0]['prem'])==1:
  3481. list_sentences[0].sort(key=lambda x:x.sentence_index)
  3482. list_sentence = list_sentences[0]
  3483. list_entity = list_entitys[0]
  3484. _data = product_attrs[1]['demand_info']['data']
  3485. re_bidding_time = re.compile("(采购|采购实施|预计招标)(时间|月份|日期)[::,].{0,2}$")
  3486. order_times = []
  3487. for entity in list_entity:
  3488. if entity.entity_type=='time':
  3489. sentence = list_sentence[entity.sentence_index]
  3490. s = spanWindow(tokens=sentence.tokens, begin_index=entity.begin_index,
  3491. end_index=entity.end_index,size=20)
  3492. entity_left = "".join(s[0])
  3493. if re.search(re_bidding_time,entity_left):
  3494. time_text = entity.entity_text.strip()
  3495. standard_time = re.compile("((?P<year>\d{4}|\d{2})\s*[-\/年\.]\s*(?P<month>\d{1,2})\s*[-\/月\.]\s*((?P<day>\d{1,2})日?)?)")
  3496. time_match = re.search(standard_time,time_text)
  3497. # print(time_text, time_match)
  3498. if time_match:
  3499. time_text = time_match.group()
  3500. order_times.append(time_text)
  3501. # print(order_times)
  3502. order_times = [tuple(self.fix_time(order_time, html, page_time)) for order_time in order_times]
  3503. order_times = [order_time for order_time in order_times if order_time[0]!=""]
  3504. if len(set(order_times))==1:
  3505. order_begin,order_end = order_times[0]
  3506. project_name = codeName[0]['name']
  3507. pack_info = [pack for pack in prem[0]['prem'].values()]
  3508. budget = pack_info[0].get('tendereeMoney',0)
  3509. product = prem[0]['product']
  3510. link = {'project_name': project_name, 'product': product, 'demand': project_name, 'budget': budget,
  3511. 'order_begin': order_begin, 'order_end': order_end}
  3512. _data.append(link)
  3513. product_attrs[1]['demand_info']['data'] = _data
  3514. # print('predict_without_table: ', product_attrs)
  3515. return product_attrs
  3516. def predict_by_text(self,product_attrs,html,list_outlines,product_list,page_time=""):
  3517. product_entity_list = list(set(product_list))
  3518. list_outline = list_outlines[0]
  3519. get_product_attrs = False
  3520. for _outline in list_outline:
  3521. if re.search("信息|情况|清单|概况",_outline.outline_summary):
  3522. outline_text = _outline.outline_text
  3523. outline_text = outline_text.replace(_outline.outline_summary,"")
  3524. key_value_list = [_split for _split in re.split("[,。;]",outline_text) if re.search("[::]",_split)]
  3525. if not key_value_list:
  3526. continue
  3527. head_list = []
  3528. head_value_list = []
  3529. for key_value in key_value_list:
  3530. key_value = re.sub("^[一二三四五六七八九十]{1,3}[、.]|^[\d]{1,2}[、.]\d{,2}|^[\((]?[一二三四五六七八九十]{1,3}[\))][、]?","",key_value)
  3531. temp = re.split("[::]",key_value)
  3532. if len(temp)>2:
  3533. if temp[0] in head_list:
  3534. key = temp[0]
  3535. value = "".join(temp[1:])
  3536. else:
  3537. key = temp[-2]
  3538. value = temp[-1]
  3539. else:
  3540. key = temp[0]
  3541. value = temp[1]
  3542. key = re.sub("^[一二三四五六七八九十]{1,3}[、.]|^[\d]{1,2}[、.]\d{,2}|^[\((]?[一二三四五六七八九十]{1,3}[\))][、]?","",key)
  3543. head_list.append(key)
  3544. head_value_list.append(value)
  3545. head_set = set(head_list)
  3546. # print('head_set',head_set)
  3547. if len(head_set & self.header_set) > len(head_set)*0.2:
  3548. loop_list = []
  3549. begin_list = [0]
  3550. for index,head in enumerate(head_list):
  3551. if head not in loop_list:
  3552. if re.search('第[一二三四五六七八九十](包|标段)', head) and re.search('第[一二三四五六七八九十](包|标段)', '|'.join(loop_list)):
  3553. begin_list.append(index)
  3554. loop_list = []
  3555. loop_list.append(head)
  3556. else:
  3557. loop_list.append(head)
  3558. else:
  3559. begin_list.append(index)
  3560. loop_list = []
  3561. loop_list.append(head)
  3562. headers = []
  3563. headers_demand = []
  3564. header_col = []
  3565. product_link = []
  3566. demand_link = []
  3567. product_set = set()
  3568. for idx in range(len(begin_list)):
  3569. if idx==len(begin_list)-1:
  3570. deal_list = head_value_list[begin_list[idx]:]
  3571. tmp_head_list = head_list[begin_list[idx]:]
  3572. else:
  3573. deal_list = head_value_list[begin_list[idx]:begin_list[idx+1]]
  3574. tmp_head_list = head_list[begin_list[idx]:begin_list[idx+1]]
  3575. product = "" # 产品
  3576. quantity = "" # 数量
  3577. quantity_unit = "" # 单位
  3578. unitPrice = "" # 单价
  3579. brand = "" # 品牌
  3580. specs = "" # 规格
  3581. demand = "" # 采购需求
  3582. budget = "" # 预算金额
  3583. order_time = "" # 采购时间
  3584. order_begin = ""
  3585. order_end = ""
  3586. total_price = "" # 总金额
  3587. parameter = "" # 参数
  3588. header_dic, found_header, header_list, header_list2 = self.find_header(tmp_head_list, self.p0, self.p1,self.p2)
  3589. if found_header:
  3590. headers.append('_'.join(header_list))
  3591. headers_demand.append('_'.join(header_list2))
  3592. header_col.append('_'.join(tmp_head_list))
  3593. # print('header_dic: ',header_dic)
  3594. id0 = header_dic.get('品目', "")
  3595. id1 = header_dic.get('名称', "")
  3596. id2 = header_dic.get('数量', "")
  3597. id2_2 = header_dic.get('单位', "")
  3598. id3 = header_dic.get('单价', "")
  3599. id4 = header_dic.get('品牌', "")
  3600. id5 = header_dic.get('规格', "")
  3601. id6 = header_dic.get('需求', "")
  3602. id7 = header_dic.get('预算', "")
  3603. id8 = header_dic.get('时间', "")
  3604. id9 = header_dic.get("总价", "")
  3605. id10 = header_dic.get('参数', "")
  3606. if id1!='' and re.search('[a-zA-Z\u4e00-\u9fa5]', deal_list[id1]) and deal_list[id1] not in self.header_set and \
  3607. re.search('备注|汇总|合计|总价|价格|金额|公司|附件|详见|无$|xxx', deal_list[id1]) == None:
  3608. product = deal_list[id1]
  3609. if id0 != "" and re.search('[a-zA-Z\u4e00-\u9fa5]', deal_list[id0]) and deal_list[id0] not in self.header_set and \
  3610. re.search('备注|汇总|合计|总价|价格|金额|公司|附件|详见|无$|xxx', deal_list[id0]) == None:
  3611. category = deal_list[id0]
  3612. product = "%s_%s" % (category, product) if product != "" else category
  3613. if product == "":
  3614. # print(deal_list[id4],deal_list[id5],tmp_head_list,deal_list)
  3615. if (id4 != "" and deal_list[id4] != "") or (id5 != "" and deal_list[id5] != ""):
  3616. for head,value in zip(tmp_head_list,deal_list):
  3617. if value and value in product_entity_list:
  3618. product = value
  3619. break
  3620. if product != "":
  3621. if id2 != "":
  3622. if re.search('\d+|[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十]', deal_list[id2]):
  3623. quantity = deal_list[id2]
  3624. quantity = re.sub('[()(),,约]', '', quantity)
  3625. quantity = re.sub('[一壹]', '1', quantity)
  3626. ser = re.search('^(\d+(?:\.\d+)?)([㎡\w/]{,5})', quantity)
  3627. if ser:
  3628. quantity = str(ser.group(1))
  3629. quantity_unit = ser.group(2)
  3630. if float(quantity)>=10000*10000:
  3631. quantity = ""
  3632. quantity_unit = ""
  3633. else:
  3634. quantity = ""
  3635. quantity_unit = ""
  3636. if id2_2 != "":
  3637. if re.search('^\w{1,4}$', deal_list[id2_2]):
  3638. quantity_unit = deal_list[id2_2]
  3639. else:
  3640. quantity_unit = ""
  3641. # if id2 != "":
  3642. # if re.search('\d+|[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十]', deal_list[id2]):
  3643. # quantity = deal_list[id2]
  3644. # else:
  3645. # quantity = ""
  3646. if id3 != "":
  3647. if re.search('\d+|[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', deal_list[id3]):
  3648. _unitPrice = deal_list[id3]
  3649. re_price = re.findall("[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,}|\d[\d,]*(?:\.\d+)?万?",_unitPrice)
  3650. if re_price:
  3651. # _unitPrice = re_price[0]
  3652. # if '万元' in header_list[3] and '万' not in _unitPrice:
  3653. # _unitPrice += '万元'
  3654. # unitPrice = getUnifyMoney(_unitPrice)
  3655. # if unitPrice>=10000*10000:
  3656. # unitPrice = ""
  3657. # unitPrice = str(unitPrice)
  3658. _unitPrice, _money_unit = money_process(_unitPrice, header_list[3])
  3659. if _unitPrice >= 10000 * 10000:
  3660. _unitPrice = ""
  3661. unitPrice = str(_unitPrice)
  3662. if '.' in unitPrice:
  3663. unitPrice = unitPrice.rstrip('0').rstrip('.')
  3664. if id4 != "":
  3665. if re.search('\w', deal_list[id4]):
  3666. brand = deal_list[id4]
  3667. if re.match('^详见|^详情', brand.strip()):
  3668. brand = ""
  3669. else:
  3670. brand = ""
  3671. if id5 != "":
  3672. if re.search('\w', deal_list[id5]):
  3673. specs = deal_list[id5][:500]
  3674. if re.match('^详见|^详情', specs.strip()):
  3675. brand = ""
  3676. else:
  3677. specs = ""
  3678. if id6 != "":
  3679. if re.search('\w', deal_list[id6]):
  3680. demand = deal_list[id6]
  3681. else:
  3682. demand = ""
  3683. if id7 != "":
  3684. if re.search('\d+|[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', deal_list[id7]):
  3685. _budget = deal_list[id7]
  3686. re_price = re.findall("[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,}|\d[\d,]*(?:\.\d+)?万?",_budget)
  3687. if re_price:
  3688. # _budget = re_price[0]
  3689. # if '万元' in header_list2[2] and '万' not in _budget:
  3690. # _budget += '万元'
  3691. # budget = str(getUnifyMoney(_budget))
  3692. _budget, _money_unit = money_process(_budget, header_list2[2])
  3693. budget = str(_budget)
  3694. if '.' in budget:
  3695. budget = budget.rstrip('0').rstrip('.')
  3696. if float(budget)>= 100000*10000:
  3697. budget = ""
  3698. if id8 != "":
  3699. if re.search('\w', deal_list[id8]) and re.search("(采购|采购实施|预计招标)(时间|月份|日期)",header_list2[3]):
  3700. order_time = deal_list[id8].strip()
  3701. order_begin, order_end = self.fix_time(order_time, html, page_time)
  3702. if id9 != "":
  3703. if re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', deal_list[id9]):
  3704. total_price = deal_list[id9]
  3705. elif re.search('^[\d,.亿万元人民币欧美日金额:()();;、,\n]+$', deal_list[id9].strip()):
  3706. total_price = deal_list[id9]
  3707. if id10 != "":
  3708. parameter = deal_list[id10][:500]
  3709. if re.match('^详见|^详情', parameter.strip()):
  3710. parameter = ""
  3711. if quantity != "" or unitPrice != "" or brand != "" or specs != "" or total_price:
  3712. if id1 != "" and id2 != "" and id3 != "" and len(re.split('[;;、,\n]', deal_list[id2])) > 1 and len(
  3713. re.split('[;;、,\n]', deal_list[id1])) == len(re.split('[;;、,\n]', deal_list[id2])): # 处理一个空格包含多个产品,逗号或空格分割情况 例子 292846806 292650743
  3714. products = re.split('[;;、,\n]', deal_list[id1])
  3715. quantitys = re.split('[;;、,\n]', deal_list[id2])
  3716. unitPrices = re.split('[;;、,\n]', deal_list[id3])
  3717. total_prices = re.split('[;;、,\n]', total_price)
  3718. brands = re.split('[;;、,\n]', brand) if re.search('等$', brand) == None else [brand]
  3719. specses = re.split('[;;、,\n]', specs) if re.search('等$', specs) == None else [specs]
  3720. parameters = re.split('[;;、,\n]', parameter) if re.search('等$', parameter) == None else [parameter]
  3721. unitPrices = [""] * len(products) if len(unitPrices) == 1 else unitPrices
  3722. total_prices = [""] * len(products) if len(total_prices) == 1 else total_prices
  3723. brands = brands * len(products) if len(brands) == 1 else brands
  3724. specses = specses * len(products) if len(specses) == 1 else specses
  3725. parameters = parameters * len(products) if len(parameters) == 1 else parameters
  3726. if len(products) == len(quantitys) == len(unitPrices) == len(brands) == len(
  3727. specses):
  3728. for product, quantity, unitPrice, brand, specs, total_price, parameter in zip(
  3729. products, quantitys, unitPrices, brands, specses, total_prices,
  3730. parameters):
  3731. if quantity != "":
  3732. quantity, quantity_unit_ = self.fix_quantity(quantity,quantity_unit)
  3733. quantity_unit = quantity_unit_ if quantity_unit_ != "" else quantity_unit
  3734. if unitPrice != "":
  3735. unitPrice, _money_unit = money_process(unitPrice, header_list[3])
  3736. unitPrice = str(unitPrice) if unitPrice != 0 and unitPrice<100000000 else ""
  3737. if budget != "":
  3738. budget, _money_unit = money_process(budget, header_list2[2])
  3739. budget = str(budget) if budget != 0 and budget<50000000000 else ''
  3740. if total_price != "":
  3741. total_price, _money_unit = money_process(total_price,
  3742. header_list[6])
  3743. total_price = str(total_price) if total_price != 0 and total_price<50000000000 else ""
  3744. link = {'product': product, 'quantity': quantity,
  3745. 'quantity_unit': quantity_unit, 'unitPrice': unitPrice,
  3746. 'brand': brand[:50], 'specs': specs, 'total_price': total_price,
  3747. 'parameter': parameter}
  3748. if (product, specs, unitPrice, quantity) not in product_set:
  3749. product_set.add((product, specs, unitPrice, quantity))
  3750. product_link.append(link)
  3751. # if link['unitPrice'] != "" and link['quantity'] != '':
  3752. # try:
  3753. # total_product_money += float(link['unitPrice']) * float(
  3754. # link['quantity']) if float(
  3755. # link['quantity']) < 50000 else 0
  3756. # except:
  3757. # log('产品属性单价数量相乘出错, 单价: %s, 数量: %s' % (
  3758. # link['unitPrice'], link['quantity']))
  3759. elif len(unitPrice) > 15 or len(product) > 100: # 单价大于15位数或 产品名称长于100字
  3760. # i += 1
  3761. continue
  3762. else:
  3763. if quantity != "":
  3764. quantity, quantity_unit_ = self.fix_quantity(quantity, quantity_unit)
  3765. quantity_unit = quantity_unit_ if quantity_unit_ != "" else quantity_unit
  3766. if unitPrice != "":
  3767. unitPrice, _money_unit = money_process(unitPrice, header_list[3])
  3768. unitPrice = str(unitPrice) if unitPrice != 0 and unitPrice<100000000 else ""
  3769. if budget != "":
  3770. budget, _money_unit = money_process(budget, header_list2[2])
  3771. budget = str(budget) if budget != 0 and budget<50000000000 else ''
  3772. if total_price != "":
  3773. total_price, _money_unit = money_process(total_price, header_list[6])
  3774. total_price = str(total_price) if total_price != 0 and total_price<50000000000 else ""
  3775. link = {'product': product, 'quantity': quantity,
  3776. 'quantity_unit': quantity_unit, 'unitPrice': unitPrice,
  3777. 'brand': brand[:50], 'specs': specs, 'total_price': total_price,
  3778. 'parameter': parameter}
  3779. if (product, specs, unitPrice, quantity) not in product_set:
  3780. product_set.add((product, specs, unitPrice, quantity))
  3781. product_link.append(link)
  3782. # if link['unitPrice'] != "" and link['quantity'] != '':
  3783. # try:
  3784. # total_product_money += float(link['unitPrice']) * float(
  3785. # link['quantity']) if float(link['quantity']) < 50000 else 0
  3786. # except:
  3787. # log('产品属性单价数量相乘出错, 单价: %s, 数量: %s' % (
  3788. # link['unitPrice'], link['quantity']))
  3789. if order_begin != "" and order_end != "":
  3790. order_begin_year = int(order_begin.split("-")[0])
  3791. order_end_year = int(order_end.split("-")[0])
  3792. # 限制附件错误识别时间
  3793. if order_begin_year >= 2050 or order_begin_year < 2000 or order_end_year >= 2050 or order_end_year < 2000:
  3794. order_begin = order_end = ""
  3795. # print(budget, order_time)
  3796. if budget != "" and order_time != "":
  3797. link = {'project_name': product, 'product': [], 'demand': demand, 'budget': budget,
  3798. 'order_begin': order_begin, 'order_end': order_end}
  3799. if link not in demand_link:
  3800. demand_link.append(link)
  3801. if len(product_link) > 0:
  3802. attr_dic = {'product_attrs': {'data': product_link, 'header': list(set(headers)), 'header_col': list(set(header_col))}}
  3803. get_product_attrs = True
  3804. else:
  3805. attr_dic = {'product_attrs': {'data': [], 'header': [], 'header_col': []}}
  3806. if len(demand_link) > 0:
  3807. demand_dic = {'demand_info': {'data': demand_link, 'header': headers_demand, 'header_col': header_col}}
  3808. else:
  3809. demand_dic = {'demand_info': {'data': [], 'header': [], 'header_col': []}}
  3810. product_attrs[0] = attr_dic
  3811. if len(product_attrs[1]['demand_info']['data']) == 0:
  3812. product_attrs[1] = demand_dic
  3813. if get_product_attrs:
  3814. break
  3815. # print('predict_by_text: ', product_attrs)
  3816. return product_attrs
  3817. def add_product_attrs(self,channel_dic, product_attrs, list_sentences,list_entitys,list_outlines,product_list,codeName,prem,text,page_time):
  3818. # print(1,product_attrs[1]['demand_info']['data'])
  3819. if channel_dic['docchannel']['docchannel']=="采购意向" and len(product_attrs[1]['demand_info']['data']) == 0:
  3820. product_attrs = self.predict_without_table(product_attrs, list_sentences,list_entitys,codeName,prem,text,page_time)
  3821. # print(2,product_attrs[1]['demand_info']['data'])
  3822. if len(product_attrs[0]['product_attrs']['data']) == 0:
  3823. product_attrs = self.predict_by_text(product_attrs,text,list_outlines,product_list,page_time)
  3824. # print(3,product_attrs[1]['demand_info']['data'])
  3825. if len(product_attrs[1]['demand_info']['data'])>0:
  3826. for d in product_attrs[1]['demand_info']['data']:
  3827. for product in set(prem[0]['product']):
  3828. if product in d['project_name'] and product not in d['product']:
  3829. d['product'].append(product) #把产品在项目名称中的添加进需求要素中
  3830. # docchannel类型提取
  3831. class DocChannel():
  3832. def __init__(self, life_model='/channel_savedmodel/channel.pb', type_model='/channel_savedmodel/doctype.pb',config=None):
  3833. self.lift_sess, self.lift_title, self.lift_content, self.lift_prob, self.lift_softmax,\
  3834. self.mask, self.mask_title = self.load_life(life_model,config)
  3835. self.type_sess, self.type_title, self.type_content, self.type_prob, self.type_softmax,\
  3836. self.type_mask, self.type_mask_title = self.load_type(type_model)
  3837. self.sequen_len = 200 # 150 200
  3838. self.title_len = 30
  3839. self.sentence_num = 10
  3840. self.kws = '供货商|候选人|供应商|入选人|项目|选定|预告|中标|成交|补遗|延期|报名|暂缓|结果|意向|出租|补充|合同|限价|比选|指定|工程|废标|取消|中止|流标|资质|资格|地块|招标|采购|货物|租赁|计划|宗地|需求|来源|土地|澄清|失败|探矿|预审|变更|变卖|遴选|撤销|意见|恢复|采矿|更正|终止|废置|报建|流拍|供地|登记|挂牌|答疑|中选|受让|拍卖|竞拍|审查|入围|更改|条件|洽谈|乙方|后审|控制|暂停|用地|询价|预'
  3841. lb_type = ['采招数据', '土地矿产', '拍卖出让', '产权交易', '新闻资讯']
  3842. lb_life = ['采购意向', '招标预告', '招标公告', '招标答疑', '公告变更', '资审结果', '中标信息', '合同公告', '废标公告']
  3843. self.id2type = {k: v for k, v in enumerate(lb_type)}
  3844. self.id2life = {k: v for k, v in enumerate(lb_life)}
  3845. self.load_pattern()
  3846. def load_pattern(self):
  3847. self.type_dic = {
  3848. '土地矿产': '供地结果|(土地|用地|宗地|地块|海域|矿)的?(基本信息|基本情况|概况|信息|详情|来源|用途|性质|编号|位置|坐落|使用年限|出让年限)|(土地|山地|农田)(经营权)?(出让|出租|招租|租赁|承包|流转)|流转土地',
  3849. '拍卖出让': '(拍卖|变卖|流拍|竞拍)的?(公告|活动|信息|结果|成交|主体|标的|资产|财产|方式|类型|流程|程序|规则|价格|保证金|时间)|(公开|进行|密封)(拍卖|变卖|竞拍)|第[一二三]次拍卖|(资产|司法|网络)拍卖|交易方式.{,2}拍卖|拍卖会',
  3850. '产权交易': '(产权|资产|权证)的?(类型|类别|用途|性质|状态|信息|名称|编号|(基本)?情况)|(经营权|承包权|使用权|租赁权|股权|债权|排污权|化学需氧量|储备量)(挂牌|转让|出让)|竞价销售|销售结果|房屋所有权房产|免租期限|交易期限|(受让|转让|承租|出租)(人|方)|(店面|店铺|商铺|铺位?|门面|门市|食堂|饭堂|校舍|车位|停车场|厂?房|仓?库|馆|资产|物业|房产|房屋|场地|农田|鱼?塘)\w{,4}(处置|招租|出租|续租|租赁|转让)|(出租|转让|产权|资产)(项目|中标|成交|流标|废标)|出租(用途|类型)|转让底价|租赁(标的物|情况)|看[样货](时间|地[点址]|方式|仓库|验货)|最小加价|加价[幅梯]度|交易模式[::\s]*延时竞价销售|挂牌(开始|结束)时间',
  3851. '采招数据': '(采购|招标)(条件|范围|文件|内容)|(申请人|投标人|供应商|报价人|参选人)的?资格要求;|采购需求清单|最低价排序|竞争性采购方式|采购进行公开竞价|竞价模式[::\s]*一次报价|预算金额' # |变更|答疑|澄清|中标|成交|合同|废标|流标 |(采购|招标|代理)(人|机构|单位)|
  3852. }
  3853. self.title_type_dic = {
  3854. '土地矿产': '(土地|用地|宗地|荒地|山地|海域|矿)(出让|出租|招租|租赁|承包|流转|使用权|经营权|征收|划拨|中标|成交)|供地结果|矿业权|探矿权|采矿权|(土地|用地|宗地|地块)(使用权)?(终止|中止|网上)?(挂牌|出让|拍卖|招拍|划拨)|征收土地',
  3855. '拍卖出让': '(拍卖|变卖|流拍|竞拍)的?(公告|公示)|拍卖|变卖|流拍|竞拍',
  3856. '产权交易': '经营权|承包权|使用权|租赁权|股权|债权|排污权|化学需氧量|储备量|竞价销售|销售结果|出租|招租|拍租|竞租|续租|挂牌|出让',
  3857. '采招数据': '(采购|招标|询价|议价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|征询|调研)的?(公告|公示|中标|成交|结果|$)|工程招标|定点服务|(设备|服务|\w{2})[直采]购|(建设|改造)项目|工程|拦标价|控制价',
  3858. # |竞价 采招/产权都有竞价方式 # 意向|需求|预公?告|报建|总承包|工程|施工|设计|勘察|代理|监理 |变更|答疑|澄清|中标|成交|合同|废标|流标
  3859. '新闻资讯': '(考试|面试|笔试)成绩|成绩的?(公告|公示|公布)|公开招聘|招聘(公告|简章|启事|合同制)|疫情防控\s{,5}(通知|情况|提示)|行政审批结果'
  3860. }
  3861. self.life_dic = {
  3862. '采购意向': '采购意向|招标意向|选取意向|意向公告|意向公示',
  3863. '采购意向neg': '发布政府采购意向|采购意向公告已于',
  3864. '招标预告': '(预计|计划)(采购|招标)(时间|日期)|采购(计划编号|需求方案|预告|预案)|(预|需求)公示|需求(方案|信息|论证|公告|公示)',
  3865. '招标公告': '(采购|招标|竞选|报名)条件|报名(时间|流程|方法|要求|\w{,5}材料)[:\s]|[^\w]成交规则|参加竞价采购交易资格|(申请人|投标人|供应商|报价人|参选人)的?资格(要求|条件)|获取(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|竞谈|应答)文件|(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|竞谈|应答)文件的?(获取|领取)|评选方式:?\s*价格最低',
  3866. '资审结果': '资审及业绩公示|资审结果及业绩|资格后审情况报告|资格(后审|预审|审查)结果(公告|公示)|(预审|审查)工作已经?结束|未通过原因', #|资格
  3867. '招标答疑': '现澄清(为|如下)|答疑补遗|澄清内容如下|第[0-9一二三四五]次澄清|答疑澄清|(最高(投标)?限价|控制价|拦标价)公示', # |异议的回复
  3868. '公告变更': '第[\d一二]次变更|(更正|变更)(公告|公示|信息|内容|事项|原因|理由|日期|时间|如下)|原公告((主要)?(信息|内容)|发布时间)|(变更|更正)[前后]内容|现?在?(变更|更正|修改|更改)(内容)?为|(公告|如下|信息|内容|事项|结果|文件|发布|时间|日期)(更正|变更)',
  3869. '公告变更neg': '履约变更内容',
  3870. '候选人公示': '候选人公示|评标结果公示|中标候选人名单公示|现将中标候选人(进行公示|公[示布]如下)|(中标|中选)候选人(信息|情况)[::\s]',
  3871. '候选人公示neg': '中标候选人公示期|中标候选人公示前',
  3872. '中标信息': '供地结果信息|采用单源直接采购的?情况说明|[特现]?将\w{,4}(成交|中标|中选|选定结果|选取结果|入围结果|竞价结果)\w{,4}(进行公示|公[示布]如下)|(询价|竞价|遴选)?(成交|中标|中选)(公告|公示)|(成交|中标|中选|选定|选取|入围|询价)结果(如下|公告|公示)|(中标|中选)(供应商|承包商|候选人|入围单位)如下|拟定供应商的情况|((中标|中选)(人|成交)|成交)\w{,3}(信息|情况)[::\s]',
  3873. '中标信息2': '\s(成交|中标|中选)(信息|日期|时间|总?金额|价格)[::\s]|(成交|中标|中选)价格\s*[\d.,]+(?万?元|(采购|招标|成交|中标|中选|评标)结果|单一来源(采购|招标)?的?(中标|成交|结果)|项目已结束|中标公示 ', # |单一来源采购原因|拟采取单一来源方式采购|单一来源采购公示
  3874. '中标信息3': '(中标|中选|成交|拟定|拟选用|最终选定的?|受让)(供应商|供货商|服务商|机构|企业|公司|单位|候选人|人)(信息[,:]?)?(名称)?[::\s]|[、\s](第一名|(拟定|推荐|入围)?(供应商|供货商)|(中选|中标|供货)单位|中选人)[::\s]|确定[\w()]{6,25}为中标人', # |唯一
  3875. '中标信息neg': '按项目控制价下浮\d%即为成交价|成交原则|不得确定为(中标|成交)|招标人按下列原则选择中标人|评选成交供应商:|拟邀请供应商|除单一来源采购项目外|单一来源除外|(各.{,5}|尊敬的)(供应商|供货商)[:\s]|竞拍起止时间:|询价结果[\s\n::]*不公开|本项目已具备招标条件|现对该项目进行招标公告|发布\w{2}结果后\d天内送达|本次\w{2}结果不对外公示|供应商\s*资格要求|成交情况:\s*[流废]标|中标单位:本次招标拟?中标单位\d家|通知中标单位|影响(成交|中标)结果|确定为成交供应商|(成交|中标|中选)公[告示](发布|\w{,2})后|竞价成交后', # 503076535 按照服务方案的优劣 确定为成交供应商
  3876. # |确定成交供应商[:,\s]
  3877. '合同公告': '合同(公告|公示|信息|内容)|合同(编号|名称|主体|基本情况|完成(日期|时间))|(供应商乙方|乙方供应商):|合同总?金额|履约信息',
  3878. '废标公告': '(终止|中止|废标|流标|流采|失败|作废|异常|撤销)(结果)?(公告|公示|招标|采购|竞价)|(谈判结果为|结果类型):?废标|((本|该)(项目|标段|合同|合同包|采购包|次)\w{,5})((失败|终止|流标|废标)|予以废标|(按|做|作)?(流标|废标|废置)处理)|(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|竞谈|应答|项目)(终止|中止|废标|流标|失败|作废|异常|撤销)',
  3879. '废标公告2': '(无效|中止|终止|废标|流标|失败|作废|异常|撤销)的?(原因|理由)|本项目因故取消|本(项目|次)(公开)?\w{2}失败|已终止\s*原因:|(人|人数|供应商|单位)(不足|未达\w{,3}数量)|已终止|不足[3三]家|无(废标)|成交情况:\s*[流废]标|现予以废置|报名未够三家',
  3880. '废标公告neg': '超过此报价将作为[废流]标处理|否则按[废流]标处理|终止规则:|成交规则:|视为流标|竞价失败的一切其他情形|是否废标:否|若不足三家公司参与|供应商数量:?\s*报名供应商不足三家|有效报价不足三家,\s*系统自动废标|如遇项目流[标采]' # 503076535 供应商数量: 报名供应商不足三家。
  3881. }
  3882. self.title_life_dic = {
  3883. '采购意向': '采购意向|招标意向|选取意向|意向公告|意向公示|意向公开',
  3884. '招标预告': '预公?告|预公示|报建公告|(批前|标前)公示|(供应|招标)计划表?$|(论证|征求|征集)(供应商)?意见|意见征询|需求评审公告|需求(公告|公示|意见)',
  3885. '公告变更': '第[\d一二]次变更|(变更|更正(事项)?|更改|延期|暂停)(招标|采购)?的?(公告|公示|通知)|变更$|更正$',
  3886. '招标答疑': '质疑|澄清|答疑(文件)?|补遗书?|(最高(投标)?限价|控制价|拦标价)(公示|公告|$)',
  3887. '废标公告': '(终止|中止|废标|废除|废置|流标|失败|作废|异常|撤销|撤回|取消成?交?|流拍|停止)(结果|竞价|项目)?的?(公告|公示|$)|(终止|中止)(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|拍卖|招租|交易|出让)|关于废置',
  3888. '合同公告': '(合同(成交|变更)?)(公告|公示|信息|公式|公开|签订)|合同备案|合同书|合同$', # |(履约|验收)(结果)?
  3889. '候选人公示': '候选人(变更)?公示|评标(结果)?(公[告示]|报告)|评审结果', #中标前公示|中标预公示|
  3890. '中标信息': '(中标|中选|中价|中租|成交)?|入选|确认)(候选人|人|供应商|记录|结果|变更|情况)?的?(公告|公示|结果)|未?入围(公示|公告)|(遴选|采购|招标|竞价|议价|比选|询比?价|评选|谈判|邀标|邀请|洽谈|约谈|评标|发包|磋商|交易|出让|抽取|抽签)\w{,2}结果|单一来源(采购|招标)?的?(中标|成交|结果)|中标通知书|中标$|项目中标|(项目|工程|服务|定点)的?结果公[告示]|超市直购订单', # |开标(记录|信息|情况)
  3891. '资审结果': '((资格|资质)(审查|预审|后审|审核)|资审)结果(公告|公示)?|(资质|资格)(预审|后审)公示|资审及业绩公示',
  3892. '招标公告': '(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|拍卖|招租|交易|出让)的?(公告|公示|$)|公开(采购|招标|招租|拍卖|挂牌|出让)|(资审|预审|后审)公告',
  3893. '开标记录': '开标记录|截标信息|评委名单公示|开标安排|开标数据表|开标信息|开标情况|开标一览表|开标结果|开标会',
  3894. '验收合同': '(验收|履约)(公告|公示)|(验收|履约)(结果|报告|意见|单)(公告|公示)|预留项目执行情况'
  3895. }
  3896. def load_life(self,life_model,config):
  3897. with tf.Graph().as_default() as graph:
  3898. output_graph_def = graph.as_graph_def()
  3899. with open(os.path.dirname(__file__)+life_model, 'rb') as f:
  3900. output_graph_def.ParseFromString(f.read())
  3901. tf.import_graph_def(output_graph_def, name='')
  3902. # print("%d ops in the final graph" % len(output_graph_def.node))
  3903. del output_graph_def
  3904. sess = tf.Session(graph=graph,config=config)
  3905. sess.run(tf.global_variables_initializer())
  3906. inputs = sess.graph.get_tensor_by_name('inputs/inputs:0')
  3907. prob = sess.graph.get_tensor_by_name('inputs/dropout:0')
  3908. title = sess.graph.get_tensor_by_name('inputs/title:0')
  3909. mask = sess.graph.get_tensor_by_name('inputs/mask:0')
  3910. mask_title = sess.graph.get_tensor_by_name('inputs/mask_title:0')
  3911. # logit = sess.graph.get_tensor_by_name('output/logit:0')
  3912. softmax = sess.graph.get_tensor_by_name('output/softmax:0')
  3913. return sess, title, inputs, prob, softmax, mask, mask_title
  3914. def load_type(self,type_model):
  3915. with tf.Graph().as_default() as graph:
  3916. output_graph_def = graph.as_graph_def()
  3917. with open(os.path.dirname(__file__)+type_model, 'rb') as f:
  3918. output_graph_def.ParseFromString(f.read())
  3919. tf.import_graph_def(output_graph_def, name='')
  3920. # print("%d ops in the final graph" % len(output_graph_def.node))
  3921. del output_graph_def
  3922. sess = tf.Session(graph=graph)
  3923. sess.run(tf.global_variables_initializer())
  3924. inputs = sess.graph.get_tensor_by_name('inputs/inputs:0')
  3925. prob = sess.graph.get_tensor_by_name('inputs/dropout:0')
  3926. title = sess.graph.get_tensor_by_name('inputs/title:0')
  3927. mask = sess.graph.get_tensor_by_name('inputs/mask:0')
  3928. mask_title = sess.graph.get_tensor_by_name('inputs/mask_title:0')
  3929. # logit = sess.graph.get_tensor_by_name('output/logit:0')
  3930. softmax = sess.graph.get_tensor_by_name('output/softmax:0')
  3931. return sess, title, inputs, prob, softmax, mask, mask_title
  3932. def predict_process(self, docid='', doctitle='', dochtmlcon=''):
  3933. # print('准备预处理')
  3934. def get_kw_senten(s, span=10):
  3935. doc_sens = []
  3936. tmp = 0
  3937. num = 0
  3938. end_idx = 0
  3939. for it in re.finditer(self.kws, s): # '|'.join(keywordset)
  3940. left = s[end_idx:it.end()].split()
  3941. right = s[it.end():].split()
  3942. tmp_seg = s[tmp:it.start()].split()
  3943. if len(tmp_seg) > span or tmp == 0:
  3944. doc_sens.append(' '.join(left[-span:] + right[:span]))
  3945. end_idx = it.end() + 1 + len(' '.join(right[:span]))
  3946. tmp = it.end()
  3947. num += 1
  3948. if num >= self.sentence_num:
  3949. break
  3950. if doc_sens == []:
  3951. doc_sens.append(s)
  3952. return doc_sens
  3953. def word2id(wordlist, max_len=self.sequen_len):
  3954. ids = [getIndexOfWords(w) for w in wordlist]
  3955. ids = ids[:max_len] if len(ids) >= max_len else ids + [0] * (max_len - len(ids))
  3956. assert len(ids) == max_len
  3957. return ids
  3958. cost_time = dict()
  3959. datas = []
  3960. datas_title = []
  3961. try:
  3962. segword_title = ' '.join(selffool.cut(doctitle)[0])
  3963. segword_content = dochtmlcon
  3964. except:
  3965. segword_content = ''
  3966. segword_title = ''
  3967. if isinstance(segword_content, float):
  3968. segword_content = ''
  3969. if isinstance(segword_title, float):
  3970. segword_title = ''
  3971. segword_content = segword_content.replace(' 中 选 ', ' 中选 ').replace(' 中 标 ', ' 中标 ').replace(' 补 遗 ', ' 补遗 '). \
  3972. replace(' 更 多', '').replace(' 更多', '').replace(' 中 号 ', ' 中标 ').replace(' 中 选人 ', ' 中选人 '). \
  3973. replace(' 点击 下载 查看', '').replace(' 咨询 报价 请 点击', '').replace('终结', '终止')
  3974. segword_title = re.sub('[^\s\u4e00-\u9fa5]', '', segword_title)
  3975. segword_content = re.sub('[^\s\u4e00-\u9fa5]', '', segword_content)
  3976. doc_word_list = segword_content.split()
  3977. if len(doc_word_list) > self.sequen_len / 2:
  3978. doc_sens = get_kw_senten(' '.join(doc_word_list[100:500]))
  3979. doc_sens = ' '.join(doc_word_list[:100]) + '\n' + '\n'.join(doc_sens)
  3980. else:
  3981. doc_sens = ' '.join(doc_word_list[:self.sequen_len])
  3982. # print('标题:',segword_title)
  3983. # print('正文:',segword_content)
  3984. datas.append(doc_sens.split())
  3985. datas_title.append(segword_title.split())
  3986. # print('完成预处理')
  3987. return datas, datas_title
  3988. def is_houxuan(self, title, content):
  3989. '''
  3990. 通过标题和中文内容判断是否属于候选人公示类别
  3991. :param title: 公告标题
  3992. :param content: 公告正文文本内容
  3993. :return: 1 是候选人公示 ;0 不是
  3994. '''
  3995. if re.search('候选人的?公示|评标结果|评审结果|中标公示', title): # (中标|成交|中选|入围)
  3996. if re.search('变更公告|更正公告|废标|终止|答疑|澄清', title):
  3997. return 0
  3998. return 1
  3999. if re.search('候选人的?公示', content[:100]):
  4000. if re.search('公示(期|活动)?已经?结束|公示期已满|中标结果公告|中标结果公示|变更公告|更正公告|废标|终止|答疑|澄清', content[:100]):
  4001. return 0
  4002. return 1
  4003. else:
  4004. return 0
  4005. def predict(self, title='', list_sentence='', web_source_no='', original_docchannel=''):
  4006. not_extract_dic = {
  4007. 104: '招标文件',
  4008. 106: '法律法规',
  4009. 107: '新闻资讯',
  4010. 108: '拟建项目',
  4011. 109: '展会推广',
  4012. 110: '企业名录',
  4013. 111: '企业资质',
  4014. 112: '全国工程人员',
  4015. 113: '业主采购'
  4016. }
  4017. if original_docchannel in not_extract_dic:
  4018. return {'docchannel': {'docchannel':'', 'doctype':not_extract_dic[original_docchannel], "original_docchannel_id": str(original_docchannel)}}
  4019. if web_source_no in ['02104-7']:
  4020. return {'docchannel': {'docchannel':'', 'doctype':'采招数据'}}
  4021. if isinstance(list_sentence, list):
  4022. token_l = [it.tokens for it in list_sentence]
  4023. tokens = [it for l in token_l for it in l]
  4024. content = ' '.join(tokens[:500])
  4025. title = re.sub('[^\u4e00-\u9fa5]', '', title)
  4026. if len(title)>50:
  4027. title = title[:20]+title[-30:]
  4028. data_content, data_title = self.predict_process(docid='', doctitle=title[-50:], dochtmlcon=content) # 标题最多取50字
  4029. text_len = len(data_content[0]) if len(data_content[0])<self.sequen_len else self.sequen_len
  4030. title_len = len(data_title[0]) if len(data_title[0])<self.title_len else self.title_len
  4031. result = {'docchannel': {'docchannel':'', 'doctype':'', "original_docchannel_id": str(original_docchannel)}}
  4032. array_content = embedding(data_content, shape=(len(data_content), self.sequen_len, 128))
  4033. array_title = embedding(data_title, shape=(len(data_title), self.title_len, 128))
  4034. pred = self.type_sess.run(self.type_softmax,
  4035. feed_dict={
  4036. self.type_title: array_title,
  4037. self.type_content: array_content,
  4038. self.type_mask:[[0]*text_len+[1]*(self.sequen_len-text_len)],
  4039. self.type_mask_title:[[0]*title_len+[1]*(self.title_len-title_len)],
  4040. self.type_prob:1}
  4041. )
  4042. id = np.argmax(pred, axis=1)[0]
  4043. prob = pred[0][id]
  4044. result['docchannel']['doctype'] = self.id2type[id]
  4045. # print('公告类别:', self.id2type[id], '概率:',prob)
  4046. # if id == 0:
  4047. if result['docchannel']['doctype'] not in ['', '新闻资讯']:
  4048. pred = self.lift_sess.run(self.lift_softmax,
  4049. feed_dict={
  4050. self.lift_title: array_title,
  4051. self.lift_content: array_content,
  4052. self.mask: [[0] * text_len + [1] * (self.sequen_len - text_len)],
  4053. self.mask_title: [[0] * title_len + [1] * (self.title_len - title_len)],
  4054. self.lift_prob:1}
  4055. )
  4056. id = np.argmax(pred, axis=1)[0]
  4057. prob = pred[0][id]
  4058. result['docchannel']['docchannel'] = self.id2life[id]
  4059. # print('生命周期:纯模型预测',self.id2life[id], '概率:',prob)
  4060. # if id == 6:
  4061. if result['docchannel']['docchannel'] == '中标信息':
  4062. if self.is_houxuan(''.join([it for it in title if it.isalpha()]), ''.join([it for it in content if it.isalpha()])):
  4063. result['docchannel']['docchannel'] = '候选人公示'
  4064. # return '候选人公示', prob
  4065. # return [{'docchannel': '候选人公示'}]
  4066. return result
  4067. # return [{'docchannel':self.id2life[id]}]
  4068. # else:
  4069. # # return self.id2type[id], prob
  4070. # return [{'docchannel':self.id2type[id]}]
  4071. def predict_rule(self, title, content, channel_dic, prem_dic):
  4072. '''2022/2/10加入规则去除某些数据源及内容过短且不包含类别关键词的公告不做预测'''
  4073. hetong = '(合同|验收|履约)(公告|公示)|合同号?$' # 合同标题正则
  4074. zhongbiao_t = '(中标|中选|成交|入选|入围|结果|确认)(公告|公示|结果)|(遴选|采购|招标|竞价|议价|比选|询价|评选|谈判|邀标|邀请|洽谈|约谈|评标|发包|遴选)结果|开标(记录|信息|情况)|单一来源|直接(选取|选定)|中标通知书|中标$'
  4075. zhongbiao_c = '(中标|中选|成交|拟选用|拟邀请|最终选定的?|拟定)(供应商|供货商|服务商|企业|公司|单位|(候选)?人)(名称)?[::]|[,。:.](供应商|供货商|服务商)(名称)?:|指定的中介服务机构:|建设服务单位:'
  4076. zhaobiao_t = '(遴选|采购|招标|竞价|议价|比选|询价|评选|谈判|邀标|邀请|洽谈|约谈)(公告|公示|$)'
  4077. title_cn = re.sub('[^\u4e00-\u9fa5]', '', title)
  4078. if len(re.sub('[^\u4e00-\u9fa5]', "", content))<50 and channel_dic['docchannel']['doctype'] != '新闻资讯':
  4079. if re.search(hetong, title_cn) != None:
  4080. channel_dic['docchannel']['docchannel'] = '合同公告'
  4081. elif re.search(zhongbiao_t, title_cn):
  4082. channel_dic['docchannel']['docchannel'] = '中标信息'
  4083. elif re.search(zhaobiao_t, title_cn):
  4084. channel_dic['docchannel']['docchannel'] = '招标公告'
  4085. else:
  4086. channel_dic['docchannel']['docchannel'] = ''
  4087. elif channel_dic['docchannel'].get('docchannel', '') == '招标公告' and 'win_tenderer' in json.dumps(prem_dic,
  4088. ensure_ascii=False):
  4089. if re.search(hetong, title_cn) != None:
  4090. channel_dic['docchannel']['docchannel'] = '合同公告'
  4091. log('正则把招标公告修改为合同公告')
  4092. elif re.search(zhongbiao_t, title_cn) or re.search(zhongbiao_t, content[:200]) or re.search(zhongbiao_c,
  4093. content):
  4094. channel_dic['docchannel']['docchannel'] = '中标信息'
  4095. log('正则把招标公告修改为中标信息')
  4096. elif channel_dic['docchannel'].get('docchannel', '') == '中标信息' and 'win_tenderer' not in json.dumps(prem_dic,
  4097. ensure_ascii=False):
  4098. if re.search(hetong, title_cn):
  4099. channel_dic['docchannel']['docchannel'] = '合同公告'
  4100. log('正则把中标信息修改为合同公告')
  4101. elif re.search(zhongbiao_t, title_cn) or re.search(zhongbiao_t, content[:200]) or re.search(zhongbiao_c,
  4102. content):
  4103. pass
  4104. elif re.search(zhaobiao_t, title_cn):
  4105. channel_dic['docchannel']['docchannel'] = '招标公告'
  4106. log('正则把中标信息修改为招标公告')
  4107. elif re.search('中标|成交|中选|入选|入围|结果|供应商|供货商|候选人', title_cn+content)==None:
  4108. channel_dic['docchannel']['docchannel'] = ''
  4109. log('正则把中标信息修改为空')
  4110. return channel_dic
  4111. def predict_merge(self, title, list_sentence, html, original_docchannel='', web_source_no=''):
  4112. '''
  4113. 正则,模型混合预测,返回公告类型及生命周期
  4114. :param title: 公告标题
  4115. :param content: 预处理后的返回的句子实体列表 list_sentence
  4116. :param html: 公告原文 html 内容
  4117. :param bidway: 招标方式
  4118. :return: {'docchannel': {'docchannel':'中标信息', 'doctype':'采招数据'}} 字典格式
  4119. '''
  4120. def cut_single_cn_space(text):
  4121. new_text = ""
  4122. for w in text.split():
  4123. if len(w) == 1 or re.search('^[\u4e00-\u9fa5][::]', w):
  4124. new_text += w
  4125. else:
  4126. new_text += ' ' + w
  4127. return new_text
  4128. def html2text(html):
  4129. ser = re.search('<div[^<>]*richTextFetch', html)
  4130. # if ser and len(re.sub('[^\u4e00-\u9fa5]', '', html[:ser.start()]))>500:
  4131. # html = html[:ser.start()]+'##richTextFetch##'
  4132. if ser:
  4133. if len(re.sub('[^\u4e00-\u9fa5]', '', html[:ser.start()])) > 200:
  4134. html = html[:ser.start()] + '##richTextFetch##'
  4135. else:
  4136. html = html[:ser.start() + 500]
  4137. text = re.sub('<[^<]*?>', '', html).replace('&nbsp;', ' ')
  4138. # text = re.sub('http[0-9a-zA-Z-.:/]+|[0-9a-zA-Z-./@]+', '', text)
  4139. text = re.sub('\s+', ' ', text)
  4140. # text = re.sub('[/|[()()]', '', text)
  4141. text = cut_single_cn_space(text)
  4142. return text[:20000]
  4143. def count_diffser(pattern, text):
  4144. num = 0
  4145. kw = []
  4146. for p in pattern.split(';'):
  4147. if re.search(p, text):
  4148. num += 1
  4149. kw.append(re.search(p, text).group(0))
  4150. return num, ';'.join(kw)
  4151. def is_single_source(bidway, title):
  4152. if re.search('单一来源|单一性采购', title):
  4153. return True
  4154. elif bidway == '单一来源':
  4155. return True
  4156. else:
  4157. return False
  4158. def get_type(title, text):
  4159. if re.search(self.title_type_dic['土地矿产'], title) or re.search(self.type_dic['土地矿产'],
  4160. text): # and re.search('(土地|用地|宗地|地块)(经营权)?(流转|承包|出租|招租|租赁|确权)', text)==None
  4161. if re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title):
  4162. return '采招数据', re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title).group(0)
  4163. return '土地矿产', (re.search(self.title_type_dic['土地矿产'], title) or re.search(self.type_dic['土地矿产'], text)).group(0)
  4164. elif re.search(self.title_type_dic['产权交易'], title) or re.search(self.type_dic['产权交易'], text):
  4165. if re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title):
  4166. return '采招数据', re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title).group(0)
  4167. return '产权交易', (re.search(self.title_type_dic['产权交易'], title) or re.search(self.type_dic['产权交易'], text)).group(0)
  4168. elif (re.search(self.title_type_dic['拍卖出让'], title) or re.search(self.type_dic['拍卖出让'], text)):
  4169. if re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title):
  4170. return '采招数据', re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title).group(0)
  4171. return '拍卖出让', (re.search(self.title_type_dic['拍卖出让'], title) or re.search(self.type_dic['拍卖出让'], text)).group(0)
  4172. elif re.search(self.title_type_dic['采招数据'], title) or re.search(self.type_dic['采招数据'], title + text):
  4173. return '采招数据', (
  4174. re.search(self.title_type_dic['采招数据'], title) or re.search(self.type_dic['采招数据'], title + text)).group(
  4175. 0)
  4176. elif re.search(self.title_type_dic['新闻资讯'], title):
  4177. if re.search(self.title_type_dic['采招数据'], title +text.strip().split(' ')[0]):
  4178. return '采招数据', re.search(self.title_type_dic['采招数据'], title +text.strip().split(' ')[0]).group(0)
  4179. return '新闻资讯', re.search(self.title_type_dic['新闻资讯'], title).group(0)
  4180. else:
  4181. return '', '没有公告类型关键词,返回空'
  4182. def get_life(title, text):
  4183. title = re.sub('[-()()0-9a-z]|第?[二三四]次公?告?', '', title)
  4184. first_line = text.split()[0] if len(text.split()) > 2 else ''
  4185. if title.strip()[-2:] not in ['公告', '公示'] and 5 < len(first_line) < 50 and first_line[-2:] in ['公告', '公示']:
  4186. # print('title: ', title, first_line)
  4187. title += first_line
  4188. def count_score(l):
  4189. return len(l) + len(set(l)) * 2
  4190. life_kw_title = {}
  4191. life_kw_content = {}
  4192. life_score = {}
  4193. # msc = ""
  4194. # 查找标题每个类别关键词
  4195. for k, v in self.title_life_dic.items():
  4196. k2 = re.sub('[\da-z]', '', k)
  4197. if k2 not in life_kw_title:
  4198. life_kw_title[k2] = []
  4199. for it in re.finditer(v, title):
  4200. life_kw_title[k2].append(it.group(0))
  4201. # 查找正文每个类别关键词
  4202. for k, v in self.life_dic.items():
  4203. k2 = re.sub('[\da-z]', '', k)
  4204. if k2 not in life_kw_content:
  4205. life_kw_content[k2] = {'pos': [], 'neg': []}
  4206. for it in re.finditer(v, text):
  4207. if 'neg' not in k:
  4208. life_kw_content[k2]['pos'].append(it.group(0))
  4209. else:
  4210. life_kw_content[k2]['neg'].append(it.group(0))
  4211. for k2 in life_kw_content:
  4212. life_score[k2] = count_score(life_kw_content[k2]['pos']) - count_score(
  4213. life_kw_content[k2]['neg'])
  4214. life_kw_title = {k: v for k, v in life_kw_title.items() if v != []}
  4215. life_kw_content = {k: v for k, v in life_kw_content.items() if life_score[k] > 0}
  4216. msc = [life_kw_title, life_kw_content, life_score]
  4217. msc = json.dumps(msc, ensure_ascii=False)
  4218. max_score = 0
  4219. life_list = []
  4220. for k in life_score.keys():
  4221. if life_score[k] > max_score:
  4222. max_score = life_score[k]
  4223. life_list = [k]
  4224. elif life_score[k] == max_score and life_score[k] > 0:
  4225. life_list.append(k)
  4226. if '采购意向' in life_kw_title or '采购意向' in life_list:
  4227. if '中标信息' in life_kw_title or '中标信息' in life_list:
  4228. return '中标信息', msc
  4229. elif '候选人公示' in life_kw_title:
  4230. return '候选人公示', msc
  4231. elif set(['候选人公示', '合同公告']) & set(life_kw_title) != set():
  4232. return '', msc
  4233. return '采购意向', msc
  4234. elif '招标预告' in life_kw_title or '招标预告' in life_list:
  4235. if '中标信息' in life_kw_title or '中标信息' in life_list:
  4236. return '中标信息', msc
  4237. elif '候选人公示' in life_kw_title:
  4238. return '候选人公示', msc
  4239. elif set(['候选人公示', '合同公告']) & set(life_kw_title) != set():
  4240. return '', msc
  4241. return '招标预告', msc
  4242. elif '公告变更' in life_kw_title or '公告变更' in life_list:
  4243. if life_score.get('候选人公示', 0) > 3 or '候选人公示' in life_kw_title:
  4244. return '候选人公示', msc
  4245. elif life_score.get('合同公告', 0) > 3 or '合同公告' in life_kw_title:
  4246. return '合同公告', msc
  4247. elif life_score.get('中标信息', 0) > 3 or '中标信息' in life_kw_title:
  4248. return '中标信息', msc
  4249. elif '招标公告' in life_kw_title and re.search('变更|更正', title[-4:])==None and life_score.get('公告变更', 0) < 4:
  4250. return '招标公告', msc
  4251. return '公告变更', msc
  4252. elif '招标答疑' in life_kw_title or '招标答疑' in life_list:
  4253. if '招标公告' in life_kw_title and life_score.get('招标答疑', 0) < 4:
  4254. return '招标公告', msc
  4255. elif life_score.get('招标答疑', 0) < max_score:
  4256. if max_score > 3 and len(life_list) == 1:
  4257. return life_list[0], msc
  4258. return '', msc
  4259. return '招标答疑', msc
  4260. elif '开标记录' in life_kw_title:
  4261. return '开标记录', msc
  4262. elif '验收合同' in life_kw_title:
  4263. return '验收合同', msc
  4264. elif '候选人公示' in life_kw_title or '候选人公示' in life_list:
  4265. if '招标公告' in life_kw_title and '候选人公示' not in life_kw_title: # and life_score.get('招标公告', 0) > 3
  4266. return '招标公告', msc
  4267. elif '废标公告' in life_kw_title or life_score.get('废标公告', 0) > 5:
  4268. return '废标公告', msc
  4269. return '候选人公示', msc
  4270. elif '合同公告' in life_kw_title or '合同公告' in life_list:
  4271. if '招标公告' in life_kw_title and life_score.get('招标公告', 0) > 3:
  4272. return '招标公告', msc
  4273. elif '废标公告' in life_kw_title or life_score.get('废标公告', 0) > 5:
  4274. return '废标公告', msc
  4275. return '合同公告', msc
  4276. elif '中标信息' in life_kw_title or '中标信息' in life_list:
  4277. if '招标公告' in life_kw_title and '中标信息' not in life_kw_title and life_score.get('招标公告',0) >= life_score.get('中标信息',0): # (life_score.get('招标公告', 0)>2 or life_score.get('中标信息', 0)<4) 0.7886409793924245
  4278. return '招标公告', msc
  4279. elif '废标公告' in life_kw_title or life_score.get('废标公告', 0) > 5:
  4280. return '废标公告', msc
  4281. elif life_score.get('候选人公示', 0) > 3:
  4282. return '候选人公示', msc
  4283. elif life_score.get('合同公告', 0) > 5:
  4284. return '合同公告', msc
  4285. return '中标信息', msc
  4286. elif '废标公告' in life_kw_title or '废标公告' in life_list:
  4287. if life_score.get('招标公告', 0) > 3 and '废标公告' not in life_kw_title:
  4288. return '招标公告', msc
  4289. return '废标公告', msc
  4290. elif '资审结果' in life_kw_title or '资审结果' in life_list:
  4291. return '资审结果', msc
  4292. elif '招标公告' in life_kw_title or '招标公告' in life_list:
  4293. return '招标公告', msc
  4294. return '', msc
  4295. def get_model_inputs(list_sentence):
  4296. list_sentence = sorted(list_sentence, key=lambda x:x.sentence_index)
  4297. token_l = [it.tokens for it in list_sentence]
  4298. tokens = [it for l in token_l for it in l]
  4299. content = ' '.join(tokens[:500])
  4300. data_content, data_title = self.predict_process(docid='', doctitle=title[-50:],
  4301. dochtmlcon=content) # 标题最多取50字
  4302. text_len = len(data_content[0]) if len(data_content[0]) < self.sequen_len else self.sequen_len
  4303. title_len = len(data_title[0]) if len(data_title[0]) < self.title_len else self.title_len
  4304. array_content = embedding(data_content, shape=(len(data_content), self.sequen_len, 128))
  4305. array_title = embedding(data_title, shape=(len(data_title), self.title_len, 128))
  4306. return array_content, array_title ,text_len, title_len, content
  4307. def type_model_predict():
  4308. pred = self.type_sess.run(self.type_softmax,
  4309. feed_dict={
  4310. self.type_title: array_title,
  4311. self.type_content: array_content,
  4312. self.type_mask: [[0] * text_len + [1] * (self.sequen_len - text_len)],
  4313. self.type_mask_title: [[0] * title_len + [1] * (self.title_len - title_len)],
  4314. self.type_prob: 1}
  4315. )
  4316. id = np.argmax(pred, axis=1)[0]
  4317. prob = pred[0][id]
  4318. return id, prob
  4319. def life_model_predict():
  4320. pred = self.lift_sess.run(self.lift_softmax,
  4321. feed_dict={
  4322. self.lift_title: array_title,
  4323. self.lift_content: array_content,
  4324. self.mask: [[0] * text_len + [1] * (self.sequen_len - text_len)],
  4325. self.mask_title: [[0] * title_len + [1] * (self.title_len - title_len)],
  4326. self.lift_prob: 1}
  4327. )
  4328. id = np.argmax(pred, axis=1)[0]
  4329. prob = pred[0][id]
  4330. return id, prob
  4331. not_extract_dic = {
  4332. 104: '招标文件',
  4333. 106: '法律法规',
  4334. 107: '新闻资讯',
  4335. 108: '拟建项目',
  4336. 109: '展会推广',
  4337. 110: '企业名录',
  4338. 111: '企业资质',
  4339. 112: '全国工程人员',
  4340. 113: '业主采购'
  4341. }
  4342. origin_dic = {51: '公告变更',
  4343. 52: '招标公告',
  4344. 101: '中标信息',
  4345. 102: '招标预告',
  4346. 103: '招标答疑',
  4347. 104: '招标文件',
  4348. 105: '资审结果',
  4349. 106: '法律法规',
  4350. 107: '新闻资讯',
  4351. 108: '拟建项目',
  4352. 109: '展会推广',
  4353. 110: '企业名录',
  4354. 111: '企业资质',
  4355. 112: '全国工程',
  4356. 113: '业主采购',
  4357. 114: '采购意向',
  4358. 115: '拍卖出让',
  4359. 116: '土地矿产',
  4360. 117: '产权交易',
  4361. 118: '废标公告',
  4362. 119: '候选人公示',
  4363. 120: '合同公告'}
  4364. self.origin_dic = origin_dic
  4365. if original_docchannel in not_extract_dic:
  4366. return {'docchannel': {'docchannel': '', 'doctype': not_extract_dic[original_docchannel], 'life_docchannel': origin_dic.get(original_docchannel, '原始类别')}}, '公告类别不在提取范围'
  4367. if web_source_no in ['02104-7', '04733', 'DX007628-6']: # 这些数据源无法识别
  4368. return {'docchannel': {'docchannel': origin_dic.get(original_docchannel, '原始类别'), 'doctype': '采招数据', 'life_docchannel': origin_dic.get(original_docchannel, '原始类别')}}, '此数据源公告分类不明确,返回数据源类别'
  4369. if original_docchannel == 303:
  4370. return {'docchannel': {'docchannel': '处罚公告', 'doctype': '处罚公告', 'life_docchannel': '处罚公告'}}, "源类别为处罚公告"
  4371. title = re.sub('[^\u4e00-\u9fa5]+|出租车', '', title)
  4372. if len(title) > 50:
  4373. title = title[:20] + title[-30:]
  4374. text = html2text(html)
  4375. self.title = title
  4376. self.text = text
  4377. result = {'docchannel': {'docchannel': '', 'doctype': ''}}
  4378. doc_type, type_kw = get_type(title, text)
  4379. # doc_life, life_kw = get_life(title, text, prem_json, bidway, original_docchannel)
  4380. doc_life, life_kw = get_life(title, text)
  4381. if doc_type in self.title_type_dic:
  4382. result['docchannel']['doctype'] = doc_type
  4383. if doc_life in self.title_life_dic:
  4384. result['docchannel']['docchannel'] = doc_life
  4385. # print('channel正则预测结果:', result)
  4386. msc = '正则结果:类型:%s, 关键词:%s, 周期:%s, 关键词:%s'%(doc_type, type_kw,doc_life, life_kw)+'\n'+'模型结果:'
  4387. # print('类型:%s, 关键词:%s, 周期:%s, 关键词:%s'%(doc_type, type_kw,doc_life, life_kw))
  4388. if doc_type == "" or doc_life == "" or (doc_type != '采招数据' and origin_dic.get(original_docchannel, '原始类别') in ['招标公告', '中标信息', '招标预告', '采购意向']):
  4389. array_content, array_title, text_len, title_len, content = get_model_inputs(list_sentence)
  4390. if doc_type =="" or (doc_type != '采招数据' and origin_dic.get(original_docchannel, '原始类别') in ['招标公告', '中标信息', '招标预告', '采购意向']):
  4391. type_id, type_prob = type_model_predict()
  4392. type_model = self.id2type[type_id]
  4393. if type_model == '新闻资讯' and doc_life!='': # 修复bug 78584245 "docchannel": "合同公告", "doctype": "新闻资讯",
  4394. result['docchannel']['doctype'] = '采招数据'
  4395. msc += '模型结果为新闻资讯,生命周期不为空,改为采招数据;'
  4396. else:
  4397. result['docchannel']['doctype'] = type_model
  4398. msc += type_model + ' 概率:%.4f;'%type_prob
  4399. # print('公告类别:', self.id2type[id], '概率:',prob)
  4400. # if id == 0:
  4401. if doc_life=="" and result['docchannel']['doctype'] not in ['', '新闻资讯']:
  4402. if len(text)>150 and re.search(self.kws, content):
  4403. life_id, life_prob = life_model_predict()
  4404. if life_prob>=0.8:
  4405. life_model = self.id2life[life_id]
  4406. result['docchannel']['docchannel'] = life_model
  4407. msc += life_model + ' 概率:%.4f;\n'%life_prob
  4408. # msc = final_change(msc)
  4409. # print('channel ', msc)
  4410. return result, msc
  4411. def final_change(self, result, prem, original_docchannel, msc):
  4412. '''
  4413. :param result: channel 结果字典
  4414. :param prem:
  4415. :param title: 标题
  4416. :param text: 正文
  4417. :param original_docchannel: 站源类别
  4418. :param msc: 备注
  4419. :return: channel结果字典
  4420. '''
  4421. '''
  4422. 修改逻辑:
  4423. 1、中标公告、合同公告无中标人且原始为非中标,返回原类型
  4424. 2、废标公告有中标人且标题无废标关键词,返回中标信息
  4425. 3、答疑公告标题无答疑关键且原始为招标,返回原始类别
  4426. 4、招标公告有中标人且原始为中标,返回中标信息
  4427. 5、预测为招标,原始为预告、意向,返回原始类别
  4428. 6、预测及原始均在变更、答疑,返回原始类别
  4429. 7、预测为采招数据,原始为产权且有关键词,返回原始类别
  4430. 8、废标公告原始为招标、预告且标题无废标关键期,返回原始类别
  4431. 9、若预测为非采招数据且源网为采招数据且有招标关键词返回采招数据
  4432. 10、招标公告有中标人,且标题有直购关键词,改为中标信息
  4433. 11、预测预告,原始为意向、招标且标题无预告关键词,返回原始类别
  4434. '''
  4435. def is_contain_winner(extract_json):
  4436. if re.search('win_tenderer', extract_json):
  4437. return True
  4438. else:
  4439. return False
  4440. origin_dic = self.origin_dic
  4441. title = self.title
  4442. text = self.text
  4443. prem_json = json.dumps(prem, ensure_ascii=False)
  4444. if result['docchannel']['docchannel'] in ['中标信息', '合同公告'] and origin_dic.get(
  4445. original_docchannel, '') in ['招标公告', '采购意向', '招标预告', '公告变更'] and is_contain_winner(
  4446. prem_json) == False and re.search(self.title_life_dic['中标信息'], title) == None:
  4447. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4448. msc += '最终规则修改:中标公告、合同公告无中标人且原始为非中标,返回原类型'
  4449. elif result['docchannel']['docchannel'] == '废标公告' and is_contain_winner(prem_json) and re.search(
  4450. self.title_life_dic['废标公告'], title) == None:
  4451. result['docchannel']['docchannel'] = '中标信息'
  4452. msc += '最终规则修改:预测为废标却有中标人且标题无废标关键词改为中标信息;'
  4453. elif result['docchannel']['docchannel'] in ['招标答疑'] and re.search(
  4454. self.title_life_dic['招标答疑'], title) == None and origin_dic.get(
  4455. original_docchannel, '') in ['招标公告', '采购意向', '招标预告']:
  4456. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4457. msc += '最终规则修改:答疑公告标题无答疑关键且原始为招标,返回原始类别;'
  4458. elif result['docchannel']['docchannel'] == '招标公告' and is_contain_winner(prem_json) and (origin_dic.get(
  4459. original_docchannel, '') == '中标信息' or re.search('直接采购', title)): # 20241025补充 标题包含直接采购且有中标人的为中标公告
  4460. result['docchannel']['docchannel'] = '中标信息'
  4461. msc += '最终规则修改:预测为招标公告却有中标人且原始为中标改为中标信息;'
  4462. elif result['docchannel']['docchannel'] in ['招标公告'] and origin_dic.get(
  4463. original_docchannel, '') in ['采购意向', '招标预告']:
  4464. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4465. msc += '最终规则修改:预测为招标,原始为预告、意向,返回原始类别'
  4466. elif result['docchannel']['docchannel'] in ['招标预告'] and origin_dic.get(
  4467. original_docchannel, '') in ['采购意向', '招标公告'] and re.search(
  4468. self.title_life_dic['招标预告'], title) == None:
  4469. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4470. msc += '最终规则修改:预测预告,原始为意向、招标且标题无预告关键词,返回原始类别'
  4471. elif result['docchannel']['docchannel'] in ['招标答疑', '公告变更'] and origin_dic.get(
  4472. original_docchannel, '') in ['招标答疑', '公告变更']:
  4473. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4474. msc += '最终规则修改:预测及原始均在答疑、变更,返回原始类别'
  4475. elif result['docchannel']['doctype'] == '采招数据' and origin_dic.get(
  4476. original_docchannel, '') in ['产权交易', '土地矿产'] and re.search('产权|转让|受让|招租|出租|承租|竞价|资产', text):
  4477. result['docchannel']['doctype'] = origin_dic.get(original_docchannel, '')
  4478. msc += '最终规则修改:预测为采招数据,原始为产权且有关键词,返回原始类别'
  4479. elif result['docchannel']['docchannel'] == '废标公告' and origin_dic.get(
  4480. original_docchannel, '') in ['招标公告', '采购意向', '招标预告'] and re.search(
  4481. self.title_life_dic['废标公告'], title) == None:
  4482. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4483. msc += '最终规则修改:废标公告原始为招标、预告且标题无废标关键期,返回原始类别;'
  4484. elif result['docchannel']['docchannel'] in ['招标公告', '招标预告'] and is_contain_winner(
  4485. prem_json) and re.search('直购', title):
  4486. result['docchannel']['docchannel'] = '中标信息'
  4487. msc += "最终规则修改:预测为招标却有中标人且标题有直购关键词返回中标"
  4488. elif result['docchannel']['docchannel'] == '开标记录' and '开标结果' in title and is_contain_winner(prem_json):
  4489. msc += "最终规则修改:开标结果包含中标人的作为中标信息"
  4490. result['docchannel']['docchannel'] = '中标信息'
  4491. if result['docchannel']['doctype'] in ['产权交易', '土地矿产', '拍卖出让'] and origin_dic.get(
  4492. original_docchannel, '') not in ['产权交易', '土地矿产', '拍卖出让'] \
  4493. and (re.search(self.title_type_dic['采招数据'], title) or re.search('工程|服务|采购|询价|磋商', title) or re.search(
  4494. '(采购|招投?标|投标)(信息|内容|项目|公告|数量|人|单位|方式)|(建设|工程|服务|施工|监理|勘察|设计)项目|(%s)' % self.type_dic['采招数据'], text)):
  4495. result['docchannel']['doctype'] = '采招数据'
  4496. msc += ' 最终规则修改:预测为非采招数据,原始为采招数据且有招标关键词,返回采招数据'
  4497. elif result['docchannel']['doctype'] in ['土地矿产'] and origin_dic.get(original_docchannel, '') in ['拍卖出让', '产权交易']:
  4498. if origin_dic.get(original_docchannel, '') in ['拍卖出让'] and (
  4499. re.search(self.title_type_dic['拍卖出让'], title) or re.search(self.type_dic['拍卖出让'], text)):
  4500. result['docchannel']['doctype'] = '拍卖出让'
  4501. msc += "最终规则修改:预测为土地矿产原始为拍卖且有拍卖关键词,返回拍卖"
  4502. elif (re.search(self.title_type_dic['产权交易'], title) or re.search(self.type_dic['产权交易'], text)):
  4503. result['docchannel']['doctype'] = '产权交易'
  4504. msc += "最终规则修改:预测为土地矿产原始为产权交易且有产权交易关键词,返回产权交易"
  4505. '''下面是新格式增加返回字段'''
  4506. if result['docchannel']['docchannel'] != '': # 预测到生命周期的复制到life_docchannel,否则用数据源结果
  4507. result['docchannel']['life_docchannel'] = result['docchannel']['docchannel']
  4508. else:
  4509. result['docchannel']['life_docchannel'] = origin_dic.get(original_docchannel, '原始类别')
  4510. return result, msc
  4511. # 保证金支付方式提取
  4512. class DepositPaymentWay():
  4513. def __init__(self,):
  4514. self.pt = '(保证金的?(交纳|缴纳|应按下列|入账|支付)方式)[::]*([^,。]{,60})'
  4515. self.pt2 = '保证金(必?须以|必?须?通过|以)(.{,8})方式'
  4516. kws = ['银行转账', '公?对公方?式?转账', '对公转账', '柜台转账', '(线上|网上)自?行?(缴纳|交纳|缴退|收退)',
  4517. '网上银行支付', '现金存入', '直接缴纳', '支票', '汇票', '本票', '电汇', '转账', '汇款', '随机码',
  4518. '入账', '基本账户转出', '基本账户汇入', '诚信库中登记的账户转出',
  4519. '银行保函', '电子保函', '担保函', '保证保险', '合法担保机构出具的担保', '金融机构、担保机构出具的保函']
  4520. self.kws = sorted(kws, key=lambda x: len(x), reverse=True)
  4521. def predict(self,content):
  4522. pay_way = {'deposit_patment_way':''}
  4523. result = []
  4524. pay = re.search(self.pt, content)
  4525. if pay:
  4526. # print(pay.group(0))
  4527. pay = pay.group(3)
  4528. for it in re.finditer('|'.join(self.kws), pay):
  4529. result.append(it.group(0))
  4530. pay_way['deposit_patment_way'] = ';'.join(result)
  4531. return pay_way
  4532. pay = re.search(self.pt2, content)
  4533. if pay:
  4534. # print(pay.group(0))
  4535. pay = pay.group(2)
  4536. for it in re.finditer('|'.join(self.kws), pay):
  4537. result.append(it.group(0))
  4538. pay_way['deposit_patment_way'] = ';'.join(result)
  4539. return pay_way
  4540. else:
  4541. return pay_way
  4542. # 项目标签
  4543. class ProjectLabel():
  4544. def __init__(self, ):
  4545. self.keyword_list = self.get_label_keywords()
  4546. self.kongjing_keyword_list = self.get_kongjing_keywords()
  4547. def get_label_keywords(self):
  4548. import csv
  4549. path = os.path.dirname(__file__)+'/project_label_keywords.csv'
  4550. with open(path, 'r',encoding='utf-8') as f:
  4551. reader = csv.reader(f)
  4552. key_word_list = []
  4553. for r in reader:
  4554. if r[0] == '类型':
  4555. continue
  4556. type = r[0]
  4557. key_wrod = r[1]
  4558. key_paichuci = str(r[2])
  4559. key_paichuci = key_paichuci if key_paichuci and key_paichuci != 'nan' else ""
  4560. type_paichuci = str(r[3])
  4561. type_paichuci = type_paichuci if type_paichuci and type_paichuci != 'nan' else ""
  4562. key_word_list.append((type, key_wrod, key_paichuci, type_paichuci))
  4563. return key_word_list
  4564. def get_kongjing_keywords(self):
  4565. import csv
  4566. path = os.path.dirname(__file__)+'/kongjing_label_keywords.csv'
  4567. with open(path, 'r',encoding='utf-8') as f:
  4568. reader = csv.reader(f)
  4569. key_word_list = []
  4570. for r in reader:
  4571. if r[0] == '关键词':
  4572. continue
  4573. key_wrod = r[0]
  4574. key_wrod2 = str(r[1])
  4575. key_wrod2 = key_wrod2 if key_wrod2 and key_wrod2 != 'nan' else ""
  4576. search_type = r[2]
  4577. info_type_list = str(r[3])
  4578. info_type_list = info_type_list if info_type_list and info_type_list != 'nan' else ""
  4579. key_word_list.append((key_wrod, key_wrod2, search_type, info_type_list))
  4580. return key_word_list
  4581. def predict(self, doctitle,product,project_name,prem):
  4582. doctitle = doctitle if doctitle else ""
  4583. product = product if product else ""
  4584. product = ",".join(set(product.split(','))) # 产品词去重
  4585. project_name = project_name if project_name else ""
  4586. tenderee = ""
  4587. agency = ""
  4588. sub_project_names = [] # 标段名称
  4589. try:
  4590. for k,v in prem[0]['prem'].items():
  4591. # sub_project_names.append(k)
  4592. sub_project_names.append(v.get("name",""))
  4593. for link in v['roleList']:
  4594. if link['role_name'] == 'tenderee' and tenderee == "":
  4595. tenderee = link['role_text']
  4596. if link['role_name'] == 'agency' and agency == "":
  4597. agency = link['role_text']
  4598. except Exception as e:
  4599. # print('解析prem 获取招标人、代理人出错')
  4600. pass
  4601. sub_project_names = ";".join(sub_project_names)
  4602. # 核心字段:标题+产品词+项目名称+标段名称
  4603. main_text = ",".join([doctitle, product, project_name, sub_project_names])
  4604. # 剔除 招标单位、代理机构名称
  4605. if tenderee:
  4606. doctitle = doctitle.replace(tenderee, " ")
  4607. main_text = main_text.replace(tenderee, " ")
  4608. if agency:
  4609. doctitle = doctitle.replace(agency, " ")
  4610. main_text = main_text.replace(agency, " ")
  4611. doctitle_dict = dict()
  4612. main_text_dict = dict()
  4613. for item in self.keyword_list:
  4614. _type = item[0]
  4615. key_wrod = item[1]
  4616. # 关键词排除词
  4617. key_paichuci = item[2]
  4618. key_paichuci_s = "|".join(key_paichuci.split('、'))
  4619. # 类型排除词
  4620. type_paichuci = item[3]
  4621. if type_paichuci:
  4622. paichuci_split = type_paichuci.split('、')
  4623. if re.search("|".join(paichuci_split), main_text):
  4624. continue
  4625. if doctitle:
  4626. if key_wrod in doctitle:
  4627. if not key_paichuci_s or (key_paichuci_s and not re.search(key_paichuci_s, doctitle)):
  4628. key_wrod_count1 = doctitle.count(key_wrod)
  4629. if _type not in doctitle_dict:
  4630. # doctitle_dict[_type] = {'关键词': [], '排除词': type_paichuci}
  4631. doctitle_dict[_type] = []
  4632. doctitle_dict[_type].append((key_wrod, key_wrod_count1))
  4633. if main_text:
  4634. if key_wrod in main_text:
  4635. if not key_paichuci_s or (key_paichuci_s and not re.search(key_paichuci_s, main_text)):
  4636. key_wrod_count2 = main_text.count(key_wrod)
  4637. if _type not in main_text_dict:
  4638. # main_text_dict[_type] = {'关键词': [], '排除词': type_paichuci}
  4639. main_text_dict[_type] = []
  4640. main_text_dict[_type].append((key_wrod, key_wrod_count2))
  4641. # 排序 doctitle
  4642. for k, v in doctitle_dict.items():
  4643. doctitle_dict[k].sort(key=lambda x: x[1], reverse=True)
  4644. # 按匹配次数保留前10个标签
  4645. if len(doctitle_dict) > 10:
  4646. doctitle_labels = [(k, sum(w[1] for w in doctitle_dict[k])) for k in doctitle_dict]
  4647. doctitle_labels.sort(key=lambda x: x[1], reverse=True)
  4648. for item in doctitle_labels[10:]:
  4649. doctitle_dict.pop(item[0])
  4650. # main_text
  4651. pop_list = []
  4652. for k, v in main_text_dict.items():
  4653. if sum([j[1] for j in main_text_dict[k]]) == 1:
  4654. # 关键词匹配次数等于1的标签
  4655. pop_list.append(k)
  4656. main_text_dict[k].sort(key=lambda x: x[1], reverse=True)
  4657. # 核心字段标签,若存在同一个标签的关键词匹配次数大于1,则只保留关键词匹配次数大于1的标签,关键词匹配次数等于1的标签不要
  4658. if len(pop_list) < len(main_text_dict):
  4659. for k in pop_list:
  4660. main_text_dict.pop(k)
  4661. # 按匹配次数保留前10个标签
  4662. if len(main_text_dict) > 10:
  4663. main_text_labels = [(k, sum(w[1] for w in main_text_dict[k])) for k in main_text_dict]
  4664. main_text_labels.sort(key=lambda x: x[1], reverse=True)
  4665. for item in main_text_labels[10:]:
  4666. main_text_dict.pop(item[0])
  4667. return {"标题":doctitle_dict,"核心字段":main_text_dict}
  4668. def predict_other(self,project_label,industry,doctitle,project_name,product,list_articles):
  4669. # doctextcon 取正文内容
  4670. doctextcon = list_articles[0].content.split('##attachment##')[0]
  4671. info_type = industry.get('industry',{}).get("class_name","")
  4672. doctitle = doctitle if doctitle else ""
  4673. product = product if product else ""
  4674. product = ",".join(set(product.split(','))) # 产品词去重
  4675. project_name = project_name if project_name else ""
  4676. get_kongjing_label = False
  4677. keywords_list = []
  4678. for item in self.kongjing_keyword_list:
  4679. key_wrod = item[0]
  4680. key_wrod2 = item[1]
  4681. search_type = item[2]
  4682. info_type_list = item[3]
  4683. info_type_list = info_type_list.split("|") if info_type_list else []
  4684. search_text = ""
  4685. if search_type=='正文':
  4686. search_text = ",".join([doctextcon,doctitle,project_name,product])
  4687. elif search_type=='产品':
  4688. search_text = ",".join([doctitle,project_name,product])
  4689. if search_type=='行业':
  4690. # ’行业’类型直接用info_type匹配关键词
  4691. if info_type==key_wrod:
  4692. # 匹配关键词记录
  4693. keywords_list.append(key_wrod)
  4694. get_kongjing_label = True
  4695. # break
  4696. else:
  4697. if key_wrod in search_text:
  4698. if key_wrod2 and key_wrod2 not in search_text:
  4699. continue
  4700. if info_type_list and info_type not in info_type_list:
  4701. continue
  4702. # 匹配关键词记录
  4703. if key_wrod2:
  4704. keywords_list.append(key_wrod+'+'+key_wrod2)
  4705. else:
  4706. keywords_list.append(key_wrod)
  4707. get_kongjing_label = True
  4708. # break
  4709. if get_kongjing_label:
  4710. project_label["核心字段"]["空净通"] = [[word,1] for word in keywords_list][:10]
  4711. return project_label
  4712. # 产权分类二级标签
  4713. class PropertyLabel():
  4714. '''
  4715. 产权分类二级标签
  4716. 全部类别:
  4717. 股权, 债权, 知识产权, 矿权, 房产, 土地, 交通运输工具, 闲置物资、设备、材料, 其他
  4718. '''
  4719. def __init__(self, ):
  4720. car = "比亚迪|奇瑞|奥迪|宝马|菲尼迪|雷克萨斯|三菱|铃木|马自达|奔驰|劳斯莱斯|北京现代|" \
  4721. "宾利|兰博基尼|布加迪|保时捷|斯柯达|雪佛兰|别克|凯迪拉克|庞蒂亚克|克尔维特|福特|林肯|克莱斯勒|道奇|JEEP品牌"
  4722. self.keywords_dict = {
  4723. "房产": "房产|住宅|公寓|商铺|车位|写字楼|办公楼|别墅|综合楼|在建工程|厂房|车库|车房|房转让|房屋|商品房|商业用房|"
  4724. "宅基地|[\u4e00-\u9fa5]{,2}用房|店面|商业房|门[面市]房|仓库|铺位|地下室|\d号?(房|室|门市|门面|商?铺|单元|户)|不动产|"
  4725. "自建房|铺面|商务楼|商住楼|阁楼|(杂物|储物|储藏)(房|间|室)|套房|[\da-zA-Z](栋|棟|幢|层|座|号?楼|单元)\d{1,4}(号|房|室|商?铺|户)|"
  4726. "[\da-zA-Z](栋|棟|幢|层|座|号?楼|单元)\d{2,}|门面+转让|楼+变卖|房地产",
  4727. "交通运输工具": "车辆|轿车|汽车(?!用品|库|位|衡)|公车|客车|货车|面包车|SUV|新能源车|二手车|车辆|商用车|机动车|观光车|巴车|"
  4728. "船舶|四驱" + "|" + car,
  4729. "股权": "\d.?股|股权(?!交易中心)|\d%(比例)?.?股|\d万.?股|\d.?元/股|增资(?!源)|扩股|股(转让|出售)|百分之[一二三四五六七八九十]{1,3}股",
  4730. "债权": "债权|债权转让|债权人|债务人|原债权人|新债权人|金融资产",
  4731. "土地": "住宅用地|商业用地|工业用地|国有[\u4e00-\u9fa5]{,3}[土用]地|集体土地|划拨|流转|地块编号|"
  4732. "土地使用权证|土地经营权|土地证|土地[发承]包|[\u4e00-\u9fa5]{,2}用地|土地\d{1,3}(亩|公?顷)|\d{1,3}(亩|公?顷)(使用|经营)权|"
  4733. "承包土地|(地块|土地)承包|水面经营权|[鱼水]塘|鱼池|(水面|旱田)[\u4e00-\u9fa5]{,3}[发承]包|水面资源|(水面|水田)[\u4e00-\u9fa5]{,3}权|"
  4734. "四荒|林地|林场|林木所有权|采伐权|水利设施所有权|水利设施使用权|海域|滩涂|林业产权|旱田|水田|机动田|机动地|耕地|荒地|农田|"
  4735. "苗圃地|塘口",
  4736. "矿权": "矿权|矿业权|采矿许可|探矿权|采矿权|开采权|矿产资源处置|矿[\u4e00-\u9fa5]{1,3}开[发采]",
  4737. "知识产权": "知识产权(?!局)|商标|专利|著作权|版权|商业秘密|科研成果",
  4738. "闲置物资、设备、材料": "(废旧|报废|废|闲置|二手|淘汰)(物资|资产|机械|设备|仪器|汽车|车|钢铁|钢材|钢|金属|塑料|材料|导管|漆|渣|有色|品|[\u4e00-\u9fa5]{,2}车|偶头)|"
  4739. "(金属|机械|设备|仪器|汽车|钢铁|钢材|钢|塑料|有色|)废料|废液|废旧|报废|边角料|残次品|(热轧|冷轧|酸洗|镀铝|热镀|镀锌|镀镁)|"
  4740. "机[器械]设备|医疗设备|生产设备|办公设备|仪器|仪表|设备出租|设备租赁|拖拉机|收割机|插秧机|挖机|车床|挖掘机|电机|"
  4741. "戒指|弃渣|电解质块|茶杯|装置|花瓶|女表|手表|男表|硫磺|物资|书画|茶叶|油茶|红茶|[茗名]茶|白酒|红酒|酒水|酒品|名酒|毛石|[石金木铁矿铜锌铝钢]料|"
  4742. "零部件",
  4743. "经营权": "经营权",
  4744. "租赁": "房+租|市场+续约|资产+出租|租赁|续租|招租|出租|租金|房租"
  4745. }
  4746. self.cqjy_keywords = self.get_cqjy_keywords()
  4747. self.score_idx = ["股权", "债权", "知识产权", "矿权", "房产", "土地", "交通运输工具", "闲置物资、设备、材料"]
  4748. def get_cqjy_keywords(self):
  4749. import csv
  4750. path = os.path.dirname(__file__)+'/property_label_products.csv'
  4751. with open(path, 'r',encoding='utf-8') as f:
  4752. reader = csv.reader(f)
  4753. key_word_list = []
  4754. for r in reader:
  4755. if r[0] == 'product':
  4756. continue
  4757. key_wrod = r[0]
  4758. _type = r[1]
  4759. key_word_list.append((_type, key_wrod))
  4760. return key_word_list
  4761. def get_type(self, text):
  4762. keyword_list = []
  4763. for key, value in self.keywords_dict.items():
  4764. keyword = "|".join([i for i in value.split("|") if '+' not in i])
  4765. keyword2 = [i for i in value.split("|") if '+' in i]
  4766. if re.search(keyword, text):
  4767. re1 = [i for i in re.finditer(keyword, text)][-1]
  4768. keyword_list.append((key, re1.start()))
  4769. else:
  4770. # 组合词 查询
  4771. for k in keyword2:
  4772. k1, k2 = k.split('+')
  4773. if re.search(k1, text) and re.search(k2, text):
  4774. keyword_list.append((key, re.search(k2, text).start()))
  4775. break
  4776. return keyword_list
  4777. def get_type2(self, text, cqjy_type_list):
  4778. have_type = [i[0] for i in cqjy_type_list]
  4779. for item in self.cqjy_keywords:
  4780. _type = item[0]
  4781. key_wrod = item[1]
  4782. if _type not in have_type:
  4783. if '+' in key_wrod:
  4784. k1, k2 = key_wrod.split('+')
  4785. if re.search(k1, text) and re.search(k2, text):
  4786. cqjy_type_list.append((_type, re.search(k2, text).start()))
  4787. have_type.append(_type)
  4788. else:
  4789. if key_wrod in text:
  4790. cqjy_type_list.append((_type, text.index(key_wrod)))
  4791. have_type.append(_type)
  4792. return cqjy_type_list
  4793. def predict(self, doctitle,product,project_name,prem,channel_dic):
  4794. docchannel = channel_dic['docchannel']['doctype']
  4795. # print('docchannel',docchannel)
  4796. if docchannel not in ['土地矿产', '拍卖出让', '产权交易']:
  4797. return ""
  4798. doctitle = doctitle if doctitle else ""
  4799. product = product if product else ""
  4800. product = ",".join(set(product.split(','))) # 产品词去重
  4801. project_name = project_name if project_name else ""
  4802. tenderee = ""
  4803. agency = ""
  4804. try:
  4805. for k,v in prem[0]['prem'].items():
  4806. for link in v['roleList']:
  4807. if link['role_name'] == 'tenderee' and tenderee == "":
  4808. tenderee = link['role_text']
  4809. if link['role_name'] == 'agency' and agency == "":
  4810. agency = link['role_text']
  4811. except Exception as e:
  4812. # print('解析prem 获取招标人、代理人出错')
  4813. pass
  4814. cqjy_type = []
  4815. idx = 0
  4816. for text in [doctitle, project_name, product]:
  4817. if tenderee:
  4818. text = text.replace(tenderee, "")
  4819. if agency:
  4820. text = text.replace(agency, "")
  4821. cqjy_type = self.get_type(text)
  4822. if not cqjy_type:
  4823. cqjy_type = self.get_type2(text, cqjy_type)
  4824. idx += 1
  4825. if idx == 2: # project_name
  4826. if len(re.split("[,、]", text)) > 9:
  4827. cqjy_type = []
  4828. if idx == 3: # product
  4829. if len(text.split(",")) > 15:
  4830. cqjy_type = []
  4831. if cqjy_type:
  4832. break
  4833. cqjy_type2 = [i[0] for i in cqjy_type]
  4834. if cqjy_type:
  4835. # 类别优先级调整
  4836. if "租赁" in cqjy_type2:
  4837. cqjy_type2 = ['租赁']
  4838. elif "经营权" in cqjy_type2:
  4839. cqjy_type2 = ['经营权']
  4840. elif "股权" in cqjy_type2 or "债权" in cqjy_type2 or "知识产权" in cqjy_type2:
  4841. cqjy_type.sort(key=lambda x: self.score_idx.index(x[0]))
  4842. cqjy_type = cqjy_type[0]
  4843. cqjy_type2 = [cqjy_type[0]]
  4844. elif len(cqjy_type2) == 2 and "房产" in cqjy_type2 and "土地" in cqjy_type2:
  4845. cqjy_type2 = ['房产']
  4846. else:
  4847. # 权重排序,取第一位
  4848. if idx in [1, 2]: # doctitle, project_name
  4849. cqjy_type.sort(key=lambda x: x[1], reverse=True)
  4850. cqjy_type = cqjy_type[0]
  4851. cqjy_type2 = [cqjy_type[0]]
  4852. else:
  4853. cqjy_type.sort(key=lambda x: self.score_idx.index(x[0]))
  4854. cqjy_type = cqjy_type[0]
  4855. cqjy_type2 = [cqjy_type[0]]
  4856. cqjy_type2 = ",".join(cqjy_type2)
  4857. if not cqjy_type2:
  4858. cqjy_type2 = '其他'
  4859. return cqjy_type2
  4860. # 总价单价提取
  4861. class TotalUnitMoney:
  4862. def __init__(self):
  4863. pass
  4864. def predict(self, list_sentences, list_entitys):
  4865. for i in range(len(list_entitys)):
  4866. list_entity = list_entitys[i]
  4867. # 总价单价
  4868. for _entity in list_entity:
  4869. if _entity.entity_type == 'money':
  4870. word_of_sentence = list_sentences[i][_entity.sentence_index].sentence_text
  4871. # 总价在中投标金额中
  4872. if _entity.label == 1:
  4873. result = extract_total_money(word_of_sentence,
  4874. _entity.entity_text,
  4875. [_entity.wordOffset_begin, _entity.wordOffset_end])
  4876. if result:
  4877. _entity.is_total_money = 1
  4878. # 单价在普通金额中
  4879. else:
  4880. result = extract_unit_money(word_of_sentence,
  4881. _entity.entity_text,
  4882. [_entity.wordOffset_begin, _entity.wordOffset_end])
  4883. if result:
  4884. _entity.is_unit_money = 1
  4885. # print("total_unit_money", _entity.entity_text,
  4886. # _entity.is_total_money, _entity.is_unit_money)
  4887. # 行业分类
  4888. class IndustryPredictor():
  4889. def __init__(self,):
  4890. self.model_path = os.path.dirname(__file__)+ '/industry_model'
  4891. self.id2lb = {0: '专业施工', 1: '专用仪器仪表', 2: '专用设备修理', 3: '互联网信息服务', 4: '互联网安全服务', 5: '互联网平台', 6: '互联网接入及相关服务', 7: '人力资源服务',
  4892. 8: '人造原油', 9: '仓储业', 10: '仪器仪表', 11: '仪器仪表修理', 12: '会计、审计及税务服务', 13: '会议、展览及相关服务', 14: '住宅、商业用房',
  4893. 15: '体育场地设施管理', 16: '体育组织', 17: '体育设备', 18: '保险服务', 19: '信息处理和存储支持服务', 20: '信息技术咨询服务',
  4894. 21: '信息系统集成和物联网技术服务', 22: '修缮工程', 23: '健康咨询', 24: '公路旅客运输', 25: '其他专业咨询与调查', 26: '其他专业技术服务',
  4895. 27: '其他交通运输设备', 28: '其他公共设施管理', 29: '其他土木工程建筑', 30: '其他工程服务', 31: '其他建筑建材', 32: '其他运输业', 33: '农业和林业机械',
  4896. 34: '农业服务', 35: '农产品', 36: '农副食品,动、植物油制品', 37: '出版业', 38: '办公消耗用品及类似物品', 39: '办公设备', 40: '化学原料及化学制品',
  4897. 41: '化学纤维', 42: '化学药品和中药专用设备', 43: '医疗设备', 44: '医药品', 45: '卫星传输服务', 46: '卫生', 47: '印刷服务', 48: '图书和档案',
  4898. 49: '图书档案设备', 50: '图书馆与档案馆', 51: '土地管理业', 52: '地质勘查', 53: '地震服务', 54: '场馆、站港用房', 55: '城市公共交通运输',
  4899. 56: '塑料制品、半成品及辅料', 57: '天然石料', 58: '娱乐设备', 59: '婚姻服务', 60: '安全保护服务', 61: '安全生产设备', 62: '家具用具',
  4900. 63: '家用电器修理', 64: '工业、生产用房', 65: '工业与专业设计及其他专业技术服务', 66: '工矿工程建筑', 67: '工程技术与设计服务', 68: '工程机械',
  4901. 69: '工程监理服务', 70: '工程评价服务', 71: '工程造价服务', 72: '市场调查', 73: '广告业', 74: '广播', 75: '广播、电视、电影设备',
  4902. 76: '广播电视传输服务', 77: '废弃资源综合利用业', 78: '建筑涂料', 79: '建筑物、构筑物附属结构', 80: '建筑物拆除和场地准备活动', 81: '建筑装饰和装修业',
  4903. 82: '录音制作', 83: '影视节目制作', 84: '房地产中介服务', 85: '房地产开发经营', 86: '房地产租赁经营', 87: '房屋租赁', 88: '招标代理',
  4904. 89: '探矿、采矿、选矿和造块设备', 90: '政法、检测专用设备', 91: '教育服务', 92: '教育设备', 93: '文物及非物质文化遗产保护', 94: '文物和陈列品',
  4905. 95: '文艺创作与表演', 96: '文艺设备', 97: '新闻业', 98: '旅行社及相关服务', 99: '日杂用品', 100: '有色金属冶炼及压延产品', 101: '有色金属矿',
  4906. 102: '木材、板材等', 103: '木材采集和加工设备', 104: '机械设备', 105: '机械设备经营租赁', 106: '林业产品', 107: '林业服务', 108: '架线和管道工程建筑',
  4907. 109: '核工业专用设备', 110: '橡胶制品', 111: '殡葬服务', 112: '殡葬设备及用品', 113: '气象服务', 114: '水上交通运输设备', 115: '水上运输业',
  4908. 116: '水利和水运工程建筑', 117: '水工机械', 118: '水文服务', 119: '水资源管理', 120: '污水处理及其再生利用', 121: '汽车、摩托车修理与维护',
  4909. 122: '法律服务', 123: '洗染服务', 124: '测绘地理信息服务', 125: '海洋仪器设备', 126: '海洋工程建筑', 127: '海洋服务', 128: '消防设备',
  4910. 129: '清洁服务', 130: '渔业产品', 131: '渔业服务', 132: '炼焦和金属冶炼轧制设备', 133: '烟草加工设备', 134: '热力生产和供应', 135: '焦炭及其副产品',
  4911. 136: '煤炭采选产品', 137: '燃气生产和供应业', 138: '物业管理', 139: '特种用途动、植物', 140: '环保咨询', 141: '环境与生态监测检测服务',
  4912. 142: '环境污染防治设备', 143: '环境治理业', 144: '玻璃及其制品', 145: '理发及美容服务', 146: '生态保护', 147: '电信',
  4913. 148: '电力、城市燃气、蒸汽和热水、水', 149: '电力供应', 150: '电力工业专用设备', 151: '电力工程施工', 152: '电力生产', 153: '电子和通信测量仪器',
  4914. 154: '电工、电子专用生产设备', 155: '电影放映', 156: '电气安装', 157: '电气设备', 158: '电气设备修理', 159: '畜牧业服务', 160: '监控设备',
  4915. 161: '石油制品', 162: '石油和化学工业专用设备', 163: '石油和天然气开采产品', 164: '石油天然气开采专用设备', 165: '研究和试验发展', 166: '社会工作',
  4916. 167: '社会经济咨询', 168: '科技推广和应用服务业', 169: '科研、医疗、教育用房', 170: '管道和设备安装', 171: '粮油作物和饲料加工设备', 172: '纸、纸制品及印刷品',
  4917. 173: '纺织原料、毛皮、被服装具', 174: '纺织设备', 175: '绿化管理', 176: '缝纫、服饰、制革和毛皮加工设备', 177: '航空器及其配套设备', 178: '航空客货运输',
  4918. 179: '航空航天工业专用设备', 180: '节能环保工程施工', 181: '装卸搬运', 182: '计算机和办公设备维修', 183: '计算机设备', 184: '计量标准器具及量具、衡器',
  4919. 185: '货币处理专用设备', 186: '货币金融服务', 187: '质检技术服务', 188: '资本市场服务', 189: '车辆', 190: '边界勘界和联检专用设备', 191: '运行维护服务',
  4920. 192: '通信设备', 193: '通用设备修理', 194: '道路货物运输', 195: '邮政专用设备', 196: '邮政业', 197: '采矿业和制造业服务',
  4921. 198: '铁路、船舶、航空航天等运输设备修理', 199: '铁路、道路、隧道和桥梁工程建筑', 200: '铁路运输设备', 201: '防洪除涝设施管理', 202: '陶瓷制品',
  4922. 203: '雷达、无线电和卫星导航设备', 204: '非金属矿', 205: '非金属矿物制品工业专用设备', 206: '非金属矿物材料', 207: '食品加工专用设备', 208: '食品及加工盐',
  4923. 209: '餐饮业', 210: '饮料、酒精及精制茶', 211: '饮料加工设备', 212: '饲养动物及其产品', 213: '黑色金属冶炼及压延产品', 214: '黑色金属矿'}
  4924. self.industry_dic = {'专业施工': {'大类': '专业施工', '门类': '建筑业'},
  4925. '专用仪器仪表': {'大类': '专用设备', '门类': '零售批发'},
  4926. '专用设备修理': {'大类': '金属制品、机械和设备修理业', '门类': '金属制品、机械和设备修理业'},
  4927. '互联网信息服务': {'大类': '互联网和相关服务', '门类': '信息传输、软件和信息技术服务业'},
  4928. '互联网安全服务': {'大类': '互联网和相关服务', '门类': '信息传输、软件和信息技术服务业'},
  4929. '互联网平台': {'大类': '互联网和相关服务', '门类': '信息传输、软件和信息技术服务业'},
  4930. '互联网接入及相关服务': {'大类': '互联网和相关服务', '门类': '信息传输、软件和信息技术服务业'},
  4931. '人力资源服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4932. '人造原油': {'大类': '炼焦产品、炼油产品', '门类': '零售批发'},
  4933. '仓储业': {'大类': '装卸搬运和运输代理业', '门类': '交通运输、仓储和邮政业'},
  4934. '仪器仪表': {'大类': '通用设备', '门类': '零售批发'},
  4935. '仪器仪表修理': {'大类': '金属制品、机械和设备修理业', '门类': '金属制品、机械和设备修理业'},
  4936. '会计、审计及税务服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4937. '会议、展览及相关服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4938. '住宅、商业用房': {'大类': '房屋建筑业', '门类': '建筑业'},
  4939. '体育场地设施管理': {'大类': '体育', '门类': '文化、体育和娱乐业'},
  4940. '体育组织': {'大类': '体育', '门类': '文化、体育和娱乐业'},
  4941. '体育设备': {'大类': '专用设备', '门类': '零售批发'},
  4942. '保险服务': {'大类': '保险业', '门类': '金融业'},
  4943. '信息处理和存储支持服务': {'大类': '软件和信息技术服务业', '门类': '信息传输、软件和信息技术服务业'},
  4944. '信息技术咨询服务': {'大类': '软件和信息技术服务业', '门类': '信息传输、软件和信息技术服务业'},
  4945. '信息系统集成和物联网技术服务': {'大类': '软件和信息技术服务业', '门类': '信息传输、软件和信息技术服务业'},
  4946. '修缮工程': {'大类': '修缮工程', '门类': '建筑业'},
  4947. '健康咨询': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4948. '公路旅客运输': {'大类': '道路运输业', '门类': '交通运输、仓储和邮政业'},
  4949. '其他专业咨询与调查': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4950. '其他专业技术服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4951. '其他交通运输设备': {'大类': '专用设备', '门类': '零售批发'},
  4952. '其他公共设施管理': {'大类': '公共设施管理业', '门类': '水利、环境和公共设施管理业'},
  4953. '其他土木工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  4954. '其他工程服务': {'大类': '工程服务', '门类': '科学研究和技术服务业'},
  4955. '其他建筑建材': {'大类': '建筑建材', '门类': '零售批发'},
  4956. '其他运输业': {'大类': '其他运输业', '门类': '交通运输、仓储和邮政业'},
  4957. '农业和林业机械': {'大类': '专用设备', '门类': '零售批发'},
  4958. '农业服务': {'大类': '农林牧副渔服务', '门类': '农林牧副渔服务'},
  4959. '农产品': {'大类': '农林牧渔业产品', '门类': '零售批发'},
  4960. '农副食品,动、植物油制品': {'大类': '食品、饮料和烟草原料', '门类': '零售批发'},
  4961. '出版业': {'大类': '新闻和出版业', '门类': '文化、体育和娱乐业'},
  4962. '办公消耗用品及类似物品': {'大类': '办公消耗用品及类似物品', '门类': '零售批发'},
  4963. '办公设备': {'大类': '通用设备', '门类': '零售批发'},
  4964. '化学原料及化学制品': {'大类': '基础化学品及相关产品', '门类': '零售批发'},
  4965. '化学纤维': {'大类': '基础化学品及相关产品', '门类': '零售批发'},
  4966. '化学药品和中药专用设备': {'大类': '专用设备', '门类': '零售批发'},
  4967. '医疗设备': {'大类': '专用设备', '门类': '零售批发'},
  4968. '医药品': {'大类': '医药品', '门类': '零售批发'},
  4969. '卫星传输服务': {'大类': '电信、广播电视和卫星传输服务', '门类': '信息传输、软件和信息技术服务业'},
  4970. '卫生': {'大类': '卫生', '门类': '卫生和社会工作'},
  4971. '印刷服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4972. '图书和档案': {'大类': '图书和档案', '门类': '零售批发'},
  4973. '图书档案设备': {'大类': '通用设备', '门类': '零售批发'},
  4974. '图书馆与档案馆': {'大类': '文化艺术业', '门类': '文化、体育和娱乐业'},
  4975. '土地管理业': {'大类': '土地管理业', '门类': '水利、环境和公共设施管理业'},
  4976. '地质勘查': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4977. '地震服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4978. '场馆、站港用房': {'大类': '房屋建筑业', '门类': '建筑业'},
  4979. '城市公共交通运输': {'大类': '道路运输业', '门类': '交通运输、仓储和邮政业'},
  4980. '塑料制品、半成品及辅料': {'大类': '橡胶、塑料、玻璃和陶瓷制品', '门类': '零售批发'},
  4981. '天然石料': {'大类': '建筑建材', '门类': '零售批发'},
  4982. '娱乐设备': {'大类': '专用设备', '门类': '零售批发'},
  4983. '婚姻服务': {'大类': '居民服务业', '门类': '居民服务、修理和其他服务业'},
  4984. '安全保护服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4985. '安全生产设备': {'大类': '专用设备', '门类': '零售批发'},
  4986. '家具用具': {'大类': '家具用具', '门类': '零售批发'},
  4987. '家用电器修理': {'大类': '机动车、电子产品和日用产品修理业', '门类': '居民服务、修理和其他服务业'},
  4988. '工业、生产用房': {'大类': '房屋建筑业', '门类': '建筑业'},
  4989. '工业与专业设计及其他专业技术服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4990. '工矿工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  4991. '工程技术与设计服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4992. '工程机械': {'大类': '专用设备', '门类': '零售批发'},
  4993. '工程监理服务': {'大类': '工程服务', '门类': '科学研究和技术服务业'},
  4994. '工程评价服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4995. '工程造价服务': {'大类': '工程服务', '门类': '科学研究和技术服务业'},
  4996. '市场调查': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4997. '广告业': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4998. '广播': {'大类': '广播、电视、电影和影视录音制作业', '门类': '文化、体育和娱乐业'},
  4999. '广播、电视、电影设备': {'大类': '通用设备', '门类': '零售批发'},
  5000. '广播电视传输服务': {'大类': '电信、广播电视和卫星传输服务', '门类': '信息传输、软件和信息技术服务业'},
  5001. '废弃资源综合利用业': {'大类': '废弃资源综合利用业', '门类': '废弃资源综合利用业'},
  5002. '建筑涂料': {'大类': '建筑建材', '门类': '零售批发'},
  5003. '建筑物、构筑物附属结构': {'大类': '建筑建材', '门类': '零售批发'},
  5004. '建筑物拆除和场地准备活动': {'大类': '建筑装饰和其他建筑业', '门类': '建筑业'},
  5005. '建筑装饰和装修业': {'大类': '建筑装饰和其他建筑业', '门类': '建筑业'},
  5006. '录音制作': {'大类': '广播、电视、电影和影视录音制作业', '门类': '文化、体育和娱乐业'},
  5007. '影视节目制作': {'大类': '广播、电视、电影和影视录音制作业', '门类': '文化、体育和娱乐业'},
  5008. '房地产中介服务': {'大类': '房地产业', '门类': '房地产业'},
  5009. '房地产开发经营': {'大类': '房地产业', '门类': '房地产业'},
  5010. '房地产租赁经营': {'大类': '房地产业', '门类': '房地产业'},
  5011. '房屋租赁': {'大类': '租赁业', '门类': '租赁和商务服务业'},
  5012. '招标代理': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  5013. '探矿、采矿、选矿和造块设备': {'大类': '专用设备', '门类': '零售批发'},
  5014. '政法、检测专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5015. '教育服务': {'大类': '教育服务', '门类': '教育'},
  5016. '教育设备': {'大类': '专用设备', '门类': '零售批发'},
  5017. '文体设备和用品出租': {'大类': '租赁业', '门类': '租赁和商务服务业'},
  5018. '文物及非物质文化遗产保护': {'大类': '文化艺术业', '门类': '文化、体育和娱乐业'},
  5019. '文物和陈列品': {'大类': '文物和陈列品', '门类': '零售批发'},
  5020. '文艺创作与表演': {'大类': '文化艺术业', '门类': '文化、体育和娱乐业'},
  5021. '文艺设备': {'大类': '专用设备', '门类': '零售批发'},
  5022. '新闻业': {'大类': '新闻和出版业', '门类': '文化、体育和娱乐业'},
  5023. '旅行社及相关服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  5024. '日杂用品': {'大类': '日杂用品', '门类': '零售批发'},
  5025. '有色金属冶炼及压延产品': {'大类': '建筑建材', '门类': '零售批发'},
  5026. '有色金属矿': {'大类': '矿与矿物', '门类': '零售批发'},
  5027. '木材、板材等': {'大类': '建筑建材', '门类': '零售批发'},
  5028. '木材采集和加工设备': {'大类': '专用设备', '门类': '零售批发'},
  5029. '机械设备': {'大类': '通用设备', '门类': '零售批发'},
  5030. '机械设备经营租赁': {'大类': '租赁业', '门类': '租赁和商务服务业'},
  5031. '林业产品': {'大类': '农林牧渔业产品', '门类': '零售批发'},
  5032. '林业服务': {'大类': '农林牧副渔服务', '门类': '农林牧副渔服务'},
  5033. '架线和管道工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  5034. '核工业专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5035. '橡胶制品': {'大类': '橡胶、塑料、玻璃和陶瓷制品', '门类': '零售批发'},
  5036. '殡葬服务': {'大类': '居民服务业', '门类': '居民服务、修理和其他服务业'},
  5037. '殡葬设备及用品': {'大类': '专用设备', '门类': '零售批发'},
  5038. '气象服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  5039. '水上交通运输设备': {'大类': '专用设备', '门类': '零售批发'},
  5040. '水上运输业': {'大类': '水上运输业', '门类': '交通运输、仓储和邮政业'},
  5041. '水利和水运工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  5042. '水工机械': {'大类': '专用设备', '门类': '零售批发'},
  5043. '水文服务': {'大类': '水利管理业', '门类': '水利、环境和公共设施管理业'},
  5044. '水资源管理': {'大类': '水利管理业', '门类': '水利、环境和公共设施管理业'},
  5045. '污水处理及其再生利用': {'大类': '水的生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  5046. '汽车、摩托车修理与维护': {'大类': '机动车、电子产品和日用产品修理业', '门类': '居民服务、修理和其他服务业'},
  5047. '法律服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  5048. '洗染服务': {'大类': '居民服务业', '门类': '居民服务、修理和其他服务业'},
  5049. '测绘地理信息服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  5050. '海洋仪器设备': {'大类': '专用设备', '门类': '零售批发'},
  5051. '海洋工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  5052. '海洋服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  5053. '消防设备': {'大类': '专用设备', '门类': '零售批发'},
  5054. '清洁服务': {'大类': '其他服务业', '门类': '居民服务、修理和其他服务业'},
  5055. '渔业产品': {'大类': '农林牧渔业产品', '门类': '零售批发'},
  5056. '渔业服务': {'大类': '农林牧副渔服务', '门类': '农林牧副渔服务'},
  5057. '炼焦和金属冶炼轧制设备': {'大类': '专用设备', '门类': '零售批发'},
  5058. '烟草加工设备': {'大类': '专用设备', '门类': '零售批发'},
  5059. '热力生产和供应': {'大类': '电力、热力生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  5060. '焦炭及其副产品': {'大类': '炼焦产品、炼油产品', '门类': '零售批发'},
  5061. '煤炭采选产品': {'大类': '矿与矿物', '门类': '零售批发'},
  5062. '燃气生产和供应业': {'大类': '燃气生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  5063. '物业管理': {'大类': '房地产业', '门类': '房地产业'},
  5064. '特种用途动、植物': {'大类': '农林牧渔业产品', '门类': '零售批发'},
  5065. '环保咨询': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  5066. '环境与生态监测检测服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  5067. '环境污染防治设备': {'大类': '专用设备', '门类': '零售批发'},
  5068. '环境治理业': {'大类': '生态保护和环境治理业', '门类': '水利、环境和公共设施管理业'},
  5069. '玻璃及其制品': {'大类': '橡胶、塑料、玻璃和陶瓷制品', '门类': '零售批发'},
  5070. '理发及美容服务': {'大类': '居民服务业', '门类': '居民服务、修理和其他服务业'},
  5071. '生态保护': {'大类': '生态保护和环境治理业', '门类': '水利、环境和公共设施管理业'},
  5072. '电信': {'大类': '电信、广播电视和卫星传输服务', '门类': '信息传输、软件和信息技术服务业'},
  5073. '电力、城市燃气、蒸汽和热水、水': {'大类': '电力、城市燃气、蒸汽和热水、水', '门类': '零售批发'},
  5074. '电力供应': {'大类': '电力、热力生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  5075. '电力工业专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5076. '电力工程施工': {'大类': '土木工程建筑业', '门类': '建筑业'},
  5077. '电力生产': {'大类': '电力、热力生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  5078. '电子和通信测量仪器': {'大类': '通用设备', '门类': '零售批发'},
  5079. '电工、电子专用生产设备': {'大类': '专用设备', '门类': '零售批发'},
  5080. '电影放映': {'大类': '广播、电视、电影和影视录音制作业', '门类': '文化、体育和娱乐业'},
  5081. '电气安装': {'大类': '建筑安装业', '门类': '建筑业'},
  5082. '电气设备': {'大类': '通用设备', '门类': '零售批发'},
  5083. '电气设备修理': {'大类': '金属制品、机械和设备修理业', '门类': '金属制品、机械和设备修理业'},
  5084. '畜牧业服务': {'大类': '农林牧副渔服务', '门类': '农林牧副渔服务'},
  5085. '监控设备': {'大类': '通用设备', '门类': '零售批发'},
  5086. '石油制品': {'大类': '炼焦产品、炼油产品', '门类': '零售批发'},
  5087. '石油和化学工业专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5088. '石油和天然气开采产品': {'大类': '矿与矿物', '门类': '零售批发'},
  5089. '石油天然气开采专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5090. '研究和试验发展': {'大类': '研究和试验发展', '门类': '科学研究和技术服务业'},
  5091. '社会工作': {'大类': '社会工作', '门类': '卫生和社会工作'},
  5092. '社会经济咨询': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  5093. '科技推广和应用服务业': {'大类': '科技推广和应用服务业', '门类': '科学研究和技术服务业'},
  5094. '科研、医疗、教育用房': {'大类': '房屋建筑业', '门类': '建筑业'},
  5095. '管道和设备安装': {'大类': '建筑安装业', '门类': '建筑业'},
  5096. '粮油作物和饲料加工设备': {'大类': '专用设备', '门类': '零售批发'},
  5097. '纸、纸制品及印刷品': {'大类': '纸、纸制品及印刷品', '门类': '零售批发'},
  5098. '纺织原料、毛皮、被服装具': {'大类': '纺织原料、毛皮、被服装具', '门类': '零售批发'},
  5099. '纺织设备': {'大类': '专用设备', '门类': '零售批发'},
  5100. '绿化管理': {'大类': '公共设施管理业', '门类': '水利、环境和公共设施管理业'},
  5101. '缝纫、服饰、制革和毛皮加工设备': {'大类': '专用设备', '门类': '零售批发'},
  5102. '航空器及其配套设备': {'大类': '专用设备', '门类': '零售批发'},
  5103. '航空客货运输': {'大类': '航空运输业', '门类': '交通运输、仓储和邮政业'},
  5104. '航空航天工业专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5105. '节能环保工程施工': {'大类': '土木工程建筑业', '门类': '建筑业'},
  5106. '装卸搬运': {'大类': '装卸搬运和运输代理业', '门类': '交通运输、仓储和邮政业'},
  5107. '计算机和办公设备维修': {'大类': '机动车、电子产品和日用产品修理业', '门类': '居民服务、修理和其他服务业'},
  5108. '计算机设备': {'大类': '通用设备', '门类': '零售批发'},
  5109. '计量标准器具及量具、衡器': {'大类': '通用设备', '门类': '零售批发'},
  5110. '货币处理专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5111. '货币金融服务': {'大类': '货币金融服务', '门类': '金融业'},
  5112. '质检技术服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  5113. '资本市场服务': {'大类': '资本市场服务', '门类': '金融业'},
  5114. '车辆': {'大类': '通用设备', '门类': '零售批发'},
  5115. '边界勘界和联检专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5116. '运行维护服务': {'大类': '软件和信息技术服务业', '门类': '信息传输、软件和信息技术服务业'},
  5117. '通信设备': {'大类': '通用设备', '门类': '零售批发'},
  5118. '通用设备修理': {'大类': '金属制品、机械和设备修理业', '门类': '金属制品、机械和设备修理业'},
  5119. '道路货物运输': {'大类': '道路运输业', '门类': '交通运输、仓储和邮政业'},
  5120. '邮政专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5121. '邮政业': {'大类': '邮政业', '门类': '交通运输、仓储和邮政业'},
  5122. '采矿业和制造业服务': {'大类': '采矿业和制造业服务', '门类': '农林牧副渔服务'},
  5123. '铁路、船舶、航空航天等运输设备修理': {'大类': '金属制品、机械和设备修理业', '门类': '金属制品、机械和设备修理业'},
  5124. '铁路、道路、隧道和桥梁工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  5125. '铁路运输设备': {'大类': '专用设备', '门类': '零售批发'},
  5126. '防洪除涝设施管理': {'大类': '水利管理业', '门类': '水利、环境和公共设施管理业'},
  5127. '陶瓷制品': {'大类': '橡胶、塑料、玻璃和陶瓷制品', '门类': '零售批发'},
  5128. '雷达、无线电和卫星导航设备': {'大类': '通用设备', '门类': '零售批发'},
  5129. '非金属矿': {'大类': '矿与矿物', '门类': '零售批发'},
  5130. '非金属矿物制品工业专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5131. '非金属矿物材料': {'大类': '建筑建材', '门类': '零售批发'},
  5132. '食品加工专用设备': {'大类': '专用设备', '门类': '零售批发'},
  5133. '食品及加工盐': {'大类': '食品、饮料和烟草原料', '门类': '零售批发'},
  5134. '餐饮业': {'大类': '餐饮业', '门类': '住宿和餐饮业'},
  5135. '饮料、酒精及精制茶': {'大类': '食品、饮料和烟草原料', '门类': '零售批发'},
  5136. '饮料加工设备': {'大类': '专用设备', '门类': '零售批发'},
  5137. '饲养动物及其产品': {'大类': '农林牧渔业产品', '门类': '零售批发'},
  5138. '黑色金属冶炼及压延产品': {'大类': '建筑建材', '门类': '零售批发'},
  5139. '黑色金属矿': {'大类': '矿与矿物', '门类': '零售批发'}}
  5140. self.sess = tf.Session(graph=tf.Graph())
  5141. self.get_model()
  5142. with open(os.path.dirname(__file__)+'/industry_rule_kw_json/tw_industry_keyword_org/tw_industry_keyword_org.json', 'r',
  5143. encoding='utf-8') as fp1:
  5144. self.json_data_industry = json.load(fp1)
  5145. with open(os.path.dirname(__file__)+'/industry_rule_kw_json/tw_company_classification_keyword/tw_company_classification_keyword.json', 'r',
  5146. encoding='utf-8') as fp2:
  5147. self.json_data_company = json.load(fp2)
  5148. with open(os.path.dirname(__file__)+'/industry_rule_kw_json/tw_custom_keyword/tw_custom_keyword.json', 'r', encoding='utf-8') as fp3:
  5149. self.json_data_custom = json.load(fp3)
  5150. def get_model(self):
  5151. with self.sess.as_default() as sess:
  5152. with self.sess.graph.as_default():
  5153. meta_graph_def = tf.saved_model.loader.load(sess,
  5154. tags=['serve'],
  5155. export_dir=os.path.dirname(__file__)+'/industry_model')
  5156. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  5157. signature_def = meta_graph_def.signature_def
  5158. self.title = sess.graph.get_tensor_by_name(signature_def[signature_key].inputs['title'].name)
  5159. self.project = sess.graph.get_tensor_by_name(signature_def[signature_key].inputs['project'].name)
  5160. self.product = sess.graph.get_tensor_by_name(signature_def[signature_key].inputs['product'].name)
  5161. self.outputs = sess.graph.get_tensor_by_name(signature_def[signature_key].outputs['outputs'].name)
  5162. def text2array(self, text, tenderee='', maxSententLen=20):
  5163. tenderee = tenderee.replace('(', '(').replace(')', ')')
  5164. text = text.replace('(', '(').replace(')', ')')
  5165. text = re.sub(
  5166. '(废标|终止|综?合?评审|评标|开标|资审|履约|验收|成交|中标人?|中选人?|单一来源|合同|候选人|结果|变更|更正|答疑|澄清|意向|需求|采购|招标|询比?价|磋商|谈判|比选|比价|竞价|议价)的?(公告|预告|公示)?|关于为?|选取|定点|直接|邀请函?|通知书?|备案|公开|公示|公告|记录|竞争性',
  5167. ' ', text)
  5168. text = text.replace(tenderee, ' ')
  5169. text = ' ' if text=="" else text
  5170. words_docs_list = selffool.cut(text)
  5171. words_docs_list = [[it for it in l if re.search('^[\u4e00-\u9fa5]+$', it)][-maxSententLen:] for l in words_docs_list]
  5172. array = embedding(words_docs_list, shape=(len(words_docs_list), maxSententLen, 128))
  5173. return array
  5174. def process(self, title, project, product, tenderee):
  5175. return self.text2array(title, tenderee), self.text2array(project, tenderee), self.text2array(product)
  5176. def predict_model(self, title, project, product, tenderee=''):
  5177. title_array, project_array, product_array = self.process(title, project, product, tenderee)
  5178. rs = self.sess.run(self.outputs,
  5179. feed_dict={
  5180. self.title:title_array,
  5181. self.project:project_array,
  5182. self.product:product_array
  5183. }
  5184. )
  5185. pred = np.argmax(rs[0])
  5186. return self.id2lb[pred], rs[0][pred]
  5187. # # 返回top2 结果
  5188. # pred_list = np.argsort(-rs[0])
  5189. # return self.id2lb[pred_list[0]], self.id2lb[pred_list[1]], rs[0][pred_list[0]], rs[0][pred_list[1]]
  5190. def predict_rule(self, doctitle, tenderee, win_tenderer, project_name, product):
  5191. doctitle = doctitle if doctitle else ''
  5192. tenderee = tenderee if tenderee else ''
  5193. win_tenderer = win_tenderer if win_tenderer else ''
  5194. project_name = project_name if project_name else ''
  5195. product = product if product else ''
  5196. text_ind = (doctitle + project_name + product).replace(tenderee, '')
  5197. text_ind = text_ind.replace('墙面粉刷', '墙面 粉刷')
  5198. text_com = win_tenderer
  5199. length_ind_text = len(text_ind) + 1
  5200. length_com_text = len(text_com) + 1
  5201. # print(text)
  5202. dic_res = {} # 行业分类字典
  5203. score_lst = [] # 得分列表
  5204. word_lst = [] # 关键词列表
  5205. # 主要内容关键词
  5206. if text_ind:
  5207. # logging.info("data_ind%s"%str(_json_data_industry[0]))
  5208. for data_industry in self.json_data_industry:
  5209. industry = data_industry['xiaolei']
  5210. key_word = data_industry['key_word']
  5211. key_word_2 = data_industry['key_word2']
  5212. power = float(data_industry['power']) if data_industry['power'] else 0
  5213. this_score = power * (text_ind.count(key_word) * len(key_word) / length_ind_text)
  5214. if key_word_2:
  5215. # key_word_compose = key_word + "+" + key_word_2
  5216. if text_ind.count(key_word_2) == 0:
  5217. this_score = 0
  5218. if this_score > 0:
  5219. # print(industry,key_word,this_score)
  5220. if industry in dic_res.keys():
  5221. dic_res[industry] += this_score
  5222. else:
  5223. dic_res[industry] = this_score
  5224. if key_word not in word_lst:
  5225. word_lst.append(key_word)
  5226. # 供应商关键词
  5227. if text_com:
  5228. for data_company in self.json_data_company:
  5229. industry = data_company['industry_type']
  5230. key_word = data_company['company_word']
  5231. power = float(data_company['industry_rate']) if data_company['industry_rate'] else 0
  5232. this_score = power * (text_com.count(key_word) * len(key_word) / length_com_text)
  5233. if this_score > 0:
  5234. # print(industry,key_word,this_score)
  5235. if industry in dic_res.keys():
  5236. dic_res[industry] += this_score
  5237. else:
  5238. dic_res[industry] = this_score
  5239. if key_word not in word_lst:
  5240. word_lst.append(key_word)
  5241. # 自定义关键词
  5242. if text_ind:
  5243. custom_ind = [
  5244. ['tenderee', '医院|疾病预防', ['设备', '系统', '器'], '医疗设备'],
  5245. ['tenderee', '学校|大学|小学|中学|学院|幼儿园', ['设备', '器'], '教育设备'],
  5246. ['tenderee', '学校|大学|小学|中学|学院|幼儿园|医院', ['工程'], '科研、医疗、教育用房'],
  5247. ['tenderee', '供电局|电网|国网|电力|电厂|粤电', ['设备', '器', '物资'], '电力工业专用设备'],
  5248. ['tenderee', '公安|法院|检察院', ['设备', '器'], '政法、检测专用设备'],
  5249. ['tenderee', '^中铁|^中交|^中建|中国建筑', ['材料'], '其他建筑建材'],
  5250. ['doctextcon', '信息技术服务|系统开发|信息化|信息系统', ['监理'], '信息技术咨询服务'],
  5251. ['doctextcon', '工程', ['消防'], '专业施工'],
  5252. ['doctextcon', '铁路|航空|船舶|航天|广铁', ['维修'], '铁路、船舶、航空航天等运输设备修理'],
  5253. ['doctextcon', '设备|仪|器', ['租赁'], '机械设备经营租赁'],
  5254. ['doctextcon', '交通|铁路|公路|道路|桥梁', ['工程'], '铁路、道路、隧道和桥梁工程建筑'],
  5255. ['win_tenderer', '电力', ['设备', '器'], '电力工业专用设备'],
  5256. ['win_tenderer', '信息|网络科技', ['系统'], '信息系统集成和物联网技术服务'],
  5257. ['tenderee,doctextcon', '铁路|广铁|铁道', ['设备', '器', '物资', '材料', '铁路'], '铁路运输设备'],
  5258. ]
  5259. for data_custom in self.json_data_custom:
  5260. industry_custom = data_custom['industry']
  5261. key_word = data_custom['company_word']
  5262. power = float(data_custom['industry_rate'])
  5263. for k in range(len(custom_ind)):
  5264. subject = ''
  5265. if 'tenderee' in custom_ind[k][0]:
  5266. subject += tenderee
  5267. if 'win_tenderer' in custom_ind[k][0]:
  5268. subject += win_tenderer
  5269. if 'doctextcon' in custom_ind[k][0]:
  5270. subject += text_ind
  5271. ptn = custom_ind[k][1]
  5272. # print('ptn',ptn)
  5273. if re.search(ptn, subject) and industry_custom in custom_ind[k][2]:
  5274. industry = custom_ind[k][3]
  5275. else:
  5276. continue
  5277. this_score = power * (text_ind.count(key_word) * len(key_word) / len(subject))
  5278. if this_score > 0:
  5279. # print(industry,key_word,this_score)
  5280. if industry in dic_res.keys():
  5281. dic_res[industry] += this_score
  5282. else:
  5283. dic_res[industry] = this_score
  5284. if key_word not in word_lst:
  5285. word_lst.append(key_word)
  5286. sort_res = sorted(dic_res.items(), key=lambda x: x[1], reverse=True)
  5287. lst_res = [s[0] for s in sort_res]
  5288. score_lst = [str(round(float(s[1]), 2)) for s in sort_res]
  5289. if len(lst_res) > 0:
  5290. return lst_res, score_lst, word_lst
  5291. else:
  5292. return [""], [], []
  5293. def predict_merge(self, pinmu_type, industry_lst):
  5294. '''
  5295. 通过一系列规则最终决定使用模型还是规则的结果
  5296. :param pinmu_type: 模型预测类别
  5297. :param industry_lst: 规则预测类别列表
  5298. :return:
  5299. '''
  5300. industry_type = industry_lst[0]
  5301. if industry_type == "":
  5302. return pinmu_type
  5303. if industry_type == '专用设备修理' and re.search('修理|维修|装修|修缮', pinmu_type):
  5304. final_type = pinmu_type
  5305. elif industry_type == '其他土木工程建筑' and re.search('工程|建筑|用房|施工|安装|质检|其他专业咨询与调查', pinmu_type):
  5306. final_type = pinmu_type
  5307. elif pinmu_type == '专用设备修理' and re.search('工程|修理', industry_type):
  5308. final_type = industry_type
  5309. elif pinmu_type == '信息系统集成和物联网技术服务' and re.search('卫星传输|信息处理和存储支持服务|信息技术咨询服务|运行维护服务|其他专业技术服务|医疗设备|医药品',
  5310. industry_type):
  5311. final_type = industry_type
  5312. elif industry_type == '仪器仪表' and re.search('仪器|器具|医疗设备', pinmu_type):
  5313. final_type = pinmu_type
  5314. elif industry_type == '医药品' and re.search('医疗设备', pinmu_type):
  5315. final_type = pinmu_type
  5316. elif industry_type == '医药品' and re.search('医疗设备', pinmu_type):
  5317. final_type = pinmu_type
  5318. elif re.search('设备', industry_type) and re.search('修理|维修', pinmu_type):
  5319. final_type = pinmu_type
  5320. elif industry_type == '社会工作' and re.search('工程', pinmu_type):
  5321. final_type = pinmu_type
  5322. elif industry_type == '信息系统集成和物联网技术服务' and re.search('信息处理|设备', pinmu_type):
  5323. final_type = pinmu_type
  5324. elif industry_type == '研究和试验发展' and re.search('其他专业咨询与调查|质检技术服务|信息系统集成|其他工程服务', pinmu_type):
  5325. final_type = pinmu_type
  5326. elif industry_type == '其他专业咨询与调查' and re.search('工程造价服务', pinmu_type):
  5327. final_type = pinmu_type
  5328. elif industry_type == '广告业' and re.search('印刷服务|影视节目制作|信息系统', pinmu_type):
  5329. final_type = pinmu_type
  5330. elif industry_type == '清洁服务' and re.search('工程|环境污染防治设备|修理', pinmu_type):
  5331. final_type = pinmu_type
  5332. elif industry_type == '其他公共设施管理' and re.search('信息系统', pinmu_type):
  5333. final_type = pinmu_type
  5334. elif industry_type == '其他专业技术服务' and re.search('工程技术与设计服务|质检技术服务|环境与生态监测检测服务', pinmu_type):
  5335. final_type = pinmu_type
  5336. elif industry_type == '机械设备经营租赁' and re.search('电信', pinmu_type):
  5337. final_type = pinmu_type
  5338. elif industry_type == '货币金融服务' and re.search('信息系统集成和物联网技术服务', pinmu_type):
  5339. final_type = pinmu_type
  5340. elif industry_type == '体育场地设施管理' and re.search('体育设备', pinmu_type):
  5341. final_type = pinmu_type
  5342. elif industry_type == '安全保护服务' and re.search('信息系统|监控设备|互联网安全服务', pinmu_type):
  5343. final_type = pinmu_type
  5344. elif industry_type == '互联网接入及相关服务' and re.search('通信设备', pinmu_type):
  5345. final_type = pinmu_type
  5346. elif industry_type == '卫生' and re.search('医疗设备|信息系统', pinmu_type):
  5347. final_type = pinmu_type
  5348. elif pinmu_type == '研究和试验发展' and re.search('其他工程服务', industry_type):
  5349. final_type = industry_type
  5350. elif pinmu_type == '办公设备' and re.search('教育设备', industry_type):
  5351. final_type = industry_type
  5352. elif re.search('车辆|机械设备经营租赁', pinmu_type) and re.search('公路旅客运输', industry_type):
  5353. final_type = industry_type
  5354. elif len(industry_lst) > 1 and pinmu_type == industry_lst[1] and re.search('会计|法律|物业|家具|印刷|互联网安全',
  5355. industry_type) == None \
  5356. and re.search('其他|人力资源服务', pinmu_type) == None:
  5357. final_type = pinmu_type
  5358. elif industry_type != "":
  5359. final_type = industry_type
  5360. else:
  5361. final_type = pinmu_type
  5362. return final_type
  5363. def predict(self, title, project, product, prem):
  5364. def get_ree_win(prem):
  5365. tenderee = ""
  5366. win_tenderer = ""
  5367. try:
  5368. for v in prem[0]['prem'].values():
  5369. for link in v['roleList']:
  5370. if link['role_name'] == 'tenderee' and tenderee == "":
  5371. tenderee = link['role_text']
  5372. elif link['role_name'] == 'win_tenderer' and win_tenderer == "":
  5373. win_tenderer = link['role_text']
  5374. except Exception as e:
  5375. print('解析prem 获取招标人、中标人出错')
  5376. return tenderee, win_tenderer
  5377. tenderee, win_tenderer = get_ree_win(prem)
  5378. result_model, prob = self.predict_model(title, project, product, tenderee)
  5379. industry_lst, score_lst, word_lst = self.predict_rule(title, tenderee, win_tenderer, project, product)
  5380. final_type = self.predict_merge(result_model, industry_lst)
  5381. # print('模型:%s;规则:%s;最终:%s'%(result_model, industry_lst[0], final_type))
  5382. # return {'industry': final_type}
  5383. return {'industry': {
  5384. 'class_name': final_type,
  5385. 'subclass': self.industry_dic[final_type]['大类'],
  5386. 'class': self.industry_dic[final_type]['门类']
  5387. }
  5388. }
  5389. class DistrictPredictor():
  5390. def __init__(self):
  5391. # with open(os.path.dirname(__file__)+'/district_dic.pkl', 'rb') as f:
  5392. # dist_dic = pickle.load(f)
  5393. # short_name = '|'.join(sorted(set([v['简称'] for v in dist_dic.values()]), key=lambda x: len(x), reverse=True))
  5394. # full_name = '|'.join(sorted(set([v['全称'] for v in dist_dic.values()]), key=lambda x: len(x), reverse=True))
  5395. # short2id = {}
  5396. # full2id = {}
  5397. # for k, v in dist_dic.items():
  5398. # if v['简称'] not in short2id:
  5399. # short2id[v['简称']] = [k]
  5400. # else:
  5401. # short2id[v['简称']].append(k)
  5402. # if v['全称'] not in full2id:
  5403. # full2id[v['全称']] = [k]
  5404. # else:
  5405. # full2id[v['全称']].append(k)
  5406. # self.dist_dic = dist_dic
  5407. # self.short_name = short_name
  5408. # self.full_name = full_name
  5409. # self.short2id = short2id
  5410. # self.full2id = full2id
  5411. # # self.f = open(os.path.dirname(__file__)+'/../test/data/district_predict.txt', 'w', encoding='utf-8')
  5412. with open(os.path.dirname(__file__)+'/district_tuple.pkl', 'rb') as f:
  5413. district_tuple = pickle.load(f)
  5414. self.p_pro, self.p_city, self.p_dis, self.idx_dic, self.full_dic, self.short_dic = district_tuple
  5415. with open(os.path.dirname(__file__) + "/area_variance_dic.pkl", 'rb') as f: # 20241113 地区变更新旧名称对照字典
  5416. self.area_variance_dic = pickle.load(f)
  5417. def predict_area(self, title, ree, addr, web_source_name):
  5418. p_pro, p_city, p_dis, idx_dic, full_dic, short_dic = self.p_pro, self.p_city, self.p_dis, self.idx_dic, self.full_dic, self.short_dic
  5419. def find_whole_areas(text, weight=1):
  5420. '''
  5421. 通过正则匹配字符串返回地址
  5422. :param pettern: 地址正则 广东省|广西省|...
  5423. :param text: 待匹配文本
  5424. :return:
  5425. '''
  5426. province_l, city_l, district_l = [], [], []
  5427. text = str(text)
  5428. text = re.sub('复合肥|海南岛|兴业银行|双河口|阳光|杭州湾|新城区|中粮屯河|老城(区|改造|更新|升级|翻新)|沙县小吃|北京时间|福田汽车|中山(大学|公园|纪念堂)|孙中山|海天水泥|阳光采购|示范县',
  5429. ' ', text) # 544151395 赤壁市老城区燃气管道老化更新改造
  5430. text = re.sub('珠海城市', '珠海', text) # 修复 426624023 珠海城市 预测为海城市
  5431. text = re.sub('怒江州', '怒江傈僳族自治州', text) # 修复 423589589 所属地域:怒江州 识别为广西 - 崇左 - 江州
  5432. text = re.sub('茂名滨海新区', '茂名市', text)
  5433. text = re.sub('中山([东南西][部区环]|黄圃|南头|东凤|小榄|石岐|翠亨|南朗)', '中山市', text)
  5434. text = re.sub('横州市', '横县', text) # 例:547363890 修复广西南宁横州 不在地区表问题
  5435. ser = re.search('海南(昌江|白沙|乐东|陵水|保亭|琼中)(黎族)?', text)
  5436. if ser and '黎族' not in ser.group(0):
  5437. text = text.replace(ser.group(0), ser.group(0) + '黎族')
  5438. for k, v in self.area_variance_dic.items(): # 20241113 根据地区变更信息替换文本
  5439. text = text.replace(k, v)
  5440. if re.search('[\u4e00-\u9fa5]', text) == None:
  5441. return province_l, city_l, district_l
  5442. pettern = "((?P<prov>%s)(?P<city>%s)?(?P<dist>%s)?)|((?P<city1>%s)(?P<dist1>%s)?)|(?P<dist2>%s)" % (
  5443. p_pro, p_city, p_dis, p_city, p_dis, p_dis)
  5444. for it in re.finditer(pettern, text):
  5445. if it.group(0) == '站前': # 20240314 修复类似 中铁二局新建沪苏湖铁路工程站前VI标项目 错识别为 省份:辽宁, 城市:营口,区县:站前
  5446. continue
  5447. for k, v in it.groupdict().items():
  5448. if v != None:
  5449. if it.end() == it.end(k) and re.search('[省市区县州旗盟]$', v) == None and re.search(
  5450. '^([东南西北中一二三四五六七八九十大小]?(村|镇|街|路|道|社区)|酒店|宾馆|经济开发区|开发区|新区)',
  5451. # 城市不匹配为区的地址 修复 滨州北海经济开发区 北海新区 等提取为北海
  5452. text[it.end(k):]) != None:
  5453. continue
  5454. if k in ['prov']:
  5455. if v in full_dic['province']:
  5456. score = 2
  5457. else:
  5458. score = 1
  5459. if it.start(k)==0 or re.search('^(\w{,2}[分支](公司|局|行|校|院|干?线)|校区|\w{,3}段|地铁|(火车|高铁)?站)'
  5460. , text[it.end(k):]) or (it.start(k)>0 and it.end(k)<len(text) and text[it.start(k)-1]=='(' and text[it.end(k)]==')'):
  5461. score += 1
  5462. score += it.end(k) / len(text) / 10
  5463. province_l.append((v, score * weight))
  5464. elif k in ['city', 'city1']:
  5465. if v in full_dic['city']:
  5466. score = 2
  5467. else:
  5468. score = 1
  5469. if it.start(k)==0 or re.search('^(\w{,2}[分支](公司|局|行|校|院|干?线)|校区|\w{,3}段|地铁|(火车|高铁)?站)'
  5470. , text[it.end(k):]) or (it.start(k)>0 and it.end(k)<len(text) and text[it.start(k)-1]=='(' and text[it.end(k)]==')'):
  5471. score += 1
  5472. score += it.end(k) / len(text) / 10
  5473. city_l.append((v, score * weight))
  5474. elif k in ['dist', 'dist1', 'dist2']:
  5475. if v in ['东区', '西区', '城区', '郊区', '矿区']:
  5476. continue
  5477. if v in full_dic['district'] and len(v)>2:
  5478. score = 2
  5479. else:
  5480. score = 0.5
  5481. if it.start(k)==0 or re.search('^(\w{,2}[分支](公司|局|行|校|院|干?线)|校区|\w{,3}段|地铁|(火车|高铁)?站)'
  5482. , text[it.end(k):]) or (it.start(k)>0 and it.end(k)<len(text) and text[it.start(k)-1]=='(' and text[it.end(k)]==')'):
  5483. score += 1
  5484. # print('县区加分:', v, text)
  5485. score += it.end(k) / len(text) / 10
  5486. if v == '昌江' and '景德镇' not in it.group(0):
  5487. district_l.append(('昌江黎族', score * weight))
  5488. else:
  5489. district_l.append((v, score * weight))
  5490. return province_l, city_l, district_l
  5491. def merge_score(province_l, city_l, district_l, filter_short_dist=True):
  5492. '''
  5493. 合并分数,下级地区分数加到上级
  5494. :param province_l: 提取到的省份列表 [(name, score)]
  5495. :param city_l: 提取到的城市列表 [(name, score)]
  5496. :param district_l: 提取到的区县列表 [(name, score)]
  5497. :param filter_short_dist: 是否过滤不在省份下的区县简称权重
  5498. :return:
  5499. '''
  5500. pro_ids = dict()
  5501. city_ids = dict()
  5502. dis_ids = dict()
  5503. for pro in province_l:
  5504. name, score = pro
  5505. idx = full_dic['province'][name] if name in full_dic['province'] else short_dic['province'][name]
  5506. if idx not in pro_ids:
  5507. pro_ids[idx] = 0
  5508. pro_ids[idx] += score
  5509. tmp_pro = {}
  5510. for city in city_l:
  5511. name, score = city
  5512. if name in full_dic['city']:
  5513. for idx in full_dic['city'][name]:
  5514. if idx not in city_ids:
  5515. city_ids[idx] = 0
  5516. city_ids[idx] += score
  5517. pro_idx = idx_dic[idx]['省']
  5518. if pro_idx in tmp_pro:
  5519. tmp_pro[pro_idx] += score
  5520. else:
  5521. tmp_pro[pro_idx] = score
  5522. elif name in short_dic['city']:
  5523. for idx in short_dic['city'][name]:
  5524. if idx not in city_ids:
  5525. city_ids[idx] = 0
  5526. city_ids[idx] += score
  5527. pro_idx = idx_dic[idx]['省']
  5528. if pro_idx in tmp_pro:
  5529. tmp_pro[pro_idx] += score
  5530. else:
  5531. tmp_pro[pro_idx] = score
  5532. if set(tmp_pro) & set(pro_ids) != set():
  5533. for k, v in tmp_pro.items():
  5534. if k in pro_ids:
  5535. pro_ids[k] += v
  5536. else:
  5537. pro_ids.update(tmp_pro)
  5538. tmp_pro = {}
  5539. tmp_city = {}
  5540. for dis in district_l:
  5541. name, score = dis
  5542. if name in full_dic['district']:
  5543. for idx in full_dic['district'][name]:
  5544. if idx not in dis_ids:
  5545. dis_ids[idx] = 0
  5546. dis_ids[idx] += score
  5547. pro_idx = idx_dic[idx]['省']
  5548. if pro_idx in tmp_pro:
  5549. tmp_pro[pro_idx] += score
  5550. else:
  5551. tmp_pro[pro_idx] = score
  5552. city_idx = idx_dic[idx]['市']
  5553. if city_idx in tmp_city:
  5554. tmp_city[city_idx] += score
  5555. else:
  5556. tmp_city[city_idx] = score
  5557. elif name in short_dic['district']:
  5558. for idx in short_dic['district'][name]:
  5559. if idx not in dis_ids:
  5560. dis_ids[idx] = 0
  5561. dis_ids[idx] += score
  5562. pro_idx = idx_dic[idx]['省']
  5563. if filter_short_dist and pro_idx not in pro_ids:
  5564. continue
  5565. if pro_idx in tmp_pro:
  5566. tmp_pro[pro_idx] += score
  5567. else:
  5568. tmp_pro[pro_idx] = score
  5569. city_idx = idx_dic[idx]['市']
  5570. if city_idx in tmp_city:
  5571. tmp_city[city_idx] += score
  5572. else:
  5573. tmp_city[city_idx] = score
  5574. if set(tmp_pro) & set(pro_ids) != set():
  5575. for k, v in tmp_pro.items():
  5576. if k in pro_ids:
  5577. pro_ids[k] += v
  5578. else:
  5579. pro_ids.update(tmp_pro)
  5580. if set(tmp_city) & set(city_ids) != set():
  5581. for k, v in tmp_city.items():
  5582. if k in city_ids:
  5583. city_ids[k] += v
  5584. else:
  5585. city_ids.update(tmp_city)
  5586. return pro_ids, city_ids, dis_ids
  5587. def get_final_addr(pro_ids, city_ids, dis_ids):
  5588. '''
  5589. 先把所有匹配的全称、简称转为id,如果省份不为空,城市不为空且有城市属于省份的取该城市
  5590. :param province_l: 匹配到的所有省份
  5591. :param city_l: 匹配到的所有城市
  5592. :param district_l: 匹配到的所有区县
  5593. :return:
  5594. '''
  5595. big_area = ""
  5596. pred_pro = ""
  5597. pred_city = ""
  5598. pred_dis = ""
  5599. final_pro = ""
  5600. final_city = ""
  5601. prob = 0
  5602. max_score = 0
  5603. if len(pro_ids) >= 1:
  5604. pro_l = sorted([(k, v) for k, v in pro_ids.items()], key=lambda x: x[1], reverse=True)
  5605. scores = [it[1] for it in pro_l]
  5606. prob = max(scores)/sum(scores)
  5607. max_score = max(scores)
  5608. final_pro, score = pro_l[0]
  5609. if score >= 0.01:
  5610. pred_pro = idx_dic[final_pro]['返回名称']
  5611. big_area = idx_dic[final_pro]['大区']
  5612. if pred_pro != "" and len(city_ids) >= 1:
  5613. city_l = sorted([(k, v) for k, v in city_ids.items()], key=lambda x: x[1], reverse=True)
  5614. for it in city_l:
  5615. if idx_dic[it[0]]['省'] == final_pro:
  5616. final_city = it[0]
  5617. pred_city = idx_dic[final_city]['返回名称']
  5618. break
  5619. if final_city != "" and len(set(dis_ids)) >= 1:
  5620. dis_l = sorted([(k, v) for k, v in dis_ids.items()], key=lambda x: x[1], reverse=True)
  5621. for it in dis_l:
  5622. if idx_dic[it[0]]['市'] == final_city:
  5623. pred_dis = idx_dic[it[0]]['返回名称']
  5624. elif pred_pro != "" and pred_city == "" and len(set(dis_ids)) >= 1: # 20241111 省份不为空,市为空,如果区县在省份下,补充对应的市县
  5625. dis_l = sorted([(k, v) for k, v in dis_ids.items()], key=lambda x: x[1], reverse=True)
  5626. for it in dis_l:
  5627. if idx_dic[it[0]]['省'] == final_pro:
  5628. pred_city = idx_dic[idx_dic[it[0]]['市']]['返回名称']
  5629. pred_dis = idx_dic[it[0]]['返回名称']
  5630. if pred_city in ['北京', '天津', '上海', '重庆']:
  5631. pred_city = pred_dis
  5632. pred_dis = ""
  5633. return big_area, pred_pro, pred_city, pred_dis, prob, max_score
  5634. def get_ree_addr(prem):
  5635. tenderee = ""
  5636. tenderee_address = ""
  5637. try:
  5638. for v in prem[0]['prem'].values():
  5639. for link in v['roleList']:
  5640. if link['role_name'] == 'tenderee' and tenderee == "":
  5641. tenderee = link['role_text']
  5642. tenderee_address = link['address']
  5643. except Exception as e:
  5644. print('解析prem 获取招标人、及地址出错')
  5645. return tenderee, tenderee_address
  5646. def get_role_address(text):
  5647. '''正则匹配获取招标人地址
  5648. 3:地址直接在招标人后面 招标人:xxx,地址:xxx
  5649. 4:招标、代理一起,两个地址一起 招标人:xxx, 代理人:xxx, 地址:xxx, 地址:xxx.
  5650. '''
  5651. p3 = '(招标|采购|甲)(人|方|单位)(信息:|(甲方))?(名称)?:[\w()]{4,15},(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5652. p4 = '(招标|采购|甲)(人|方|单位)(信息:|(甲方))?(名称)?:[\w()]{4,15},(招标|采购)?代理(人|机构)(名称)?:[\w()]{4,15},(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5653. p5 = '(采购|招标)(人|单位)(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5654. if re.search(p3, text):
  5655. return re.search(p3, text).group('addr')
  5656. elif re.search(p4, text):
  5657. return re.search(p4, text).group('addr')
  5658. elif re.search(p5, text):
  5659. return re.search(p5, text).group('addr')
  5660. else:
  5661. return ''
  5662. def get_project_addr(text):
  5663. p1 = '(项目|施工|实施|建设|工程|服务|交货|送货|收货|展示|看样|拍卖)(地址|地点|位置|所在地区?)(位于)?:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+([\w()]{,20}[,。])?|\w{2,15}[,。])'
  5664. p2 = '项目位于(?P<addr>\w{2}市\w{2,4}区)'
  5665. if re.search(p1, text):
  5666. return re.search(p1, text).group('addr')
  5667. elif re.search(p2, text):
  5668. return re.search(p2, text).group('addr')
  5669. else:
  5670. return ''
  5671. def get_bid_addr(text):
  5672. p2 = '(磋商|谈判|开标|投标|评标|报名|递交|评审|发售|所属)(地址|地点|所在地区?|地域):(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5673. if re.search(p2, text):
  5674. return re.search(p2, text).group('addr')
  5675. else:
  5676. return ''
  5677. def get_all_addr(list_entitys):
  5678. tenderee_l = []
  5679. addr_l = []
  5680. for ent in list_entitys[0]:
  5681. if ent.entity_type == 'location' and len(ent.entity_text) > 2:
  5682. addr_l.append(ent.entity_text)
  5683. elif ent.entity_type in ['org', 'company']:
  5684. if ent.label in [0, 1]: # 加招标或代理
  5685. tenderee_l.append(ent.entity_text)
  5686. return ' '.join(addr_l), ' '.join(tenderee_l)
  5687. def get_title_addr(text):
  5688. p1 = '(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5689. if re.search(p1, text):
  5690. return re.search(p1, text).group('addr')
  5691. else:
  5692. return ''
  5693. area_dic = {'area': '全国', 'province': '全国', 'city': '未知', 'district': '未知', "is_in_text": False}
  5694. province_l, city_l, district_l = find_whole_areas(title)
  5695. pro_ids, city_ids, dis_ids = merge_score(province_l, city_l, district_l)
  5696. big_area, pred_pro, pred_city, pred_dis, prob, max_score = get_final_addr(pro_ids, city_ids, dis_ids)
  5697. # print('关键词1:', province_l, city_l, district_l)
  5698. # print('分数:', pro_ids, city_ids, dis_ids, prob, max_score)
  5699. if pred_city == "" or prob < 0.7 or max_score<2:
  5700. province_l2, city_l2, district_l2 = find_whole_areas('%s %s' % (ree, addr), weight=0.8)
  5701. province_l.extend(province_l2)
  5702. city_l.extend(city_l2)
  5703. district_l.extend(district_l2)
  5704. pro_ids, city_ids, dis_ids = merge_score(province_l, city_l, district_l)
  5705. big_area, pred_pro, pred_city, pred_dis, prob, max_score = get_final_addr(pro_ids, city_ids, dis_ids)
  5706. # print('关键词2:', province_l, city_l, district_l)
  5707. # print('分数:', pro_ids, city_ids, dis_ids, prob, max_score)
  5708. if pred_city == "" or prob < 0.7 or max_score<2:
  5709. province_l3, city_l3, district_l3 = find_whole_areas(web_source_name, weight=0.6)
  5710. province_l.extend(province_l3)
  5711. city_l.extend(city_l3)
  5712. district_l.extend(district_l3)
  5713. pro_ids, city_ids, dis_ids = merge_score(province_l, city_l, district_l)
  5714. big_area, pred_pro, pred_city, pred_dis, prob, max_score = get_final_addr(pro_ids, city_ids, dis_ids)
  5715. # print('关键词3:', province_l, city_l, district_l)
  5716. # print('分数:', pro_ids, city_ids, dis_ids, prob, max_score)
  5717. in_content = False
  5718. if big_area != "":
  5719. area_dic['area'] = big_area
  5720. if pred_pro != "":
  5721. area_dic['province'] = pred_pro
  5722. if pred_city != "":
  5723. area_dic['city'] = pred_city
  5724. if pred_dis != "":
  5725. area_dic['district'] = pred_dis
  5726. if in_content:
  5727. area_dic['is_in_text'] = True
  5728. return {'district': area_dic}
  5729. def get_area(self, text, web_name, in_content=False):
  5730. p_pro, p_city, p_dis, idx_dic, full_dic, short_dic = self.p_pro, self.p_city, self.p_dis, self.idx_dic, self.full_dic, self.short_dic
  5731. def get_final_addr(pro_ids, city_ids, dis_ids):
  5732. '''
  5733. 先把所有匹配的全称、简称转为id,如果省份不为空,城市不为空且有城市属于省份的取该城市
  5734. :param province_l: 匹配到的所有省份
  5735. :param city_l: 匹配到的所有城市
  5736. :param district_l: 匹配到的所有区县
  5737. :return:
  5738. '''
  5739. big_area = ""
  5740. pred_pro = ""
  5741. pred_city = ""
  5742. pred_dis = ""
  5743. final_pro = ""
  5744. final_city = ""
  5745. pro_prob = 0
  5746. city_prob = 0
  5747. if len(pro_ids) >= 1:
  5748. pro_l = sorted([(k, v) for k, v in pro_ids.items()], key=lambda x: x[1], reverse=True)
  5749. scores = [it[1] for it in pro_l]
  5750. pro_prob = max(scores)/sum(scores)
  5751. final_pro, score = pro_l[0]
  5752. if score >= 0.01:
  5753. pred_pro = idx_dic[final_pro]['返回名称']
  5754. big_area = idx_dic[final_pro]['大区']
  5755. # else:
  5756. # print("得分过低,过滤掉", idx_dic[final_pro]['返回名称'], score)
  5757. if pred_pro != "" and len(city_ids) >= 1:
  5758. city_l = sorted([(k, v) for k, v in city_ids.items()], key=lambda x: x[1], reverse=True)
  5759. scores = [it[1] for it in city_l]
  5760. city_prob = max(scores) / sum(scores)
  5761. for it in city_l:
  5762. if idx_dic[it[0]]['省'] == final_pro:
  5763. final_city = it[0]
  5764. pred_city = idx_dic[final_city]['返回名称']
  5765. break
  5766. if final_city != "" and len(set(dis_ids)) >= 1:
  5767. dis_l = sorted([(k, v) for k, v in dis_ids.items()], key=lambda x: x[1], reverse=True)
  5768. for it in dis_l:
  5769. if idx_dic[it[0]]['市'] == final_city:
  5770. pred_dis = idx_dic[it[0]]['返回名称']
  5771. elif pred_pro != "" and pred_city == "" and len(set(dis_ids)) >= 1: # 20241111 省份不为空,市为空,如果区县在省份下,补充对应的市县
  5772. dis_l = sorted([(k, v) for k, v in dis_ids.items()], key=lambda x: x[1], reverse=True)
  5773. for it in dis_l:
  5774. if idx_dic[it[0]]['省'] == final_pro:
  5775. pred_city = idx_dic[idx_dic[it[0]]['市']]['返回名称']
  5776. pred_dis = idx_dic[it[0]]['返回名称']
  5777. # print('20241111 省份不为空,市为空,如果区县在省份下,补充对应的市县: ', pred_city, pred_dis)
  5778. if pred_city in ['北京', '天津', '上海', '重庆']:
  5779. pred_city = pred_dis
  5780. pred_dis = ""
  5781. return big_area, pred_pro, pred_city, pred_dis
  5782. def find_areas(pettern, text):
  5783. '''
  5784. 通过正则匹配字符串返回地址
  5785. :param pettern: 地址正则 广东省|广西省|...
  5786. :param text: 待匹配文本
  5787. :return:
  5788. '''
  5789. addr = []
  5790. for it in re.finditer(pettern, text):
  5791. if re.search('[省市区县旗盟]$', it.group(0)) == None and re.search(
  5792. '^([东南西北中一二三四五六七八九十大小]?(村|镇|街|路|道|社区)|酒店|宾馆)', text[it.end():]):
  5793. continue
  5794. if it.group(0) == '站前': # 20240314 修复类似 中铁二局新建沪苏湖铁路工程站前VI标项目 错识别为 省份:辽宁, 城市:营口,区县:站前
  5795. continue
  5796. if re.search('^(经济开发区|开发区|新区)', text[it.end():]) and re.search('广州市', pettern): # 城市不匹配为区的地址 修复 滨州北海经济开发区 北海新区 等提取为北海
  5797. continue
  5798. addr.append((it.group(0), it.start(), it.end()))
  5799. if re.search('^([分支](公司|局|行|校|院|干?线)|\w{,3}段|地铁|(火车|高铁)?站|\w{,3}项目)', text[it.end():]):
  5800. addr.append((it.group(0), it.start(), it.end()))
  5801. return addr
  5802. def chage_area2score(group_list, max_len):
  5803. '''
  5804. 把匹配的的地址转为分数
  5805. :param group_list: [('name', b, e)]
  5806. :return:
  5807. '''
  5808. area_list = []
  5809. if group_list != []:
  5810. for it in group_list:
  5811. name, b, e = it
  5812. area_list.append((name, (e - b + e) / max_len / 2))
  5813. return area_list
  5814. def find_whole_areas(text):
  5815. '''
  5816. 通过正则匹配字符串返回地址
  5817. :param pettern: 地址正则 广东省|广西省|...
  5818. :param text: 待匹配文本
  5819. :return:
  5820. '''
  5821. pettern = "((?P<prov>%s)(?P<city>%s)?(?P<dist>%s)?)|((?P<city1>%s)(?P<dist1>%s)?)|(?P<dist2>%s)" % (
  5822. p_pro, p_city, p_dis, p_city, p_dis, p_dis)
  5823. province_l, city_l, district_l = [], [], []
  5824. for it in re.finditer(pettern, text):
  5825. if re.search('[省市区县旗盟]', it.group(0)) == None and re.search(
  5826. '^([东南西北中一二三四五六七八九十大小]?(村|镇|街|路|道|社区)|酒店|宾馆)', text[it.end():]):
  5827. continue
  5828. if it.group(0) == '站前': # 20240314 修复类似 中铁二局新建沪苏湖铁路工程站前VI标项目 错识别为 省份:辽宁, 城市:营口,区县:站前
  5829. continue
  5830. for k, v in it.groupdict().items():
  5831. if v != None:
  5832. if k in ['prov']:
  5833. province_l.append((it.group(k), it.start(k), it.end(k)))
  5834. elif k in ['city', 'city1']:
  5835. if re.search('^(经济开发区|开发区|新区)', text[it.end(k):]): # 城市不匹配为区的地址 修复 滨州北海经济开发区 北海新区 等提取为北海
  5836. continue
  5837. city_l.append((it.group(k), it.start(k), it.end(k)))
  5838. if re.search('^([分支](公司|局|行|校|院|干?线)|\w{,3}段|地铁|(火车|高铁)?站|\w{,3}项目)', text[it.end(k):]):
  5839. city_l.append((it.group(k), it.start(k), it.end(k)))
  5840. elif k in ['dist', 'dist1', 'dist2']:
  5841. if it.group(k)=='昌江' and '景德镇' not in it.group(0):
  5842. district_l.append(('昌江黎族', it.start(k), it.end(k)))
  5843. else:
  5844. district_l.append((it.group(k), it.start(k), it.end(k)))
  5845. return province_l, city_l, district_l
  5846. def get_pro_city_dis_score(text, text_weight=1):
  5847. text = re.sub('复合肥|海南岛|兴业银行|双河口|阳光|杭州湾|新城区|中粮屯河|老城(区|改造|更新|升级|翻新)|沙县小吃|北京时间', ' ', text) # 544151395 赤壁市老城区燃气管道老化更新改造
  5848. text = re.sub('珠海城市', '珠海', text) # 修复 426624023 珠海城市 预测为海城市
  5849. text = re.sub('怒江州', '怒江傈僳族自治州', text) # 修复 423589589 所属地域:怒江州 识别为广西 - 崇左 - 江州
  5850. text = re.sub('茂名滨海新区', '茂名市', text)
  5851. text = re.sub('中山([东南西][部区环]|黄圃|南头|东凤|小榄|石岐|翠亨|南朗)', '中山市', text)
  5852. text = re.sub('横州市', '横县', text) # 例:547363890 修复广西南宁横州 不在地区表问题
  5853. ser = re.search('海南(昌江|白沙|乐东|陵水|保亭|琼中)(黎族)?', text)
  5854. if ser and '黎族' not in ser.group(0):
  5855. text = text.replace(ser.group(0), ser.group(0)+'黎族')
  5856. for k, v in self.area_variance_dic.items(): # 20241113 根据地区变更信息替换文本
  5857. text = text.replace(k, v)
  5858. # province_l = find_areas(p_pro, text)
  5859. # city_l = find_areas(p_city, text)
  5860. # district_l = find_areas(p_dis, text)
  5861. province_l, city_l, district_l = find_whole_areas(text) # 20240703 优化地址提取,解决类似 海南昌江 得到 海南 南昌 结果
  5862. # if len(province_l) == len(city_l) == 0:
  5863. # district_l = [it for it in district_l if
  5864. # re.search('[市县旗区]$', it[0])] # 20240428去掉只有区县地址且不是全称的匹配,避免错误 例 凌云工业股份有限公司 提取地区为广西白色凌云
  5865. province_l = chage_area2score(province_l, max_len=len(text))
  5866. city_l = chage_area2score(city_l, max_len=len(text))
  5867. district_l = chage_area2score(district_l, max_len=len(text))
  5868. pro_ids = dict()
  5869. city_ids = dict()
  5870. dis_ids = dict()
  5871. for pro in province_l:
  5872. name, score = pro
  5873. assert (name in full_dic['province'] or name in short_dic['province'])
  5874. if name in full_dic['province']:
  5875. idx = full_dic['province'][name]
  5876. if idx not in pro_ids:
  5877. pro_ids[idx] = 0
  5878. pro_ids[idx] += (score + 1)
  5879. else:
  5880. idx = short_dic['province'][name]
  5881. if idx not in pro_ids:
  5882. pro_ids[idx] = 0
  5883. pro_ids[idx] += (score + 0)
  5884. for city in city_l:
  5885. name, score = city
  5886. if name in full_dic['city']:
  5887. w = 0.1 if len(full_dic['city'][name]) > 1 else 1
  5888. for idx in full_dic['city'][name]:
  5889. if idx not in city_ids:
  5890. city_ids[idx] = 0
  5891. # weight = idx_dic[idx]['权重']
  5892. city_ids[idx] += (score + 2) * w
  5893. pro_idx = idx_dic[idx]['省']
  5894. if pro_idx in pro_ids:
  5895. pro_ids[pro_idx] += (score + 2) * w
  5896. else:
  5897. pro_ids[pro_idx] = (score + 2) * w * 0.5
  5898. elif name in short_dic['city']:
  5899. w = 0.1 if len(short_dic['city'][name]) > 1 else 1
  5900. for idx in short_dic['city'][name]:
  5901. if idx not in city_ids:
  5902. city_ids[idx] = 0
  5903. weight = idx_dic[idx]['权重']
  5904. city_ids[idx] += (score + 1) * w * weight
  5905. pro_idx = idx_dic[idx]['省']
  5906. if pro_idx in pro_ids:
  5907. pro_ids[pro_idx] += (score + 1) * w * weight
  5908. else:
  5909. pro_ids[pro_idx] = (score + 1) * w * weight * 0.5
  5910. for dis in district_l:
  5911. name, score = dis
  5912. if name in full_dic['district']:
  5913. w = 0.1 if len(full_dic['district'][name]) > 1 else 1
  5914. for idx in full_dic['district'][name]:
  5915. if idx not in dis_ids:
  5916. dis_ids[idx] = 0
  5917. # weight = idx_dic[idx]['权重']
  5918. dis_ids[idx] += (score + 1) * w
  5919. pro_idx = idx_dic[idx]['省']
  5920. if pro_idx in pro_ids:
  5921. pro_ids[pro_idx] += (score + 1) * w
  5922. else:
  5923. pro_ids[pro_idx] = (score + 1) * w * 0.5
  5924. city_idx = idx_dic[idx]['市']
  5925. if city_idx in city_ids:
  5926. city_ids[city_idx] += (score + 1) * w
  5927. else:
  5928. city_ids[city_idx] = (score + 1) * w * 0.5
  5929. elif name in short_dic['district']:
  5930. w = 0.1 if len(short_dic['district'][name]) > 1 else 1
  5931. for idx in short_dic['district'][name]:
  5932. if idx not in dis_ids:
  5933. dis_ids[idx] = 0
  5934. weight = idx_dic[idx]['权重']
  5935. dis_ids[idx] += (score + 0) * w
  5936. if idx_dic[idx]['市'] not in city_ids and idx_dic[idx]['省'] not in pro_ids: # 20241111 区县简称不在获取到的省、市范围内的过滤掉
  5937. continue
  5938. pro_idx = idx_dic[idx]['省']
  5939. if pro_idx in pro_ids:
  5940. pro_ids[pro_idx] += (score + 0) * w * weight
  5941. # else: # 20241015 注销 区县简称且不在提取的省市下面,不加分,避免提取错误 例:536550843
  5942. # pro_ids[pro_idx] = (score + 0) * w * weight * 0.5
  5943. city_idx = idx_dic[idx]['市']
  5944. if city_idx in city_ids:
  5945. city_ids[city_idx] += (score + 0) * w * weight
  5946. # else: # 20241015 注销 区县简称且不在提取的省市下面,不加分,避免提取错误 例:536550843
  5947. # city_ids[city_idx] = (score + 0) * w * weight * 0.1
  5948. elif pro_idx in pro_ids:
  5949. city_ids[city_idx] = (score + 0) * w * weight * 0.1
  5950. for k, v in pro_ids.items():
  5951. pro_ids[k] = v * text_weight
  5952. for k, v in city_ids.items():
  5953. city_ids[k] = v * text_weight
  5954. for k, v in dis_ids.items():
  5955. dis_ids[k] = v * text_weight
  5956. return pro_ids, city_ids, dis_ids
  5957. area_dic = {'area': '全国', 'province': '全国', 'city': '未知', 'district': '未知', "is_in_text": False}
  5958. pro_ids, city_ids, dis_ids = get_pro_city_dis_score(text)
  5959. pro_ids1, city_ids1, dis_ids1 = get_pro_city_dis_score(web_name, text_weight=0.01) # 20240422 修改为站源名称只取前三字,避免类似 459056219 中金岭南阳光采购平台 错提取阳光
  5960. for k in pro_ids1:
  5961. if k in pro_ids:
  5962. pro_ids[k] += pro_ids1[k]
  5963. else:
  5964. pro_ids[k] = pro_ids1[k]
  5965. for k in city_ids1:
  5966. if k in city_ids:
  5967. city_ids[k] += city_ids1[k]
  5968. else:
  5969. city_ids[k] = city_ids1[k]
  5970. for k in dis_ids1:
  5971. if k in dis_ids:
  5972. dis_ids[k] += dis_ids1[k]
  5973. else:
  5974. dis_ids[k] = dis_ids1[k]
  5975. big_area, pred_pro, pred_city, pred_dis = get_final_addr(pro_ids, city_ids, dis_ids)
  5976. if big_area != "":
  5977. area_dic['area'] = big_area
  5978. if pred_pro != "":
  5979. area_dic['province'] = pred_pro
  5980. if pred_city != "":
  5981. area_dic['city'] = pred_city
  5982. if pred_dis != "":
  5983. area_dic['district'] = pred_dis
  5984. if in_content:
  5985. area_dic['is_in_text'] = True
  5986. return {'district': area_dic}
  5987. def predict(self, project_name, prem, title, list_articles, web_source_name = "", list_entitys=""):
  5988. '''
  5989. 先匹配 project_name+tenderee+tenderee_address, 如果缺少省或市 再匹配 title+content
  5990. :param project_name:
  5991. :param prem:
  5992. :param title:
  5993. :param list_articles:
  5994. :param web_source_name:
  5995. :return:
  5996. '''
  5997. def get_ree_addr(prem):
  5998. tenderee = ""
  5999. tenderee_address = ""
  6000. try:
  6001. for v in prem[0]['prem'].values():
  6002. for link in v['roleList']:
  6003. if link['role_name'] == 'tenderee' and tenderee == "":
  6004. tenderee = link['role_text']
  6005. tenderee_address = link['address']
  6006. except Exception as e:
  6007. print('解析prem 获取招标人、及地址出错')
  6008. return tenderee, tenderee_address
  6009. def get_role_address(text):
  6010. '''正则匹配获取招标人地址
  6011. 3:地址直接在招标人后面 招标人:xxx,地址:xxx
  6012. 4:招标、代理一起,两个地址一起 招标人:xxx, 代理人:xxx, 地址:xxx, 地址:xxx.
  6013. '''
  6014. p3 = '(招标|采购|甲)(人|方|单位)(信息:|(甲方))?(名称)?:[\w()]{4,15},(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  6015. p4 = '(招标|采购|甲)(人|方|单位)(信息:|(甲方))?(名称)?:[\w()]{4,15},(招标|采购)?代理(人|机构)(名称)?:[\w()]{4,15},(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  6016. p5 = '(采购|招标)(人|单位)(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  6017. if re.search(p3, text):
  6018. return re.search(p3, text).group('addr')
  6019. elif re.search(p4, text):
  6020. return re.search(p4, text).group('addr')
  6021. elif re.search(p5, text):
  6022. return re.search(p5, text).group('addr')
  6023. else:
  6024. return ''
  6025. def get_project_addr(text):
  6026. p1 = '(项目|施工|实施|建设|工程|服务|交货|送货|收货|展示|看样|拍卖)(地址|地点|位置|所在地区?)(位于)?:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+([\w()]{,20}[,。])?|\w{2,15}[,。])'
  6027. p2 = '项目位于(?P<addr>\w{2}市\w{2,4}区)'
  6028. if re.search(p1, text):
  6029. return re.search(p1, text).group('addr')
  6030. elif re.search(p2, text):
  6031. return re.search(p2, text).group('addr')
  6032. else:
  6033. return ''
  6034. def get_bid_addr(text):
  6035. p2 = '(磋商|谈判|开标|投标|评标|报名|递交|评审|发售|所属)(地址|地点|所在地区?|地域):(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  6036. if re.search(p2, text):
  6037. return re.search(p2, text).group('addr')
  6038. else:
  6039. return ''
  6040. def get_all_addr(list_entitys):
  6041. tenderee_l = []
  6042. addr_l = []
  6043. for ent in list_entitys[0]:
  6044. if ent.entity_type == 'location' and len(ent.entity_text) > 2:
  6045. addr_l.append(ent.entity_text)
  6046. elif ent.entity_type in ['org', 'company']:
  6047. if ent.label in [0, 1]: # 加招标或代理
  6048. tenderee_l.append(ent.entity_text)
  6049. return ' '.join(addr_l), ' '.join(tenderee_l)
  6050. def get_title_addr(text):
  6051. p1 = '(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  6052. if re.search(p1, text):
  6053. return re.search(p1, text).group('addr')
  6054. else:
  6055. return ''
  6056. if '##attachment##' in list_articles[0].content:
  6057. content, attachment = list_articles[0].content.split('##attachment##')
  6058. if len(content) < 200:
  6059. content += attachment
  6060. else:
  6061. content = list_articles[0].content
  6062. tenderee, tenderee_address = get_ree_addr(prem)
  6063. msc = ""
  6064. pro_addr = get_project_addr(content)
  6065. if pro_addr != "" and re.search('(采购人|招标人)?指定地点', pro_addr)==None: # 排除错误项目地址 例:554024168 1.5服务地点:采购人指定地点。
  6066. msc += '使用规则提取的项目地址;'
  6067. tenderee_address = pro_addr
  6068. else:
  6069. role_addr = get_role_address(content)
  6070. if role_addr != "" and re.search('(采购人|招标人)?指定地点', role_addr)==None:
  6071. msc += '使用规则提取的联系人地址;'
  6072. tenderee_address = role_addr
  6073. if tenderee_address == "":
  6074. title_addr = get_title_addr(title)
  6075. if title_addr != "":
  6076. msc += '使用规则提取的标题地址;'
  6077. tenderee_address = title_addr
  6078. else:
  6079. bid_addr = get_bid_addr(content)
  6080. if bid_addr != "":
  6081. msc += '使用规则提取的开标地址;'
  6082. tenderee_address = bid_addr
  6083. project_name = str(project_name)
  6084. tenderee = str(tenderee)
  6085. # print('招标人地址',role_addr, tenderee_address)
  6086. project_name = project_name + title if project_name not in title else title
  6087. # project_name = project_name.replace(tenderee, '')
  6088. if len(project_name)>3:
  6089. entity_list = getNers([project_name],useselffool=False) # 2024/4/26 修改为去重项目名称中所有公司名称
  6090. for tup in entity_list[0]:
  6091. if tup[2] in ['org', 'company']:
  6092. project_name = project_name.replace(tup[3], '')
  6093. text1 = "{0} {1} {2}".format(tenderee, tenderee_address, project_name)
  6094. web_source_name = str(web_source_name) # 修复某些不是字符串类型造成报错
  6095. text1 = re.sub('复合肥|铁路|公路|新会计', ' ', text1) # 预防提取错 合肥 路南 新会 等地区
  6096. if pro_addr and re.search('\w{2,}([市县旗盟]|自治[区州县旗])', pro_addr):
  6097. if re.search('[市县旗盟]', pro_addr)==None: # 修复 486623506 项目地址不完整
  6098. pro_addr = text1 + ' '+ pro_addr
  6099. msc += '## 使用项目地址输入:%s ##;' % pro_addr
  6100. rs = self.get_area(pro_addr, '')
  6101. msc += '预测结果:省份:%s, 城市:%s,区县:%s;' % (
  6102. rs['district']['province'], rs['district']['city'], rs['district']['district'])
  6103. if rs['district']['province'] != '全国' and rs['district']['city'] != '未知':
  6104. # print('地区匹配:', msc)
  6105. return rs
  6106. # print('text1:', text1)
  6107. msc += '## 第一次预测输入:%s ##;' % text1
  6108. rs = self.get_area(text1, '') # 2024/4/22 调整第一次输入不带站源名称,避免出错
  6109. msc += '预测结果:省份:%s, 城市:%s,区县:%s;' % (
  6110. rs['district']['province'], rs['district']['city'], rs['district']['district'])
  6111. # self.f.write('%s %s \n' % (list_articles[0].id, msc))
  6112. # print('地区匹配:', msc)
  6113. if rs['district']['province'] == '全国' or rs['district']['city'] == '未知':
  6114. # msc = ""
  6115. all_addr, tenderees = get_all_addr(list_entitys)
  6116. text2 = tenderees + " " + all_addr + ' ' + title
  6117. msc += '使用实体列表所有招标人+所有地址;'
  6118. # text2 += title + content if len(content)<2000 else title + content[:1000] + content[-1000:]
  6119. text2 = re.sub('复合肥|铁路|公路|新会计', ' ', text2)
  6120. # print('text2:', text2)
  6121. msc += '## 第二次预测输入:%s %s##' % (text2,web_source_name)
  6122. rs2 = self.get_area(text2, web_source_name, in_content=True)
  6123. # rs2['district']['is_in_text'] = True
  6124. if rs['district']['province'] == '全国' and rs2['district']['province'] != '全国':
  6125. rs = rs2
  6126. elif rs['district']['province'] == rs2['district']['province'] and rs2['district']['city'] != '未知':
  6127. rs = rs2
  6128. msc += '预测结果:省份:%s, 城市:%s,区县:%s' % (
  6129. rs['district']['province'], rs['district']['city'], rs['district']['district'])
  6130. # self.f.write('%s %s \n'%(list_articles[0].id, msc))
  6131. # print('地区匹配:', msc)
  6132. return rs
  6133. class TableTag2List():
  6134. '''把soup table 转化为表格补全后的文本列表[[td, td, td], [td, td, td]]'''
  6135. def table2list(self, table, text_process=None):
  6136. self._output = []
  6137. row_ind = 0
  6138. col_ind = 0
  6139. for row in table.find_all('tr'):
  6140. # record the smallest row_span, so that we know how many rows
  6141. # we should skip
  6142. smallest_row_span = 1
  6143. if len(row.find_all(['td', 'th'], recursive=False)) > 20:
  6144. log('未补全前表格列数大于20的不做表格处理')
  6145. return []
  6146. for cell in row.children:
  6147. if cell.name in ('td', 'th'):
  6148. # check multiple rows
  6149. # pdb.set_trace()
  6150. row_span = int(re.sub('[^0-9]', '', cell.get('rowspan'))) if cell.get('rowspan') and cell.get('rowspan').isdigit() else 1
  6151. # try updating smallest_row_span
  6152. smallest_row_span = min(smallest_row_span, row_span)
  6153. # check multiple columns
  6154. col_span = int(re.sub('[^0-9]', '', cell.get('colspan'))) if cell.get('colspan') and cell.get('colspan').isdigit() else 1
  6155. if col_span > 20: # 修复 335590254 山东港口阳光智采e平台 数据源表格第一行colspan为200超过50列造成无法提取问题
  6156. col_span = 20
  6157. # find the right index
  6158. while True:
  6159. if self._check_cell_validity(row_ind, col_ind):
  6160. break
  6161. col_ind += 1
  6162. # insert into self._output
  6163. try:
  6164. if text_process != None:
  6165. # text = [re.sub('\xa0', '', text_process(cell, final=False)), 0]
  6166. # td_text = re.sub('\xa0', '', text_process(cell, final=False))
  6167. td_text = re.sub('\s|\xa0', '', str(cell.get_text())) # 修复 370835008 td 内公司被p标签拆分为两半情况
  6168. if 'title' in cell.attrs and cell.get_text().strip().endswith('...') and cell.get_text().strip()[:-3] in cell.attrs['title']:
  6169. td_text = cell.attrs['title'] # 修复 类似 215597851 省略号隐藏内容
  6170. elif len(td_text)>30:
  6171. td_text = re.sub('\xa0', '', text_process(cell, final=False))
  6172. if td_text == "":
  6173. td_text = ' '
  6174. text = [td_text,0]
  6175. else:
  6176. text = str(cell.get_text()).strip().replace("\x06", "").replace("\x05", "").replace("\x07", "").replace('\\', '').replace("(", "(").replace(')', ')').replace('?', '')
  6177. # text = re.sub('\s', '', text)[:200] # 只需取前200字即可
  6178. text = ' ' if text == "" else text
  6179. self._insert(row_ind, col_ind, row_span, col_span, text)
  6180. except UnicodeEncodeError:
  6181. raise Exception( 'Failed to decode text; you might want to specify kwargs transformer=unicode' )
  6182. # update col_ind
  6183. col_ind += col_span
  6184. if col_ind > 50 and text_process == None: # 表格要素提取及候选人提取的 表格列数大于50的去掉
  6185. return []
  6186. # update row_ind
  6187. row_ind += smallest_row_span
  6188. col_ind = 0
  6189. return self._output
  6190. def _check_validity(self, i, j, height, width):
  6191. """
  6192. check if a rectangle (i, j, height, width) can be put into self.output
  6193. """
  6194. return all(self._check_cell_validity(ii, jj) for ii in range(i, i+height) for jj in range(j, j+width))
  6195. def _check_cell_validity(self, i, j):
  6196. """
  6197. check if a cell (i, j) can be put into self._output
  6198. """
  6199. if i >= len(self._output):
  6200. return True
  6201. if j >= len(self._output[i]):
  6202. return True
  6203. if self._output[i][j] == "":
  6204. return True
  6205. return False
  6206. def _insert(self, i, j, height, width, val):
  6207. # pdb.set_trace()
  6208. for ii in range(i, i+height):
  6209. for jj in range(j, j+width):
  6210. self._insert_cell(ii, jj, val)
  6211. def _insert_cell(self, i, j, val):
  6212. while i >= len(self._output):
  6213. self._output.append([])
  6214. while j >= len(self._output[i]):
  6215. self._output[i].append("")
  6216. if self._output[i][j] == "":
  6217. self._output[i][j] = val
  6218. def is_head_line(list_item):
  6219. '''
  6220. 调用表头识别模型判断是否为表头行
  6221. :param list_item: 行内容 例: ['技术参数、要求', '变更项']
  6222. :return:
  6223. '''
  6224. x = []
  6225. for item in list_item:
  6226. x.append(getPredictor("form").encode(item))
  6227. predict_y = getPredictor("form").predict(np.array(x), type="item")
  6228. count = 0
  6229. for item, values in zip(list_item, list(predict_y)):
  6230. if values[1] > 0.6:
  6231. count += 1
  6232. if count/len(list_item)>0.6:
  6233. return True
  6234. return False
  6235. class TablePremExtractor(object):
  6236. def __init__(self):
  6237. '''各要素表头规则'''
  6238. self.head_rule_dic = {
  6239. 'project_code': "(项目|招标|采购|计划|公告|包[段组件]|标[段包的]|标段(包)|分[包标])(编号|编码|代码)",
  6240. 'package_code': "(包[段组件]|标[段包]|分[包标])(序?号|$)|包号|^标段$|^品目$",
  6241. "project_name": "(包[段组件]|标[段包的项]|标段(包)|分[包标]|采购|项目|工程|货物|商品|产品|设备|通用|主要标的|^包)(名称?|内容)",
  6242. "win_sort": "排名|排序|名次|推荐顺序",
  6243. 'win_or_not': '是否(建议|推荐)?(中标|成交|中选)|是否入围|是否入库|入围结论|未(中标|成交)原因',
  6244. "tenderer": "(中标|中选|中价|成交|供货|承包|承建|承租|竞得|受让)(候选)?(人|单位|供应商|公司|企业|厂家|商家?|客户|供?方|银行)(名称|$)|^(拟定|单一来源|邀请|拟?推荐(入选|入围)?)?供应商(名称)?$",
  6245. "tenderee": "(项目|采购|招标|遴选|寻源|竞价|议价|比选|委托|询比?价|比价|评选|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选)(人|公司|单位|组织|用户|业主|主体|方|部门)(名称|$)",
  6246. "budget": "最高(投标)?限价|总价限价|控制(价格?|金额|总价)|(总价|采购)限价|上限价|拦标价|(采购|招标|项目)?预算|(预算|招标|采购|计划)金额|挂牌价",
  6247. "bid_amount": "投标[报总]?价|报价(总?金额|总价|总额)|总报价|^\w{,5}报价(([\w、/]{1,15}))?$|(中标|成交|合同))?总?(金?额|[报均总]价|价[格款]?)|承包价|含税价|经评审的价格|中标存款金?额|中标资金|中标存款|存放金额|分配额度",
  6248. "serviceTime": '合同期限|工期/交货期/服务期|工期\(交货期\)|合格工期|服务期限|工期' \
  6249. '|工期要求|项目周期|工期\(交货期\)|计划工期\(服务期限\)|服务时限|履行期限|服务周期|供货期限' \
  6250. '|合格工期|计划工期\(服务期\)|服务期|服务,期|交货\(完工\)时间|交付\(服务、完工\)时间' \
  6251. '|交货时间|保洁期限|维保期|管理年限|工期承诺|(服务|合同|施工|实施|工程|设计)的?(年限|期限|周期|期:)' \
  6252. '|计划工期|工期要求|服务期限?' \
  6253. '|投标工期|设计工期|合格服务周期|总工期|服务时间(范围)?|流转期限|维护期限|服务时限|交货期' \
  6254. '|完成时间|中标工期|项目周期|期限要求|周期|供货期|合同的?履行日期|计划周期' \
  6255. '|履约期限|合同的?约定完成时限|合同的?完成日期|承诺完成日期' \
  6256. '|合同起始日起|合同的?履约期|履约截止日期|承包期限|合同的?完成日期|特许经营期限' \
  6257. '|服务期间|服务履行期|委托(管理)?期限|经营期限|数量' \
  6258. '|(工期|服务期限?|交货期限?|服务履行期|合同期限?|履[行约]期限?)说明|存款期限?|(存款|存放|定存)(期|年)限' \
  6259. '|服务(有效期|年限)|本?合同有效期|协议有效期|项目期限'
  6260. }
  6261. with open(os.path.dirname(__file__)+'/header_set.pkl', 'rb') as f:
  6262. self.headerset = pickle.load(f)
  6263. self.tb = TableTag2List()
  6264. def find_header(self, td_list, all_winner=False, first_line=False):
  6265. fix_td_list = [re.sub('[::]$|^[一二三四五六七八九十0-9]{1,3}、|(([\w、×*/]{1,20}))$|(不?含税)|/万?元|拟|\s', '', it) for it in td_list] # 去除表头无关信息,方便匹配判断是否为表头
  6266. header_dic = dict()
  6267. flag = False
  6268. contain_header = False
  6269. not_sure_winner = False # 是否 不确定中标的中标人表达方式
  6270. for text in set(fix_td_list) - self.headerset:
  6271. if len(text)<10 and re.search(self.head_rule_dic['bid_amount'], text):
  6272. self.headerset.add(text)
  6273. if len(set(fix_td_list))>0 and (first_line or len(set(fix_td_list) & self.headerset)>=2) and (len(set(fix_td_list) & self.headerset)/len(set(fix_td_list))>=0.6 or is_head_line(fix_td_list)):
  6274. other_tenderer = ""
  6275. other_tenderer2 = ""
  6276. flag = True
  6277. for i in range(len(td_list)) :
  6278. text = td_list[i]
  6279. text = re.sub('\s|[((]排名不分先后[))]', '', text)
  6280. text = re.sub('^人选', '入选', text)
  6281. if text == '备选中标人':
  6282. text = '第二候选人'
  6283. if len(re.sub('(([\w、×*/]{1,20}))$', '', text)) > 15: # 长度大于15 不进行表头匹配
  6284. continue
  6285. if re.search('未(中标|成交|中选|入围)原因', text): # 不提取此种表格
  6286. return flag, contain_header, dict(), not_sure_winner
  6287. num = 0
  6288. for k, v in self.head_rule_dic.items():
  6289. if re.search('评分|得分|分数|分值', text):
  6290. continue
  6291. if re.search(v, text):
  6292. if k in ['tenderer'] and re.search('是否', text):
  6293. continue
  6294. if k == 'budget' and re.search('量', text): # 预算工作量 预算采购量 等不作为预算
  6295. continue
  6296. elif k == 'bid_amount' and re.search('分配方案|基准利率|BP值', text): # 517987084 中标资金分配方案
  6297. continue
  6298. elif k in header_dic:
  6299. if k in ['budget', 'bid_amount'] and re.search('总(价|金?额)', text): # 总价替换单价
  6300. header_dic[k] = (i, text)
  6301. num += 1
  6302. elif k == 'project_code' and text != header_dic[k][1] and 'package_code' not in header_dic\
  6303. and re.search(self.head_rule_dic['package_code'], re.sub('\s', '', ','.join(td_list)))==None: # 如果出现两次项目编号且没有包号,把第二次出现的作为包号 例:472537470
  6304. header_dic['package_code'] = (i, text)
  6305. continue
  6306. header_dic[k] = (i, text)
  6307. num += 1
  6308. elif re.search('^((中标|成交|中选|入围|入选)(候选)?)(人|单位|机构|中介(服务)?机构|供应商|客户|方|公司|厂商|商家?|社会资本方?|银行)(名称)?$', text) and re.search('未', text)==None:
  6309. other_tenderer = (i, text)
  6310. elif re.search('^((投标|应答|响应|候选)(人|单位|机构|中介(服务)?机构|供应商|客户|方|公司|厂商|商家?|社会资本方?|银行)|(存款|投标)?银行|供应商)(名称)?$|^机构名称$|^单位(名称)?$', text) and re.search('未', text)==None:
  6311. other_tenderer2 = (i, text)
  6312. if num>1:
  6313. if re.search(self.head_rule_dic['project_code'], text) and re.search(self.head_rule_dic['package_code'], text): # 修复 528486798 分标编号-包号
  6314. continue
  6315. # print('表头错误,一个td匹配到两个表头:', header_dic)
  6316. return flag, contain_header, dict(), not_sure_winner
  6317. if text == '单位': # 20241128 补充金额单位
  6318. header_dic['amount_unit'] = (i, text)
  6319. if re.search(';金额((万?元))?;', ';'.join(td_list)): # 召回某些表格只写 金额 作为表头,不能识别为招标或中标金额
  6320. if 'tenderer' in header_dic and 'bid_amount' not in header_dic:
  6321. for i in range(len(td_list)):
  6322. text = td_list[i]
  6323. if re.search('^金额((万?元))?$',text):
  6324. header_dic['bid_amount'] = (i, text)
  6325. break
  6326. elif 'tenderee' in header_dic and 'budget' not in header_dic:
  6327. for i in range(len(td_list)):
  6328. text = td_list[i]
  6329. if re.search('^金额((万?元))?$', text):
  6330. header_dic['budget'] = (i, text)
  6331. break
  6332. if all_winner and 'tenderer' not in header_dic: # 标题有存款、入库、入围等公告补充其他表达做中标人
  6333. if other_tenderer!="":
  6334. header_dic['tenderer'] = other_tenderer
  6335. elif other_tenderer2!="":
  6336. header_dic['tenderer'] = other_tenderer2
  6337. if 'win_sort' not in header_dic:
  6338. not_sure_winner = True
  6339. if all_winner == 1 and 'win_sort' in header_dic: # 标题有存管类公告不分排名
  6340. header_dic.pop('win_sort')
  6341. if ('project_code' in header_dic or 'package_code' in header_dic or 'project_name' in header_dic) and (
  6342. 'tenderer' in header_dic or'budget' in header_dic): # 包含标段及招标金额或中标人的进行提取
  6343. return flag, contain_header, header_dic, not_sure_winner
  6344. elif ('tenderer' in header_dic) and ('bid_amount' in header_dic): # 包含中标人及中标金额的进行提取
  6345. if 'win_sort' in header_dic: # 有排名的 用候选人提取类
  6346. return flag, contain_header, dict(), not_sure_winner
  6347. elif re.search('^(候选)?供应商(名称)?', header_dic['tenderer'][1]) and 'win_or_not' not in header_dic and re.search('(中标|成交|合同))?总?(金?额|[报均总]价|价[格款]?)', header_dic['bid_amount'][1])==None: # 只有供应商名称 没排名和包号的去掉,预防错误包提取 334205629
  6348. # print('只有供应商名称 没排名和包号的去掉')
  6349. return flag, contain_header, dict(), not_sure_winner
  6350. return flag,contain_header, header_dic, not_sure_winner
  6351. elif 'tenderer' in header_dic and (re.search('(中标|中选|中价|成交|竞得)(人|单位|供应商|公司|企业|厂家|商家?|客户|供?方|银行)',header_dic['tenderer'][1]) or all_winner): # 有中标人,且有明确中标关键词的进行提取
  6352. return flag, contain_header, header_dic, not_sure_winner
  6353. # elif 'tenderer' in header_dic and 'serviceTime' in header_dic:
  6354. # return flag, contain_header, header_dic, not_sure_winner
  6355. elif len(set(fix_td_list) & self.headerset) >= 2 or (len(set(fix_td_list)) == 2 and len(set(td_list) & self.headerset) >= 1): # 如果包含两个表头以上或 只有两列且包含一个表头
  6356. contain_header = True
  6357. return flag, contain_header, dict(), not_sure_winner
  6358. def get_role(self, text, nlp_enterprise):
  6359. '''
  6360. 获取字符串text角色实体
  6361. :param text: 待获取实体字符串
  6362. :param nlp_enterprise: 公告中的角色实体列表
  6363. :return:
  6364. '''
  6365. text = re.sub('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:|[((][主成][))]'
  6366. , ',', text)
  6367. text = re.sub('\s', '', text) # 修复 370835008 表格中实体中间有\n
  6368. text = re.sub('[一二三四五六七八九十]+标段[::]|标段[一二三四五六七八九十]+[::]|第[一二三四五六七八九十]+名[::]', '', text) # 2024/4/22 修复 372839375 三标段:宁夏一山科技有限公司
  6369. text = re.sub('1[3-9]\d{9}|\d{3}-\d{8}|\d{4}-\d{7}', '', text) # 2024/4/23 去除电话
  6370. if text in nlp_enterprise:
  6371. return text
  6372. if len(text) > 50 or len(text)<4:
  6373. return ''
  6374. ners = getNers([text], useselffool=True)
  6375. roles = []
  6376. if ners:
  6377. for ner in ners[0]:
  6378. if ner[2] in ['org', 'company']:
  6379. roles.append(ner[3])
  6380. elif ner[2] in ['location'] and re.search('^\w{3,10}(海关|殡仪馆|店|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场)$', ner[3]):
  6381. roles.append(ner[3])
  6382. if roles and len(''.join(roles)) > len(text)*0.8:
  6383. return roles[0]
  6384. else:
  6385. return ''
  6386. def extract_from_df(self, df, headers, web_source_name, all_winner=False):
  6387. prem_dic = {}
  6388. previous_package = "" # 上一行包号
  6389. multi_same_package = False # 非连续的重复包号
  6390. package_fix2raw = dict() # 处理后包号:处理前包号 字典
  6391. link_set = set()
  6392. tenderer_list = [] # 保存所有中标人
  6393. serviceTime_list = []
  6394. not_package = True if 'project_name' in headers and re.search('(货物|商品|产品|通用|主要标的)(名称?|内容)', headers['project_name'][1]) and \
  6395. 'package_code' not in headers and 'budget' not in headers and "bid_amount" not in headers else False
  6396. if set(['project_code', 'package_code', 'tenderee', 'tenderer']) & set(headers) == set() and ('project_name' not in headers # 补充没有项目名称或有项目名称且是货物的才过滤掉
  6397. or re.search('(货物|商品|产品|设备|通用|主要标的)(名称?|内容)', headers['project_name'][1])): # 20240131修复只有货物名称及最高限价的错误作为多包 396636683; 补充避免423647863采购意向被过滤
  6398. # print('没有包号及角色的不要')
  6399. return {}
  6400. have_bid_amount = False # 是否包含中标金额
  6401. if "bid_amount" in headers and re.search('[1-9]+', '#'.join([it.strip() for it in df[headers['bid_amount'][0]]])):
  6402. have_bid_amount = True
  6403. for i in df.index:
  6404. same_package = False # 连续重复包号,一般是 rowspan 造成;一包 多个采购
  6405. project_code = df.loc[i, headers['project_code'][0]].strip() if "project_code" in headers else ""
  6406. package_code_raw = df.loc[i, headers['package_code'][0]].strip() if "package_code" in headers else ""
  6407. project_name = df.loc[i, headers['project_name'][0]].strip() if "project_name" in headers else ""
  6408. tenderee = df.loc[i, headers['tenderee'][0]].strip() if "tenderee" in headers else ""
  6409. tenderer = df.loc[i, headers['tenderer'][0]].strip() if "tenderer" in headers else ""
  6410. budget_ = df.loc[i, headers['budget'][0]].strip() if "budget" in headers else ""
  6411. bid_amount_ = df.loc[i, headers['bid_amount'][0]].strip() if "bid_amount" in headers else ""
  6412. win_sort = df.loc[i, headers['win_sort'][0]].strip() if "win_sort" in headers else ""
  6413. win_or_not = df.loc[i, headers['win_or_not'][0]].strip() if "win_or_not" in headers else ""
  6414. serviceTime = df.loc[i, headers['serviceTime'][0]].strip() if "serviceTime" in headers else ""
  6415. amount_unit = df.loc[i, headers['amount_unit'][0]].strip() if "amount_unit" in headers else ""
  6416. if set([project_code, package_code_raw, project_name,tenderee,tenderer,budget_,bid_amount_]) & self.headerset != set(): # 只要有一项为表头 停止匹配
  6417. # print('只要有一项为表头 停止匹配', set([project_code, package_code_raw, project_name,tenderee,tenderer,budget_,bid_amount_,win_sort]) & self.headerset)
  6418. break
  6419. if len(set([project_code, package_code_raw, project_name,tenderee,tenderer,budget_,bid_amount_,win_sort])- set(['', ' '])) < 2 and tenderer=='': # 内容为空或全部一样 停止匹配
  6420. # print('内容为空或全部一样 停止匹配')
  6421. break
  6422. if re.search('详见', project_name): # 去除某些表达: 详见招标文件
  6423. project_name = ""
  6424. if package_code_raw == "" and re.search('第?[0-9一二三四五六七八九十a-zA-Z]{1,4}(标[段号的包项]|([分子]?包|包[组件号]))$|^(标[段号的包项]|([分子]?包|包[组件号]))号?:?[0-9一二三四五六七八九十a-zA-Z]{1,4}$', project_name):
  6425. package_code_raw = project_name
  6426. project_name = ""
  6427. package_code = package_code_raw
  6428. if re.search('合计|总计', package_code+project_code+project_name):
  6429. continue
  6430. if package_code + project_code == previous_package: # 处理 208162730 一个包采购多种东西情况
  6431. same_package = True
  6432. if previous_package!="": # 有包号或项目编号且跟上一行相同时,去除项目名称
  6433. project_name = ''
  6434. previous_package = package_code + project_code
  6435. if win_sort != "" and re.search('排名|排序|名次|推荐顺序', headers['win_sort'][1]): # 此类型表由 CandidateExtractor类提取 防止类似 328485591 作为多包
  6436. break
  6437. if win_or_not != "" and (re.search('(建议|推荐)(中标|成交|中选)|是|^(中标|成交|中选)', win_or_not)==None or re.search('\w', win_or_not)==None): # 2024/04/2 修复 252208201 为空的不中标
  6438. continue
  6439. if "win_sort" in headers and win_sort == "": # '表头有是否中标,内容却空白的,过滤掉'
  6440. continue
  6441. if win_sort == "" and "tenderer" in headers and re.search('候选|入围|入选', headers['tenderer'][1]) and re.search('推荐的?((中标|成交|中选)候选人|(候选|入围|入选)供应商)', headers['tenderer'][1])==None and all_winner == False:
  6442. tenderer = ""
  6443. if tenderer in ['采购失败', '废标']: # 避免类似 353867205 这篇只提取到一个
  6444. continue
  6445. # tenderee = tenderee if self.is_role(tenderee) else ""
  6446. # tenderer = tenderer if self.is_role(tenderer) else ""
  6447. package = uniform_package_name(package_code) if package_code else '自增1' # 没有包号的自动编号的修改为提取到多少个包,某些行未必中标
  6448. if project_name != "" and package.startswith('自增'):
  6449. pk_l = find_package(project_name)
  6450. if len(pk_l)==1:
  6451. package = uniform_package_name(pk_l[0].group(0))
  6452. elif re.search('[一二三四五六七八九十]+标段:|标段[一二三四五六七八九十]+:', tenderer) and package.startswith('自增'):
  6453. pk_l = find_package(tenderer)
  6454. if len(pk_l) == 1:
  6455. package = uniform_package_name(pk_l[0].group(0))
  6456. tenderee = self.get_role(tenderee, self.nlp_enterprise) if tenderee!="" else tenderee
  6457. tenderer = self.get_role(tenderer, self.nlp_enterprise) if tenderer!='' else tenderer
  6458. tenderee = cut_repeat_name(tenderee)
  6459. tenderer = cut_repeat_name(tenderer)
  6460. if len(set([project_code, package_code, project_name, tenderee, tenderer, budget_, bid_amount_])) < 2:
  6461. break
  6462. if not_package:
  6463. if (project_code, package_code, tenderee, tenderer, budget_, bid_amount_) in link_set:
  6464. continue
  6465. link_set.add((project_code, package_code, tenderee, tenderer, budget_, bid_amount_))
  6466. else:
  6467. if (project_code, package_code, project_name, tenderee, tenderer, budget_, bid_amount_) in link_set:
  6468. continue
  6469. link_set.add((project_code, package_code, project_name, tenderee, tenderer, budget_, bid_amount_))
  6470. if project_code != "":
  6471. uni_project_code= uniform_package_name(project_code)
  6472. if uni_project_code != "" and uni_project_code!=package:
  6473. if package.startswith('自增'): # 没有包号有项目编号的,直接用项目编号
  6474. package = uni_project_code
  6475. else:
  6476. # print('重组包号:', '%s_%s'%(uni_project_code, package))
  6477. package = '%s_%s'%(uni_project_code, package) # 同时包号项目编号及包号的,组合起来做包号
  6478. if package_code_raw!='':
  6479. if multi_same_package == False and package not in package_fix2raw: # 如果处理后的标段号 已经在列表里面,采用原始标段号文本
  6480. package_fix2raw[package] = package_code_raw
  6481. elif same_package == False:
  6482. multi_same_package = True
  6483. if multi_same_package:
  6484. package = package_code_raw
  6485. if package not in prem_dic or not same_package:
  6486. prem_dic[package] = {
  6487. 'code': '',
  6488. 'name': '',
  6489. 'roleList': [],
  6490. 'tendereeMoney': 0,
  6491. 'tendereeMoneyUnit': ""
  6492. }
  6493. prem_dic[package]['code'] = project_code
  6494. prem_dic[package]['name'] = project_name
  6495. if budget_ != "":
  6496. if len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\s\d,.]|人民币|不?含税|(六个月|一年|\w{2,3})期加点\d+BP', '', budget_)) > 5: # 金额字段出现超过5个非金额字符,中断匹配
  6497. prem_dic.pop(package)
  6498. break
  6499. budget_header = headers['budget'][1] if 'budget' in headers else ''
  6500. if amount_unit!='' and re.search('^[万亿]?元|%|折[\w/]{,6}$', amount_unit) and re.search('元', budget_+budget_header)==None : # 20241128 补充某些表格价格单位分开两列, 例:557953660
  6501. budget_ += amount_unit
  6502. budget, money_unit = money_process(budget_, budget_header) if re.search('[%%‰折]|浮率|期加点\d+BP', budget_)==None else (0, '')
  6503. if re.search('元[/每]', amount_unit) or re.search('单价', budget_header):
  6504. unit_tendereeMoney = budget
  6505. budget = 0
  6506. else:
  6507. unit_tendereeMoney = 0
  6508. if (re.search('费率|下浮率|[%%‰折]|优惠率',
  6509. budget_header + budget_) and budget < 100) or budget > 50000000000: # 如果是费率或大于500亿的金额改为0
  6510. budget = 0
  6511. if budget > 0:
  6512. if same_package and prem_dic[package]['tendereeMoney'] != budget: # 处理 类似 136839070 一包多物品多预算
  6513. prem_dic[package]['tendereeMoney'] += budget
  6514. else:
  6515. prem_dic[package]['tendereeMoney'] = budget
  6516. prem_dic[package]['tendereeMoneyUnit'] = money_unit
  6517. if unit_tendereeMoney > 0:
  6518. if 'unit_tendereeMoney' not in prem_dic[package]:
  6519. prem_dic[package]['unit_tendereeMoney'] = 0
  6520. if same_package and prem_dic[package]['unit_tendereeMoney'] != unit_tendereeMoney: # 处理 类似 136839070 一包多物品多预算
  6521. prem_dic[package]['unit_tendereeMoney'] += unit_tendereeMoney
  6522. else:
  6523. prem_dic[package]['unit_tendereeMoney'] = unit_tendereeMoney
  6524. if tenderee and not same_package:
  6525. prem_dic[package]['roleList'].append({
  6526. "address": "",
  6527. "linklist": [],
  6528. "role_money": {
  6529. "discount_ratio": "",
  6530. "downward_floating_ratio": "",
  6531. "floating_ratio": "",
  6532. "money": 0,
  6533. "money_unit": ""
  6534. },
  6535. "role_name": "tenderee",
  6536. "role_text": tenderee,
  6537. "serviceTime": ""
  6538. })
  6539. if tenderer:
  6540. if len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\s\d,.]|人民币|不?含税|(六个月|一年|\w{2,3})期加点\d+BP', '',
  6541. bid_amount_)) > 5: # 金额字段出现超过5个非金额字符,中断匹配
  6542. prem_dic.pop(package)
  6543. break
  6544. bid_amount_header = headers['bid_amount'][1] if bid_amount_ != "" else ''
  6545. if amount_unit != '' and re.search('^[万亿]?元|%|折[\w/]{,6}$', amount_unit) and bid_amount_!='' and re.search('元',
  6546. bid_amount_ + bid_amount_header) == None:
  6547. bid_amount_ += amount_unit
  6548. bid_amount, money_unit = money_process(bid_amount_, headers['bid_amount'][1]) if bid_amount_ != "" and re.search('[%%‰折]|浮率|期加点\d+BP', bid_amount_)==None and 'bid_amount' in headers else (0, '')
  6549. if re.search('元[/每]', amount_unit) or re.search('单价', bid_amount_header):
  6550. unit_price = bid_amount
  6551. bid_amount = 0
  6552. else:
  6553. unit_price = 0
  6554. if web_source_name == '河钢供应链管理平台' and 'bid_amount' in headers and re.search('[%%‰折]|浮率', bid_amount_) == None and bid_amount == 0: # 有中标金额字段却金额为0的过滤掉,防止类似 河钢供应链管理平台 站源错误,金额不为0的才算中标
  6555. if len(prem_dic[package]['roleList']) == 0 and prem_dic[package]['tendereeMoney'] == 0: # 只有项目编号和名称的包 丢弃
  6556. prem_dic.pop(package)
  6557. continue
  6558. elif 'bid_amount' in headers and re.search('[%%‰折]|浮率', bid_amount_) == None and have_bid_amount and bid_amount_ in ['/','','0','0.0']: # 如果不是所有行中标金额都为0,则把为0的做非中标
  6559. if len(prem_dic[package]['roleList']) == 0 and prem_dic[package]['tendereeMoney'] == 0: # 只有项目编号和名称的包 丢弃
  6560. prem_dic.pop(package)
  6561. continue
  6562. if (re.search('费率|下浮率|[%%‰折]|优惠率',
  6563. bid_amount_header + bid_amount_) and bid_amount < 100) or bid_amount > 50000000000: # 如果是费率或大于500亿的金额改为0
  6564. bid_amount = 0
  6565. if serviceTime:
  6566. serviceTime_text = headers['serviceTime'][1] + serviceTime if headers['serviceTime'][1][-1] in [':',':'] else headers['serviceTime'][1] + ':' + serviceTime
  6567. # print('serviceTime_text',serviceTime_text)
  6568. serviceTime = extract_servicetime(serviceTime_text)
  6569. serviceTime.sort(key=lambda x:x.get('begin_index',0))
  6570. serviceTime = extract_serviceTime(serviceTime[0]['body'],"") if serviceTime else ""
  6571. # print(serviceTime)
  6572. if not same_package or len(prem_dic[package]['roleList'])==0:
  6573. role_dic = {
  6574. "address": "",
  6575. "linklist": [],
  6576. "role_money": {
  6577. "discount_ratio": "",
  6578. "downward_floating_ratio": "",
  6579. "floating_ratio": "",
  6580. "money": bid_amount,
  6581. "money_unit": money_unit
  6582. },
  6583. "role_name": "win_tenderer",
  6584. "role_text": tenderer,
  6585. "serviceTime": serviceTime
  6586. }
  6587. if unit_price > 0:
  6588. role_dic['role_money']['unit_price'] = unit_price
  6589. prem_dic[package]['roleList'].append(role_dic)
  6590. elif prem_dic[package]['roleList'] and prem_dic[package]['roleList'][-1].get('role_name', '')=='win_tenderer':
  6591. if 'multi_winner' not in prem_dic[package]['roleList'][-1]:
  6592. prem_dic[package]['roleList'][-1]['multi_winner'] = prem_dic[package]['roleList'][-1]['role_text']
  6593. prem_dic[package]['roleList'][-1]['multi_winner'] += ','+ tenderer
  6594. elif tenderer not in prem_dic[package]['roleList'][-1]['multi_winner']:
  6595. prem_dic[package]['roleList'][-1]['multi_winner'] += ','+ tenderer
  6596. if bid_amount != 0 or unit_price > 0: # 有中标金额的才放进去
  6597. if 'other_winner_dic' not in prem_dic[package]['roleList'][-1]:
  6598. prem_dic[package]['roleList'][-1]['other_winner_dic'] = []
  6599. prem_dic[package]['roleList'][-1]['other_winner_dic'].append({'role_text': tenderer, "money": bid_amount, "money_unit": money_unit, "serviceTime": serviceTime})
  6600. tenderer_list.append(tenderer)
  6601. serviceTime_list.append(serviceTime)
  6602. if len(prem_dic[package]['roleList']) == 0 and prem_dic[package]['tendereeMoney'] == 0: # 只有项目编号和名称的 丢弃 并不再继续往下匹配
  6603. prem_dic.pop(package)
  6604. # break # 注释掉避免 400084571 某些包废标 中断匹配
  6605. if multi_same_package: # 预处理后包号重复的,使用原始包号
  6606. for k, v in package_fix2raw.items():
  6607. if k in prem_dic:
  6608. prem_dic[v] = prem_dic.pop(k)
  6609. if len(tenderer_list)>2 and len(set(tenderer_list))==1 and "package_code" not in headers: # 没提取到包号且中标人一样应该是错误多包,需去掉多包 例 244355092 281854766
  6610. total_money = 0
  6611. for v in prem_dic.values():
  6612. for d in v['roleList']:
  6613. if d['role_name'] == "win_tenderer":
  6614. total_money += d['role_money']['money']
  6615. if 'other_winner_dic' in d:
  6616. for other in d['other_winner_dic']:
  6617. total_money += other.get('money', 0)
  6618. return {'自增1': {
  6619. 'code': '',
  6620. 'name': '',
  6621. 'roleList': [{
  6622. "address": "",
  6623. "linklist": [],
  6624. "role_money": {
  6625. "discount_ratio": "",
  6626. "downward_floating_ratio": "",
  6627. "floating_ratio": "",
  6628. "money": total_money,
  6629. "money_unit": ''
  6630. },
  6631. "role_name": "win_tenderer",
  6632. "role_text": tenderer_list[0],
  6633. "serviceTime": serviceTime_list[0]
  6634. }],
  6635. 'tendereeMoney': 0,
  6636. 'tendereeMoneyUnit': ""
  6637. }}
  6638. return prem_dic
  6639. def update_prem(self, rs_dic, tmp_dic):
  6640. '''
  6641. 合并更新 prem
  6642. :param rs_dic: 返回结果
  6643. :param tmp_dic: 待合并结果
  6644. :return:
  6645. '''
  6646. if '自增1' in tmp_dic and '自增1' not in rs_dic and len(tmp_dic)==len(rs_dic):
  6647. pass
  6648. else:
  6649. for pack in tmp_dic:
  6650. if pack in rs_dic:
  6651. for k in tmp_dic[pack]:
  6652. if rs_dic[pack][k] in ['', 0]:
  6653. rs_dic[pack][k] = tmp_dic[pack][k]
  6654. elif rs_dic[pack][k] == []:
  6655. rs_dic[pack][k] = tmp_dic[pack][k]
  6656. elif k == 'roleList' and len(rs_dic[pack][k])>0 and rs_dic[pack][k][0].get('role_money', {}).get('money', 0) == 0:
  6657. rs_dic[pack][k] = tmp_dic[pack][k]
  6658. else:
  6659. rs_dic[pack] = tmp_dic[pack]
  6660. def get_prem(self, soup, web_source_name='', all_winner=False):
  6661. tables = soup.find_all('table')
  6662. tables.reverse()
  6663. rs_dic = {}
  6664. for table in tables:
  6665. text = table.text.strip()
  6666. pre_text = ""
  6667. previous = None
  6668. if table.findPreviousSibling() != None:
  6669. previous = table.findPreviousSibling()
  6670. pre_text = previous.text.strip()
  6671. if pre_text == "" and table.findPreviousSibling().findPreviousSibling() != None: # 修复表格前一标签没内容,再前一个才有内容情况
  6672. previous = table.findPreviousSibling().findPreviousSibling()
  6673. pre_text = previous.text.strip()
  6674. if re.search('项目业主|业\s*主', text) and re.search('业\s*绩', text+pre_text): # 包含业绩的表格过滤掉,不进行处理
  6675. tb_ex = table.extract()
  6676. if previous:
  6677. sib = previous.extract()
  6678. continue
  6679. trs = self.tb.table2list(table)
  6680. # table.extract()
  6681. i = 0
  6682. headers = ""
  6683. table_prem = {}
  6684. while i < len(trs) - 1:
  6685. flag_, contain_header_, headers_, not_sure_winner = self.find_header(trs[i], all_winner, first_line=i==0)
  6686. if flag_ and 'tenderer' in headers_ and not_sure_winner and re.search('中标|成交|中选|入围|入选', pre_text)==None:
  6687. # print('过滤:',headers_)
  6688. flag_ = False
  6689. headers_ = {}
  6690. if flag_ and headers_ != dict():
  6691. table_items = []
  6692. headers = headers_
  6693. for j in range(i + 1, len(trs)):
  6694. if len(trs[j]) == len(trs[i]):
  6695. flag_2, contain_header_2, headers_2, not_sure_winner = self.find_header(trs[j], all_winner)
  6696. if flag_2 or contain_header_2:
  6697. if j == i+1 and flag_2:
  6698. if len(headers_)<=len(headers_2):
  6699. headers = headers_2
  6700. continue
  6701. elif trs[i] == trs[j]: # 修复表格重复表头多次出现情况 例:514890585
  6702. continue
  6703. break
  6704. elif ''.join(trs[j]).strip() == '': # 修复整行为空的 例:514890585
  6705. continue
  6706. else:
  6707. table_items.append(trs[j])
  6708. else:
  6709. # print('表头,内容 列数不一致', len(trs[i]), len(trs[j]))
  6710. break
  6711. if len(table_items) > 0:
  6712. df = pd.DataFrame(table_items)
  6713. prem_ = self.extract_from_df(df, headers, web_source_name, all_winner)
  6714. # rs_dic.update(prem_)
  6715. # table_prem.update(prem_)
  6716. self.update_prem(table_prem, prem_)
  6717. i = j - 1
  6718. i += 1
  6719. if table_prem and 'project_code' not in headers and 'package_code' not in headers and '自增1' in table_prem and table.find_previous_sibling(): # 表格内没有标段的,从上一个兄弟标签找标段
  6720. sib = table.find_previous_sibling()
  6721. sib_text = sib.get_text()
  6722. ser_sib = re.search('第?[0-9一二三四五六七八九十a-zA-Z]{1,4}(标[段号的包项]|([分子]?包|包[组件号]))|(标[段号的包项]|([分子]?包|包[组件号]))号?:?[0-9一二三四五六七八九十a-zA-Z]{1,4}|包名:[0-9一二三四五六七八九十]{1,4}', sib_text)
  6723. if sib.name in ['p','div','dl','ol','ul','h1','h2','h3','h4','h5','h6'] and len(sib_text)<100 and ser_sib:
  6724. package_sib = ser_sib.group(0)
  6725. package_sib = uniform_package_name(package_sib)
  6726. table_prem[package_sib] = table_prem.pop('自增1')
  6727. if table_prem:
  6728. # rs_dic.update(table_prem)
  6729. self.update_prem(rs_dic, table_prem)
  6730. table.extract()
  6731. return rs_dic
  6732. def predict(self, html, nlp_enterprise, web_source_name="", all_winner=False):
  6733. html = re.sub("<html>|</html>|<body>|</body>","",html)
  6734. html = re.sub("##attachment##","",html)
  6735. soup = BeautifulSoup(html, 'lxml')
  6736. richText = soup.find(name='div', attrs={'class': 'richTextFetch'})
  6737. self.nlp_enterprise = nlp_enterprise
  6738. in_attachment = False
  6739. if richText:
  6740. richText = richText.extract() # 过滤掉附件
  6741. del_tabel_achievement(soup) # 20240819 过滤掉业绩表格
  6742. prem = self.get_prem(soup, web_source_name, all_winner)
  6743. if prem == {} and richText:
  6744. del_tabel_achievement(richText) # 20240819 过滤掉业绩表格
  6745. prem = self.get_prem(richText, web_source_name, all_winner)
  6746. in_attachment = True
  6747. if len(prem) == 1: # 只有一个包且包号为1 或 长度大于2 的大概率为自动增加编号包,改为Project
  6748. k = list(prem)[0]
  6749. if k.startswith('自增'):
  6750. prem['Project'] = prem.pop(k)
  6751. return prem, in_attachment
  6752. class CandidateExtractor(object):
  6753. def __init__(self):
  6754. '''各要素表头规则'''
  6755. self.head_rule_dic = {
  6756. 'package_code': "(包[段组件]|标[段包]|分[包标])(序?号|$)|包号|^标段$",
  6757. 'project_code': "(项目|招标|采购|计划|公告|包[段组件]|标[段包的]|标段(包)|分[包标])(编号|编码)",
  6758. "project_name": "(包[段组件]|标[段包的项]|标段(包)|分[包标]|采购|项目|工程|货物|商品|产品|设备|通用|主要标的|^包)(名称?|内容)|^标的$",
  6759. "win_sort": "排名|排序|名次|推荐顺序",
  6760. 'win_or_not': '是否(建议|推荐)?(中标|成交)|是否入围|是否入库|入围结论',
  6761. "candidate": "((候选|入围|入选|投标|应答|响应)(供应商库)?的?(人|人?单位|机构|供应商|供货商|服务商|投标人|(中标)?公司|(中标)?企业|银行)|(通过)?名单|中标候选人)(名称|名单|全称|\d)?$|^供应商(名称|信息)?$|投标个人/单位", #补充 368295593 投标个人/单位 提取
  6762. "bid_amount": "投标[报总]?价|报价(总?金额|总价|总额)|总报价|^\w{,5}报价(([\w、/]{1,15}))?$|(中标|成交|合同))?([金总]额|[报均总]价|价[格款]?)|承包价|含税价|经评审的价格",
  6763. "win_tenderer": "第一名|第一(中标|成交)?候选人",
  6764. "second_tenderer": "第二名|第二(中标|成交)?候选人",
  6765. "third_tenderer": "第三名|第三(中标|成交)?候选人",
  6766. }
  6767. '''非表格候选人正则'''
  6768. # self.p = '((候选|入围|入选|投标)(供应商库)?的?(人|人?单位|机构|供应商|供货商|服务商|投标人|(中标)?公司|(中标)?企业|应答人)|(通过)?名单)(名称|名单|全称|\d)?:$'
  6769. self.p = '((候选|入围|入选|投标|报价|成交|中标|中选|供[货应]|应答|响应)(人|方|人?单位|机构|厂?商|商家|服务商|公司|企业)|(通过|入围)名单)(名称|名单|全称|\d)?[是为:]?$'
  6770. self.tb = TableTag2List()
  6771. with open(os.path.dirname(__file__)+'/header_set.pkl', 'rb') as f:
  6772. self.headerset = pickle.load(f)
  6773. def find_header(self, td_list):
  6774. fix_td_list = [re.sub('[::]$|^[一二三四五六七八九十0-9]{1,3}、|(([\w、×*/]{1,20}))$|(不?含税)|/万?元|拟|\s', '', it) for it in td_list] # 去除表头无关信息,方便匹配判断是否为表头
  6775. header_dic = dict()
  6776. flag = False
  6777. contain_header = False
  6778. if len(set(fix_td_list) & self.headerset)>=2 and (len(set(fix_td_list) & self.headerset)/len(set(fix_td_list))>=0.6 or is_head_line(fix_td_list)):
  6779. flag = True
  6780. for i in range(len(td_list)) :
  6781. text = td_list[i]
  6782. text = re.sub('\s|[((]排名不分先后[))]', '', text)
  6783. if len(text) > 15: # 长度大于15 不进行表头匹配
  6784. continue
  6785. if re.search('未(中标|成交)原因', text): # 不提取此种表格
  6786. return flag, contain_header, dict()
  6787. num = 0
  6788. for k, v in self.head_rule_dic.items():
  6789. if k == 'candidate' and re.search('第[一二三]名|第[一二三](中标|成交)?候选人', text):
  6790. continue
  6791. if re.search('评分|得分|分数|分值', text):
  6792. continue
  6793. if re.search(v, text):
  6794. if k in ['candidate', 'win_tenderer', 'second_tenderer', 'third_tenderer'] and re.search('是否', text):
  6795. continue
  6796. header_dic[k] = (i, text)
  6797. # if k != 'candidate': # candidate 可与前三候选重复
  6798. num += 1
  6799. if 'win_tenderer'in header_dic and 'second_tenderer' in header_dic and 'candidate' in header_dic:
  6800. header_dic.pop('candidate')
  6801. if num>1:
  6802. # print('表头错误,一个td匹配到两个表头:', header_dic)
  6803. return flag, contain_header, dict()
  6804. if text == '单位': # 20241128 补充金额单位
  6805. header_dic['amount_unit'] = (i, text)
  6806. if ('candidate' in header_dic and 'win_sort' in header_dic) or ('win_tenderer' in header_dic and 'second_tenderer' in header_dic): # 有排名才返回表头进行提取
  6807. return flag, contain_header, header_dic
  6808. elif len(set(fix_td_list) & self.headerset) >= 2 or (len(set(fix_td_list)) == 2 and len(set(fix_td_list) & self.headerset) >= 1): # 如果包含两个表头以上或 只有两列且包含一个表头
  6809. contain_header = True
  6810. return flag, contain_header, dict()
  6811. def is_role(self, text):
  6812. if len(text) > 25 or len(text) < 4:
  6813. return False
  6814. elif len(re.findall('有限责?任?公司', text)) > 1:
  6815. return False
  6816. elif re.search('[\w()]{4,}(有限责?任?公司|学校|学院|大学|中学|小学|医院|管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园|厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处)$', text):
  6817. return True
  6818. else:
  6819. ners = selffool.ner(text)
  6820. if len(ners[0]) == 1 and ('company' in ners[0][0] or 'org' in ners[0][0]):
  6821. return True
  6822. return False
  6823. def get_role(self, text, nlp_enterprise):
  6824. '''
  6825. 获取字符串text角色实体
  6826. :param text: 待获取实体字符串
  6827. :param nlp_enterprise: 公告中的角色实体列表
  6828. :return:
  6829. '''
  6830. text = re.sub('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:|[((][主成][))]'
  6831. , ',', text)
  6832. text = re.sub('\s', '', text) # 修复 370835008 表格中实体中间有\n
  6833. text = re.sub('[一二三四五六七八九十]+标段[::]|标段[一二三四五六七八九十]+[::]|第[一二三四五六七八九十]+名[::]', '',
  6834. text) # 2024/4/22 修复 372839375 三标段:宁夏一山科技有限公司
  6835. text = re.sub('1[3-9]\d{9}|\d{3}-\d{8}|\d{4}-\d{7}', '', text) # 2024/4/23 去除电话
  6836. if text in nlp_enterprise:
  6837. return text
  6838. if len(text) > 50 or len(text)<4:
  6839. return ''
  6840. ners = getNers([text], useselffool=True)
  6841. roles = []
  6842. if ners:
  6843. for ner in ners[0]:
  6844. if ner[2] in ['org', 'company', 'location']:
  6845. roles.append(ner[3])
  6846. if roles and len(''.join(roles)) > len(text)*0.8:
  6847. return roles[0]
  6848. else:
  6849. return ''
  6850. def extract_from_df(self, df, headers):
  6851. prem_dic = {}
  6852. link_set = set()
  6853. candidate_set = set()
  6854. role_dic = dict() # 保存一二三候选人并排的情况
  6855. findtop3 = False
  6856. findmoney = False
  6857. line_num = 0
  6858. line_package = None
  6859. package_flag = 0
  6860. if "package_code" in headers:
  6861. package_flag = 1
  6862. if len(df)!=len(set(df[headers["package_code"][0]])): # 如果有包号但重复,进行下列判断是否和跟其他字段组合包号
  6863. if "project_code" in headers and df[headers["project_code"][0]][0] != df[headers["package_code"][0]][0]:
  6864. package_flag = 2
  6865. elif "project_name" in headers and find_package(df[headers["package_code"][0]][0]):
  6866. package_flag = 3
  6867. for i in df.index:
  6868. package_code_raw = df.loc[i, headers['package_code'][0]].strip() if "package_code" in headers else ""
  6869. project_code = df.loc[i, headers['project_code'][0]].strip() if "project_code" in headers else ""
  6870. project_name = df.loc[i, headers['project_name'][0]].strip() if "project_name" in headers else ""
  6871. candidate_ = df.loc[i, headers['candidate'][0]].strip() if "candidate" in headers else ""
  6872. win_or_not = df.loc[i, headers['win_or_not'][0]].strip() if "win_or_not" in headers else ""
  6873. # budget_ = df.loc[i, headers['budget'][0]] if "budget" in headers else ""
  6874. bid_amount_ = df.loc[i, headers['bid_amount'][0]].strip() if "bid_amount" in headers else ""
  6875. win_sort = df.loc[i, headers['win_sort'][0]].strip() if "win_sort" in headers else ""
  6876. win_tenderer = df.loc[i, headers['win_tenderer'][0]].strip() if "win_tenderer" in headers else ""
  6877. second_tenderer = df.loc[i, headers['second_tenderer'][0]].strip() if "second_tenderer" in headers else ""
  6878. third_tenderer = df.loc[i, headers['third_tenderer'][0]].strip() if "third_tenderer" in headers else ""
  6879. amount_unit = df.loc[i, headers['amount_unit'][0]].strip() if "amount_unit" in headers else ""
  6880. if set([package_code_raw, candidate_, win_or_not, bid_amount_, win_tenderer, second_tenderer, third_tenderer]) & self.headerset != set(): # 包含表头, 停止匹配 # 排除 ,win_sort 避免367940050漏提取
  6881. # print('包含表头, 停止匹配')
  6882. break
  6883. if len(set([package_code_raw, candidate_,win_sort, win_or_not, bid_amount_, win_tenderer, second_tenderer, third_tenderer]) - set(['', ' '])) < 2: # 全部为空或内容一样 停止匹配
  6884. # print('全部为空或内容一样 停止匹配')
  6885. if len(set(df.loc[i,:]))==1 and re.search('^第?([一二三四五六七八九十]{1,3}|[a-zA-Z0-9-]{,9})?[分子]?(标[段包项]?|包[组件标]?|合同[包段])([一二三四五六七八九十]{1,3}|[a-zA-Z0-9-]{,9})?$', win_sort):
  6886. line_package = win_sort
  6887. continue
  6888. else:
  6889. break
  6890. if candidate_ != "" and win_sort == "" and headers['candidate'][0] > 0: # 修复某些表头不说 排名,直接用候选人代替
  6891. col_indx = headers['candidate'][0] -1
  6892. pre_col = df.loc[i, col_indx]
  6893. if col_indx > 0 and pre_col == candidate_:
  6894. pre_col = df.loc[i, col_indx - 1]
  6895. if re.search('第[一二三]名|第[一二三](中标)?候选人', pre_col):
  6896. win_sort = pre_col
  6897. package_code = package_code_raw
  6898. if package_code == '' and line_package:
  6899. package_code = line_package
  6900. # candidate = candidate_ if self.is_role(candidate_) else ""
  6901. # tenderer = tenderer if self.is_role(tenderer) else ""
  6902. candidate = self.get_role(candidate_, self.nlp_enterprise)
  6903. # if len(set([project_code, package_code, project_name, tenderee, tenderer, budget_, bid_amount_])) < 2:
  6904. # break
  6905. if(candidate_,win_tenderer, second_tenderer,third_tenderer, bid_amount_,package_code,project_code,win_sort) in link_set:
  6906. continue
  6907. link_set.add((candidate_, win_tenderer, second_tenderer, third_tenderer, bid_amount_,package_code,project_code,win_sort))
  6908. package = package_code
  6909. if package == "" and project_code != "": # 修复 395747178 多项目 只提取到一个
  6910. package = project_code
  6911. package = uniform_package_name(package) if package !="" else "Project"
  6912. if package_flag == 2 and project_code != "":
  6913. project_code_pk = uniform_package_name(project_code)
  6914. package = "%s_%s"%(project_code_pk, package)
  6915. elif package_flag == 3 and project_name != "":
  6916. for iter in find_package(project_name):
  6917. project_name_pk = uniform_package_name(iter.group(0))
  6918. package = "%s_%s"%(project_name_pk, package)
  6919. break
  6920. if candidate:
  6921. if win_or_not and re.search('否|未入围', win_or_not):
  6922. candidate_set.add(candidate)
  6923. # elif re.search('^((建议|推荐)(中标|成交)|是)$', win_or_not) and win_sort in ['', '参与投标单位及排名'] and win_tenderer=='':
  6924. # win_sort = '第一名'
  6925. # candidate_set.add(candidate)
  6926. else:
  6927. candidate_set.add(candidate)
  6928. if win_tenderer and second_tenderer: # and third_tenderer 128778062 这篇只有 第一二候选人
  6929. if re.search("(候选人|投标人|单位|公司)名?称?$", df.loc[i, 0]) or re.search("(候选人|投标人|单位|公司)名?称?", df.loc[i, 1]):
  6930. findtop3 = True
  6931. for type, text in zip(['win_tenderer', 'second_tenderer', 'third_tenderer'],
  6932. [win_tenderer, second_tenderer, third_tenderer]):
  6933. text = self.get_role(text, self.nlp_enterprise)
  6934. if text:
  6935. # if self.is_role(text):
  6936. if type not in role_dic:
  6937. role_dic[type] = dict()
  6938. role_dic[type]['role_text'] = text
  6939. candidate_set.add(text)
  6940. elif re.search('投标报价|报价$', df.loc[i, 0]) or re.search('投标报价|报价$', df.loc[i, 1]):
  6941. findmoney = True
  6942. header = df.loc[i, 0] if re.search('投标报价|报价$', df.loc[i, 0]) else df.loc[i, 1]
  6943. for type, text in zip(['win_tenderer', 'second_tenderer', 'third_tenderer'],
  6944. [win_tenderer, second_tenderer, third_tenderer]):
  6945. if len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\s\d,.]|人民币|不?含税', '',
  6946. text)) > 5: # 金额字段出现超过5个非金额字符,中断匹配
  6947. break
  6948. if amount_unit != '' and re.search('^[万亿]?元|%|折[\w/]{,6}$', amount_unit) and re.search('元', text+header)==None: # 补充另外在一列的金额单位
  6949. text += amount_unit
  6950. money, money_unit = money_process(text, header)
  6951. if re.search('元[/每]', amount_unit) or re.search('单价', header):
  6952. unit_price = money
  6953. money = 0
  6954. else:
  6955. unit_price = 0
  6956. if (re.search('费率|下浮率|[%%‰折]|优惠率', header+text) and money < 100) or money > 50000000000: # 如果是费率或大于500亿的金额改为0
  6957. money = 0
  6958. if money > 0:
  6959. if type not in role_dic:
  6960. role_dic[type] = dict()
  6961. role_dic[type]['money'] = money
  6962. role_dic[type]['money_unit'] = money_unit
  6963. if unit_price > 0:
  6964. if type not in role_dic:
  6965. role_dic[type] = dict()
  6966. role_dic[type]['unit_price'] = unit_price
  6967. role_dic[type]['money_unit'] = money_unit
  6968. else:
  6969. line_num += 1
  6970. if findtop3 and findmoney:
  6971. break
  6972. if line_num > 3:
  6973. break
  6974. elif candidate and win_sort:
  6975. role_type = ""
  6976. if re.search('第[一1]|^[一1]$', win_sort):
  6977. role_type = "win_tenderer"
  6978. elif re.search('第[二2]|^[二2]$', win_sort):
  6979. role_type = "second_tenderer"
  6980. elif re.search('第[三3]|^[三3]$', win_sort):
  6981. role_type = "third_tenderer"
  6982. if role_type != "":
  6983. if package not in prem_dic:
  6984. prem_dic[package] = {
  6985. 'code': '',
  6986. 'name': '',
  6987. 'roleList': [],
  6988. 'tendereeMoney': 0,
  6989. 'tendereeMoneyUnit': ""
  6990. }
  6991. prem_dic[package]['code'] = project_code
  6992. prem_dic[package]['name'] = project_name
  6993. if len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\s\d,.]|人民币|不?含税', '', bid_amount_))> 5: # 金额字段出现超过5个非金额字符,中断匹配
  6994. break
  6995. header = headers['bid_amount'][1] if "bid_amount" in headers else ''
  6996. if amount_unit != '' and re.search('^[万亿]?元|%|折[\w/]{,6}$', amount_unit) and re.search('元',
  6997. bid_amount_ + header) == None: # 补充另外在一列的金额单位
  6998. bid_amount_ += amount_unit
  6999. bid_amount, money_unit = money_process(bid_amount_, headers['bid_amount'][1]) if "bid_amount" in headers else (0, "")
  7000. if re.search('元[/每]', amount_unit) or re.search('单价', header):
  7001. unit_price = bid_amount
  7002. bid_amount = 0
  7003. else:
  7004. unit_price = 0
  7005. if (re.search('费率|下浮率|[%%‰折]|优惠率',
  7006. header + bid_amount_) and bid_amount < 100) or bid_amount > 50000000000: # 如果是费率或大于500亿的金额改为0
  7007. bid_amount = 0
  7008. tmp_role_dic = {
  7009. "address": "",
  7010. "linklist": [],
  7011. "role_money": {
  7012. "discount_ratio": "",
  7013. "downward_floating_ratio": "",
  7014. "floating_ratio": "",
  7015. "money": bid_amount,
  7016. "money_unit": money_unit
  7017. },
  7018. "role_name": role_type,
  7019. "role_text": candidate,
  7020. "serviceTime": ""
  7021. }
  7022. if unit_price > 0:
  7023. tmp_role_dic['role_money']['unit_price'] = unit_price
  7024. prem_dic[package]['roleList'].append(tmp_role_dic)
  7025. if len(prem_dic[package]['roleList']) == 0: # 只有项目编号和名称的 丢弃
  7026. prem_dic.pop(package)
  7027. if role_dic and prem_dic == dict():
  7028. if package not in prem_dic:
  7029. prem_dic[package] = {
  7030. 'code': '',
  7031. 'name': '',
  7032. 'roleList': [],
  7033. 'tendereeMoney': 0,
  7034. 'tendereeMoneyUnit': ""
  7035. }
  7036. for role_type, v in role_dic.items():
  7037. role_text = v.get('role_text', '')
  7038. if role_text == "":
  7039. continue
  7040. money = v.get('money', 0)
  7041. money_unit = v.get('money_unit', '')
  7042. prem_dic[package]['roleList'].append({
  7043. "address": "",
  7044. "linklist": [],
  7045. "role_money": {
  7046. "discount_ratio": "",
  7047. "downward_floating_ratio": "",
  7048. "floating_ratio": "",
  7049. "money": money,
  7050. "money_unit": money_unit
  7051. },
  7052. "role_name": role_type,
  7053. "role_text": role_text,
  7054. "serviceTime": ""
  7055. })
  7056. if len(prem_dic[package]['roleList']) == 0: # 只有项目编号和名称的 丢弃
  7057. prem_dic.pop(package)
  7058. return prem_dic, candidate_set
  7059. def get_prem(self, soup):
  7060. tables = soup.find_all('table')
  7061. tables.reverse()
  7062. rs_dic = {}
  7063. candidate_set = set()
  7064. for table in tables:
  7065. trs = self.tb.table2list(table)
  7066. i = 0
  7067. headers = ""
  7068. while i < len(trs) - 1:
  7069. flag_, contain_header_, headers_ = self.find_header(trs[i])
  7070. if flag_ and headers_ != dict():
  7071. table_items = []
  7072. headers = headers_
  7073. for j in range(i + 1, len(trs)):
  7074. if len(trs[j]) == len(trs[i]):
  7075. flag_, contain_header_, headers_ = self.find_header(trs[j])
  7076. if flag_ or contain_header_:
  7077. break
  7078. else:
  7079. table_items.append(trs[j])
  7080. else:
  7081. # print('表头,内容 列数不一致', len(trs[i]), len(trs[j]))
  7082. break
  7083. if len(table_items) >= 1:
  7084. df = pd.DataFrame(table_items)
  7085. prem_, candidate_set_ = self.extract_from_df(df, headers)
  7086. # print('prem_: ', prem_)
  7087. rs_dic.update(prem_)
  7088. candidate_set.update(candidate_set_)
  7089. i = j - 1
  7090. i += 1
  7091. if rs_dic and 'package_code' not in headers and 'Project' in rs_dic and table.find_previous_sibling(): # 一个表格只有两行且没有标段的,从上一个兄弟标签找标段
  7092. sib = table.find_previous_sibling()
  7093. sib_text = sib.get_text()
  7094. ser_sib = re.search('第?[0-9一二三四五六七八九十a-zA-Z]{1,4}(标[段号的包项]|([分子]?包|包[组件号]))|(标[段号的包项]|([分子]?包|包[组件号]))号?:?[0-9一二三四五六七八九十a-zA-Z]{1,4}|包名:[0-9一二三四五六七八九十]{1,4}', sib_text)
  7095. if sib.name in ['p', 'div'] and len(sib_text)<100 and ser_sib:
  7096. package_sib = ser_sib.group(0)
  7097. package_sib = uniform_package_name(package_sib)
  7098. rs_dic[package_sib] = rs_dic.pop('Project')
  7099. table.extract()
  7100. return rs_dic, candidate_set
  7101. def get_candidates_from_text(self, list_sentences, list_entitys):
  7102. candidates = set()
  7103. tenderee_or_agency = set()
  7104. sentences = sorted(list_sentences[0], key=lambda x: x.sentence_index)
  7105. for ent in list_entitys[0]:
  7106. if ent.entity_type in ['org', 'company']:
  7107. sen_index = ent.sentence_index
  7108. text = sentences[sen_index].sentence_text
  7109. b = ent.wordOffset_begin
  7110. e = ent.wordOffset_end
  7111. if ent.label in [2,3,4]: # 直接加实体预测的候选人, 否则规则检查是否为候选人
  7112. candidates.add(ent.entity_text)
  7113. elif isinstance(b, int) and isinstance(e, int) and ent.label in [5]:
  7114. foreword = text[max(0, b - 10):b]
  7115. if re.search(self.p, foreword):
  7116. candidates.add(ent.entity_text)
  7117. if ent.label in [0, 1] and ent.values[ent.label]>0.5:
  7118. tenderee_or_agency.add(ent.entity_text)
  7119. candidates -= tenderee_or_agency # 2024/05/10 463166661 把 四川省第二中医医院作为候选人 过滤掉为招标或代理角色 的候选人
  7120. return candidates
  7121. def predict(self, html, list_sentences, list_entitys, nlp_enterprise):
  7122. self.nlp_enterprise = nlp_enterprise
  7123. html = html.replace('比选申请单位', '中标候选人') # 82347769
  7124. html = re.sub("<html>|</html>|<body>|</body>","",html)
  7125. html = re.sub("##attachment##","",html)
  7126. soup = BeautifulSoup(html, 'lxml')
  7127. richText = soup.find(name='div', attrs={'class': 'richTextFetch'})
  7128. in_attachment = False
  7129. if richText:
  7130. richText = richText.extract() # 过滤掉附件
  7131. del_tabel_achievement(soup) # 20240819 过滤掉业绩表格 例:500817166
  7132. prem, candidate_set = self.get_prem(soup)
  7133. if prem == {} and richText:
  7134. del_tabel_achievement(richText) # 20240819 过滤掉业绩表格
  7135. prem, candidate_set = self.get_prem(richText)
  7136. in_attachment = True
  7137. candidate_set2 = self.get_candidates_from_text(list_sentences, list_entitys)
  7138. candidate_set.update(candidate_set2)
  7139. return prem, {'candidate': ','.join(candidate_set)}, in_attachment
  7140. def role_special_predictor(web_source_name, content, nlp_enterprise):
  7141. if web_source_name == '中国电子科技集团有限公司电子采购平台':
  7142. ser = re.search(',(\w{5,30}),发布时间:\d+', content)
  7143. if ser and ser.group(1) in nlp_enterprise:
  7144. return ser.group(1)
  7145. elif web_source_name == '高校仪器设备竞价网':
  7146. ser = re.search('--(\w{5,30}),申购单主题', content)
  7147. if ser and ser.group(1) in nlp_enterprise:
  7148. return ser.group(1)
  7149. elif web_source_name == '台泥阳光采购平台':
  7150. ser = re.search(',(\w{5,30})招标公告,', content)
  7151. if ser and ser.group(1) in nlp_enterprise:
  7152. return ser.group(1)
  7153. class WebsourceTenderee():
  7154. def __init__(self):
  7155. with open(os.path.dirname(__file__)+'/websource_tenderee.pkl', 'r', encoding='utf-8') as f:
  7156. self.webno2ree = json.load(f)
  7157. def get_websource_tenderee(self, web_source_no, web_source_name, prem):
  7158. '''
  7159. 通过数据源唯一招标人召回调整prem中的招标人,
  7160. :param web_source_no:
  7161. :param prem:
  7162. :return:
  7163. '''
  7164. p = '(医院|学院|学校|中学|小学|大学|幼儿园|保健院|党校|银行|研究院|血站|红十字会|防治院|研究所)'
  7165. web_ree = self.webno2ree.get(web_source_no, '')
  7166. if web_source_no.startswith('18591-') and web_ree == "":
  7167. web_ree = '中国人民解放军总医院'
  7168. elif web_source_no.startswith('Y00484-') and web_ree == "":
  7169. web_ree = '航空总医院'
  7170. if web_ree == "" and re.search('\w{2,8}(大学|医院)$', web_source_name): # 20240524 大学、医院类站源没唯一招标人默认为站源名称
  7171. web_ree = web_source_name
  7172. if web_ree != '':
  7173. if 'Project' in prem[0]['prem']:
  7174. find_tenderee = False
  7175. for d in prem[0]['prem']['Project']['roleList']:
  7176. if d['role_name'] == 'tenderee':
  7177. find_tenderee = True
  7178. if d['role_text'] == "":
  7179. d['role_text'] = web_ree
  7180. elif re.search('大学$', web_ree) and re.search('学院$', d['role_text']) and web_ree not in d['role_text']:
  7181. d['role_text'] = web_ree
  7182. elif d.get('role_prob', 0) < 0.8 and get_business_data(d['role_text'])[0] == False: # 20240201 概率低于0.8且没有工商数据的替换为站源招标人
  7183. d['role_text'] = web_ree
  7184. # elif re.search(p, web_ree) and (re.search(p, d['role_text'])==None and len(d['role_text'])<6): # 数据源唯一招标人以医院等结尾,角色中无相关关键词的,替换为数据源招标人
  7185. # d['role_text'] = web_ree
  7186. # elif re.search('有限(责任)?公司', web_ree) and (re.search('有限(责任)?公司', d['role_text'])==None and len(d['role_text'])<6):
  7187. # d['role_text'] = web_ree
  7188. break
  7189. if not find_tenderee: # 没招标人的添加
  7190. prem[0]['prem']['Project']['roleList'].append({'role_name': 'tenderee',
  7191. 'role_text': '%s' % web_ree,
  7192. 'role_money': {'money': 0, 'money_unit': '',
  7193. 'floating_ratio': '',
  7194. 'downward_floating_ratio': '',
  7195. 'discount_ratio': ''},
  7196. 'linklist': [],
  7197. 'serviceTime': '',
  7198. 'address': ''})
  7199. else:
  7200. prem[0]['prem']['Project'] = {'code': '',
  7201. 'tendereeMoney': 0,
  7202. 'roleList': [
  7203. {'role_name': 'tenderee',
  7204. 'role_text': '%s' % web_ree,
  7205. 'role_money': {'money': 0, 'money_unit': '', 'floating_ratio': '',
  7206. 'downward_floating_ratio': '', 'discount_ratio': ''},
  7207. 'linklist': [],
  7208. 'serviceTime': '',
  7209. 'address': ''}
  7210. ]}
  7211. return prem
  7212. def get_header_line(list_item):
  7213. '''
  7214. 判断列表内文本哪些是表头,哪些不是
  7215. :param list_item: [ '批复结果', '许可/同意', '批复文号',]
  7216. :return:
  7217. '''
  7218. rs = []
  7219. x = []
  7220. for item in list_item:
  7221. x.append(getPredictor("form").encode(item))
  7222. predict_y = getPredictor("form").predict(np.array(x), type="item")
  7223. for item, values in zip(list_item, list(predict_y)):
  7224. lb = 1 if values[1] > 0.5 else 0
  7225. if item in ['许可/同意', '办结(通过)', '办结(准予许可)','批准']:
  7226. lb = 0
  7227. elif item in ['环境影响评价机构', '建设单位或地方政府作出的相关环保承诺']:
  7228. lb = 1
  7229. rs.append(lb)
  7230. return rs
  7231. class ApprovalPredictor():
  7232. def __init__(self):
  7233. '''
  7234. 项目(法人)单位
  7235. '''
  7236. self.other_part = {
  7237. "project_name": "((项目|工程|采购|招标|计划|建设|规划)名称?|生产建设项目|申请项目):(?P<main>[^:。]{5,50})[,。]([\w()]{2,15}:|$)?", # 项目名称
  7238. "project_code": "(立案号|项目(统一)?代码|(项目|工程|采购|招标|计划|任务|备案|索引)([编代][号码]|号)):?(?P<main>(\w{2,8})?[()〔〕【】\[\]a-zA-Z0-9-]{5,30}号?)([\w()]{2,15}:|$)?", # 项目编号
  7239. "doc_num": "((环评|\w{,3})(审[批查核]|批[复准]|立项|[定知文]书|[公发批]文|用地|决定|备案|核准|许可|确认|受理|申请报告|文[件书]|意见书|办件)[文编证]?号|综合受理号|文书?号|合格书号|申报号|(办件|事项)[编代][号码]|收件号))?为?:?(?P<main>[()〔〕【】\[\]0-9]{,8}([\w()〔〕【】]{2,15})?[()〔〕【】\[\]a-zA-Z0-9-.]{3,30}号?)[,。]?([\w()]{2,15}:|$)?", # 文号
  7240. "pro_type": "((申[报请]|审核备|项目|立项)(类型|种类)|项目所属行业|行业(分类|归属)|产业领域|项目行业):(?P<main>[^:。]{2,30})[,。]([\w()]{2,15}:|$)?", # 项目类型
  7241. "year_limit": "((建设|工程|服务|项目)(起止|\w{,2})?(年限|期限|时长|工期)):(约|超过|大概|建设工期|共计|合计)?(?P<main>[\d一二三四五六七八九十]+个月|\d{1,3}(日?历?天|小时)|20\d{2}[年/-](\d{1,2}[月/-]?)?(\d{1,2}日?)?([至—-]+20\d{2}[年/-](\d{1,2}[月/-]?)?(\d{1,2}日?)?)?)[(,。]([\w()]{2,15}:|$)?", # 建设年限
  7242. "construction_scale": "([\d一二三四五六七八九十]{1,2}、|([\d一二三四五六七八九十]{1,2}))?(工程|项目|\w{,4})?((建设内容[及和](建设)?规模|建设规模[及和](主要)?(建设)?内容|(建设|招标|采购))?内容|(建设|工程|项目)(主要)?(规模|内容|概况|面积)([及和](主要)?(规模|内容|概况|面积))?(如下|为)?)|^规模(情况)?):(?P<main>[^:。]{2,500})[,。]?([\w()]{2,30}:|$)?", # 建设规模 #56924861 主要环境影响及预防或者减轻不良环境影响的对策和措施:
  7243. "approval_items": "((审[批查核]|批[复准]|申请|监管|受理)(事项|内容|名称)|事项名称|事项审批):(?P<main>[^:。]{2,150})[,。]([\w()]{2,15}:|$)?", # 审批事项
  7244. "properties": "((建设|工程|项目)性质):(?P<main>[^:。]{2,50})[,。]([\w()]{2,15}:|$)?", # 建设性质
  7245. "approval_result": "((审[批查核]|批[复准]|核[发准]|许可|抽查|备案)(结果|决定|结论|状态|回复|意见)|(办[理件]|,)(状态|意见|结果)|项目(当前|目前)?状态):(?P<main>[^:。]{2,20})[,。]([\w()]{2,15}:|$)?", # 审批结果
  7246. "phone": "(联系)?电话:(?P<main>1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|" # 联系电话
  7247. '\+86.?1[3-9]\d{9}|'
  7248. '0[1-9]\d{1,2}[-—-―][2-9]\d{6}\d?[-—-―]\d{1,4}|'
  7249. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=1[3-9]\d{9})|'
  7250. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[2-9]\d{6}\d?)|'
  7251. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=[2-9]\d{6,7})|'
  7252. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?|'
  7253. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?[2-9]\d{6}\d?-?\d{,4}|'
  7254. '400\d{7}转\d{1,4}|'
  7255. '[2-9]\d{6,7})[,。]([\w()]{2,15}:|$)?'
  7256. }
  7257. self.role_type = {
  7258. "declare_company": "(申[请报]|填报|呈报)(人|部门|机关|单位|企业|公司|机构|组织)", # 申报单位
  7259. "construct_company": "(业主|建设|用地|委托|发包|产权|项目|法人|采购|招标|询价))?(部门|机关|单位|企业|公司|方|业主|人)|主送机关|法人单位|甲方", # 建设单位
  7260. "approver": "(审[批查核议图]|许可|批[复准](用地)?|发证|管理|办理|受理|核[发准]|备案|承办))?(部门|机关|单位|企业|公司|机构)|实施主体", # 审批部门
  7261. "evaluation_agency": "(环境|环保)?(影响)?(环评|评价|评估)(机构|单位|公司)" , # 环评机构
  7262. "compilation_unit": "编制单位", # 编制单位 20240701加
  7263. "publisher": "(发布|发文|公示|公告)(人|部门|机关|单位|企业|公司|机构|组织)" # 发布机构 20240703加
  7264. }
  7265. self.person_type = {
  7266. "legal_person": "项目法人|法定代表人|企业法人" # 项目法人
  7267. }
  7268. self.date_type = {
  7269. "time_declare": "(申[请报]|填报|呈报)(时间|日期)", # 申报时间
  7270. "time_commencement": "(开工|动工|(项目|建设|工程|施工)开始)(时间|日期)", # 开工时间
  7271. "time_completion": "(竣工|完工|验收|(项目|建设|工程|施工)(完成|结束))(备案)?(时间|日期)", # 竣工时间
  7272. "time_approval": "(审[批查核查议]|许可|批[复准](用地)?|发证|管理|办理|受理|核[发准]|备案|决定)(时间|日期)", # 审批时间 20240701加
  7273. "time_release": "(发布|发文|公告|生成|成文)(时间|日期)" # 发布时间
  7274. }
  7275. self.addr_type = {
  7276. "project_addr": "((建设|工程|项目|施工|地块|用地)\w{,2}(地址|地点|位置|所在地)|[宗土]地坐落)" # 建设地址
  7277. }
  7278. self.money_type = {
  7279. "total_tendereeMoney": "(项目|概算|投资)金额|项目投资|总投资|总预算|总概算|投资(规模|总额|估算|概算)|批复概算|投资额|项目概算", # 总投资
  7280. }
  7281. def recursive_text(self, tag):
  7282. '''
  7283. 递归获取 soup 节点文本
  7284. :param tag:
  7285. :return:
  7286. '''
  7287. texts = []
  7288. for child in tag.children:
  7289. if child.name:
  7290. if child.name in ['p'] and len(child.find_all('br'))>2:
  7291. texts.extend(self.recursive_text(child))
  7292. if child.name in ["td", "th", "p", "li", "h1", "h2", "h3", "h4", "h5",
  7293. "h6"] and child.get_text().strip():
  7294. texts.append(re.sub('\s', '', child.get_text().strip().replace(':', ':').replace('(', '(').replace(')', ')')))
  7295. else:
  7296. texts.extend(self.recursive_text(child))
  7297. else:
  7298. if child.strip():
  7299. texts.append(re.sub('\s', '', child.strip().replace(':', ':').replace('(', '(').replace(')', ')')))
  7300. return texts
  7301. def predict(self, list_sentences, list_entitys, html, span=12):
  7302. soup = BeautifulSoup(html)
  7303. texts_list = self.recursive_text(soup)
  7304. rs_dic = {k: "" for k in
  7305. self.other_part.keys() | self.role_type.keys() | self.date_type.keys() | self.addr_type.keys() | self.money_type.keys() | self.person_type.keys()}
  7306. rs_dic['moneysource'] = ""
  7307. sentences = [it.sentence_text for it in sorted(list_sentences[0], key=lambda x: x.sentence_index)]
  7308. entities = [[] for _ in range(len(sentences))]
  7309. rs_l = []
  7310. found_key = 0
  7311. code_name_set = set() # 项目编号、名称集合
  7312. org_set = set() # 保存可能为审批部门的角色
  7313. for entity in list_entitys[0]:
  7314. entities[entity.sentence_index].append(entity)
  7315. for i in range(len(sentences)):
  7316. multi_project = {k: "" for k in
  7317. self.other_part.keys() | self.role_type.keys() | self.date_type.keys() | self.addr_type.keys() | self.money_type.keys() | self.person_type.keys()}
  7318. multi_project['moneysource'] = ''
  7319. text = sentences[i]
  7320. for entity in entities[i]:
  7321. b, e = entity.wordOffset_begin, entity.wordOffset_end
  7322. if entity.entity_type in ['org', 'company']:
  7323. flag = 1
  7324. role_l = []
  7325. for k, v in self.role_type.items():
  7326. ser = re.search(v, sentences[entity.sentence_index][max(0, b - span):b])
  7327. if ser:
  7328. role_l.append((k, ser.end()))
  7329. if role_l:
  7330. role_l = sorted(role_l, key=lambda x: x[1]) # 解决 400064746000 表格某个为空导致两个表头相近提取错误 申报单位名称:备案机关:海门经济技术开发区管理委员会,备案证号:海开审备〔2024〕346号
  7331. k, _ = role_l[-1]
  7332. if rs_dic[k] == '':
  7333. rs_dic[k] = entity.entity_text
  7334. multi_project[k] = entity.entity_text
  7335. found_key = 1
  7336. flag = 0
  7337. if flag and entity.entity_type == "org" and re.search('(局|委员会|委|厅)$', entity.entity_text):
  7338. org_set.add(entity.entity_text)
  7339. elif entity.entity_type in ['person']:
  7340. for k, v in self.person_type.items():
  7341. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  7342. if rs_dic[k] == '':
  7343. rs_dic[k] = entity.entity_text
  7344. multi_project[k] = entity.entity_text
  7345. found_key = 1
  7346. break
  7347. elif entity.entity_type in ['time']:
  7348. time_l = []
  7349. for k, v in self.date_type.items():
  7350. ser = re.search(v, sentences[entity.sentence_index][max(0, b - span):b])
  7351. if ser:
  7352. time_l.append((k, ser.end()))
  7353. if time_l:
  7354. time_l = sorted(time_l, key=lambda x: x[1])
  7355. k, end = time_l[-1]
  7356. time = timeFormat(entity.entity_text, default_first_day=False) if k in [
  7357. 'time_completion'] else timeFormat(entity.entity_text)
  7358. if time == "":
  7359. continue
  7360. if rs_dic[k] == '':
  7361. rs_dic[k] = time
  7362. multi_project[k] = time
  7363. found_key = 1
  7364. elif entity.entity_type in ['location']:
  7365. for k, v in self.addr_type.items():
  7366. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  7367. if rs_dic[k] == '':
  7368. rs_dic[k] = entity.entity_text
  7369. multi_project[k] = entity.entity_text
  7370. found_key = 1
  7371. elif entity.entity_type in ['money']:
  7372. for k, v in self.money_type.items():
  7373. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  7374. if rs_dic[k] == '':
  7375. rs_dic[k] = entity.entity_text
  7376. multi_project[k] = entity.entity_text
  7377. found_key = 1
  7378. elif entity.entity_type in ['moneysource']:
  7379. rs_dic['moneysource'] = turnMoneySource(entity.entity_text)
  7380. multi_project['moneysource'] = turnMoneySource(entity.entity_text)
  7381. elif entity.entity_type in ['code']:
  7382. k = 'project_code'
  7383. v = self.other_part[k].split(':', maxsplit=1)[0]
  7384. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  7385. if rs_dic[k] == '':
  7386. rs_dic[k] = entity.entity_text
  7387. multi_project[k] = entity.entity_text
  7388. found_key = 1
  7389. elif entity.entity_type in ['name']:
  7390. k = 'project_name'
  7391. v = self.other_part[k].split(':', maxsplit=1)[0]
  7392. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  7393. if rs_dic[k] == '':
  7394. rs_dic[k] = entity.entity_text
  7395. multi_project[k] = entity.entity_text
  7396. found_key = 1
  7397. for k, v in self.other_part.items(): # 规则提取非实体类信息
  7398. ser = re.search(v, text)
  7399. if ser:
  7400. if rs_dic[k] == '' or (k == 'project_name' and ',审批事项:' in rs_dic[k]): # 修复 54087410 项目名称包含错误
  7401. rs_dic[k] = ser.group('main')
  7402. multi_project[k] = ser.group('main')
  7403. found_key = 1
  7404. for k, v in self.date_type.items(): # 规则补充时间实体
  7405. if multi_project[k] != '':
  7406. continue
  7407. ser = re.search(v+':?(?P<main>20\d{2}-\d{1,2}(-\d{1,2})?|20\d{2}/\d{1,2}(/\d{1,2})?|20\d{2}\.\d{1,2}(\.\d{1,2})?|20\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])?)', text)
  7408. if ser:# 规则补充实体识别不到的日期时间
  7409. time = timeFormat(ser.group('main'), default_first_day=False) if k in ['time_completion'] else timeFormat(ser.group('main'))
  7410. if time == "":
  7411. continue
  7412. if rs_dic[k] == '':
  7413. rs_dic[k] = time
  7414. multi_project[k] = time
  7415. found_key = 1
  7416. for k, v in self.addr_type.items(): # 规则补充地址实体 400063690529 实体不完整 建设地点:湖北省-咸宁市-通城县 通城县大坪乡沙口村15组(通城经济开发区)
  7417. ser = re.search(v + ':?(?P<main>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])',text)
  7418. if ser:
  7419. if rs_dic[k] == '' or len(rs_dic[k]) < len(ser.group('main')):
  7420. rs_dic[k] = ser.group('main')
  7421. if len(multi_project[k]) < len(ser.group('main')):
  7422. multi_project[k] = ser.group('main')
  7423. found_key = 1
  7424. for k, v in self.role_type.items(): # 规则补充公司实体
  7425. if multi_project[k] != '':
  7426. continue
  7427. ser = re.search('(%s):(?P<main>[\w()]{6,30}(局|发改|超市|棋牌室|店|(个体工商户)))[,。]'%self.role_type[k], text)
  7428. if ser:
  7429. if rs_dic[k] == '':
  7430. rs_dic[k] = ser.group('main')
  7431. multi_project[k] = ser.group('main')
  7432. if (multi_project['project_code'] != "" or multi_project['project_name'] != "") and multi_project['project_code']+multi_project['project_name'] not in code_name_set:
  7433. code_name_set.add(multi_project['project_code']+multi_project['project_name'])
  7434. if len(set([k for k,v in multi_project.items() if v!=''])-set(['project_name', 'project_code']))<2: # 除了包其他要素少于两个的不作为多包
  7435. continue
  7436. district = getPredictor('district').get_area(
  7437. multi_project['approver'] + multi_project['project_name'] + multi_project['project_addr'], '')
  7438. if district['district']['province'] != '全国':
  7439. multi_project['area'] = district['district']['area']
  7440. multi_project['province'] = district['district']['province']
  7441. multi_project['city'] = district['district']['city']
  7442. multi_project['district'] = district['district']['district']
  7443. multi_project = {k: v for k, v in multi_project.items() if v != ''}
  7444. rs_l.append(multi_project)
  7445. if len(rs_l)>1 and len(set(rs_l[0].keys()))>2 and set(rs_l[0].keys())==set(rs_l[1].keys()):
  7446. return rs_l
  7447. elif found_key == 1:
  7448. district = getPredictor('district').get_area(
  7449. rs_dic['approver'] + rs_dic['project_name'] + rs_dic['project_addr'], '')
  7450. if district['district']['province'] != '全国':
  7451. rs_dic['area'] = district['district']['area']
  7452. rs_dic['province'] = district['district']['province']
  7453. rs_dic['city'] = district['district']['city']
  7454. rs_dic['district'] = district['district']['district']
  7455. if len(org_set) == 1 and rs_dic['approver'] == "":
  7456. rs_dic['approver'] == org_set.pop()
  7457. n = 0
  7458. scale_l = [] # 保存以建设规模开头的文本,如果只有一个且比原来长的替换为此文本,避免提取不完成情况
  7459. for text in texts_list: # 补充纠正内容
  7460. for k, v in self.other_part.items():
  7461. kw = v.split(':')[0]
  7462. if re.search('^(%s)$'%kw, text) and rs_dic[k]=='': # 处理非表格表头内容 排列数据 例:400064764198,web_no: XM0016-5
  7463. if n >1 and n+2 < len(texts_list) and get_header_line(texts_list[n-2:n+3]) == [1,0,1,0,1]:
  7464. rs_dic[k] = texts_list[n+1]
  7465. elif n in [0,1] and n+2 < len(texts_list) and get_header_line(texts_list[n:n+3]) == [1,0,1]:
  7466. rs_dic[k] = texts_list[n + 1]
  7467. elif n >1 and n+2 == len(texts_list) and get_header_line(texts_list[n-2:n+2]) == [1,0,1,0]:
  7468. rs_dic[k] = texts_list[n + 1]
  7469. elif k == 'construction_scale' and re.search('^(?[一二三四五六七八九十][)、]', text) and n+1 < len(texts_list): # 大纲 例:53375037
  7470. rs_dic[k] = texts_list[n + 1]
  7471. if k == 'construction_scale' and len(rs_dic.get(k, '')) < len(text):
  7472. ser = re.search('^(%s):(?P<main>.+)'%kw, text)
  7473. if ser:
  7474. rs_dic[k] = ser.group('main')
  7475. n += 1
  7476. if 0<len(rs_dic['construction_scale'])<len(text) and rs_dic['construction_scale'][-1] not in [',', '。'] and text.find(rs_dic['construction_scale'])==0:
  7477. scale_l.append(text)
  7478. if len(scale_l)==1 and len(scale_l[0])>len(rs_dic['construction_scale']): # 规则补充不完整规模信息 例:53334434
  7479. rs_dic['construction_scale'] = scale_l[0]
  7480. if 0<len(rs_dic['construction_scale'])<8 and re.search('([编代][号码]|名称|时间|日期|金额|单位|机构)$', rs_dic['construction_scale']):
  7481. rs_dic['construction_scale'] = ''
  7482. for k, v in rs_dic.items(): # 限制最大长度
  7483. if len(v)>500:
  7484. v = v[:500]+'...后面省略%d字'%(len(v)-500)
  7485. rs_dic[k] = v
  7486. if v == 'null':
  7487. rs_dic[k] = ''
  7488. rs_dic = {k: v for k, v in rs_dic.items() if v != ''}
  7489. return [rs_dic]
  7490. return []
  7491. def getSavedModel():
  7492. #predictor = FormPredictor()
  7493. graph = tf.Graph()
  7494. with graph.as_default():
  7495. model = tf.keras.models.load_model("../form/model/model_form.model_item.hdf5",custom_objects={"precision":precision,"recall":recall,"f1_score":f1_score})
  7496. #print(tf.graph_util.remove_training_nodes(model))
  7497. tf.saved_model.simple_save(
  7498. tf.keras.backend.get_session(),
  7499. "./h5_savedmodel/",
  7500. inputs={"image": model.input},
  7501. outputs={"scores": model.output}
  7502. )
  7503. def getBiLSTMCRFModel(MAX_LEN,vocab,EMBED_DIM,BiRNN_UNITS,chunk_tags,weights):
  7504. '''
  7505. model = models.Sequential()
  7506. model.add(layers.Embedding(len(vocab), EMBED_DIM, mask_zero=True)) # Random embedding
  7507. model.add(layers.Bidirectional(layers.LSTM(BiRNN_UNITS // 2, return_sequences=True)))
  7508. crf = CRF(len(chunk_tags), sparse_target=True)
  7509. model.add(crf)
  7510. model.summary()
  7511. model.compile('adam', loss=crf.loss_function, metrics=[crf.accuracy])
  7512. return model
  7513. '''
  7514. input = layers.Input(shape=(None,),dtype="int32")
  7515. if weights is not None:
  7516. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True,weights=[weights],trainable=True)(input)
  7517. else:
  7518. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True)(input)
  7519. bilstm = layers.Bidirectional(layers.LSTM(BiRNN_UNITS//2,return_sequences=True))(embedding)
  7520. bilstm_dense = layers.TimeDistributed(layers.Dense(len(chunk_tags)))(bilstm)
  7521. crf = CRF(len(chunk_tags),sparse_target=True)
  7522. crf_out = crf(bilstm_dense)
  7523. model = models.Model(input=[input],output = [crf_out])
  7524. model.summary()
  7525. model.compile(optimizer = 'adam', loss = crf.loss_function, metrics = [crf.accuracy])
  7526. return model
  7527. import h5py
  7528. def h5_to_graph(sess,graph,h5file):
  7529. f = h5py.File(h5file,'r') #打开h5文件
  7530. def getValue(v):
  7531. _value = f["model_weights"]
  7532. list_names = str(v.name).split("/")
  7533. for _index in range(len(list_names)):
  7534. print(v.name)
  7535. if _index==1:
  7536. _value = _value[list_names[0]]
  7537. _value = _value[list_names[_index]]
  7538. return _value.value
  7539. def _load_attributes_from_hdf5_group(group, name):
  7540. """Loads attributes of the specified name from the HDF5 group.
  7541. This method deals with an inherent problem
  7542. of HDF5 file which is not able to store
  7543. data larger than HDF5_OBJECT_HEADER_LIMIT bytes.
  7544. # Arguments
  7545. group: A pointer to a HDF5 group.
  7546. name: A name of the attributes to load.
  7547. # Returns
  7548. data: Attributes data.
  7549. """
  7550. if name in group.attrs:
  7551. data = [n.decode('utf8') for n in group.attrs[name]]
  7552. else:
  7553. data = []
  7554. chunk_id = 0
  7555. while ('%s%d' % (name, chunk_id)) in group.attrs:
  7556. data.extend([n.decode('utf8')
  7557. for n in group.attrs['%s%d' % (name, chunk_id)]])
  7558. chunk_id += 1
  7559. return data
  7560. def readGroup(gr,parent_name,data):
  7561. for subkey in gr:
  7562. print(subkey)
  7563. if parent_name!=subkey:
  7564. if parent_name=="":
  7565. _name = subkey
  7566. else:
  7567. _name = parent_name+"/"+subkey
  7568. else:
  7569. _name = parent_name
  7570. if str(type(gr[subkey]))=="<class 'h5py._hl.group.Group'>":
  7571. readGroup(gr[subkey],_name,data)
  7572. else:
  7573. data.append([_name,gr[subkey].value])
  7574. print(_name,gr[subkey].shape)
  7575. layer_names = _load_attributes_from_hdf5_group(f["model_weights"], 'layer_names')
  7576. list_name_value = []
  7577. readGroup(f["model_weights"], "", list_name_value)
  7578. '''
  7579. for k, name in enumerate(layer_names):
  7580. g = f["model_weights"][name]
  7581. weight_names = _load_attributes_from_hdf5_group(g, 'weight_names')
  7582. #weight_values = [np.asarray(g[weight_name]) for weight_name in weight_names]
  7583. for weight_name in weight_names:
  7584. list_name_value.append([weight_name,np.asarray(g[weight_name])])
  7585. '''
  7586. for name_value in list_name_value:
  7587. name = name_value[0]
  7588. '''
  7589. if re.search("dense",name) is not None:
  7590. name = name[:7]+"_1"+name[7:]
  7591. '''
  7592. value = name_value[1]
  7593. print(name,graph.get_tensor_by_name(name),np.shape(value))
  7594. sess.run(tf.assign(graph.get_tensor_by_name(name),value))
  7595. def initialize_uninitialized(sess):
  7596. global_vars = tf.global_variables()
  7597. is_not_initialized = sess.run([tf.is_variable_initialized(var) for var in global_vars])
  7598. not_initialized_vars = [v for (v, f) in zip(global_vars, is_not_initialized) if not f]
  7599. adam_vars = []
  7600. for _vars in not_initialized_vars:
  7601. if re.search("Adam",_vars.name) is not None:
  7602. adam_vars.append(_vars)
  7603. print([str(i.name) for i in adam_vars]) # only for testing
  7604. if len(adam_vars):
  7605. sess.run(tf.variables_initializer(adam_vars))
  7606. def save_codename_model():
  7607. # filepath = "../projectCode/models/model_project_"+str(60)+"_"+str(200)+".hdf5"
  7608. filepath = "../../dl_dev/projectCode/models_tf/59-L0.471516189943-F0.8802154826344823-P0.8789179683459191-R0.8815168335321886/model.ckpt"
  7609. vocabpath = "../projectCode/models/vocab.pk"
  7610. classlabelspath = "../projectCode/models/classlabels.pk"
  7611. # vocab = load(vocabpath)
  7612. # class_labels = load(classlabelspath)
  7613. w2v_matrix = load('codename_w2v_matrix.pk')
  7614. graph = tf.get_default_graph()
  7615. with graph.as_default() as g:
  7616. ''''''
  7617. # model = getBiLSTMCRFModel(None, vocab, 60, 200, class_labels,weights=None)
  7618. #model = models.load_model(filepath,custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score,"CRF":CRF,"loss":CRF.loss_function})
  7619. sess = tf.Session(graph=g)
  7620. # sess = tf.keras.backend.get_session()
  7621. char_input, logits, target, keepprob, length, crf_loss, trans, train_op = BiLSTM_CRF_tfmodel(sess, w2v_matrix)
  7622. #with sess.as_default():
  7623. sess.run(tf.global_variables_initializer())
  7624. # print(sess.run("time_distributed_1/kernel:0"))
  7625. # model.load_weights(filepath)
  7626. saver = tf.train.Saver()
  7627. saver.restore(sess, filepath)
  7628. # print("logits",sess.run(logits))
  7629. # print("#",sess.run("time_distributed_1/kernel:0"))
  7630. # x = load("codename_x.pk")
  7631. #y = model.predict(x)
  7632. # y = sess.run(model.output,feed_dict={model.input:x})
  7633. # for item in np.argmax(y,-1):
  7634. # print(item)
  7635. tf.saved_model.simple_save(
  7636. sess,
  7637. "./codename_savedmodel_tf/",
  7638. inputs={"inputs": char_input,
  7639. "inputs_length":length,
  7640. 'keepprob':keepprob},
  7641. outputs={"logits": logits,
  7642. "trans":trans}
  7643. )
  7644. def save_role_model():
  7645. '''
  7646. @summary: 保存model为savedModel,部署到PAI平台上调用
  7647. '''
  7648. model_role = PREMPredict().model_role
  7649. with model_role.graph.as_default():
  7650. model = model_role.getModel()
  7651. sess = tf.Session(graph=model_role.graph)
  7652. print(type(model.input))
  7653. sess.run(tf.global_variables_initializer())
  7654. h5_to_graph(sess, model_role.graph, model_role.model_role_file)
  7655. model = model_role.getModel()
  7656. tf.saved_model.simple_save(sess,
  7657. "./role_savedmodel/",
  7658. inputs={"input0":model.input[0],
  7659. "input1":model.input[1],
  7660. "input2":model.input[2]},
  7661. outputs={"outputs":model.output}
  7662. )
  7663. def save_money_model():
  7664. model_file = os.path.dirname(__file__)+"/../money/models/model_money_word.h5"
  7665. graph = tf.Graph()
  7666. with graph.as_default():
  7667. sess = tf.Session(graph=graph)
  7668. with sess.as_default():
  7669. # model = model_money.getModel()
  7670. # model.summary()
  7671. # sess.run(tf.global_variables_initializer())
  7672. # h5_to_graph(sess, model_money.graph, model_money.model_money_file)
  7673. model = models.load_model(model_file,custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score})
  7674. model.summary()
  7675. print(model.weights)
  7676. tf.saved_model.simple_save(sess,
  7677. "./money_savedmodel2/",
  7678. inputs = {"input0":model.input[0],
  7679. "input1":model.input[1],
  7680. "input2":model.input[2]},
  7681. outputs = {"outputs":model.output}
  7682. )
  7683. def save_person_model():
  7684. model_person = EPCPredict().model_person
  7685. with model_person.graph.as_default():
  7686. x = load("person_x.pk")
  7687. _data = np.transpose(np.array(x),(1,0,2,3))
  7688. model = model_person.getModel()
  7689. sess = tf.Session(graph=model_person.graph)
  7690. with sess.as_default():
  7691. sess.run(tf.global_variables_initializer())
  7692. model_person.load_weights()
  7693. #h5_to_graph(sess, model_person.graph, model_person.model_person_file)
  7694. predict_y = sess.run(model.output,feed_dict={model.input[0]:_data[0],model.input[1]:_data[1]})
  7695. #predict_y = model.predict([_data[0],_data[1]])
  7696. print(np.argmax(predict_y,-1))
  7697. tf.saved_model.simple_save(sess,
  7698. "./person_savedmodel/",
  7699. inputs={"input0":model.input[0],
  7700. "input1":model.input[1]},
  7701. outputs = {"outputs":model.output})
  7702. def save_form_model():
  7703. model_form = FormPredictor()
  7704. with model_form.graph.as_default():
  7705. model = model_form.getModel("item")
  7706. sess = tf.Session(graph=model_form.graph)
  7707. sess.run(tf.global_variables_initializer())
  7708. h5_to_graph(sess, model_form.graph, model_form.model_file_item)
  7709. tf.saved_model.simple_save(sess,
  7710. "./form_savedmodel/",
  7711. inputs={"inputs":model.input},
  7712. outputs = {"outputs":model.output})
  7713. def save_codesplit_model():
  7714. filepath_code = "../../dl_dev/projectCode/models/model_code.hdf5"
  7715. graph = tf.Graph()
  7716. with graph.as_default():
  7717. model_code = models.load_model(filepath_code, custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score})
  7718. sess = tf.Session()
  7719. sess.run(tf.global_variables_initializer())
  7720. h5_to_graph(sess, graph, filepath_code)
  7721. tf.saved_model.simple_save(sess,
  7722. "./codesplit_savedmodel/",
  7723. inputs={"input0":model_code.input[0],
  7724. "input1":model_code.input[1],
  7725. "input2":model_code.input[2]},
  7726. outputs={"outputs":model_code.output})
  7727. def save_timesplit_model():
  7728. filepath = '../time/model_label_time_classify.model.hdf5'
  7729. with tf.Graph().as_default() as graph:
  7730. time_model = models.load_model(filepath, custom_objects={'precision': precision, 'recall': recall, 'f1_score': f1_score})
  7731. with tf.Session() as sess:
  7732. sess.run(tf.global_variables_initializer())
  7733. h5_to_graph(sess, graph, filepath)
  7734. tf.saved_model.simple_save(sess,
  7735. "./timesplit_model/",
  7736. inputs={"input0":time_model.input[0],
  7737. "input1":time_model.input[1]},
  7738. outputs={"outputs":time_model.output})
  7739. if __name__=="__main__":
  7740. #save_role_model()
  7741. # save_codename_model()
  7742. # save_money_model()
  7743. #save_person_model()
  7744. #save_form_model()
  7745. #save_codesplit_model()
  7746. # save_timesplit_model()
  7747. '''
  7748. # with tf.Session(graph=tf.Graph()) as sess:
  7749. # from tensorflow.python.saved_model import tag_constants
  7750. # meta_graph_def = tf.saved_model.loader.load(sess, [tag_constants.SERVING], "./person_savedModel")
  7751. # graph = tf.get_default_graph()
  7752. # signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  7753. # signature = meta_graph_def.signature_def
  7754. # input0 = sess.graph.get_tensor_by_name(signature[signature_key].inputs["input0"].name)
  7755. # input1 = sess.graph.get_tensor_by_name(signature[signature_key].inputs["input1"].name)
  7756. # outputs = sess.graph.get_tensor_by_name(signature[signature_key].outputs["outputs"].name)
  7757. # x = load("person_x.pk")
  7758. # _data = np.transpose(x,[1,0,2,3])
  7759. # y = sess.run(outputs,feed_dict={input0:_data[0],input1:_data[1]})
  7760. # print(np.argmax(y,-1))
  7761. '''
  7762. # MAX_LEN = 1000
  7763. # # vocabpath = os.path.dirname(__file__) + "/codename_vocab.pk"
  7764. # # vocab = load(vocabpath)
  7765. # # word2index = dict((w, i) for i, w in enumerate(np.array(vocab)))
  7766. # # index_unk = word2index.get("<unk>")
  7767. # # sentence = "招标人:广州市重点公共建设项目管理中心,联系人:李工,联系方式:020-22905689,招标代理:广东重工建设监理有限公司," \
  7768. # # "代理联系人:薛家伟,代理联系方式:13535014481,招标监督机构:广州市重点公共建设项目管理中心,监督电话:020-22905690," \
  7769. # # "备注:以上为招标公告简要描述,招标公告详细信息请查看“招标公告”附件,"
  7770. # # sentence = sentence*5
  7771. # # list_sentence = [sentence]*200
  7772. # # # print(list_sentence)
  7773. # # x = [[word2index.get(word, index_unk) for word in sentence] for sentence in
  7774. # # list_sentence]
  7775. # # x_len = [len(_x) if len(_x) < MAX_LEN else MAX_LEN for _x in x]
  7776. # # # print(x_len)
  7777. # # x = pad_sequences(x, maxlen=MAX_LEN, padding="post", truncating="post")
  7778. # #
  7779. # # requests_result = requests.post(API_URL + "/predict_codeName", json={"inouts": x.tolist(), "inouts_len": x_len},
  7780. # # verify=True)
  7781. # # # predict_y = json.loads(requests_result.text)['result']
  7782. # # print("cost_time:", json.loads(requests_result.text)['cost_time'])
  7783. # # print(MAX_LEN, len(sentence), len(list_sentence))
  7784. # # requests_result = requests.post(API_URL + "/predict_codeName", json={"inouts": x.tolist(), "inouts_len": x_len},
  7785. # # verify=True)
  7786. # # # predict_y = json.loads(requests_result.text)['result']
  7787. # # print("cost_time:", json.loads(requests_result.text)['cost_time'])
  7788. # # print(MAX_LEN, len(sentence), len(list_sentence))
  7789. # docid = ""
  7790. # title = ''
  7791. # with open('d:/html/2.html', 'r', encoding='utf-8') as f:
  7792. # html = f.read()
  7793. # product_attr = ProductAttributesPredictor()
  7794. # rs = product_attr.predict(docid='', html=html, page_time="")
  7795. # print(rs)
  7796. docid = ""
  7797. title = '甘肃省妇幼保健院(甘肃省中心医院)2024年度大额资金定期存款竞争性存放项目(第二期)采购结果公告'
  7798. with open('d:/html/2.html', 'r', encoding='utf-8') as f:
  7799. html = f.read()
  7800. tb_extract = TablePremExtractor()
  7801. rs = tb_extract.predict(html, [
  7802. "江苏中联铸本混凝土有限公司",
  7803. "鼓楼区协荣机械设备经销部"
  7804. ], web_source_name = '', all_winner=False)
  7805. print('标段数:',len(rs[0]))
  7806. print(rs)
  7807. # # # ids = [199601430, 195636197, 123777031, 195191849, 163533442, 121845385, 217782764, 163370956, 238134423, 191700799, 148218772, 189295942, 145940984, 166830213, 119271266, 90157660, 180314485, 136564968, 119094883, 89822506, 209263355, 132839357, 85452163, 110204324, 204773640, 83910716, 126657693, 107244197, 79107109, 47810780, 233548561, 237887867, 79134266, 77124584, 75804469, 43206978, 237560666, 67472815, 42078089, 66307082, 38382419, 224367857, 224751772, 54913238, 237390205, 60511017, 33170000, 228578442, 69042200, 228535928, 79997322, 233492018, 51828144, 219494938, 240514770]
  7808. # # # ids = [42078089, 51828144, 54913238, 60511017, 67472815, 69042200, 75804469, 77124584, 79107109, 79997322, 83910716, 85452163, 89822506, 90157660, 107244197, 110204324, 119094883, 121845385, 123777031, 132839357, 136564968, 145940984, 148218772, 163370956, 163533442, 166830213, 180314485, 191700799, 195191849, 199601430, 204773640, 209263355, 217782764, 219494938, 224367857, 224751772, 228535928, 228578442, 233492018, 237390205, 237560666, 237887867, 238134423, 240514770]
  7809. # # # ids = [42078089, 51828144, 60511017, 69042200, 77124584, 79107109, 79997322, 83910716, 85452163, 89822506, 107244197, 110204324, 119094883, 121845385, 123777031, 132839357, 136564968, 145940984, 148218772, 163370956, 163533442, 166830213, 180314485, 191700799, 195191849, 199601430, 204773640, 209263355, 217782764, 219494938, 224367857, 224751772, 228535928, 228578442, 233492018, 237390205, 237560666, 237887867, 238134423, 240514770]
  7810. # # # ids = [ 224751772, 228535928, 228578442, 233492018, 237390205, 237560666, 237887867, 238134423, 240514770]
  7811. # # # ids = [37756133, 39743626, 42068246, 51176657, 70624901, 75687028, 85489552, 95342532, 97337474, 109601526, 111464967, 112548665, 116223553, 117329696, 117850214, 120619166, 121717252, 122345499, 128511969, 133403846, 133602236, 136564970, 137772969, 138020374, 140929169, 147414295, 152659064, 155485083, 186412244, 195546784, 196135909, 202981523, 214647448, 216377830, 217957372, 218789230, 225050691, 228064464, 228590691, 236342514, 237352780, 239814252]
  7812. # # # ids = [51176657, 70624901, 85489552, 95342532, 109601526, 111464967, 112548665, 116223553, 117329696, 117850214, 120619166, 121717252, 122345499, 128511969, 133403846, 133602236, 136564970, 137772969, 138020374, 140929169, 147414295, 152659064, 155485083, 186412244, 195546784, 196135909, 202981523, 214647448, 216377830, 217957372, 218789230, 225050691, 228064464, 228590691, 236342514, 237352780, 239814252]
  7813. # ids = [31995310, 33586422, 34213587, 36093749, 37238528, 37739743, 39150739, 39281429, 40038908, 40289771, 40581071, 40591331, 42200293, 42739447, 42923948, 43351479, 44237678, 44506815, 44592013, 45106514, 45469037, 48411467, 51822565, 52127391, 54236264, 54706723, 54894477, 54898083, 55934378, 56104538, 56218948, 59606477, 60116927, 60638934, 61523351, 61685037, 61706106, 62187765, 62203118, 62843892, 63850238, 64139401, 65707507, 66072846, 66137391, 66738991, 67676932, 67902417, 69795866, 70868740, 71180456, 71796375, 77613620, 77641817, 77748144, 77761818, 78250390, 78606698, 78717682, 78854831, 79597122, 79597366, 79819968, 80377018, 82461832, 84018089, 84134439, 84815332, 85123470, 85123525, 85456789, 87474450, 88129399, 88288685, 88329278, 88342999, 88747517, 89632339, 89861712, 89985134, 91538446, 93323837, 94609104, 95522891, 97476802, 97629540, 98662744, 100207494, 100558146, 100755026, 101009561, 101275254, 101348782, 101462933, 101857772, 102924005, 103432276, 103459091, 104062674, 106601819, 106812124, 107065735, 107559314, 108201680, 108455612, 108544389, 108832580, 108995821, 109196083, 110726641, 110780095, 111234020, 111588327, 111656418, 111797176, 111993708, 114376859, 115869547, 117725909, 118032923, 118349683, 119080451, 119224972, 120120112, 120304657, 120830324, 122331341, 122856799, 123439110, 123641276, 123733047, 123733333, 123874242, 123918651, 124253086, 124942182, 125372140, 125464462, 125568385, 126185770, 126305386, 126512513, 126840529, 126844209, 126902118, 127254675, 127510817, 127670247, 128441465, 128498056, 129557176, 129833289, 129875792, 130121559, 130554345, 130556979, 131051006, 131142204, 131480539, 133743564, 133834740, 133984477, 134796953, 135533772, 135986763, 136777096, 137403576, 137864604, 138148591, 139840028, 139974803, 140105753, 145439181, 149105875, 150129836, 150828866, 152675649, 153688731, 155564708, 155599250, 155600699, 156728197, 161246902, 161775170, 162476194, 162914022, 162963943, 164007344, 164775490, 165339842, 175705079, 176218853, 176944891, 178251502, 178372090, 179732253, 180379187, 181626147, 184044160, 184404217, 186383436, 188468811, 192103014, 192574092, 192754157, 193358322, 195686462, 195868255, 196060419, 199113788, 201588003, 201874243, 201879319, 204796942, 205348530, 206735492, 208308899, 210310963, 210313993, 212124901, 212363133, 212389173, 213573782, 213818877, 214044075, 214989980, 215356671, 215367201, 215646443, 216212563, 216377823, 216490415, 217483041, 217486509, 218429429, 219181483, 219411056, 219971724, 220400698, 220780247, 221398716, 222545237, 223267606, 223906281, 224074580, 224383778, 224995705, 225390819, 227536610, 227829175, 227908020, 227980430, 229421942, 229862241, 230217038, 230227848, 230391553, 230592027, 233836843, 234465556, 235108306, 235217324, 235995802, 236010068, 236359727, 236419142, 236997002, 238069580, 238106585, 238534142, 238567209, 238839802, 239260141, 240214254, 240263848, 240535275, 240680028]
  7814. # df = pd.read_csv('E:\产品单价数量/待预测数据html内容4.csv')
  7815. # print('公告数:', len(df), len(ids))
  7816. # df = df[df['docid'].isin(ids)]
  7817. # ids = []
  7818. # for docid,html in zip(df['docid'],df['dochtmlcon']):
  7819. # product_attr = ProductAttributesPredictor()
  7820. # rs, _ = product_attr.predict(docid='', html=html, page_time="")
  7821. # # print(docid, rs)
  7822. # # print(docid, rs[0]['product_attrs']['header_col'])
  7823. # # print('*'*20)
  7824. # if rs[0]['product_attrs']['header_col'] == []:
  7825. # ids.append(docid)
  7826. # print(docid, rs[0]['product_attrs']['header_col'])
  7827. # print('*' * 20)
  7828. # else:
  7829. # print(docid, rs[0]['product_attrs']['header_col'])
  7830. # print('*' * 20)
  7831. # print(len(ids), ids)
  7832. # role = RoleRulePredictor()
  7833. # labels = []
  7834. # keywords = []
  7835. # # df = pd.read_excel('E:\实体识别数据/2023-08-24所有公告_重新预测结果.xlsx')
  7836. # df = pd.read_excel('E:\实体识别数据/2023-08-24所有公告_重新预测结果60000-90000.xlsx')
  7837. # columns = ['docid', 'type', 'label', 'value', 'front', 'behind',
  7838. # 'front6', 'entity_text', 'behind6', 'front6_reverse', 'rule_label', 'keyword', 'pos']
  7839. # print(df.columns)
  7840. # df.fillna('', inplace=True)
  7841. # for front, center, behind, entity_text in zip(df['front'], df['entity_text'], df['behind'], df['entity_text']):
  7842. # front = str(front)
  7843. # behind = str(behind)
  7844. # label, _prob, _flag, keyword = role.rule_predict(front, center, behind, entity_text)
  7845. # labels.append(label)
  7846. # keywords.append(keyword)
  7847. # df['rule_label'] = pd.Series(labels)
  7848. # df['keyword'] = pd.Series(keywords)
  7849. # df['front6'] = df['front'].apply(lambda x: str(x)[-6:])
  7850. # df['behind6'] = df['behind'].apply(lambda x: str(x)[:6])
  7851. # df['pos'] = df.apply(lambda x: 1 if x['label']==x['rule_label'] else 0, axis=1)
  7852. # # df.to_excel('E:\实体识别数据/2023-08-24所有公告_重新预测结果_rule_predict.xlsx', index=False, columns=columns)
  7853. # df.to_excel('E:\实体识别数据/2023-08-24所有公告_重新预测结果60000-90000_rule_predict.xlsx', index=False, columns=columns)
  7854. # print(get_header_line(['环评项目登记号','/','环评批文文号','金环许[2023]126号','环评批文日期']))
  7855. # print(get_header_line(['序号', '项目名称', '建设地点', '建设单位', '环评机构', '项目概况', '主要环境影响及预防或者减轻不良环境影响的对策和措施', '建设单位或地方政府作出的相关环保承诺', '公众反馈意见的联系方式']))