predictor.py 497 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810
  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. # import fool # 统一用 selffool ,阿里云上只有selffool 包
  31. cpu_num = int(os.environ.get("CPU_NUM",0))
  32. sess_config = tf.ConfigProto(
  33. inter_op_parallelism_threads = cpu_num,
  34. intra_op_parallelism_threads = cpu_num,
  35. log_device_placement=True)
  36. sess_config = None
  37. file = os.path.dirname(__file__) + '/agency_set.pkl'
  38. with open(file, 'rb') as f:
  39. agency_set = pickle.load(f)
  40. def is_agency(entity_text):
  41. if re.search('(招投?标|采购|代理|咨询|管理|物资|事务所?|顾问|监理|拍卖)[()\w]{,4}(有限)?(责任)?公司|(采购|招投?标|交易|代理|咨询)[()\w]{,4}(中心|服务所)|法院$',
  42. entity_text) or entity_text in agency_set:
  43. return True
  44. return False
  45. from threading import RLock
  46. dict_predictor = {"codeName":{"predictor":None,"Lock":RLock()},
  47. "prem":{"predictor":None,"Lock":RLock()},
  48. "epc":{"predictor":None,"Lock":RLock()},
  49. "roleRule":{"predictor":None,"Lock":RLock()},
  50. "roleRuleFinal":{"predictor":None,"Lock":RLock()},
  51. "tendereeRuleRecall":{"predictor":None,"Lock":RLock()},
  52. "form":{"predictor":None,"Lock":RLock()},
  53. "time":{"predictor":None,"Lock":RLock()},
  54. "punish":{"predictor":None,"Lock":RLock()},
  55. "product":{"predictor":None,"Lock":RLock()},
  56. "product_attrs":{"predictor":None,"Lock":RLock()},
  57. "channel": {"predictor": None, "Lock": RLock()},
  58. "deposit_payment_way": {"predictor": None, "Lock": RLock()},
  59. "total_unit_money": {"predictor": None, "Lock": RLock()},
  60. "industry": {"predictor": None, "Lock": RLock()},
  61. "rolegrade": {"predictor": None, "Lock": RLock()},
  62. "moneygrade": {"predictor": None, "Lock": RLock()},
  63. "district": {"predictor": None, "Lock": RLock()},
  64. 'tableprem': {"predictor": None, "Lock": RLock()},
  65. 'candidate': {"predictor": None, "Lock": RLock()},
  66. 'websource_tenderee': {"predictor": None, "Lock": RLock()},
  67. 'project_label': {"predictor": None, "Lock": RLock()},
  68. 'pb_extract': {"predictor": None, "Lock": RLock()},
  69. 'property_label': {"predictor": None, "Lock": RLock()},
  70. 'approval': {"predictor": None, "Lock": RLock()} # 审批项目预测
  71. }
  72. def getPredictor(_type):
  73. if _type in dict_predictor:
  74. with dict_predictor[_type]["Lock"]:
  75. if dict_predictor[_type]["predictor"] is None:
  76. if _type == "codeName":
  77. dict_predictor[_type]["predictor"] = CodeNamePredict(config=sess_config)
  78. if _type == "prem":
  79. dict_predictor[_type]["predictor"] = PREMPredict(config=sess_config)
  80. if _type == "epc":
  81. dict_predictor[_type]["predictor"] = EPCPredict(config=sess_config)
  82. if _type == "roleRule":
  83. dict_predictor[_type]["predictor"] = RoleRulePredictor()
  84. if _type == "roleRuleFinal":
  85. dict_predictor[_type]["predictor"] = RoleRuleFinalAdd()
  86. if _type == "tendereeRuleRecall":
  87. dict_predictor[_type]["predictor"] = TendereeRuleRecall()
  88. if _type == "form":
  89. dict_predictor[_type]["predictor"] = FormPredictor(config=sess_config)
  90. if _type == "time":
  91. dict_predictor[_type]["predictor"] = TimePredictor(config=sess_config)
  92. if _type == "punish":
  93. dict_predictor[_type]["predictor"] = Punish_Extract()
  94. if _type == "product":
  95. dict_predictor[_type]["predictor"] = ProductPredictor(config=sess_config)
  96. if _type == "product_attrs":
  97. dict_predictor[_type]["predictor"] = ProductAttributesPredictor()
  98. if _type == "channel":
  99. dict_predictor[_type]["predictor"] = DocChannel(config=sess_config)
  100. if _type == 'deposit_payment_way':
  101. dict_predictor[_type]["predictor"] = DepositPaymentWay()
  102. if _type == 'total_unit_money':
  103. dict_predictor[_type]["predictor"] = TotalUnitMoney()
  104. if _type == 'industry':
  105. dict_predictor[_type]["predictor"] = IndustryPredictor()
  106. if _type == 'rolegrade':
  107. dict_predictor[_type]["predictor"] = RoleGrade()
  108. if _type == 'moneygrade':
  109. dict_predictor[_type]["predictor"] = MoneyGrade()
  110. if _type == 'district':
  111. dict_predictor[_type]["predictor"] = DistrictPredictor()
  112. if _type == 'tableprem':
  113. dict_predictor[_type]["predictor"] = TablePremExtractor()
  114. if _type == 'candidate':
  115. dict_predictor[_type]["predictor"] = CandidateExtractor()
  116. if _type == 'websource_tenderee':
  117. dict_predictor[_type]['predictor'] = WebsourceTenderee()
  118. if _type == 'project_label':
  119. dict_predictor[_type]['predictor'] = ProjectLabel()
  120. if _type == 'pb_extract':
  121. dict_predictor[_type]['predictor'] = PBPredictor()
  122. if _type == 'property_label':
  123. dict_predictor[_type]['predictor'] = PropertyLabel()
  124. if _type == 'approval':
  125. dict_predictor[_type]['predictor'] = ApprovalPredictor()
  126. return dict_predictor[_type]["predictor"]
  127. raise NameError("no this type of predictor")
  128. # 编号名称模型
  129. class CodeNamePredict():
  130. def __init__(self,EMBED_DIM=None,BiRNN_UNITS=None,lazyLoad=getLazyLoad(),config=None):
  131. self.model = None
  132. self.MAX_LEN = None
  133. self.model_code = None
  134. if EMBED_DIM is None:
  135. self.EMBED_DIM = 60
  136. else:
  137. self.EMBED_DIM = EMBED_DIM
  138. if BiRNN_UNITS is None:
  139. self.BiRNN_UNITS = 200
  140. else:
  141. self.BiRNN_UNITS = BiRNN_UNITS
  142. self.filepath = os.path.dirname(__file__)+"/../projectCode/models/model_project_"+str(self.EMBED_DIM)+"_"+str(self.BiRNN_UNITS)+".hdf5"
  143. #self.filepath = "../projectCode/models/model_project_60_200_200ep017-loss6.456-val_loss7.852-val_acc0.969.hdf5"
  144. self.filepath_code = os.path.dirname(__file__)+"/../projectCode/models/model_code.hdf5"
  145. vocabpath = os.path.dirname(__file__)+"/codename_vocab.pk"
  146. classlabelspath = os.path.dirname(__file__)+"/codename_classlabels.pk"
  147. self.vocab = load(vocabpath)
  148. self.class_labels = load(classlabelspath)
  149. #生成提取编号和名称的正则
  150. id_PC_B = self.class_labels.index("PC_B")
  151. id_PC_M = self.class_labels.index("PC_M")
  152. id_PC_E = self.class_labels.index("PC_E")
  153. id_PN_B = self.class_labels.index("PN_B")
  154. id_PN_M = self.class_labels.index("PN_M")
  155. id_PN_E = self.class_labels.index("PN_E")
  156. self.PC_pattern = re.compile(str(id_PC_B)+str(id_PC_M)+"*"+str(id_PC_E))
  157. self.PN_pattern = re.compile(str(id_PN_B)+str(id_PN_M)+"*"+str(id_PN_E))
  158. # print("pc",self.PC_pattern)
  159. # print("pn",self.PN_pattern)
  160. self.word2index = dict((w,i) for i,w in enumerate(np.array(self.vocab)))
  161. self.inputs = None
  162. self.outputs = None
  163. self.sess_codename = tf.Session(graph=tf.Graph(),config=config)
  164. self.sess_codesplit = tf.Session(graph=tf.Graph(),config=config)
  165. self.inputs_code = None
  166. self.outputs_code = None
  167. if not lazyLoad:
  168. self.getModel()
  169. self.getModel_code()
  170. def getModel(self):
  171. '''
  172. @summary: 取得编号和名称模型
  173. '''
  174. if self.inputs is None:
  175. log("get model of codename")
  176. with self.sess_codename.as_default():
  177. with self.sess_codename.graph.as_default():
  178. meta_graph_def = tf.saved_model.loader.load(self.sess_codename, ["serve"], export_dir=os.path.dirname(__file__)+"/codename_savedmodel_tf")
  179. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  180. signature_def = meta_graph_def.signature_def
  181. self.inputs = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].inputs["inputs"].name)
  182. self.inputs_length = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].inputs["inputs_length"].name)
  183. self.keepprob = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].inputs["keepprob"].name)
  184. self.logits = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].outputs["logits"].name)
  185. self.trans = self.sess_codename.graph.get_tensor_by_name(signature_def[signature_key].outputs["trans"].name)
  186. return self.inputs,self.inputs_length,self.keepprob,self.logits,self.trans
  187. else:
  188. return self.inputs,self.inputs_length,self.keepprob,self.logits,self.trans
  189. '''
  190. if self.model is None:
  191. self.model = self.getBiLSTMCRFModel(self.MAX_LEN, self.vocab, self.EMBED_DIM, self.BiRNN_UNITS, self.class_labels,weights=None)
  192. self.model.load_weights(self.filepath)
  193. return self.model
  194. '''
  195. def getModel_code(self):
  196. if self.inputs_code is None:
  197. log("get model of code")
  198. with self.sess_codesplit.as_default():
  199. with self.sess_codesplit.graph.as_default():
  200. meta_graph_def = tf.saved_model.loader.load(self.sess_codesplit, ["serve"], export_dir=os.path.dirname(__file__)+"/codesplit_savedmodel")
  201. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  202. signature_def = meta_graph_def.signature_def
  203. self.inputs_code = []
  204. self.inputs_code.append(self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].inputs["input0"].name))
  205. self.inputs_code.append(self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].inputs["input1"].name))
  206. self.inputs_code.append(self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].inputs["input2"].name))
  207. self.outputs_code = self.sess_codesplit.graph.get_tensor_by_name(signature_def[signature_key].outputs["outputs"].name)
  208. self.sess_codesplit.graph.finalize()
  209. return self.inputs_code,self.outputs_code
  210. else:
  211. return self.inputs_code,self.outputs_code
  212. '''
  213. if self.model_code is None:
  214. log("get model of model_code")
  215. with self.sess_codesplit.as_default():
  216. with self.sess_codesplit.graph.as_default():
  217. self.model_code = models.load_model(self.filepath_code, custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score})
  218. return self.model_code
  219. '''
  220. def getBiLSTMCRFModel(self,MAX_LEN,vocab,EMBED_DIM,BiRNN_UNITS,chunk_tags,weights):
  221. '''
  222. model = models.Sequential()
  223. model.add(layers.Embedding(len(vocab), EMBED_DIM, mask_zero=True)) # Random embedding
  224. model.add(layers.Bidirectional(layers.LSTM(BiRNN_UNITS // 2, return_sequences=True)))
  225. crf = CRF(len(chunk_tags), sparse_target=True)
  226. model.add(crf)
  227. model.summary()
  228. model.compile('adam', loss=crf.loss_function, metrics=[crf.accuracy])
  229. return model
  230. '''
  231. input = layers.Input(shape=(None,))
  232. if weights is not None:
  233. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True,weights=[weights],trainable=True)(input)
  234. else:
  235. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True)(input)
  236. bilstm = layers.Bidirectional(layers.LSTM(BiRNN_UNITS//2,return_sequences=True))(embedding)
  237. bilstm_dense = layers.TimeDistributed(layers.Dense(len(chunk_tags)))(bilstm)
  238. crf = CRF(len(chunk_tags),sparse_target=True)
  239. crf_out = crf(bilstm_dense)
  240. model = models.Model(input=[input],output = [crf_out])
  241. model.summary()
  242. model.compile(optimizer = 'adam', loss = crf.loss_function, metrics = [crf.accuracy])
  243. return model
  244. #根据规则补全编号或名称两边的符号
  245. def fitDataByRule(self,data):
  246. symbol_dict = {"(":")",
  247. "(":")",
  248. "[":"]",
  249. "【":"】",
  250. ")":"(",
  251. ")":"(",
  252. "]":"[",
  253. "】":"【"}
  254. leftSymbol_pattern = re.compile("[\((\[【]")
  255. rightSymbol_pattern = re.compile("[\))\]】]")
  256. leftfinds = re.findall(leftSymbol_pattern,data)
  257. rightfinds = re.findall(rightSymbol_pattern,data)
  258. result = data
  259. if len(leftfinds)+len(rightfinds)==0:
  260. return data
  261. elif len(leftfinds)==len(rightfinds):
  262. return data
  263. elif abs(len(leftfinds)-len(rightfinds))==1:
  264. if len(leftfinds)>len(rightfinds):
  265. if symbol_dict.get(data[0]) is not None:
  266. result = data[1:]
  267. else:
  268. #print(symbol_dict.get(leftfinds[0]))
  269. result = data+symbol_dict.get(leftfinds[0])
  270. else:
  271. if symbol_dict.get(data[-1]) is not None:
  272. result = data[:-1]
  273. else:
  274. result = symbol_dict.get(rightfinds[0])+data
  275. return result
  276. def decode(self,logits, trans, sequence_lengths, tag_num):
  277. viterbi_sequences = []
  278. for logit, length in zip(logits, sequence_lengths):
  279. score = logit[:length]
  280. viterbi_seq, viterbi_score = viterbi_decode(score, trans)
  281. viterbi_sequences.append(viterbi_seq)
  282. return viterbi_sequences
  283. def predict(self,list_sentences,list_entitys=None,MAX_AREA = 5000):
  284. #@summary: 获取每篇文章的code和name
  285. # pattern_score = re.compile("工程|服务|采购|施工|项目|系统|招标|中标|公告|学校|[大中小]学校?|医院|公司|分公司|研究院|政府采购中心|学院|中心校?|办公室|政府|财[政务]局|办事处|委员会|[部总支]队|警卫局|幼儿园|党委|党校|银行|分行|解放军|发电厂|供电局|管理所|供电公司|卷烟厂|机务段|研究[院所]|油厂|调查局|调查中心|出版社|电视台|监狱|水厂|服务站|信用合作联社|信用社|交易所|交易中心|交易中心党校|科学院|测绘所|运输厅|管理处|局|中心|机关|部门?|处|科|厂|集团|图书馆|馆|所|厅|楼|区|酒店|场|基地|矿|餐厅|酒店")
  286. pattern_score = re.compile('建设项目|服务项目|工程项目|工程施工|建设工程|服务中心|基础设施|物业管理|工程设计|妇幼保健|咨询服务|管理系统|管理中心|改建工程|配套工程|公安局|幼儿园|管理局|使用权|办公楼|教育局|管理处|图书馆|经营权|项目|采购|工程|改造|服务|设备|中心|医院|系统|建设|监理|施工|维修|学院|安装|设计|关于|标段|招标|技术|询价|管理|学校|小学|中学|平台|提升|设施|检测|整治|社区|装修|政府|绿化|物资|租赁|地块|医疗|编制|公开|规划|监控|教育|维护|校区|治理|升级|安置|竞价|购置|评估|勘察|承包|实验|大学|材料|生产|耗材|招租|硬化|维保|用地|消防|审计|拍卖|物业|入围|养护|机关|企业|用房|出让|资产|分局|验收|宣传|处置|校园|研究|咨询|修缮|更换|装饰|劳务|保养|物流|出租|局|院')
  287. result = []
  288. index_unk = self.word2index.get("<unk>")
  289. # index_pad = self.word2index.get("<pad>")
  290. if list_entitys is None:
  291. list_entitys = [[] for _ in range(len(list_sentences))]
  292. for list_sentence,list_entity in zip(list_sentences,list_entitys):
  293. if len(list_sentence)==0:
  294. result.append([{"code":[],"name":""}])
  295. continue
  296. doc_id = list_sentence[0].doc_id
  297. # sentences = []
  298. # for sentence in list_sentence:
  299. # if len(sentence.sentence_text)>MAX_AREA:
  300. # for _sentence_comma in re.split("[;;,\n]",sentence):
  301. # _comma_index = 0
  302. # while(_comma_index<len(_sentence_comma)):
  303. # sentences.append(_sentence_comma[_comma_index:_comma_index+MAX_AREA])
  304. # _comma_index += MAX_AREA
  305. # else:
  306. # sentences.append(sentence+"。")
  307. list_sentence.sort(key=lambda x:len(x.sentence_text),reverse=True)
  308. _begin_index = 0
  309. item = {"code":[],"name":""}
  310. code_set = set()
  311. dict_name_freq_score = dict()
  312. while(True):
  313. MAX_LEN = len(list_sentence[_begin_index].sentence_text)
  314. if MAX_LEN>MAX_AREA:
  315. MAX_LEN = MAX_AREA
  316. _LEN = MAX_AREA//MAX_LEN
  317. #预测
  318. 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]]
  319. # x = [[getIndexOfWord(word) for word in sentence.sentence_text[:MAX_AREA]]for sentence in list_sentence[_begin_index:_begin_index+_LEN]]
  320. x_len = [len(_x) if len(_x) < MAX_LEN else MAX_LEN for _x in x]
  321. x = pad_sequences(x,maxlen=MAX_LEN,padding="post",truncating="post")
  322. if USE_API:
  323. requests_result = requests.post(API_URL + "/predict_codeName", json={"inouts": x.tolist(), "inouts_len": x_len},verify=True)
  324. predict_y = json.loads(requests_result.text)['result']
  325. # print("cost_time:", json.loads(requests_result.text)['cost_time'])
  326. # print(MAX_LEN,_LEN,_begin_index)
  327. else:
  328. with self.sess_codename.as_default():
  329. t_input,t_input_length,t_keepprob,t_logits,t_trans = self.getModel()
  330. _logits,_trans = self.sess_codename.run([t_logits,t_trans],feed_dict={t_input:x,
  331. t_input_length:x_len,
  332. t_keepprob:1.0})
  333. predict_y = self.decode(_logits,_trans,x_len,7)
  334. # print('==========',_logits)
  335. '''
  336. for item11 in np.argmax(predict_y,-1):
  337. print(item11)
  338. print(predict_y)
  339. '''
  340. # print(predict_y)
  341. for sentence,predict in zip(list_sentence[_begin_index:_begin_index+_LEN],np.array(predict_y)):
  342. pad_sentence = sentence.sentence_text[:MAX_LEN]
  343. join_predict = "".join([str(s) for s in predict])
  344. # print(pad_sentence)
  345. # print(join_predict)
  346. code_x = []
  347. code_text = []
  348. pre_text = []
  349. temp_entitys = []
  350. for iter in re.finditer(self.PC_pattern,join_predict):
  351. get_len = 40
  352. if iter.span()[0]<get_len:
  353. begin = 0
  354. else:
  355. begin = iter.span()[0]-get_len
  356. end = iter.span()[1]+get_len
  357. 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)))
  358. code_text.append(pad_sentence[iter.span()[0]:iter.span()[1]].replace(",", ""))
  359. pre_text.append(pad_sentence[begin:iter.span()[0]])
  360. _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)
  361. temp_entitys.append(_entity)
  362. #print("code",code_text)
  363. if len(code_x)>0:
  364. code_x = np.transpose(np.array(code_x,dtype=np.float32),(1,0,2,3))
  365. if USE_PAI_EAS:
  366. request = tf_predict_pb2.PredictRequest()
  367. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  368. request.inputs["input0"].array_shape.dim.extend(np.shape(code_x[0]))
  369. request.inputs["input0"].float_val.extend(np.array(code_x[0],dtype=np.float64).reshape(-1))
  370. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  371. request.inputs["input1"].array_shape.dim.extend(np.shape(code_x[1]))
  372. request.inputs["input1"].float_val.extend(np.array(code_x[1],dtype=np.float64).reshape(-1))
  373. request.inputs["input2"].dtype = tf_predict_pb2.DT_FLOAT
  374. request.inputs["input2"].array_shape.dim.extend(np.shape(code_x[2]))
  375. request.inputs["input2"].float_val.extend(np.array(code_x[2],dtype=np.float64).reshape(-1))
  376. request_data = request.SerializeToString()
  377. list_outputs = ["outputs"]
  378. _result = vpc_requests(codeclasses_url, codeclasses_authorization, request_data, list_outputs)
  379. if _result is not None:
  380. predict_code = _result["outputs"]
  381. else:
  382. with self.sess_codesplit.as_default():
  383. with self.sess_codesplit.graph.as_default():
  384. predict_code = self.getModel_code().predict([code_x[0],code_x[1],code_x[2]])
  385. else:
  386. with self.sess_codesplit.as_default():
  387. with self.sess_codesplit.graph.as_default():
  388. inputs_code,outputs_code = self.getModel_code()
  389. 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]
  390. #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]})
  391. #predict_code = self.getModel_code().predict([code_x[0],code_x[1],code_x[2]])
  392. for h in range(len(predict_code)):
  393. if predict_code[h][0]>0.5:
  394. the_code = self.fitDataByRule(code_text[h])
  395. # print(the_code)
  396. #add code to entitys
  397. list_entity.append(temp_entitys[h])
  398. if re.search(',|/|;|、|,', the_code) and len(the_code)>25:
  399. for it in re.split(',|/|;|、|,', the_code):
  400. if len(it) > 8:
  401. if it not in code_set:
  402. code_set.add(it)
  403. # item['code'].append(it)
  404. if re.search("(项目编号|招标编号):?$", pre_text[h]):
  405. item['code'].append((it, 0, sentence.sentence_index))
  406. elif re.search('采购(计划)?编号:?$', pre_text[h]):
  407. item['code'].append((it, 1, sentence.sentence_index))
  408. elif re.search('(询价|合同)编号:?$', pre_text[h]):
  409. item['code'].append((it, 2, sentence.sentence_index))
  410. else:
  411. item['code'].append((it, 3, sentence.sentence_index))
  412. elif len(item['code']) > 0:
  413. new_it = item['code'][-1][0] + re.search(',|/|;|、|,', the_code).group(0) + it
  414. if new_it not in code_set:
  415. code_set.add(new_it)
  416. # item['code'][-1] = new_it
  417. if re.search("(项目编号|招标编号):?$", pre_text[h]):
  418. item['code'][-1] = (new_it, 0, sentence.sentence_index)
  419. elif re.search('采购(计划)?编号:?$', pre_text[h]):
  420. item['code'][-1] = (new_it, 1, sentence.sentence_index)
  421. elif re.search('(询价|合同)编号:?$', pre_text[h]):
  422. item['code'][-1] = (new_it, 2, sentence.sentence_index)
  423. else:
  424. item['code'][-1] = (new_it, 3, sentence.sentence_index)
  425. else:
  426. if the_code not in code_set:
  427. code_set.add(the_code)
  428. # item['code'].append(the_code)
  429. if re.search("(项目编号|招标编号):?$", pre_text[h]):
  430. item['code'].append((the_code, 0, sentence.sentence_index))
  431. elif re.search('采购(计划)?编号:?$', pre_text[h]):
  432. item['code'].append((the_code, 1, sentence.sentence_index))
  433. elif re.search('(询价|合同)编号:?$', pre_text[h]):
  434. item['code'].append((the_code, 2, sentence.sentence_index))
  435. else:
  436. item['code'].append((the_code, 3, sentence.sentence_index))
  437. break
  438. elif the_code not in code_set:
  439. code_set.add(the_code)
  440. # item['code'].append(the_code)
  441. if re.search("(项目编号|招标编号):?$", pre_text[h]):
  442. item['code'].append((the_code, 0, sentence.sentence_index))
  443. elif re.search('采购(计划)?编号:?$', pre_text[h]):
  444. item['code'].append((the_code, 1, sentence.sentence_index))
  445. elif re.search('(询价|合同)编号:?$', pre_text[h]):
  446. item['code'].append((the_code, 2, sentence.sentence_index))
  447. else:
  448. item['code'].append((the_code, 3, sentence.sentence_index))
  449. # if the_code not in code_set:
  450. # code_set.add(the_code)
  451. # item['code'] = list(code_set)
  452. for iter in re.finditer(self.PN_pattern,join_predict):
  453. _name = self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  454. if len(_name)>200: # 避免模型预测类似 202750503 这种很长重复字很多的错误项目名称
  455. continue
  456. elif '公司:你单位在' in _name: # 避免类似 339900030 这种作为项目名称,导致中标角色作为招标角色
  457. continue
  458. #add name to entitys
  459. _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)
  460. list_entity.append(_entity)
  461. # w = 1 if re.search('(项目|工程|招标|合同|标项|标的|计划|询价|询价单|询价通知书|申购)(名称|标题|主题)[::\s]', pad_sentence[iter.span()[0]-10:iter.span()[0]])!=None else 0.5
  462. w = 1 if re.search('(项目|工程|招标|采购|合同|标项|标的|计划|询价|询价单|询价通知书|申购)(名称|标题|主题|项目)[::\s]', pad_sentence[iter.span()[0]-10:iter.span()[0]])!=None else 0.5
  463. if _name not in dict_name_freq_score:
  464. # dict_name_freq_score[_name] = [1,len(re.findall(pattern_score,_name))+len(_name)*0.1]
  465. len_name = len(_name) if len(_name) <50 else 100-len(_name) # 2023/03/02 超出50长度的逐渐递减
  466. dict_name_freq_score[_name] = [1, (len(re.findall(pattern_score, _name)) + len_name * 0.05)*w+(5-sentence.sentence_index)*0.2]
  467. else:
  468. dict_name_freq_score[_name][0] += 1
  469. '''
  470. for iter in re.finditer(self.PN_pattern,join_predict):
  471. print("name-",self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]]))
  472. if item[1]['name']=="":
  473. for iter in re.finditer(self.PN_pattern,join_predict):
  474. #item[1]['name']=item[1]['name']+";"+self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  475. item[1]['name']=self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  476. break
  477. '''
  478. if _begin_index+_LEN>=len(list_sentence):
  479. break
  480. _begin_index += _LEN
  481. list_name_freq_score = []
  482. # print('模型预测项目名称:', dict_name_freq_score)
  483. # 2020/11/23 大网站规则调整
  484. if len(dict_name_freq_score) == 0:
  485. # name_re1 = '(项目|工程|招标|合同|标项|标的|计划|询价|询价单|询价通知书|申购)(名称|标题|主题)[::\s]+([^,。:;]{2,60})[,。]'
  486. name_re1 = '(项目|工程|招标|采购(条目)?|合同|标项|标的|计划|询价|询价单|询价通知书|申购单|申购)(名称|标名|标题|主题)[::\s]+(?P<name>[^,。:;]{2,60})[,。]'
  487. for sentence in list_sentence:
  488. # pad_sentence = sentence.sentence_text
  489. othername = re.search(name_re1, sentence.sentence_text)
  490. if othername != None:
  491. project_name = othername.group('name')
  492. if re.search('[\u4e00-\u9fa5]+', project_name) == None: # 没有中文的项目名称去除
  493. # log('没有中文的项目名称去除')
  494. continue
  495. beg = find_index([project_name], sentence.sentence_text)[0]
  496. end = beg + len(project_name)
  497. _name = self.fitDataByRule(sentence.sentence_text[beg:end])
  498. # print('规则召回项目名称:', _name)
  499. # add name to entitys
  500. _entity = Entity(doc_id=sentence.doc_id, entity_id="%s_%s_%s_%s" % (
  501. sentence.doc_id, sentence.sentence_index, beg, end), entity_text=_name,
  502. entity_type="name", sentence_index=sentence.sentence_index, begin_index=0,
  503. end_index=0, wordOffset_begin=beg, wordOffset_end=end,in_attachment=sentence.in_attachment)
  504. list_entity.append(_entity)
  505. w = 1
  506. if _name not in dict_name_freq_score:
  507. # dict_name_freq_score[_name] = [1,len(re.findall(pattern_score,_name))+len(_name)*0.1]
  508. dict_name_freq_score[_name] = [1, (len(re.findall(pattern_score, _name)) + len(_name) * 0.05) * w+(5-sentence.sentence_index)*0.2]
  509. else:
  510. dict_name_freq_score[_name][0] += 1
  511. # othername = re.search(name_re1, sentence.sentence_text)
  512. # if othername != None:
  513. # _name = othername.group(3)
  514. # if _name not in dict_name_freq_score:
  515. # dict_name_freq_score[_name] = [1, len(re.findall(pattern_score, _name)) + len(_name) * 0.1]
  516. # else:
  517. # dict_name_freq_score[_name][0] += 1
  518. for _name in dict_name_freq_score.keys():
  519. list_name_freq_score.append([_name,dict_name_freq_score[_name]])
  520. # print(list_name_freq_score)
  521. if len(list_name_freq_score)>0:
  522. list_name_freq_score.sort(key=lambda x:x[1][0]*x[1][1],reverse=True)
  523. item['name'] = list_name_freq_score[0][0]
  524. # for it in list_name_freq_score:
  525. # print('项目名称及分值:',it[0],it[1], it[1][0]*it[1][1])
  526. # if list_name_freq_score[0][1][0]>1:
  527. # item[1]['name'] = list_name_freq_score[0][0]
  528. # else:
  529. # list_name_freq_score.sort(key=lambda x:x[1][1],reverse=True)
  530. # item[1]["name"] = list_name_freq_score[0][0]
  531. #下面代码加上去用正则添加某些识别不到的项目编号
  532. if item['code'] == []:
  533. for sentence in list_sentence:
  534. # othercode = re.search('(采购计划编号|询价编号)[\))]?[::]?([\[\]a-zA-Z0-9\-]{5,30})', sentence.sentence_text)
  535. # if othercode != None:
  536. # item[1]['code'].append(othercode.group(2))
  537. # 2020/11/23 大网站规则调整
  538. othercode = re.search('(项目|采购|招标|品目|询价|竞价|询价[单书]|磋商|订单|账单|交易|文件|计划|场次|标的|标段|标包|分包|标段\(包\)|招标文件|合同|通知书|公告|工程|寻源|标书|包件|谈判|申购)(单据?号|编号|标号|编码|代码|备案号|号)[::\s]+(?P<code>[^,。;:、]{8,30}[a-zA-Z0-9\号])[\),。\u4e00-\u9fa5]', sentence.sentence_text)
  539. if othercode != None:
  540. # item['code'].append(othercode.group('code'))
  541. if re.search("(项目编号|招标编号):?$", othercode.group(0)):
  542. item['code'].append((othercode.group('code'), 0, sentence.sentence_index))
  543. elif re.search('采购(计划)?编号:?$', othercode.group(0)):
  544. item['code'].append((othercode.group('code'), 1, sentence.sentence_index))
  545. elif re.search('(询价|合同)编号:?$', othercode.group(0)):
  546. item['code'].append((othercode.group('code'), 2, sentence.sentence_index))
  547. else:
  548. item['code'].append((othercode.group('code'), 3, sentence.sentence_index))
  549. # print('规则召回项目编号:', othercode.group('code'))
  550. # item['code'] = [code for code in item['code'] if len(code)<500]
  551. # item['code'].sort(key=lambda x:len(x),reverse=True)
  552. item['code'] = [code for code in item['code'] if len(code[0]) < 500]
  553. item['code'].sort(key=lambda x: [x[1],x[2]])
  554. item['code'] = [it[0] for it in item['code']]
  555. result.append(item)
  556. list_sentence.sort(key=lambda x: x.sentence_index,reverse=False)
  557. return result
  558. '''
  559. #当数据量过大时会报错
  560. def predict(self,articles,MAX_LEN = None):
  561. sentences = []
  562. for article in articles:
  563. for sentence in article.content.split("。"):
  564. sentences.append([sentence,article.id])
  565. if MAX_LEN is None:
  566. sent_len = [len(sentence[0]) for sentence in sentences]
  567. MAX_LEN = max(sent_len)
  568. #print(MAX_LEN)
  569. #若为空,则直接返回空
  570. result = []
  571. if MAX_LEN==0:
  572. for article in articles:
  573. result.append([article.id,{"code":[],"name":""}])
  574. return result
  575. index_unk = self.word2index.get("<unk>")
  576. index_pad = self.word2index.get("<pad>")
  577. x = [[self.word2index.get(word,index_unk)for word in sentence[0]]for sentence in sentences]
  578. x = pad_sequences(x,maxlen=MAX_LEN,padding="post",truncating="post")
  579. predict_y = self.getModel().predict(x)
  580. last_doc_id = ""
  581. item = []
  582. for sentence,predict in zip(sentences,np.argmax(predict_y,-1)):
  583. pad_sentence = sentence[0][:MAX_LEN]
  584. doc_id = sentence[1]
  585. join_predict = "".join([str(s) for s in predict])
  586. if doc_id!=last_doc_id:
  587. if last_doc_id!="":
  588. result.append(item)
  589. item = [doc_id,{"code":[],"name":""}]
  590. code_set = set()
  591. code_x = []
  592. code_text = []
  593. for iter in re.finditer(self.PC_pattern,join_predict):
  594. get_len = 40
  595. if iter.span()[0]<get_len:
  596. begin = 0
  597. else:
  598. begin = iter.span()[0]-get_len
  599. end = iter.span()[1]+get_len
  600. 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)))
  601. code_text.append(pad_sentence[iter.span()[0]:iter.span()[1]])
  602. if len(code_x)>0:
  603. code_x = np.transpose(np.array(code_x),(1,0,2,3))
  604. predict_code = self.getModel_code().predict([code_x[0],code_x[1],code_x[2]])
  605. for h in range(len(predict_code)):
  606. if predict_code[h][0]>0.5:
  607. the_code = self.fitDataByRule(code_text[h])
  608. if the_code not in code_set:
  609. code_set.add(the_code)
  610. item[1]['code'] = list(code_set)
  611. if item[1]['name']=="":
  612. for iter in re.finditer(self.PN_pattern,join_predict):
  613. #item[1]['name']=item[1]['name']+";"+self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  614. item[1]['name']=self.fitDataByRule(pad_sentence[iter.span()[0]:iter.span()[1]])
  615. break
  616. last_doc_id = doc_id
  617. result.append(item)
  618. return result
  619. '''
  620. #角色金额模型
  621. class PREMPredict():
  622. def __init__(self,config=None):
  623. #self.model_role_file = os.path.abspath("../role/models/model_role.model.hdf5")
  624. # self.model_role_file = os.path.dirname(__file__)+"/../role/log/new_biLSTM-ep012-loss0.028-val_loss0.040-f10.954.h5"
  625. self.model_role = Model_role_classify_word(config=config)
  626. self.model_money = Model_money_classify(config=config)
  627. # self.role_file = open('/data/python/lsm/role_model_predict.txt', 'a', encoding='utf-8')
  628. # self.money_file = open('/data/python/lsm/money_model_predict.txt', 'a', encoding='utf-8')
  629. return
  630. def search_role_data(self,list_sentences,list_entitys):
  631. '''
  632. @summary:根据句子list和实体list查询角色模型的输入数据
  633. @param:
  634. list_sentences:文章的sentences
  635. list_entitys:文章的entitys
  636. @return:角色模型的输入数据
  637. '''
  638. text_list = []
  639. data_x = []
  640. points_entitys = []
  641. for list_entity,list_sentence in zip(list_entitys,list_sentences):
  642. list_entity.sort(key=lambda x:x.sentence_index)
  643. list_sentence.sort(key=lambda x:x.sentence_index)
  644. p_entitys = 0
  645. p_sentences = 0
  646. while(p_entitys<len(list_entity)):
  647. entity = list_entity[p_entitys]
  648. if entity.entity_type in ['org','company']:
  649. while(p_sentences<len(list_sentence)):
  650. sentence = list_sentence[p_sentences]
  651. if entity.doc_id==sentence.doc_id and entity.sentence_index==sentence.sentence_index:
  652. # text_list.append(sentence.sentence_text[max(0, entity.wordOffset_begin-13):entity.wordOffset_end+10])
  653. text_sen = sentence.sentence_text
  654. b = entity.wordOffset_begin
  655. e = entity.wordOffset_end
  656. text_list.append((text_sen[max(0, b-13):b], text_sen[b:e], text_sen[e:e+15]))
  657. # 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)
  658. # item_x = self.model_role.encode(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,entity_text=entity.entity_text)
  659. item_x = self.model_role.encode_word(sentence_text=text_sen, begin_index=entity.wordOffset_begin, end_index=entity.wordOffset_end, size=30)
  660. data_x.append(item_x)
  661. points_entitys.append(entity)
  662. break
  663. p_sentences += 1
  664. p_entitys += 1
  665. if len(points_entitys)==0:
  666. return None
  667. return [data_x,points_entitys, text_list]
  668. def search_money_data(self,list_sentences,list_entitys):
  669. '''
  670. @summary:根据句子list和实体list查询金额模型的输入数据
  671. @param:
  672. list_sentences:文章的sentences
  673. list_entitys:文章的entitys
  674. @return:金额模型的输入数据
  675. '''
  676. text_list = []
  677. data_x = []
  678. points_entitys = []
  679. for list_entity,list_sentence in zip(list_entitys,list_sentences):
  680. list_entity.sort(key=lambda x:x.sentence_index)
  681. list_sentence.sort(key=lambda x:x.sentence_index)
  682. p_entitys = 0
  683. while(p_entitys<len(list_entity)):
  684. entity = list_entity[p_entitys]
  685. if entity.entity_type=="money":
  686. p_sentences = 0
  687. while(p_sentences<len(list_sentence)):
  688. sentence = list_sentence[p_sentences]
  689. if entity.doc_id==sentence.doc_id and entity.sentence_index==sentence.sentence_index:
  690. # text_list.append(sentence.sentence_text[max(0, entity.wordOffset_begin - 13):entity.wordOffset_begin])
  691. text_sen = sentence.sentence_text
  692. b = entity.wordOffset_begin
  693. e = entity.wordOffset_end
  694. text_list.append((text_sen[max(0, b - 13):b], text_sen[b:e], text_sen[e:e + 10]))
  695. #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)
  696. #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)
  697. item_x = self.model_money.encode(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index)
  698. data_x.append(item_x)
  699. points_entitys.append(entity)
  700. break
  701. p_sentences += 1
  702. p_entitys += 1
  703. if len(points_entitys)==0:
  704. return None
  705. return [data_x,points_entitys, text_list]
  706. def predict_role(self,list_sentences, list_entitys):
  707. datas = self.search_role_data(list_sentences, list_entitys)
  708. if datas is None:
  709. return
  710. points_entitys = datas[1]
  711. text_list = datas[2]
  712. if USE_PAI_EAS:
  713. _data = datas[0]
  714. _data = np.transpose(np.array(_data),(1,0,2))
  715. request = tf_predict_pb2.PredictRequest()
  716. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  717. request.inputs["input0"].array_shape.dim.extend(np.shape(_data[0]))
  718. request.inputs["input0"].float_val.extend(np.array(_data[0],dtype=np.float64).reshape(-1))
  719. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  720. request.inputs["input1"].array_shape.dim.extend(np.shape(_data[1]))
  721. request.inputs["input1"].float_val.extend(np.array(_data[1],dtype=np.float64).reshape(-1))
  722. request.inputs["input2"].dtype = tf_predict_pb2.DT_FLOAT
  723. request.inputs["input2"].array_shape.dim.extend(np.shape(_data[2]))
  724. request.inputs["input2"].float_val.extend(np.array(_data[2],dtype=np.float64).reshape(-1))
  725. request_data = request.SerializeToString()
  726. list_outputs = ["outputs"]
  727. _result = vpc_requests(role_url, role_authorization, request_data, list_outputs)
  728. if _result is not None:
  729. predict_y = _result["outputs"]
  730. else:
  731. predict_y = self.model_role.predict(datas[0])
  732. else:
  733. predict_y = self.model_role.predict(np.array(datas[0],dtype=np.float64))
  734. for i in range(len(predict_y)):
  735. entity = points_entitys[i]
  736. label = np.argmax(predict_y[i])
  737. values = predict_y[i]
  738. # text = text_list[i]
  739. text_tup = text_list[i]
  740. front, middle, behind = text_tup
  741. whole = "".join(text_tup)
  742. # print('模型预测角色:', front, entity.entity_text, behind,label, values)
  743. # if label in [0, 1, 2, 3, 4]:
  744. # self.role_file.write("{0}#split#{1}#split#{2}#split#{3}#split#{4}\n".format(front, entity.entity_text, behind,label, entity.doc_id))
  745. if re.search('^以\d+[\d,.]+万?元中标', behind) and label != 2: # 优化244261884预测错误 大连长之琳科技发展有限公司以7.63277万元中标
  746. label = 2
  747. values[label] = 0.8
  748. if label in [0, 1, 2, 3, 4] and values[label] < 0.5: # 小于阈值的设为其他,让后面的规则召回重新判断
  749. # print(' # 小于阈值的设为其他,让后面的规则召回重新判断', values[label])
  750. label = 5
  751. elif label in [2,3,4] and re.search('序号:\d+,\w{,2}候选', front):
  752. label = 5
  753. elif label == 0:
  754. if re.search('拟邀请$|受邀谈判方', front):
  755. label = 2
  756. values[label] = 0.501
  757. elif re.search('(发布(人|方|单位|机构|组织|用户|业主|主体|部门|公司|企业)|组织(单位|人|方|机构)?|(采购|招标|发布)机构)(名称)?[是为:]+', front) and is_agency(entity.entity_text):
  758. label = 1
  759. values[label] = 0.501
  760. elif re.search('受托人((盖章))?:$', front):
  761. label = 1
  762. values[label] = 0.501
  763. elif re.search('采用$|异议受理部门|本次招标有:$|直购企业:$', front): # 368177736 因本项目招标采用广西壮族自治区公共资源交易平台系统- 标公告,本次招标有:内黄县汇融钢材有限公司、安阳正元建筑工程有限公司、内黄县鸿业贸易有限责任公司三家合格供应商进行报名投标。 438880541 直购企业可能为多个,其中一个中标
  764. label = 5
  765. elif re.search(',单位名称:$', front) and re.search('^,(中标|中选)价格', behind):
  766. label = 2
  767. values[label] = 0.501
  768. elif label == 2:
  769. if re.search('中标单位和.{,25}签订合同', whole):
  770. label = 0
  771. values[label] = 0.501
  772. elif re.search('尊敬的供应商:.{,25}我公司', whole):
  773. label = 0
  774. values[label] = 0.801
  775. elif re.search('尊敬的供应商:$', front):
  776. label = 0
  777. values[label] = 0.501
  778. elif re.search('第[4-9四五六]中标候选人|(提交单位|竞投单位):$', front): #修复第4以上的预测错为中标人
  779. label = 5
  780. values[label] = 0.5
  781. elif re.search('(排名|排序|名次):([4-9]|\d{2,}),', front) or re.search('序号:\d+,(供应商|投标|候选)', front): # 293225236 附件中 排名预测错误
  782. values[2] = 0.5
  783. label = 5
  784. elif re.search('税费', front) and re.search('^承担', behind):
  785. label = 5
  786. elif re.search('第一候补|第一后备|备选', front):
  787. label = 3
  788. values[label] = 0.6
  789. elif re.search('^放弃中标资格|是否中标:否|^(中标|成交)(公示|公告)', behind):
  790. values[2] = 0.5
  791. label = 5
  792. elif re.search('^,?(投标报价|(资格性审查:|符合性审查:)?(不通过|不符合))', behind) and re.search('中标|成交|中选|排名|排序|名次|第[一1]名', front)==None:
  793. values[2] = 0.5
  794. label = 5
  795. elif re.search('(承包权人|帐户名称|债务人|推荐预审合格投标人名单):$|确定为标的的受让方,$|[主次出]入口?,?$|确定(项目|\w{,2})成交供应商,$', front): # 234501112 民币元,序号:1,债务人: 东营市海宁工贸有限责任公司 ,债权本金: 262414286 八、中标后签约单位,合同签约单位:
  796. label = 5
  797. elif re.search(',来源:$', front) and re.search('^,', behind): # 修复 472062585 项目采购-关于定制手机询比价采购中标公告,来源:深圳市网联安瑞网络科技有限公司 预测为中标
  798. label = 0
  799. values[label] = 0.5
  800. elif re.search('合同供方:?$|合同签约单位', front):
  801. label = 0
  802. values[label] = 0.5
  803. elif re.search('现由$', front) and re.search('^作为\d个单位的牵头(单位|公司)?', behind): # 修复 469369884 站源批量预测错误 现由第七合同段保利长大工程有限公司作为6个单位的牵头单位,
  804. label = 5
  805. elif re.search('是否中标:是,供应商', front) and label == 5:
  806. label = 2
  807. values[label] = 0.9
  808. elif label == 1:
  809. if re.search('委托(单位|人|方)[是为:]+',front) and re.search('受委托(单位|人|方)[是为:]+', front)==None:
  810. label = 0
  811. values[label] = 0.501
  812. elif re.search('([,。:]|^)(第一)?(服务|中选|中标)(中介服务|代理)?(公司|机构)(名称)?', front):
  813. label = 2
  814. values[label] = 0.501
  815. elif re.search('在中介超市委托$', front) and re.search('^负责', behind):
  816. label = 2
  817. values[label] = 0.501
  818. elif re.search('^:受', behind): # 354009560 附件格式问题 ,中选中介服务机构通知书,编号:HZ2305120541,中汕项目管理有限公司:受惠东县人民政府大岭街道办事处委托
  819. label = 5
  820. elif re.search('发布机构', front) and not is_agency(entity.entity_text):
  821. label = 0
  822. values[label] = 0.501
  823. elif re.search('开户银行:$|环境影响评价机构|环评机构|评价机构', front): # 368214232 法定代表人:委托代理人:开户银行:鸡东建行
  824. label = 5
  825. elif re.search('委托$', front) and re.search('^(抽样|送检|看样)', behind):
  826. label = 5
  827. elif re.search('推荐入围的招标代理单位:$', front): # 20240709 修复302505502预测错为代理
  828. label = 2
  829. values[label] = 0.501
  830. elif label in [3,4]:
  831. if re.search('第[二三]分(公司|店),中标(人|供应商|单位|公司):$', front):
  832. label = 2
  833. values[label] = 0.7
  834. elif re.search('决定选择第[二三]名', front) and re.search('^作为(中标|成交)(人|供应商|单位|公司)', behind):
  835. label = 2
  836. values[label] = 0.8
  837. elif re.search('\d+\.\d+,供应商名称:', front): # 341385226 30.2,供应商名称: 预测为第二名
  838. label = 2
  839. values[label] = 0.501
  840. elif re.search('\d+\.\d+[,、]?(中标|成交)候选人|[;,][23]、(中标|中选|成交)候选人:', front):
  841. label = 5
  842. values[label] = 0.501
  843. elif re.search('第一名:$', front):
  844. label = 2
  845. values[label] = 0.7
  846. elif re.search('(中标|成交)通知书[,:]$', front) and re.search('^:', behind) and label != 2:
  847. label = 2
  848. values[label] = 0.8
  849. elif label==5 and re.search('^拟(招标|采购)一批|^须购置一批', front):
  850. label = 0
  851. values[label] = 0.7
  852. entity.set_Role(label, values)
  853. def predict_money(self,list_sentences,list_entitys):
  854. datas = self.search_money_data(list_sentences, list_entitys)
  855. if datas is None:
  856. return
  857. points_entitys = datas[1]
  858. _data = datas[0]
  859. text_list = datas[2]
  860. if USE_PAI_EAS:
  861. _data = np.transpose(np.array(_data),(1,0,2,3))
  862. request = tf_predict_pb2.PredictRequest()
  863. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  864. request.inputs["input0"].array_shape.dim.extend(np.shape(_data[0]))
  865. request.inputs["input0"].float_val.extend(np.array(_data[0],dtype=np.float64).reshape(-1))
  866. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  867. request.inputs["input1"].array_shape.dim.extend(np.shape(_data[1]))
  868. request.inputs["input1"].float_val.extend(np.array(_data[1],dtype=np.float64).reshape(-1))
  869. request.inputs["input2"].dtype = tf_predict_pb2.DT_FLOAT
  870. request.inputs["input2"].array_shape.dim.extend(np.shape(_data[2]))
  871. request.inputs["input2"].float_val.extend(np.array(_data[2],dtype=np.float64).reshape(-1))
  872. request_data = request.SerializeToString()
  873. list_outputs = ["outputs"]
  874. _result = vpc_requests(money_url, money_authorization, request_data, list_outputs)
  875. if _result is not None:
  876. predict_y = _result["outputs"]
  877. else:
  878. predict_y = self.model_money.predict(_data)
  879. else:
  880. predict_y = self.model_money.predict(_data)
  881. for i in range(len(predict_y)):
  882. entity = points_entitys[i]
  883. label = np.argmax(predict_y[i])
  884. values = predict_y[i]
  885. # text = text_list[i]
  886. text_tup = text_list[i]
  887. front, middle, behind = text_tup
  888. whole = "".join(text_tup)
  889. # print('金额: ', entity.entity_text, label, values, front, middle, behind)
  890. # if label in [0, 1]:
  891. # self.money_file.write("{0} {1} {2} {3}\n".format(front, entity.entity_text, behind, label))
  892. if label in [0, 1] and values[label] < 0.5: # 小于阈值的设为其他金额,让后面的规则召回重新判断
  893. # print('模型预测金额: ', entity.entity_text, label, values, front, middle, behind)
  894. label = 2
  895. elif label == 1: # 错误中标金额处理
  896. if re.search('[::,。](总金额|总价|单价|合价)((万?元))?:?$', front) and re.search('(中标|投标|成交|中价)', front)==None:
  897. values[label] = 0.5
  898. elif re.search('[\+=]((中标|成交)(金?额|价格?)|[若如]果?(中标|成交)(金?额|价格?)为?', front): # 处理例如 241561780 如中标金额为 500-1000万元,则代理服务费=100 万元×0.5%+400万元×0.35%+(中标金额-500)万元
  899. values[label] = 0.49
  900. elif re.search('^(以[上下])?按[\d.%]+收取|^及?以[上下]|^[()]?[+×*-][\d.%]+', behind):
  901. values[label] = 0.49
  902. elif re.search('(含|在|包括|[大小等高低]于|达到)$|[\d.%]+[+×*-]$', front):
  903. values[label] = 0.49
  904. elif entity.notes == '单价' and float(entity.entity_text)<5000:
  905. label = 2
  906. elif label ==0: # 错误招标金额处理
  907. if entity.notes in ["投资", "总投资","工程造价"] or re.search('最低限价:?$|注册资本', front) or re.search('服务内容:([\d,.]+万?亿?元?-?)$', front):
  908. values[label] = 0.49
  909. elif re.search('^(以[上下])?按[\d.%]+收取|^及?以[上下]|^[()]?[+×*-][\d.%]+|(含)', behind):
  910. values[label] = 0.49
  911. elif re.search('(含|在|包括|[大小等高低]于|如预算金额为)$|[\d.%]+((含))?[+×*-]$', front):
  912. values[label] = 0.49
  913. elif entity.notes == '单价' and float(entity.entity_text)<5000:
  914. label = 2
  915. elif re.search('报价:预估不?含税总价[为:]$', front) and (label != 1 or values[label]<0.5):
  916. label = 1
  917. values[label] = 0.8
  918. entity.set_Money(label, values)
  919. def correct_money_by_rule(self, title, list_entitys, list_articles):
  920. if (len(re.findall('监理|施工|设计|勘察', title)) == 1 and re.search('施工|总承包|epc|EPC', title) == None) or re.search('服务金额', list_articles[0].content):
  921. # keyword = re.search('监理|设计|勘察', title).group(0)
  922. for list_entity in list_entitys:
  923. for _entity in list_entity:
  924. # print('keyword:',keyword, '_entity.notes :',_entity.notes)
  925. # if _entity.entity_type == "money" and _entity.notes == keyword and _entity.label == 2:
  926. if _entity.entity_type == "money" and _entity.notes == '招标或中标金额' and _entity.label == 2:
  927. # if channel_dic['docchannel'] == "招标公告":
  928. if re.search('中标|成交|中选|中价|中租|结果|入围', title + list_articles[0].content[:100]) == None:
  929. _entity.values[0] = 0.51
  930. _entity.set_Money(0, _entity.values) # 2021/11/18 根据公告类别把费用改为招标或中投标金额
  931. else:
  932. _entity.values[1] = 0.51
  933. _entity.set_Money(1, _entity.values)
  934. def predict(self,list_sentences,list_entitys):
  935. self.predict_role(list_sentences,list_entitys)
  936. self.predict_money(list_sentences,list_entitys)
  937. #联系人模型
  938. class EPCPredict():
  939. def __init__(self,config=None):
  940. self.model_person = Model_person_classify(config=config)
  941. def search_person_data(self,list_sentences,list_entitys):
  942. '''
  943. @summary:根据句子list和实体list查询联系人模型的输入数据
  944. @param:
  945. list_sentences:文章的sentences
  946. list_entitys:文章的entitys
  947. @return:联系人模型的输入数据
  948. '''
  949. data_x = []
  950. points_entitys = []
  951. pre_texts = []
  952. for list_entity,list_sentence in zip(list_entitys,list_sentences):
  953. p_entitys = 0
  954. dict_index_sentence = {}
  955. for _sentence in list_sentence:
  956. dict_index_sentence[_sentence.sentence_index] = _sentence
  957. _list_entity = [entity for entity in list_entity if entity.entity_type=="person"]
  958. while(p_entitys<len(_list_entity)):
  959. entity = _list_entity[p_entitys]
  960. if entity.entity_type=="person":
  961. sentence = dict_index_sentence[entity.sentence_index]
  962. item_x = self.model_person.encode(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index)
  963. data_x.append(item_x)
  964. points_entitys.append(entity)
  965. pre_texts.append(spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=20))
  966. p_entitys += 1
  967. if len(points_entitys)==0:
  968. return None
  969. # return [data_x,points_entitys,dianhua]
  970. return [data_x,points_entitys, pre_texts]
  971. def predict_person(self,list_sentences, list_entitys):
  972. datas = self.search_person_data(list_sentences, list_entitys)
  973. if datas is None:
  974. return
  975. points_entitys = datas[1]
  976. pre_texts = datas[2]
  977. # phone = datas[2]
  978. if USE_PAI_EAS:
  979. _data = datas[0]
  980. _data = np.transpose(np.array(_data),(1,0,2,3))
  981. request = tf_predict_pb2.PredictRequest()
  982. request.inputs["input0"].dtype = tf_predict_pb2.DT_FLOAT
  983. request.inputs["input0"].array_shape.dim.extend(np.shape(_data[0]))
  984. request.inputs["input0"].float_val.extend(np.array(_data[0],dtype=np.float64).reshape(-1))
  985. request.inputs["input1"].dtype = tf_predict_pb2.DT_FLOAT
  986. request.inputs["input1"].array_shape.dim.extend(np.shape(_data[1]))
  987. request.inputs["input1"].float_val.extend(np.array(_data[1],dtype=np.float64).reshape(-1))
  988. request_data = request.SerializeToString()
  989. list_outputs = ["outputs"]
  990. _result = vpc_requests(person_url, person_authorization, request_data, list_outputs)
  991. if _result is not None:
  992. predict_y = _result["outputs"]
  993. else:
  994. predict_y = self.model_person.predict(datas[0])
  995. else:
  996. predict_y = self.model_person.predict(datas[0])
  997. # assert len(predict_y)==len(points_entitys)==len(phone)
  998. assert len(predict_y)==len(points_entitys)
  999. for i in range(len(predict_y)):
  1000. entity = points_entitys[i]
  1001. label = np.argmax(predict_y[i])
  1002. pre_text = ''.join(pre_texts[i][0])
  1003. # print('pre_text', pre_text)
  1004. if label==0 and re.search('(谈判|磋商|询价|资格审查|评审专家|(评选|议标|评标|评审)委员会?|专家|评委)(小?组|小?组成员)?(成员|名单)[:,](\w{2,4}((组长)|(成员))?[、,,])*$', pre_text):
  1005. # print(entity.entity_text, re.search('(谈判|磋商|询价|资格审查|评审专家|(评选|议标|评标|评审)委员会?|专家|评委)(小?组|小?组成员)?(成员|名单)[:,](\w{2,4}((组长)|(成员))?[、,,])*$', pre_text).group(0))
  1006. label = 4
  1007. values = []
  1008. for item in predict_y[i]:
  1009. values.append(item)
  1010. # phone_number = phone[i]
  1011. # entity.set_Person(label,values,phone_number)
  1012. entity.set_Person(label,values,[])
  1013. # 为联系人匹配电话
  1014. # self.person_search_phone(list_sentences, list_entitys)
  1015. def person_search_phone(self,list_sentences, list_entitys):
  1016. def phoneFromList(phones):
  1017. # for phone in phones:
  1018. # if len(phone)==11:
  1019. # return re.sub('电话[:|:]|联系方式[:|:]','',phone)
  1020. return re.sub('电话[:|:]|联系方式[:|:]', '', phones[0])
  1021. for list_entity, list_sentence in zip(list_entitys, list_sentences):
  1022. # p_entitys = 0
  1023. # p_sentences = 0
  1024. #
  1025. # key_word = re.compile('电话[:|:].{0,4}\d{7,12}|联系方式[:|:].{0,4}\d{7,12}')
  1026. # # 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}') # 联系电话
  1027. # # 2020/11/25 增加发现的号码段
  1028. # phone = re.compile('1[3|4|5|6|7|8|9][0-9][-—-]?\d{4}[-—-]?\d{4}|'
  1029. # '\d{3,4}[-—-][1-9]\d{6,7}/\d{3,8}|'
  1030. # '\d{3,4}[-—-]\d{7,8}转\d{1,4}|'
  1031. # '\d{3,4}[-—-]?[1-9]\d{6,7}|'
  1032. # '[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1033. # '[1-9]\d{6,7}') # 联系电话
  1034. # dict_index_sentence = {}
  1035. # for _sentence in list_sentence:
  1036. # dict_index_sentence[_sentence.sentence_index] = _sentence
  1037. #
  1038. # dict_context_itemx = {}
  1039. # last_person = "####****++++$$^"
  1040. # last_person_phone = "####****++++$^"
  1041. # _list_entity = [entity for entity in list_entity if entity.entity_type == "person"]
  1042. # while (p_entitys < len(_list_entity)):
  1043. # entity = _list_entity[p_entitys]
  1044. # if entity.entity_type == "person" and entity.label in [1,2,3]:
  1045. # sentence = dict_index_sentence[entity.sentence_index]
  1046. # # 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)
  1047. #
  1048. # # s = spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=20)
  1049. #
  1050. # # 2021/5/8 取上下文的句子,解决表格处理的分句问题
  1051. # left_sentence = dict_index_sentence.get(entity.sentence_index - 1)
  1052. # left_sentence_tokens = left_sentence.tokens if left_sentence else []
  1053. # right_sentence = dict_index_sentence.get(entity.sentence_index + 1)
  1054. # right_sentence_tokens = right_sentence.tokens if right_sentence else []
  1055. # entity_beginIndex = entity.begin_index + len(left_sentence_tokens)
  1056. # entity_endIndex = entity.end_index + len(left_sentence_tokens)
  1057. # context_sentences_tokens = left_sentence_tokens + sentence.tokens + right_sentence_tokens
  1058. # s = spanWindow(tokens=context_sentences_tokens, begin_index=entity_beginIndex,
  1059. # end_index=entity_endIndex, size=20)
  1060. #
  1061. # _key = "".join(["".join(x) for x in s])
  1062. # if _key in dict_context_itemx:
  1063. # _dianhua = dict_context_itemx[_key][0]
  1064. # else:
  1065. # s1 = ''.join(s[1])
  1066. # # s1 = re.sub(',)', '-', s1)
  1067. # s1 = re.sub('\s', '', s1)
  1068. # have_key = re.findall(key_word, s1)
  1069. # have_phone = re.findall(phone, s1)
  1070. # s0 = ''.join(s[0])
  1071. # # s0 = re.sub(',)', '-', s0)
  1072. # s0 = re.sub('\s', '', s0)
  1073. # have_key2 = re.findall(key_word, s0)
  1074. # have_phone2 = re.findall(phone, s0)
  1075. #
  1076. # s3 = ''.join(s[1])
  1077. # # s0 = re.sub(',)', '-', s0)
  1078. # s3 = re.sub(',|,|\s', '', s3)
  1079. # have_key3 = re.findall(key_word, s3)
  1080. # have_phone3 = re.findall(phone, s3)
  1081. #
  1082. # s4 = ''.join(s[0])
  1083. # # s0 = re.sub(',)', '-', s0)
  1084. # s4 = re.sub(',|,|\s', '', s0)
  1085. # have_key4 = re.findall(key_word, s4)
  1086. # have_phone4 = re.findall(phone, s4)
  1087. #
  1088. # _dianhua = ""
  1089. # if have_phone:
  1090. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s1.find(
  1091. # last_person_phone) != -1:
  1092. # if len(have_phone) > 1:
  1093. # _dianhua = phoneFromList(have_phone[1:])
  1094. # else:
  1095. # _dianhua = phoneFromList(have_phone)
  1096. # elif have_key:
  1097. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s1.find(
  1098. # last_person_phone) != -1:
  1099. # if len(have_key) > 1:
  1100. # _dianhua = phoneFromList(have_key[1:])
  1101. # else:
  1102. # _dianhua = phoneFromList(have_key)
  1103. # elif have_phone2:
  1104. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s0.find(
  1105. # last_person_phone) != -1:
  1106. # if len(have_phone2) > 1:
  1107. # _dianhua = phoneFromList(have_phone2[1:])
  1108. # else:
  1109. # _dianhua = phoneFromList(have_phone2)
  1110. # elif have_key2:
  1111. # if entity.entity_text != last_person and s0.find(last_person) != -1 and s0.find(
  1112. # last_person_phone) != -1:
  1113. # if len(have_key2) > 1:
  1114. # _dianhua = phoneFromList(have_key2[1:])
  1115. # else:
  1116. # _dianhua = phoneFromList(have_key2)
  1117. # elif have_phone3:
  1118. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s3.find(
  1119. # last_person_phone) != -1:
  1120. # if len(have_phone3) > 1:
  1121. # _dianhua = phoneFromList(have_phone3[1:])
  1122. # else:
  1123. # _dianhua = phoneFromList(have_phone3)
  1124. # elif have_key3:
  1125. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s3.find(
  1126. # last_person_phone) != -1:
  1127. # if len(have_key3) > 1:
  1128. # _dianhua = phoneFromList(have_key3[1:])
  1129. # else:
  1130. # _dianhua = phoneFromList(have_key3)
  1131. # elif have_phone4:
  1132. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s4.find(
  1133. # last_person_phone) != -1:
  1134. # if len(have_phone4) > 1:
  1135. # _dianhua = phoneFromList(have_phone4)
  1136. # else:
  1137. # _dianhua = phoneFromList(have_phone4)
  1138. # elif have_key4:
  1139. # if entity.entity_text != last_person and s4.find(last_person) != -1 and s4.find(
  1140. # last_person_phone) != -1:
  1141. # if len(have_key4) > 1:
  1142. # _dianhua = phoneFromList(have_key4)
  1143. # else:
  1144. # _dianhua = phoneFromList(have_key4)
  1145. # else:
  1146. # _dianhua = ""
  1147. # # dict_context_itemx[_key] = [item_x, _dianhua]
  1148. # dict_context_itemx[_key] = [_dianhua]
  1149. # # points_entitys.append(entity)
  1150. # # dianhua.append(_dianhua)
  1151. # last_person = entity.entity_text
  1152. # if _dianhua:
  1153. # # 更新联系人entity联系方式(person_phone)
  1154. # entity.person_phone = _dianhua
  1155. # last_person_phone = _dianhua
  1156. # else:
  1157. # last_person_phone = "####****++++$^"
  1158. # p_entitys += 1
  1159. from scipy.optimize import linear_sum_assignment
  1160. from BiddingKG.dl.interface.Entitys import Match
  1161. def dispatch(match_list):
  1162. main_roles = list(set([match.main_role for match in match_list]))
  1163. attributes = list(set([match.attribute for match in match_list]))
  1164. label = np.zeros(shape=(len(main_roles), len(attributes)))
  1165. for match in match_list:
  1166. main_role = match.main_role
  1167. attribute = match.attribute
  1168. value = match.value
  1169. label[main_roles.index(main_role), attributes.index(attribute)] = value + 10000
  1170. # print(label)
  1171. gragh = -label
  1172. # km算法
  1173. row, col = linear_sum_assignment(gragh)
  1174. max_dispatch = [(i, j) for i, j, value in zip(row, col, gragh[row, col]) if value]
  1175. return [Match(main_roles[row], attributes[col]) for row, col in max_dispatch]
  1176. # km算法
  1177. key_word = re.compile('((?:电话|联系方式|联系人).{0,4}?)(\d{7,12})')
  1178. phone = re.compile('1[3|4|5|6|7|8|9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1179. '\+86.?1[3|4|5|6|7|8|9]\d{9}|'
  1180. '0\d{2,3}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1181. '0\d{2,3}[-—-―]\d{7,8}转\d{1,4}|'
  1182. '0\d{2,3}[-—-―]?[1-9]\d{6,7}|'
  1183. '[\(|\(]0\d{2,3}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1184. '[1-9]\d{6,7}')
  1185. phone_entitys = []
  1186. for _sentence in list_sentence:
  1187. sentence_text = _sentence.sentence_text
  1188. res_set = set()
  1189. for i in re.finditer(phone,sentence_text):
  1190. res_set.add((i.group(),i.start(),i.end()))
  1191. for i in re.finditer(key_word,sentence_text):
  1192. res_set.add((i.group(2),i.start()+len(i.group(1)),i.end()))
  1193. for item in list(res_set):
  1194. phone_left = sentence_text[max(0,item[1]-10):item[1]]
  1195. phone_right = sentence_text[item[2]:item[2]+8]
  1196. # 排除传真号 和 其它错误项
  1197. if re.search("传,?真|信,?箱|邮,?箱",phone_left):
  1198. if not re.search("电,?话",phone_left):
  1199. continue
  1200. if re.search("帐,?号|编,?号|报,?价|证,?号|价,?格|[\((]万?元[\))]",phone_left):
  1201. continue
  1202. if re.search("[.,]\d{2,}",phone_right):
  1203. continue
  1204. _entity = Entity(_sentence.doc_id, None, item[0], "phone", _sentence.sentence_index, None, None,item[1], item[2],in_attachment=_sentence.in_attachment)
  1205. phone_entitys.append(_entity)
  1206. person_entitys = []
  1207. for entity in list_entity:
  1208. if entity.entity_type == "person":
  1209. entity.person_phone = ""
  1210. person_entitys.append(entity)
  1211. _list_entity = phone_entitys + person_entitys
  1212. _list_entity = sorted(_list_entity,key=lambda x:(x.sentence_index,x.wordOffset_begin))
  1213. words_num_dict = dict()
  1214. last_words_num = 0
  1215. list_sentence = sorted(list_sentence, key=lambda x: x.sentence_index)
  1216. for sentence in list_sentence:
  1217. _index = sentence.sentence_index
  1218. if _index == 0:
  1219. words_num_dict[_index] = 0
  1220. else:
  1221. words_num_dict[_index] = words_num_dict[_index - 1] + last_words_num
  1222. last_words_num = len(sentence.sentence_text)
  1223. match_list = []
  1224. for index in range(len(_list_entity)):
  1225. entity = _list_entity[index]
  1226. if entity.entity_type=="person" and entity.label in [1,2,3]:
  1227. match_nums = 0
  1228. for after_index in range(index + 1, min(len(_list_entity), index + 5)):
  1229. after_entity = _list_entity[after_index]
  1230. if after_entity.entity_type=="phone":
  1231. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1232. distance = (words_num_dict[after_entity.sentence_index] + after_entity.wordOffset_begin) - (
  1233. words_num_dict[entity.sentence_index] + entity.wordOffset_end)
  1234. if sentence_distance < 2 and distance < 50:
  1235. value = (-1 / 2 * (distance ** 2)) / 10000
  1236. match_list.append(Match(entity, after_entity, value))
  1237. match_nums += 1
  1238. else:
  1239. break
  1240. if after_entity.entity_type=="person":
  1241. if after_entity.label not in [1,2,3]:
  1242. break
  1243. if not match_nums:
  1244. for previous_index in range(index-1, max(0,index-5), -1):
  1245. previous_entity = _list_entity[previous_index]
  1246. if previous_entity.entity_type == "phone":
  1247. sentence_distance = entity.sentence_index - previous_entity.sentence_index
  1248. distance = (words_num_dict[entity.sentence_index] + entity.wordOffset_begin) - (
  1249. words_num_dict[previous_entity.sentence_index] + previous_entity.wordOffset_end)
  1250. if sentence_distance < 1 and distance<30:
  1251. # 前向 没有 /10000
  1252. value = (-1 / 2 * (distance ** 2))
  1253. match_list.append(Match(entity, previous_entity, value))
  1254. else:
  1255. break
  1256. result = dispatch(match_list)
  1257. for match in result:
  1258. entity = match.main_role
  1259. # 更新 list_entity
  1260. entity_index = list_entity.index(entity)
  1261. list_entity[entity_index].person_phone = match.attribute.entity_text
  1262. def predict(self,list_sentences,list_entitys):
  1263. self.predict_person(list_sentences,list_entitys)
  1264. #表格预测
  1265. class FormPredictor():
  1266. def __init__(self,lazyLoad=getLazyLoad(),config=None):
  1267. self.model_file_line = os.path.dirname(__file__)+"/../form/model/model_form.model_line.hdf5"
  1268. self.model_file_item = os.path.dirname(__file__)+"/../form/model/model_form.model_item.hdf5"
  1269. self.model_form_item = Model_form_item(config=config)
  1270. self.model_dict = {"line":[None,self.model_file_line]}
  1271. self.model_form_context = Model_form_context(config=config)
  1272. def getModel(self,type):
  1273. if type=="item":
  1274. return self.model_form_item
  1275. elif type=="context":
  1276. return self.model_form_context
  1277. else:
  1278. return self.getModel(type)
  1279. def encode(self,data,**kwargs):
  1280. return encodeInput([data], word_len=50, word_flag=True,userFool=False)[0]
  1281. return encodeInput_form(data)
  1282. def predict(self,form_datas,type):
  1283. if type=="item":
  1284. return self.model_form_item.predict(form_datas)
  1285. elif type=="context":
  1286. return self.model_form_context.predict(form_datas)
  1287. else:
  1288. return self.getModel(type).predict(form_datas)
  1289. #角色规则
  1290. #依据正则给所有无角色的实体赋予角色,给予等于阈值的最低概率
  1291. class RoleRulePredictor():
  1292. def __init__(self):
  1293. # (?P<tenderee_left_w1> 正则组名 后面的 w1 为概率权重关键词
  1294. self.pattern_tenderee_left_55 = "(?P<tenderee_left_55>((遴选|寻源|采购|招标|竞价|议价|比选|委托|询比?价|比价|评选|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选|项目|需求|甲方?|转让|招租|议标|合同主体|挂牌|出租|出让|出售|标卖|处置|发包|最终|建设|业主|竞卖|申购|公选)" \
  1295. "(人|方|单位|组织|用户|业主|主体|部门|公司|企业|工厂)|需求?方|买方|业主|权属人|甲方当事人|询价书企业|比选发起人|采购(执行|实施)单位)"\
  1296. "[))]?(信息|联系方式|概况)?[,,::]?([((](1|2|1.1|1.2)[))])?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|为|:|:|\s*)+$)"
  1297. self.pattern_tenderee_left_60 = "(?P<tenderee_left_60>(,|。|^)(项目)?((遴选|寻源|采购|招标|竞价|议价|比选|委托|询比?价|比价|评选|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选|项目|需求|甲|转让|招租|议标|合同主体|挂牌|出租|出让|出售|标卖|处置|发包)" \
  1298. "(人|方|单位|组织|用户|业主|主体|部门|公司|企业|工厂))"\
  1299. "[))]?(信息|联系方式|概况)?[,,。::]?([((]?(1|2|1.1|1.2)[))]?)?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|为|:|:|,|\s*)+$)" # 367784094 隆道-大企业采购平台 采购商:C5石油树脂-中国建材集团有限公司-四川省/成都市/市辖区
  1300. self.pattern_tenderee_left_50 = "(?P<tenderee_left_50>((所需|需[用求]|购货|征集|发布|交易发起|开户|申报|填报|开票|收货)" \
  1301. "(人|方|单位|组织|用户|业主|主体|部门|公司|企业|工厂)|[转流]出方|文章来源|委托机构|产权所有人|承包权人|结算单位|收货地址)" \
  1302. "[))]?(信息|联系方式|概况)?[,,::]?([((](1|2|1.1|1.2)[))])?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|为|:|:|\s*)+$|(采购商|招标人):(\w{2,10}-)?$)"
  1303. self.pattern_tenderee_center = "(?P<tenderee_center>(受.{5,20}的?委托|现将[\w()()]{5,20}[\d年月季度至()]+采购意向|尊敬的供应商(伙伴)?:\w{5,20}(以下简称“\w{2,5}”)))"
  1304. self.pattern_tenderee_right = "(?P<tenderee_right>^([((](以下简称)?[,\"“]*(招标|采购)(人|单位|机构)[,\"”]*[))]|^委托|^将于[\d年月日,::]+进行|^现委托|^的\w{2,10}正在进行|[\d年月季度至]+采购意向|^)?的招标工作已圆满结束)|^([拟须需]|计划)(采购|招标|购置|购买)|^须购[买置]一批|作为(采购|招标)(人|单位)|^关于)" #|(^[^.。,,::](采购|竞价|招标|施工|监理|中标|物资)(公告|公示|项目|结果|招标))|的.*正在进行询比价)
  1305. self.pattern_tendereeORagency_right = "(?P<tendereeORagency_right>(^拟对|^现?就|^现对))"
  1306. self.pattern_agency_left = "(?P<agency_left>((代理|拍卖)(?:人|机构|公司|企业|单位|组织)|专业采购机构|集中采购机构|招标组织机构|交易机构|集采机构|[招议))]+标机构|(采购|招标)代理)(名称|.{,4}名,?称|全称)?(是|为|:|:|[,,]?\s*)$|(受.{5,20}委托,?$))"
  1307. self.pattern_agency_right = "(?P<agency_right>^([((](以下简称)?[,\"“]*(代理)(人|单位|机构)[,\"”]*[))])|^受.{5,20}委托|^受委?托,)" # |^受托 会与 受托生产等冲突,代理表达一般会在后面有逗号
  1308. # 2020//11/24 大网站规则 中标关键词添加 选定单位|指定的中介服务机构
  1309. self.pattern_winTenderer_left_50 = "(?P<winTenderer_left_51>" \
  1310. "(乙|竞得|受让|买受|签约|施工|供货|供应?|合作|承做|承包|承建|承销|承保|承接|承制|承担|承修|承租((包))?|入围|入选|竞买)(候选|投标)?(人|单位|机构|供应商|方|公司|企业|厂商|商|社会资本方?)(:?单位名称|:?名称|盖章)?[::是为]+$" \
  1311. "|(选定单位|指定的中介服务机构|实施主体|中标银行|中标通知书,致|征集结果|选择中介|选择结果|成交对象|勘察人|(,|审计|处置|勘察|设计)服务单位|受托[人方])[::是为]+$" \
  1312. "|((评审结果|名次|排名|中标结果)[::]*第?[一1]名?)[::是为]+$|成交供应商信息[,:]?(序号1)?:?|供应商名称$" \
  1313. "|单一来源(采购)?(供应商|供货商|服务商|方式向)$|((中标|成交)(结果|信息))[::是为]+$|(中标|成交)供应商、(中标|成交)(金额|价格),$" \
  1314. "|现(公布|宣布|公示)中标单位如下:$|现将中标单位(公布|公示)如下:$|现宣布以下(企业|单位|公司)中标:$|经讨论,决定采用$)" # 承办单位:不作为中标 83914772
  1315. self.pattern_winTenderer_left_60 = "(?P<winTenderer_left_60>" \
  1316. "(,|。|:|^)((中标(投标)?|[拟预]中标|中选|中价|中签|成交)(人|单位|机构|中介(服务)?机构|供应商|客户|方|公司|企业|厂商|商家?|社会资本方?)|(中标候选人)?第?[一1]名|第[一1](中标|中选|成交)?候选人|服务机构)" \
  1317. "(:?单位名称|:?名称|盖章)?[,,]?([((]按综合排名排序[))]|:择优选取)?[::,,]$|选取(情况|说明):中选,中介机构名称:$|排名如下:1、$)" # 解决表头识别不到加逗号情况,需前面为,。空 20240621补充 中选 云南省投资审批中介超市 补充排名如下 南阳师范学院
  1318. self.pattern_winTenderer_left_55 = "(?P<winTenderer_left_55>(中标(投标)?|[拟预]中标|中选|中价|中签|成交|入选)(人|单位|机构|中介(服务)?机构|供应商|客户|方|公司|企业|厂商|商家?|社会资本方?)" \
  1319. "(:?单位名称|:?名称|盖章)?([((]按综合排名排序[))]|:择优选取)?[::是为]+$" \
  1320. "|结果公示如下:摇出球号:\d+号,中介机构:$)" # 取消逗号 并拒绝执行改进计划的供应商,华新水泥将可能终止与其合作关系 # 中标候选人不能作为中标 # |直购企业:$不能作为中标人,看到有些公告会又多个公司,然后还会发布中选结果的公告,其中一个公司中标
  1321. self.pattern_winTenderer_right = "(?P<winTenderer_right>(^[是为](首选)?((采购|中标|成交)(供应商|供货商|服务商)|(第[一1]|预)?(拟?(中标|中选|中价|成交)(候选|排序)?(人|单位|机构|供应商|公司|企业|厂商)))|" \
  1322. "^((报价|价格)最低,|以\w{5,10})?(确定|成|作)?为[\w“”()]{3,25}((成交|中选|中标|服务)(人|单位|供应商|企业|公司)|供货单位|供应商|第一中标候选人)[,。]" \
  1323. "|^:贵公司参与|^:?你方于|^(胜出)?中标。|^取得中标(单位)?资格|^以\d+[\d,.]+万?元(中标|成交|中选)" \
  1324. "|^通过(挂牌|拍卖)方式(以[\d.,]+万?元)?竞得|^[((](中标|成交|承包)人名?称?[))]))" # 去掉 |\w{,20} 修复 460216955 网上公布的与本次采购项目有关的信息视为已送达各响应供应商。 作为中标
  1325. self.pattern_winTenderer_whole = "(?P<winTenderer_center>(贵公司|由).{,15}以\w{,15}中标|确定[\w()]{5,20}为[^,。;]{5,50}的?中标单位" \
  1326. "|选定报价最低的[“”\w()]{5,25}为[^,。;]{5,50}的?(服务|中标|成交)单位" \
  1327. "|拟邀请[\w()]{5,20}(进行)?单一来源谈判|(承办单位|报价人|投标人|中介机构)(名称)?:[\w()]{5,20},(中标|承办|中选)(价格|金额)" \
  1328. "|(谈判结果:|结果|最终|确定|决定)[以由为][^,。;]{5,25}(向我单位)?(供货|承担|承接|中标|竞买成功)|中标通知书.{,15}你方|单一来源方?式?[从向][()\w]{5,20}采购|供应商名称:[()\w]{5,20},独家采购原因)" # 2020//11/24 大网站规则 中标关键词添加 谈判结果:由.{5,20}供货
  1329. self.pattern_secondTenderer_left = "(?P<secondTenderer_left>((第[二2]名?(名|((中标|中选|中价|成交|候选)(候选)?(人|单位|机构|供应商|公司))))(名称)?[::是为]+$)|((评审结果|名次|排名|排序)[::]第?[二2]名?,?(投标(供应)?商|供应商)(名称)?[::]+$))"
  1330. self.pattern_secondTenderer_right = "(?P<secondTenderer_right>^[是为\(]第[二2](名|(中标|中选|中价|成交)(候选)?(人|单位|机构|供应商|公司)))"
  1331. self.pattern_thirdTenderer_left = "(?P<thirdTenderer_left>(第[三3]名?(名|((中标|中选|中价|成交|候选)(候选)?(人|单位|机构|供应商|公司))))(名称)?[::是为]+$|((评审结果|名次|排名|排序)[::]第?[三3]名?,?(投标(供应)?商|供应商)(名称)?[::]+$))"
  1332. self.pattern_thirdTenderer_right = "(?P<thirdTenderer_right>^[是为\(]第[三3](名|(中标|中选|中价|成交)(候选)?(人|单位|机构|供应商|公司)))"
  1333. self.condadate_left = "(?P<candidate_left>(((中标|成交|入围|入选)候选|投标)(人|单位|机构|中介(服务)?机构|供应商|客户|方|公司|厂商|商家?|社会资本方?)|服务单位)(:?单位名称|:?名称|全称|(?盖\w{,5}章)?|如下|:?牵头人)?[::是为]+$)"
  1334. self.pattern_left = [
  1335. self.pattern_tenderee_left_60,
  1336. self.pattern_tenderee_left_55,
  1337. self.pattern_tenderee_left_50,
  1338. self.pattern_agency_left,
  1339. self.pattern_secondTenderer_left,
  1340. self.pattern_thirdTenderer_left,
  1341. self.pattern_winTenderer_left_60,
  1342. self.pattern_winTenderer_left_55,
  1343. self.pattern_winTenderer_left_50,
  1344. ]
  1345. self.pattern_whole = [
  1346. self.pattern_winTenderer_whole,
  1347. self.pattern_tenderee_center,
  1348. ]
  1349. self.pattern_right = [
  1350. self.pattern_thirdTenderer_right,
  1351. self.pattern_secondTenderer_right,
  1352. self.pattern_agency_right,
  1353. self.pattern_tendereeORagency_right,
  1354. self.pattern_tenderee_right,
  1355. self.pattern_winTenderer_right,
  1356. ]
  1357. self.SET_NOT_TENDERER = set(["人民政府","人民法院","中华人民共和国","人民检察院","评标委员会","中国政府","中国海关","中华人民共和国政府"])
  1358. self.pattern_money_tenderee = re.compile("投?标?最高限价|采购计划金额|项目预算|招标金额|采购金额|项目金额|投资估算|采购(单位|人)委托价|招标限价|拦标价|预算金额|标底|总计|限额|资金来源,?为\w{2,4}资金|采购成本价|总费用约?为") # |建安费用 不作为招标金额
  1359. self.pattern_money_tenderer = re.compile("((合同|成交|中标|应付款|交易|投标|验收|订单)[)\)]?(综合)?(总?金额|结果|[单报总]?价))|标的基本情况|承包价|报酬(含税):|经评审的价格") # 单写 总价 不能作为中标金额,很多表格有单价、总价
  1360. self.pattern_money_tenderer_whole = re.compile("(以金额.*中标)|中标供应商.*单价|以.*元中标")
  1361. self.pattern_money_other = re.compile("代理费|服务费")
  1362. self.pattern_pack = "(([^承](包|标[段号的包]|分?包|包组)编?号?|项目)[::]?[\((]?[0-9A-Za-z一二三四五六七八九十]{1,4})[^至]?|(第?[0-9A-Za-z一二三四五六七八九十]{1,4}(包号|标[段号的包]|分?包))|[0-9]个(包|标[段号的包]|分?包|包组)"
  1363. # self.role_file = open('/data/python/lsm/role_rule_predict.txt', 'a', encoding='utf-8')
  1364. def _check_input(self,text, ignore=False):
  1365. if not text:
  1366. return []
  1367. if not isinstance(text, list):
  1368. text = [text]
  1369. null_index = [i for i, t in enumerate(text) if not t]
  1370. if null_index and not ignore:
  1371. raise Exception("null text in input ")
  1372. return text
  1373. def ser_role(self, pattern_list, text, entity_text):
  1374. for _pattern in pattern_list:
  1375. for _iter in re.finditer(_pattern, text):
  1376. for _group, _v_group in _iter.groupdict().items():
  1377. if _v_group is not None and _v_group != "":
  1378. _role = _group.split("_")[0]
  1379. if _role == "tendereeORagency": # 2022/3/9 新增不确定招标代理判断逻辑
  1380. # print('p_entity_sentenceindex:', p_entity.sentence_index)
  1381. # if re.search('医院|学校|大学|中学|小学|幼儿园|政府|部|委员会|署|行|局|厅|处|室|科|股|站', entity_text) \
  1382. # or re.search('(采购|招标|投标|交易|代理|拍卖|咨询|顾问|管理)', entity_text) == None:
  1383. if is_agency(entity_text):
  1384. _role = 'tenderee'
  1385. else:
  1386. _role = "agency"
  1387. _direct = _group.split("_")[1]
  1388. # _weight = _group.split("_")[2] if len(_group.split("_")) == 3 else ""
  1389. prob = int(_group.split("_")[2])/100 if len(_group.split("_")) == 3 else 0.55
  1390. # print('实体召回概率:', prob)
  1391. _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1392. "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1393. return (_label, prob, _iter.group(0))
  1394. return (5, 0.5, '')
  1395. def rule_predict(self, before, center, after, entity_text):
  1396. # before = before if isinstance(before, str) else ""
  1397. # center = center if isinstance(center, str) else ""
  1398. # after = after if isinstance(after, str) else ""
  1399. _label, _prob, keyword = self.ser_role(self.pattern_left, before, entity_text) # 前文匹配
  1400. keyword = "left_" + keyword if keyword!="" else keyword
  1401. if _label == 2 and re.search(
  1402. '各.{,5}供应商|尊敬的供应商|[^\w]候选供应商|业绩|拟招|(交易|采购|招标|建设)服务(单位|机构)|第[四五六七4567]|是否中标:否|序号:\d+,\w{,2}候选|(排名|排序|名次):([4-9]|\d{2,})|未(中[标选]|入围)|不得确定为|(响应|参[加与]报价|通过资格审查)的?供应商',
  1403. # 135463002 拟招一家供应商为宜宾市第三人民医院、李庄同济医院院区提供消防维保服务
  1404. before) != None:
  1405. _label = 5
  1406. elif _label == 2 and re.search('为$', before) and re.match('\w', after): # 排除错误 前文为结尾,后文不是标点符号结尾的,如 353824459 供应商为社会团体的, 供应商为玉田县中医医院提供安保服务
  1407. _label = 5
  1408. elif _label == 2 and re.search('评委|未中标', after[:5]): # 397194341 过滤掉错误召回中标人
  1409. _label = 5
  1410. elif _label == 2 and re.search('^,?(投标报价|(资格性审查:|符合性审查:)?(不通过|不符合))', after) and re.search('中标|成交|中选|排名|排序|名次|第[一1]名', before[-10:])==None: #20240705 处理类似 493939047 错误
  1411. _label = 5
  1412. if _label == 5:
  1413. _label, _prob, keyword = self.ser_role(self.pattern_whole, before + center + after, entity_text) # 前后文匹配
  1414. keyword = 'whole_'+ keyword[:keyword.find(entity_text)] if keyword!="" else keyword
  1415. if _label == 2 and re.search('以[^,。;]{10,30}为准', before + center + after)!=None:
  1416. _label = 5
  1417. if _label != 5 and self.ser_role(self.pattern_whole, before, entity_text)[0] != 5 or \
  1418. self.ser_role(self.pattern_whole, after, entity_text)[0] != 5:
  1419. _label = 5
  1420. if _label == 5:
  1421. _label, _prob, keyword = self.ser_role(self.pattern_right, after, entity_text) # 后文匹配
  1422. keyword = "right_" + keyword if keyword!="" else keyword
  1423. if _label==5 and re.search('(中标|中选|成交)?)(结果)?(公告|公示|通知书?),', before) and re.match(':', after):
  1424. _label = 2
  1425. _prob = 0.5
  1426. _flag = False if _label==5 else True
  1427. return (_label, _prob, _flag, keyword)
  1428. def predict(self, list_articles, list_sentences, list_entitys, list_codenames, on_value=0.5):
  1429. for article, list_entity, list_sentence, list_codename in zip(list_articles, list_entitys, list_sentences,
  1430. list_codenames):
  1431. list_sentence.sort(key=lambda x: x.sentence_index) # 2022/1/5 按句子顺序排序
  1432. # list_name = list_codename["name"]
  1433. list_name = [] # 2022/1/5 改为实体列表内所有项目名称
  1434. name_entitys = [] # 2023/6/30 保存项目名称实体,直接通过位置判断角色是否在项目名称里面
  1435. candidates = [] # 保存不能确定为第几的候选人 2023/04/14
  1436. notfound_tenderer = True # 未找到前三候选人
  1437. for entity in list_entity:
  1438. if entity.entity_type == 'name':
  1439. list_name.append(entity.entity_text)
  1440. name_entitys.append(entity)
  1441. list_name = self._check_input(list_name) + [article.title]
  1442. for p_entity in list_entity:
  1443. if p_entity.entity_type in ["org", "company"]:
  1444. # 只解析角色为无的或者概率低于阈值的
  1445. if p_entity.label is None:
  1446. continue
  1447. # 将上下文包含标题的实体概率置为0.6,因为标题中的实体不一定是招标人
  1448. if str(p_entity.label) == "0":
  1449. find_flag = False
  1450. for _sentence in list_sentence:
  1451. if _sentence.sentence_index == p_entity.sentence_index:
  1452. _span = spanWindow(tokens=_sentence.tokens, begin_index=p_entity.begin_index,
  1453. end_index=p_entity.end_index, size=20, center_include=True,
  1454. word_flag=True, use_text=True,
  1455. text=re.sub(")", ")", re.sub("(", "(", p_entity.entity_text)))
  1456. if re.search(self.pattern_tenderee_left_50, _span[0]) or re.search(self.pattern_tenderee_left_55, _span[0]): # 前面有关键词的实体不判断是否在项目名称中出现
  1457. find_flag = True
  1458. break
  1459. if re.search('(项目|工程|招标|采购(条目)?|合同|标项|标的|计划|询价|询价单|询价通知书|申购单|申购)(名称|标名|标题|主题):$', _span[0]):
  1460. find_flag = True
  1461. if re.search('(局|院|府|学|处|站|会|所|校|馆|队|厅|室|司|心|园|厂)$', p_entity.entity_text):
  1462. p_entity.values[0] = 0.6 if p_entity.values[0]>0.6 else 0.55
  1463. else:
  1464. p_entity.values[0] = on_value # 项目名称里面实体修改为最低概率
  1465. break
  1466. for _name in name_entitys:
  1467. if _name.sentence_index == p_entity.sentence_index and p_entity.wordOffset_begin >=_name.wordOffset_begin and p_entity.wordOffset_end < _name.wordOffset_end:
  1468. find_flag = True
  1469. if re.search('(局|院|府|学|处|站|会|所|校|馆|队|厅|室|司|心|园|厂)$', p_entity.entity_text):
  1470. p_entity.values[0] = 0.6 if p_entity.values[0] > 0.6 else 0.55
  1471. else:
  1472. p_entity.values[0] = on_value # 项目名称里面实体修改为最低概率
  1473. break
  1474. # if p_entity.values[0] > on_value:
  1475. # p_entity.values[0] = 0.5 + (p_entity.values[0] - 0.5) / 10
  1476. # else:
  1477. # p_entity.values[0] = on_value # 2022/03/08 修正类似 223985179 公司在文章开头的项目名称概率又没达到0.5的情况
  1478. # for _name in list_name:
  1479. # if _name != "" and str(_span[0][-10:]+_span[1] + _span[2][:len(str(_name))]).find(_name) >= 0: #加上前面一些信息,修复公司不在项目名称开头的,检测不到
  1480. # find_flag = True
  1481. # if p_entity.values[0] > on_value:
  1482. # p_entity.values[0] = 0.5 + (p_entity.values[0] - 0.5) / 10
  1483. # else:
  1484. # p_entity.values[0] = on_value # 2022/03/08 修正类似 223985179 公司在文章开头的项目名称概率又没达到0.5的情况
  1485. if find_flag:
  1486. continue
  1487. # 正则从概率低于阈值或其他类别中召回角色
  1488. role_prob = float(p_entity.values[int(p_entity.label)])
  1489. if role_prob < on_value or str(p_entity.label) == "5":
  1490. # 将标题中的实体置为招标人
  1491. _list_name = self._check_input(list_name, ignore=True)
  1492. find_flag = False
  1493. for _name in _list_name: # 2022/1/5修正只要项目名称出现过的角色,所有位置都标注为招标人
  1494. if str(_name).find(p_entity.entity_text) >= 0 and p_entity.sentence_index < 4:
  1495. for _sentence in list_sentence:
  1496. if _sentence.sentence_index == p_entity.sentence_index:
  1497. _span = spanWindow(tokens=_sentence.tokens, begin_index=p_entity.begin_index,
  1498. end_index=p_entity.end_index, size=20, center_include=True,
  1499. word_flag=True, use_text=True, text=p_entity.entity_text)
  1500. if _span[2].startswith(":"): # 实体后面为冒号的不作为招标人,避免项目名称出错中标变招标 368122675 陇西兴恒建建筑有限责任公司:线路安全保护区内环境治理专项整改(第二标段)项目
  1501. break
  1502. if str(_span[0][-len(str(_name)):]+_span[1] + _span[2][:len(str(_name))]).find(
  1503. _name) >= 0 or str(_name).startswith(p_entity.entity_text): # 20240621 补充公司开头的项目名称召回,避免name太长召回失败 例 367033697
  1504. # if p_entity.entity_text in agency_set or re.search('(代理|管理|咨询|招投?标|采购)\w{,6}公司', p_entity.entity_text): # 在代理人集合的作为代理人
  1505. if is_agency(p_entity.entity_text): # 2024/3/29 统一方法判断是否为代理
  1506. find_flag = True
  1507. _label = 1
  1508. p_entity.label = _label
  1509. p_entity.values[int(_label)] = on_value
  1510. break
  1511. else:
  1512. find_flag = True
  1513. _label = 0
  1514. p_entity.label = _label
  1515. p_entity.values[int(_label)] = on_value + p_entity.values[int(_label)] / 10
  1516. if 6<len(p_entity.entity_text) < 20 and p_entity.entity_type == 'org': # 标题中角色长度在一定范围内的加分 优化类似367720967 标题中两个实体选择错误问题
  1517. p_entity.values[int(_label)] += 0.005
  1518. break
  1519. if p_entity.sentence_index >= 4:
  1520. break
  1521. if find_flag:
  1522. break
  1523. # 若是实体在标题中,默认为招标人,不进行以下的规则匹配
  1524. if find_flag:
  1525. continue
  1526. for s_index in range(len(list_sentence)):
  1527. if p_entity.doc_id == list_sentence[s_index].doc_id and p_entity.sentence_index == \
  1528. list_sentence[s_index].sentence_index:
  1529. tokens = list_sentence[s_index].tokens
  1530. begin_index = p_entity.begin_index
  1531. end_index = p_entity.end_index
  1532. size = 40 #15
  1533. spans = spanWindow(tokens, begin_index, end_index, size, center_include=True,
  1534. word_flag=True, use_text=False)
  1535. # _flag = False
  1536. # 添加中标通知书类型特殊处理
  1537. try:
  1538. if s_index == 0 and re.search('中标通知书.{,30}[,:]%s:'%p_entity.entity_text.replace('(', '').replace(')', ''),
  1539. list_sentence[s_index].sentence_text.replace('(', '').replace(')', '')[:100]):
  1540. p_entity.label = 2
  1541. p_entity.values[2] = 0.5
  1542. notfound_tenderer = False
  1543. # 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]))
  1544. break
  1545. except Exception as e:
  1546. print('正则报错:', e)
  1547. before, center, after = spans[0], spans[1], spans[2]
  1548. entity_text = p_entity.entity_text
  1549. _label, _prob, _flag, kw = self.rule_predict(before, center, after, entity_text)
  1550. # if _label in [0, 1, 2, 3, 4]:
  1551. # self.role_file.write("{0}#split#{1}#split#{2}#split#{3}#split#{4}\n".format(before,
  1552. # entity.entity_text,
  1553. # after,
  1554. # _label,
  1555. # entity.doc_id))
  1556. # 得到结果
  1557. if _flag:
  1558. if _label in [2, 3, 4]:
  1559. notfound_tenderer = False
  1560. p_entity.label = _label
  1561. # p_entity.values[int(_label)] = on_value + p_entity.values[
  1562. # int(_label)] / 10
  1563. p_entity.values[_label] = _prob + p_entity.values[int(_label)] / 10
  1564. # log('正则召回实体: %s, %s, %d, %.4f, %s'%(kw, p_entity.entity_text, p_entity.label, p_entity.values[p_entity.label], before+" "+after))
  1565. break
  1566. if re.search(self.condadate_left, before) and re.search('尊敬的|各', before[-10:])==None:
  1567. candidates.append(p_entity)
  1568. # # 使用正则+距离解决冲突
  1569. # # 2021/6/11update center: spans[1] --> spans[0][-30:]+spans[1]
  1570. # list_spans = [spans[0][-30:], spans[0][-10:] + spans[1] + spans[2][:25], spans[2]] # 实体左、中、右 信息
  1571. # for _i_span in range(len(list_spans)):
  1572. # _flag = False
  1573. # _prob_weight = 1
  1574. #
  1575. # # print(list_spans[_i_span],p_entity.entity_text)
  1576. # for _pattern in self.pattern_whole:
  1577. # for _iter in re.finditer(_pattern, list_spans[_i_span]):
  1578. # for _group, _v_group in _iter.groupdict().items():
  1579. # if _v_group is not None and _v_group != "":
  1580. # _role = _group.split("_")[0]
  1581. # if _role == "tendereeORagency": # 2022/3/9 新增不确定招标代理判断逻辑
  1582. # # print('p_entity_sentenceindex:', p_entity.sentence_index)
  1583. # if p_entity.sentence_index>=1: # 只在第一句进行这种模糊匹配
  1584. # continue
  1585. # if re.search('医院|学校|大学|中学|小学|幼儿园|政府|部|委员会|署|行|局|厅|处|室|科|股|站', p_entity.entity_text)\
  1586. # or re.search('(采购|招标|投标|交易|代理|拍卖|咨询|顾问|管理)', p_entity.entity_text) == None:
  1587. # _role = 'tenderee'
  1588. # else:
  1589. # _role = "agency"
  1590. # _direct = _group.split("_")[1]
  1591. # _weight = _group.split("_")[2] if len(_group.split("_"))==3 else ""
  1592. # # _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1593. # # "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1594. # if _i_span == 0 and _direct == "left" and re.search('各.{,5}供应商|尊敬的供应商|业绩|拟招|(交易|采购|招标|建设)服务(单位|机构)|第[四五六七4567]|是否中标:否|序号:\d+,\w{,2}候选|(排名|排序|名次):([4-9]|\d{2,})', #135463002 拟招一家供应商为宜宾市第三人民医院、李庄同济医院院区提供消防维保服务
  1595. # list_spans[0]) == None: # 2021/12/22 修正错误中标召回 例子208668937
  1596. # _flag = True
  1597. # _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1598. # "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1599. # _prob_weight = 1.2 if _weight=='w1' else 1
  1600. # # print('_v_group:',_group, _v_group, p_entity.entity_text)
  1601. #
  1602. # 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:
  1603. # _flag = True
  1604. # _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1605. # "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1606. # _prob_weight = 1.2 if _weight == 'w1' else 1
  1607. # # print('_v_group:', _group, _v_group, p_entity.entity_text)
  1608. #
  1609. # if _i_span == 2 and _direct == "right":
  1610. # _flag = True
  1611. # _label = {"tenderee": 0, "agency": 1, "winTenderer": 2,
  1612. # "secondTenderer": 3, "thirdTenderer": 4}.get(_role)
  1613. # _prob_weight = 1.2 if _weight == 'w1' else 1
  1614. # # print('_v_group:', _group, _v_group, p_entity.entity_text)
  1615. # # 得到结果
  1616. # if _flag:
  1617. # if _label in [2, 3, 4]:
  1618. # notfound_tenderer = False
  1619. # p_entity.label = _label
  1620. # p_entity.values[int(_label)] = on_value*_prob_weight + p_entity.values[int(_label)] / 10
  1621. # # 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]))
  1622. # break
  1623. # if _i_span == 0 and re.search(self.condadate_left, list_spans[_i_span]):
  1624. # candidates.append(p_entity)
  1625. elif str(p_entity.label) in ['2', '3', '4']:
  1626. notfound_tenderer = False
  1627. # 其他金额通过正则召回可能是招标或中投标的金额
  1628. if p_entity.entity_type in ["money"]:
  1629. if str(p_entity.label) == "2":
  1630. for _sentence in list_sentence:
  1631. if _sentence.sentence_index == p_entity.sentence_index:
  1632. _span = spanWindow(tokens=_sentence.tokens, begin_index=p_entity.begin_index,
  1633. end_index=p_entity.end_index, size=10, center_include=True,
  1634. word_flag=True, text=p_entity.entity_text)
  1635. if re.search('(含|在|包括)(\d+)?$', _span[0]):
  1636. continue
  1637. if re.search(',\w{2,}', _span[0]):
  1638. _span[0] = _span[0].split(',')[-1] if len(_span[0].split(',')[-1])>4 else _span[0][-8:] #避免多个价格在一起造成误判
  1639. if re.search(self.pattern_money_tenderee, _span[0]) is not None and re.search(
  1640. self.pattern_money_other, _span[0]) is None:
  1641. p_entity.values[0] = 0.8 + p_entity.values[0] / 10
  1642. p_entity.label = 0
  1643. # print('规则召回预算金额:', p_entity.entity_text, _span[0])
  1644. if re.search(self.pattern_money_tenderer, _span[0]) is not None:
  1645. if re.search(self.pattern_money_other, _span[0]) is not None:
  1646. if re.search(self.pattern_money_tenderer, _span[0]).span()[1] > \
  1647. re.search(self.pattern_money_other, _span[0]).span()[1]:
  1648. p_entity.values[1] = 0.8 + p_entity.values[1] / 10
  1649. p_entity.label = 1
  1650. else:
  1651. p_entity.values[1] = 0.8 + p_entity.values[1] / 10
  1652. p_entity.label = 1
  1653. if re.search(self.pattern_money_tenderer_whole,
  1654. "".join(_span)) is not None and re.search(self.pattern_money_other,
  1655. _span[0]) is None:
  1656. p_entity.values[1] = 0.8 + p_entity.values[1] / 10
  1657. p_entity.label = 1
  1658. elif re.search('(预算金额|最高(投标)?上?限[价额]?格?|招标控制价))?:?([\d.,]+万?元[,(]其中)?(第?[一二三四五0-9](标[段|包]|[分子]包):?[\d.,]+万?元,)*第?[一二三四五0-9](标[段|包]|[分子]包):?$'
  1659. , _sentence.sentence_text[:p_entity.wordOffset_begin]): # 处理几个标段金额相邻情况 例子:191705231
  1660. p_entity.values[0] = 0.8 + p_entity.values[0] / 10
  1661. p_entity.label = 0
  1662. # print('规则召回预算金额2:', p_entity.entity_text, _sentence.sentence_text[:p_entity.wordOffset_begin])
  1663. if notfound_tenderer and len(set([ent.entity_text for ent in candidates])) == 1 and re.search(
  1664. '(中标|中选|中价|中租|成交|入选|确认)(候选人|人|供应商|记录|结果|变更)?(公告|公示|结果)|(遴选|采购|招标|竞价|议价|比选|询比?价|评选|谈判|邀标|邀请|洽谈|约谈|评标|发包|磋商|交易|评审)\w{,2}结果|单一来源(采购|招标)?的?(中标|成交|结果)|中标通知书',
  1665. article.title+article.content[:100]):
  1666. for p_entity in candidates:
  1667. # print('只有一个候选人的作为中标人', p_entity.entity_text)
  1668. p_entity.label = 2
  1669. p_entity.values[2] = on_value
  1670. # 增加招标金额扩展,招标金额+连续的未识别金额,并且都可以匹配到标段信息,则将为识别的金额设置为招标金额
  1671. list_p = []
  1672. state = 0
  1673. for p_entity in list_entity:
  1674. for _sentence in list_sentence:
  1675. if _sentence.sentence_index == p_entity.sentence_index:
  1676. _span = spanWindow(tokens=_sentence.tokens, begin_index=p_entity.begin_index,
  1677. end_index=p_entity.end_index, size=20, center_include=True, word_flag=True,
  1678. text=p_entity.entity_text)
  1679. if state == 2:
  1680. for _p in list_p[1:]:
  1681. _p.values[0] = 0.8 + _p.values[0] / 10
  1682. _p.label = 0
  1683. state = 0
  1684. list_p = []
  1685. if state == 0:
  1686. if p_entity.entity_type in ["money"]:
  1687. if str(p_entity.label) == "0" and re.search(self.pattern_pack,
  1688. _span[0] + "-" + _span[2]) is not None:
  1689. state = 1
  1690. list_p.append(p_entity)
  1691. elif state == 1:
  1692. if p_entity.entity_type in ["money"]:
  1693. if str(p_entity.label) in ["0", "2"] and re.search(self.pattern_pack,
  1694. _span[0] + "-" + _span[
  1695. 2]) is not None and re.search(
  1696. self.pattern_money_other,
  1697. _span[0] + "-" + _span[2]) is None and p_entity.sentence_index == list_p[
  1698. 0].sentence_index:
  1699. list_p.append(p_entity)
  1700. else:
  1701. state = 2
  1702. if len(list_p) > 1:
  1703. for _p in list_p[1:]:
  1704. # print("==",_p.entity_text,_p.sentence_index,_p.label)
  1705. _p.values[0] = 0.8 + _p.values[0] / 10
  1706. _p.label = 0
  1707. state = 0
  1708. list_p = []
  1709. for p_entity in list_entity:
  1710. # 将属于集合中的不可能是中标人的标签置为无
  1711. if p_entity.entity_text in self.SET_NOT_TENDERER:
  1712. p_entity.label = 5
  1713. '''正则补充最后一句实体日期格式为招标或代理 2021/12/30'''
  1714. class RoleRuleFinalAdd():
  1715. def predict(self, list_articles,list_sentences, list_entitys, list_codenames):
  1716. '''
  1717. 最终规则召回角色
  1718. :param list_articles:
  1719. :param list_sentences:
  1720. :param list_entitys:
  1721. :param list_codenames:
  1722. :return:
  1723. '''
  1724. # text_end = list_articles[0].content.split('##attachment##')[0][-40:]
  1725. main_sentences = [sentence for sentence in list_sentences[0] if not sentence.in_attachment]
  1726. if len(list_sentences[0])>0 and list_sentences[0][-1].in_attachment:
  1727. main_sentences = list_sentences[0][-1:] + main_sentences[-2:]
  1728. if len(main_sentences)==0:
  1729. return 0
  1730. # end_tokens = []
  1731. for sentence in main_sentences[-5:][::-1]: # 402073799 最后五句由后往前,匹配文末角色,日期
  1732. # end_tokens.extend(sentence.tokens)
  1733. # text_end = "".join(end_tokens[-30:])
  1734. # text_end = "".join(end_tokens)
  1735. text_end = "".join(sentence.tokens)
  1736. text_end = re.sub(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", '', text_end) # 去除网址
  1737. 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日, 这种情况
  1738. # sear_ent = re.search('[,。]([\u4e00-\u9fa5()()]{5,20}),?\s*[.]{2,4}年.{1,2}月.{1,2}日', text_end)
  1739. 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)
  1740. if sear_ent:
  1741. b, e = sear_ent.span()
  1742. if re.search('报价记录|竞价成交', text_end[max(b-10, 0):b] + text_end[e:]):
  1743. sear_ent = None
  1744. break
  1745. if sear_ent == None:
  1746. text_end = list_articles[0].content[-100:]
  1747. sear_ent = re.search(
  1748. '([,。;]|^)(?P<entity>[\u4e00-\u9fa5()()]{5,20}(,?[\u4e00-\u9fa5]{,8})?),?\s*(公告日期:)?[0-9零一二三四五六七八九十〇]{2,4}[年\-/][0-9零一二三四五六七八九十]{1,2}[月\-/][0-9零一二三四五六七八九十]{1,2}日?',
  1749. text_end)
  1750. if sear_ent:
  1751. b, e = sear_ent.span()
  1752. if re.search('报价记录|竞价成交', text_end[max(b-10, 0):b] + text_end[e:]):
  1753. sear_ent = None
  1754. sear_ent1 = re.search('((招标|采购)联系人)[,::][A-Za-z0-9_]*(?P<entity>[\u4e00-\u9fa5()()]{4,20})', list_articles[0].content[:5000])
  1755. sear_ent2 = re.search('[,:](户名|开户名称|发票抬头|单位名称|名称)[::](?P<entity>[\u4e00-\u9fa5()()]{5,20})[,。]', list_articles[0].content[:5000])
  1756. if sear_ent2 and sear_ent2.group(1) in ['单位名称','名称'] and re.search('投标报价|(中标|成交|结果|候选人|评标|开标)(公告|公示)', list_articles[0].content[:5000]): # 排除 341354479 这种作为招标人
  1757. sear_ent2 = None
  1758. sear_ent3 = re.search('(买家信息|所有权人|土地权属单位|报名咨询|[收送交]货地点)[,:](?P<entity>[\u4e00-\u9fa5()()]{5,20})[0-9\-]*[,。]', list_articles[0].content[:5000])
  1759. sear_ent4 = re.search('(发布(?:人|单位|机构|企业)|项目业主|所属公司|寻源单位)[,::][A-Za-z0-9_]*(?P<entity>[\u4e00-\u9fa5()()]{4,20})[,。]', list_articles[0].content[:5000])
  1760. sear_list = [sear_ent4 , sear_ent3 , sear_ent2 ,sear_ent1, sear_ent]
  1761. tenderee_notfound = True
  1762. agency_notfound = True
  1763. tenderee_list = []
  1764. agency_list = []
  1765. ents = []
  1766. for ent in list_entitys[0]:
  1767. if ent.entity_type in ['org', 'company']:
  1768. if ent.label == 0 and ent.values[ent.label]>0.55:
  1769. if '公共资源交易中心' in ent.entity_text: # 公共资源交易中心不算招标或代理,只算平台
  1770. # ent.label = 5
  1771. ent.values[ent.label] = 0.6 if ent.values[ent.label]>0.6 else 0.5 # 改为降低概率,不改类别,防止 382573066 明显招标人表达不提取
  1772. continue
  1773. tenderee_list.append(ent.entity_text)
  1774. tenderee_notfound = False
  1775. elif ent.label == 1 and ent.values[ent.label]>0.55:
  1776. agency_list.append(ent.entity_text)
  1777. agency_notfound = False
  1778. elif ent.label == 5:
  1779. if '公共资源交易中心' in ent.entity_text:
  1780. continue
  1781. ents.append(ent)
  1782. if sear_ent or sear_ent1 or sear_ent2 or sear_ent3 or sear_ent4:
  1783. for _sear_ent in [_sear for _sear in sear_list if _sear]:
  1784. ent_re = _sear_ent.group('entity')
  1785. ent_re = ent_re.replace(',', '').replace("(","(").replace(")",")")
  1786. if tenderee_notfound or agency_notfound:
  1787. n = 0
  1788. for i in range(len(ents) - 1, -1, -1):
  1789. if not ents[i].in_attachment:
  1790. n += 1
  1791. if n > 3 and _sear_ent==sear_ent: # 文章末尾角色加日期这种只找后三个实体
  1792. break
  1793. elif _sear_ent==sear_ent and ents[i].label != 5: # 后面有角色的实体的停止继续往前
  1794. break
  1795. 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):
  1796. if agency_notfound and is_agency(ents[i].entity_text) and ents[i].entity_text not in tenderee_list:
  1797. ents[i].label = 1
  1798. ents[i].values[1] = 0.51 # 修改为比标题概率略高
  1799. agency_notfound = False
  1800. elif tenderee_notfound and not is_agency(ents[i].entity_text) and ents[i].entity_text not in agency_list:
  1801. ents[i].label = 0
  1802. ents[i].values[0] = 0.51 # 修改为比标题概率略高
  1803. tenderee_notfound = False
  1804. # log('正则最后补充实体: %s'%(ent_re))
  1805. break
  1806. if not tenderee_notfound:
  1807. break
  1808. # 招标人角色召回规则
  1809. class TendereeRuleRecall():
  1810. def __init__(self):
  1811. # self.tenderee_left = re.compile("(发布(人|单位|机构)|需求方(信息[,:])?(单位|公司)?名称|购买主体|收货单位|项目申请单位|发起组织|联系单位|"
  1812. # "询价(机构|企业)|联系(人|方式),?(单位|公司)(名称)?|联系(人|方式),名称)[::是为][^。;,]{,5}$")
  1813. # self.tenderee_left_1 = re.compile("采购商公司|询价单位|项目法人单位|项目法人|项目业主名称|申购单位|预算单位|预算单位名称|预算单位单位名称|买方单位|需求公司|寻源单位|项目业主|采购商|业主单位咨询电话|需用单位|采购工厂|征集单位")
  1814. self.tenderee_left_1 = re.compile("((?:采购商|项目法人|项目业主)(名称)?|(?:采购商|询价|项目法人|项目业主|申购|预算|买方|需求|寻源|需用|征集)(单位|公司)((?:单位|公司)?名称)?|询价企业|"
  1815. "业主单位咨询电话|购买主体|采购工厂|需求方(信息[,:])?(单位|公司)?名称|采购单位[\((].{1,6}[\))])[::是为][^。;,]{,2}$")
  1816. self.tenderee_left_2 = re.compile("(招标承办单位|交易人(?:名称)?|招标人代表|(采购|招标)联系人|交易单位|发起(单位|组织)|收货单位|使用方|买家信息)[::是为][^。;,]{,2}$")
  1817. self.tenderee_left_3 = re.compile("[本我](?:公司|单位)[\(\[(【]?$")
  1818. # self.tenderee_left_4 = re.compile("(采购机构|组织机构|组织方|执行单位|采购组织单位|招标组织单位|招标组织部门|采购执行方|采购执行单位|询价执行组织|组织单位|联系单位|联系部门)[::是为][^。;,]{,2}$")
  1819. self.tenderee_left_4 = re.compile("(采购机构|(?:采购|招标|询价)?(组织|执行)(机构|方|单位|部门|组织)|联系(单位|部门)|联系(人|方式),?(单位|公司)(名称)?|联系(人|方式),名称)[::是为][^。;,]{,2}$")
  1820. self.tenderee_left_5 = re.compile("(撰写单位|发布(?:人|单位|机构|公司|部门|企业))[^。;,]{,2}$")
  1821. self.tenderee_right = re.compile("^[^。;::]{,5}[((](以?下简?称)?,?[,\"“]*[我本][\u4e00-\u9fa5]{1,2}[,\"”]*[))]|"
  1822. "^[\((][^。;::\))]{,5}称(?:招标|采购)(?:人|单位)|"
  1823. "^[^。;::]{,10}[对就][^。;,]+,?[^。;,]{,20}进行[^。;,]*(采购|询比?价|遴选|招投?标|征集)|"
  1824. "^[^。;::]{,10}关于[^。;,]+,?[^。;,]{,20}的[^。;,]{,20}公告|"
  1825. "^[^。;,::]{,10}的[^。;,]+,?[^。;,]{,20}正在[^。;,]{,5}进行|"
  1826. "^[^。;,::]{,10}的[^。;,]+,?[^。,;]{,20}已?[^。;,]{,20}批准|"
  1827. "^[^。;,::]{,15}(选定|选取|征集|遴选)[^。;,]{,20}(供应商|(代理|咨询|设计)[^。;,]{,5}机构|代理人)")
  1828. self.tenderee_right2 = re.compile("^[^。;,::]{,10}(招标办|采购部|办事处|采购小?组)")
  1829. self.tenderee_right3 = re.compile("^[^。;,::]{,10}(对|就|关于|的)(?P<project>[^。;,?!::]{4,40})")
  1830. # 公告主语判断规则
  1831. self.subject = re.compile("[我本][院校局]")
  1832. # 未识别实体召回正则
  1833. self.unrecognized1 = re.compile("(?P<tenderee_left>((遴选|采购|招标|竞价|议价|比选|委托|询比?价|评选|谈判|邀标|邀请|洽谈|约谈)" \
  1834. "(人|商|公司|单位|组织|用户|业主|主体|方|部门))" \
  1835. "(信息[,:]?)?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|:|:)+)(?P<unrecognized>[^,。::;]+)[,。;::]")
  1836. self.unrecognized2 = re.compile("(?P<tenderee_left>((项目|需求|最终|建设|业主|转让|招租|甲|议标|合同主体|挂牌|出租|出让|选取|抽取|抽选|出售|标卖|比价|处置)" \
  1837. "(人|公司|单位|组织|用户|业主|主体|方|部门)|文章来源|委托机构|产权所有人|需求?方|买方|业主|(业主|采购人|招标人)联系方式[,:]公司名称:|权属人|甲方当事人|询价书企业|比选发起人|项目单位[,:]单位名称|结算单位)"\
  1838. "[))]?(信息[,:])?((公司|单位)?名称)?([((](全称|盖章)[))])?(是|:|:)+)(?P<unrecognized>[^,。::;]+)[,。;::]")
  1839. # 未识别实体尾部判断
  1840. # self.unrecognized_end1 = re.compile(
  1841. # "^[\u4e00-\u9fa5]{2,}?(?:公司|医院|学校|学院|大学|中学|小学|幼儿园|政府|指挥部|办公室|项目部|业主大会|监狱|教育局|委员会|研究所|招标办|采购部|办事处|水利局|公墓|中心|联合社|合作社)")
  1842. # self.unrecognized_end2 = re.compile("^[\u4e00-\u9fa5]{4,}(?:署|局|厅|处|室|科|部|站|所|股|行|园)")
  1843. def predict(self, list_articles,list_sentences, list_entitys, list_codenames):
  1844. self.get_tenderee = False
  1845. ents = []
  1846. list_name = []
  1847. agency_set = set()
  1848. for ent in list_entitys[0]:
  1849. if ent.entity_type == 'name':
  1850. list_name.append(ent.entity_text)
  1851. if ent.entity_type in ['org', 'company']:
  1852. if ent.label == 0 and ent.values[ent.label]>=0.5:
  1853. self.get_tenderee = True
  1854. break
  1855. elif ent.label == 1:
  1856. if ent.values[ent.label]>0.5:
  1857. agency_set.add(ent.entity_text)
  1858. elif ent.label == 5:
  1859. if len(ent.entity_text)>=4:
  1860. ents.append(ent)
  1861. if not self.get_tenderee:
  1862. self.entity_context_rule(ents,list_name,list_sentences,list(agency_set))
  1863. if not self.get_tenderee:
  1864. self.subject_rule(ents,list_articles,list_sentences)
  1865. # if not self.get_tenderee:
  1866. # self.unrecognized_entity_rule(self.unrecognized1,list_sentences,list_entitys,0.55)
  1867. # if not self.get_tenderee:
  1868. # self.unrecognized_entity_rule(self.unrecognized2,list_sentences,list_entitys,0.5)
  1869. #entity上下文正则判断
  1870. def entity_context_rule(self,entitys,list_name,list_sentences,list_agency):
  1871. list_sentences[0].sort(key=lambda x:x.sentence_index)
  1872. entity_data = []
  1873. for ent in entitys:
  1874. _sentence = list_sentences[0][ent.sentence_index]
  1875. _span = spanWindow(tokens=_sentence.tokens, begin_index=ent.begin_index,
  1876. end_index=ent.end_index, size=40, center_include=True,
  1877. word_flag=True, use_text=True,
  1878. text=re.sub(")", ")", re.sub("(", "(", ent.entity_text)))
  1879. entity_data.append((ent,_span))
  1880. if not self.get_tenderee:
  1881. for _data in entity_data:
  1882. ent = _data[0]
  1883. _span = _data[1]
  1884. if re.search(self.tenderee_left_1,_span[0]):
  1885. ent.label = 0
  1886. ent.values[0] = 0.5 + ent.values[0] / 10
  1887. self.get_tenderee = True
  1888. if not self.get_tenderee:
  1889. for _data in entity_data:
  1890. ent = _data[0]
  1891. _span = _data[1]
  1892. if re.search(self.tenderee_left_2,_span[0]):
  1893. ent.label = 0
  1894. ent.values[0] = 0.5 + ent.values[0] / 10
  1895. self.get_tenderee = True
  1896. if not self.get_tenderee:
  1897. for _data in entity_data:
  1898. ent = _data[0]
  1899. _span = _data[1]
  1900. if re.search(self.tenderee_left_3,_span[0]):
  1901. ent.label = 0
  1902. ent.values[0] = 0.5 + ent.values[0] / 10
  1903. self.get_tenderee = True
  1904. if not self.get_tenderee:
  1905. for _data in entity_data:
  1906. ent = _data[0]
  1907. _span = _data[1]
  1908. if re.search(self.tenderee_left_4,_span[0]):
  1909. if len(list_agency)>0:
  1910. _same = False
  1911. for agency in list_agency:
  1912. if ent.entity_text in agency or agency in ent.entity_text:
  1913. _same = True
  1914. break
  1915. if not _same:
  1916. ent.label = 0
  1917. ent.values[0] = 0.5 + ent.values[0] / 10
  1918. self.get_tenderee = True
  1919. else:
  1920. if re.search('医院|学校|大学|中学|小学|幼儿园|政府|部|委员会|署|行|局|厅|处|室|科|股|站', ent.entity_text
  1921. ) or not re.search('(采购|招标|投标|交易|代理|拍卖|咨询|顾问|管理)', ent.entity_text) or re.search("自行.?采购",list_sentences[0][ent.sentence_index].sentence_text):
  1922. ent.label = 0
  1923. ent.values[0] = 0.5 + ent.values[0] / 10
  1924. self.get_tenderee = True
  1925. if not self.get_tenderee:
  1926. for _data in entity_data:
  1927. ent = _data[0]
  1928. _span = _data[1]
  1929. if re.search(self.tenderee_left_5,_span[0]):
  1930. if len(list_agency)>0:
  1931. _same = False
  1932. for agency in list_agency:
  1933. if ent.entity_text in agency or agency in ent.entity_text:
  1934. _same = True
  1935. break
  1936. if not _same:
  1937. ent.label = 0
  1938. ent.values[0] = 0.5 + ent.values[0] / 10
  1939. self.get_tenderee = True
  1940. else:
  1941. if re.search('医院|学校|大学|中学|小学|幼儿园|政府|部|委员会|署|行|局|厅|处|室|科|股|站', ent.entity_text
  1942. ) or not re.search('(采购|招标|投标|交易|代理|拍卖|咨询|顾问|管理)', ent.entity_text):
  1943. ent.label = 0
  1944. ent.values[0] = 0.5 + ent.values[0] / 10
  1945. self.get_tenderee = True
  1946. if not self.get_tenderee:
  1947. for _data in entity_data:
  1948. ent = _data[0]
  1949. _span = _data[1]
  1950. if re.search(self.tenderee_right, _span[2]):
  1951. ent.label = 0
  1952. ent.values[0] = 0.5 + ent.values[0] / 10
  1953. self.get_tenderee = True
  1954. if not self.get_tenderee:
  1955. for _data in entity_data:
  1956. ent = _data[0]
  1957. _span = _data[1]
  1958. if re.search(self.tenderee_right2, _span[2]):
  1959. ent.label = 0
  1960. ent.values[0] = 0.5 + ent.values[0] / 10
  1961. self.get_tenderee = True
  1962. if not self.get_tenderee:
  1963. if list_name:
  1964. for _data in entity_data:
  1965. ent = _data[0]
  1966. _span = _data[1]
  1967. pj_name = re.search(self.tenderee_right3, _span[2])
  1968. if pj_name:
  1969. pj_name = pj_name.groupdict()["project"]
  1970. for _name in list_name:
  1971. if _name in pj_name:
  1972. ent.label = 0
  1973. ent.values[0] = 0.5
  1974. self.get_tenderee = True
  1975. break
  1976. # for _data in entity_data:
  1977. # ent = _data[0]
  1978. # _span = _data[1]
  1979. # if re.search(self.tenderee_left,_span[0]):
  1980. # ent.label = 0
  1981. # ent.values[0] = 0.5 + ent.values[0] / 10
  1982. # self.get_tenderee = True
  1983. # elif re.search(self.tenderee_right,_span[2]):
  1984. # ent.label = 0
  1985. # ent.values[0] = 0.5 + ent.values[0] / 10
  1986. # self.get_tenderee = True
  1987. # elif re.search(self.tenderee_right2, _span[2]):
  1988. # ent.label = 0
  1989. # ent.values[0] = 0.5 + ent.values[0] / 10
  1990. # self.get_tenderee = True
  1991. # elif list_name:
  1992. # pj_name = re.search(self.tenderee_right3, _span[2])
  1993. # if pj_name:
  1994. # pj_name = pj_name.groupdict()["project"]
  1995. # for _name in list_name:
  1996. # if _name in pj_name:
  1997. # ent.label = 0
  1998. # ent.values[0] = 0.5
  1999. # self.get_tenderee = True
  2000. # break
  2001. # 公告主语判断
  2002. def subject_rule(self, entitys,list_articles,list_sentences):
  2003. content = list_articles[0].content.split('##attachment##')[0]
  2004. if re.search(self.subject,content):
  2005. _subject = re.search(self.subject,content).group()
  2006. for ent in entitys:
  2007. if re.search("院",_subject) and re.search("医院|学院",ent.entity_text):
  2008. ent.label = 0
  2009. ent.values[0] = 0.5 + ent.values[0] / 10
  2010. self.get_tenderee = True
  2011. elif re.search("校",_subject) and re.search("学校|学院|大学|高中|初中|中学|小学",ent.entity_text):
  2012. ent.label = 0
  2013. ent.values[0] = 0.5 + ent.values[0] / 10
  2014. self.get_tenderee = True
  2015. elif re.search("局", _subject) and re.search("局", ent.entity_text):
  2016. _sentence = list_sentences[0][ent.sentence_index]
  2017. _span = spanWindow(tokens=_sentence.tokens, begin_index=ent.begin_index,
  2018. end_index=ent.end_index, size=20, center_include=True,
  2019. word_flag=True, use_text=True,
  2020. text=re.sub(")", ")", re.sub("(", "(", ent.entity_text)))
  2021. if not re.search("监督|投诉",_span[0][-10:]):
  2022. ent.label = 0
  2023. ent.values[0] = 0.5 + ent.values[0] / 10
  2024. self.get_tenderee = True
  2025. # 正则召回未识别实体
  2026. # def unrecognized_entity_rule(self,pattern,list_sentences,list_entitys,on_value=0.5):
  2027. # list_sentence = list_sentences[0]
  2028. # for in_attachment in [False,True]:
  2029. # for sentence in [sentence for sentence in list_sentence if sentence.in_attachment==in_attachment]:
  2030. # sentence_text = sentence.sentence_text
  2031. # tokens = sentence.tokens
  2032. # doc_id = sentence.doc_id
  2033. # in_attachment = sentence.in_attachment
  2034. # list_tokenbegin = []
  2035. # begin = 0
  2036. # for i in range(0, len(tokens)):
  2037. # list_tokenbegin.append(begin)
  2038. # begin += len(str(tokens[i]))
  2039. # list_tokenbegin.append(begin + 1)
  2040. # for _match in re.finditer(pattern,sentence_text):
  2041. # _groupdict = _match.groupdict()
  2042. # _match_text = _match.group()
  2043. # _unrecognized_text = _groupdict["unrecognized"]
  2044. # _unrecognized = re.search(self.unrecognized_end1,_unrecognized_text)
  2045. # if not _unrecognized:
  2046. # _unrecognized = re.search(self.unrecognized_end2, _unrecognized_text)
  2047. # if _unrecognized:
  2048. # _unrecognized = _unrecognized.group()
  2049. # else:
  2050. # continue
  2051. # # print(_unrecognized)
  2052. # if re.search("某|乙方|代理",_unrecognized) or len(_unrecognized)>15:
  2053. # continue
  2054. # begin_index_temp = _match.start()+len(_groupdict['tenderee_left'])
  2055. # for j in range(len(list_tokenbegin)):
  2056. # if list_tokenbegin[j] == begin_index_temp:
  2057. # begin_index = j
  2058. # break
  2059. # elif list_tokenbegin[j] > begin_index_temp:
  2060. # begin_index = j - 1
  2061. # break
  2062. # index = begin_index_temp + len(_unrecognized)
  2063. # end_index_temp = index
  2064. # for j in range(begin_index, len(list_tokenbegin)):
  2065. # if list_tokenbegin[j] >= index:
  2066. # end_index = j - 1
  2067. # break
  2068. # entity_id = "%s_%d_%d_%d" % (doc_id, sentence.sentence_index, begin_index, end_index)
  2069. # entity_text = _unrecognized
  2070. # new_entity = Entity(doc_id, entity_id, entity_text, 'company', sentence.sentence_index, begin_index, end_index,
  2071. # begin_index_temp, end_index_temp, in_attachment=in_attachment)
  2072. # new_entity.label = 0
  2073. # new_entity.values = [on_value,0,0,0,0,0]
  2074. # list_entitys[0].append(new_entity)
  2075. # self.get_tenderee = True
  2076. # if self.get_tenderee:
  2077. # list_entitys[0] = sorted(list_entitys[0], key=lambda x: (x.sentence_index, x.begin_index))
  2078. # break
  2079. class RoleGrade():
  2080. def __init__(self):
  2081. self.tenderee_left_9 = "(?P<tenderee_left_9>(招标|采购|遴选|寻源|竞价|议价|比选|询比?价|比价|评选|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选)(人|方|单位))"
  2082. self.tenderee_center_8 = "(?P<tenderee_center_8>受.{5,20}委托)"
  2083. self.tenderee_left_8 = "(?P<tenderee_left_8>(尊敬的供应商|项目法人|(需求|最终|发包|征集|甲|转让|出租|处置)(人|方|单位|组织|用户|业主|主体|部门|公司)))"
  2084. self.tenderee_left_6 = "(?P<tenderee_left_6>(业主|建设|委托)(人|方|单位|组织|用户|业主|主体|部门|公司|企业)|业主|买方)"
  2085. self.tenderee_left_5 = "(?P<tenderee_left_5>(发布)(人|方|单位|组织|用户|业主|主体|部门|公司|企业)|买方|发布机构)"
  2086. self.agency_left_9 = "(?P<agency_left_9>代理)"
  2087. self.winTenderer_left_9 = "(?P<winTenderer_left_9>(中标|中选|中价|成交|竞得)|第[1一]名|排[名序]:1|名次:1)"
  2088. self.winTenderer_left_8 = "(?P<winTenderer_left_8>(入选供应商|供货商|乙方|最[终后]选[择取]))" # 229435497 最后选择西平,县中原彩印有限公司,作为此项目中标供应商,
  2089. self.winTenderer_left_6 = "(?P<winTenderer_left_6>(入围|承[接建包修做制担租销]))"
  2090. self.winTenderer_right_9 = "(?P<winTenderer_right_9>^(为(中标|成交|中选)(人|单位|供应商|公司)|以\d+[\d.,]+万?元中标))"
  2091. self.secondTenderer_left_9 = "(?P<secondTenderer_left_9>(第[二2](中标|中选|中价|成交)?候选(人|单位|供应商|公司)|第[二2]名|排[名序]:2|名次:2))"
  2092. self.thirdTenderer_left_9 = "(?P<thirdTenderer_left_9>(第[三3](中标|中选|中价|成交)?候选(人|单位|供应商|公司)|第[三3]名|排[名序]:3|名次:3))"
  2093. 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,
  2094. self.winTenderer_left_6, self.winTenderer_left_9,self.winTenderer_left_8, self.winTenderer_right_9, self.secondTenderer_left_9, self.thirdTenderer_left_9]
  2095. def predict(self, list_sentences, list_entitys, original_docchannel, span=15, min_prob=0.7):
  2096. '''
  2097. 根据规则给角色分配不同等级概率;分三级:0.9-1,0.8-0.9,0.7-0.8;附件0.7-0.8,0.6-0.7,0.5-0.6
  2098. 修改概率小于0.6的且在大数据代理集合里面的招标人为代理人
  2099. :param list_articles:
  2100. :param list_sentences:
  2101. :param list_entitys:
  2102. :param codeName:
  2103. :return:
  2104. '''
  2105. sentences = sorted(list_sentences[0], key=lambda x:x.sentence_index)
  2106. role2id = {"tenderee": 0, "agency": 1, "winTenderer": 2, "secondTenderer": 3, "thirdTenderer": 4}
  2107. org_winner = []
  2108. company_winner = []
  2109. org_tenderee = []
  2110. agency_l = []
  2111. agency_like_tenderee = [] # 类似招标人的代理人实体列表
  2112. low_prob_agency = []
  2113. low_prob_tenderee = []
  2114. low_prob_winner = []
  2115. all_tenderee_agency = []
  2116. for entity in list_entitys[0]:
  2117. if entity.entity_type in ['org', 'company'] and entity.label in [0, 1, 2, 3, 4] and entity.values[entity.label]> min_prob:
  2118. text = sentences[entity.sentence_index].sentence_text
  2119. in_att = sentences[entity.sentence_index].in_attachment
  2120. pre_prob = entity.values[entity.label] # 模型预测角色概率
  2121. b = entity.wordOffset_begin
  2122. e = entity.wordOffset_end
  2123. not_found = 1
  2124. if re.search('(乙方:甲方:|甲方:乙方:)$', text[max(0, b-span):b]):
  2125. entity.label = 0 if entity.entity_type == 'org' else 5 # 修复 290777022 乙方:甲方: 重庆机场集团有限公司 错分为中标
  2126. entity.values[entity.label] = 0.55
  2127. continue
  2128. elif re.search('(采购|招标)人(?或其?(采购|招标)?代理机构)?', text[max(0, b-span-2):b]): # 修复 275206588 招标人或其招标代理机构:(盖章)
  2129. entity.label = 1 if is_agency(entity.entity_text) else 0
  2130. entity.values[entity.label] = 0.8
  2131. continue
  2132. elif re.search('(采购|招标|询比?价|遴选|寻源|比选)机构[是为:]+', text[max(0, b-span):b]) and not is_agency(entity.entity_text):
  2133. agency_like_tenderee.append(entity)
  2134. for pattern in self.pattern_list:
  2135. if 'left' in pattern:
  2136. context = text[max(0, b-span):b]
  2137. elif 'right' in pattern:
  2138. context = text[e:e+span]
  2139. elif 'center' in pattern:
  2140. context = text[max(0, b-span):e+span]
  2141. else:
  2142. print('规则错误', pattern)
  2143. ser = re.search(pattern, context)
  2144. if ser:
  2145. groupdict = pattern.split('>')[0].replace('(?P<', '')
  2146. _role, _direct, _prob = groupdict.split('_')
  2147. _label = role2id.get(_role)
  2148. if _label != entity.label:
  2149. continue
  2150. _prob = int(_prob)*0.1
  2151. # print('规则修改角色概率前:', entity.entity_text, entity.label, entity.values)
  2152. if in_att:
  2153. _prob = _prob - 0.1 # 0.2
  2154. if pre_prob < _prob: # 如果模型预测概率小于关键词概率
  2155. _prob = 0.65
  2156. if len(entity.entity_text) < 6 and re.search('大学|医院', entity.entity_text)==None: # 如果实体名称小于6个字,概率再降0.05
  2157. _prob -= 0.05
  2158. if re.search('(地址|联系方式):$', context): # 地址结尾的概率 概率降低
  2159. _prob -= 0.05
  2160. entity.values[_label] = _prob + entity.values[_label] / 20
  2161. not_found = 0
  2162. # print('规则修改角色概率后:', entity.entity_text, entity.label, entity.values)
  2163. break
  2164. if not_found and entity.values[entity.label]> min_prob:
  2165. _prob = min_prob - 0.1 if in_att else min_prob
  2166. entity.values[entity.label] = _prob + entity.values[entity.label] / 20
  2167. # print('找不到规则修改角色概率:', entity.entity_text, entity.label, entity.values)
  2168. if entity.label == 2 and entity.values[entity.label]> min_prob:
  2169. if entity.entity_type == 'org':
  2170. org_winner.append(entity)
  2171. elif entity.entity_type == 'company':
  2172. company_winner.append(entity) # 保存中标人实体
  2173. if entity.label == 0 and entity.values[entity.label]> min_prob:
  2174. org_tenderee.append(entity.entity_text) # 保存所有招标人名称
  2175. elif entity.label == 1 and entity.values[entity.label]> min_prob:
  2176. agency_l.append(entity.entity_text)
  2177. # 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的且在大数据代理集合里面的招标人为代理人
  2178. # # log('修改概率小于0.6的且在大数据代理集合里面的招标人为代理人%s:'%entity.entity_text)
  2179. # entity.label = 1
  2180. # entity.values[entity.label] = 0.5
  2181. elif entity.entity_type in ['org', 'company'] and entity.label in [1, 0] and 0.5<=entity.values[entity.label]<0.6:
  2182. if entity.label == 1:
  2183. low_prob_agency.append(entity)
  2184. else:
  2185. low_prob_tenderee.append(entity)
  2186. elif entity.entity_type in ['org', 'company'] and entity.label == 2 and 0.5<=entity.values[entity.label]<0.6:
  2187. low_prob_winner.append(entity)
  2188. 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 同时为低概率招标、中标被改
  2189. all_tenderee_agency.append(entity.entity_text)
  2190. if org_tenderee == [] and agency_like_tenderee:
  2191. for entity in agency_like_tenderee:
  2192. entity.label = 0
  2193. entity.values[entity.label] = 0.6
  2194. for entity in low_prob_agency: # 如果低概率代理在招标人列表,改为招标人
  2195. if entity.entity_text in org_tenderee:
  2196. entity.label = 0
  2197. entity.values[entity.label] = 0.6
  2198. for entity in low_prob_tenderee:
  2199. if entity.entity_text in agency_l:
  2200. entity.label = 1
  2201. entity.values[entity.label] = 0.6
  2202. for entity in low_prob_winner: # 如果低概率中标人在招标或代理列表,改为非角色
  2203. if entity.entity_text in all_tenderee_agency:
  2204. entity.label = 5
  2205. if org_winner != []:
  2206. flag = 0
  2207. if org_tenderee != []:
  2208. for ent in org_winner:
  2209. if ent.entity_text in org_tenderee:
  2210. # log('如果org中标人同时为招标人角色,降低中标概率:%s, %s' % (ent.entity_text, ent.label))
  2211. ent.values[2] = 0.6
  2212. flag = 1
  2213. # if flag == 0 and company_winner != []: # 2024/04/18 注释掉 避免提取不到 273351465 供应商(乙方:湖南省第二测绘院
  2214. # for ent in org_winner:
  2215. # if ent.label == 2 and ent.values[2] > 0.6:
  2216. # # log('如果同时包含org和company中标人,降低org中标人概率为0.6:%s, %s' % (ent.entity_text, ent.values[2]))
  2217. # ent.values[2] = 0.6
  2218. class MoneyGrade():
  2219. def __init__(self):
  2220. self.tenderee_money_left_9 = "(?P<tenderee_left_9>最高(投标)?限价)|控制价|拦标价"
  2221. self.tenderee_money_left_8 = "(?P<tenderee_left_8>预算|限价|起始|起拍|底价|标底)"
  2222. self.tenderer_money_left_9 = "(?P<tenderer_left_9>(中标|成交|合同|总报价))"
  2223. self.tenderer_money_left_8 = "(?P<tenderer_left_8>(投标|总价))"
  2224. self.pattern_list = [self.tenderee_money_left_8, self.tenderer_money_left_8, self.tenderee_money_left_9, self.tenderer_money_left_9]
  2225. def predict(self, list_sentences, list_entitys, span=10, min_prob=0.7):
  2226. sentences = sorted(list_sentences[0], key=lambda x:x.sentence_index)
  2227. role2id = {"tenderee": 0, "tenderer": 1}
  2228. for entity in list_entitys[0]:
  2229. if entity.entity_type in ['money'] and entity.label in [0, 1] and entity.values[entity.label]> 0.6:
  2230. text = sentences[entity.sentence_index].sentence_text
  2231. in_att = sentences[entity.sentence_index].in_attachment
  2232. b = entity.wordOffset_begin
  2233. e = entity.wordOffset_end
  2234. context = text[max(0, b - span):b]
  2235. not_found = 1
  2236. for pattern in self.pattern_list:
  2237. ser = re.search(pattern, context)
  2238. if ser:
  2239. groupdict = pattern.split('>')[0].replace('(?P<', '')
  2240. _role, _direct, _prob = groupdict.split('_')
  2241. if re.search('单价', context[-4:]) or re.search('(最低|风险)控制价', context) or float(entity.entity_text)<100:
  2242. _prob = 6
  2243. _label = role2id.get(_role)
  2244. if _label != entity.label:
  2245. continue
  2246. _prob = int(_prob) * 0.1
  2247. # print('规则修改金额概率前:', entity.entity_text, entity.label, entity.values)
  2248. if in_att:
  2249. _prob = max(0.5, _prob - 0.2)
  2250. entity.values[_label] = _prob + entity.values[_label] / 20
  2251. not_found = 0
  2252. # print('规则修改金额概率后:', entity.entity_text, entity.label, entity.values)
  2253. break
  2254. if not_found and entity.values[entity.label] > min_prob:
  2255. if re.search('单价', context[-4:]) or re.search('(最低|风险)控制价', context) or float(entity.entity_text)<100:
  2256. _prob = 0.6
  2257. elif in_att:
  2258. _prob = max(0.5, min_prob - 0.1)
  2259. else:
  2260. _prob = min_prob
  2261. # _prob = min_prob - 0.1 if in_att else min_prob
  2262. entity.values[entity.label] = _prob + entity.values[entity.label] / 20
  2263. # print('找不到规则修改金额概率:', entity.entity_text, entity.label, entity.values)
  2264. # 时间类别
  2265. class TimePredictor():
  2266. def __init__(self,config=None):
  2267. self.sess = tf.Session(graph=tf.Graph(),config=config)
  2268. self.inputs_code = None
  2269. self.outputs_code = None
  2270. self.input_shape = (2,40,128)
  2271. self.load_model()
  2272. def load_model(self):
  2273. model_path = os.path.dirname(__file__)+'/timesplit_model'
  2274. if self.inputs_code is None:
  2275. log("get model of time")
  2276. with self.sess.as_default():
  2277. with self.sess.graph.as_default():
  2278. meta_graph_def = tf.saved_model.loader.load(self.sess, tags=["serve"], export_dir=model_path)
  2279. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  2280. signature_def = meta_graph_def.signature_def
  2281. self.inputs_code = []
  2282. self.inputs_code.append(
  2283. self.sess.graph.get_tensor_by_name(signature_def[signature_key].inputs["input0"].name))
  2284. self.inputs_code.append(
  2285. self.sess.graph.get_tensor_by_name(signature_def[signature_key].inputs["input1"].name))
  2286. self.outputs_code = self.sess.graph.get_tensor_by_name(signature_def[signature_key].outputs["outputs"].name)
  2287. return self.inputs_code, self.outputs_code
  2288. else:
  2289. return self.inputs_code, self.outputs_code
  2290. def search_time_data(self,list_sentences,list_entitys):
  2291. data_x = []
  2292. points_entitys = []
  2293. for list_sentence, list_entity in zip(list_sentences, list_entitys):
  2294. p_entitys = 0
  2295. p_sentences = 0
  2296. list_sentence.sort(key=lambda x: x.sentence_index)
  2297. while(p_entitys<len(list_entity)):
  2298. entity = list_entity[p_entitys]
  2299. if entity.entity_type in ['time']:
  2300. while(p_sentences<len(list_sentence)):
  2301. sentence = list_sentence[p_sentences]
  2302. if entity.doc_id == sentence.doc_id and entity.sentence_index == sentence.sentence_index:
  2303. # left = sentence.sentence_text[max(0,entity.wordOffset_begin-self.input_shape[1]):entity.wordOffset_begin]
  2304. # right = sentence.sentence_text[entity.wordOffset_end:entity.wordOffset_end+self.input_shape[1]]
  2305. s = spanWindow(tokens=sentence.tokens,begin_index=entity.begin_index,end_index=entity.end_index,size=self.input_shape[1])
  2306. left = s[0]
  2307. right = s[1]
  2308. context = [left, right]
  2309. x = self.embedding_words(context, shape=self.input_shape)
  2310. data_x.append(x)
  2311. points_entitys.append(entity)
  2312. break
  2313. p_sentences += 1
  2314. p_entitys += 1
  2315. if len(points_entitys)==0:
  2316. return None
  2317. data_x = np.transpose(np.array(data_x), (1, 0, 2, 3))
  2318. return [data_x, points_entitys]
  2319. def embedding_words(self, datas, shape):
  2320. '''
  2321. @summary:查找词汇对应的词向量
  2322. @param:
  2323. datas:词汇的list
  2324. shape:结果的shape
  2325. @return: array,返回对应shape的词嵌入
  2326. '''
  2327. model_w2v = getModel_w2v()
  2328. embed = np.zeros(shape)
  2329. length = shape[1]
  2330. out_index = 0
  2331. for data in datas:
  2332. index = 0
  2333. for item in data:
  2334. item_not_space = re.sub("\s*", "", item)
  2335. if index >= length:
  2336. break
  2337. if item_not_space in model_w2v.vocab:
  2338. embed[out_index][index] = model_w2v[item_not_space]
  2339. index += 1
  2340. else:
  2341. embed[out_index][index] = model_w2v['unk']
  2342. index += 1
  2343. out_index += 1
  2344. return embed
  2345. def predict(self, list_sentences,list_entitys):
  2346. datas = self.search_time_data(list_sentences, list_entitys)
  2347. if datas is None:
  2348. return
  2349. points_entitys = datas[1]
  2350. with self.sess.as_default():
  2351. predict_y = limitRun(self.sess,[self.outputs_code], feed_dict={self.inputs_code[0]:datas[0][0]
  2352. ,self.inputs_code[1]:datas[0][1]})[0]
  2353. for i in range(len(predict_y)):
  2354. entity = points_entitys[i]
  2355. label = np.argmax(predict_y[i])
  2356. values = []
  2357. for item in predict_y[i]:
  2358. values.append(item)
  2359. if label != 0:
  2360. if not timeFormat(entity.entity_text):
  2361. label = 0
  2362. values[0] = 0.5
  2363. entity.set_Role(label, values)
  2364. # 产品字段提取
  2365. class ProductPredictor():
  2366. def __init__(self,config=None):
  2367. vocabpath = os.path.dirname(__file__) + "/codename_vocab.pk"
  2368. self.vocab = load(vocabpath)
  2369. self.word2index = dict((w, i) for i, w in enumerate(np.array(self.vocab)))
  2370. self.sess = tf.Session(graph=tf.Graph(),config=config)
  2371. self.load_model()
  2372. def load_model(self):
  2373. # model_path = os.path.dirname(__file__)+'/product_savedmodel/product.pb'
  2374. model_path = os.path.dirname(__file__)+'/product_savedmodel/productAndfailreason.pb'
  2375. with self.sess.as_default():
  2376. with self.sess.graph.as_default():
  2377. output_graph_def = tf.GraphDef()
  2378. with open(model_path, 'rb') as f:
  2379. output_graph_def.ParseFromString(f.read())
  2380. tf.import_graph_def(output_graph_def, name='')
  2381. self.sess.run(tf.global_variables_initializer())
  2382. self.char_input = self.sess.graph.get_tensor_by_name('CharInputs:0')
  2383. self.length = self.sess.graph.get_tensor_by_name("Sum:0")
  2384. self.dropout = self.sess.graph.get_tensor_by_name("Dropout:0")
  2385. self.logit = self.sess.graph.get_tensor_by_name("logits/Reshape:0")
  2386. self.tran = self.sess.graph.get_tensor_by_name("crf_loss/transitions:0")
  2387. def decode(self,logits, lengths, matrix):
  2388. paths = []
  2389. small = -1000.0
  2390. # start = np.asarray([[small] * 4 + [0]])
  2391. start = np.asarray([[small]*7+[0]])
  2392. for score, length in zip(logits, lengths):
  2393. score = score[:length]
  2394. pad = small * np.ones([length, 1])
  2395. logits = np.concatenate([score, pad], axis=1)
  2396. logits = np.concatenate([start, logits], axis=0)
  2397. path, _ = viterbi_decode(logits, matrix)
  2398. paths.append(path[1:])
  2399. return paths
  2400. def predict(self, list_sentences,list_entitys=None,list_articles=[], fail=False, MAX_AREA=5000):
  2401. '''
  2402. 预测实体代码,每个句子最多取MAX_AREA个字,超过截断
  2403. :param list_sentences: 多篇公告句子列表,[[一篇公告句子列表],[公告句子列表]]
  2404. :param list_entitys: 多篇公告实体列表
  2405. :param MAX_AREA: 每个句子最多截取多少字
  2406. :return: 把预测出来的实体放进实体类
  2407. '''
  2408. with self.sess.as_default() as sess:
  2409. with self.sess.graph.as_default():
  2410. result = []
  2411. product_list = []
  2412. if fail and list_articles!=[]:
  2413. text_list = [list_articles[0].content[:MAX_AREA]]
  2414. chars = [[self.word2index.get(it, self.word2index.get('<unk>')) for it in text] for text in text_list]
  2415. if USE_API:
  2416. requests_result = requests.post(API_URL + "/predict_product",
  2417. json={"inputs": chars}, verify=True)
  2418. batch_paths = json.loads(requests_result.text)['result']
  2419. lengths = json.loads(requests_result.text)['lengths']
  2420. else:
  2421. lengths, scores, tran_ = sess.run([self.length, self.logit, self.tran],
  2422. feed_dict={
  2423. self.char_input: np.asarray(chars),
  2424. self.dropout: 1.0
  2425. })
  2426. batch_paths = self.decode(scores, lengths, tran_)
  2427. for text, path, length in zip(text_list, batch_paths, lengths):
  2428. tags = ''.join([str(it) for it in path[:length]])
  2429. # 提取产品
  2430. for it in re.finditer("12*3", tags):
  2431. start = it.start()
  2432. end = it.end()
  2433. _entity = Entity(doc_id=list_articles[0].id, entity_id="%s_%s_%s_%s" % (
  2434. list_articles[0].doc_id, 0, start, end),
  2435. entity_text=text[start:end],
  2436. entity_type="product", sentence_index=0,
  2437. begin_index=0, end_index=0, wordOffset_begin=start,
  2438. wordOffset_end=end)
  2439. list_entitys[0].append(_entity)
  2440. product_list.append(text[start:end])
  2441. # 提取失败原因
  2442. for it in re.finditer("45*6", tags):
  2443. start = it.start()
  2444. end = it.end()
  2445. result.append(text[start:end].replace('?', '').strip())
  2446. reasons = []
  2447. for it in result:
  2448. if "(√)" in it or "(√)" in it:
  2449. reasons = [it]
  2450. break
  2451. if reasons != [] and (it not in reasons[-1] and it not in reasons):
  2452. reasons.append(it)
  2453. elif reasons == []:
  2454. reasons.append(it)
  2455. if reasons == []: # 如果模型识别不到失败原因 就用规则补充
  2456. for text in text_list:
  2457. ser1 = re.search('\w{,4}(理由|原因):\s*((第\d+包|标项\d+|原因类型)?[::]?[\s*\w,]{2,30}((不满?足|少于|未达)((法定)?[123一二三两]家|(规定)?要求)|(项目|采购)(终止|废标)),?)+',text)
  2458. ser2 = re.search(
  2459. '\w{,4}(理由|原因):\s*(第\d+包|标项\d+|原因类型)?[::]?[\s*\w]{4,30},', text)
  2460. if ser1:
  2461. reasons.append(ser1.group(0))
  2462. break
  2463. elif ser2:
  2464. reasons.append(ser2.group(0))
  2465. break
  2466. return {'fail_reason':';'.join(reasons)}, product_list
  2467. if list_entitys is None:
  2468. list_entitys = [[] for _ in range(len(list_sentences))]
  2469. for list_sentence, list_entity in zip(list_sentences,list_entitys):
  2470. if len(list_sentence)==0:
  2471. result.append({"product":[]})
  2472. continue
  2473. list_sentence.sort(key=lambda x:len(x.sentence_text), reverse=True)
  2474. _begin_index = 0
  2475. item = {"product":[]}
  2476. temp_list = []
  2477. while True:
  2478. MAX_LEN = len(list_sentence[_begin_index].sentence_text)
  2479. if MAX_LEN > MAX_AREA:
  2480. MAX_LEN = MAX_AREA
  2481. _LEN = MAX_AREA//MAX_LEN
  2482. chars = [sentence.sentence_text[:MAX_LEN] for sentence in list_sentence[_begin_index:_begin_index+_LEN]]
  2483. chars = [[self.word2index.get(it, self.word2index.get('<unk>')) for it in l] for l in chars]
  2484. chars = pad_sequences(chars, maxlen=MAX_LEN, padding="post", truncating="post")
  2485. if USE_API:
  2486. requests_result = requests.post(API_URL + "/predict_product",
  2487. json={"inputs": chars.tolist()}, verify=True)
  2488. batch_paths = json.loads(requests_result.text)['result']
  2489. lengths = json.loads(requests_result.text)['lengths']
  2490. else:
  2491. lengths, scores, tran_ = sess.run([self.length, self.logit, self.tran],
  2492. feed_dict={
  2493. self.char_input: np.asarray(chars),
  2494. self.dropout: 1.0
  2495. })
  2496. batch_paths = self.decode(scores, lengths, tran_)
  2497. for sentence, path, length in zip(list_sentence[_begin_index:_begin_index+_LEN],batch_paths, lengths):
  2498. tags = ''.join([str(it) for it in path[:length]])
  2499. for it in re.finditer("12*3", tags):
  2500. start = it.start()
  2501. end = it.end()
  2502. _entity = Entity(doc_id=sentence.doc_id, entity_id="%s_%s_%s_%s" % (
  2503. sentence.doc_id, sentence.sentence_index, start, end),
  2504. entity_text=sentence.sentence_text[start:end],
  2505. entity_type="product", sentence_index=sentence.sentence_index,
  2506. begin_index=0, end_index=0, wordOffset_begin=start,
  2507. wordOffset_end=end,in_attachment=sentence.in_attachment)
  2508. list_entity.append(_entity)
  2509. temp_list.append(sentence.sentence_text[start:end])
  2510. product_list.append(sentence.sentence_text[start:end])
  2511. # item["product"] = list(set(temp_list))
  2512. # result.append(item)
  2513. if _begin_index+_LEN >= len(list_sentence):
  2514. break
  2515. _begin_index += _LEN
  2516. item["product"] = list(set(temp_list))
  2517. result.append(item) # 修正bug
  2518. return {'fail_reason': ""},product_list
  2519. # 产品数量单价品牌规格提取 #2021/11/10 添加表格中的项目、需求、预算、时间要素提取
  2520. class ProductAttributesPredictor():
  2521. def __init__(self,):
  2522. self.p0 = '(类别|类型|物类|目录|类目|分类)(名称|$)|^品名|^品类|^品目|(标项|分项|项目|计划|包组|标段|[分子]?包|子目|服务|招标|中标|成交|工程|招标内容)(名称|内容|描述)'
  2523. self.p1 = '(标的|维修|系统|报价构成|商品|产品|物料|物资|货物|设备|采购品|采购条目|物品|材料|印刷品?|采购|物装|配件|资产|耗材|清单|器材|仪器|器械|备件|拍卖物|标的物|物件|药品|药材|药械|货品|食品|食材|品目|^品名|气体)[\))的]?([、\w]{,4}名称|内容|描述)'
  2524. self.p2 = '标的|标项|项目$|商品|产品|物料|物资|货物|设备|采购品|采购条目|物品|材料|印刷品|物装|配件|资产|招标内容|耗材|清单|器材|仪器|器械|备件|拍卖物|标的物|物件|药品|药材|药械|货品|食品|食材|菜名|^品目$|^品名$|^名称|^内容$|(标项|分项|项目|计划|包组|标段|[分子]?包|子目|服务|招标|中标|成交|工程|招标内容)(名称|内容|描述)'
  2525. # self.p1 = '(设备|货物|商品|产品|物品|货品|材料|物资|物料|物件|耗材|备件|食材|食品|品目|标的|标的物|标项|资产|拍卖物|仪器|器材|器械|药械|药品|药材|采购品?|项目|招标|工程|服务)[\))]?(名称|内容|描述)'
  2526. # self.p2 = '设备|货物|商品|产品|物品|货品|材料|物资|物料|物件|耗材|备件|食材|食品|品目|标的|标的物|资产|拍卖物|仪器|器材|器械|药械|药品|药材|采购品|项目|品名|菜名|内容|名称'
  2527. with open(os.path.dirname(__file__)+'/header_set.pkl', 'rb') as f:
  2528. self.header_set = pickle.load(f)
  2529. self.tb = TableTag2List()
  2530. def isTrueTable(self, table):
  2531. '''真假表格规则:
  2532. 1、包含<caption>或<th>标签为真
  2533. 2、包含大量链接、表单、图片或嵌套表格为假
  2534. 3、表格尺寸太小为假
  2535. 4、外层<table>嵌套子<table>,一般子为真,外为假'''
  2536. if table.find_all(['caption', 'th']) != []:
  2537. return True
  2538. elif len(table.find_all(['form', 'a', 'img'])) > 5:
  2539. # print('过滤表格:包含链接图片等大于5的为假表格')
  2540. return False
  2541. elif len(table.find_all(['tr'])) < 2:
  2542. # print('过滤表格:行数小于2的为假表格')
  2543. return False
  2544. elif len(table.find_all(['table'])) >= 1:
  2545. # print('过滤表格:包含多个表格的为假表格')
  2546. return False
  2547. else:
  2548. return True
  2549. def getTrs(self, tbody):
  2550. # 获取所有的tr
  2551. trs = []
  2552. objs = tbody.find_all(recursive=False)
  2553. for obj in objs:
  2554. if obj.name == "tr":
  2555. trs.append(obj)
  2556. if obj.name == "tbody":
  2557. for tr in obj.find_all("tr", recursive=False):
  2558. trs.append(tr)
  2559. return trs
  2560. def getTable(self, tbody):
  2561. trs = self.getTrs(tbody)
  2562. inner_table = []
  2563. if len(trs) < 2:
  2564. return inner_table
  2565. for tr in trs:
  2566. tr_line = []
  2567. tds = tr.findChildren(['td', 'th'], recursive=False)
  2568. if len(tds) < 2:
  2569. continue
  2570. for td in tds:
  2571. # td_text = re.sub('\s+|…', ' ', td.get_text()).strip()
  2572. td_text = re.sub('…', '', td.get_text()).strip()
  2573. td_text = td_text.replace("\x06", "").replace("\x05", "").replace("\x07", "").replace('\\', '/').replace('"', '') # 修复272144312 # 产品单价数量提取结果有特殊符号\ 气动执行装置备件\密封组件\NBR+PT
  2574. td_text = td_text.replace("(", "(").replace(")", ")").replace(':', ':')
  2575. tr_line.append(td_text)
  2576. inner_table.append(tr_line)
  2577. return inner_table
  2578. def fixSpan(self, tbody):
  2579. # 处理colspan, rowspan信息补全问题
  2580. trs = self.getTrs(tbody)
  2581. ths_len = 0
  2582. ths = list()
  2583. trs_set = set()
  2584. # 修改为先进行列补全再进行行补全,否则可能会出现表格解析混乱
  2585. # 遍历每一个tr
  2586. for indtr, tr in enumerate(trs):
  2587. ths_tmp = tr.findChildren('th', recursive=False)
  2588. # 不补全含有表格的tr
  2589. if len(tr.findChildren('table')) > 0:
  2590. continue
  2591. if len(ths_tmp) > 0:
  2592. ths_len = ths_len + len(ths_tmp)
  2593. for th in ths_tmp:
  2594. ths.append(th)
  2595. trs_set.add(tr)
  2596. # 遍历每行中的element
  2597. tds = tr.findChildren(recursive=False)
  2598. if len(tds) < 3:
  2599. continue # 列数太少的不补全
  2600. for indtd, td in enumerate(tds):
  2601. # 若有colspan 则补全同一行下一个位置
  2602. if 'colspan' in td.attrs and str(re.sub("[^0-9]", "", str(td['colspan']))) != "":
  2603. col = int(re.sub("[^0-9]", "", str(td['colspan'])))
  2604. if col < 10 and len(td.get_text()) < 500:
  2605. td['colspan'] = 1
  2606. for i in range(1, col, 1):
  2607. td.insert_after(copy.copy(td))
  2608. for indtr, tr in enumerate(trs):
  2609. ths_tmp = tr.findChildren('th', recursive=False)
  2610. # 不补全含有表格的tr
  2611. if len(tr.findChildren('table')) > 0:
  2612. continue
  2613. if len(ths_tmp) > 0:
  2614. ths_len = ths_len + len(ths_tmp)
  2615. for th in ths_tmp:
  2616. ths.append(th)
  2617. trs_set.add(tr)
  2618. # 遍历每行中的element
  2619. tds = tr.findChildren(recursive=False)
  2620. same_span = 0
  2621. if len(tds) > 1 and 'rowspan' in tds[0].attrs:
  2622. span0 = tds[0].attrs['rowspan']
  2623. for td in tds:
  2624. if 'rowspan' in td.attrs and td.attrs['rowspan'] == span0:
  2625. same_span += 1
  2626. if same_span == len(tds):
  2627. continue
  2628. for indtd, td in enumerate(tds):
  2629. # 若有rowspan 则补全下一行同样位置
  2630. if 'rowspan' in td.attrs and str(re.sub("[^0-9]", "", str(td['rowspan']))) != "":
  2631. row = int(re.sub("[^0-9]", "", str(td['rowspan'])))
  2632. td['rowspan'] = 1
  2633. for i in range(1, row, 1):
  2634. # 获取下一行的所有td, 在对应的位置插入
  2635. if indtr + i < len(trs):
  2636. tds1 = trs[indtr + i].findChildren(['td', 'th'], recursive=False)
  2637. if len(tds1) >= (indtd) and len(tds1) > 0:
  2638. if indtd > 0:
  2639. tds1[indtd - 1].insert_after(copy.copy(td))
  2640. else:
  2641. tds1[0].insert_before(copy.copy(td))
  2642. elif len(tds1) > 0 and len(tds1) == indtd - 1:
  2643. tds1[indtd - 2].insert_after(copy.copy(td))
  2644. def get_monthlen(self, year, month):
  2645. '''输入年份、月份 int类型 得到该月份天数'''
  2646. try:
  2647. weekday, num = calendar.monthrange(int(year), int(month))
  2648. except:
  2649. num = 30
  2650. return str(num)
  2651. def fix_time(self, text, html, page_time):
  2652. '''输入日期字段返回格式化日期'''
  2653. for it in [('十二', '12'),('十一', '11'),('十','10'),('九','9'),('八','8'),('七','7'),
  2654. ('六','6'),('五','5'),('四','4'),('三','3'),('二','2'),('一','1')]:
  2655. if it[0] in text:
  2656. text = text.replace(it[0], it[1])
  2657. if re.search('^\d{1,2}月$', text):
  2658. m = re.search('^(\d{1,2})月$', text).group(1)
  2659. if len(m) < 2:
  2660. m = '0' + m
  2661. year = re.search('(\d{4})年(.{,12}采购意向)?', html)
  2662. if year:
  2663. y = year.group(1)
  2664. num = self.get_monthlen(y, m)
  2665. if len(num) < 2:
  2666. num = '0' + num
  2667. order_begin = "%s-%s-01" % (y, m)
  2668. order_end = "%s-%s-%s" % (y, m, num)
  2669. elif page_time != "":
  2670. year = re.search('\d{4}', page_time)
  2671. if year:
  2672. y = year.group(0)
  2673. num = self.get_monthlen(y, m)
  2674. if len(num) < 2:
  2675. num = '0' + num
  2676. order_begin = "%s-%s-01" % (y, m)
  2677. order_end = "%s-%s-%s" % (y, m, num)
  2678. else:
  2679. y = str(datetime.datetime.now().year)
  2680. num = self.get_monthlen(y, m)
  2681. if len(num) < 2:
  2682. num = '0' + num
  2683. order_begin = "%s-%s-01" % (y, m)
  2684. order_end = "%s-%s-%s" % (y, m, num)
  2685. else:
  2686. y = str(datetime.datetime.now().year)
  2687. num = self.get_monthlen(y, m)
  2688. if len(num) < 2:
  2689. num = '0' + num
  2690. order_begin = "%s-%s-01" % (y, m)
  2691. order_end = "%s-%s-%s" % (y, m, num)
  2692. return order_begin, order_end
  2693. t1 = re.search('^(\d{4})(年|/|\.|-)(\d{1,2})月?$', text)
  2694. if t1:
  2695. year = t1.group(1)
  2696. month = t1.group(3)
  2697. num = self.get_monthlen(year, month)
  2698. if len(month)<2:
  2699. month = '0'+month
  2700. if len(num) < 2:
  2701. num = '0'+num
  2702. order_begin = "%s-%s-01" % (year, month)
  2703. order_end = "%s-%s-%s" % (year, month, num)
  2704. return order_begin, order_end
  2705. t2 = re.search('^(\d{4})(年|/|\.|-)(\d{1,2})(月|/|\.|-)(\d{1,2})日?$', text)
  2706. if t2:
  2707. y = t2.group(1)
  2708. m = t2.group(3)
  2709. d = t2.group(5)
  2710. m = '0'+ m if len(m)<2 else m
  2711. d = '0'+d if len(d)<2 else d
  2712. order_begin = order_end = "%s-%s-%s"%(y,m,d)
  2713. return order_begin, order_end
  2714. # 时间样式:"202105"
  2715. t3 = re.search("^(20\d{2})(\d{1,2})$",text)
  2716. if t3:
  2717. year = t3.group(1)
  2718. month = t3.group(2)
  2719. if int(month)>0 and int(month)<=12:
  2720. num = self.get_monthlen(year, month)
  2721. if len(month) < 2:
  2722. month = '0' + month
  2723. if len(num) < 2:
  2724. num = '0' + num
  2725. order_begin = "%s-%s-01" % (year, month)
  2726. order_end = "%s-%s-%s" % (year, month, num)
  2727. return order_begin, order_end
  2728. # 时间样式:"20210510"
  2729. t4 = re.search("^(20\d{2})(\d{2})(\d{2})$", text)
  2730. if t4:
  2731. year = t4.group(1)
  2732. month = t4.group(2)
  2733. day = t4.group(3)
  2734. if int(month) > 0 and int(month) <= 12 and int(day)>0 and int(day)<=31:
  2735. order_begin = order_end = "%s-%s-%s"%(year,month,day)
  2736. return order_begin, order_end
  2737. all_match = re.finditer('^(?P<y1>\d{4})(年|/|\.)(?P<m1>\d{1,2})(?:(月|/|\.)(?:(?P<d1>\d{1,2})日)?)?'
  2738. '(到|至|-)(?:(?P<y2>\d{4})(年|/|\.))?(?P<m2>\d{1,2})(?:(月|/|\.)'
  2739. '(?:(?P<d2>\d{1,2})日)?)?$', text)
  2740. y1 = m1 = d1 = y2 = m2 = d2 = ""
  2741. found_math = False
  2742. for _match in all_match:
  2743. if len(_match.group()) > 0:
  2744. found_math = True
  2745. for k, v in _match.groupdict().items():
  2746. if v!="" and v is not None:
  2747. if k == 'y1':
  2748. y1 = v
  2749. elif k == 'm1':
  2750. m1 = v
  2751. elif k == 'd1':
  2752. d1 = v
  2753. elif k == 'y2':
  2754. y2 = v
  2755. elif k == 'm2':
  2756. m2 = v
  2757. elif k == 'd2':
  2758. d2 = v
  2759. if not found_math:
  2760. return "", ""
  2761. y2 = y1 if y2 == "" else y2
  2762. d1 = '1' if d1 == "" else d1
  2763. d2 = self.get_monthlen(y2, m2) if d2 == "" else d2
  2764. m1 = '0' + m1 if len(m1) < 2 else m1
  2765. m2 = '0' + m2 if len(m2) < 2 else m2
  2766. d1 = '0' + d1 if len(d1) < 2 else d1
  2767. d2 = '0' + d2 if len(d2) < 2 else d2
  2768. order_begin = "%s-%s-%s"%(y1,m1,d1)
  2769. order_end = "%s-%s-%s"%(y2,m2,d2)
  2770. return order_begin, order_end
  2771. def fix_quantity(self, quantity_text, header_quan_unit):
  2772. '''
  2773. 产品数量标准化,统一为数值型字符串
  2774. :param quantity_text: 原始数量字符串
  2775. :param header_quan_unit: 表头数量单位字符串
  2776. :return: 返回数量及单位
  2777. '''
  2778. quantity = quantity_text
  2779. quantity = re.sub('[一壹]', '1', quantity)
  2780. quantity = re.sub('[,,约]|(\d+)', '', quantity)
  2781. ser = re.search('^(\d+\.?\d*)(?([㎡\w/]{,5})', quantity)
  2782. if ser:
  2783. quantity = str(ser.group(1))
  2784. quantity_unit = ser.group(2)
  2785. if quantity_unit == "" and header_quan_unit != "":
  2786. quantity_unit = header_quan_unit
  2787. else:
  2788. quantity = ""
  2789. quantity_unit = ""
  2790. return quantity, quantity_unit
  2791. def find_header(self, items,p0, p1, p2):
  2792. '''
  2793. inner_table 每行正则检查是否为表头,是则返回表头所在列序号,及表头内容
  2794. :param items: 列表,内容为每个td 文本内容
  2795. :param p1: 优先表头正则
  2796. :param p2: 第二表头正则
  2797. :return: 表头所在列序号,是否表头,表头内容
  2798. '''
  2799. items = [re.sub('\s', '', it) for it in items]
  2800. flag = False
  2801. header_dic = {'名称': '', '数量': '', '单位': '', '单价': '', '品牌': '', '规格': '', '需求': '', '预算': '', '时间': '', '总价': '', '品目': '', '参数': '', '采购人':'', '备注':'','发布日期':''}
  2802. product = "" # 产品
  2803. quantity = "" # 数量
  2804. quantity_unit = "" # 数量单位
  2805. unitPrice = "" # 单价
  2806. brand = "" # 品牌
  2807. specs = "" # 规格
  2808. demand = "" # 采购需求
  2809. budget = "" # 预算金额
  2810. order_time = "" # 采购时间
  2811. total_price = "" # 总价
  2812. category = "" # 品目
  2813. parameter = "" # 参数
  2814. tenderee = "" # 采购人
  2815. notes = "" # 备注 2024/3/27 达仁 需求
  2816. issue_date = "" # 发布日期 2024/3/27 达仁 需求
  2817. # for i in range(min(6, len(items))):
  2818. for i in range(len(items)):
  2819. it = items[i]
  2820. if len(it) < 15 and re.search(p0, it) != None:
  2821. flag = True
  2822. if category != "" and category != it:
  2823. continue
  2824. category = it
  2825. header_dic['品目'] = i
  2826. elif len(it) < 15 and re.search(p1, it) != None:
  2827. flag = True
  2828. if product !='' and product != it:
  2829. break
  2830. product = it
  2831. header_dic['名称'] = i
  2832. # break
  2833. # if not flag:
  2834. if product == "":
  2835. # for i in range(min(4, len(items))):
  2836. for i in range(len(items)):
  2837. it = items[i]
  2838. if len(it) < 15 and it != category and re.search(p2, it) and (re.search('^名称|^品名|^品目', it) or re.search(
  2839. '编号|编码|号|情况|报名|单位|位置|地址|数量|单价|价格|金额|品牌|规格类型|型号|公司|中标人|企业|供应商|候选人', it) == None):
  2840. flag = True
  2841. product = it
  2842. header_dic['名称'] = i
  2843. break
  2844. if flag == False and len(items)>3 and re.search('^第[一二三四五六七八九十](包|标段)$', items[0]):
  2845. product = items[0]
  2846. header_dic['名称'] = 0
  2847. flag = True
  2848. if flag:
  2849. # for j in range(i + 1, len(items)):
  2850. for j in range(len(items)):
  2851. if items[j] in [product, category]:
  2852. continue
  2853. if len(items[j]) > 20 and len(re.sub('[\((].*[)\)]|[^\u4e00-\u9fa5]', '', items[j])) > 10:
  2854. continue
  2855. if header_dic['数量']=="" and re.search('数量|采购量', items[j]) and re.search('单价|用途|要求|规格|型号|运输|承运', items[j])==None:
  2856. header_dic['数量'] = j
  2857. quantity = items[j]
  2858. elif header_dic['单位']=="" and re.search('^(数量单位|计量单位|单位)$', items[j]):
  2859. header_dic['单位'] = j
  2860. quantity_unit = items[j]
  2861. elif re.search('单价', items[j]) and re.search('数量|规格|型号|品牌|供应商', items[j])==None:
  2862. header_dic['单价'] = j
  2863. unitPrice = items[j]
  2864. elif re.search('品牌', items[j]):
  2865. header_dic['品牌'] = j
  2866. brand = items[j]
  2867. elif re.search('规格|型号', items[j]):
  2868. header_dic['规格'] = j
  2869. specs = items[j]
  2870. elif re.search('参数', items[j]):
  2871. header_dic['参数'] = j
  2872. parameter = items[j]
  2873. elif re.search('预算单位|(采购|招标|购买)(单位|人|方|主体)|项目业主|采购商|申购单位|需求单位|业主单位',items[j]) and len(items[j])<=8:
  2874. header_dic['采购人'] = j
  2875. tenderee = items[j]
  2876. elif re.search('需求|服务要求|服务标准', items[j]):
  2877. header_dic['需求'] = j
  2878. demand = items[j]
  2879. elif re.search('预算|控制金额', items[j]) and not re.search('预算单位',items[j]):
  2880. header_dic['预算'] = j
  2881. budget = items[j]
  2882. elif re.search('时间|采购实施月份|采购月份|采购日期', items[j]):
  2883. header_dic['时间'] = j
  2884. order_time = items[j]
  2885. elif re.search('总价|(成交|中标|验收|合同|预算|控制|总|合计))?([金总]额|价格?)|最高限价|价格|金额', items[j]) and re.search('数量|规格|型号|品牌|供应商', items[j])==None:
  2886. header_dic['总价'] = j
  2887. total_price = items[j]
  2888. elif re.search('^备\s*注$|资质要求|预留面向中小企业|是否适宜中小企业采购预算预留|公开征集信息', items[j]):
  2889. header_dic['备注'] = j
  2890. notes = items[j]
  2891. elif re.search('^\w{,4}发布(时间|日期)$', items[j]):
  2892. header_dic['发布日期'] = j
  2893. issue_date = items[j]
  2894. if header_dic.get('名称', "") != "" or header_dic.get('品目', "") != "":
  2895. # num = 0
  2896. # for it in (quantity, unitPrice, brand, specs, product, demand, budget, order_time, total_price):
  2897. # if it != "":
  2898. # num += 1
  2899. # if num >=2:
  2900. # return header_dic, flag, (product, quantity, quantity_unit, unitPrice, brand, specs, total_price, category, parameter), (product, demand, budget, order_time)
  2901. if set([quantity, brand, specs, unitPrice, total_price])!=set([""]) or set([demand, budget])!=set([""]):
  2902. return header_dic, flag, (product, quantity, quantity_unit, unitPrice, brand, specs, total_price, category, parameter), (product, demand, budget, order_time,tenderee, notes,issue_date)
  2903. flag = False
  2904. return header_dic, flag, (product, quantity, quantity_unit, unitPrice, brand, specs, total_price, category, parameter), (product, demand, budget, order_time,tenderee,notes,issue_date)
  2905. def predict(self, docid='', html='', page_time=""):
  2906. '''
  2907. 正则寻找table表格内 产品相关信息
  2908. :param html:公告HTML原文
  2909. :return:公告表格内 产品、数量、单价、品牌、规格 ,表头,表头列等信息
  2910. '''
  2911. html = html.replace('<br>', '\n').replace('<br/>', '\n')
  2912. html = re.sub("<html>|</html>|<body>|</body>","",html)
  2913. html = re.sub("##attachment##","",html)
  2914. soup = BeautifulSoup(html, 'lxml')
  2915. # flag_yx = True if re.search('采购意向', html) else False
  2916. flag_yx = True if re.search('采购意向|招标意向|选取意向|意向公告|意向公示|意向公开', html) else False
  2917. tables = soup.find_all(['table'])
  2918. headers = []
  2919. headers_demand = []
  2920. header_col = []
  2921. product_link = []
  2922. demand_link = []
  2923. product_set = set()
  2924. total_product_money = 0
  2925. unit_price_list = [] # 单价列表,用于判断是否重复单价,避免多个表格重复提取造成合计产品价格错误。
  2926. total_price_list = [] # 总价列表,拥有判断是否为几行产品合计总价
  2927. # print('表格数:', len(tables))
  2928. for i in range(len(tables)): # (len(tables)-1, -1, -1) 由从最后到前改为 前到后
  2929. table = tables[i]
  2930. if table.parent.name == 'td' and len(table.find_all('td')) <= 3:
  2931. table.string = table.get_text()
  2932. table.name = 'turntable'
  2933. # print('过滤表格:表格父节点为td,且表格td数量小于等于3')
  2934. continue
  2935. if not self.isTrueTable(table):
  2936. continue
  2937. # self.fixSpan(table)
  2938. # inner_table = self.getTable(table)
  2939. inner_table = self.tb.table2list(table)
  2940. table.extract()
  2941. # print(inner_table)
  2942. i = 0
  2943. found_header = False
  2944. header_quan_unit = "" # 数量表头 包含单位
  2945. header_colnum = 0
  2946. if flag_yx:
  2947. # print('意向公告, 提取意向信息')
  2948. col0_l = []
  2949. col1_l = []
  2950. for tds in inner_table:
  2951. if len(tds) == 2:
  2952. col0_l.append(re.sub('[::]', '', tds[0])) # 处理只有两列的情况
  2953. col1_l.append(tds[1])
  2954. elif len(tds)>=4 and len(inner_table)==2: # 处理只有两行的情况
  2955. col0_l = inner_table[0]
  2956. col1_l = inner_table[1]
  2957. break
  2958. # print(set(col0_l))
  2959. # print('head: ',set(col0_l) & self.header_set)
  2960. if len(set(col0_l) & self.header_set) > len(col0_l) * 0.2 and len(col0_l)==len(col1_l): # 保证两个列数一致
  2961. header_list2 = []
  2962. product = demand = budget = order_begin = order_end = ""
  2963. tenderee = ""
  2964. notes = ''
  2965. issue_date = ''
  2966. for i in range(len(col0_l)):
  2967. if re.search('项目名称', col0_l[i]):
  2968. header_list2.append(col0_l[i])
  2969. product = col1_l[i]
  2970. elif re.search('采购需求|需求概况', col0_l[i]):
  2971. header_list2.append(col0_l[i])
  2972. demand = col1_l[i]
  2973. elif re.search('采购预算|预算金额|控制金额', col0_l[i]):
  2974. header_list2.append(col0_l[i])
  2975. _budget = col1_l[i]
  2976. re_price = re.findall("[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,}|\d[\d,]*(?:\.\d+)?万?", _budget)
  2977. if re_price:
  2978. # _budget = re_price[0]
  2979. # if '万元' in col0_l[i] and '万' not in _budget:
  2980. # _budget += '万元'
  2981. # budget = str(getUnifyMoney(_budget))
  2982. _budget, _money_unit = money_process(_budget, col0_l[i])
  2983. budget = str(_budget)
  2984. if '.' in budget:
  2985. budget = budget.rstrip('0').rstrip('.')
  2986. if float(budget)>= 500*100000000:
  2987. budget = ""
  2988. elif re.search('预算单位|(采购|招标|购买)(单位|人|方|主体)|项目业主|采购商|申购单位|需求单位|业主单位', col0_l[i]):
  2989. header_list2.append(col0_l[i])
  2990. tenderee = re.sub("\s","",col1_l[i])
  2991. if len(tenderee) > 20:
  2992. tenderee = ""
  2993. elif re.search('采购时间|采购实施月份|采购月份|采购日期', col0_l[i]):
  2994. header_list2.append(col0_l[i])
  2995. order_time = col1_l[i].strip()
  2996. order_begin, order_end = self.fix_time(order_time, html, page_time)
  2997. elif re.search('^备\s*注$|资质要求|预留面向中小企业|是否适宜中小企业采购预算预留|公开征集信息', col0_l[i]):
  2998. header_list2.append(col0_l[i])
  2999. notes = col1_l[i].strip()
  3000. elif re.search('^\w{,4}发布(时间|日期)$', col0_l[i]):
  3001. header_list2.append(col0_l[i])
  3002. issue_date = self.fix_time(col1_l[i].strip(), '', '')[0]
  3003. if order_begin != "" and order_end!="":
  3004. order_begin_year = int(order_begin.split("-")[0])
  3005. order_end_year = int(order_end.split("-")[0])
  3006. # 限制附件错误识别时间
  3007. if order_begin_year>=2050 or order_end_year>=2050:
  3008. order_begin = order_end = ""
  3009. # print(product,demand,budget,order_begin)
  3010. if product!= "" and demand != "" and budget!="" and order_begin != "":
  3011. link = {'project_name': product, 'product': [], 'demand': demand, 'budget': budget,
  3012. 'order_begin': order_begin, 'order_end': order_end ,'tenderee':tenderee, 'notes':notes, 'issue_date':issue_date}
  3013. if link not in demand_link:
  3014. demand_link.append(link)
  3015. headers_demand.append('_'.join(header_list2))
  3016. continue
  3017. if len(inner_table)>3 and len(inner_table[0])==2 and len(inner_table[1])==2: # 只有两列且第一列为表头的,行列切换
  3018. col0_l = []
  3019. col1_l = []
  3020. for tds in inner_table:
  3021. if len(tds) == 2:
  3022. col0_l.append(re.sub('[::]', '', tds[0])) # 处理只有两列的情况
  3023. col1_l.append(tds[1])
  3024. else:
  3025. break
  3026. if len(set(col0_l) & self.header_set) > len(col0_l) * 0.5 and len(col0_l) == len(col1_l):
  3027. inner_table = [col0_l, col1_l]
  3028. 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: # 只有两列且第一列为表头的,行列切换
  3029. col0_l = []
  3030. col1_l = []
  3031. col2_l = []
  3032. col3_l = []
  3033. for tds in inner_table:
  3034. if len(tds) == 4 and len(set(tds))>2:
  3035. col0_l.append(re.sub('[::]', '', tds[0])) # 处理只有两列的情况
  3036. col1_l.append(tds[1])
  3037. col2_l.append(re.sub('[::]', '', tds[2])) # 处理只有两列的情况
  3038. col3_l.append(tds[3])
  3039. else:
  3040. break
  3041. 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:
  3042. inner_table = [col0_l+col2_l, col1_l+col3_l]
  3043. while i < (len(inner_table)):
  3044. tds = inner_table[i]
  3045. not_empty = [it for it in tds if re.sub('\s', '', it) != ""]
  3046. if len(set(not_empty))<2 or len(set(tds))<2 or (len(set(tds))==2 and re.search('总计|合计|汇总', tds[0])): # 非空列或者不重复内容小于两列的 继续
  3047. i += 1
  3048. # print('表格产品提取:非空列或者不重复内容小于两列的 继续', i, tds)
  3049. continue
  3050. product = "" # 产品
  3051. quantity = "" # 数量
  3052. quantity_unit = "" # 数量单位
  3053. unitPrice = "" # 单价
  3054. brand = "" # 品牌
  3055. specs = "" # 规格
  3056. demand = "" # 采购需求
  3057. budget = "" # 预算金额
  3058. order_time = "" # 采购时间
  3059. order_begin = ""
  3060. order_end = ""
  3061. total_price = "" # 总金额
  3062. parameter = "" # 参数
  3063. tenderee = "" # 采购人
  3064. notes = '' # 备注
  3065. issue_date = '' # 发布日期
  3066. if len(set([re.sub('[::\s]','',td) for td in tds]) & self.header_set) > len(tds) * 0.4:
  3067. # if len(set(tds) & self.header_set) > len(tds) * 0.2:
  3068. header_dic, found_header, header_list, header_list2 = self.find_header(tds, self.p0, self.p1, self.p2)
  3069. if found_header:
  3070. header_colnum = len(tds) # 保存表头所在行列数
  3071. # print('发现表头:', header_colnum, header_dic)
  3072. if found_header and isinstance(header_list, tuple) and len(header_list) > 2: # 获取表头中的 数量单位
  3073. quantity_header = header_list[1].replace('单位:', '')
  3074. if re.search('(([\w/]{,5}))', quantity_header):
  3075. header_quan_unit = re.search('(([\w/]{,5}))', quantity_header).group(1)
  3076. else:
  3077. header_quan_unit = ""
  3078. if found_header and ('_'.join(header_list) not in headers or '_'.join(header_list2) not in headers_demand):# and len(headers)<1: # 只保留出现的第一个表头
  3079. headers.append('_'.join(header_list))
  3080. headers_demand.append('_'.join(header_list2))
  3081. header_col.append('_'.join(tds))
  3082. i += 1
  3083. # print('表头数量占行列数0.4倍不做内容匹配', set([re.sub('[::]','',td) for td in tds]) & self.header_set, tds)
  3084. continue
  3085. elif found_header:
  3086. if len(tds) > header_colnum or len(tds)-1<max([it for it in header_dic.values() if it!=""]): # 表头、属性列数不一致跳过
  3087. i += 1
  3088. # print('表头、属性列数不一致跳过', len(tds), header_colnum, tds)
  3089. continue
  3090. id0 = header_dic.get('品目', "")
  3091. id1 = header_dic.get('名称', "")
  3092. id2 = header_dic.get('数量', "")
  3093. id2_2 = header_dic.get('单位', "")
  3094. id3 = header_dic.get('单价', "")
  3095. id4 = header_dic.get('品牌', "")
  3096. id5 = header_dic.get('规格', "")
  3097. id6 = header_dic.get('需求', "")
  3098. id7 = header_dic.get('预算', "")
  3099. id8 = header_dic.get('时间', "")
  3100. id9 = header_dic.get("总价", "")
  3101. id10 = header_dic.get('参数', "")
  3102. id11 = header_dic.get('采购人', "")
  3103. id12 = header_dic.get('备注', "")
  3104. id13 = header_dic.get('发布日期', "")
  3105. not_attr = 0
  3106. for k, v in header_dic.items():
  3107. if isinstance(v, int):
  3108. if v >= len(tds) or tds[v] in self.header_set:
  3109. # print('内容属性在表头集合里面', tds[v], v >= len(tds))
  3110. not_attr = 1
  3111. # break
  3112. if not_attr>=2: # 只要属性里面有两项为表头,停止匹配
  3113. i += 1
  3114. found_header = False
  3115. # print('只要属性里面有两项为表头,停止匹配')
  3116. continue
  3117. if id1!="" and re.search('[a-zA-Z\u4e00-\u9fa5]', tds[id1]) and tds[id1] not in self.header_set and \
  3118. re.search('备注|汇总|合计|总价|价格|金额|^详见|无$|xxx', tds[id1]) == None:
  3119. product = tds[id1]
  3120. if id0!="" and re.search('[a-zA-Z\u4e00-\u9fa5]', tds[id0]) and tds[id0] not in self.header_set and \
  3121. re.search('备注|汇总|合计|总价|价格|金额|^详见|无$|xxx', tds[id0]) == None:
  3122. category = tds[id0]
  3123. product = "%s_%s"%(category, product) if product!="" and product!=category else category
  3124. if product != "" and product not in ['工程类', '服务类', '货物类', '工程', '服务', '货物']:
  3125. # print('匹配产品内容: ', product)
  3126. if id2 != "":
  3127. if re.search('\d+|[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十]', tds[id2]):
  3128. # if re.search('(^\d{,3}(,?\d{3}){2,}(\.\d{2,7},?)$)|万?元', tds[id2]): # 254816100 这篇数量很大,貌似正常
  3129. # i += 1
  3130. # print('过滤:数量包含金额单位或值很大类似金额', tds[id2])
  3131. # continue
  3132. quantity = tds[id2]
  3133. elif re.search('\w{5,}', tds[id2]) and re.search('^详见|^详情', tds[id2])==None:
  3134. i += 1
  3135. # print('过滤:数量包含五个字符以上且不包含^详见|^详情等字符', tds[id2])
  3136. continue
  3137. if id2_2 != "":
  3138. if re.search('^\w{1,4}$', tds[id2_2]) and re.search('元', tds[id2_2])==None:
  3139. quantity_unit = tds[id2_2]
  3140. if id3 != "":
  3141. if re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', tds[id3]):
  3142. unitPrice = tds[id3]
  3143. elif re.search('^[\d,.亿万元人民币欧美日金额:()();;、,\n]+$|¥|¥|RMB|USD|EUR|JPY|CNY|元$', tds[id3].strip()):
  3144. unitPrice = tds[id3]
  3145. elif len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\d,.]', '', tds[id3])) > 5 and re.search('^详见|^详情', tds[id3])==None:
  3146. i += 1
  3147. # print('过滤:产品单价包含金额外的字符数大于5个', tds[id3])
  3148. continue
  3149. if id4 != "":
  3150. if re.search('\w', tds[id4]):
  3151. brand = tds[id4]
  3152. if re.match('^详见|^详情', brand.strip()):
  3153. brand = ""
  3154. else:
  3155. brand = ""
  3156. if id5 != "":
  3157. if re.search('\w', tds[id5]):
  3158. specs = tds[id5][:500] # 限制最多500字
  3159. if re.match('^详见|^详情', specs.strip()):
  3160. specs = ""
  3161. else:
  3162. specs = ""
  3163. if id6 != "":
  3164. if re.search('\w', tds[id6]):
  3165. demand = tds[id6]
  3166. else:
  3167. demand = ""
  3168. if id7 != "":
  3169. if re.search('\d+|[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', tds[id7]):
  3170. budget = tds[id7]
  3171. if id8 != "":
  3172. if re.search('\w', tds[id8]):
  3173. order_time = tds[id8].strip()
  3174. order_begin, order_end = self.fix_time(order_time, html, page_time)
  3175. if id9 != "":
  3176. if re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', tds[id9]):
  3177. total_price = tds[id9]
  3178. elif re.search('^[\d,.亿万元人民币欧美日金额:()();;、,\n]+$|¥|¥|RMB|USD|EUR|JPY|CNY|元$', tds[id9].strip()):
  3179. total_price = tds[id9]
  3180. elif len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\d,.]', '', tds[id9])) > 5 and re.search('^详见|^详情', tds[id9])==None:
  3181. i += 1
  3182. # print('过滤:产品总价包含金额外的字符数大于5个', tds[id9])
  3183. continue
  3184. if id10 != "":
  3185. parameter = tds[id10][:500]
  3186. if re.match('^详见|^详情', parameter.strip()):
  3187. parameter = ""
  3188. if id11 != "":
  3189. tenderee = re.sub("\s","",tds[id11])
  3190. if len(tenderee) > 30:
  3191. tenderee = ""
  3192. if id12 != "":
  3193. notes = tds[id12].strip()
  3194. if id13 != "":
  3195. issue_date = self.fix_time(tds[id13].strip(), '', '')[0]
  3196. # print('数量:{0}, 单价:{1}, 品牌:{2}, 规格:{3},总价:{4}'.format(quantity ,unitPrice, brand, specs, total_price))
  3197. if quantity != "" or unitPrice != "" or brand != "" or specs != "" or total_price or '单价' in header_dic or '总价' in header_dic:
  3198. 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
  3199. products = re.split('[;;、,\n]+', tds[id1])
  3200. quantitys = re.split('[;;、,\n]+', tds[id2])
  3201. unitPrices = re.split('[;;、,\n]+', tds[id3])
  3202. total_prices = re.split('[;;、,\n]+', total_price)
  3203. brands = re.split('[;;、,\n]+', brand) if re.search('等$', brand)==None else [brand]
  3204. specses = re.split('[;;、,\n]+', specs) if re.search('等$', specs)==None else [specs]
  3205. parameters = re.split('[;;、,\n]+', parameter) if re.search('等$', parameter)==None else [parameter]
  3206. unitPrices = [""]*len(products) if len(unitPrices)==1 else unitPrices
  3207. total_prices = [""]*len(products) if len(total_prices)==1 else total_prices
  3208. brands = brands*len(products) if len(brands)==1 else brands
  3209. specses = specses*len(products) if len(specses)==1 else specses
  3210. brands = [brand]*len(products) if len(brands) < len(products) else brands
  3211. specses = [specs] * len(products) if len(specses) < len(products) else specses
  3212. parameters = parameters*len(products) if len(parameters)==1 else parameters
  3213. # print('产品拆分:', len(products),len(quantitys) , len(unitPrices),len(brands),len(specses))
  3214. if len(products) == len(quantitys) == len(unitPrices) == len(brands) == len(specses):
  3215. for product, quantity, unitPrice, brand, specs, total_price, parameter in zip(products,quantitys,unitPrices, brands, specses, total_prices, parameters):
  3216. if quantity != "":
  3217. quantity, quantity_unit_ = self.fix_quantity(quantity, header_quan_unit)
  3218. quantity_unit = quantity_unit_ if quantity_unit_ != "" else quantity_unit
  3219. if unitPrice != "":
  3220. unitPrice, _money_unit = money_process(unitPrice, header_list[3])
  3221. unitPrice = str(unitPrice) if unitPrice != 0 and unitPrice<100000000 else ""
  3222. if budget != "":
  3223. budget, _money_unit = money_process(budget, header_list2[2])
  3224. budget = str(budget) if budget != 0 and budget<50000000000 else ''
  3225. if total_price != "":
  3226. total_price, _money_unit = money_process(total_price, header_list[6])
  3227. total_price_list.append(total_price)
  3228. total_price = str(total_price) if total_price != 0 and total_price<50000000000 else ""
  3229. link = {'product': product, 'quantity': quantity,
  3230. 'quantity_unit': quantity_unit, 'unitPrice': unitPrice,
  3231. 'brand': brand[:50], 'specs': specs, 'total_price': total_price, 'parameter': parameter}
  3232. # if link not in product_link:
  3233. # product_link.append(link)
  3234. # mat = re.match('([0-9.,]+)[((]?\w{,3}[))]?$', link['quantity'])
  3235. # if link['unitPrice'] != "" and mat:
  3236. # try:
  3237. # total_product_money += float(link['unitPrice']) * float(
  3238. # mat.group(1).replace(',', '')) if float(
  3239. # mat.group(1).replace(',', '')) < 50000 else 0
  3240. # except:
  3241. # log('产品属性单价数量相乘出错, 单价: %s, 数量: %s' % (
  3242. # link['unitPrice'], link['quantity']))
  3243. if (product, specs, unitPrice, quantity) not in product_set:
  3244. product_set.add((product, specs, unitPrice, quantity))
  3245. product_link.append(link)
  3246. if link['unitPrice'] != "" and link['quantity'] != '':
  3247. try:
  3248. total_product_money += float(link['unitPrice']) * float(
  3249. link['quantity']) if float(link['quantity']) < 50000 else 0
  3250. except:
  3251. log('产品属性单价数量相乘出错, 单价: %s, 数量: %s' % (
  3252. link['unitPrice'], link['quantity']))
  3253. elif len(product)>100: # 产品名称长于100字
  3254. i += 1
  3255. # print('过滤: 产品名称长于100字',)
  3256. continue
  3257. else:
  3258. if quantity != "":
  3259. quantity, quantity_unit_ = self.fix_quantity(quantity, header_quan_unit)
  3260. quantity_unit = quantity_unit_ if quantity_unit_ != "" else quantity_unit
  3261. if unitPrice != "":
  3262. unitPrice, _money_unit = money_process(unitPrice, header_list[3])
  3263. unitPrice = str(unitPrice) if unitPrice != 0 and unitPrice<100000000 else ""
  3264. if budget != "":
  3265. budget, _money_unit = money_process(budget, header_list2[2])
  3266. budget = str(budget) if budget != 0 and budget<50000000000 else ''
  3267. if total_price != "":
  3268. total_price, _money_unit = money_process(total_price, header_list[6])
  3269. total_price_list.append(total_price)
  3270. total_price = str(total_price) if total_price != 0 and total_price<50000000000 else ""
  3271. link = {'product': product, 'quantity': quantity, 'quantity_unit': quantity_unit, 'unitPrice': unitPrice,
  3272. 'brand': brand[:50], 'specs':specs, 'total_price': total_price, 'parameter': parameter}
  3273. # if link not in product_link:
  3274. # product_link.append(link)
  3275. # mat = re.match('([0-9.,]+)[((]?\w{,3}[))]?$', link['quantity'])
  3276. # if link['unitPrice'] != "" and mat:
  3277. # try:
  3278. # total_product_money += float(link['unitPrice'])*float(mat.group(1).replace(',', '')) if float(mat.group(1).replace(',', ''))<50000 else 0
  3279. # except:
  3280. # log('产品属性单价数量相乘出错, 单价: %s, 数量: %s'%(link['unitPrice'], link['quantity']))
  3281. # if (product, unitPrice, quantity) not in product_set:
  3282. # product_set.add((product, unitPrice, quantity))
  3283. if (product, unitPrice,) not in product_set: # 2023/09/22 改为只判断产品/单价,只要两个一样就不作为新产品 避免多个表格重复表达有些没数量造成重复提取 353858683
  3284. product_set.add((product, unitPrice))
  3285. product_link.append(link)
  3286. if link['unitPrice']:
  3287. unit_price_list.append(link['unitPrice'])
  3288. if link['unitPrice'] != "" and link['quantity'] != '':
  3289. try:
  3290. total_product_money += float(link['unitPrice'])*float(link['quantity']) if float(link['quantity'])<50000 else 0
  3291. except:
  3292. log('产品属性单价数量相乘出错, 单价: %s, 数量: %s'%(link['unitPrice'], link['quantity']))
  3293. if order_begin != "" and order_end != "":
  3294. order_begin_year = int(order_begin.split("-")[0])
  3295. order_end_year = int(order_end.split("-")[0])
  3296. # 限制附件错误识别时间
  3297. if order_begin_year >= 2050 or order_end_year >= 2050:
  3298. order_begin = order_end = ""
  3299. # print(budget,order_time)
  3300. if budget != "" and order_time != "":
  3301. 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}
  3302. if link not in demand_link:
  3303. demand_link.append(link)
  3304. i += 1
  3305. else:
  3306. i += 1
  3307. if len(total_price_list)>1 and len(set(total_price_list))/len(total_price_list)<=0.5: # 2023/7/27 总价一半以上重复的为多行一个总价,需去掉
  3308. # print('总价一半以上重复的为多行一个总价,需去掉', total_price_list)
  3309. for link in product_link: # 预防最后一列总价为所有产品总价,列补全后所有产品总价一样情况
  3310. if 'total_price' in link:
  3311. link['total_price'] = ""
  3312. 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 如果单价重复率高不算总产品价避免错误
  3313. # print('如果单价重复率高不算总产品价避免错误')
  3314. total_product_money = 0
  3315. # for link in product_link:
  3316. # if 'unitPrice' in link:
  3317. # link['unitPrice'] = ""
  3318. if len(product_link)>0:
  3319. attr_dic = {'product_attrs':{'data':product_link, 'header':headers, 'header_col':header_col}}
  3320. else:
  3321. attr_dic = {'product_attrs': {'data': [], 'header': [], 'header_col': []}}
  3322. if len(demand_link)>0:
  3323. demand_dic = {'demand_info':{'data':demand_link, 'header':headers_demand, 'header_col':header_col}}
  3324. else:
  3325. demand_dic = {'demand_info':{'data':[], 'header':[], 'header_col':[]}}
  3326. # print('表格产品属性提取:', attr_dic)
  3327. return [attr_dic, demand_dic], total_product_money
  3328. def predict_without_table(self,product_attrs,list_sentences,list_entitys,codeName,prem, html='', page_time=""):
  3329. if len(prem[0]['prem'])==1:
  3330. list_sentences[0].sort(key=lambda x:x.sentence_index)
  3331. list_sentence = list_sentences[0]
  3332. list_entity = list_entitys[0]
  3333. _data = product_attrs[1]['demand_info']['data']
  3334. re_bidding_time = re.compile("(采购|采购实施|预计招标)(时间|月份|日期)[::,].{0,2}$")
  3335. order_times = []
  3336. for entity in list_entity:
  3337. if entity.entity_type=='time':
  3338. sentence = list_sentence[entity.sentence_index]
  3339. s = spanWindow(tokens=sentence.tokens, begin_index=entity.begin_index,
  3340. end_index=entity.end_index,size=20)
  3341. entity_left = "".join(s[0])
  3342. if re.search(re_bidding_time,entity_left):
  3343. time_text = entity.entity_text.strip()
  3344. standard_time = re.compile("((?P<year>\d{4}|\d{2})\s*[-\/年\.]\s*(?P<month>\d{1,2})\s*[-\/月\.]\s*((?P<day>\d{1,2})日?)?)")
  3345. time_match = re.search(standard_time,time_text)
  3346. # print(time_text, time_match)
  3347. if time_match:
  3348. time_text = time_match.group()
  3349. order_times.append(time_text)
  3350. # print(order_times)
  3351. order_times = [tuple(self.fix_time(order_time, html, page_time)) for order_time in order_times]
  3352. order_times = [order_time for order_time in order_times if order_time[0]!=""]
  3353. if len(set(order_times))==1:
  3354. order_begin,order_end = order_times[0]
  3355. project_name = codeName[0]['name']
  3356. pack_info = [pack for pack in prem[0]['prem'].values()]
  3357. budget = pack_info[0].get('tendereeMoney',0)
  3358. product = prem[0]['product']
  3359. link = {'project_name': project_name, 'product': product, 'demand': project_name, 'budget': budget,
  3360. 'order_begin': order_begin, 'order_end': order_end}
  3361. _data.append(link)
  3362. product_attrs[1]['demand_info']['data'] = _data
  3363. # print('predict_without_table: ', product_attrs)
  3364. return product_attrs
  3365. def predict_by_text(self,product_attrs,html,list_outlines,product_list,page_time=""):
  3366. product_entity_list = list(set(product_list))
  3367. list_outline = list_outlines[0]
  3368. get_product_attrs = False
  3369. for _outline in list_outline:
  3370. if re.search("信息|情况|清单|概况",_outline.outline_summary):
  3371. outline_text = _outline.outline_text
  3372. outline_text = outline_text.replace(_outline.outline_summary,"")
  3373. key_value_list = [_split for _split in re.split("[,。;]",outline_text) if re.search("[::]",_split)]
  3374. if not key_value_list:
  3375. continue
  3376. head_list = []
  3377. head_value_list = []
  3378. for key_value in key_value_list:
  3379. key_value = re.sub("^[一二三四五六七八九十]{1,3}[、.]|^[\d]{1,2}[、.]\d{,2}|^[\((]?[一二三四五六七八九十]{1,3}[\))][、]?","",key_value)
  3380. temp = re.split("[::]",key_value)
  3381. if len(temp)>2:
  3382. if temp[0] in head_list:
  3383. key = temp[0]
  3384. value = "".join(temp[1:])
  3385. else:
  3386. key = temp[-2]
  3387. value = temp[-1]
  3388. else:
  3389. key = temp[0]
  3390. value = temp[1]
  3391. key = re.sub("^[一二三四五六七八九十]{1,3}[、.]|^[\d]{1,2}[、.]\d{,2}|^[\((]?[一二三四五六七八九十]{1,3}[\))][、]?","",key)
  3392. head_list.append(key)
  3393. head_value_list.append(value)
  3394. head_set = set(head_list)
  3395. # print('head_set',head_set)
  3396. if len(head_set & self.header_set) > len(head_set)*0.2:
  3397. loop_list = []
  3398. begin_list = [0]
  3399. for index,head in enumerate(head_list):
  3400. if head not in loop_list:
  3401. if re.search('第[一二三四五六七八九十](包|标段)', head) and re.search('第[一二三四五六七八九十](包|标段)', '|'.join(loop_list)):
  3402. begin_list.append(index)
  3403. loop_list = []
  3404. loop_list.append(head)
  3405. else:
  3406. loop_list.append(head)
  3407. else:
  3408. begin_list.append(index)
  3409. loop_list = []
  3410. loop_list.append(head)
  3411. headers = []
  3412. headers_demand = []
  3413. header_col = []
  3414. product_link = []
  3415. demand_link = []
  3416. product_set = set()
  3417. for idx in range(len(begin_list)):
  3418. if idx==len(begin_list)-1:
  3419. deal_list = head_value_list[begin_list[idx]:]
  3420. tmp_head_list = head_list[begin_list[idx]:]
  3421. else:
  3422. deal_list = head_value_list[begin_list[idx]:begin_list[idx+1]]
  3423. tmp_head_list = head_list[begin_list[idx]:begin_list[idx+1]]
  3424. product = "" # 产品
  3425. quantity = "" # 数量
  3426. quantity_unit = "" # 单位
  3427. unitPrice = "" # 单价
  3428. brand = "" # 品牌
  3429. specs = "" # 规格
  3430. demand = "" # 采购需求
  3431. budget = "" # 预算金额
  3432. order_time = "" # 采购时间
  3433. order_begin = ""
  3434. order_end = ""
  3435. total_price = "" # 总金额
  3436. parameter = "" # 参数
  3437. header_dic, found_header, header_list, header_list2 = self.find_header(tmp_head_list, self.p0, self.p1,self.p2)
  3438. if found_header:
  3439. headers.append('_'.join(header_list))
  3440. headers_demand.append('_'.join(header_list2))
  3441. header_col.append('_'.join(tmp_head_list))
  3442. # print('header_dic: ',header_dic)
  3443. id0 = header_dic.get('品目', "")
  3444. id1 = header_dic.get('名称', "")
  3445. id2 = header_dic.get('数量', "")
  3446. id2_2 = header_dic.get('单位', "")
  3447. id3 = header_dic.get('单价', "")
  3448. id4 = header_dic.get('品牌', "")
  3449. id5 = header_dic.get('规格', "")
  3450. id6 = header_dic.get('需求', "")
  3451. id7 = header_dic.get('预算', "")
  3452. id8 = header_dic.get('时间', "")
  3453. id9 = header_dic.get("总价", "")
  3454. id10 = header_dic.get('参数', "")
  3455. if id1!='' and re.search('[a-zA-Z\u4e00-\u9fa5]', deal_list[id1]) and deal_list[id1] not in self.header_set and \
  3456. re.search('备注|汇总|合计|总价|价格|金额|公司|附件|详见|无$|xxx', deal_list[id1]) == None:
  3457. product = deal_list[id1]
  3458. if id0 != "" and re.search('[a-zA-Z\u4e00-\u9fa5]', deal_list[id0]) and deal_list[id0] not in self.header_set and \
  3459. re.search('备注|汇总|合计|总价|价格|金额|公司|附件|详见|无$|xxx', deal_list[id0]) == None:
  3460. category = deal_list[id0]
  3461. product = "%s_%s" % (category, product) if product != "" else category
  3462. if product == "":
  3463. # print(deal_list[id4],deal_list[id5],tmp_head_list,deal_list)
  3464. if (id4 != "" and deal_list[id4] != "") or (id5 != "" and deal_list[id5] != ""):
  3465. for head,value in zip(tmp_head_list,deal_list):
  3466. if value and value in product_entity_list:
  3467. product = value
  3468. break
  3469. if product != "":
  3470. if id2 != "":
  3471. if re.search('\d+|[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十]', deal_list[id2]):
  3472. quantity = deal_list[id2]
  3473. quantity = re.sub('[()(),,约]', '', quantity)
  3474. quantity = re.sub('[一壹]', '1', quantity)
  3475. ser = re.search('^(\d+(?:\.\d+)?)([㎡\w/]{,5})', quantity)
  3476. if ser:
  3477. quantity = str(ser.group(1))
  3478. quantity_unit = ser.group(2)
  3479. if float(quantity)>=10000*10000:
  3480. quantity = ""
  3481. quantity_unit = ""
  3482. else:
  3483. quantity = ""
  3484. quantity_unit = ""
  3485. if id2_2 != "":
  3486. if re.search('^\w{1,4}$', deal_list[id2_2]):
  3487. quantity_unit = deal_list[id2_2]
  3488. else:
  3489. quantity_unit = ""
  3490. # if id2 != "":
  3491. # if re.search('\d+|[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十]', deal_list[id2]):
  3492. # quantity = deal_list[id2]
  3493. # else:
  3494. # quantity = ""
  3495. if id3 != "":
  3496. if re.search('\d+|[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', deal_list[id3]):
  3497. _unitPrice = deal_list[id3]
  3498. re_price = re.findall("[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,}|\d[\d,]*(?:\.\d+)?万?",_unitPrice)
  3499. if re_price:
  3500. # _unitPrice = re_price[0]
  3501. # if '万元' in header_list[3] and '万' not in _unitPrice:
  3502. # _unitPrice += '万元'
  3503. # unitPrice = getUnifyMoney(_unitPrice)
  3504. # if unitPrice>=10000*10000:
  3505. # unitPrice = ""
  3506. # unitPrice = str(unitPrice)
  3507. _unitPrice, _money_unit = money_process(_unitPrice, header_list[3])
  3508. if _unitPrice >= 10000 * 10000:
  3509. _unitPrice = ""
  3510. unitPrice = str(_unitPrice)
  3511. if '.' in unitPrice:
  3512. unitPrice = unitPrice.rstrip('0').rstrip('.')
  3513. if id4 != "":
  3514. if re.search('\w', deal_list[id4]):
  3515. brand = deal_list[id4]
  3516. if re.match('^详见|^详情', brand.strip()):
  3517. brand = ""
  3518. else:
  3519. brand = ""
  3520. if id5 != "":
  3521. if re.search('\w', deal_list[id5]):
  3522. specs = deal_list[id5][:500]
  3523. if re.match('^详见|^详情', specs.strip()):
  3524. brand = ""
  3525. else:
  3526. specs = ""
  3527. if id6 != "":
  3528. if re.search('\w', deal_list[id6]):
  3529. demand = deal_list[id6]
  3530. else:
  3531. demand = ""
  3532. if id7 != "":
  3533. if re.search('\d+|[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', deal_list[id7]):
  3534. _budget = deal_list[id7]
  3535. re_price = re.findall("[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,}|\d[\d,]*(?:\.\d+)?万?",_budget)
  3536. if re_price:
  3537. # _budget = re_price[0]
  3538. # if '万元' in header_list2[2] and '万' not in _budget:
  3539. # _budget += '万元'
  3540. # budget = str(getUnifyMoney(_budget))
  3541. _budget, _money_unit = money_process(_budget, header_list2[2])
  3542. budget = str(_budget)
  3543. if '.' in budget:
  3544. budget = budget.rstrip('0').rstrip('.')
  3545. if float(budget)>= 100000*10000:
  3546. budget = ""
  3547. if id8 != "":
  3548. if re.search('\w', deal_list[id8]) and re.search("(采购|采购实施|预计招标)(时间|月份|日期)",header_list2[3]):
  3549. order_time = deal_list[id8].strip()
  3550. order_begin, order_end = self.fix_time(order_time, html, page_time)
  3551. if id9 != "":
  3552. if re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,}', deal_list[id9]):
  3553. total_price = deal_list[id9]
  3554. elif re.search('^[\d,.亿万元人民币欧美日金额:()();;、,\n]+$', deal_list[id9].strip()):
  3555. total_price = deal_list[id9]
  3556. if id10 != "":
  3557. parameter = deal_list[id10][:500]
  3558. if re.match('^详见|^详情', parameter.strip()):
  3559. parameter = ""
  3560. if quantity != "" or unitPrice != "" or brand != "" or specs != "" or total_price:
  3561. if id1 != "" and id2 != "" and id3 != "" and len(re.split('[;;、,\n]', deal_list[id2])) > 1 and len(
  3562. re.split('[;;、,\n]', deal_list[id1])) == len(re.split('[;;、,\n]', deal_list[id2])): # 处理一个空格包含多个产品,逗号或空格分割情况 例子 292846806 292650743
  3563. products = re.split('[;;、,\n]', deal_list[id1])
  3564. quantitys = re.split('[;;、,\n]', deal_list[id2])
  3565. unitPrices = re.split('[;;、,\n]', deal_list[id3])
  3566. total_prices = re.split('[;;、,\n]', total_price)
  3567. brands = re.split('[;;、,\n]', brand) if re.search('等$', brand) == None else [brand]
  3568. specses = re.split('[;;、,\n]', specs) if re.search('等$', specs) == None else [specs]
  3569. parameters = re.split('[;;、,\n]', parameter) if re.search('等$', parameter) == None else [parameter]
  3570. unitPrices = [""] * len(products) if len(unitPrices) == 1 else unitPrices
  3571. total_prices = [""] * len(products) if len(total_prices) == 1 else total_prices
  3572. brands = brands * len(products) if len(brands) == 1 else brands
  3573. specses = specses * len(products) if len(specses) == 1 else specses
  3574. parameters = parameters * len(products) if len(parameters) == 1 else parameters
  3575. if len(products) == len(quantitys) == len(unitPrices) == len(brands) == len(
  3576. specses):
  3577. for product, quantity, unitPrice, brand, specs, total_price, parameter in zip(
  3578. products, quantitys, unitPrices, brands, specses, total_prices,
  3579. parameters):
  3580. if quantity != "":
  3581. quantity, quantity_unit_ = self.fix_quantity(quantity,quantity_unit)
  3582. quantity_unit = quantity_unit_ if quantity_unit_ != "" else quantity_unit
  3583. if unitPrice != "":
  3584. unitPrice, _money_unit = money_process(unitPrice, header_list[3])
  3585. unitPrice = str(unitPrice) if unitPrice != 0 and unitPrice<100000000 else ""
  3586. if budget != "":
  3587. budget, _money_unit = money_process(budget, header_list2[2])
  3588. budget = str(budget) if budget != 0 and budget<50000000000 else ''
  3589. if total_price != "":
  3590. total_price, _money_unit = money_process(total_price,
  3591. header_list[6])
  3592. total_price = str(total_price) if total_price != 0 and total_price<50000000000 else ""
  3593. link = {'product': product, 'quantity': quantity,
  3594. 'quantity_unit': quantity_unit, 'unitPrice': unitPrice,
  3595. 'brand': brand[:50], 'specs': specs, 'total_price': total_price,
  3596. 'parameter': parameter}
  3597. if (product, specs, unitPrice, quantity) not in product_set:
  3598. product_set.add((product, specs, unitPrice, quantity))
  3599. product_link.append(link)
  3600. # if link['unitPrice'] != "" and link['quantity'] != '':
  3601. # try:
  3602. # total_product_money += float(link['unitPrice']) * float(
  3603. # link['quantity']) if float(
  3604. # link['quantity']) < 50000 else 0
  3605. # except:
  3606. # log('产品属性单价数量相乘出错, 单价: %s, 数量: %s' % (
  3607. # link['unitPrice'], link['quantity']))
  3608. elif len(unitPrice) > 15 or len(product) > 100: # 单价大于15位数或 产品名称长于100字
  3609. # i += 1
  3610. continue
  3611. else:
  3612. if quantity != "":
  3613. quantity, quantity_unit_ = self.fix_quantity(quantity, quantity_unit)
  3614. quantity_unit = quantity_unit_ if quantity_unit_ != "" else quantity_unit
  3615. if unitPrice != "":
  3616. unitPrice, _money_unit = money_process(unitPrice, header_list[3])
  3617. unitPrice = str(unitPrice) if unitPrice != 0 and unitPrice<100000000 else ""
  3618. if budget != "":
  3619. budget, _money_unit = money_process(budget, header_list2[2])
  3620. budget = str(budget) if budget != 0 and budget<50000000000 else ''
  3621. if total_price != "":
  3622. total_price, _money_unit = money_process(total_price, header_list[6])
  3623. total_price = str(total_price) if total_price != 0 and total_price<50000000000 else ""
  3624. link = {'product': product, 'quantity': quantity,
  3625. 'quantity_unit': quantity_unit, 'unitPrice': unitPrice,
  3626. 'brand': brand[:50], 'specs': specs, 'total_price': total_price,
  3627. 'parameter': parameter}
  3628. if (product, specs, unitPrice, quantity) not in product_set:
  3629. product_set.add((product, specs, unitPrice, quantity))
  3630. product_link.append(link)
  3631. # if link['unitPrice'] != "" and link['quantity'] != '':
  3632. # try:
  3633. # total_product_money += float(link['unitPrice']) * float(
  3634. # link['quantity']) if float(link['quantity']) < 50000 else 0
  3635. # except:
  3636. # log('产品属性单价数量相乘出错, 单价: %s, 数量: %s' % (
  3637. # link['unitPrice'], link['quantity']))
  3638. if order_begin != "" and order_end != "":
  3639. order_begin_year = int(order_begin.split("-")[0])
  3640. order_end_year = int(order_end.split("-")[0])
  3641. # 限制附件错误识别时间
  3642. if order_begin_year >= 2050 or order_begin_year < 2000 or order_end_year >= 2050 or order_end_year < 2000:
  3643. order_begin = order_end = ""
  3644. # print(budget, order_time)
  3645. if budget != "" and order_time != "":
  3646. link = {'project_name': product, 'product': [], 'demand': demand, 'budget': budget,
  3647. 'order_begin': order_begin, 'order_end': order_end}
  3648. if link not in demand_link:
  3649. demand_link.append(link)
  3650. if len(product_link) > 0:
  3651. attr_dic = {'product_attrs': {'data': product_link, 'header': list(set(headers)), 'header_col': list(set(header_col))}}
  3652. get_product_attrs = True
  3653. else:
  3654. attr_dic = {'product_attrs': {'data': [], 'header': [], 'header_col': []}}
  3655. if len(demand_link) > 0:
  3656. demand_dic = {'demand_info': {'data': demand_link, 'header': headers_demand, 'header_col': header_col}}
  3657. else:
  3658. demand_dic = {'demand_info': {'data': [], 'header': [], 'header_col': []}}
  3659. product_attrs[0] = attr_dic
  3660. if len(product_attrs[1]['demand_info']['data']) == 0:
  3661. product_attrs[1] = demand_dic
  3662. if get_product_attrs:
  3663. break
  3664. # print('predict_by_text: ', product_attrs)
  3665. return product_attrs
  3666. def add_product_attrs(self,channel_dic, product_attrs, list_sentences,list_entitys,list_outlines,product_list,codeName,prem,text,page_time):
  3667. # print(1,product_attrs[1]['demand_info']['data'])
  3668. if channel_dic['docchannel']['docchannel']=="采购意向" and len(product_attrs[1]['demand_info']['data']) == 0:
  3669. product_attrs = self.predict_without_table(product_attrs, list_sentences,list_entitys,codeName,prem,text,page_time)
  3670. # print(2,product_attrs[1]['demand_info']['data'])
  3671. if len(product_attrs[0]['product_attrs']['data']) == 0:
  3672. product_attrs = self.predict_by_text(product_attrs,text,list_outlines,product_list,page_time)
  3673. # print(3,product_attrs[1]['demand_info']['data'])
  3674. if len(product_attrs[1]['demand_info']['data'])>0:
  3675. for d in product_attrs[1]['demand_info']['data']:
  3676. for product in set(prem[0]['product']):
  3677. if product in d['project_name'] and product not in d['product']:
  3678. d['product'].append(product) #把产品在项目名称中的添加进需求要素中
  3679. # docchannel类型提取
  3680. class DocChannel():
  3681. def __init__(self, life_model='/channel_savedmodel/channel.pb', type_model='/channel_savedmodel/doctype.pb',config=None):
  3682. self.lift_sess, self.lift_title, self.lift_content, self.lift_prob, self.lift_softmax,\
  3683. self.mask, self.mask_title = self.load_life(life_model,config)
  3684. self.type_sess, self.type_title, self.type_content, self.type_prob, self.type_softmax,\
  3685. self.type_mask, self.type_mask_title = self.load_type(type_model)
  3686. self.sequen_len = 200 # 150 200
  3687. self.title_len = 30
  3688. self.sentence_num = 10
  3689. self.kws = '供货商|候选人|供应商|入选人|项目|选定|预告|中标|成交|补遗|延期|报名|暂缓|结果|意向|出租|补充|合同|限价|比选|指定|工程|废标|取消|中止|流标|资质|资格|地块|招标|采购|货物|租赁|计划|宗地|需求|来源|土地|澄清|失败|探矿|预审|变更|变卖|遴选|撤销|意见|恢复|采矿|更正|终止|废置|报建|流拍|供地|登记|挂牌|答疑|中选|受让|拍卖|竞拍|审查|入围|更改|条件|洽谈|乙方|后审|控制|暂停|用地|询价|预'
  3690. lb_type = ['采招数据', '土地矿产', '拍卖出让', '产权交易', '新闻资讯']
  3691. lb_life = ['采购意向', '招标预告', '招标公告', '招标答疑', '公告变更', '资审结果', '中标信息', '合同公告', '废标公告']
  3692. self.id2type = {k: v for k, v in enumerate(lb_type)}
  3693. self.id2life = {k: v for k, v in enumerate(lb_life)}
  3694. self.load_pattern()
  3695. def load_pattern(self):
  3696. self.type_dic = {
  3697. '土地矿产': '供地结果|(土地|用地|宗地|地块|海域|矿)的?(基本信息|基本情况|概况|信息|详情|来源|用途|性质|编号|位置|坐落|使用年限|出让年限)|(土地|山地|农田)(经营权)?(出让|出租|招租|租赁|承包|流转)|流转土地',
  3698. '拍卖出让': '(拍卖|变卖|流拍|竞拍)的?(公告|活动|信息|结果|成交|主体|标的|资产|财产|方式|类型|流程|程序|规则|价格|保证金|时间)|(公开|进行|密封)(拍卖|变卖|竞拍)|第[一二三]次拍卖|(资产|司法|网络)拍卖|交易方式.{,2}拍卖|拍卖会',
  3699. '产权交易': '(产权|资产|权证)的?(类型|类别|用途|性质|状态|信息|名称|编号|(基本)?情况)|(经营权|承包权|使用权|租赁权|股权|债权|排污权|化学需氧量|储备量)(挂牌|转让|出让)|竞价销售|销售结果|房屋所有权房产|免租期限|交易期限|(受让|转让|承租|出租)(人|方)|(店面|店铺|商铺|铺位?|门面|门市|食堂|饭堂|校舍|车位|停车场|厂?房|仓?库|馆|资产|物业|房产|房屋|场地|农田|鱼?塘)\w{,4}(处置|招租|出租|续租|租赁|转让)|(出租|转让|产权|资产)(项目|中标|成交|流标|废标)|出租(用途|类型)|转让底价|租赁(标的物|情况)|看[样货](时间|地[点址]|方式|仓库|验货)|最小加价|加价[幅梯]度|交易模式[::\s]*延时竞价销售|挂牌(开始|结束)时间',
  3700. '采招数据': '(采购|招标)(条件|范围|文件|内容)|(申请人|投标人|供应商|报价人|参选人)的?资格要求;|采购需求清单|最低价排序|竞争性采购方式|采购进行公开竞价|竞价模式[::\s]*一次报价|预算金额' # |变更|答疑|澄清|中标|成交|合同|废标|流标 |(采购|招标|代理)(人|机构|单位)|
  3701. }
  3702. self.title_type_dic = {
  3703. '土地矿产': '(土地|用地|宗地|荒地|山地|海域|矿)(出让|出租|招租|租赁|承包|流转|使用权|经营权|征收|划拨|中标|成交)|供地结果|矿业权|探矿权|采矿权|(土地|用地|宗地|地块)(使用权)?(终止|中止|网上)?(挂牌|出让|拍卖|招拍|划拨)|征收土地',
  3704. '拍卖出让': '(拍卖|变卖|流拍|竞拍)的?(公告|公示)|拍卖|变卖|流拍|竞拍',
  3705. '产权交易': '经营权|承包权|使用权|租赁权|股权|债权|排污权|化学需氧量|储备量|竞价销售|销售结果|出租|招租|拍租|竞租|续租|挂牌|出让',
  3706. '采招数据': '(采购|招标|询价|议价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|征询|调研)的?(公告|公示|中标|成交|结果|$)|工程招标|定点服务|竞价采购|(设备|服务)采购|网上超市采购|定点采购',
  3707. # |竞价 采招/产权都有竞价方式 # 意向|需求|预公?告|报建|总承包|工程|施工|设计|勘察|代理|监理 |变更|答疑|澄清|中标|成交|合同|废标|流标
  3708. '新闻资讯': '(考试|面试|笔试)成绩|成绩的?(公告|公示|公布)|公开招聘|招聘(公告|简章|启事|合同制)|疫情防控\s{,5}(通知|情况|提示)|行政审批结果'
  3709. }
  3710. self.life_dic = {
  3711. '采购意向': '采购意向|招标意向|选取意向|意向公告|意向公示',
  3712. '采购意向neg': '发布政府采购意向|采购意向公告已于',
  3713. '招标预告': '(预计|计划)(采购|招标)(时间|日期)|采购(计划编号|需求方案|预告|预案)|(预|需求)公示|需求(方案|信息|论证|公告|公示)',
  3714. '招标公告': '(采购|招标|竞选|报名)条件|报名(时间|流程|方法|要求|\w{,5}材料)[:\s]|[^\w]成交规则|参加竞价采购交易资格|(申请人|投标人|供应商|报价人|参选人)的?资格要求|获取(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|竞谈|应答)文件|(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|竞谈|应答)文件的?(获取|领取)|评选方式:?\s*价格最低',
  3715. '资审结果': '资审及业绩公示|资审结果及业绩|资格后审情况报告|资格(后审|预审|审查)结果(公告|公示)|(预审|审查)工作已经?结束|未通过原因', #|资格
  3716. '招标答疑': '现澄清(为|如下)|答疑补遗|澄清内容如下|第[0-9一二三四五]次澄清|答疑澄清|(最高(投标)?限价|控制价|拦标价)公示', # |异议的回复
  3717. '公告变更': '第[\d一二]次变更|(更正|变更)(公告|公示|信息|内容|事项|原因|理由|日期|时间|如下)|原公告((主要)?(信息|内容)|发布时间)|(变更|更正)[前后]内容|现?在?(变更|更正|修改|更改)(内容)?为|(公告|如下|信息|内容|事项|结果|文件|发布|时间|日期)(更正|变更)',
  3718. '公告变更neg': '履约变更内容',
  3719. '候选人公示': '候选人公示|评标结果公示|中标候选人名单公示|现将中标候选人(进行公示|公[示布]如下)|(中标|中选)候选人(信息|情况)[::\s]',
  3720. '候选人公示neg': '中标候选人公示期|中标候选人公示前',
  3721. '中标信息': '供地结果信息|采用单源直接采购的?情况说明|[特现]?将\w{,4}(成交|中标|中选|选定结果|选取结果|入围结果|竞价结果)\w{,4}(进行公示|公[示布]如下)|(询价|竞价|遴选)?(成交|中标|中选)(公告|公示)|(成交|中标|中选|选定|选取|入围|询价)结果(如下|公告|公示)|(中标|中选)(供应商|承包商|候选人|入围单位)如下|拟定供应商的情况|((中标|中选)(人|成交)|成交)\w{,3}(信息|情况)[::\s]',
  3722. '中标信息2': '\s(成交|中标|中选)(信息|日期|时间|总?金额|价格)[::\s]|(成交|中标|中选)价格\s*[\d.,]+(?万?元|(采购|招标|成交|中标|中选|评标)结果|单一来源(采购|招标)?的?(中标|成交|结果)|项目已结束|中标公示 ', # |单一来源采购原因|拟采取单一来源方式采购|单一来源采购公示
  3723. '中标信息3': '(中标|中选|成交|拟定|拟选用|最终选定的?|受让)(供应商|供货商|服务商|机构|企业|公司|单位|候选人|人)(信息[,:]?)?(名称)?[::\s]|[、\s](第一名|(拟定|推荐|入围)?(供应商|供货商)|(中选|中标|供货)单位|中选人)[::\s]|确定[\w()]{6,25}为中标人', # |唯一
  3724. '中标信息neg': '按项目控制价下浮\d%即为成交价|成交原则|不得确定为(中标|成交)|招标人按下列原则选择中标人|评选成交供应商:|拟邀请供应商|除单一来源采购项目外|单一来源除外|(各.{,5}|尊敬的)(供应商|供货商)[:\s]|竞拍起止时间:|询价结果[\s\n::]*不公开|本项目已具备招标条件|现对该项目进行招标公告|发布\w{2}结果后\d天内送达|本次\w{2}结果不对外公示|供应商\s*资格要求|成交情况:\s*[流废]标|中标单位:本次招标拟?中标单位\d家|通知中标单位|影响(成交|中标)结果|确定为成交供应商|(成交|中标|中选)公[告示](发布|\w{,2})后|竞价成交后', # 503076535 按照服务方案的优劣 确定为成交供应商
  3725. # |确定成交供应商[:,\s]
  3726. '合同公告': '合同(公告|公示|信息|内容)|合同(编号|名称|主体|基本情况|完成(日期|时间))|(供应商乙方|乙方供应商):|合同总?金额|履约信息',
  3727. '废标公告': '(终止|中止|废标|流标|流采|失败|作废|异常|撤销)(结果)?(公告|公示|招标|采购|竞价)|(谈判结果为|结果类型):?废标|((本|该)(项目|标段|合同|合同包|采购包|次)\w{,5})((失败|终止|流标|废标)|予以废标|(按|做|作)?(流标|废标|废置)处理)|(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|竞谈|应答|项目)(终止|中止|废标|流标|失败|作废|异常|撤销)',
  3728. '废标公告2': '(无效|中止|终止|废标|流标|失败|作废|异常|撤销)的?(原因|理由)|本项目因故取消|本(项目|次)(公开)?\w{2}失败|已终止\s*原因:|(人|人数|供应商|单位)(不足|未达\w{,3}数量)|已终止|不足[3三]家|无(废标)|成交情况:\s*[流废]标|现予以废置',
  3729. '废标公告neg': '超过此报价将作为[废流]标处理|否则按[废流]标处理|终止规则:|成交规则:|视为流标|竞价失败的一切其他情形|是否废标:否|若不足三家公司参与|供应商数量:?\s*报名供应商不足三家|有效报价不足三家,\s*系统自动废标' # 503076535 供应商数量: 报名供应商不足三家。
  3730. }
  3731. self.title_life_dic = {
  3732. '采购意向': '采购意向|招标意向|选取意向|意向公告|意向公示|意向公开',
  3733. '招标预告': '预公?告|预公示|报建公告|(批前|标前)公示|(供应|招标)计划表?$|(论证|征求|征集)(供应商)?意见|意见征询|需求评审公告|需求(公告|公示|意见)',
  3734. '公告变更': '第[\d一二]次变更|(变更|更正(事项)?|更改|延期|暂停)(招标|采购)?的?(公告|公示|通知)|变更$|更正$',
  3735. '招标答疑': '质疑|澄清|答疑(文件)?|补遗书?|(最高(投标)?限价|控制价|拦标价)(公示|公告|$)',
  3736. '废标公告': '(终止|中止|废标|废除|废置|流标|失败|作废|异常|撤销|撤回|取消成?交?|流拍)(结果|竞价|项目)?的?(公告|公示|$)|(终止|中止)(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|拍卖|招租|交易|出让)|关于废置',
  3737. '合同公告': '(合同(成交|变更)?)(公告|公示|信息|公式|公开|签订)|合同备案|合同书|合同$', # |(履约|验收)(结果)?
  3738. '候选人公示': '候选人(变更)?公示|评标(结果)?公示|中标前?公示|中标预公示|评审结果',
  3739. '中标信息': '(中标|中选|中价|中租|成交|入选|确认)(候选人|人|供应商|记录|结果|变更)?(公告|公示|结果)|未?入围(公示|公告)|(遴选|采购|招标|竞价|议价|比选|询比?价|评选|谈判|邀标|邀请|洽谈|约谈|评标|发包|遴选|交易)\w{,2}结果|单一来源(采购|招标)?的?(中标|成交|结果)|中标通知书|中标$|项目中标', # |开标(记录|信息|情况)
  3740. '资审结果': '((资格|资质)(审查|预审|后审|审核)|资审)结果(公告|公示)?|(资质|资格)(预审|后审)公示|资审及业绩公示',
  3741. '招标公告': '(采购|招标|询价|议价|竞价|比价|比选|遴选|邀请|邀标|磋商|洽谈|约谈|谈判|拍卖|招租|交易|出让)的?(公告|公示|$)|公开(采购|招标|招租|拍卖|挂牌|出让)|(资审|预审|后审)公告',
  3742. '开标记录': '开标记录|截标信息|评委名单公示|开标安排|开标数据表|开标信息|开标情况|开标一览表|开标结果|开标会',
  3743. '验收合同': '(验收|履约)(公告|公示)|(验收|履约)(结果|报告|意见|单)(公告|公示)'
  3744. }
  3745. def load_life(self,life_model,config):
  3746. with tf.Graph().as_default() as graph:
  3747. output_graph_def = graph.as_graph_def()
  3748. with open(os.path.dirname(__file__)+life_model, 'rb') as f:
  3749. output_graph_def.ParseFromString(f.read())
  3750. tf.import_graph_def(output_graph_def, name='')
  3751. # print("%d ops in the final graph" % len(output_graph_def.node))
  3752. del output_graph_def
  3753. sess = tf.Session(graph=graph,config=config)
  3754. sess.run(tf.global_variables_initializer())
  3755. inputs = sess.graph.get_tensor_by_name('inputs/inputs:0')
  3756. prob = sess.graph.get_tensor_by_name('inputs/dropout:0')
  3757. title = sess.graph.get_tensor_by_name('inputs/title:0')
  3758. mask = sess.graph.get_tensor_by_name('inputs/mask:0')
  3759. mask_title = sess.graph.get_tensor_by_name('inputs/mask_title:0')
  3760. # logit = sess.graph.get_tensor_by_name('output/logit:0')
  3761. softmax = sess.graph.get_tensor_by_name('output/softmax:0')
  3762. return sess, title, inputs, prob, softmax, mask, mask_title
  3763. def load_type(self,type_model):
  3764. with tf.Graph().as_default() as graph:
  3765. output_graph_def = graph.as_graph_def()
  3766. with open(os.path.dirname(__file__)+type_model, 'rb') as f:
  3767. output_graph_def.ParseFromString(f.read())
  3768. tf.import_graph_def(output_graph_def, name='')
  3769. # print("%d ops in the final graph" % len(output_graph_def.node))
  3770. del output_graph_def
  3771. sess = tf.Session(graph=graph)
  3772. sess.run(tf.global_variables_initializer())
  3773. inputs = sess.graph.get_tensor_by_name('inputs/inputs:0')
  3774. prob = sess.graph.get_tensor_by_name('inputs/dropout:0')
  3775. title = sess.graph.get_tensor_by_name('inputs/title:0')
  3776. mask = sess.graph.get_tensor_by_name('inputs/mask:0')
  3777. mask_title = sess.graph.get_tensor_by_name('inputs/mask_title:0')
  3778. # logit = sess.graph.get_tensor_by_name('output/logit:0')
  3779. softmax = sess.graph.get_tensor_by_name('output/softmax:0')
  3780. return sess, title, inputs, prob, softmax, mask, mask_title
  3781. def predict_process(self, docid='', doctitle='', dochtmlcon=''):
  3782. # print('准备预处理')
  3783. def get_kw_senten(s, span=10):
  3784. doc_sens = []
  3785. tmp = 0
  3786. num = 0
  3787. end_idx = 0
  3788. for it in re.finditer(self.kws, s): # '|'.join(keywordset)
  3789. left = s[end_idx:it.end()].split()
  3790. right = s[it.end():].split()
  3791. tmp_seg = s[tmp:it.start()].split()
  3792. if len(tmp_seg) > span or tmp == 0:
  3793. doc_sens.append(' '.join(left[-span:] + right[:span]))
  3794. end_idx = it.end() + 1 + len(' '.join(right[:span]))
  3795. tmp = it.end()
  3796. num += 1
  3797. if num >= self.sentence_num:
  3798. break
  3799. if doc_sens == []:
  3800. doc_sens.append(s)
  3801. return doc_sens
  3802. def word2id(wordlist, max_len=self.sequen_len):
  3803. ids = [getIndexOfWords(w) for w in wordlist]
  3804. ids = ids[:max_len] if len(ids) >= max_len else ids + [0] * (max_len - len(ids))
  3805. assert len(ids) == max_len
  3806. return ids
  3807. cost_time = dict()
  3808. datas = []
  3809. datas_title = []
  3810. try:
  3811. segword_title = ' '.join(selffool.cut(doctitle)[0])
  3812. segword_content = dochtmlcon
  3813. except:
  3814. segword_content = ''
  3815. segword_title = ''
  3816. if isinstance(segword_content, float):
  3817. segword_content = ''
  3818. if isinstance(segword_title, float):
  3819. segword_title = ''
  3820. segword_content = segword_content.replace(' 中 选 ', ' 中选 ').replace(' 中 标 ', ' 中标 ').replace(' 补 遗 ', ' 补遗 '). \
  3821. replace(' 更 多', '').replace(' 更多', '').replace(' 中 号 ', ' 中标 ').replace(' 中 选人 ', ' 中选人 '). \
  3822. replace(' 点击 下载 查看', '').replace(' 咨询 报价 请 点击', '').replace('终结', '终止')
  3823. segword_title = re.sub('[^\s\u4e00-\u9fa5]', '', segword_title)
  3824. segword_content = re.sub('[^\s\u4e00-\u9fa5]', '', segword_content)
  3825. doc_word_list = segword_content.split()
  3826. if len(doc_word_list) > self.sequen_len / 2:
  3827. doc_sens = get_kw_senten(' '.join(doc_word_list[100:500]))
  3828. doc_sens = ' '.join(doc_word_list[:100]) + '\n' + '\n'.join(doc_sens)
  3829. else:
  3830. doc_sens = ' '.join(doc_word_list[:self.sequen_len])
  3831. # print('标题:',segword_title)
  3832. # print('正文:',segword_content)
  3833. datas.append(doc_sens.split())
  3834. datas_title.append(segword_title.split())
  3835. # print('完成预处理')
  3836. return datas, datas_title
  3837. def is_houxuan(self, title, content):
  3838. '''
  3839. 通过标题和中文内容判断是否属于候选人公示类别
  3840. :param title: 公告标题
  3841. :param content: 公告正文文本内容
  3842. :return: 1 是候选人公示 ;0 不是
  3843. '''
  3844. if re.search('候选人的?公示|评标结果|评审结果|中标公示', title): # (中标|成交|中选|入围)
  3845. if re.search('变更公告|更正公告|废标|终止|答疑|澄清', title):
  3846. return 0
  3847. return 1
  3848. if re.search('候选人的?公示', content[:100]):
  3849. if re.search('公示(期|活动)?已经?结束|公示期已满|中标结果公告|中标结果公示|变更公告|更正公告|废标|终止|答疑|澄清', content[:100]):
  3850. return 0
  3851. return 1
  3852. else:
  3853. return 0
  3854. def predict(self, title='', list_sentence='', web_source_no='', original_docchannel=''):
  3855. not_extract_dic = {
  3856. 104: '招标文件',
  3857. 106: '法律法规',
  3858. 107: '新闻资讯',
  3859. 108: '拟建项目',
  3860. 109: '展会推广',
  3861. 110: '企业名录',
  3862. 111: '企业资质',
  3863. 112: '全国工程人员',
  3864. 113: '业主采购'
  3865. }
  3866. if original_docchannel in not_extract_dic:
  3867. return {'docchannel': {'docchannel':'', 'doctype':not_extract_dic[original_docchannel], "original_docchannel_id": str(original_docchannel)}}
  3868. if web_source_no in ['02104-7']:
  3869. return {'docchannel': {'docchannel':'', 'doctype':'采招数据'}}
  3870. if isinstance(list_sentence, list):
  3871. token_l = [it.tokens for it in list_sentence]
  3872. tokens = [it for l in token_l for it in l]
  3873. content = ' '.join(tokens[:500])
  3874. title = re.sub('[^\u4e00-\u9fa5]', '', title)
  3875. if len(title)>50:
  3876. title = title[:20]+title[-30:]
  3877. data_content, data_title = self.predict_process(docid='', doctitle=title[-50:], dochtmlcon=content) # 标题最多取50字
  3878. text_len = len(data_content[0]) if len(data_content[0])<self.sequen_len else self.sequen_len
  3879. title_len = len(data_title[0]) if len(data_title[0])<self.title_len else self.title_len
  3880. result = {'docchannel': {'docchannel':'', 'doctype':'', "original_docchannel_id": str(original_docchannel)}}
  3881. array_content = embedding(data_content, shape=(len(data_content), self.sequen_len, 128))
  3882. array_title = embedding(data_title, shape=(len(data_title), self.title_len, 128))
  3883. pred = self.type_sess.run(self.type_softmax,
  3884. feed_dict={
  3885. self.type_title: array_title,
  3886. self.type_content: array_content,
  3887. self.type_mask:[[0]*text_len+[1]*(self.sequen_len-text_len)],
  3888. self.type_mask_title:[[0]*title_len+[1]*(self.title_len-title_len)],
  3889. self.type_prob:1}
  3890. )
  3891. id = np.argmax(pred, axis=1)[0]
  3892. prob = pred[0][id]
  3893. result['docchannel']['doctype'] = self.id2type[id]
  3894. # print('公告类别:', self.id2type[id], '概率:',prob)
  3895. # if id == 0:
  3896. if result['docchannel']['doctype'] not in ['', '新闻资讯']:
  3897. pred = self.lift_sess.run(self.lift_softmax,
  3898. feed_dict={
  3899. self.lift_title: array_title,
  3900. self.lift_content: array_content,
  3901. self.mask: [[0] * text_len + [1] * (self.sequen_len - text_len)],
  3902. self.mask_title: [[0] * title_len + [1] * (self.title_len - title_len)],
  3903. self.lift_prob:1}
  3904. )
  3905. id = np.argmax(pred, axis=1)[0]
  3906. prob = pred[0][id]
  3907. result['docchannel']['docchannel'] = self.id2life[id]
  3908. # print('生命周期:纯模型预测',self.id2life[id], '概率:',prob)
  3909. # if id == 6:
  3910. if result['docchannel']['docchannel'] == '中标信息':
  3911. if self.is_houxuan(''.join([it for it in title if it.isalpha()]), ''.join([it for it in content if it.isalpha()])):
  3912. result['docchannel']['docchannel'] = '候选人公示'
  3913. # return '候选人公示', prob
  3914. # return [{'docchannel': '候选人公示'}]
  3915. return result
  3916. # return [{'docchannel':self.id2life[id]}]
  3917. # else:
  3918. # # return self.id2type[id], prob
  3919. # return [{'docchannel':self.id2type[id]}]
  3920. def predict_rule(self, title, content, channel_dic, prem_dic):
  3921. '''2022/2/10加入规则去除某些数据源及内容过短且不包含类别关键词的公告不做预测'''
  3922. hetong = '(合同|验收|履约)(公告|公示)|合同号?$' # 合同标题正则
  3923. zhongbiao_t = '(中标|中选|成交|入选|入围|结果|确认)(公告|公示|结果)|(遴选|采购|招标|竞价|议价|比选|询价|评选|谈判|邀标|邀请|洽谈|约谈|评标|发包|遴选)结果|开标(记录|信息|情况)|单一来源|直接(选取|选定)|中标通知书|中标$'
  3924. zhongbiao_c = '(中标|中选|成交|拟选用|拟邀请|最终选定的?|拟定)(供应商|供货商|服务商|企业|公司|单位|(候选)?人)(名称)?[::]|[,。:.](供应商|供货商|服务商)(名称)?:|指定的中介服务机构:|建设服务单位:'
  3925. zhaobiao_t = '(遴选|采购|招标|竞价|议价|比选|询价|评选|谈判|邀标|邀请|洽谈|约谈)(公告|公示|$)'
  3926. title_cn = re.sub('[^\u4e00-\u9fa5]', '', title)
  3927. if len(re.sub('[^\u4e00-\u9fa5]', "", content))<50 and channel_dic['docchannel']['doctype'] != '新闻资讯':
  3928. if re.search(hetong, title_cn) != None:
  3929. channel_dic['docchannel']['docchannel'] = '合同公告'
  3930. elif re.search(zhongbiao_t, title_cn):
  3931. channel_dic['docchannel']['docchannel'] = '中标信息'
  3932. elif re.search(zhaobiao_t, title_cn):
  3933. channel_dic['docchannel']['docchannel'] = '招标公告'
  3934. else:
  3935. channel_dic['docchannel']['docchannel'] = ''
  3936. elif channel_dic['docchannel'].get('docchannel', '') == '招标公告' and 'win_tenderer' in json.dumps(prem_dic,
  3937. ensure_ascii=False):
  3938. if re.search(hetong, title_cn) != None:
  3939. channel_dic['docchannel']['docchannel'] = '合同公告'
  3940. log('正则把招标公告修改为合同公告')
  3941. elif re.search(zhongbiao_t, title_cn) or re.search(zhongbiao_t, content[:200]) or re.search(zhongbiao_c,
  3942. content):
  3943. channel_dic['docchannel']['docchannel'] = '中标信息'
  3944. log('正则把招标公告修改为中标信息')
  3945. elif channel_dic['docchannel'].get('docchannel', '') == '中标信息' and 'win_tenderer' not in json.dumps(prem_dic,
  3946. ensure_ascii=False):
  3947. if re.search(hetong, title_cn):
  3948. channel_dic['docchannel']['docchannel'] = '合同公告'
  3949. log('正则把中标信息修改为合同公告')
  3950. elif re.search(zhongbiao_t, title_cn) or re.search(zhongbiao_t, content[:200]) or re.search(zhongbiao_c,
  3951. content):
  3952. pass
  3953. elif re.search(zhaobiao_t, title_cn):
  3954. channel_dic['docchannel']['docchannel'] = '招标公告'
  3955. log('正则把中标信息修改为招标公告')
  3956. elif re.search('中标|成交|中选|入选|入围|结果|供应商|供货商|候选人', title_cn+content)==None:
  3957. channel_dic['docchannel']['docchannel'] = ''
  3958. log('正则把中标信息修改为空')
  3959. return channel_dic
  3960. def predict_merge(self, title, list_sentence, html, bidway, prem, original_docchannel='', web_source_no=''):
  3961. '''
  3962. 正则,模型混合预测,返回公告类型及生命周期
  3963. :param title: 公告标题
  3964. :param content: 预处理后的返回的句子实体列表 list_sentence
  3965. :param html: 公告原文 html 内容
  3966. :param bidway: 招标方式
  3967. :param prem: 提取的prem 字典
  3968. :return: {'docchannel': {'docchannel':'中标信息', 'doctype':'采招数据'}} 字典格式
  3969. '''
  3970. def cut_single_cn_space(text):
  3971. new_text = ""
  3972. for w in text.split():
  3973. if len(w) == 1 or re.search('^[\u4e00-\u9fa5][::]', w):
  3974. new_text += w
  3975. else:
  3976. new_text += ' ' + w
  3977. return new_text
  3978. def html2text(html):
  3979. ser = re.search('<div[^<>]*richTextFetch', html)
  3980. # if ser and len(re.sub('[^\u4e00-\u9fa5]', '', html[:ser.start()]))>500:
  3981. # html = html[:ser.start()]+'##richTextFetch##'
  3982. if ser:
  3983. if len(re.sub('[^\u4e00-\u9fa5]', '', html[:ser.start()])) > 200:
  3984. html = html[:ser.start()] + '##richTextFetch##'
  3985. else:
  3986. html = html[:ser.start() + 500]
  3987. text = re.sub('<[^<]*?>', '', html).replace('&nbsp;', ' ')
  3988. # text = re.sub('http[0-9a-zA-Z-.:/]+|[0-9a-zA-Z-./@]+', '', text)
  3989. text = re.sub('\s+', ' ', text)
  3990. # text = re.sub('[/|[()()]', '', text)
  3991. text = cut_single_cn_space(text)
  3992. return text[:20000]
  3993. def count_diffser(pattern, text):
  3994. num = 0
  3995. kw = []
  3996. for p in pattern.split(';'):
  3997. if re.search(p, text):
  3998. num += 1
  3999. kw.append(re.search(p, text).group(0))
  4000. return num, ';'.join(kw)
  4001. def is_contain_winner(extract_json):
  4002. if re.search('win_tenderer', extract_json):
  4003. return True
  4004. else:
  4005. return False
  4006. def is_single_source(bidway, title):
  4007. if re.search('单一来源|单一性采购', title):
  4008. return True
  4009. elif bidway == '单一来源':
  4010. return True
  4011. else:
  4012. return False
  4013. def get_type(title, text):
  4014. if re.search(self.title_type_dic['土地矿产'], title) or re.search(self.type_dic['土地矿产'],
  4015. text): # and re.search('(土地|用地|宗地|地块)(经营权)?(流转|承包|出租|招租|租赁|确权)', text)==None
  4016. if re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title):
  4017. return '采招数据', re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title).group(0)
  4018. return '土地矿产', (re.search(self.title_type_dic['土地矿产'], title) or re.search(self.type_dic['土地矿产'], text)).group(0)
  4019. elif (re.search(self.title_type_dic['拍卖出让'], title) or re.search(self.type_dic['拍卖出让'], text)):
  4020. if re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title):
  4021. return '采招数据', re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title).group(0)
  4022. return '拍卖出让', (re.search(self.title_type_dic['拍卖出让'], title) or re.search(self.type_dic['拍卖出让'], text)).group(0)
  4023. elif re.search(self.title_type_dic['产权交易'], title) or re.search(self.type_dic['产权交易'], text):
  4024. if re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title):
  4025. return '采招数据', re.search(self.title_type_dic['采招数据'], text.strip().split(' ')[0] + title).group(0)
  4026. return '产权交易', (re.search(self.title_type_dic['产权交易'], title) or re.search(self.type_dic['产权交易'], text)).group(0)
  4027. elif re.search(self.title_type_dic['采招数据'], title) or re.search(self.type_dic['采招数据'], title + text):
  4028. return '采招数据', (
  4029. re.search(self.title_type_dic['采招数据'], title) or re.search(self.type_dic['采招数据'], title + text)).group(
  4030. 0)
  4031. elif re.search(self.title_type_dic['新闻资讯'], title):
  4032. if re.search(self.title_type_dic['采招数据'], title +text.strip().split(' ')[0]):
  4033. return '采招数据', re.search(self.title_type_dic['采招数据'], title +text.strip().split(' ')[0]).group(0)
  4034. return '新闻资讯', re.search(self.title_type_dic['新闻资讯'], title).group(0)
  4035. else:
  4036. return '', '没有公告类型关键词,返回空'
  4037. def get_life(title, text):
  4038. title = re.sub('[-()()0-9a-z]|第?[二三四]次公?告?', '', title)
  4039. first_line = text.split()[0] if len(text.split()) > 2 else ''
  4040. if title.strip()[-2:] not in ['公告', '公示'] and 5 < len(first_line) < 50 and first_line[-2:] in ['公告', '公示']:
  4041. # print('title: ', title, first_line)
  4042. title += first_line
  4043. def count_score(l):
  4044. return len(l) + len(set(l)) * 2
  4045. life_kw_title = {}
  4046. life_kw_content = {}
  4047. life_score = {}
  4048. # msc = ""
  4049. # 查找标题每个类别关键词
  4050. for k, v in self.title_life_dic.items():
  4051. k2 = re.sub('[\da-z]', '', k)
  4052. if k2 not in life_kw_title:
  4053. life_kw_title[k2] = []
  4054. for it in re.finditer(v, title):
  4055. life_kw_title[k2].append(it.group(0))
  4056. # 查找正文每个类别关键词
  4057. for k, v in self.life_dic.items():
  4058. k2 = re.sub('[\da-z]', '', k)
  4059. if k2 not in life_kw_content:
  4060. life_kw_content[k2] = {'pos': [], 'neg': []}
  4061. for it in re.finditer(v, text):
  4062. if 'neg' not in k:
  4063. life_kw_content[k2]['pos'].append(it.group(0))
  4064. else:
  4065. life_kw_content[k2]['neg'].append(it.group(0))
  4066. for k2 in life_kw_content:
  4067. life_score[k2] = count_score(life_kw_content[k2]['pos']) - count_score(
  4068. life_kw_content[k2]['neg'])
  4069. life_kw_title = {k: v for k, v in life_kw_title.items() if v != []}
  4070. life_kw_content = {k: v for k, v in life_kw_content.items() if life_score[k] > 0}
  4071. msc = [life_kw_title, life_kw_content, life_score]
  4072. msc = json.dumps(msc, ensure_ascii=False)
  4073. max_score = 0
  4074. life_list = []
  4075. for k in life_score.keys():
  4076. if life_score[k] > max_score:
  4077. max_score = life_score[k]
  4078. life_list = [k]
  4079. elif life_score[k] == max_score and life_score[k] > 0:
  4080. life_list.append(k)
  4081. if '采购意向' in life_kw_title or '采购意向' in life_list:
  4082. if '中标信息' in life_kw_title or '中标信息' in life_list:
  4083. return '中标信息', msc
  4084. elif set(['候选人公示', '合同公告']) & set(life_kw_title) != set():
  4085. return '', msc
  4086. return '采购意向', msc
  4087. elif '招标预告' in life_kw_title or '招标预告' in life_list:
  4088. if '中标信息' in life_kw_title or '中标信息' in life_list:
  4089. return '中标信息', msc
  4090. elif set(['候选人公示', '合同公告']) & set(life_kw_title) != set():
  4091. return '', msc
  4092. return '招标预告', msc
  4093. elif '公告变更' in life_kw_title or '公告变更' in life_list:
  4094. if life_score.get('候选人公示', 0) > 3 or '候选人公示' in life_kw_title:
  4095. return '候选人公示', msc
  4096. elif life_score.get('合同公告', 0) > 3 or '合同公告' in life_kw_title:
  4097. return '合同公告', msc
  4098. elif life_score.get('中标信息', 0) > 3 or '中标信息' in life_kw_title:
  4099. return '中标信息', msc
  4100. elif '招标公告' in life_kw_title and re.search('变更|更正', title[-4:])==None and life_score.get('公告变更', 0) < 4:
  4101. return '招标公告', msc
  4102. return '公告变更', msc
  4103. elif '招标答疑' in life_kw_title or '招标答疑' in life_list:
  4104. if '招标公告' in life_kw_title and life_score.get('招标答疑', 0) < 4:
  4105. return '招标公告', msc
  4106. elif life_score.get('招标答疑', 0) < max_score:
  4107. if max_score > 3 and len(life_list) == 1:
  4108. return life_list[0], msc
  4109. return '', msc
  4110. return '招标答疑', msc
  4111. elif '开标记录' in life_kw_title:
  4112. if '开标结果' in title and is_contain_winner(prem_json):
  4113. return '中标信息', msc
  4114. return '开标记录', msc
  4115. elif '验收合同' in life_kw_title:
  4116. return '验收合同', msc
  4117. elif '候选人公示' in life_kw_title or '候选人公示' in life_list:
  4118. if '招标公告' in life_kw_title and '候选人公示' not in life_kw_title: # and life_score.get('招标公告', 0) > 3
  4119. return '招标公告', msc
  4120. elif '废标公告' in life_kw_title or life_score.get('废标公告', 0) > 5:
  4121. return '废标公告', msc
  4122. return '候选人公示', msc
  4123. elif '合同公告' in life_kw_title or '合同公告' in life_list:
  4124. if '招标公告' in life_kw_title and life_score.get('招标公告', 0) > 3:
  4125. return '招标公告', msc
  4126. elif '废标公告' in life_kw_title or life_score.get('废标公告', 0) > 5:
  4127. return '废标公告', msc
  4128. return '合同公告', msc
  4129. elif '中标信息' in life_kw_title or '中标信息' in life_list:
  4130. 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
  4131. return '招标公告', msc
  4132. elif '废标公告' in life_kw_title or life_score.get('废标公告', 0) > 5:
  4133. return '废标公告', msc
  4134. elif life_score.get('候选人公示', 0) > 3:
  4135. return '候选人公示', msc
  4136. elif life_score.get('合同公告', 0) > 5:
  4137. return '合同公告', msc
  4138. return '中标信息', msc
  4139. elif '废标公告' in life_kw_title or '废标公告' in life_list:
  4140. if life_score.get('招标公告', 0) > 3 and '废标公告' not in life_kw_title:
  4141. return '招标公告', msc
  4142. return '废标公告', msc
  4143. elif '资审结果' in life_kw_title or '资审结果' in life_list:
  4144. return '资审结果', msc
  4145. elif '招标公告' in life_kw_title or '招标公告' in life_list:
  4146. return '招标公告', msc
  4147. return '', msc
  4148. def get_model_inputs(list_sentence):
  4149. list_sentence = sorted(list_sentence, key=lambda x:x.sentence_index)
  4150. token_l = [it.tokens for it in list_sentence]
  4151. tokens = [it for l in token_l for it in l]
  4152. content = ' '.join(tokens[:500])
  4153. data_content, data_title = self.predict_process(docid='', doctitle=title[-50:],
  4154. dochtmlcon=content) # 标题最多取50字
  4155. text_len = len(data_content[0]) if len(data_content[0]) < self.sequen_len else self.sequen_len
  4156. title_len = len(data_title[0]) if len(data_title[0]) < self.title_len else self.title_len
  4157. array_content = embedding(data_content, shape=(len(data_content), self.sequen_len, 128))
  4158. array_title = embedding(data_title, shape=(len(data_title), self.title_len, 128))
  4159. return array_content, array_title ,text_len, title_len, content
  4160. def type_model_predict():
  4161. pred = self.type_sess.run(self.type_softmax,
  4162. feed_dict={
  4163. self.type_title: array_title,
  4164. self.type_content: array_content,
  4165. self.type_mask: [[0] * text_len + [1] * (self.sequen_len - text_len)],
  4166. self.type_mask_title: [[0] * title_len + [1] * (self.title_len - title_len)],
  4167. self.type_prob: 1}
  4168. )
  4169. id = np.argmax(pred, axis=1)[0]
  4170. prob = pred[0][id]
  4171. return id, prob
  4172. def life_model_predict():
  4173. pred = self.lift_sess.run(self.lift_softmax,
  4174. feed_dict={
  4175. self.lift_title: array_title,
  4176. self.lift_content: array_content,
  4177. self.mask: [[0] * text_len + [1] * (self.sequen_len - text_len)],
  4178. self.mask_title: [[0] * title_len + [1] * (self.title_len - title_len)],
  4179. self.lift_prob: 1}
  4180. )
  4181. id = np.argmax(pred, axis=1)[0]
  4182. prob = pred[0][id]
  4183. return id, prob
  4184. def final_change(msc):
  4185. '''
  4186. 修改逻辑:
  4187. 1、中标公告、合同公告无中标人且原始为非中标,返回原类型
  4188. 2、废标公告有中标人且标题无废标关键词,返回中标信息
  4189. 3、答疑公告标题无答疑关键且原始为招标,返回原始类别
  4190. 4、招标公告有中标人且原始为中标,返回中标信息
  4191. 5、预测为招标,原始为预告、意向,返回原始类别
  4192. 6、预测及原始均在变更、答疑,返回原始类别
  4193. 7、预测为采招数据,原始为产权且有关键词,返回原始类别
  4194. 8、废标公告原始为招标、预告且标题无废标关键期,返回原始类别
  4195. 9、若预测为非采招数据且源网为采招数据且有招标关键词返回采招数据
  4196. 10、招标公告有中标人,且标题有直购关键词,改为中标信息
  4197. 11、预测预告,原始为意向、招标且标题无预告关键词,返回原始类别
  4198. '''
  4199. if result['docchannel']['docchannel'] in ['中标信息', '合同公告'] and origin_dic.get(
  4200. original_docchannel, '') in ['招标公告', '采购意向', '招标预告', '公告变更'] and is_contain_winner(
  4201. prem_json)==False and re.search(self.title_life_dic['中标信息'], title)==None:
  4202. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4203. msc += '最终规则修改:中标公告、合同公告无中标人且原始为非中标,返回原类型'
  4204. elif result['docchannel']['docchannel'] == '废标公告' and is_contain_winner(prem_json) and re.search(
  4205. self.title_life_dic['废标公告'], title) == None:
  4206. result['docchannel']['docchannel'] = '中标信息'
  4207. msc += '最终规则修改:预测为废标却有中标人且标题无废标关键词改为中标信息;'
  4208. elif result['docchannel']['docchannel'] in ['招标答疑'] and re.search(
  4209. self.title_life_dic['招标答疑'], title) == None and origin_dic.get(
  4210. original_docchannel, '') in ['招标公告', '采购意向', '招标预告']:
  4211. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4212. msc += '最终规则修改:答疑公告标题无答疑关键且原始为招标,返回原始类别;'
  4213. elif result['docchannel']['docchannel'] == '招标公告' and is_contain_winner(prem_json) and origin_dic.get(
  4214. original_docchannel, '') == '中标信息':
  4215. result['docchannel']['docchannel'] = '中标信息'
  4216. msc += '最终规则修改:预测为招标公告却有中标人且原始为中标改为中标信息;'
  4217. elif result['docchannel']['docchannel'] in ['招标公告'] and origin_dic.get(
  4218. original_docchannel, '') in ['采购意向', '招标预告']:
  4219. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4220. msc += '最终规则修改:预测为招标,原始为预告、意向,返回原始类别'
  4221. elif result['docchannel']['docchannel'] in ['招标预告'] and origin_dic.get(
  4222. original_docchannel, '') in ['采购意向', '招标公告'] and re.search(
  4223. self.title_life_dic['招标预告'], title)==None:
  4224. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4225. msc += '最终规则修改:预测预告,原始为意向、招标且标题无预告关键词,返回原始类别'
  4226. elif result['docchannel']['docchannel'] in ['招标答疑', '公告变更'] and origin_dic.get(
  4227. original_docchannel, '') in ['招标答疑', '公告变更']:
  4228. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4229. msc += '最终规则修改:预测及原始均在答疑、变更,返回原始类别'
  4230. elif result['docchannel']['doctype'] == '采招数据' and origin_dic.get(
  4231. original_docchannel, '') in ['产权交易', '土地矿产'] and re.search('产权|转让|受让|招租|出租|承租|竞价|资产', text):
  4232. result['docchannel']['doctype'] = origin_dic.get(original_docchannel, '')
  4233. msc += '最终规则修改:预测为采招数据,原始为产权且有关键词,返回原始类别'
  4234. elif result['docchannel']['docchannel'] == '废标公告' and origin_dic.get(
  4235. original_docchannel, '') in ['招标公告', '采购意向', '招标预告'] and re.search(
  4236. self.title_life_dic['废标公告'], title) == None:
  4237. result['docchannel']['docchannel'] = origin_dic.get(original_docchannel, '')
  4238. msc += '最终规则修改:废标公告原始为招标、预告且标题无废标关键期,返回原始类别;'
  4239. elif result['docchannel']['docchannel'] in ['招标公告', '招标预告'] and is_contain_winner(
  4240. prem_json) and re.search('直购', title):
  4241. result['docchannel']['docchannel'] = '中标信息'
  4242. msc += "最终规则修改:预测为招标却有中标人且标题有直购关键词返回中标"
  4243. if result['docchannel']['doctype'] in ['产权交易', '土地矿产', '拍卖出让'] and origin_dic.get(
  4244. original_docchannel, '') not in ['产权交易', '土地矿产', '拍卖出让'] \
  4245. and (re.search(self.title_type_dic['采招数据'], title) or re.search('工程|服务|采购|询价|磋商', title) or re.search('(采购|招投?标|投标)(信息|内容|项目|公告|数量|人|单位|方式)|(建设|工程|服务|施工|监理|勘察|设计)项目|(%s)'%self.type_dic['采招数据'], text)):
  4246. result['docchannel']['doctype'] = '采招数据'
  4247. msc += ' 最终规则修改:预测为非采招数据,原始为采招数据且有招标关键词,返回采招数据'
  4248. elif result['docchannel']['doctype'] in ['土地矿产'] and origin_dic.get(original_docchannel, '') in ['拍卖出让', '产权交易']:
  4249. if origin_dic.get(original_docchannel, '') in ['拍卖出让'] and (re.search(self.title_type_dic['拍卖出让'], title) or re.search(self.type_dic['拍卖出让'], text)):
  4250. result['docchannel']['doctype'] = '拍卖出让'
  4251. msc += "最终规则修改:预测为土地矿产原始为拍卖且有拍卖关键词,返回拍卖"
  4252. elif (re.search(self.title_type_dic['产权交易'], title) or re.search(self.type_dic['产权交易'], text)):
  4253. result['docchannel']['doctype'] = '产权交易'
  4254. msc += "最终规则修改:预测为土地矿产原始为产权交易且有产权交易关键词,返回产权交易"
  4255. '''下面是新格式增加返回字段'''
  4256. if result['docchannel']['docchannel'] != '': # 预测到生命周期的复制到life_docchannel,否则用数据源结果
  4257. result['docchannel']['life_docchannel'] = result['docchannel']['docchannel']
  4258. else:
  4259. result['docchannel']['life_docchannel'] = origin_dic.get(original_docchannel, '原始类别')
  4260. return msc
  4261. not_extract_dic = {
  4262. 104: '招标文件',
  4263. 106: '法律法规',
  4264. 107: '新闻资讯',
  4265. 108: '拟建项目',
  4266. 109: '展会推广',
  4267. 110: '企业名录',
  4268. 111: '企业资质',
  4269. 112: '全国工程人员',
  4270. 113: '业主采购'
  4271. }
  4272. origin_dic = {51: '公告变更',
  4273. 52: '招标公告',
  4274. 101: '中标信息',
  4275. 102: '招标预告',
  4276. 103: '招标答疑',
  4277. 104: '招标文件',
  4278. 105: '资审结果',
  4279. 106: '法律法规',
  4280. 107: '新闻资讯',
  4281. 108: '拟建项目',
  4282. 109: '展会推广',
  4283. 110: '企业名录',
  4284. 111: '企业资质',
  4285. 112: '全国工程',
  4286. 113: '业主采购',
  4287. 114: '采购意向',
  4288. 115: '拍卖出让',
  4289. 116: '土地矿产',
  4290. 117: '产权交易',
  4291. 118: '废标公告',
  4292. 119: '候选人公示',
  4293. 120: '合同公告'}
  4294. if original_docchannel in not_extract_dic:
  4295. return {'docchannel': {'docchannel': '', 'doctype': not_extract_dic[original_docchannel], 'life_docchannel': origin_dic.get(original_docchannel, '原始类别')}}, '公告类别不在提取范围'
  4296. if web_source_no in ['02104-7', '04733', 'DX007628-6']: # 这些数据源无法识别
  4297. return {'docchannel': {'docchannel': '', 'doctype': '采招数据', 'life_docchannel': origin_dic.get(original_docchannel, '原始类别')}}, '此数据源公告分类不明确,返回数据源类别'
  4298. if original_docchannel == 303:
  4299. return {'docchannel': {'docchannel': '处罚公告', 'doctype': '处罚公告', 'life_docchannel': '处罚公告'}}, "源类别为处罚公告"
  4300. title = re.sub('[^\u4e00-\u9fa5]+|出租车', '', title)
  4301. if len(title) > 50:
  4302. title = title[:20] + title[-30:]
  4303. text = html2text(html)
  4304. prem_json = json.dumps(prem, ensure_ascii=False)
  4305. result = {'docchannel': {'docchannel': '', 'doctype': ''}}
  4306. doc_type, type_kw = get_type(title, text)
  4307. # doc_life, life_kw = get_life(title, text, prem_json, bidway, original_docchannel)
  4308. doc_life, life_kw = get_life(title, text)
  4309. if doc_type in self.title_type_dic:
  4310. result['docchannel']['doctype'] = doc_type
  4311. if doc_life in self.title_life_dic:
  4312. result['docchannel']['docchannel'] = doc_life
  4313. # print('channel正则预测结果:', result)
  4314. msc = '正则结果:类型:%s, 关键词:%s, 周期:%s, 关键词:%s'%(doc_type, type_kw,doc_life, life_kw)+'\n'+'模型结果:'
  4315. # print('类型:%s, 关键词:%s, 周期:%s, 关键词:%s'%(doc_type, type_kw,doc_life, life_kw))
  4316. if doc_type == "" or doc_life == "" or (doc_type != '采招数据' and origin_dic.get(original_docchannel, '原始类别') in ['招标公告', '中标信息', '招标预告', '采购意向']):
  4317. array_content, array_title, text_len, title_len, content = get_model_inputs(list_sentence)
  4318. if doc_type =="" or (doc_type != '采招数据' and origin_dic.get(original_docchannel, '原始类别') in ['招标公告', '中标信息', '招标预告', '采购意向']):
  4319. type_id, type_prob = type_model_predict()
  4320. type_model = self.id2type[type_id]
  4321. if type_model == '新闻资讯' and doc_life!='': # 修复bug 78584245 "docchannel": "合同公告", "doctype": "新闻资讯",
  4322. result['docchannel']['doctype'] = '采招数据'
  4323. msc += '模型结果为新闻资讯,生命周期不为空,改为采招数据;'
  4324. else:
  4325. result['docchannel']['doctype'] = type_model
  4326. msc += type_model + ' 概率:%.4f;'%type_prob
  4327. # print('公告类别:', self.id2type[id], '概率:',prob)
  4328. # if id == 0:
  4329. if doc_life=="" and result['docchannel']['doctype'] not in ['', '新闻资讯']:
  4330. if len(text)>150 and re.search(self.kws, content):
  4331. life_id, life_prob = life_model_predict()
  4332. if life_prob>=0.8:
  4333. life_model = self.id2life[life_id]
  4334. result['docchannel']['docchannel'] = life_model
  4335. msc += life_model + ' 概率:%.4f;\n'%life_prob
  4336. msc = final_change(msc)
  4337. # print('channel ', msc)
  4338. return result, msc
  4339. # 保证金支付方式提取
  4340. class DepositPaymentWay():
  4341. def __init__(self,):
  4342. self.pt = '(保证金的?(交纳|缴纳|应按下列|入账|支付)方式)[::]*([^,。]{,60})'
  4343. self.pt2 = '保证金(必?须以|必?须?通过|以)(.{,8})方式'
  4344. kws = ['银行转账', '公?对公方?式?转账', '对公转账', '柜台转账', '(线上|网上)自?行?(缴纳|交纳|缴退|收退)',
  4345. '网上银行支付', '现金存入', '直接缴纳', '支票', '汇票', '本票', '电汇', '转账', '汇款', '随机码',
  4346. '入账', '基本账户转出', '基本账户汇入', '诚信库中登记的账户转出',
  4347. '银行保函', '电子保函', '担保函', '保证保险', '合法担保机构出具的担保', '金融机构、担保机构出具的保函']
  4348. self.kws = sorted(kws, key=lambda x: len(x), reverse=True)
  4349. def predict(self,content):
  4350. pay_way = {'deposit_patment_way':''}
  4351. result = []
  4352. pay = re.search(self.pt, content)
  4353. if pay:
  4354. # print(pay.group(0))
  4355. pay = pay.group(3)
  4356. for it in re.finditer('|'.join(self.kws), pay):
  4357. result.append(it.group(0))
  4358. pay_way['deposit_patment_way'] = ';'.join(result)
  4359. return pay_way
  4360. pay = re.search(self.pt2, content)
  4361. if pay:
  4362. # print(pay.group(0))
  4363. pay = pay.group(2)
  4364. for it in re.finditer('|'.join(self.kws), pay):
  4365. result.append(it.group(0))
  4366. pay_way['deposit_patment_way'] = ';'.join(result)
  4367. return pay_way
  4368. else:
  4369. return pay_way
  4370. # 项目标签
  4371. class ProjectLabel():
  4372. def __init__(self, ):
  4373. self.keyword_list = self.get_label_keywords()
  4374. self.kongjing_keyword_list = self.get_kongjing_keywords()
  4375. def get_label_keywords(self):
  4376. import csv
  4377. path = os.path.dirname(__file__)+'/project_label_keywords.csv'
  4378. with open(path, 'r',encoding='utf-8') as f:
  4379. reader = csv.reader(f)
  4380. key_word_list = []
  4381. for r in reader:
  4382. if r[0] == '类型':
  4383. continue
  4384. type = r[0]
  4385. key_wrod = r[1]
  4386. key_paichuci = str(r[2])
  4387. key_paichuci = key_paichuci if key_paichuci and key_paichuci != 'nan' else ""
  4388. type_paichuci = str(r[3])
  4389. type_paichuci = type_paichuci if type_paichuci and type_paichuci != 'nan' else ""
  4390. key_word_list.append((type, key_wrod, key_paichuci, type_paichuci))
  4391. return key_word_list
  4392. def get_kongjing_keywords(self):
  4393. import csv
  4394. path = os.path.dirname(__file__)+'/kongjing_label_keywords.csv'
  4395. with open(path, 'r',encoding='utf-8') as f:
  4396. reader = csv.reader(f)
  4397. key_word_list = []
  4398. for r in reader:
  4399. if r[0] == '关键词':
  4400. continue
  4401. key_wrod = r[0]
  4402. key_wrod2 = str(r[1])
  4403. key_wrod2 = key_wrod2 if key_wrod2 and key_wrod2 != 'nan' else ""
  4404. search_type = r[2]
  4405. info_type_list = str(r[3])
  4406. info_type_list = info_type_list if info_type_list and info_type_list != 'nan' else ""
  4407. key_word_list.append((key_wrod, key_wrod2, search_type, info_type_list))
  4408. return key_word_list
  4409. def predict(self, doctitle,product,project_name,prem):
  4410. doctitle = doctitle if doctitle else ""
  4411. product = product if product else ""
  4412. product = ",".join(set(product.split(','))) # 产品词去重
  4413. project_name = project_name if project_name else ""
  4414. tenderee = ""
  4415. agency = ""
  4416. sub_project_names = [] # 标段名称
  4417. try:
  4418. for k,v in prem[0]['prem'].items():
  4419. # sub_project_names.append(k)
  4420. sub_project_names.append(v.get("name",""))
  4421. for link in v['roleList']:
  4422. if link['role_name'] == 'tenderee' and tenderee == "":
  4423. tenderee = link['role_text']
  4424. if link['role_name'] == 'agency' and agency == "":
  4425. agency = link['role_text']
  4426. except Exception as e:
  4427. # print('解析prem 获取招标人、代理人出错')
  4428. pass
  4429. sub_project_names = ";".join(sub_project_names)
  4430. # 核心字段:标题+产品词+项目名称+标段名称
  4431. main_text = ",".join([doctitle, product, project_name, sub_project_names])
  4432. # 剔除 招标单位、代理机构名称
  4433. if tenderee:
  4434. doctitle = doctitle.replace(tenderee, " ")
  4435. main_text = main_text.replace(tenderee, " ")
  4436. if agency:
  4437. doctitle = doctitle.replace(agency, " ")
  4438. main_text = main_text.replace(agency, " ")
  4439. doctitle_dict = dict()
  4440. main_text_dict = dict()
  4441. for item in self.keyword_list:
  4442. _type = item[0]
  4443. key_wrod = item[1]
  4444. # 关键词排除词
  4445. key_paichuci = item[2]
  4446. key_paichuci_s = "|".join(key_paichuci.split('、'))
  4447. # 类型排除词
  4448. type_paichuci = item[3]
  4449. if type_paichuci:
  4450. paichuci_split = type_paichuci.split('、')
  4451. if re.search("|".join(paichuci_split), main_text):
  4452. continue
  4453. if doctitle:
  4454. if key_wrod in doctitle:
  4455. if not key_paichuci_s or (key_paichuci_s and not re.search(key_paichuci_s, doctitle)):
  4456. key_wrod_count1 = doctitle.count(key_wrod)
  4457. if _type not in doctitle_dict:
  4458. # doctitle_dict[_type] = {'关键词': [], '排除词': type_paichuci}
  4459. doctitle_dict[_type] = []
  4460. doctitle_dict[_type].append((key_wrod, key_wrod_count1))
  4461. if main_text:
  4462. if key_wrod in main_text:
  4463. if not key_paichuci_s or (key_paichuci_s and not re.search(key_paichuci_s, main_text)):
  4464. key_wrod_count2 = main_text.count(key_wrod)
  4465. if _type not in main_text_dict:
  4466. # main_text_dict[_type] = {'关键词': [], '排除词': type_paichuci}
  4467. main_text_dict[_type] = []
  4468. main_text_dict[_type].append((key_wrod, key_wrod_count2))
  4469. # 排序 doctitle
  4470. for k, v in doctitle_dict.items():
  4471. doctitle_dict[k].sort(key=lambda x: x[1], reverse=True)
  4472. # 按匹配次数保留前10个标签
  4473. if len(doctitle_dict) > 10:
  4474. doctitle_labels = [(k, sum(w[1] for w in doctitle_dict[k])) for k in doctitle_dict]
  4475. doctitle_labels.sort(key=lambda x: x[1], reverse=True)
  4476. for item in doctitle_labels[10:]:
  4477. doctitle_dict.pop(item[0])
  4478. # main_text
  4479. pop_list = []
  4480. for k, v in main_text_dict.items():
  4481. if sum([j[1] for j in main_text_dict[k]]) == 1:
  4482. # 关键词匹配次数等于1的标签
  4483. pop_list.append(k)
  4484. main_text_dict[k].sort(key=lambda x: x[1], reverse=True)
  4485. # 核心字段标签,若存在同一个标签的关键词匹配次数大于1,则只保留关键词匹配次数大于1的标签,关键词匹配次数等于1的标签不要
  4486. if len(pop_list) < len(main_text_dict):
  4487. for k in pop_list:
  4488. main_text_dict.pop(k)
  4489. # 按匹配次数保留前10个标签
  4490. if len(main_text_dict) > 10:
  4491. main_text_labels = [(k, sum(w[1] for w in main_text_dict[k])) for k in main_text_dict]
  4492. main_text_labels.sort(key=lambda x: x[1], reverse=True)
  4493. for item in main_text_labels[10:]:
  4494. main_text_dict.pop(item[0])
  4495. return {"标题":doctitle_dict,"核心字段":main_text_dict}
  4496. def predict_other(self,project_label,industry,doctitle,project_name,product,list_articles):
  4497. # doctextcon 取正文内容
  4498. doctextcon = list_articles[0].content.split('##attachment##')[0]
  4499. info_type = industry.get('industry',{}).get("class_name","")
  4500. doctitle = doctitle if doctitle else ""
  4501. product = product if product else ""
  4502. product = ",".join(set(product.split(','))) # 产品词去重
  4503. project_name = project_name if project_name else ""
  4504. get_kongjing_label = False
  4505. keywords_list = []
  4506. for item in self.kongjing_keyword_list:
  4507. key_wrod = item[0]
  4508. key_wrod2 = item[1]
  4509. search_type = item[2]
  4510. info_type_list = item[3]
  4511. info_type_list = info_type_list.split("|") if info_type_list else []
  4512. search_text = ""
  4513. if search_type=='正文':
  4514. search_text = ",".join([doctextcon,doctitle,project_name,product])
  4515. elif search_type=='产品':
  4516. search_text = ",".join([doctitle,project_name,product])
  4517. if search_type=='行业':
  4518. # ’行业’类型直接用info_type匹配关键词
  4519. if info_type==key_wrod:
  4520. # 匹配关键词记录
  4521. keywords_list.append(key_wrod)
  4522. get_kongjing_label = True
  4523. # break
  4524. else:
  4525. if key_wrod in search_text:
  4526. if key_wrod2 and key_wrod2 not in search_text:
  4527. continue
  4528. if info_type_list and info_type not in info_type_list:
  4529. continue
  4530. # 匹配关键词记录
  4531. if key_wrod2:
  4532. keywords_list.append(key_wrod+'+'+key_wrod2)
  4533. else:
  4534. keywords_list.append(key_wrod)
  4535. get_kongjing_label = True
  4536. # break
  4537. if get_kongjing_label:
  4538. project_label["核心字段"]["空净通"] = [[word,1] for word in keywords_list][:10]
  4539. return project_label
  4540. # 产权分类二级标签
  4541. class PropertyLabel():
  4542. '''
  4543. 产权分类二级标签
  4544. 全部类别:
  4545. 股权, 债权, 知识产权, 矿权, 房产, 土地, 交通运输工具, 闲置物资、设备、材料, 其他
  4546. '''
  4547. def __init__(self, ):
  4548. car = "比亚迪|奇瑞|奥迪|宝马|菲尼迪|雷克萨斯|三菱|铃木|马自达|奔驰|劳斯莱斯|北京现代|" \
  4549. "宾利|兰博基尼|布加迪|保时捷|斯柯达|雪佛兰|别克|凯迪拉克|庞蒂亚克|克尔维特|福特|林肯|克莱斯勒|道奇|JEEP品牌"
  4550. self.keywords_dict = {
  4551. "房产": "房产|住宅|公寓|商铺|车位|写字楼|办公楼|别墅|综合楼|在建工程|厂房|车库|车房|房转让|房屋|商品房|商业用房|"
  4552. "宅基地|[\u4e00-\u9fa5]{,2}用房|店面|商业房|门[面市]房|仓库|铺位|地下室|\d号?(房|室|门市|门面|商?铺|单元|户)|不动产|"
  4553. "自建房|铺面|商务楼|商住楼|阁楼|(杂物|储物|储藏)(房|间|室)|套房|[\da-zA-Z](栋|棟|幢|层|座|号?楼|单元)\d{1,4}(号|房|室|商?铺|户)|"
  4554. "[\da-zA-Z](栋|棟|幢|层|座|号?楼|单元)\d{2,}|门面+转让|楼+变卖|房地产",
  4555. "交通运输工具": "车辆|轿车|汽车(?!用品|库|位|衡)|公车|客车|货车|面包车|SUV|新能源车|二手车|车辆|商用车|机动车|观光车|巴车|"
  4556. "船舶|四驱" + "|" + car,
  4557. "股权": "\d.?股|股权(?!交易中心)|\d%(比例)?.?股|\d万.?股|\d.?元/股|增资(?!源)|扩股|股(转让|出售)|百分之[一二三四五六七八九十]{1,3}股",
  4558. "债权": "债权|债权转让|债权人|债务人|原债权人|新债权人|金融资产",
  4559. "土地": "住宅用地|商业用地|工业用地|国有[\u4e00-\u9fa5]{,3}[土用]地|集体土地|划拨|流转|地块编号|"
  4560. "土地使用权证|土地经营权|土地证|土地[发承]包|[\u4e00-\u9fa5]{,2}用地|土地\d{1,3}(亩|公?顷)|\d{1,3}(亩|公?顷)(使用|经营)权|"
  4561. "承包土地|(地块|土地)承包|水面经营权|[鱼水]塘|鱼池|(水面|旱田)[\u4e00-\u9fa5]{,3}[发承]包|水面资源|(水面|水田)[\u4e00-\u9fa5]{,3}权|"
  4562. "四荒|林地|林场|林木所有权|采伐权|水利设施所有权|水利设施使用权|海域|滩涂|林业产权|旱田|水田|机动田|机动地|耕地|荒地|农田|"
  4563. "苗圃地|塘口",
  4564. "矿权": "矿权|矿业权|采矿许可|探矿权|采矿权|开采权|矿产资源处置|矿[\u4e00-\u9fa5]{1,3}开[发采]",
  4565. "知识产权": "知识产权(?!局)|商标|专利|著作权|版权|商业秘密|科研成果",
  4566. "闲置物资、设备、材料": "(废旧|报废|废|闲置|二手|淘汰)(物资|资产|机械|设备|仪器|汽车|车|钢铁|钢材|钢|金属|塑料|材料|导管|漆|渣|有色|品|[\u4e00-\u9fa5]{,2}车|偶头)|"
  4567. "(金属|机械|设备|仪器|汽车|钢铁|钢材|钢|塑料|有色|)废料|废液|废旧|报废|边角料|残次品|(热轧|冷轧|酸洗|镀铝|热镀|镀锌|镀镁)|"
  4568. "机[器械]设备|医疗设备|生产设备|办公设备|仪器|仪表|设备出租|设备租赁|拖拉机|收割机|插秧机|挖机|车床|挖掘机|电机|"
  4569. "戒指|弃渣|电解质块|茶杯|装置|花瓶|女表|手表|男表|硫磺|物资|书画|茶叶|油茶|红茶|[茗名]茶|白酒|红酒|酒水|酒品|名酒|毛石|[石金木铁矿铜锌铝钢]料|"
  4570. "零部件",
  4571. "经营权": "经营权",
  4572. "租赁": "房+租|市场+续约|资产+出租|租赁|续租|招租|出租|租金|房租"
  4573. }
  4574. self.cqjy_keywords = self.get_cqjy_keywords()
  4575. self.score_idx = ["股权", "债权", "知识产权", "矿权", "房产", "土地", "交通运输工具", "闲置物资、设备、材料"]
  4576. def get_cqjy_keywords(self):
  4577. import csv
  4578. path = os.path.dirname(__file__)+'/property_label_products.csv'
  4579. with open(path, 'r',encoding='utf-8') as f:
  4580. reader = csv.reader(f)
  4581. key_word_list = []
  4582. for r in reader:
  4583. if r[0] == 'product':
  4584. continue
  4585. key_wrod = r[0]
  4586. _type = r[1]
  4587. key_word_list.append((_type, key_wrod))
  4588. return key_word_list
  4589. def get_type(self, text):
  4590. keyword_list = []
  4591. for key, value in self.keywords_dict.items():
  4592. keyword = "|".join([i for i in value.split("|") if '+' not in i])
  4593. keyword2 = [i for i in value.split("|") if '+' in i]
  4594. if re.search(keyword, text):
  4595. re1 = [i for i in re.finditer(keyword, text)][-1]
  4596. keyword_list.append((key, re1.start()))
  4597. else:
  4598. # 组合词 查询
  4599. for k in keyword2:
  4600. k1, k2 = k.split('+')
  4601. if re.search(k1, text) and re.search(k2, text):
  4602. keyword_list.append((key, re.search(k2, text).start()))
  4603. break
  4604. return keyword_list
  4605. def get_type2(self, text, cqjy_type_list):
  4606. have_type = [i[0] for i in cqjy_type_list]
  4607. for item in self.cqjy_keywords:
  4608. _type = item[0]
  4609. key_wrod = item[1]
  4610. if _type not in have_type:
  4611. if '+' in key_wrod:
  4612. k1, k2 = key_wrod.split('+')
  4613. if re.search(k1, text) and re.search(k2, text):
  4614. cqjy_type_list.append((_type, re.search(k2, text).start()))
  4615. have_type.append(_type)
  4616. else:
  4617. if key_wrod in text:
  4618. cqjy_type_list.append((_type, text.index(key_wrod)))
  4619. have_type.append(_type)
  4620. return cqjy_type_list
  4621. def predict(self, doctitle,product,project_name,prem,channel_dic):
  4622. docchannel = channel_dic['docchannel']['doctype']
  4623. # print('docchannel',docchannel)
  4624. if docchannel not in ['土地矿产', '拍卖出让', '产权交易']:
  4625. return ""
  4626. doctitle = doctitle if doctitle else ""
  4627. product = product if product else ""
  4628. product = ",".join(set(product.split(','))) # 产品词去重
  4629. project_name = project_name if project_name else ""
  4630. tenderee = ""
  4631. agency = ""
  4632. try:
  4633. for k,v in prem[0]['prem'].items():
  4634. for link in v['roleList']:
  4635. if link['role_name'] == 'tenderee' and tenderee == "":
  4636. tenderee = link['role_text']
  4637. if link['role_name'] == 'agency' and agency == "":
  4638. agency = link['role_text']
  4639. except Exception as e:
  4640. # print('解析prem 获取招标人、代理人出错')
  4641. pass
  4642. cqjy_type = []
  4643. idx = 0
  4644. for text in [doctitle, project_name, product]:
  4645. if tenderee:
  4646. text = text.replace(tenderee, "")
  4647. if agency:
  4648. text = text.replace(agency, "")
  4649. cqjy_type = self.get_type(text)
  4650. if not cqjy_type:
  4651. cqjy_type = self.get_type2(text, cqjy_type)
  4652. idx += 1
  4653. if idx == 2: # project_name
  4654. if len(re.split("[,、]", text)) > 9:
  4655. cqjy_type = []
  4656. if idx == 3: # product
  4657. if len(text.split(",")) > 15:
  4658. cqjy_type = []
  4659. if cqjy_type:
  4660. break
  4661. cqjy_type2 = [i[0] for i in cqjy_type]
  4662. if cqjy_type:
  4663. # 类别优先级调整
  4664. if "租赁" in cqjy_type2:
  4665. cqjy_type2 = ['租赁']
  4666. elif "经营权" in cqjy_type2:
  4667. cqjy_type2 = ['经营权']
  4668. elif "股权" in cqjy_type2 or "债权" in cqjy_type2 or "知识产权" in cqjy_type2:
  4669. cqjy_type.sort(key=lambda x: self.score_idx.index(x[0]))
  4670. cqjy_type = cqjy_type[0]
  4671. cqjy_type2 = [cqjy_type[0]]
  4672. elif len(cqjy_type2) == 2 and "房产" in cqjy_type2 and "土地" in cqjy_type2:
  4673. cqjy_type2 = ['房产']
  4674. else:
  4675. # 权重排序,取第一位
  4676. if idx in [1, 2]: # doctitle, project_name
  4677. cqjy_type.sort(key=lambda x: x[1], reverse=True)
  4678. cqjy_type = cqjy_type[0]
  4679. cqjy_type2 = [cqjy_type[0]]
  4680. else:
  4681. cqjy_type.sort(key=lambda x: self.score_idx.index(x[0]))
  4682. cqjy_type = cqjy_type[0]
  4683. cqjy_type2 = [cqjy_type[0]]
  4684. cqjy_type2 = ",".join(cqjy_type2)
  4685. if not cqjy_type2:
  4686. cqjy_type2 = '其他'
  4687. return cqjy_type2
  4688. # 总价单价提取
  4689. class TotalUnitMoney:
  4690. def __init__(self):
  4691. pass
  4692. def predict(self, list_sentences, list_entitys):
  4693. for i in range(len(list_entitys)):
  4694. list_entity = list_entitys[i]
  4695. # 总价单价
  4696. for _entity in list_entity:
  4697. if _entity.entity_type == 'money':
  4698. word_of_sentence = list_sentences[i][_entity.sentence_index].sentence_text
  4699. # 总价在中投标金额中
  4700. if _entity.label == 1:
  4701. result = extract_total_money(word_of_sentence,
  4702. _entity.entity_text,
  4703. [_entity.wordOffset_begin, _entity.wordOffset_end])
  4704. if result:
  4705. _entity.is_total_money = 1
  4706. # 单价在普通金额中
  4707. else:
  4708. result = extract_unit_money(word_of_sentence,
  4709. _entity.entity_text,
  4710. [_entity.wordOffset_begin, _entity.wordOffset_end])
  4711. if result:
  4712. _entity.is_unit_money = 1
  4713. # print("total_unit_money", _entity.entity_text,
  4714. # _entity.is_total_money, _entity.is_unit_money)
  4715. # 行业分类
  4716. class IndustryPredictor():
  4717. def __init__(self,):
  4718. self.model_path = os.path.dirname(__file__)+ '/industry_model'
  4719. self.id2lb = {0: '专业施工', 1: '专用仪器仪表', 2: '专用设备修理', 3: '互联网信息服务', 4: '互联网安全服务', 5: '互联网平台', 6: '互联网接入及相关服务', 7: '人力资源服务',
  4720. 8: '人造原油', 9: '仓储业', 10: '仪器仪表', 11: '仪器仪表修理', 12: '会计、审计及税务服务', 13: '会议、展览及相关服务', 14: '住宅、商业用房',
  4721. 15: '体育场地设施管理', 16: '体育组织', 17: '体育设备', 18: '保险服务', 19: '信息处理和存储支持服务', 20: '信息技术咨询服务',
  4722. 21: '信息系统集成和物联网技术服务', 22: '修缮工程', 23: '健康咨询', 24: '公路旅客运输', 25: '其他专业咨询与调查', 26: '其他专业技术服务',
  4723. 27: '其他交通运输设备', 28: '其他公共设施管理', 29: '其他土木工程建筑', 30: '其他工程服务', 31: '其他建筑建材', 32: '其他运输业', 33: '农业和林业机械',
  4724. 34: '农业服务', 35: '农产品', 36: '农副食品,动、植物油制品', 37: '出版业', 38: '办公消耗用品及类似物品', 39: '办公设备', 40: '化学原料及化学制品',
  4725. 41: '化学纤维', 42: '化学药品和中药专用设备', 43: '医疗设备', 44: '医药品', 45: '卫星传输服务', 46: '卫生', 47: '印刷服务', 48: '图书和档案',
  4726. 49: '图书档案设备', 50: '图书馆与档案馆', 51: '土地管理业', 52: '地质勘查', 53: '地震服务', 54: '场馆、站港用房', 55: '城市公共交通运输',
  4727. 56: '塑料制品、半成品及辅料', 57: '天然石料', 58: '娱乐设备', 59: '婚姻服务', 60: '安全保护服务', 61: '安全生产设备', 62: '家具用具',
  4728. 63: '家用电器修理', 64: '工业、生产用房', 65: '工业与专业设计及其他专业技术服务', 66: '工矿工程建筑', 67: '工程技术与设计服务', 68: '工程机械',
  4729. 69: '工程监理服务', 70: '工程评价服务', 71: '工程造价服务', 72: '市场调查', 73: '广告业', 74: '广播', 75: '广播、电视、电影设备',
  4730. 76: '广播电视传输服务', 77: '废弃资源综合利用业', 78: '建筑涂料', 79: '建筑物、构筑物附属结构', 80: '建筑物拆除和场地准备活动', 81: '建筑装饰和装修业',
  4731. 82: '录音制作', 83: '影视节目制作', 84: '房地产中介服务', 85: '房地产开发经营', 86: '房地产租赁经营', 87: '房屋租赁', 88: '招标代理',
  4732. 89: '探矿、采矿、选矿和造块设备', 90: '政法、检测专用设备', 91: '教育服务', 92: '教育设备', 93: '文物及非物质文化遗产保护', 94: '文物和陈列品',
  4733. 95: '文艺创作与表演', 96: '文艺设备', 97: '新闻业', 98: '旅行社及相关服务', 99: '日杂用品', 100: '有色金属冶炼及压延产品', 101: '有色金属矿',
  4734. 102: '木材、板材等', 103: '木材采集和加工设备', 104: '机械设备', 105: '机械设备经营租赁', 106: '林业产品', 107: '林业服务', 108: '架线和管道工程建筑',
  4735. 109: '核工业专用设备', 110: '橡胶制品', 111: '殡葬服务', 112: '殡葬设备及用品', 113: '气象服务', 114: '水上交通运输设备', 115: '水上运输业',
  4736. 116: '水利和水运工程建筑', 117: '水工机械', 118: '水文服务', 119: '水资源管理', 120: '污水处理及其再生利用', 121: '汽车、摩托车修理与维护',
  4737. 122: '法律服务', 123: '洗染服务', 124: '测绘地理信息服务', 125: '海洋仪器设备', 126: '海洋工程建筑', 127: '海洋服务', 128: '消防设备',
  4738. 129: '清洁服务', 130: '渔业产品', 131: '渔业服务', 132: '炼焦和金属冶炼轧制设备', 133: '烟草加工设备', 134: '热力生产和供应', 135: '焦炭及其副产品',
  4739. 136: '煤炭采选产品', 137: '燃气生产和供应业', 138: '物业管理', 139: '特种用途动、植物', 140: '环保咨询', 141: '环境与生态监测检测服务',
  4740. 142: '环境污染防治设备', 143: '环境治理业', 144: '玻璃及其制品', 145: '理发及美容服务', 146: '生态保护', 147: '电信',
  4741. 148: '电力、城市燃气、蒸汽和热水、水', 149: '电力供应', 150: '电力工业专用设备', 151: '电力工程施工', 152: '电力生产', 153: '电子和通信测量仪器',
  4742. 154: '电工、电子专用生产设备', 155: '电影放映', 156: '电气安装', 157: '电气设备', 158: '电气设备修理', 159: '畜牧业服务', 160: '监控设备',
  4743. 161: '石油制品', 162: '石油和化学工业专用设备', 163: '石油和天然气开采产品', 164: '石油天然气开采专用设备', 165: '研究和试验发展', 166: '社会工作',
  4744. 167: '社会经济咨询', 168: '科技推广和应用服务业', 169: '科研、医疗、教育用房', 170: '管道和设备安装', 171: '粮油作物和饲料加工设备', 172: '纸、纸制品及印刷品',
  4745. 173: '纺织原料、毛皮、被服装具', 174: '纺织设备', 175: '绿化管理', 176: '缝纫、服饰、制革和毛皮加工设备', 177: '航空器及其配套设备', 178: '航空客货运输',
  4746. 179: '航空航天工业专用设备', 180: '节能环保工程施工', 181: '装卸搬运', 182: '计算机和办公设备维修', 183: '计算机设备', 184: '计量标准器具及量具、衡器',
  4747. 185: '货币处理专用设备', 186: '货币金融服务', 187: '质检技术服务', 188: '资本市场服务', 189: '车辆', 190: '边界勘界和联检专用设备', 191: '运行维护服务',
  4748. 192: '通信设备', 193: '通用设备修理', 194: '道路货物运输', 195: '邮政专用设备', 196: '邮政业', 197: '采矿业和制造业服务',
  4749. 198: '铁路、船舶、航空航天等运输设备修理', 199: '铁路、道路、隧道和桥梁工程建筑', 200: '铁路运输设备', 201: '防洪除涝设施管理', 202: '陶瓷制品',
  4750. 203: '雷达、无线电和卫星导航设备', 204: '非金属矿', 205: '非金属矿物制品工业专用设备', 206: '非金属矿物材料', 207: '食品加工专用设备', 208: '食品及加工盐',
  4751. 209: '餐饮业', 210: '饮料、酒精及精制茶', 211: '饮料加工设备', 212: '饲养动物及其产品', 213: '黑色金属冶炼及压延产品', 214: '黑色金属矿'}
  4752. self.industry_dic = {'专业施工': {'大类': '专业施工', '门类': '建筑业'},
  4753. '专用仪器仪表': {'大类': '专用设备', '门类': '零售批发'},
  4754. '专用设备修理': {'大类': '金属制品、机械和设备修理业', '门类': '金属制品、机械和设备修理业'},
  4755. '互联网信息服务': {'大类': '互联网和相关服务', '门类': '信息传输、软件和信息技术服务业'},
  4756. '互联网安全服务': {'大类': '互联网和相关服务', '门类': '信息传输、软件和信息技术服务业'},
  4757. '互联网平台': {'大类': '互联网和相关服务', '门类': '信息传输、软件和信息技术服务业'},
  4758. '互联网接入及相关服务': {'大类': '互联网和相关服务', '门类': '信息传输、软件和信息技术服务业'},
  4759. '人力资源服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4760. '人造原油': {'大类': '炼焦产品、炼油产品', '门类': '零售批发'},
  4761. '仓储业': {'大类': '装卸搬运和运输代理业', '门类': '交通运输、仓储和邮政业'},
  4762. '仪器仪表': {'大类': '通用设备', '门类': '零售批发'},
  4763. '仪器仪表修理': {'大类': '金属制品、机械和设备修理业', '门类': '金属制品、机械和设备修理业'},
  4764. '会计、审计及税务服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4765. '会议、展览及相关服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4766. '住宅、商业用房': {'大类': '房屋建筑业', '门类': '建筑业'},
  4767. '体育场地设施管理': {'大类': '体育', '门类': '文化、体育和娱乐业'},
  4768. '体育组织': {'大类': '体育', '门类': '文化、体育和娱乐业'},
  4769. '体育设备': {'大类': '专用设备', '门类': '零售批发'},
  4770. '保险服务': {'大类': '保险业', '门类': '金融业'},
  4771. '信息处理和存储支持服务': {'大类': '软件和信息技术服务业', '门类': '信息传输、软件和信息技术服务业'},
  4772. '信息技术咨询服务': {'大类': '软件和信息技术服务业', '门类': '信息传输、软件和信息技术服务业'},
  4773. '信息系统集成和物联网技术服务': {'大类': '软件和信息技术服务业', '门类': '信息传输、软件和信息技术服务业'},
  4774. '修缮工程': {'大类': '修缮工程', '门类': '建筑业'},
  4775. '健康咨询': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4776. '公路旅客运输': {'大类': '道路运输业', '门类': '交通运输、仓储和邮政业'},
  4777. '其他专业咨询与调查': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4778. '其他专业技术服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4779. '其他交通运输设备': {'大类': '专用设备', '门类': '零售批发'},
  4780. '其他公共设施管理': {'大类': '公共设施管理业', '门类': '水利、环境和公共设施管理业'},
  4781. '其他土木工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  4782. '其他工程服务': {'大类': '工程服务', '门类': '科学研究和技术服务业'},
  4783. '其他建筑建材': {'大类': '建筑建材', '门类': '零售批发'},
  4784. '其他运输业': {'大类': '其他运输业', '门类': '交通运输、仓储和邮政业'},
  4785. '农业和林业机械': {'大类': '专用设备', '门类': '零售批发'},
  4786. '农业服务': {'大类': '农林牧副渔服务', '门类': '农林牧副渔服务'},
  4787. '农产品': {'大类': '农林牧渔业产品', '门类': '零售批发'},
  4788. '农副食品,动、植物油制品': {'大类': '食品、饮料和烟草原料', '门类': '零售批发'},
  4789. '出版业': {'大类': '新闻和出版业', '门类': '文化、体育和娱乐业'},
  4790. '办公消耗用品及类似物品': {'大类': '办公消耗用品及类似物品', '门类': '零售批发'},
  4791. '办公设备': {'大类': '通用设备', '门类': '零售批发'},
  4792. '化学原料及化学制品': {'大类': '基础化学品及相关产品', '门类': '零售批发'},
  4793. '化学纤维': {'大类': '基础化学品及相关产品', '门类': '零售批发'},
  4794. '化学药品和中药专用设备': {'大类': '专用设备', '门类': '零售批发'},
  4795. '医疗设备': {'大类': '专用设备', '门类': '零售批发'},
  4796. '医药品': {'大类': '医药品', '门类': '零售批发'},
  4797. '卫星传输服务': {'大类': '电信、广播电视和卫星传输服务', '门类': '信息传输、软件和信息技术服务业'},
  4798. '卫生': {'大类': '卫生', '门类': '卫生和社会工作'},
  4799. '印刷服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4800. '图书和档案': {'大类': '图书和档案', '门类': '零售批发'},
  4801. '图书档案设备': {'大类': '通用设备', '门类': '零售批发'},
  4802. '图书馆与档案馆': {'大类': '文化艺术业', '门类': '文化、体育和娱乐业'},
  4803. '土地管理业': {'大类': '土地管理业', '门类': '水利、环境和公共设施管理业'},
  4804. '地质勘查': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4805. '地震服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4806. '场馆、站港用房': {'大类': '房屋建筑业', '门类': '建筑业'},
  4807. '城市公共交通运输': {'大类': '道路运输业', '门类': '交通运输、仓储和邮政业'},
  4808. '塑料制品、半成品及辅料': {'大类': '橡胶、塑料、玻璃和陶瓷制品', '门类': '零售批发'},
  4809. '天然石料': {'大类': '建筑建材', '门类': '零售批发'},
  4810. '娱乐设备': {'大类': '专用设备', '门类': '零售批发'},
  4811. '婚姻服务': {'大类': '居民服务业', '门类': '居民服务、修理和其他服务业'},
  4812. '安全保护服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4813. '安全生产设备': {'大类': '专用设备', '门类': '零售批发'},
  4814. '家具用具': {'大类': '家具用具', '门类': '零售批发'},
  4815. '家用电器修理': {'大类': '机动车、电子产品和日用产品修理业', '门类': '居民服务、修理和其他服务业'},
  4816. '工业、生产用房': {'大类': '房屋建筑业', '门类': '建筑业'},
  4817. '工业与专业设计及其他专业技术服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4818. '工矿工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  4819. '工程技术与设计服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4820. '工程机械': {'大类': '专用设备', '门类': '零售批发'},
  4821. '工程监理服务': {'大类': '工程服务', '门类': '科学研究和技术服务业'},
  4822. '工程评价服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4823. '工程造价服务': {'大类': '工程服务', '门类': '科学研究和技术服务业'},
  4824. '市场调查': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4825. '广告业': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4826. '广播': {'大类': '广播、电视、电影和影视录音制作业', '门类': '文化、体育和娱乐业'},
  4827. '广播、电视、电影设备': {'大类': '通用设备', '门类': '零售批发'},
  4828. '广播电视传输服务': {'大类': '电信、广播电视和卫星传输服务', '门类': '信息传输、软件和信息技术服务业'},
  4829. '废弃资源综合利用业': {'大类': '废弃资源综合利用业', '门类': '废弃资源综合利用业'},
  4830. '建筑涂料': {'大类': '建筑建材', '门类': '零售批发'},
  4831. '建筑物、构筑物附属结构': {'大类': '建筑建材', '门类': '零售批发'},
  4832. '建筑物拆除和场地准备活动': {'大类': '建筑装饰和其他建筑业', '门类': '建筑业'},
  4833. '建筑装饰和装修业': {'大类': '建筑装饰和其他建筑业', '门类': '建筑业'},
  4834. '录音制作': {'大类': '广播、电视、电影和影视录音制作业', '门类': '文化、体育和娱乐业'},
  4835. '影视节目制作': {'大类': '广播、电视、电影和影视录音制作业', '门类': '文化、体育和娱乐业'},
  4836. '房地产中介服务': {'大类': '房地产业', '门类': '房地产业'},
  4837. '房地产开发经营': {'大类': '房地产业', '门类': '房地产业'},
  4838. '房地产租赁经营': {'大类': '房地产业', '门类': '房地产业'},
  4839. '房屋租赁': {'大类': '租赁业', '门类': '租赁和商务服务业'},
  4840. '招标代理': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4841. '探矿、采矿、选矿和造块设备': {'大类': '专用设备', '门类': '零售批发'},
  4842. '政法、检测专用设备': {'大类': '专用设备', '门类': '零售批发'},
  4843. '教育服务': {'大类': '教育服务', '门类': '教育'},
  4844. '教育设备': {'大类': '专用设备', '门类': '零售批发'},
  4845. '文体设备和用品出租': {'大类': '租赁业', '门类': '租赁和商务服务业'},
  4846. '文物及非物质文化遗产保护': {'大类': '文化艺术业', '门类': '文化、体育和娱乐业'},
  4847. '文物和陈列品': {'大类': '文物和陈列品', '门类': '零售批发'},
  4848. '文艺创作与表演': {'大类': '文化艺术业', '门类': '文化、体育和娱乐业'},
  4849. '文艺设备': {'大类': '专用设备', '门类': '零售批发'},
  4850. '新闻业': {'大类': '新闻和出版业', '门类': '文化、体育和娱乐业'},
  4851. '旅行社及相关服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4852. '日杂用品': {'大类': '日杂用品', '门类': '零售批发'},
  4853. '有色金属冶炼及压延产品': {'大类': '建筑建材', '门类': '零售批发'},
  4854. '有色金属矿': {'大类': '矿与矿物', '门类': '零售批发'},
  4855. '木材、板材等': {'大类': '建筑建材', '门类': '零售批发'},
  4856. '木材采集和加工设备': {'大类': '专用设备', '门类': '零售批发'},
  4857. '机械设备': {'大类': '通用设备', '门类': '零售批发'},
  4858. '机械设备经营租赁': {'大类': '租赁业', '门类': '租赁和商务服务业'},
  4859. '林业产品': {'大类': '农林牧渔业产品', '门类': '零售批发'},
  4860. '林业服务': {'大类': '农林牧副渔服务', '门类': '农林牧副渔服务'},
  4861. '架线和管道工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  4862. '核工业专用设备': {'大类': '专用设备', '门类': '零售批发'},
  4863. '橡胶制品': {'大类': '橡胶、塑料、玻璃和陶瓷制品', '门类': '零售批发'},
  4864. '殡葬服务': {'大类': '居民服务业', '门类': '居民服务、修理和其他服务业'},
  4865. '殡葬设备及用品': {'大类': '专用设备', '门类': '零售批发'},
  4866. '气象服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4867. '水上交通运输设备': {'大类': '专用设备', '门类': '零售批发'},
  4868. '水上运输业': {'大类': '水上运输业', '门类': '交通运输、仓储和邮政业'},
  4869. '水利和水运工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  4870. '水工机械': {'大类': '专用设备', '门类': '零售批发'},
  4871. '水文服务': {'大类': '水利管理业', '门类': '水利、环境和公共设施管理业'},
  4872. '水资源管理': {'大类': '水利管理业', '门类': '水利、环境和公共设施管理业'},
  4873. '污水处理及其再生利用': {'大类': '水的生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  4874. '汽车、摩托车修理与维护': {'大类': '机动车、电子产品和日用产品修理业', '门类': '居民服务、修理和其他服务业'},
  4875. '法律服务': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4876. '洗染服务': {'大类': '居民服务业', '门类': '居民服务、修理和其他服务业'},
  4877. '测绘地理信息服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4878. '海洋仪器设备': {'大类': '专用设备', '门类': '零售批发'},
  4879. '海洋工程建筑': {'大类': '土木工程建筑业', '门类': '建筑业'},
  4880. '海洋服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4881. '消防设备': {'大类': '专用设备', '门类': '零售批发'},
  4882. '清洁服务': {'大类': '其他服务业', '门类': '居民服务、修理和其他服务业'},
  4883. '渔业产品': {'大类': '农林牧渔业产品', '门类': '零售批发'},
  4884. '渔业服务': {'大类': '农林牧副渔服务', '门类': '农林牧副渔服务'},
  4885. '炼焦和金属冶炼轧制设备': {'大类': '专用设备', '门类': '零售批发'},
  4886. '烟草加工设备': {'大类': '专用设备', '门类': '零售批发'},
  4887. '热力生产和供应': {'大类': '电力、热力生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  4888. '焦炭及其副产品': {'大类': '炼焦产品、炼油产品', '门类': '零售批发'},
  4889. '煤炭采选产品': {'大类': '矿与矿物', '门类': '零售批发'},
  4890. '燃气生产和供应业': {'大类': '燃气生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  4891. '物业管理': {'大类': '房地产业', '门类': '房地产业'},
  4892. '特种用途动、植物': {'大类': '农林牧渔业产品', '门类': '零售批发'},
  4893. '环保咨询': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4894. '环境与生态监测检测服务': {'大类': '专业技术服务业', '门类': '科学研究和技术服务业'},
  4895. '环境污染防治设备': {'大类': '专用设备', '门类': '零售批发'},
  4896. '环境治理业': {'大类': '生态保护和环境治理业', '门类': '水利、环境和公共设施管理业'},
  4897. '玻璃及其制品': {'大类': '橡胶、塑料、玻璃和陶瓷制品', '门类': '零售批发'},
  4898. '理发及美容服务': {'大类': '居民服务业', '门类': '居民服务、修理和其他服务业'},
  4899. '生态保护': {'大类': '生态保护和环境治理业', '门类': '水利、环境和公共设施管理业'},
  4900. '电信': {'大类': '电信、广播电视和卫星传输服务', '门类': '信息传输、软件和信息技术服务业'},
  4901. '电力、城市燃气、蒸汽和热水、水': {'大类': '电力、城市燃气、蒸汽和热水、水', '门类': '零售批发'},
  4902. '电力供应': {'大类': '电力、热力生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  4903. '电力工业专用设备': {'大类': '专用设备', '门类': '零售批发'},
  4904. '电力工程施工': {'大类': '土木工程建筑业', '门类': '建筑业'},
  4905. '电力生产': {'大类': '电力、热力生产和供应业', '门类': '电力、热力、燃气及水生产和供应业'},
  4906. '电子和通信测量仪器': {'大类': '通用设备', '门类': '零售批发'},
  4907. '电工、电子专用生产设备': {'大类': '专用设备', '门类': '零售批发'},
  4908. '电影放映': {'大类': '广播、电视、电影和影视录音制作业', '门类': '文化、体育和娱乐业'},
  4909. '电气安装': {'大类': '建筑安装业', '门类': '建筑业'},
  4910. '电气设备': {'大类': '通用设备', '门类': '零售批发'},
  4911. '电气设备修理': {'大类': '金属制品、机械和设备修理业', '门类': '金属制品、机械和设备修理业'},
  4912. '畜牧业服务': {'大类': '农林牧副渔服务', '门类': '农林牧副渔服务'},
  4913. '监控设备': {'大类': '通用设备', '门类': '零售批发'},
  4914. '石油制品': {'大类': '炼焦产品、炼油产品', '门类': '零售批发'},
  4915. '石油和化学工业专用设备': {'大类': '专用设备', '门类': '零售批发'},
  4916. '石油和天然气开采产品': {'大类': '矿与矿物', '门类': '零售批发'},
  4917. '石油天然气开采专用设备': {'大类': '专用设备', '门类': '零售批发'},
  4918. '研究和试验发展': {'大类': '研究和试验发展', '门类': '科学研究和技术服务业'},
  4919. '社会工作': {'大类': '社会工作', '门类': '卫生和社会工作'},
  4920. '社会经济咨询': {'大类': '商务服务业', '门类': '租赁和商务服务业'},
  4921. '科技推广和应用服务业': {'大类': '科技推广和应用服务业', '门类': '科学研究和技术服务业'},
  4922. '科研、医疗、教育用房': {'大类': '房屋建筑业', '门类': '建筑业'},
  4923. '管道和设备安装': {'大类': '建筑安装业', '门类': '建筑业'},
  4924. '粮油作物和饲料加工设备': {'大类': '专用设备', '门类': '零售批发'},
  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. self.sess = tf.Session(graph=tf.Graph())
  4969. self.get_model()
  4970. with open(os.path.dirname(__file__)+'/industry_rule_kw_json/tw_industry_keyword_org/tw_industry_keyword_org.json', 'r',
  4971. encoding='utf-8') as fp1:
  4972. self.json_data_industry = json.load(fp1)
  4973. with open(os.path.dirname(__file__)+'/industry_rule_kw_json/tw_company_classification_keyword/tw_company_classification_keyword.json', 'r',
  4974. encoding='utf-8') as fp2:
  4975. self.json_data_company = json.load(fp2)
  4976. with open(os.path.dirname(__file__)+'/industry_rule_kw_json/tw_custom_keyword/tw_custom_keyword.json', 'r', encoding='utf-8') as fp3:
  4977. self.json_data_custom = json.load(fp3)
  4978. def get_model(self):
  4979. with self.sess.as_default() as sess:
  4980. with self.sess.graph.as_default():
  4981. meta_graph_def = tf.saved_model.loader.load(sess,
  4982. tags=['serve'],
  4983. export_dir=os.path.dirname(__file__)+'/industry_model')
  4984. signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  4985. signature_def = meta_graph_def.signature_def
  4986. self.title = sess.graph.get_tensor_by_name(signature_def[signature_key].inputs['title'].name)
  4987. self.project = sess.graph.get_tensor_by_name(signature_def[signature_key].inputs['project'].name)
  4988. self.product = sess.graph.get_tensor_by_name(signature_def[signature_key].inputs['product'].name)
  4989. self.outputs = sess.graph.get_tensor_by_name(signature_def[signature_key].outputs['outputs'].name)
  4990. def text2array(self, text, tenderee='', maxSententLen=20):
  4991. tenderee = tenderee.replace('(', '(').replace(')', ')')
  4992. text = text.replace('(', '(').replace(')', ')')
  4993. text = re.sub(
  4994. '(废标|终止|综?合?评审|评标|开标|资审|履约|验收|成交|中标人?|中选人?|单一来源|合同|候选人|结果|变更|更正|答疑|澄清|意向|需求|采购|招标|询比?价|磋商|谈判|比选|比价|竞价|议价)的?(公告|预告|公示)?|关于为?|选取|定点|直接|邀请函?|通知书?|备案|公开|公示|公告|记录|竞争性',
  4995. ' ', text)
  4996. text = text.replace(tenderee, ' ')
  4997. text = ' ' if text=="" else text
  4998. words_docs_list = selffool.cut(text)
  4999. words_docs_list = [[it for it in l if re.search('^[\u4e00-\u9fa5]+$', it)][-maxSententLen:] for l in words_docs_list]
  5000. array = embedding(words_docs_list, shape=(len(words_docs_list), maxSententLen, 128))
  5001. return array
  5002. def process(self, title, project, product, tenderee):
  5003. return self.text2array(title, tenderee), self.text2array(project, tenderee), self.text2array(product)
  5004. def predict_model(self, title, project, product, tenderee=''):
  5005. title_array, project_array, product_array = self.process(title, project, product, tenderee)
  5006. rs = self.sess.run(self.outputs,
  5007. feed_dict={
  5008. self.title:title_array,
  5009. self.project:project_array,
  5010. self.product:product_array
  5011. }
  5012. )
  5013. pred = np.argmax(rs[0])
  5014. return self.id2lb[pred], rs[0][pred]
  5015. # # 返回top2 结果
  5016. # pred_list = np.argsort(-rs[0])
  5017. # return self.id2lb[pred_list[0]], self.id2lb[pred_list[1]], rs[0][pred_list[0]], rs[0][pred_list[1]]
  5018. def predict_rule(self, doctitle, tenderee, win_tenderer, project_name, product):
  5019. doctitle = doctitle if doctitle else ''
  5020. tenderee = tenderee if tenderee else ''
  5021. win_tenderer = win_tenderer if win_tenderer else ''
  5022. project_name = project_name if project_name else ''
  5023. product = product if product else ''
  5024. text_ind = (doctitle + project_name + product).replace(tenderee, '')
  5025. text_ind = text_ind.replace('墙面粉刷', '墙面 粉刷')
  5026. text_com = win_tenderer
  5027. length_ind_text = len(text_ind) + 1
  5028. length_com_text = len(text_com) + 1
  5029. # print(text)
  5030. dic_res = {} # 行业分类字典
  5031. score_lst = [] # 得分列表
  5032. word_lst = [] # 关键词列表
  5033. # 主要内容关键词
  5034. if text_ind:
  5035. # logging.info("data_ind%s"%str(_json_data_industry[0]))
  5036. for data_industry in self.json_data_industry:
  5037. industry = data_industry['xiaolei']
  5038. key_word = data_industry['key_word']
  5039. key_word_2 = data_industry['key_word2']
  5040. power = float(data_industry['power']) if data_industry['power'] else 0
  5041. this_score = power * (text_ind.count(key_word) * len(key_word) / length_ind_text)
  5042. if key_word_2:
  5043. # key_word_compose = key_word + "+" + key_word_2
  5044. if text_ind.count(key_word_2) == 0:
  5045. this_score = 0
  5046. if this_score > 0:
  5047. # print(industry,key_word,this_score)
  5048. if industry in dic_res.keys():
  5049. dic_res[industry] += this_score
  5050. else:
  5051. dic_res[industry] = this_score
  5052. if key_word not in word_lst:
  5053. word_lst.append(key_word)
  5054. # 供应商关键词
  5055. if text_com:
  5056. for data_company in self.json_data_company:
  5057. industry = data_company['industry_type']
  5058. key_word = data_company['company_word']
  5059. power = float(data_company['industry_rate']) if data_company['industry_rate'] else 0
  5060. this_score = power * (text_com.count(key_word) * len(key_word) / length_com_text)
  5061. if this_score > 0:
  5062. # print(industry,key_word,this_score)
  5063. if industry in dic_res.keys():
  5064. dic_res[industry] += this_score
  5065. else:
  5066. dic_res[industry] = this_score
  5067. if key_word not in word_lst:
  5068. word_lst.append(key_word)
  5069. # 自定义关键词
  5070. if text_ind:
  5071. custom_ind = [
  5072. ['tenderee', '医院|疾病预防', ['设备', '系统', '器'], '医疗设备'],
  5073. ['tenderee', '学校|大学|小学|中学|学院|幼儿园', ['设备', '器'], '教育设备'],
  5074. ['tenderee', '学校|大学|小学|中学|学院|幼儿园|医院', ['工程'], '科研、医疗、教育用房'],
  5075. ['tenderee', '供电局|电网|国网|电力|电厂|粤电', ['设备', '器', '物资'], '电力工业专用设备'],
  5076. ['tenderee', '公安|法院|检察院', ['设备', '器'], '政法、检测专用设备'],
  5077. ['tenderee', '^中铁|^中交|^中建|中国建筑', ['材料'], '其他建筑建材'],
  5078. ['doctextcon', '信息技术服务|系统开发|信息化|信息系统', ['监理'], '信息技术咨询服务'],
  5079. ['doctextcon', '工程', ['消防'], '专业施工'],
  5080. ['doctextcon', '铁路|航空|船舶|航天|广铁', ['维修'], '铁路、船舶、航空航天等运输设备修理'],
  5081. ['doctextcon', '设备|仪|器', ['租赁'], '机械设备经营租赁'],
  5082. ['doctextcon', '交通|铁路|公路|道路|桥梁', ['工程'], '铁路、道路、隧道和桥梁工程建筑'],
  5083. ['win_tenderer', '电力', ['设备', '器'], '电力工业专用设备'],
  5084. ['win_tenderer', '信息|网络科技', ['系统'], '信息系统集成和物联网技术服务'],
  5085. ['tenderee,doctextcon', '铁路|广铁|铁道', ['设备', '器', '物资', '材料', '铁路'], '铁路运输设备'],
  5086. ]
  5087. for data_custom in self.json_data_custom:
  5088. industry_custom = data_custom['industry']
  5089. key_word = data_custom['company_word']
  5090. power = float(data_custom['industry_rate'])
  5091. for k in range(len(custom_ind)):
  5092. subject = ''
  5093. if 'tenderee' in custom_ind[k][0]:
  5094. subject += tenderee
  5095. if 'win_tenderer' in custom_ind[k][0]:
  5096. subject += win_tenderer
  5097. if 'doctextcon' in custom_ind[k][0]:
  5098. subject += text_ind
  5099. ptn = custom_ind[k][1]
  5100. # print('ptn',ptn)
  5101. if re.search(ptn, subject) and industry_custom in custom_ind[k][2]:
  5102. industry = custom_ind[k][3]
  5103. else:
  5104. continue
  5105. this_score = power * (text_ind.count(key_word) * len(key_word) / len(subject))
  5106. if this_score > 0:
  5107. # print(industry,key_word,this_score)
  5108. if industry in dic_res.keys():
  5109. dic_res[industry] += this_score
  5110. else:
  5111. dic_res[industry] = this_score
  5112. if key_word not in word_lst:
  5113. word_lst.append(key_word)
  5114. sort_res = sorted(dic_res.items(), key=lambda x: x[1], reverse=True)
  5115. lst_res = [s[0] for s in sort_res]
  5116. score_lst = [str(round(float(s[1]), 2)) for s in sort_res]
  5117. if len(lst_res) > 0:
  5118. return lst_res, score_lst, word_lst
  5119. else:
  5120. return [""], [], []
  5121. def predict_merge(self, pinmu_type, industry_lst):
  5122. '''
  5123. 通过一系列规则最终决定使用模型还是规则的结果
  5124. :param pinmu_type: 模型预测类别
  5125. :param industry_lst: 规则预测类别列表
  5126. :return:
  5127. '''
  5128. industry_type = industry_lst[0]
  5129. if industry_type == "":
  5130. return pinmu_type
  5131. if industry_type == '专用设备修理' and re.search('修理|维修|装修|修缮', pinmu_type):
  5132. final_type = pinmu_type
  5133. elif industry_type == '其他土木工程建筑' and re.search('工程|建筑|用房|施工|安装|质检|其他专业咨询与调查', pinmu_type):
  5134. final_type = pinmu_type
  5135. elif pinmu_type == '专用设备修理' and re.search('工程|修理', industry_type):
  5136. final_type = industry_type
  5137. elif pinmu_type == '信息系统集成和物联网技术服务' and re.search('卫星传输|信息处理和存储支持服务|信息技术咨询服务|运行维护服务|其他专业技术服务|医疗设备|医药品',
  5138. industry_type):
  5139. final_type = industry_type
  5140. elif industry_type == '仪器仪表' and re.search('仪器|器具|医疗设备', pinmu_type):
  5141. final_type = pinmu_type
  5142. elif industry_type == '医药品' and re.search('医疗设备', pinmu_type):
  5143. final_type = pinmu_type
  5144. elif industry_type == '医药品' and re.search('医疗设备', pinmu_type):
  5145. final_type = pinmu_type
  5146. elif re.search('设备', industry_type) and re.search('修理|维修', pinmu_type):
  5147. final_type = pinmu_type
  5148. elif industry_type == '社会工作' and re.search('工程', pinmu_type):
  5149. final_type = pinmu_type
  5150. elif industry_type == '信息系统集成和物联网技术服务' and re.search('信息处理|设备', pinmu_type):
  5151. final_type = pinmu_type
  5152. elif industry_type == '研究和试验发展' and re.search('其他专业咨询与调查|质检技术服务|信息系统集成|其他工程服务', pinmu_type):
  5153. final_type = pinmu_type
  5154. elif industry_type == '其他专业咨询与调查' and re.search('工程造价服务', pinmu_type):
  5155. final_type = pinmu_type
  5156. elif industry_type == '广告业' and re.search('印刷服务|影视节目制作|信息系统', pinmu_type):
  5157. final_type = pinmu_type
  5158. elif industry_type == '清洁服务' and re.search('工程|环境污染防治设备|修理', pinmu_type):
  5159. final_type = pinmu_type
  5160. elif industry_type == '其他公共设施管理' and re.search('信息系统', pinmu_type):
  5161. final_type = pinmu_type
  5162. elif industry_type == '其他专业技术服务' and re.search('工程技术与设计服务|质检技术服务|环境与生态监测检测服务', pinmu_type):
  5163. final_type = pinmu_type
  5164. elif industry_type == '机械设备经营租赁' and re.search('电信', pinmu_type):
  5165. final_type = pinmu_type
  5166. elif industry_type == '货币金融服务' and re.search('信息系统集成和物联网技术服务', pinmu_type):
  5167. final_type = pinmu_type
  5168. elif industry_type == '体育场地设施管理' and re.search('体育设备', pinmu_type):
  5169. final_type = pinmu_type
  5170. elif industry_type == '安全保护服务' and re.search('信息系统|监控设备|互联网安全服务', pinmu_type):
  5171. final_type = pinmu_type
  5172. elif industry_type == '互联网接入及相关服务' and re.search('通信设备', pinmu_type):
  5173. final_type = pinmu_type
  5174. elif industry_type == '卫生' and re.search('医疗设备|信息系统', pinmu_type):
  5175. final_type = pinmu_type
  5176. elif pinmu_type == '研究和试验发展' and re.search('其他工程服务', industry_type):
  5177. final_type = industry_type
  5178. elif pinmu_type == '办公设备' and re.search('教育设备', industry_type):
  5179. final_type = industry_type
  5180. elif re.search('车辆|机械设备经营租赁', pinmu_type) and re.search('公路旅客运输', industry_type):
  5181. final_type = industry_type
  5182. elif len(industry_lst) > 1 and pinmu_type == industry_lst[1] and re.search('会计|法律|物业|家具|印刷|互联网安全',
  5183. industry_type) == None \
  5184. and re.search('其他|人力资源服务', pinmu_type) == None:
  5185. final_type = pinmu_type
  5186. elif industry_type != "":
  5187. final_type = industry_type
  5188. else:
  5189. final_type = pinmu_type
  5190. return final_type
  5191. def predict(self, title, project, product, prem):
  5192. def get_ree_win(prem):
  5193. tenderee = ""
  5194. win_tenderer = ""
  5195. try:
  5196. for v in prem[0]['prem'].values():
  5197. for link in v['roleList']:
  5198. if link['role_name'] == 'tenderee' and tenderee == "":
  5199. tenderee = link['role_text']
  5200. elif link['role_name'] == 'win_tenderer' and win_tenderer == "":
  5201. win_tenderer = link['role_text']
  5202. except Exception as e:
  5203. print('解析prem 获取招标人、中标人出错')
  5204. return tenderee, win_tenderer
  5205. tenderee, win_tenderer = get_ree_win(prem)
  5206. result_model, prob = self.predict_model(title, project, product, tenderee)
  5207. industry_lst, score_lst, word_lst = self.predict_rule(title, tenderee, win_tenderer, project, product)
  5208. final_type = self.predict_merge(result_model, industry_lst)
  5209. # print('模型:%s;规则:%s;最终:%s'%(result_model, industry_lst[0], final_type))
  5210. # return {'industry': final_type}
  5211. return {'industry': {
  5212. 'class_name': final_type,
  5213. 'subclass': self.industry_dic[final_type]['大类'],
  5214. 'class': self.industry_dic[final_type]['门类']
  5215. }
  5216. }
  5217. class DistrictPredictor():
  5218. def __init__(self):
  5219. # with open(os.path.dirname(__file__)+'/district_dic.pkl', 'rb') as f:
  5220. # dist_dic = pickle.load(f)
  5221. # short_name = '|'.join(sorted(set([v['简称'] for v in dist_dic.values()]), key=lambda x: len(x), reverse=True))
  5222. # full_name = '|'.join(sorted(set([v['全称'] for v in dist_dic.values()]), key=lambda x: len(x), reverse=True))
  5223. # short2id = {}
  5224. # full2id = {}
  5225. # for k, v in dist_dic.items():
  5226. # if v['简称'] not in short2id:
  5227. # short2id[v['简称']] = [k]
  5228. # else:
  5229. # short2id[v['简称']].append(k)
  5230. # if v['全称'] not in full2id:
  5231. # full2id[v['全称']] = [k]
  5232. # else:
  5233. # full2id[v['全称']].append(k)
  5234. # self.dist_dic = dist_dic
  5235. # self.short_name = short_name
  5236. # self.full_name = full_name
  5237. # self.short2id = short2id
  5238. # self.full2id = full2id
  5239. # # self.f = open(os.path.dirname(__file__)+'/../test/data/district_predict.txt', 'w', encoding='utf-8')
  5240. with open(os.path.dirname(__file__)+'/district_tuple.pkl', 'rb') as f:
  5241. district_tuple = pickle.load(f)
  5242. self.p_pro, self.p_city, self.p_dis, self.idx_dic, self.full_dic, self.short_dic = district_tuple
  5243. def predict_backup(self, project_name, prem, title, list_articles, web_source_name = "", list_entitys=""):
  5244. '''
  5245. 先匹配 project_name+tenderee+tenderee_address, 如果缺少省或市 再匹配 title+content
  5246. :param project_name:
  5247. :param prem:
  5248. :param title:
  5249. :param list_articles:
  5250. :param web_source_name:
  5251. :return:
  5252. '''
  5253. def get_ree_addr(prem):
  5254. tenderee = ""
  5255. tenderee_address = ""
  5256. try:
  5257. for v in prem[0]['prem'].values():
  5258. for link in v['roleList']:
  5259. if link['role_name'] == 'tenderee' and tenderee == "":
  5260. tenderee = link['role_text']
  5261. tenderee_address = link['address']
  5262. except Exception as e:
  5263. print('解析prem 获取招标人、及地址出错')
  5264. return tenderee, tenderee_address
  5265. def get_area(text, web_source_name, not_in_content=True):
  5266. score_l = []
  5267. id_set = set()
  5268. if re.search(self.short_name, text):
  5269. for it in re.finditer(self.full_name, text):
  5270. name = it.group(0)
  5271. score = len(name) / len(text)
  5272. for _id in self.full2id[name]:
  5273. area = self.dist_dic[_id]['area'] + [''] * (3 - len(self.dist_dic[_id]['area']))
  5274. # score_l.append([_id, score] + area)
  5275. # w = self.dist_dic[_id]['权重']
  5276. score_l.append([_id, score + 1] + area) # 匹配全称的加1 ,不加权重,因为权重某些赋值不好
  5277. flag = 0
  5278. for it in re.finditer(self.short_name, text):
  5279. if it.end() < len(text) and re.search('^(村|镇|街|路|江|河|湖|北路|南路|东路|大道|社区)', text[it.end():]) == None:
  5280. name = it.group(0)
  5281. score = (it.start() + len(name)) / len(text)
  5282. for _id in self.short2id[name]:
  5283. score2 = 0
  5284. w = self.dist_dic[_id]['权重']
  5285. _type = self.dist_dic[_id]['类型']
  5286. area = self.dist_dic[_id]['area'] + [''] * (3 - len(self.dist_dic[_id]['area']))
  5287. if area[0] in ['2', '16', '20', '30']:
  5288. _type += 10
  5289. if w < 1 and it.end() < len(text) and text[it.end()] in ['省', '市', '县']: # 如果简称后面 有省市县权重改为1
  5290. w = 1
  5291. score2 += w
  5292. if _id not in id_set:
  5293. if _type == 20:
  5294. type_w = 3
  5295. elif _type == 30:
  5296. if it.start()>3 and text[it.start()-1] == '市': # 城市后面 简称不能作为市
  5297. type_w = 0
  5298. else:
  5299. type_w = 2
  5300. else:
  5301. if it.end()<len(text) and text[it.end()] == '市': # 简称后面 有市字 改为市级
  5302. type_w = 2
  5303. else:
  5304. type_w = 0.5
  5305. id_set.add(_id)
  5306. score2 += w * type_w
  5307. score_l.append([_id, score * w + score2] + area)
  5308. if flag == 1:
  5309. pass
  5310. # print('score', score)
  5311. if re.search('公司', web_source_name) == None:
  5312. for it in re.finditer(self.short_name, web_source_name):
  5313. name = it.group(0)
  5314. for _id in self.short2id[name]:
  5315. area = self.dist_dic[_id]['area'] + [''] * (3 - len(self.dist_dic[_id]['area']))
  5316. w = self.dist_dic[_id]['权重']
  5317. score = w * 0.2
  5318. score_l.append([_id, score] + area)
  5319. area_dic = {'area': '全国', 'province': '全国', 'city': '未知', 'district': '未知', "is_in_text": False}
  5320. if len(score_l) == 0:
  5321. return {'district': area_dic}
  5322. else:
  5323. df = pd.DataFrame(score_l, columns=['id', 'score', 'province', 'city', 'district'])
  5324. df['简称'] = df['id'].apply(lambda x: self.dist_dic[x]['地区'])
  5325. # print('地区评分:')
  5326. # print(df)
  5327. df_pro = df.groupby('province').sum().sort_values(by=['score'], ascending=False)
  5328. pro_id = df_pro.index[0]
  5329. if df_pro.loc[pro_id, 'score'] < 0.1 and not_in_content: # 不是二次全文匹配的 省级评分小于0.1的不要
  5330. # print('评分低于0.1', df_pro.loc[pro_id, 'score'], self.dist_dic[pro_id]['地区'])
  5331. return {'district': area_dic}
  5332. area_dic['province'] = self.dist_dic[pro_id]['地区']
  5333. area_dic['area'] = self.dist_dic[pro_id]['大区']
  5334. df = df[df['city'] != ""]
  5335. df = df[df['province'] == pro_id]
  5336. if len(df) > 0:
  5337. df_city = df.groupby('city').sum().sort_values(by=['score'], ascending=False)
  5338. city_id = df_city.index[0]
  5339. area_dic['city'] = self.dist_dic[city_id]['地区']
  5340. df = df[df['district'] != ""]
  5341. df = df[df['city'] == city_id]
  5342. if len(df) > 0:
  5343. df_dist = df.groupby('district').sum().sort_values(by=['score'], ascending=False)
  5344. dist_id = df_dist.index[0]
  5345. area_dic['district'] = self.dist_dic[dist_id]['地区']
  5346. # print(area_dic)
  5347. return {'district': area_dic}
  5348. def get_role_address(text):
  5349. '''正则匹配获取招标人地址
  5350. 3:地址直接在招标人后面 招标人:xxx,地址:xxx
  5351. 4:招标、代理一起,两个地址一起 招标人:xxx, 代理人:xxx, 地址:xxx, 地址:xxx.
  5352. '''
  5353. p3 = '(招标|采购|甲)(人|方|单位)(信息:|(甲方))?(名称)?:[\w()]{4,15},(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5354. p4 = '(招标|采购|甲)(人|方|单位)(信息:|(甲方))?(名称)?:[\w()]{4,15},(招标|采购)?代理(人|机构)(名称)?:[\w()]{4,15},(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5355. p5 = '(采购|招标)(人|单位)(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5356. if re.search(p3, text):
  5357. return re.search(p3, text).group('addr')
  5358. elif re.search(p4, text):
  5359. return re.search(p4, text).group('addr')
  5360. elif re.search(p5, text):
  5361. return re.search(p5, text).group('addr')
  5362. else:
  5363. return ''
  5364. def get_project_addr(text):
  5365. p1 = '(项目(施工|实施)?|建设|工程|服务|交货|送货|收货|展示|看样|拍卖)(地址|地点|位置|所在地区?):(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5366. if re.search(p1, text):
  5367. return re.search(p1, text).group('addr')
  5368. else:
  5369. return ''
  5370. def get_bid_addr(text):
  5371. p2 = '(磋商|谈判|开标|投标|评标|报名|递交|评审|发售)(地址|地点|所在地区?):(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5372. if re.search(p2, text):
  5373. return re.search(p2, text).group('addr')
  5374. else:
  5375. return ''
  5376. def get_all_addr(list_entitys):
  5377. tenderee_l = []
  5378. addr_l = []
  5379. for ent in list_entitys[0]:
  5380. if ent.entity_type == 'location' and len(ent.entity_text)>2:
  5381. addr_l.append(ent.entity_text)
  5382. elif ent.entity_type in ['org', 'company']:
  5383. if ent.label in [0, 1]: # 加招标或代理
  5384. tenderee_l.append(ent.entity_text)
  5385. return ' '.join(addr_l), ' '.join(tenderee_l)
  5386. def get_title_addr(text):
  5387. p1 = '(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5388. if re.search(p1, text):
  5389. return re.search(p1, text).group('addr')
  5390. else:
  5391. return ''
  5392. if '##attachment##' in list_articles[0].content:
  5393. content, attachment = list_articles[0].content.split('##attachment##')
  5394. if len(content) < 200:
  5395. content += attachment
  5396. else:
  5397. content = list_articles[0].content
  5398. tenderee, tenderee_address = get_ree_addr(prem)
  5399. msc = ""
  5400. pro_addr = get_project_addr(content)
  5401. if pro_addr != "":
  5402. msc += '使用规则提取的项目地址;'
  5403. tenderee_address = pro_addr
  5404. else:
  5405. role_addr = get_role_address(content)
  5406. if role_addr != "":
  5407. msc += '使用规则提取的联系人地址;'
  5408. tenderee_address = role_addr
  5409. if tenderee_address == "":
  5410. title_addr = get_title_addr(title)
  5411. if title_addr != "":
  5412. msc += '使用规则提取的标题地址;'
  5413. tenderee_address = title_addr
  5414. else:
  5415. bid_addr = get_bid_addr(content)
  5416. if bid_addr != "":
  5417. msc += '使用规则提取的开标地址;'
  5418. tenderee_address = bid_addr
  5419. project_name = str(project_name)
  5420. tenderee = str(tenderee)
  5421. # print('招标人地址',role_addr, tenderee_address)
  5422. project_name = project_name + title if project_name not in title else project_name
  5423. project_name = project_name.replace(tenderee, '')
  5424. text1 = "{0} {1} {2}".format(project_name, tenderee, tenderee_address)
  5425. web_source_name = str(web_source_name) # 修复某些不是字符串类型造成报错
  5426. text1 = re.sub('复合肥|铁路|公路|新会计', ' ', text1) #预防提取错 合肥 路南 新会 等地区
  5427. if pro_addr:
  5428. msc += '## 使用项目地址输入:%s ##;' % pro_addr
  5429. rs = get_area(pro_addr, '')
  5430. msc += '预测结果:省份:%s, 城市:%s,区县:%s;' % (
  5431. rs['district']['province'], rs['district']['city'], rs['district']['district'])
  5432. if rs['district']['province'] != '全国':
  5433. # print('地区匹配:', msc)
  5434. return rs
  5435. # print('text1:', text1)
  5436. msc += '## 第一次预测输入:%s ##;'%text1
  5437. rs = get_area(text1, web_source_name)
  5438. msc += '预测结果:省份:%s, 城市:%s,区县:%s;' % (
  5439. rs['district']['province'], rs['district']['city'], rs['district']['district'])
  5440. # self.f.write('%s %s \n' % (list_articles[0].id, msc))
  5441. # print('地区匹配:', msc)
  5442. if rs['district']['province'] == '全国' or rs['district']['city'] == '未知':
  5443. msc = ""
  5444. all_addr, tenderees = get_all_addr(list_entitys)
  5445. text2 = tenderees + " " + all_addr + ' ' + title
  5446. msc += '使用实体列表所有招标人+所有地址;'
  5447. # text2 += title + content if len(content)<2000 else title + content[:1000] + content[-1000:]
  5448. text2 = re.sub('复合肥|铁路|公路|新会计', ' ', text2)
  5449. # print('text2:', text2)
  5450. msc += '## 第二次预测输入:%s ##'%text2
  5451. rs2 = get_area(text2, web_source_name, not_in_content=False)
  5452. rs2['district']['is_in_text'] = True
  5453. if rs['district']['province'] == '全国' and rs2['district']['province'] != '全国':
  5454. rs = rs2
  5455. elif rs['district']['province'] == rs2['district']['province'] and rs2['district']['city'] != '未知':
  5456. rs = rs2
  5457. msc += '预测结果:省份:%s, 城市:%s,区县:%s'%(
  5458. rs['district']['province'],rs['district']['city'],rs['district']['district'])
  5459. # self.f.write('%s %s \n'%(list_articles[0].id, msc))
  5460. # print('地区匹配:', msc)
  5461. return rs
  5462. def get_area(self, text, web_name, in_content=False):
  5463. 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
  5464. def get_final_addr(pro_ids, city_ids, dis_ids):
  5465. '''
  5466. 先把所有匹配的全称、简称转为id,如果省份不为空,城市不为空且有城市属于省份的取该城市
  5467. :param province_l: 匹配到的所有省份
  5468. :param city_l: 匹配到的所有城市
  5469. :param district_l: 匹配到的所有区县
  5470. :return:
  5471. '''
  5472. big_area = ""
  5473. pred_pro = ""
  5474. pred_city = ""
  5475. pred_dis = ""
  5476. final_pro = ""
  5477. final_city = ""
  5478. if len(pro_ids) >= 1:
  5479. pro_l = sorted([(k, v) for k, v in pro_ids.items()], key=lambda x: x[1], reverse=True)
  5480. final_pro, score = pro_l[0]
  5481. if score >= 0.01:
  5482. pred_pro = idx_dic[final_pro]['返回名称']
  5483. big_area = idx_dic[final_pro]['大区']
  5484. # else:
  5485. # print("得分过低,过滤掉", idx_dic[final_pro]['返回名称'], score)
  5486. if pred_pro != "" and len(city_ids) >= 1:
  5487. city_l = sorted([(k, v) for k, v in city_ids.items()], key=lambda x: x[1], reverse=True)
  5488. for it in city_l:
  5489. if idx_dic[it[0]]['省'] == final_pro:
  5490. final_city = it[0]
  5491. pred_city = idx_dic[final_city]['返回名称']
  5492. break
  5493. if final_city != "" and len(set(dis_ids)) >= 1:
  5494. dis_l = sorted([(k, v) for k, v in dis_ids.items()], key=lambda x: x[1], reverse=True)
  5495. for it in dis_l:
  5496. if idx_dic[it[0]]['市'] == final_city:
  5497. pred_dis = idx_dic[it[0]]['返回名称']
  5498. if pred_city in ['北京', '天津', '上海', '重庆']:
  5499. pred_city = pred_dis
  5500. pred_dis = ""
  5501. return big_area, pred_pro, pred_city, pred_dis
  5502. def find_areas(pettern, text):
  5503. '''
  5504. 通过正则匹配字符串返回地址
  5505. :param pettern: 地址正则 广东省|广西省|...
  5506. :param text: 待匹配文本
  5507. :return:
  5508. '''
  5509. addr = []
  5510. for it in re.finditer(pettern, text):
  5511. if re.search('[省市区县旗盟]$', it.group(0)) == None and re.search(
  5512. '^([东南西北中一二三四五六七八九十大小]?(村|镇|街|路|道|社区)|酒店|宾馆)', text[it.end():]):
  5513. continue
  5514. if it.group(0) == '站前': # 20240314 修复类似 中铁二局新建沪苏湖铁路工程站前VI标项目 错识别为 省份:辽宁, 城市:营口,区县:站前
  5515. continue
  5516. if re.search('^(经济开发区|开发区|新区)', text[it.end():]) and re.search('广州市', pettern): # 城市不匹配为区的地址 修复 滨州北海经济开发区 北海新区 等提取为北海
  5517. continue
  5518. addr.append((it.group(0), it.start(), it.end()))
  5519. if re.search('^([分支](公司|局|行|校|院|干?线)|\w{,3}段|地铁|(火车|高铁)?站|\w{,3}项目)', text[it.end():]):
  5520. addr.append((it.group(0), it.start(), it.end()))
  5521. return addr
  5522. def chage_area2score(group_list, max_len):
  5523. '''
  5524. 把匹配的的地址转为分数
  5525. :param group_list: [('name', b, e)]
  5526. :return:
  5527. '''
  5528. area_list = []
  5529. if group_list != []:
  5530. for it in group_list:
  5531. name, b, e = it
  5532. area_list.append((name, (e - b + e) / max_len / 2))
  5533. return area_list
  5534. def find_whole_areas(text):
  5535. '''
  5536. 通过正则匹配字符串返回地址
  5537. :param pettern: 地址正则 广东省|广西省|...
  5538. :param text: 待匹配文本
  5539. :return:
  5540. '''
  5541. pettern = "((?P<prov>%s)(?P<city>%s)?(?P<dist>%s)?)|((?P<city1>%s)(?P<dist1>%s)?)|(?P<dist2>%s)" % (
  5542. p_pro, p_city, p_dis, p_city, p_dis, p_dis)
  5543. province_l, city_l, district_l = [], [], []
  5544. for it in re.finditer(pettern, text):
  5545. if re.search('[省市区县旗盟]$', it.group(0)) == None and re.search(
  5546. '^([东南西北中一二三四五六七八九十大小]?(村|镇|街|路|道|社区)|酒店|宾馆)', text[it.end():]):
  5547. continue
  5548. if it.group(0) == '站前': # 20240314 修复类似 中铁二局新建沪苏湖铁路工程站前VI标项目 错识别为 省份:辽宁, 城市:营口,区县:站前
  5549. continue
  5550. for k, v in it.groupdict().items():
  5551. if v != None:
  5552. if k in ['prov']:
  5553. province_l.append((it.group(k), it.start(k), it.end(k)))
  5554. elif k in ['city', 'city1']:
  5555. if re.search('^(经济开发区|开发区|新区)', text[it.end(k):]): # 城市不匹配为区的地址 修复 滨州北海经济开发区 北海新区 等提取为北海
  5556. continue
  5557. city_l.append((it.group(k), it.start(k), it.end(k)))
  5558. if re.search('^([分支](公司|局|行|校|院|干?线)|\w{,3}段|地铁|(火车|高铁)?站|\w{,3}项目)', text[it.end(k):]):
  5559. city_l.append((it.group(k), it.start(k), it.end(k)))
  5560. elif k in ['dist', 'dist1', 'dist2']:
  5561. if it.group(k)=='昌江' and '景德镇' not in it.group(0):
  5562. district_l.append(('昌江黎族', it.start(k), it.end(k)))
  5563. else:
  5564. district_l.append((it.group(k), it.start(k), it.end(k)))
  5565. return province_l, city_l, district_l
  5566. def get_pro_city_dis_score(text, text_weight=1):
  5567. text = re.sub('复合肥|海南岛|兴业银行|双河口|阳光|杭州湾', ' ', text)
  5568. text = re.sub('珠海城市', '珠海', text) # 修复 426624023 珠海城市 预测为海城市
  5569. text = re.sub('怒江州', '怒江傈僳族自治州', text) # 修复 423589589 所属地域:怒江州 识别为广西 - 崇左 - 江州
  5570. text = re.sub('茂名滨海新区', '茂名市', text)
  5571. text = re.sub('中山([东南西][部区环]|黄圃|南头|东凤|小榄|石岐|翠亨|南朗)', '中山市', text)
  5572. ser = re.search('海南(昌江|白沙|乐东|陵水|保亭|琼中)(黎族)?', text)
  5573. if ser and '黎族' not in ser.group(0):
  5574. text = text.replace(ser.group(0), ser.group(0)+'黎族')
  5575. # province_l = find_areas(p_pro, text)
  5576. # city_l = find_areas(p_city, text)
  5577. # district_l = find_areas(p_dis, text)
  5578. province_l, city_l, district_l = find_whole_areas(text) # 20240703 优化地址提取,解决类似 海南昌江 得到 海南 南昌 结果
  5579. if len(province_l) == len(city_l) == 0:
  5580. district_l = [it for it in district_l if
  5581. re.search('[市县旗区]$', it[0])] # 20240428去掉只有区县地址且不是全称的匹配,避免错误 例 凌云工业股份有限公司 提取地区为广西白色凌云
  5582. province_l = chage_area2score(province_l, max_len=len(text))
  5583. city_l = chage_area2score(city_l, max_len=len(text))
  5584. district_l = chage_area2score(district_l, max_len=len(text))
  5585. pro_ids = dict()
  5586. city_ids = dict()
  5587. dis_ids = dict()
  5588. for pro in province_l:
  5589. name, score = pro
  5590. assert (name in full_dic['province'] or name in short_dic['province'])
  5591. if name in full_dic['province']:
  5592. idx = full_dic['province'][name]
  5593. if idx not in pro_ids:
  5594. pro_ids[idx] = 0
  5595. pro_ids[idx] += (score + 1)
  5596. else:
  5597. idx = short_dic['province'][name]
  5598. if idx not in pro_ids:
  5599. pro_ids[idx] = 0
  5600. pro_ids[idx] += (score + 0)
  5601. for city in city_l:
  5602. name, score = city
  5603. if name in full_dic['city']:
  5604. w = 0.1 if len(full_dic['city'][name]) > 1 else 1
  5605. for idx in full_dic['city'][name]:
  5606. if idx not in city_ids:
  5607. city_ids[idx] = 0
  5608. # weight = idx_dic[idx]['权重']
  5609. city_ids[idx] += (score + 2) * w
  5610. pro_idx = idx_dic[idx]['省']
  5611. if pro_idx in pro_ids:
  5612. pro_ids[pro_idx] += (score + 2) * w
  5613. else:
  5614. pro_ids[pro_idx] = (score + 2) * w * 0.5
  5615. elif name in short_dic['city']:
  5616. w = 0.1 if len(short_dic['city'][name]) > 1 else 1
  5617. for idx in short_dic['city'][name]:
  5618. if idx not in city_ids:
  5619. city_ids[idx] = 0
  5620. weight = idx_dic[idx]['权重']
  5621. city_ids[idx] += (score + 1) * w * weight
  5622. pro_idx = idx_dic[idx]['省']
  5623. if pro_idx in pro_ids:
  5624. pro_ids[pro_idx] += (score + 1) * w * weight
  5625. else:
  5626. pro_ids[pro_idx] = (score + 1) * w * weight * 0.5
  5627. for dis in district_l:
  5628. name, score = dis
  5629. if name in full_dic['district']:
  5630. w = 0.1 if len(full_dic['district'][name]) > 1 else 1
  5631. for idx in full_dic['district'][name]:
  5632. if idx not in dis_ids:
  5633. dis_ids[idx] = 0
  5634. # weight = idx_dic[idx]['权重']
  5635. dis_ids[idx] += (score + 1) * w
  5636. pro_idx = idx_dic[idx]['省']
  5637. if pro_idx in pro_ids:
  5638. pro_ids[pro_idx] += (score + 1) * w
  5639. else:
  5640. pro_ids[pro_idx] = (score + 1) * w * 0.5
  5641. city_idx = idx_dic[idx]['市']
  5642. if city_idx in city_ids:
  5643. city_ids[city_idx] += (score + 1) * w
  5644. else:
  5645. city_ids[city_idx] = (score + 1) * w * 0.5
  5646. elif name in short_dic['district']:
  5647. w = 0.1 if len(short_dic['district'][name]) > 1 else 1
  5648. for idx in short_dic['district'][name]:
  5649. if idx not in dis_ids:
  5650. dis_ids[idx] = 0
  5651. weight = idx_dic[idx]['权重']
  5652. dis_ids[idx] += (score + 0) * w
  5653. pro_idx = idx_dic[idx]['省']
  5654. if pro_idx in pro_ids:
  5655. pro_ids[pro_idx] += (score + 0) * w * weight
  5656. else:
  5657. pro_ids[pro_idx] = (score + 0) * w * weight * 0.5
  5658. city_idx = idx_dic[idx]['市']
  5659. if city_idx in city_ids:
  5660. city_ids[city_idx] += (score + 0) * w * weight
  5661. else:
  5662. city_ids[city_idx] = (score + 0) * w * weight * 0.1
  5663. for k, v in pro_ids.items():
  5664. pro_ids[k] = v * text_weight
  5665. for k, v in city_ids.items():
  5666. city_ids[k] = v * text_weight
  5667. for k, v in dis_ids.items():
  5668. dis_ids[k] = v * text_weight
  5669. return pro_ids, city_ids, dis_ids
  5670. area_dic = {'area': '全国', 'province': '全国', 'city': '未知', 'district': '未知', "is_in_text": False}
  5671. pro_ids, city_ids, dis_ids = get_pro_city_dis_score(text)
  5672. pro_ids1, city_ids1, dis_ids1 = get_pro_city_dis_score(web_name[:3], text_weight=0.2) # 20240422 修改为站源名称只取前三字,避免类似 459056219 中金岭南阳光采购平台 错提取阳光
  5673. for k in pro_ids1:
  5674. if k in pro_ids:
  5675. pro_ids[k] += pro_ids1[k]
  5676. else:
  5677. pro_ids[k] = pro_ids1[k]
  5678. for k in city_ids1:
  5679. if k in city_ids:
  5680. city_ids[k] += city_ids1[k]
  5681. else:
  5682. city_ids[k] = city_ids1[k]
  5683. for k in dis_ids1:
  5684. if k in dis_ids:
  5685. dis_ids[k] += dis_ids1[k]
  5686. else:
  5687. dis_ids[k] = dis_ids1[k]
  5688. big_area, pred_pro, pred_city, pred_dis = get_final_addr(pro_ids, city_ids, dis_ids)
  5689. if big_area != "":
  5690. area_dic['area'] = big_area
  5691. if pred_pro != "":
  5692. area_dic['province'] = pred_pro
  5693. if pred_city != "":
  5694. area_dic['city'] = pred_city
  5695. if pred_dis != "":
  5696. area_dic['district'] = pred_dis
  5697. if in_content:
  5698. area_dic['is_in_text'] = True
  5699. return {'district': area_dic}
  5700. def predict(self, project_name, prem, title, list_articles, web_source_name = "", list_entitys=""):
  5701. '''
  5702. 先匹配 project_name+tenderee+tenderee_address, 如果缺少省或市 再匹配 title+content
  5703. :param project_name:
  5704. :param prem:
  5705. :param title:
  5706. :param list_articles:
  5707. :param web_source_name:
  5708. :return:
  5709. '''
  5710. def get_ree_addr(prem):
  5711. tenderee = ""
  5712. tenderee_address = ""
  5713. try:
  5714. for v in prem[0]['prem'].values():
  5715. for link in v['roleList']:
  5716. if link['role_name'] == 'tenderee' and tenderee == "":
  5717. tenderee = link['role_text']
  5718. tenderee_address = link['address']
  5719. except Exception as e:
  5720. print('解析prem 获取招标人、及地址出错')
  5721. return tenderee, tenderee_address
  5722. def get_role_address(text):
  5723. '''正则匹配获取招标人地址
  5724. 3:地址直接在招标人后面 招标人:xxx,地址:xxx
  5725. 4:招标、代理一起,两个地址一起 招标人:xxx, 代理人:xxx, 地址:xxx, 地址:xxx.
  5726. '''
  5727. p3 = '(招标|采购|甲)(人|方|单位)(信息:|(甲方))?(名称)?:[\w()]{4,15},(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5728. p4 = '(招标|采购|甲)(人|方|单位)(信息:|(甲方))?(名称)?:[\w()]{4,15},(招标|采购)?代理(人|机构)(名称)?:[\w()]{4,15},(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5729. p5 = '(采购|招标)(人|单位)(联系)?地址:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5730. if re.search(p3, text):
  5731. return re.search(p3, text).group('addr')
  5732. elif re.search(p4, text):
  5733. return re.search(p4, text).group('addr')
  5734. elif re.search(p5, text):
  5735. return re.search(p5, text).group('addr')
  5736. else:
  5737. return ''
  5738. def get_project_addr(text):
  5739. p1 = '(项目|施工|实施|建设|工程|服务|交货|送货|收货|展示|看样|拍卖)(地址|地点|位置|所在地区?)(位于)?:(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5740. p2 = '项目位于(?P<addr>\w{2}市\w{2,4}区)'
  5741. if re.search(p1, text):
  5742. return re.search(p1, text).group('addr')
  5743. elif re.search(p2, text):
  5744. return re.search(p2, text).group('addr')
  5745. else:
  5746. return ''
  5747. def get_bid_addr(text):
  5748. p2 = '(磋商|谈判|开标|投标|评标|报名|递交|评审|发售|所属)(地址|地点|所在地区?|地域):(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5749. if re.search(p2, text):
  5750. return re.search(p2, text).group('addr')
  5751. else:
  5752. return ''
  5753. def get_all_addr(list_entitys):
  5754. tenderee_l = []
  5755. addr_l = []
  5756. for ent in list_entitys[0]:
  5757. if ent.entity_type == 'location' and len(ent.entity_text) > 2:
  5758. addr_l.append(ent.entity_text)
  5759. elif ent.entity_type in ['org', 'company']:
  5760. if ent.label in [0, 1]: # 加招标或代理
  5761. tenderee_l.append(ent.entity_text)
  5762. return ' '.join(addr_l), ' '.join(tenderee_l)
  5763. def get_title_addr(text):
  5764. p1 = '(?P<addr>(\w{1,13}(自治[区州县旗]|地区|[省市区县旗盟])[^\w]*)+|\w{2,15}[,。])'
  5765. if re.search(p1, text):
  5766. return re.search(p1, text).group('addr')
  5767. else:
  5768. return ''
  5769. if '##attachment##' in list_articles[0].content:
  5770. content, attachment = list_articles[0].content.split('##attachment##')
  5771. if len(content) < 200:
  5772. content += attachment
  5773. else:
  5774. content = list_articles[0].content
  5775. tenderee, tenderee_address = get_ree_addr(prem)
  5776. msc = ""
  5777. pro_addr = get_project_addr(content)
  5778. if pro_addr != "":
  5779. msc += '使用规则提取的项目地址;'
  5780. tenderee_address = pro_addr
  5781. else:
  5782. role_addr = get_role_address(content)
  5783. if role_addr != "":
  5784. msc += '使用规则提取的联系人地址;'
  5785. tenderee_address = role_addr
  5786. if tenderee_address == "":
  5787. title_addr = get_title_addr(title)
  5788. if title_addr != "":
  5789. msc += '使用规则提取的标题地址;'
  5790. tenderee_address = title_addr
  5791. else:
  5792. bid_addr = get_bid_addr(content)
  5793. if bid_addr != "":
  5794. msc += '使用规则提取的开标地址;'
  5795. tenderee_address = bid_addr
  5796. project_name = str(project_name)
  5797. tenderee = str(tenderee)
  5798. # print('招标人地址',role_addr, tenderee_address)
  5799. project_name = project_name + title if project_name not in title else title
  5800. # project_name = project_name.replace(tenderee, '')
  5801. if len(project_name)>3:
  5802. entity_list = getNers([project_name],useselffool=False) # 2024/4/26 修改为去重项目名称中所有公司名称
  5803. for tup in entity_list[0]:
  5804. if tup[2] in ['org', 'company']:
  5805. project_name = project_name.replace(tup[3], '')
  5806. text1 = "{0} {1} {2}".format(tenderee, tenderee_address, project_name)
  5807. web_source_name = str(web_source_name) # 修复某些不是字符串类型造成报错
  5808. text1 = re.sub('复合肥|铁路|公路|新会计', ' ', text1) # 预防提取错 合肥 路南 新会 等地区
  5809. if pro_addr and re.search('\w{2,}([省市县旗盟]|自治[区州县旗])', pro_addr):
  5810. msc += '## 使用项目地址输入:%s ##;' % pro_addr
  5811. rs = self.get_area(pro_addr, '')
  5812. msc += '预测结果:省份:%s, 城市:%s,区县:%s;' % (
  5813. rs['district']['province'], rs['district']['city'], rs['district']['district'])
  5814. if rs['district']['province'] != '全国':
  5815. # print('地区匹配:', msc)
  5816. return rs
  5817. # print('text1:', text1)
  5818. msc += '## 第一次预测输入:%s ##;' % text1
  5819. rs = self.get_area(text1, '') # 2024/4/22 调整第一次输入不带站源名称,避免出错
  5820. msc += '预测结果:省份:%s, 城市:%s,区县:%s;' % (
  5821. rs['district']['province'], rs['district']['city'], rs['district']['district'])
  5822. # self.f.write('%s %s \n' % (list_articles[0].id, msc))
  5823. # print('地区匹配:', msc)
  5824. if rs['district']['province'] == '全国' or rs['district']['city'] == '未知':
  5825. msc = ""
  5826. all_addr, tenderees = get_all_addr(list_entitys)
  5827. text2 = tenderees + " " + all_addr + ' ' + title
  5828. msc += '使用实体列表所有招标人+所有地址;'
  5829. # text2 += title + content if len(content)<2000 else title + content[:1000] + content[-1000:]
  5830. text2 = re.sub('复合肥|铁路|公路|新会计', ' ', text2)
  5831. # print('text2:', text2)
  5832. msc += '## 第二次预测输入:%s %s##' % (text2,web_source_name)
  5833. rs2 = self.get_area(text2, web_source_name, in_content=True)
  5834. # rs2['district']['is_in_text'] = True
  5835. if rs['district']['province'] == '全国' and rs2['district']['province'] != '全国':
  5836. rs = rs2
  5837. elif rs['district']['province'] == rs2['district']['province'] and rs2['district']['city'] != '未知':
  5838. rs = rs2
  5839. msc += '预测结果:省份:%s, 城市:%s,区县:%s' % (
  5840. rs['district']['province'], rs['district']['city'], rs['district']['district'])
  5841. # self.f.write('%s %s \n'%(list_articles[0].id, msc))
  5842. # print('地区匹配:', msc)
  5843. return rs
  5844. class TableTag2List():
  5845. '''把soup table 转化为表格补全后的文本列表[[td, td, td], [td, td, td]]'''
  5846. def table2list(self, table, text_process=None):
  5847. self._output = []
  5848. row_ind = 0
  5849. col_ind = 0
  5850. for row in table.find_all('tr'):
  5851. # record the smallest row_span, so that we know how many rows
  5852. # we should skip
  5853. smallest_row_span = 1
  5854. if len(row.find_all(['td', 'th'], recursive=False)) > 20:
  5855. log('未补全前表格列数大于20的不做表格处理')
  5856. return []
  5857. for cell in row.children:
  5858. if cell.name in ('td', 'th'):
  5859. # check multiple rows
  5860. # pdb.set_trace()
  5861. row_span = int(re.sub('[^0-9]', '', cell.get('rowspan'))) if cell.get('rowspan') and cell.get('rowspan').isdigit() else 1
  5862. # try updating smallest_row_span
  5863. smallest_row_span = min(smallest_row_span, row_span)
  5864. # check multiple columns
  5865. col_span = int(re.sub('[^0-9]', '', cell.get('colspan'))) if cell.get('colspan') and cell.get('colspan').isdigit() else 1
  5866. if col_span > 20: # 修复 335590254 山东港口阳光智采e平台 数据源表格第一行colspan为200超过50列造成无法提取问题
  5867. col_span = 20
  5868. # find the right index
  5869. while True:
  5870. if self._check_cell_validity(row_ind, col_ind):
  5871. break
  5872. col_ind += 1
  5873. # insert into self._output
  5874. try:
  5875. if text_process != None:
  5876. # text = [re.sub('\xa0', '', text_process(cell, final=False)), 0]
  5877. # td_text = re.sub('\xa0', '', text_process(cell, final=False))
  5878. td_text = re.sub('\s|\xa0', '', str(cell.get_text())) # 修复 370835008 td 内公司被p标签拆分为两半情况
  5879. if 'title' in cell.attrs and cell.get_text().strip().endswith('...') and cell.get_text().strip()[:-3] in cell.attrs['title']:
  5880. td_text = cell.attrs['title'] # 修复 类似 215597851 省略号隐藏内容
  5881. elif len(td_text)>30:
  5882. td_text = re.sub('\xa0', '', text_process(cell, final=False))
  5883. if td_text == "":
  5884. td_text = ' '
  5885. text = [td_text,0]
  5886. else:
  5887. text = str(cell.get_text()).strip().replace("\x06", "").replace("\x05", "").replace("\x07", "").replace('\\', '').replace("(", "(").replace(')', ')').replace('?', '')
  5888. # text = re.sub('\s', '', text)[:200] # 只需取前200字即可
  5889. text = ' ' if text == "" else text
  5890. self._insert(row_ind, col_ind, row_span, col_span, text)
  5891. except UnicodeEncodeError:
  5892. raise Exception( 'Failed to decode text; you might want to specify kwargs transformer=unicode' )
  5893. # update col_ind
  5894. col_ind += col_span
  5895. if col_ind > 50 and text_process == None: # 表格要素提取及候选人提取的 表格列数大于50的去掉
  5896. return []
  5897. # update row_ind
  5898. row_ind += smallest_row_span
  5899. col_ind = 0
  5900. return self._output
  5901. def _check_validity(self, i, j, height, width):
  5902. """
  5903. check if a rectangle (i, j, height, width) can be put into self.output
  5904. """
  5905. return all(self._check_cell_validity(ii, jj) for ii in range(i, i+height) for jj in range(j, j+width))
  5906. def _check_cell_validity(self, i, j):
  5907. """
  5908. check if a cell (i, j) can be put into self._output
  5909. """
  5910. if i >= len(self._output):
  5911. return True
  5912. if j >= len(self._output[i]):
  5913. return True
  5914. if self._output[i][j] == "":
  5915. return True
  5916. return False
  5917. def _insert(self, i, j, height, width, val):
  5918. # pdb.set_trace()
  5919. for ii in range(i, i+height):
  5920. for jj in range(j, j+width):
  5921. self._insert_cell(ii, jj, val)
  5922. def _insert_cell(self, i, j, val):
  5923. while i >= len(self._output):
  5924. self._output.append([])
  5925. while j >= len(self._output[i]):
  5926. self._output[i].append("")
  5927. if self._output[i][j] == "":
  5928. self._output[i][j] = val
  5929. class TablePremExtractor(object):
  5930. def __init__(self):
  5931. '''各要素表头规则'''
  5932. self.head_rule_dic = {
  5933. 'project_code': "(项目|招标|采购|计划|公告|包[段组件]|标[段包的]|标段(包)|分[包标])(编号|编码|代码)",
  5934. 'package_code': "(包[段组件]|标[段包]|分[包标])(序?号|$)|包号|^标段$|^品目$",
  5935. "project_name": "(包[段组件]|标[段包的项]|标段(包)|分[包标]|采购|项目|工程|货物|商品|产品|设备|通用|主要标的|^包)(名称?|内容)",
  5936. "win_sort": "是否(中标|成交|中选)|排名|排序|名次|未(中标|成交)原因|推荐顺序",
  5937. "tenderer": "(中标|中选|中价|成交|供货|承包|承建|承租|竞得|受让)(候选)?(人|单位|供应商|公司|企业|厂家|商家?|客户|方)(名称|$)|^(拟定|单一来源|邀请|拟推荐(入选|入围)?)?供应商(名称)?$",
  5938. "tenderee": "(项目|采购|招标|遴选|寻源|竞价|议价|比选|委托|询比?价|比价|评选|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选)(人|公司|单位|组织|用户|业主|主体|方|部门)(名称|$)",
  5939. "budget": "最高(投标)?限价|总价限价|控制(价格?|金额|总价)|(总价|采购)限价|上限价|拦标价|(采购|招标|项目)?预算|(预算|招标|采购|计划)金额|挂牌价",
  5940. "bid_amount": "投标[报总]?价|报价(总?金额|总价|总额)|总报价|^\w{,5}报价(([\w、/]{1,15}))?$|(中标|成交|合同))?总?(金?额|[报均总]价|价[格款]?)|承包价|含税价|经评审的价格",
  5941. }
  5942. with open(os.path.dirname(__file__)+'/header_set.pkl', 'rb') as f:
  5943. self.headerset = pickle.load(f)
  5944. self.tb = TableTag2List()
  5945. def find_header(self, td_list):
  5946. fix_td_list = [re.sub('[::]$|^[一二三四五六七八九十0-9]{1,3}、|(([\w、×*/]{1,20}))$|(不?含税)|/万?元|拟|\s', '', it) for it in td_list] # 去除表头无关信息,方便匹配判断是否为表头
  5947. header_dic = dict()
  5948. flag = False
  5949. contain_header = False
  5950. if len(set(fix_td_list))>=2 and len(set(fix_td_list) & self.headerset)/len(set(fix_td_list))>=0.6:
  5951. flag = True
  5952. for i in range(len(td_list)) :
  5953. text = td_list[i]
  5954. text = re.sub('\s', '', text)
  5955. if text == '备选中标人':
  5956. text = '第二候选人'
  5957. if len(text) > 15: # 长度大于15 不进行表头匹配
  5958. continue
  5959. if re.search('未(中标|成交)原因', text): # 不提取此种表格
  5960. return flag, contain_header, dict()
  5961. num = 0
  5962. for k, v in self.head_rule_dic.items():
  5963. if re.search('评分|得分|分数|分值', text):
  5964. continue
  5965. if re.search(v, text):
  5966. if k in ['tenderer'] and re.search('是否', text):
  5967. continue
  5968. if k == 'budget' and re.search('量', text): # 预算工作量 预算采购量 等不作为预算
  5969. continue
  5970. elif k in header_dic:
  5971. if k in ['budget', 'bid_amount'] and re.search('总(价|金?额)', text): # 总价替换单价
  5972. header_dic[k] = (i, text)
  5973. num += 1
  5974. elif k == 'project_code' and text != header_dic[k][1] and 'package_code' not in header_dic\
  5975. and re.search(self.head_rule_dic['package_code'], re.sub('\s', '', ','.join(td_list)))==None: # 如果出现两次项目编号且没有包号,把第二次出现的作为包号 例:472537470
  5976. header_dic['package_code'] = (i, text)
  5977. continue
  5978. header_dic[k] = (i, text)
  5979. num += 1
  5980. if num>1:
  5981. # print('表头错误,一个td匹配到两个表头:', header_dic)
  5982. return flag, contain_header, dict()
  5983. if re.search(';金额((万?元))?;', ';'.join(td_list)): # 召回某些表格只写 金额 作为表头,不能识别为招标或中标金额
  5984. if 'tenderer' in header_dic and 'bid_amount' not in header_dic:
  5985. for i in range(len(td_list)):
  5986. text = td_list[i]
  5987. if re.search('^金额((万?元))?$',text):
  5988. header_dic['bid_amount'] = (i, text)
  5989. break
  5990. elif 'tenderee' in header_dic and 'budget' not in header_dic:
  5991. for i in range(len(td_list)):
  5992. text = td_list[i]
  5993. if re.search('^金额((万?元))?$', text):
  5994. header_dic['budget'] = (i, text)
  5995. break
  5996. if ('project_code' in header_dic or 'package_code' in header_dic or 'project_name' in header_dic) and (
  5997. 'tenderer' in header_dic or'budget' in header_dic): # 包含标段及招标金额或中标人的进行提取
  5998. return flag, contain_header, header_dic
  5999. elif ('tenderer' in header_dic) and ('bid_amount' in header_dic): # 包含中标人及中标金额的进行提取
  6000. if re.search('^(候选)?供应商(名称)?', header_dic['tenderer'][1]) and 'win_sort' not in header_dic and re.search('(中标|成交|合同))?总?(金?额|[报均总]价|价[格款]?)', header_dic['bid_amount'][1])==None: # 只有供应商名称 没排名和包号的去掉,预防错误包提取 334205629
  6001. # print('只有供应商名称 没排名和包号的去掉')
  6002. return flag, contain_header, dict()
  6003. return flag,contain_header, header_dic
  6004. elif len(set(fix_td_list) & self.headerset) >= 2 or (len(set(fix_td_list)) == 2 and len(set(td_list) & self.headerset) >= 1): # 如果包含两个表头以上或 只有两列且包含一个表头
  6005. contain_header = True
  6006. return flag, contain_header, dict()
  6007. def is_role(self, text):
  6008. if len(text) > 25 or len(text)<4:
  6009. return False
  6010. elif len(re.findall('有限责?任?公司', text)) > 1:
  6011. return False
  6012. elif re.search('[\w()]{4,}(有限责?任?公司|学校|学院|大学|中学|小学|医院|管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园|厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处)$', text):
  6013. return True
  6014. else:
  6015. ners = selffool.ner(text)
  6016. if len(ners[0]) == 1 and ('company' in ners[0][0] or 'org' in ners[0][0]):
  6017. return True
  6018. return False
  6019. def get_role(self, text, nlp_enterprise):
  6020. '''
  6021. 获取字符串text角色实体
  6022. :param text: 待获取实体字符串
  6023. :param nlp_enterprise: 公告中的角色实体列表
  6024. :return:
  6025. '''
  6026. text = re.sub('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:|[((][主成][))]'
  6027. , ',', text)
  6028. text = re.sub('\s', '', text) # 修复 370835008 表格中实体中间有\n
  6029. text = re.sub('[一二三四五六七八九十]+标段:|标段[一二三四五六七八九十]+:', '', text) # 2024/4/22 修复 372839375 三标段:宁夏一山科技有限公司
  6030. text = re.sub('1[3-9]\d{9}|\d{3}-\d{8}|\d{4}-\d{7}', '', text) # 2024/4/23 去除电话
  6031. if text in nlp_enterprise:
  6032. return text
  6033. if len(text) > 50 or len(text)<4:
  6034. return ''
  6035. ners = getNers([text], useselffool=True)
  6036. roles = []
  6037. if ners:
  6038. for ner in ners[0]:
  6039. if ner[2] in ['org', 'company']:
  6040. roles.append(ner[3])
  6041. elif ner[2] in ['location'] and re.search('^\w{3,10}(海关|殡仪馆|店|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场)$', ner[3]):
  6042. roles.append(ner[3])
  6043. if roles and len(''.join(roles)) > len(text)*0.8:
  6044. return roles[0]
  6045. else:
  6046. return ''
  6047. def extract_from_df(self, df, headers, web_source_name):
  6048. prem_dic = {}
  6049. previous_package = "" # 上一行包号
  6050. multi_same_package = False # 非连续的重复包号
  6051. package_fix2raw = dict() # 处理后包号:处理前包号 字典
  6052. link_set = set()
  6053. tenderer_list = [] # 保存所有中标人
  6054. not_package = True if 'project_name' in headers and re.search('(货物|商品|产品|通用|主要标的)(名称?|内容)', headers['project_name'][1]) and \
  6055. 'package_code' not in headers and 'budget' not in headers and "bid_amount" not in headers else False
  6056. if set(['project_code', 'package_code', 'tenderee', 'tenderer']) & set(headers) == set() and ('project_name' not in headers # 补充没有项目名称或有项目名称且是货物的才过滤掉
  6057. or re.search('(货物|商品|产品|设备|通用|主要标的)(名称?|内容)', headers['project_name'][1])): # 20240131修复只有货物名称及最高限价的错误作为多包 396636683; 补充避免423647863采购意向被过滤
  6058. # print('没有包号及角色的不要')
  6059. return {}
  6060. for i in df.index:
  6061. same_package = False # 连续重复包号,一般是 rowspan 造成;一包 多个采购
  6062. project_code = df.loc[i, headers['project_code'][0]].strip() if "project_code" in headers else ""
  6063. package_code_raw = df.loc[i, headers['package_code'][0]].strip() if "package_code" in headers else ""
  6064. project_name = df.loc[i, headers['project_name'][0]].strip() if "project_name" in headers else ""
  6065. tenderee = df.loc[i, headers['tenderee'][0]].strip() if "tenderee" in headers else ""
  6066. tenderer = df.loc[i, headers['tenderer'][0]].strip() if "tenderer" in headers else ""
  6067. budget_ = df.loc[i, headers['budget'][0]].strip() if "budget" in headers else ""
  6068. bid_amount_ = df.loc[i, headers['bid_amount'][0]].strip() if "bid_amount" in headers else ""
  6069. win_sort = df.loc[i, headers['win_sort'][0]].strip() if "win_sort" in headers else ""
  6070. if set([project_code, package_code_raw, project_name,tenderee,tenderer,budget_,bid_amount_]) & self.headerset != set(): # 只要有一项为表头 停止匹配
  6071. # print('只要有一项为表头 停止匹配', set([project_code, package_code_raw, project_name,tenderee,tenderer,budget_,bid_amount_,win_sort]) & self.headerset)
  6072. break
  6073. if len(set([project_code, package_code_raw, project_name,tenderee,tenderer,budget_,bid_amount_,win_sort])- set(['', ' '])) < 2: # 内容为空或全部一样 停止匹配
  6074. # print('内容为空或全部一样 停止匹配')
  6075. break
  6076. if re.search('详见', project_name): # 去除某些表达: 详见招标文件
  6077. project_name = ""
  6078. if package_code_raw == "" and re.search('第?[0-9一二三四五六七八九十a-zZ-Z]{1,4}(标[段号的包项]|([分子]?包|包[组件号]))$|^(标[段号的包项]|([分子]?包|包[组件号]))号?:?[0-9一二三四五六七八九十a-zZ-Z]{1,4}$', project_name):
  6079. package_code_raw = project_name
  6080. project_name = ""
  6081. package_code = package_code_raw
  6082. if re.search('合计|总计', package_code+project_code):
  6083. continue
  6084. if package_code != '' and package_code + project_code == previous_package: # 处理 208162730 一个包采购多种东西情况
  6085. same_package = True
  6086. project_name = ''
  6087. previous_package = package_code + project_code
  6088. if win_sort != "" and re.search('排名|排序|名次|推荐顺序', headers['win_sort'][1]): # 此类型表由 CandidateExtractor类提取 防止类似 328485591 作为多包
  6089. break
  6090. if win_sort != "" and re.search('是否(中标|成交|中选)', headers['win_sort'][1]) and (re.search('否|未(中标|成交|中选)', win_sort) or win_sort==''): # 2024/04/2 修复 252208201 为空的不中标
  6091. continue
  6092. if "win_sort" in headers and win_sort == "": # '表头有是否中标,内容却空白的,过滤掉'
  6093. continue
  6094. if win_sort == "" and "tenderer" in headers and re.search('候选|入围|入选', headers['tenderer'][1]) and re.search('推荐的?((中标|成交|中选)候选人|(候选|入围|入选)供应商)', headers['tenderer'][1])==None:
  6095. tenderer = ""
  6096. if tenderer in ['采购失败', '废标']: # 避免类似 353867205 这篇只提取到一个
  6097. continue
  6098. # tenderee = tenderee if self.is_role(tenderee) else ""
  6099. # tenderer = tenderer if self.is_role(tenderer) else ""
  6100. package = uniform_package_name(package_code) if package_code else '自增'+str(len(prem_dic)+1) # 没有包号的自动编号的修改为提取到多少个包,某些行未必中标
  6101. if project_name != "" and package.startswith('自增'):
  6102. pk_l = find_package(project_name)
  6103. if len(pk_l)==1:
  6104. package = uniform_package_name(pk_l[0].group(0))
  6105. elif re.search('[一二三四五六七八九十]+标段:|标段[一二三四五六七八九十]+:', tenderer) and package.startswith('自增'):
  6106. pk_l = find_package(tenderer)
  6107. if len(pk_l) == 1:
  6108. package = uniform_package_name(pk_l[0].group(0))
  6109. tenderee = self.get_role(tenderee, self.nlp_enterprise) if tenderee!="" else tenderee
  6110. tenderer = self.get_role(tenderer, self.nlp_enterprise) if tenderer!='' else tenderer
  6111. if len(set([project_code, package_code, project_name, tenderee, tenderer, budget_, bid_amount_])) < 2:
  6112. break
  6113. if not_package:
  6114. if (project_code, package_code, tenderee, tenderer, budget_, bid_amount_) in link_set:
  6115. continue
  6116. link_set.add((project_code, package_code, tenderee, tenderer, budget_, bid_amount_))
  6117. else:
  6118. if (project_code, package_code, project_name, tenderee, tenderer, budget_, bid_amount_) in link_set:
  6119. continue
  6120. link_set.add((project_code, package_code, project_name, tenderee, tenderer, budget_, bid_amount_))
  6121. if project_code != "":
  6122. uni_project_code= uniform_package_name(project_code)
  6123. if uni_project_code != "" and uni_project_code!=package:
  6124. if package.startswith('自增'): # 没有包号有项目编号的,直接用项目编号
  6125. package = uni_project_code
  6126. else:
  6127. # print('重组包号:', '%s_%s'%(uni_project_code, package))
  6128. package = '%s_%s'%(uni_project_code, package) # 同时包号项目编号及包号的,组合起来做包号
  6129. if package_code_raw!='':
  6130. if multi_same_package == False and package not in package_fix2raw: # 如果处理后的标段号 已经在列表里面,采用原始标段号文本
  6131. package_fix2raw[package] = package_code_raw
  6132. elif same_package == False:
  6133. multi_same_package = True
  6134. if multi_same_package:
  6135. package = package_code_raw
  6136. if package not in prem_dic or not same_package:
  6137. prem_dic[package] = {
  6138. 'code': '',
  6139. 'name': '',
  6140. 'roleList': [],
  6141. 'tendereeMoney': 0,
  6142. 'tendereeMoneyUnit': ""
  6143. }
  6144. prem_dic[package]['code'] = project_code
  6145. prem_dic[package]['name'] = project_name
  6146. if budget_ != "":
  6147. if len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\s\d,.]|人民币|不?含税', '', budget_)) > 5: # 金额字段出现超过5个非金额字符,中断匹配
  6148. prem_dic.pop(package)
  6149. break
  6150. budget_header = headers['budget'][1] if 'budget' in headers else ''
  6151. budget, money_unit = money_process(budget_, budget_header) if re.search('[%%‰折]|浮率', budget_)==None else (0, '')
  6152. if (re.search('费率|下浮率|[%%‰折]',
  6153. budget_header + budget_) and budget < 100) or budget > 50000000000: # 如果是费率或大于500亿的金额改为0
  6154. budget = 0
  6155. if budget > 0:
  6156. if same_package and prem_dic[package]['tendereeMoney'] != budget: # 处理 类似 136839070 一包多物品多预算
  6157. prem_dic[package]['tendereeMoney'] += budget
  6158. else:
  6159. prem_dic[package]['tendereeMoney'] = budget
  6160. prem_dic[package]['tendereeMoneyUnit'] = money_unit
  6161. if tenderee and not same_package:
  6162. prem_dic[package]['roleList'].append({
  6163. "address": "",
  6164. "linklist": [],
  6165. "role_money": {
  6166. "discount_ratio": "",
  6167. "downward_floating_ratio": "",
  6168. "floating_ratio": "",
  6169. "money": 0,
  6170. "money_unit": ""
  6171. },
  6172. "role_name": "tenderee",
  6173. "role_text": tenderee,
  6174. "serviceTime": ""
  6175. })
  6176. if tenderer and not same_package:
  6177. if len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\s\d,.]|人民币|不?含税', '',
  6178. bid_amount_)) > 5: # 金额字段出现超过5个非金额字符,中断匹配
  6179. prem_dic.pop(package)
  6180. break
  6181. bid_amount, money_unit = money_process(bid_amount_, headers['bid_amount'][1]) if bid_amount_ != "" and re.search('[%%‰折]|浮率', bid_amount_)==None and 'bid_amount' in headers else (0, '')
  6182. if web_source_name == '河钢供应链管理平台' and 'bid_amount' in headers and re.search('[%%‰折]|浮率', bid_amount_) == None and bid_amount == 0: # 有中标金额字段却金额为0的过滤掉,防止类似 河钢供应链管理平台 站源错误,金额不为0的才算中标
  6183. if len(prem_dic[package]['roleList']) == 0 and prem_dic[package]['tendereeMoney'] == 0: # 只有项目编号和名称的包 丢弃
  6184. prem_dic.pop(package)
  6185. continue
  6186. bid_amount_header = headers['bid_amount'][1] if bid_amount_ != "" else ''
  6187. if (re.search('费率|下浮率|[%%‰折]',
  6188. bid_amount_header + bid_amount_) and bid_amount < 100) or bid_amount > 50000000000: # 如果是费率或大于500亿的金额改为0
  6189. bid_amount = 0
  6190. prem_dic[package]['roleList'].append({
  6191. "address": "",
  6192. "linklist": [],
  6193. "role_money": {
  6194. "discount_ratio": "",
  6195. "downward_floating_ratio": "",
  6196. "floating_ratio": "",
  6197. "money": bid_amount,
  6198. "money_unit": money_unit
  6199. },
  6200. "role_name": "win_tenderer",
  6201. "role_text": tenderer,
  6202. "serviceTime": ""
  6203. })
  6204. tenderer_list.append(tenderer)
  6205. if len(prem_dic[package]['roleList']) == 0 and prem_dic[package]['tendereeMoney'] == 0: # 只有项目编号和名称的 丢弃 并不再继续往下匹配
  6206. prem_dic.pop(package)
  6207. # break # 注释掉避免 400084571 某些包废标 中断匹配
  6208. if multi_same_package: # 预处理后包号重复的,使用原始包号
  6209. for k, v in package_fix2raw.items():
  6210. if k in prem_dic:
  6211. prem_dic[v] = prem_dic.pop(k)
  6212. if len(tenderer_list)>2 and len(set(tenderer_list))==1 and "package_code" not in headers: # 没提取到包号且中标人一样应该是错误多包,需去掉多包 例 244355092 281854766
  6213. total_money = 0
  6214. for v in prem_dic.values():
  6215. for d in v['roleList']:
  6216. if d['role_name'] == "win_tenderer":
  6217. total_money += d['role_money']['money']
  6218. return {'自增1': {
  6219. 'code': '',
  6220. 'name': '',
  6221. 'roleList': [{
  6222. "address": "",
  6223. "linklist": [],
  6224. "role_money": {
  6225. "discount_ratio": "",
  6226. "downward_floating_ratio": "",
  6227. "floating_ratio": "",
  6228. "money": total_money,
  6229. "money_unit": ''
  6230. },
  6231. "role_name": "win_tenderer",
  6232. "role_text": tenderer_list[0],
  6233. "serviceTime": ""
  6234. }],
  6235. 'tendereeMoney': 0,
  6236. 'tendereeMoneyUnit': ""
  6237. }}
  6238. return prem_dic
  6239. def update_prem(self, rs_dic, tmp_dic):
  6240. '''
  6241. 合并更新 prem
  6242. :param rs_dic: 返回结果
  6243. :param tmp_dic: 待合并结果
  6244. :return:
  6245. '''
  6246. if '自增1' in tmp_dic and '自增1' not in rs_dic and len(tmp_dic)==len(rs_dic):
  6247. pass
  6248. else:
  6249. for pack in tmp_dic:
  6250. if pack in rs_dic:
  6251. for k in tmp_dic[pack]:
  6252. if rs_dic[pack][k] in ['', 0]:
  6253. rs_dic[pack][k] = tmp_dic[pack][k]
  6254. elif rs_dic[pack][k] == []:
  6255. rs_dic[pack][k] = tmp_dic[pack][k]
  6256. elif k == 'roleList' and len(rs_dic[pack][k])>0 and rs_dic[pack][k][0].get('role_money', {}).get('money', 0) == 0:
  6257. rs_dic[pack][k] = tmp_dic[pack][k]
  6258. else:
  6259. rs_dic[pack] = tmp_dic[pack]
  6260. def get_prem(self, soup, web_source_name=''):
  6261. tables = soup.find_all('table')
  6262. tables.reverse()
  6263. rs_dic = {}
  6264. for table in tables:
  6265. text = table.text.strip()
  6266. previous = table.findPreviousSibling()
  6267. text2 = previous .text.strip() if previous else ""
  6268. # text2 = table.findPreviousSibling().text.strip() if table.findPreviousSibling() != None else ""
  6269. if re.search('项目业主|业\s*主', text) and re.search('业\s*绩', text+text2): # 包含业绩的表格过滤掉,不进行处理
  6270. tb_ex = table.extract()
  6271. if previous:
  6272. sib = previous.extract()
  6273. continue
  6274. trs = self.tb.table2list(table)
  6275. # table.extract()
  6276. i = 0
  6277. headers = ""
  6278. table_prem = {}
  6279. while i < len(trs) - 1:
  6280. flag_, contain_header_, headers_ = self.find_header(trs[i])
  6281. if flag_ and headers_ != dict():
  6282. table_items = []
  6283. headers = headers_
  6284. for j in range(i + 1, len(trs)):
  6285. if len(trs[j]) == len(trs[i]):
  6286. flag_, contain_header_, headers_ = self.find_header(trs[j])
  6287. if flag_ or contain_header_:
  6288. break
  6289. else:
  6290. table_items.append(trs[j])
  6291. else:
  6292. # print('表头,内容 列数不一致', len(trs[i]), len(trs[j]))
  6293. break
  6294. if len(table_items) > 0:
  6295. df = pd.DataFrame(table_items)
  6296. prem_ = self.extract_from_df(df, headers, web_source_name)
  6297. # rs_dic.update(prem_)
  6298. # table_prem.update(prem_)
  6299. self.update_prem(table_prem, prem_)
  6300. i = j - 1
  6301. i += 1
  6302. if table_prem and len(trs) == 2 and 'package_code' not in headers and '自增1' in table_prem and table.find_previous_sibling(): # 一个表格只有两行且没有标段的,从上一个兄弟标签找标段
  6303. sib = table.find_previous_sibling()
  6304. sib_text = sib.get_text()
  6305. ser_sib = re.search('第?[0-9一二三四五六七八九十a-zZ-Z]{1,4}(标[段号的包项]|([分子]?包|包[组件号]))|(标[段号的包项]|([分子]?包|包[组件号]))号?:?[0-9一二三四五六七八九十a-zZ-Z]{1,4}|包名:[0-9一二三四五六七八九十]{1,4}', sib_text)
  6306. if sib.name in ['p', 'div'] and len(sib_text)<100 and ser_sib:
  6307. package_sib = ser_sib.group(0)
  6308. package_sib = uniform_package_name(package_sib)
  6309. table_prem[package_sib] = table_prem.pop('自增1')
  6310. if table_prem:
  6311. # rs_dic.update(table_prem)
  6312. self.update_prem(rs_dic, table_prem)
  6313. table.extract()
  6314. return rs_dic
  6315. def predict(self, html, nlp_enterprise, web_source_name=""):
  6316. html = re.sub("<html>|</html>|<body>|</body>","",html)
  6317. html = re.sub("##attachment##","",html)
  6318. soup = BeautifulSoup(html, 'lxml')
  6319. richText = soup.find(name='div', attrs={'class': 'richTextFetch'})
  6320. self.nlp_enterprise = nlp_enterprise
  6321. in_attachment = False
  6322. if richText:
  6323. richText = richText.extract() # 过滤掉附件
  6324. prem = self.get_prem(soup, web_source_name)
  6325. if prem == {} and richText:
  6326. prem = self.get_prem(richText, web_source_name)
  6327. in_attachment = True
  6328. if len(prem) == 1: # 只有一个包且包号为1 或 长度大于2 的大概率为自动增加编号包,改为Project
  6329. k = list(prem)[0]
  6330. if k.startswith('自增'):
  6331. prem['Project'] = prem.pop(k)
  6332. return prem, in_attachment
  6333. class CandidateExtractor(object):
  6334. def __init__(self):
  6335. '''各要素表头规则'''
  6336. self.head_rule_dic = {
  6337. 'package_code': "(包[段组件]|标[段包]|分[包标])(序?号|$)|包号|^标段$",
  6338. 'project_code': "(项目|招标|采购|计划|公告|包[段组件]|标[段包的]|标段(包)|分[包标])(编号|编码)",
  6339. "project_name": "(包[段组件]|标[段包的项]|标段(包)|分[包标]|采购|项目|工程|货物|商品|产品|设备|通用|主要标的|^包)(名称?|内容)",
  6340. "win_sort": "排名|排序|名次|推荐顺序",
  6341. 'win_or_not': '是否(建议|推荐)?(中标|成交)|是否入围|是否入库|入围结论',
  6342. "candidate": "((候选|入围|入选|投标)(供应商库)?的?(人|人?单位|机构|供应商|供货商|服务商|投标人|(中标)?公司|(中标)?企业)|(通过)?名单|中标候选人)(名称|名单|全称|\d)?$|^供应商(名称|信息)?$|投标个人/单位", #补充 368295593 投标个人/单位 提取
  6343. "bid_amount": "投标[报总]?价|报价(总?金额|总价|总额)|总报价|^\w{,5}报价(([\w、/]{1,15}))?$|(中标|成交|合同))?([金总]额|[报均总]价|价[格款]?)|承包价|含税价|经评审的价格",
  6344. "win_tenderer": "第一名|第一(中标|成交)?候选人",
  6345. "second_tenderer": "第二名|第二(中标|成交)?候选人",
  6346. "third_tenderer": "第三名|第三(中标|成交)?候选人",
  6347. }
  6348. '''非表格候选人正则'''
  6349. # self.p = '((候选|入围|入选|投标)(供应商库)?的?(人|人?单位|机构|供应商|供货商|服务商|投标人|(中标)?公司|(中标)?企业|应答人)|(通过)?名单)(名称|名单|全称|\d)?:$'
  6350. self.p = '((候选|入围|入选|投标|报价|成交|中标|中选|供[货应]|应答)(人|方|人?单位|机构|厂?商|商家|服务商|公司|企业)|(通过|入围)名单)(名称|名单|全称|\d)?:?$'
  6351. self.tb = TableTag2List()
  6352. with open(os.path.dirname(__file__)+'/header_set.pkl', 'rb') as f:
  6353. self.headerset = pickle.load(f)
  6354. def find_header(self, td_list):
  6355. fix_td_list = [re.sub('[::]$|^[一二三四五六七八九十0-9]{1,3}、|(([\w、×*/]{1,20}))$|(不?含税)|/万?元|拟|\s', '', it) for it in td_list] # 去除表头无关信息,方便匹配判断是否为表头
  6356. header_dic = dict()
  6357. flag = False
  6358. contain_header = False
  6359. if len(set(fix_td_list))>=2 and len(set(fix_td_list) & self.headerset)/len(set(fix_td_list))>=0.6:
  6360. flag = True
  6361. for i in range(len(td_list)) :
  6362. text = td_list[i]
  6363. if len(text) > 15: # 长度大于15 不进行表头匹配
  6364. continue
  6365. if re.search('未(中标|成交)原因', text): # 不提取此种表格
  6366. return flag, contain_header, dict()
  6367. num = 0
  6368. for k, v in self.head_rule_dic.items():
  6369. if k == 'candidate' and re.search('第[一二三]名|第[一二三](中标|成交)?候选人', text):
  6370. continue
  6371. if re.search('评分|得分|分数|分值', text):
  6372. continue
  6373. if re.search(v, text):
  6374. if k in ['candidate', 'win_tenderer', 'second_tenderer', 'third_tenderer'] and re.search('是否', text):
  6375. continue
  6376. header_dic[k] = (i, text)
  6377. # if k != 'candidate': # candidate 可与前三候选重复
  6378. num += 1
  6379. if 'win_tenderer'in header_dic and 'second_tenderer' in header_dic and 'candidate' in header_dic:
  6380. header_dic.pop('candidate')
  6381. if num>1:
  6382. # print('表头错误,一个td匹配到两个表头:', header_dic)
  6383. return flag, contain_header, dict()
  6384. if 'candidate' in header_dic or ('win_tenderer' in header_dic and 'second_tenderer' in header_dic):
  6385. return flag, contain_header, header_dic
  6386. 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): # 如果包含两个表头以上或 只有两列且包含一个表头
  6387. contain_header = True
  6388. return flag, contain_header, dict()
  6389. def is_role(self, text):
  6390. if len(text) > 25 or len(text) < 4:
  6391. return False
  6392. elif len(re.findall('有限责?任?公司', text)) > 1:
  6393. return False
  6394. elif re.search('[\w()]{4,}(有限责?任?公司|学校|学院|大学|中学|小学|医院|管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园|厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处)$', text):
  6395. return True
  6396. else:
  6397. ners = selffool.ner(text)
  6398. if len(ners[0]) == 1 and ('company' in ners[0][0] or 'org' in ners[0][0]):
  6399. return True
  6400. return False
  6401. def get_role(self, text, nlp_enterprise):
  6402. '''
  6403. 获取字符串text角色实体
  6404. :param text: 待获取实体字符串
  6405. :param nlp_enterprise: 公告中的角色实体列表
  6406. :return:
  6407. '''
  6408. text = re.sub('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:|[((][主成][))]'
  6409. , ',', text)
  6410. text = re.sub('\s', '', text) # 修复 370835008 表格中实体中间有\n
  6411. if text in nlp_enterprise:
  6412. return text
  6413. if len(text) > 50 or len(text)<4:
  6414. return ''
  6415. ners = getNers([text], useselffool=True)
  6416. roles = []
  6417. if ners:
  6418. for ner in ners[0]:
  6419. if ner[2] in ['org', 'company', 'location']:
  6420. roles.append(ner[3])
  6421. if roles and len(''.join(roles)) > len(text)*0.8:
  6422. return roles[0]
  6423. else:
  6424. return ''
  6425. def extract_from_df(self, df, headers):
  6426. prem_dic = {}
  6427. link_set = set()
  6428. candidate_set = set()
  6429. role_dic = dict() # 保存一二三候选人并排的情况
  6430. findtop3 = False
  6431. findmoney = False
  6432. line_num = 0
  6433. line_package = None
  6434. for i in df.index:
  6435. package_code_raw = df.loc[i, headers['package_code'][0]].strip() if "package_code" in headers else ""
  6436. project_code = df.loc[i, headers['project_code'][0]].strip() if "project_code" in headers else ""
  6437. project_name = df.loc[i, headers['project_name'][0]].strip() if "project_name" in headers else ""
  6438. candidate_ = df.loc[i, headers['candidate'][0]].strip() if "candidate" in headers else ""
  6439. win_or_not = df.loc[i, headers['win_or_not'][0]].strip() if "win_or_not" in headers else ""
  6440. # budget_ = df.loc[i, headers['budget'][0]] if "budget" in headers else ""
  6441. bid_amount_ = df.loc[i, headers['bid_amount'][0]].strip() if "bid_amount" in headers else ""
  6442. win_sort = df.loc[i, headers['win_sort'][0]].strip() if "win_sort" in headers else ""
  6443. win_tenderer = df.loc[i, headers['win_tenderer'][0]].strip() if "win_tenderer" in headers else ""
  6444. second_tenderer = df.loc[i, headers['second_tenderer'][0]].strip() if "second_tenderer" in headers else ""
  6445. third_tenderer = df.loc[i, headers['third_tenderer'][0]].strip() if "third_tenderer" in headers else ""
  6446. if set([package_code_raw, candidate_, win_or_not, bid_amount_, win_tenderer, second_tenderer, third_tenderer]) & self.headerset != set(): # 包含表头, 停止匹配 # 排除 ,win_sort 避免367940050漏提取
  6447. # print('包含表头, 停止匹配')
  6448. break
  6449. if len(set([package_code_raw, candidate_,win_sort, win_or_not, bid_amount_, win_tenderer, second_tenderer, third_tenderer]) - set(['', ' '])) < 2: # 全部为空或内容一样 停止匹配
  6450. # print('全部为空或内容一样 停止匹配')
  6451. 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):
  6452. line_package = win_sort
  6453. continue
  6454. else:
  6455. break
  6456. if candidate_ != "" and win_sort == "" and headers['candidate'][0] > 0: # 修复某些表头不说 排名,直接用候选人代替
  6457. col_indx = headers['candidate'][0] -1
  6458. pre_col = df.loc[i, col_indx]
  6459. if col_indx > 0 and pre_col == candidate_:
  6460. pre_col = df.loc[i, col_indx - 1]
  6461. if re.search('第[一二三]名|第[一二三](中标)?候选人', pre_col):
  6462. win_sort = pre_col
  6463. package_code = package_code_raw
  6464. if package_code == '' and line_package:
  6465. package_code = line_package
  6466. # candidate = candidate_ if self.is_role(candidate_) else ""
  6467. # tenderer = tenderer if self.is_role(tenderer) else ""
  6468. candidate = self.get_role(candidate_, self.nlp_enterprise)
  6469. # if len(set([project_code, package_code, project_name, tenderee, tenderer, budget_, bid_amount_])) < 2:
  6470. # break
  6471. if(candidate_,win_tenderer, second_tenderer,third_tenderer, bid_amount_,package_code,project_code,win_sort) in link_set:
  6472. continue
  6473. link_set.add((candidate_, win_tenderer, second_tenderer, third_tenderer, bid_amount_,package_code,project_code,win_sort))
  6474. package = package_code
  6475. if package == "" and project_code != "": # 修复 395747178 多项目 只提取到一个
  6476. package = project_code
  6477. package = uniform_package_name(package) if package !="" else "Project"
  6478. if candidate:
  6479. if win_or_not and re.search('否|未入围', win_or_not):
  6480. candidate_set.add(candidate)
  6481. elif re.search('^((建议|推荐)(中标|成交)|是)$', win_or_not) and win_sort in ['', '参与投标单位及排名'] and win_tenderer=='':
  6482. win_sort = '第一名'
  6483. candidate_set.add(candidate)
  6484. else:
  6485. candidate_set.add(candidate)
  6486. if win_tenderer and second_tenderer: # and third_tenderer 128778062 这篇只有 第一二候选人
  6487. if re.search("(候选人|投标人|单位|公司)名?称?$", df.loc[i, 0]) or re.search("(候选人|投标人|单位|公司)名?称?", df.loc[i, 1]):
  6488. findtop3 = True
  6489. for type, text in zip(['win_tenderer', 'second_tenderer', 'third_tenderer'],
  6490. [win_tenderer, second_tenderer, third_tenderer]):
  6491. text = self.get_role(text, self.nlp_enterprise)
  6492. if text:
  6493. # if self.is_role(text):
  6494. if type not in role_dic:
  6495. role_dic[type] = dict()
  6496. role_dic[type]['role_text'] = text
  6497. candidate_set.add(text)
  6498. elif re.search('投标报价|报价$', df.loc[i, 0]) or re.search('投标报价|报价$', df.loc[i, 1]):
  6499. findmoney = True
  6500. header = df.loc[i, 0] if re.search('投标报价|报价$', df.loc[i, 0]) else df.loc[i, 1]
  6501. for type, text in zip(['win_tenderer', 'second_tenderer', 'third_tenderer'],
  6502. [win_tenderer, second_tenderer, third_tenderer]):
  6503. if len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\s\d,.]|人民币|不?含税', '',
  6504. text)) > 5: # 金额字段出现超过5个非金额字符,中断匹配
  6505. break
  6506. money, money_unit = money_process(text, header)
  6507. if (re.search('费率|下浮率|[%%‰折]', header+text) and money < 100) or money > 50000000000: # 如果是费率或大于500亿的金额改为0
  6508. money = 0
  6509. if money > 0:
  6510. if type not in role_dic:
  6511. role_dic[type] = dict()
  6512. role_dic[type]['money'] = money
  6513. role_dic[type]['money_unit'] = money_unit
  6514. else:
  6515. line_num += 1
  6516. if findtop3 and findmoney:
  6517. break
  6518. if line_num > 3:
  6519. break
  6520. elif candidate and win_sort:
  6521. role_type = ""
  6522. if re.search('第[一1]|^[一1]$', win_sort):
  6523. role_type = "win_tenderer"
  6524. elif re.search('第[二2]|^[二2]$', win_sort):
  6525. role_type = "second_tenderer"
  6526. elif re.search('第[三3]|^[三3]$', win_sort):
  6527. role_type = "third_tenderer"
  6528. if role_type != "":
  6529. if package not in prem_dic:
  6530. prem_dic[package] = {
  6531. 'code': '',
  6532. 'name': '',
  6533. 'roleList': [],
  6534. 'tendereeMoney': 0,
  6535. 'tendereeMoneyUnit': ""
  6536. }
  6537. prem_dic[package]['code'] = project_code
  6538. prem_dic[package]['name'] = project_name
  6539. if len(re.sub('[金额万元()()::零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分¥整\s\d,.]|人民币|不?含税', '', bid_amount_))> 5: # 金额字段出现超过5个非金额字符,中断匹配
  6540. break
  6541. bid_amount, money_unit = money_process(bid_amount_, headers['bid_amount'][1]) if "bid_amount" in headers else (0, "")
  6542. header = headers['bid_amount'][1] if "bid_amount" in headers else ''
  6543. if (re.search('费率|下浮率|[%%‰折]',
  6544. header + bid_amount_) and bid_amount < 100) or bid_amount > 50000000000: # 如果是费率或大于500亿的金额改为0
  6545. bid_amount = 0
  6546. prem_dic[package]['roleList'].append({
  6547. "address": "",
  6548. "linklist": [],
  6549. "role_money": {
  6550. "discount_ratio": "",
  6551. "downward_floating_ratio": "",
  6552. "floating_ratio": "",
  6553. "money": bid_amount,
  6554. "money_unit": money_unit
  6555. },
  6556. "role_name": role_type,
  6557. "role_text": candidate,
  6558. "serviceTime": ""
  6559. })
  6560. if len(prem_dic[package]['roleList']) == 0: # 只有项目编号和名称的 丢弃
  6561. prem_dic.pop(package)
  6562. if role_dic and prem_dic == dict():
  6563. if package not in prem_dic:
  6564. prem_dic[package] = {
  6565. 'code': '',
  6566. 'name': '',
  6567. 'roleList': [],
  6568. 'tendereeMoney': 0,
  6569. 'tendereeMoneyUnit': ""
  6570. }
  6571. for role_type, v in role_dic.items():
  6572. role_text = v.get('role_text', '')
  6573. if role_text == "":
  6574. continue
  6575. money = v.get('money', 0)
  6576. money_unit = v.get('money_unit', '')
  6577. prem_dic[package]['roleList'].append({
  6578. "address": "",
  6579. "linklist": [],
  6580. "role_money": {
  6581. "discount_ratio": "",
  6582. "downward_floating_ratio": "",
  6583. "floating_ratio": "",
  6584. "money": money,
  6585. "money_unit": money_unit
  6586. },
  6587. "role_name": role_type,
  6588. "role_text": role_text,
  6589. "serviceTime": ""
  6590. })
  6591. if len(prem_dic[package]['roleList']) == 0: # 只有项目编号和名称的 丢弃
  6592. prem_dic.pop(package)
  6593. return prem_dic, candidate_set
  6594. def get_prem(self, soup):
  6595. tables = soup.find_all('table')
  6596. tables.reverse()
  6597. rs_dic = {}
  6598. candidate_set = set()
  6599. for table in tables:
  6600. trs = self.tb.table2list(table)
  6601. i = 0
  6602. headers = ""
  6603. while i < len(trs) - 1:
  6604. flag_, contain_header_, headers_ = self.find_header(trs[i])
  6605. if flag_ and headers_ != dict():
  6606. table_items = []
  6607. headers = headers_
  6608. for j in range(i + 1, len(trs)):
  6609. if len(trs[j]) == len(trs[i]):
  6610. flag_, contain_header_, headers_ = self.find_header(trs[j])
  6611. if flag_ or contain_header_:
  6612. break
  6613. else:
  6614. table_items.append(trs[j])
  6615. else:
  6616. # print('表头,内容 列数不一致', len(trs[i]), len(trs[j]))
  6617. break
  6618. if len(table_items) >= 1:
  6619. df = pd.DataFrame(table_items)
  6620. prem_, candidate_set_ = self.extract_from_df(df, headers)
  6621. # print('prem_: ', prem_)
  6622. rs_dic.update(prem_)
  6623. candidate_set.update(candidate_set_)
  6624. i = j - 1
  6625. i += 1
  6626. if rs_dic and 'package_code' not in headers and 'Project' in rs_dic and table.find_previous_sibling(): # 一个表格只有两行且没有标段的,从上一个兄弟标签找标段
  6627. sib = table.find_previous_sibling()
  6628. sib_text = sib.get_text()
  6629. ser_sib = re.search('第?[0-9一二三四五六七八九十a-zZ-Z]{1,4}(标[段号的包项]|([分子]?包|包[组件号]))|(标[段号的包项]|([分子]?包|包[组件号]))号?:?[0-9一二三四五六七八九十a-zZ-Z]{1,4}|包名:[0-9一二三四五六七八九十]{1,4}', sib_text)
  6630. if sib.name in ['p', 'div'] and len(sib_text)<100 and ser_sib:
  6631. package_sib = ser_sib.group(0)
  6632. package_sib = uniform_package_name(package_sib)
  6633. rs_dic[package_sib] = rs_dic.pop('Project')
  6634. table.extract()
  6635. return rs_dic, candidate_set
  6636. def get_candidates_from_text(self, list_sentences, list_entitys):
  6637. candidates = set()
  6638. tenderee_or_agency = set()
  6639. sentences = sorted(list_sentences[0], key=lambda x: x.sentence_index)
  6640. for ent in list_entitys[0]:
  6641. if ent.entity_type in ['org', 'company']:
  6642. sen_index = ent.sentence_index
  6643. text = sentences[sen_index].sentence_text
  6644. b = ent.wordOffset_begin
  6645. e = ent.wordOffset_end
  6646. if ent.label in [2,3,4]: # 直接加实体预测的候选人, 否则规则检查是否为候选人
  6647. candidates.add(ent.entity_text)
  6648. elif isinstance(b, int) and isinstance(e, int) and ent.label in [5]:
  6649. foreword = text[max(0, b - 10):b]
  6650. if re.search(self.p, foreword):
  6651. candidates.add(ent.entity_text)
  6652. if ent.label in [0, 1] and ent.values[ent.label]>0.5:
  6653. tenderee_or_agency.add(ent.entity_text)
  6654. candidates -= tenderee_or_agency # 2024/05/10 463166661 把 四川省第二中医医院作为候选人 过滤掉为招标或代理角色 的候选人
  6655. return candidates
  6656. def predict(self, html, list_sentences, list_entitys, nlp_enterprise):
  6657. self.nlp_enterprise = nlp_enterprise
  6658. html = html.replace('比选申请单位', '中标候选人') # 82347769
  6659. html = re.sub("<html>|</html>|<body>|</body>","",html)
  6660. html = re.sub("##attachment##","",html)
  6661. soup = BeautifulSoup(html, 'lxml')
  6662. richText = soup.find(name='div', attrs={'class': 'richTextFetch'})
  6663. in_attachment = False
  6664. if richText:
  6665. richText = richText.extract() # 过滤掉附件
  6666. prem, candidate_set = self.get_prem(soup)
  6667. if prem == {} and richText:
  6668. prem, candidate_set = self.get_prem(richText)
  6669. in_attachment = True
  6670. candidate_set2 = self.get_candidates_from_text(list_sentences, list_entitys)
  6671. candidate_set.update(candidate_set2)
  6672. return prem, {'candidate': ','.join(candidate_set)}, in_attachment
  6673. def role_special_predictor(web_source_name, content, nlp_enterprise):
  6674. if web_source_name == '中国电子科技集团有限公司电子采购平台':
  6675. ser = re.search(',(\w{5,30}),发布时间:\d+', content)
  6676. if ser and ser.group(1) in nlp_enterprise:
  6677. return ser.group(1)
  6678. elif web_source_name == '高校仪器设备竞价网':
  6679. ser = re.search('--(\w{5,30}),申购单主题', content)
  6680. if ser and ser.group(1) in nlp_enterprise:
  6681. return ser.group(1)
  6682. elif web_source_name == '台泥阳光采购平台':
  6683. ser = re.search(',(\w{5,30})招标公告,', content)
  6684. if ser and ser.group(1) in nlp_enterprise:
  6685. return ser.group(1)
  6686. class WebsourceTenderee():
  6687. def __init__(self):
  6688. with open(os.path.dirname(__file__)+'/websource_tenderee.pkl', 'r', encoding='utf-8') as f:
  6689. self.webno2ree = json.load(f)
  6690. def get_websource_tenderee(self, web_source_no, web_source_name, prem):
  6691. '''
  6692. 通过数据源唯一招标人召回调整prem中的招标人,
  6693. :param web_source_no:
  6694. :param prem:
  6695. :return:
  6696. '''
  6697. p = '(医院|学院|学校|中学|小学|大学|幼儿园|保健院|党校|银行|研究院|血站|红十字会|防治院|研究所)'
  6698. web_ree = self.webno2ree.get(web_source_no, '')
  6699. if web_source_no.startswith('18591-') and web_ree == "":
  6700. web_ree = '中国人民解放军总医院'
  6701. elif web_source_no.startswith('Y00484-') and web_ree == "":
  6702. web_ree = '航空总医院'
  6703. if web_ree == "" and re.search('\w{2,8}(大学|医院)$', web_source_name): # 20240524 大学、医院类站源没唯一招标人默认为站源名称
  6704. web_ree = web_source_name
  6705. if web_ree != '':
  6706. if 'Project' in prem[0]['prem']:
  6707. find_tenderee = False
  6708. for d in prem[0]['prem']['Project']['roleList']:
  6709. if d['role_name'] == 'tenderee':
  6710. find_tenderee = True
  6711. if d['role_text'] == "":
  6712. d['role_text'] = web_ree
  6713. elif re.search('大学$', web_ree) and re.search('学院$', d['role_text']) and web_ree not in d['role_text']:
  6714. d['role_text'] = web_ree
  6715. elif d.get('role_prob', 0) < 0.8 and get_business_data(d['role_text'])[0] == False: # 20240201 概率低于0.8且没有工商数据的替换为站源招标人
  6716. d['role_text'] = web_ree
  6717. # elif re.search(p, web_ree) and (re.search(p, d['role_text'])==None and len(d['role_text'])<6): # 数据源唯一招标人以医院等结尾,角色中无相关关键词的,替换为数据源招标人
  6718. # d['role_text'] = web_ree
  6719. # elif re.search('有限(责任)?公司', web_ree) and (re.search('有限(责任)?公司', d['role_text'])==None and len(d['role_text'])<6):
  6720. # d['role_text'] = web_ree
  6721. break
  6722. if not find_tenderee: # 没招标人的添加
  6723. prem[0]['prem']['Project']['roleList'].append({'role_name': 'tenderee',
  6724. 'role_text': '%s' % web_ree,
  6725. 'role_money': {'money': 0, 'money_unit': '',
  6726. 'floating_ratio': '',
  6727. 'downward_floating_ratio': '',
  6728. 'discount_ratio': ''},
  6729. 'linklist': [],
  6730. 'serviceTime': '',
  6731. 'address': ''})
  6732. else:
  6733. prem[0]['prem']['Project'] = {'code': '',
  6734. 'tendereeMoney': 0,
  6735. 'roleList': [
  6736. {'role_name': 'tenderee',
  6737. 'role_text': '%s' % web_ree,
  6738. 'role_money': {'money': 0, 'money_unit': '', 'floating_ratio': '',
  6739. 'downward_floating_ratio': '', 'discount_ratio': ''},
  6740. 'linklist': [],
  6741. 'serviceTime': '',
  6742. 'address': ''}
  6743. ]}
  6744. return prem
  6745. class ApprovalPredictor():
  6746. def __init__(self):
  6747. '''
  6748. 项目(法人)单位
  6749. '''
  6750. self.other_part = {
  6751. "project_name": "((项目|工程|采购|招标|计划|建设|规划)名称?|生产建设项目|申请项目):(?P<main>[^:。]{5,50})[,。](\w{2,10}:|$)?", # 项目名称
  6752. "project_code": "(立案号|项目(统一)?代码|(项目|工程|采购|招标|计划|任务|备案|索引)(编[号码]|号)):?(?P<main>(\w{2,8})?[()〔〕【】\[\]a-zA-Z0-9-]{5,30}号?)(\w{2,10}:|$)?", # 项目编号
  6753. "doc_num": "((审[批查核]|批[复准]|立项|[定知]书|[公发批]文|用地|决定|备案|核准|许可|确认|受理|申请报告|文件|意见书|办件)[文编]?号|综合受理号|文书?号|合格书号):?(?P<main>(\w{2,8})?[()〔〕【】\[\]a-zA-Z0-9-.]{5,30}号?)[,。]?(\w{2,10}:|$)?", # 文号
  6754. "pro_type": "((申[报请]|审核备|项目|立项)(类型|种类)|项目所属行业|行业(分类|归属)|产业领域|项目行业):(?P<main>[^:。]{2,30})[,。](\w{2,10}:|$)?", # 项目类型
  6755. "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,10}:|$)?", # 建设年限
  6756. "construction_scale": "(建设内容[及和](建设)?规模|建设规模[及和](主要)?(建设)?内容|(建设|招标|采购))?内容|(建设|工程|项目)(主要)?(规模|内容|概况|面积)([及和](主要)?(规模|内容|概况|面积))?(如下)?):(?P<main>[^:。]{2,250})[,。](\w{2,10}:|$)?", # 建设规模
  6757. "approval_items": "((审[批查核]|批[复准]|申请|监管)(事项|内容|名称)|事项名称|事项审批):(?P<main>[^:。]{2,70})[,。](\w{2,10}:|$)?", # 审批事项
  6758. "properties": "((建设|工程|项目)性质):(?P<main>[^:。]{2,50})[,。](\w{2,10}:|$)?", # 建设性质
  6759. "approval_result": "((审[批查核]|批[复准]|核[发准]|许可|抽查|备案)(结果|决定|结论|状态|回复|意见)|(办[理件]|,)(状态|意见|结果)|项目(当前|目前)?状态):(?P<main>[^:。]{2,20})[,。](\w{2,10}:|$)?", # 审批结果
  6760. "phone": "(联系)?电话:(?P<main>1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|" # 联系电话
  6761. '\+86.?1[3-9]\d{9}|'
  6762. '0[1-9]\d{1,2}[-—-―][2-9]\d{6}\d?[-—-―]\d{1,4}|'
  6763. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=1[3-9]\d{9})|'
  6764. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[2-9]\d{6}\d?)|'
  6765. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?(?=[2-9]\d{6,7})|'
  6766. '0[1-9]\d{1,2}[-—-―]{0,2}[2-9]\d{6}\d?|'
  6767. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?[2-9]\d{6}\d?-?\d{,4}|'
  6768. '400\d{7}转\d{1,4}|'
  6769. '[2-9]\d{6,7})[,。](\w{2,10}:|$)?'
  6770. }
  6771. self.role_type = {
  6772. "declare_company": "(申[请报]|填报|呈报)(人|部门|机关|单位|企业|公司|机构|组织)", # 申报单位
  6773. "construct_company": "(业主|建设|用地|委托|发包|产权|项目))?(部门|机关|单位|企业|公司|方|业主)|主送机关|法人单位|甲方", # 建设单位
  6774. "approver": "(审[批查核议图]|许可|批[复准](用地)?|发证|管理|办理|受理|核[发准]|备案|承办)(部门|机关|单位|企业|公司|机构)|实施主体", # 审批部门
  6775. "evaluation_agency": "(环境|环保)?(影响)?(环评|评价|评估)(机构|单位|公司)" , # 环评机构
  6776. "compilation_unit": "编制单位", # 编制单位 20240701加
  6777. "publisher": "(发布|发文|公示|公告)(人|部门|机关|单位|企业|公司|机构|组织)" # 发布机构 20240703加
  6778. }
  6779. self.person_type = {
  6780. "legal_person": "项目法人|法定代表人|企业法人" # 项目法人
  6781. }
  6782. self.date_type = {
  6783. "time_declare": "(申[请报]|填报|呈报)(时间|日期)", # 申报时间
  6784. "time_commencement": "(开工|动工|(项目|建设|工程|施工)开始)(时间|日期)", # 开工时间
  6785. "time_completion": "(竣工|完工|验收|(项目|建设|工程|施工)(完成|结束))(备案)?(时间|日期)", # 竣工时间
  6786. "time_approval": "(审[批查核查议]|许可|批[复准](用地)?|发证|管理|办理|受理|核[发准]|备案|决定)(时间|日期)", # 审批时间 20240701加
  6787. "time_release": "(发布|发文|公告|生成|成文)(时间|日期)" # 发布时间
  6788. }
  6789. self.addr_type = {
  6790. "project_addr": "(建设|工程|项目|施工|地块|用地)\w{,2}(地址|地点|位置|所在地)|[宗土]地坐落" # 建设地址
  6791. }
  6792. self.money_type = {
  6793. "total_tendereeMoney": "(项目|概算|投资)金额|项目投资|总投资|总预算|总概算|投资(规模|总额|估算|概算)|批复概算|投资额", # 总投资
  6794. }
  6795. def predict(self, list_sentences, list_entitys, span=12):
  6796. rs_dic = {k: "" for k in
  6797. self.other_part.keys() | self.role_type.keys() | self.date_type.keys() | self.addr_type.keys() | self.money_type.keys() | self.person_type.keys()}
  6798. rs_dic['moneysource'] = ""
  6799. sentences = [it.sentence_text for it in sorted(list_sentences[0], key=lambda x: x.sentence_index)]
  6800. entities = [[] for _ in range(len(sentences))]
  6801. rs_l = []
  6802. found_key = 0
  6803. code_name_set = set() # 项目编号、名称集合
  6804. org_set = set() # 保存可能为审批部门的角色
  6805. for entity in list_entitys[0]:
  6806. entities[entity.sentence_index].append(entity)
  6807. for i in range(len(sentences)):
  6808. multi_project = {k: "" for k in
  6809. self.other_part.keys() | self.role_type.keys() | self.date_type.keys() | self.addr_type.keys() | self.money_type.keys() | self.person_type.keys()}
  6810. multi_project['moneysource'] = ''
  6811. text = sentences[i]
  6812. for entity in entities[i]:
  6813. b, e = entity.wordOffset_begin, entity.wordOffset_end
  6814. if entity.entity_type in ['org', 'company']:
  6815. flag = 1
  6816. for k, v in self.role_type.items():
  6817. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  6818. if rs_dic[k] == '':
  6819. rs_dic[k] = entity.entity_text
  6820. multi_project[k] = entity.entity_text
  6821. found_key = 1
  6822. flag = 0
  6823. if flag and entity.entity_type == "org" and re.search('(局|委员会|委|厅)$', entity.entity_text):
  6824. org_set.add(entity.entity_text)
  6825. elif entity.entity_type in ['person']:
  6826. for k, v in self.person_type.items():
  6827. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  6828. if rs_dic[k] == '':
  6829. rs_dic[k] = entity.entity_text
  6830. multi_project[k] = entity.entity_text
  6831. found_key = 1
  6832. break
  6833. elif entity.entity_type in ['time']:
  6834. for k, v in self.date_type.items():
  6835. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  6836. time = timeFormat(entity.entity_text, default_first_day=False) if k in ['time_completion'] else timeFormat(entity.entity_text)
  6837. if time == "":
  6838. continue
  6839. if rs_dic[k] == '':
  6840. rs_dic[k] = time
  6841. multi_project[k] = time
  6842. found_key = 1
  6843. elif entity.entity_type in ['location']:
  6844. for k, v in self.addr_type.items():
  6845. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  6846. if rs_dic[k] == '':
  6847. rs_dic[k] = entity.entity_text
  6848. multi_project[k] = entity.entity_text
  6849. found_key = 1
  6850. elif entity.entity_type in ['money']:
  6851. for k, v in self.money_type.items():
  6852. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  6853. if rs_dic[k] == '':
  6854. rs_dic[k] = entity.entity_text
  6855. multi_project[k] = entity.entity_text
  6856. found_key = 1
  6857. elif entity.entity_type in ['moneysource']:
  6858. rs_dic['moneysource'] = turnMoneySource(entity.entity_text)
  6859. multi_project['moneysource'] = turnMoneySource(entity.entity_text)
  6860. elif entity.entity_type in ['code']:
  6861. k = 'project_code'
  6862. v = self.other_part[k].split(':', maxsplit=1)[0]
  6863. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  6864. if rs_dic[k] == '':
  6865. rs_dic[k] = entity.entity_text
  6866. multi_project[k] = entity.entity_text
  6867. found_key = 1
  6868. elif entity.entity_type in ['name']:
  6869. k = 'project_name'
  6870. v = self.other_part[k].split(':', maxsplit=1)[0]
  6871. if re.search(v, sentences[entity.sentence_index][max(0, b - span):b]):
  6872. if rs_dic[k] == '':
  6873. rs_dic[k] = entity.entity_text
  6874. multi_project[k] = entity.entity_text
  6875. found_key = 1
  6876. for k, v in self.other_part.items():
  6877. for iter in re.finditer(v, text):
  6878. if rs_dic[k] == '':
  6879. rs_dic[k] = iter.group('main')
  6880. multi_project[k] = iter.group('main')
  6881. found_key = 1
  6882. break
  6883. for k, v in self.date_type.items():
  6884. for iter in re.finditer(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): # 规则补充实体识别不到的日期时间
  6885. time = timeFormat(iter.group('main'), default_first_day=False) if k in ['time_completion'] else timeFormat(iter.group('main'))
  6886. if time == "":
  6887. continue
  6888. if rs_dic[k] == '':
  6889. rs_dic[k] = time
  6890. multi_project[k] = time
  6891. found_key = 1
  6892. break
  6893. if (multi_project['project_code'] != "" or multi_project['project_name'] != "") and multi_project['project_code']+multi_project['project_name'] not in code_name_set:
  6894. code_name_set.add(multi_project['project_code']+multi_project['project_name'])
  6895. district = getPredictor('district').get_area(
  6896. multi_project['project_name'] + multi_project['project_addr'], '')
  6897. if district['district']['province'] != '全国':
  6898. multi_project['area'] = district['district']['area']
  6899. multi_project['province'] = district['district']['province']
  6900. multi_project['city'] = district['district']['city']
  6901. multi_project['district'] = district['district']['district']
  6902. multi_project = {k:v for k,v in multi_project.items() if v != ''}
  6903. rs_l.append(multi_project)
  6904. if len(rs_l)>1 and len(set(rs_l[0].keys()))>2 and set(rs_l[0].keys())&set(rs_l[1].keys())!=set():
  6905. return rs_l
  6906. elif found_key == 1:
  6907. district = getPredictor('district').get_area(
  6908. rs_dic['construct_company'] + rs_dic['project_name'] + rs_dic['project_addr'], '')
  6909. if district['district']['province'] != '全国':
  6910. rs_dic['area'] = district['district']['area']
  6911. rs_dic['province'] = district['district']['province']
  6912. rs_dic['city'] = district['district']['city']
  6913. rs_dic['district'] = district['district']['district']
  6914. if len(org_set) == 1 and rs_dic['approver'] == "":
  6915. rs_dic['approver'] == org_set.pop()
  6916. rs_dic = {k: v for k, v in rs_dic.items() if v != ''}
  6917. return [rs_dic]
  6918. return []
  6919. def getSavedModel():
  6920. #predictor = FormPredictor()
  6921. graph = tf.Graph()
  6922. with graph.as_default():
  6923. model = tf.keras.models.load_model("../form/model/model_form.model_item.hdf5",custom_objects={"precision":precision,"recall":recall,"f1_score":f1_score})
  6924. #print(tf.graph_util.remove_training_nodes(model))
  6925. tf.saved_model.simple_save(
  6926. tf.keras.backend.get_session(),
  6927. "./h5_savedmodel/",
  6928. inputs={"image": model.input},
  6929. outputs={"scores": model.output}
  6930. )
  6931. def getBiLSTMCRFModel(MAX_LEN,vocab,EMBED_DIM,BiRNN_UNITS,chunk_tags,weights):
  6932. '''
  6933. model = models.Sequential()
  6934. model.add(layers.Embedding(len(vocab), EMBED_DIM, mask_zero=True)) # Random embedding
  6935. model.add(layers.Bidirectional(layers.LSTM(BiRNN_UNITS // 2, return_sequences=True)))
  6936. crf = CRF(len(chunk_tags), sparse_target=True)
  6937. model.add(crf)
  6938. model.summary()
  6939. model.compile('adam', loss=crf.loss_function, metrics=[crf.accuracy])
  6940. return model
  6941. '''
  6942. input = layers.Input(shape=(None,),dtype="int32")
  6943. if weights is not None:
  6944. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True,weights=[weights],trainable=True)(input)
  6945. else:
  6946. embedding = layers.embeddings.Embedding(len(vocab),EMBED_DIM,mask_zero=True)(input)
  6947. bilstm = layers.Bidirectional(layers.LSTM(BiRNN_UNITS//2,return_sequences=True))(embedding)
  6948. bilstm_dense = layers.TimeDistributed(layers.Dense(len(chunk_tags)))(bilstm)
  6949. crf = CRF(len(chunk_tags),sparse_target=True)
  6950. crf_out = crf(bilstm_dense)
  6951. model = models.Model(input=[input],output = [crf_out])
  6952. model.summary()
  6953. model.compile(optimizer = 'adam', loss = crf.loss_function, metrics = [crf.accuracy])
  6954. return model
  6955. import h5py
  6956. def h5_to_graph(sess,graph,h5file):
  6957. f = h5py.File(h5file,'r') #打开h5文件
  6958. def getValue(v):
  6959. _value = f["model_weights"]
  6960. list_names = str(v.name).split("/")
  6961. for _index in range(len(list_names)):
  6962. print(v.name)
  6963. if _index==1:
  6964. _value = _value[list_names[0]]
  6965. _value = _value[list_names[_index]]
  6966. return _value.value
  6967. def _load_attributes_from_hdf5_group(group, name):
  6968. """Loads attributes of the specified name from the HDF5 group.
  6969. This method deals with an inherent problem
  6970. of HDF5 file which is not able to store
  6971. data larger than HDF5_OBJECT_HEADER_LIMIT bytes.
  6972. # Arguments
  6973. group: A pointer to a HDF5 group.
  6974. name: A name of the attributes to load.
  6975. # Returns
  6976. data: Attributes data.
  6977. """
  6978. if name in group.attrs:
  6979. data = [n.decode('utf8') for n in group.attrs[name]]
  6980. else:
  6981. data = []
  6982. chunk_id = 0
  6983. while ('%s%d' % (name, chunk_id)) in group.attrs:
  6984. data.extend([n.decode('utf8')
  6985. for n in group.attrs['%s%d' % (name, chunk_id)]])
  6986. chunk_id += 1
  6987. return data
  6988. def readGroup(gr,parent_name,data):
  6989. for subkey in gr:
  6990. print(subkey)
  6991. if parent_name!=subkey:
  6992. if parent_name=="":
  6993. _name = subkey
  6994. else:
  6995. _name = parent_name+"/"+subkey
  6996. else:
  6997. _name = parent_name
  6998. if str(type(gr[subkey]))=="<class 'h5py._hl.group.Group'>":
  6999. readGroup(gr[subkey],_name,data)
  7000. else:
  7001. data.append([_name,gr[subkey].value])
  7002. print(_name,gr[subkey].shape)
  7003. layer_names = _load_attributes_from_hdf5_group(f["model_weights"], 'layer_names')
  7004. list_name_value = []
  7005. readGroup(f["model_weights"], "", list_name_value)
  7006. '''
  7007. for k, name in enumerate(layer_names):
  7008. g = f["model_weights"][name]
  7009. weight_names = _load_attributes_from_hdf5_group(g, 'weight_names')
  7010. #weight_values = [np.asarray(g[weight_name]) for weight_name in weight_names]
  7011. for weight_name in weight_names:
  7012. list_name_value.append([weight_name,np.asarray(g[weight_name])])
  7013. '''
  7014. for name_value in list_name_value:
  7015. name = name_value[0]
  7016. '''
  7017. if re.search("dense",name) is not None:
  7018. name = name[:7]+"_1"+name[7:]
  7019. '''
  7020. value = name_value[1]
  7021. print(name,graph.get_tensor_by_name(name),np.shape(value))
  7022. sess.run(tf.assign(graph.get_tensor_by_name(name),value))
  7023. def initialize_uninitialized(sess):
  7024. global_vars = tf.global_variables()
  7025. is_not_initialized = sess.run([tf.is_variable_initialized(var) for var in global_vars])
  7026. not_initialized_vars = [v for (v, f) in zip(global_vars, is_not_initialized) if not f]
  7027. adam_vars = []
  7028. for _vars in not_initialized_vars:
  7029. if re.search("Adam",_vars.name) is not None:
  7030. adam_vars.append(_vars)
  7031. print([str(i.name) for i in adam_vars]) # only for testing
  7032. if len(adam_vars):
  7033. sess.run(tf.variables_initializer(adam_vars))
  7034. def save_codename_model():
  7035. # filepath = "../projectCode/models/model_project_"+str(60)+"_"+str(200)+".hdf5"
  7036. filepath = "../../dl_dev/projectCode/models_tf/59-L0.471516189943-F0.8802154826344823-P0.8789179683459191-R0.8815168335321886/model.ckpt"
  7037. vocabpath = "../projectCode/models/vocab.pk"
  7038. classlabelspath = "../projectCode/models/classlabels.pk"
  7039. # vocab = load(vocabpath)
  7040. # class_labels = load(classlabelspath)
  7041. w2v_matrix = load('codename_w2v_matrix.pk')
  7042. graph = tf.get_default_graph()
  7043. with graph.as_default() as g:
  7044. ''''''
  7045. # model = getBiLSTMCRFModel(None, vocab, 60, 200, class_labels,weights=None)
  7046. #model = models.load_model(filepath,custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score,"CRF":CRF,"loss":CRF.loss_function})
  7047. sess = tf.Session(graph=g)
  7048. # sess = tf.keras.backend.get_session()
  7049. char_input, logits, target, keepprob, length, crf_loss, trans, train_op = BiLSTM_CRF_tfmodel(sess, w2v_matrix)
  7050. #with sess.as_default():
  7051. sess.run(tf.global_variables_initializer())
  7052. # print(sess.run("time_distributed_1/kernel:0"))
  7053. # model.load_weights(filepath)
  7054. saver = tf.train.Saver()
  7055. saver.restore(sess, filepath)
  7056. # print("logits",sess.run(logits))
  7057. # print("#",sess.run("time_distributed_1/kernel:0"))
  7058. # x = load("codename_x.pk")
  7059. #y = model.predict(x)
  7060. # y = sess.run(model.output,feed_dict={model.input:x})
  7061. # for item in np.argmax(y,-1):
  7062. # print(item)
  7063. tf.saved_model.simple_save(
  7064. sess,
  7065. "./codename_savedmodel_tf/",
  7066. inputs={"inputs": char_input,
  7067. "inputs_length":length,
  7068. 'keepprob':keepprob},
  7069. outputs={"logits": logits,
  7070. "trans":trans}
  7071. )
  7072. def save_role_model():
  7073. '''
  7074. @summary: 保存model为savedModel,部署到PAI平台上调用
  7075. '''
  7076. model_role = PREMPredict().model_role
  7077. with model_role.graph.as_default():
  7078. model = model_role.getModel()
  7079. sess = tf.Session(graph=model_role.graph)
  7080. print(type(model.input))
  7081. sess.run(tf.global_variables_initializer())
  7082. h5_to_graph(sess, model_role.graph, model_role.model_role_file)
  7083. model = model_role.getModel()
  7084. tf.saved_model.simple_save(sess,
  7085. "./role_savedmodel/",
  7086. inputs={"input0":model.input[0],
  7087. "input1":model.input[1],
  7088. "input2":model.input[2]},
  7089. outputs={"outputs":model.output}
  7090. )
  7091. def save_money_model():
  7092. model_file = os.path.dirname(__file__)+"/../money/models/model_money_word.h5"
  7093. graph = tf.Graph()
  7094. with graph.as_default():
  7095. sess = tf.Session(graph=graph)
  7096. with sess.as_default():
  7097. # model = model_money.getModel()
  7098. # model.summary()
  7099. # sess.run(tf.global_variables_initializer())
  7100. # h5_to_graph(sess, model_money.graph, model_money.model_money_file)
  7101. model = models.load_model(model_file,custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score})
  7102. model.summary()
  7103. print(model.weights)
  7104. tf.saved_model.simple_save(sess,
  7105. "./money_savedmodel2/",
  7106. inputs = {"input0":model.input[0],
  7107. "input1":model.input[1],
  7108. "input2":model.input[2]},
  7109. outputs = {"outputs":model.output}
  7110. )
  7111. def save_person_model():
  7112. model_person = EPCPredict().model_person
  7113. with model_person.graph.as_default():
  7114. x = load("person_x.pk")
  7115. _data = np.transpose(np.array(x),(1,0,2,3))
  7116. model = model_person.getModel()
  7117. sess = tf.Session(graph=model_person.graph)
  7118. with sess.as_default():
  7119. sess.run(tf.global_variables_initializer())
  7120. model_person.load_weights()
  7121. #h5_to_graph(sess, model_person.graph, model_person.model_person_file)
  7122. predict_y = sess.run(model.output,feed_dict={model.input[0]:_data[0],model.input[1]:_data[1]})
  7123. #predict_y = model.predict([_data[0],_data[1]])
  7124. print(np.argmax(predict_y,-1))
  7125. tf.saved_model.simple_save(sess,
  7126. "./person_savedmodel/",
  7127. inputs={"input0":model.input[0],
  7128. "input1":model.input[1]},
  7129. outputs = {"outputs":model.output})
  7130. def save_form_model():
  7131. model_form = FormPredictor()
  7132. with model_form.graph.as_default():
  7133. model = model_form.getModel("item")
  7134. sess = tf.Session(graph=model_form.graph)
  7135. sess.run(tf.global_variables_initializer())
  7136. h5_to_graph(sess, model_form.graph, model_form.model_file_item)
  7137. tf.saved_model.simple_save(sess,
  7138. "./form_savedmodel/",
  7139. inputs={"inputs":model.input},
  7140. outputs = {"outputs":model.output})
  7141. def save_codesplit_model():
  7142. filepath_code = "../../dl_dev/projectCode/models/model_code.hdf5"
  7143. graph = tf.Graph()
  7144. with graph.as_default():
  7145. model_code = models.load_model(filepath_code, custom_objects={'precision':precision,'recall':recall,'f1_score':f1_score})
  7146. sess = tf.Session()
  7147. sess.run(tf.global_variables_initializer())
  7148. h5_to_graph(sess, graph, filepath_code)
  7149. tf.saved_model.simple_save(sess,
  7150. "./codesplit_savedmodel/",
  7151. inputs={"input0":model_code.input[0],
  7152. "input1":model_code.input[1],
  7153. "input2":model_code.input[2]},
  7154. outputs={"outputs":model_code.output})
  7155. def save_timesplit_model():
  7156. filepath = '../time/model_label_time_classify.model.hdf5'
  7157. with tf.Graph().as_default() as graph:
  7158. time_model = models.load_model(filepath, custom_objects={'precision': precision, 'recall': recall, 'f1_score': f1_score})
  7159. with tf.Session() as sess:
  7160. sess.run(tf.global_variables_initializer())
  7161. h5_to_graph(sess, graph, filepath)
  7162. tf.saved_model.simple_save(sess,
  7163. "./timesplit_model/",
  7164. inputs={"input0":time_model.input[0],
  7165. "input1":time_model.input[1]},
  7166. outputs={"outputs":time_model.output})
  7167. if __name__=="__main__":
  7168. #save_role_model()
  7169. # save_codename_model()
  7170. # save_money_model()
  7171. #save_person_model()
  7172. #save_form_model()
  7173. #save_codesplit_model()
  7174. # save_timesplit_model()
  7175. '''
  7176. # with tf.Session(graph=tf.Graph()) as sess:
  7177. # from tensorflow.python.saved_model import tag_constants
  7178. # meta_graph_def = tf.saved_model.loader.load(sess, [tag_constants.SERVING], "./person_savedModel")
  7179. # graph = tf.get_default_graph()
  7180. # signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
  7181. # signature = meta_graph_def.signature_def
  7182. # input0 = sess.graph.get_tensor_by_name(signature[signature_key].inputs["input0"].name)
  7183. # input1 = sess.graph.get_tensor_by_name(signature[signature_key].inputs["input1"].name)
  7184. # outputs = sess.graph.get_tensor_by_name(signature[signature_key].outputs["outputs"].name)
  7185. # x = load("person_x.pk")
  7186. # _data = np.transpose(x,[1,0,2,3])
  7187. # y = sess.run(outputs,feed_dict={input0:_data[0],input1:_data[1]})
  7188. # print(np.argmax(y,-1))
  7189. '''
  7190. # MAX_LEN = 1000
  7191. # # vocabpath = os.path.dirname(__file__) + "/codename_vocab.pk"
  7192. # # vocab = load(vocabpath)
  7193. # # word2index = dict((w, i) for i, w in enumerate(np.array(vocab)))
  7194. # # index_unk = word2index.get("<unk>")
  7195. # # sentence = "招标人:广州市重点公共建设项目管理中心,联系人:李工,联系方式:020-22905689,招标代理:广东重工建设监理有限公司," \
  7196. # # "代理联系人:薛家伟,代理联系方式:13535014481,招标监督机构:广州市重点公共建设项目管理中心,监督电话:020-22905690," \
  7197. # # "备注:以上为招标公告简要描述,招标公告详细信息请查看“招标公告”附件,"
  7198. # # sentence = sentence*5
  7199. # # list_sentence = [sentence]*200
  7200. # # # print(list_sentence)
  7201. # # x = [[word2index.get(word, index_unk) for word in sentence] for sentence in
  7202. # # list_sentence]
  7203. # # x_len = [len(_x) if len(_x) < MAX_LEN else MAX_LEN for _x in x]
  7204. # # # print(x_len)
  7205. # # x = pad_sequences(x, maxlen=MAX_LEN, padding="post", truncating="post")
  7206. # #
  7207. # # requests_result = requests.post(API_URL + "/predict_codeName", json={"inouts": x.tolist(), "inouts_len": x_len},
  7208. # # verify=True)
  7209. # # # predict_y = json.loads(requests_result.text)['result']
  7210. # # print("cost_time:", json.loads(requests_result.text)['cost_time'])
  7211. # # print(MAX_LEN, len(sentence), len(list_sentence))
  7212. # # requests_result = requests.post(API_URL + "/predict_codeName", json={"inouts": x.tolist(), "inouts_len": x_len},
  7213. # # verify=True)
  7214. # # # predict_y = json.loads(requests_result.text)['result']
  7215. # # print("cost_time:", json.loads(requests_result.text)['cost_time'])
  7216. # # print(MAX_LEN, len(sentence), len(list_sentence))
  7217. # docid = ""
  7218. # title = ''
  7219. # with open('d:/html/2.html', 'r', encoding='utf-8') as f:
  7220. # html = f.read()
  7221. # product_attr = ProductAttributesPredictor()
  7222. # rs = product_attr.predict(docid='', html=html, page_time="")
  7223. # print(rs)
  7224. # docid = ""
  7225. # title = ''
  7226. # with open('d:/html/2.html', 'r', encoding='utf-8') as f:
  7227. # html = f.read()
  7228. # tb_extract = TablePremExtractor()
  7229. # rs = tb_extract.predict(html, [
  7230. # "广东省广裕集团嘉顺实业有限责任公司",
  7231. # "广州顺为招标采购有限公司",
  7232. # "中华人民共和国"
  7233. # ], web_source_name = '河钢供应链管理平台')
  7234. # print('标段数:',len(rs))
  7235. # print(rs)
  7236. # # # 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]
  7237. # # # 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]
  7238. # # # 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]
  7239. # # # ids = [ 224751772, 228535928, 228578442, 233492018, 237390205, 237560666, 237887867, 238134423, 240514770]
  7240. # # # 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]
  7241. # # # 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]
  7242. # 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]
  7243. # df = pd.read_csv('E:\产品单价数量/待预测数据html内容4.csv')
  7244. # print('公告数:', len(df), len(ids))
  7245. # df = df[df['docid'].isin(ids)]
  7246. # ids = []
  7247. # for docid,html in zip(df['docid'],df['dochtmlcon']):
  7248. # product_attr = ProductAttributesPredictor()
  7249. # rs, _ = product_attr.predict(docid='', html=html, page_time="")
  7250. # # print(docid, rs)
  7251. # # print(docid, rs[0]['product_attrs']['header_col'])
  7252. # # print('*'*20)
  7253. # if rs[0]['product_attrs']['header_col'] == []:
  7254. # ids.append(docid)
  7255. # print(docid, rs[0]['product_attrs']['header_col'])
  7256. # print('*' * 20)
  7257. # else:
  7258. # print(docid, rs[0]['product_attrs']['header_col'])
  7259. # print('*' * 20)
  7260. # print(len(ids), ids)
  7261. # role = RoleRulePredictor()
  7262. # labels = []
  7263. # keywords = []
  7264. # # df = pd.read_excel('E:\实体识别数据/2023-08-24所有公告_重新预测结果.xlsx')
  7265. # df = pd.read_excel('E:\实体识别数据/2023-08-24所有公告_重新预测结果60000-90000.xlsx')
  7266. # columns = ['docid', 'type', 'label', 'value', 'front', 'behind',
  7267. # 'front6', 'entity_text', 'behind6', 'front6_reverse', 'rule_label', 'keyword', 'pos']
  7268. # print(df.columns)
  7269. # df.fillna('', inplace=True)
  7270. # for front, center, behind, entity_text in zip(df['front'], df['entity_text'], df['behind'], df['entity_text']):
  7271. # front = str(front)
  7272. # behind = str(behind)
  7273. # label, _prob, _flag, keyword = role.rule_predict(front, center, behind, entity_text)
  7274. # labels.append(label)
  7275. # keywords.append(keyword)
  7276. # df['rule_label'] = pd.Series(labels)
  7277. # df['keyword'] = pd.Series(keywords)
  7278. # df['front6'] = df['front'].apply(lambda x: str(x)[-6:])
  7279. # df['behind6'] = df['behind'].apply(lambda x: str(x)[:6])
  7280. # df['pos'] = df.apply(lambda x: 1 if x['label']==x['rule_label'] else 0, axis=1)
  7281. # # df.to_excel('E:\实体识别数据/2023-08-24所有公告_重新预测结果_rule_predict.xlsx', index=False, columns=columns)
  7282. # df.to_excel('E:\实体识别数据/2023-08-24所有公告_重新预测结果60000-90000_rule_predict.xlsx', index=False, columns=columns)