extract.go 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983
  1. package extract
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/shopspring/decimal"
  7. "go.mongodb.org/mongo-driver/bson/primitive"
  8. "jy/clear"
  9. db "jy/mongodbutil"
  10. "jy/pretreated"
  11. ju "jy/util"
  12. qu "qfw/util"
  13. "qfw/util/redis"
  14. "regexp"
  15. "sort"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "unicode/utf8"
  21. log "github.com/donnie4w/go-logger/logger"
  22. "gopkg.in/mgo.v2/bson"
  23. )
  24. var (
  25. lock, lockrule, lockclear, locktag, blocktag sync.RWMutex
  26. JYUrl = "https://www.jianyu360.com/article/content/%s.html"
  27. cut = ju.NewCut() //获取正文并清理
  28. ExtLogs map[*TaskInfo][]map[string]interface{} //抽取日志
  29. TaskList map[string]*ExtractTask //任务列表
  30. ClearTaskList map[string]*ClearTask //清理任务列表
  31. saveLimit = 100 //抽取日志批量保存
  32. PageSize = 5000 //查询分页
  33. Fields = `{"title":1,"summary":1,"detail":1,"contenthtml":1,"site":1,"spidercode":1,"toptype":1,"subtype":1,"bidstatus":1,"area":1,"city":1,"comeintime":1,"publishtime":1,"sensitive":1,"projectinfo":1,"jsondata":1,"href":1,"infoformat":1,"attach_text":1,"dataging":1,"review_experts":1,"purchasing":1}`
  34. //Fields = `{"title":1,"summary":1,"detail":1,"contenthtml":1,"site":1,"spidercode":1,"toptype":1,"subtype":1,"bidstatus":1,"area":1,"city":1,"comeintime":1,"publishtime":1,"sensitive":1,"projectinfo":1,"jsondata":1,"href":1,"infoformat":1,"attach_text":1,"dataging":1,"new_attach_text":1,"createtime":1,"currency":1,"id":1,"company_email":1,"buyerclass":1,"tagname":1,"company_phone":1,"appid":1,"industry":1,"projectscope":1,"item":1,"s_subscopeclass":1,"matchkey":1,"jybxhref":1,"legal_person":1,"matchtype":1,"review_experts":1,"purchasing":1}`
  35. Fields2 = `{"budget":1,"bidamount":1,"title":1,"projectname":1,"winner":1}`
  36. /*f = map[string]bool{
  37. "T": true,
  38. "_d": true,
  39. "area": true,
  40. "channel": true,
  41. "comeintime": true,
  42. "competehref": true,
  43. "href": true,
  44. "l_np_publishtime": true,
  45. "publishtime": true,
  46. "sendflag": true,
  47. "site": true,
  48. "spidercode": true,
  49. "title": true,
  50. "projectname": true,
  51. }*/
  52. /*f = map[string]bool{
  53. "contentid": true,
  54. "progName": true,
  55. "updateTime": true,
  56. "url": true,
  57. "areaId": true,
  58. "areaName": true,
  59. "popTitle": true,
  60. "showTitle": true,
  61. "progId": true,
  62. "catid": true,
  63. "isConcern": true,
  64. "followCount": true,
  65. "followSuggestion": true,
  66. "isBoutique": true,
  67. "canTj": true,
  68. "tenderAmountNumber": true,
  69. "tenderAmountUnit": true,
  70. "bidderAmountNumber": true,
  71. "bidderAmountUnit": true,
  72. "registrationBeginTime": true,
  73. "registrationEndTime": true,
  74. "starNum": true,
  75. "title": true,
  76. "proInvested": true,
  77. "projectname": true,
  78. }*/
  79. spidercode = map[string]bool{
  80. "gd_zhsggzyjyzx_jsgc_fjczbgg": true,
  81. "js_szgyyqggzyjyzx_jsgc_zjfbgs": true,
  82. "zj_tzsyhggzyjyzx_jsgc_kbqk": true,
  83. "hb_tmsggzyjyxxw_jsgc_kbqk": true,
  84. "zj_nbsyyggzyjyw_jsgc_kbqk": true,
  85. "zj_zjsggzyjyzx_jyxx_kbjg": true,
  86. "zj_zjzdgcjyw_ztbjglxx_kbjg": true,
  87. "zj_lssggzyjyw_jsgc_kbsk": true,
  88. "zj_qzslyxggzyjyzx_gggs_xkbjl": true,
  89. "sc_mssggzydzjypt_jsgc_kbjl": true,
  90. "sc_pzhsggzyjyfwzx_jsgc_kbylb": true,
  91. "a_zgzbtbggfwpt_wasjgf_ss_kbjl": true,
  92. "a_hbszbtbggfwpt_kbjl": true,
  93. "a_szsjsgcjyfwzxbafzx_kbqkgs": true,
  94. "a_szldzbyxgs_kbxx": true,
  95. "zj_zssssxggzyjyw_gcjs_kbjggs": true,
  96. "gd_szszfhjsj_kbqkgs": true,
  97. "a_gjggzyjypt_gcjs_kbjl": true,
  98. "a_gjggzyjypt_gcjs_kbjl_new": true,
  99. "zj_tzsyhggzyjyzx_kbjggg": true,
  100. "a_zgzbtbggfwpy_wasjgf_kbjl_lsbl": true,
  101. "ah_czsggzyjyw_jsgc_kbjl": true,
  102. "ah_czsggzyjyw_zfcg_kbxx": true,
  103. "ah_whsggzyjyfww_kbxx_cgxm": true,
  104. "ah_whsggzyjyfww_kbxx_gcxm": true,
  105. }
  106. )
  107. //启动测试抽取-、、、、结果追踪
  108. func StartExtractTestTask(taskId, startId, num, resultcoll, trackcoll string) bool {
  109. defer qu.Catch()
  110. ext := TaskList[taskId]
  111. if ext == nil {
  112. ext = &ExtractTask{}
  113. ext.Id = taskId
  114. ext.InitTestTaskInfo(resultcoll, trackcoll)
  115. ext.IsRun = true
  116. ext.TaskInfo.FDB = db.MgoFactory(1, 3, 120, ext.TaskInfo.FromDbAddr, ext.TaskInfo.FromDB)
  117. }
  118. ext.InitSite()
  119. ext.InitRulePres()
  120. ext.InitRuleBacks(false)
  121. ext.InitRuleBacks(true)
  122. ext.InitRuleCore(false)
  123. ext.InitRuleCore(true)
  124. ext.InitPkgCore()
  125. ext.InitBlockRule()
  126. ext.InfoTypeList()
  127. ext.InitTag(false)
  128. ext.InitTag(true)
  129. ext.InitClearFn(false)
  130. ext.InitClearFn(true)
  131. ext.Lock()
  132. //ext.IsExtractCity = false
  133. if ext.IsExtractCity { //版本上控制是否开始城市抽取
  134. //初始化城市DFA信息
  135. ext.InitCityInfo()
  136. //ext.InitCityDFA()
  137. ext.InitAreaCode()
  138. ext.InitPostCode()
  139. }
  140. ext.Unlock()
  141. //质量审核
  142. ext.InitAuditFields()
  143. ext.InitAuditRule()
  144. ext.InitAuditClass()
  145. ext.InitAuditRecogField()
  146. //品牌抽取是否开启
  147. ju.IsBrandGoods, _ = ju.Config["brandgoods"].(bool)
  148. //价格个数抽取是否开启
  149. ju.IsPriceNumber, _ = ju.Config["pricenumber"].(bool)
  150. //附件抽取是否开启
  151. ext.InitFile()
  152. ext.TaskInfo.TestColl = resultcoll
  153. TaskList[taskId] = ext
  154. return RunExtractTestTask(ext, startId, num)
  155. }
  156. func IdTrans(startId string) bson.ObjectId {
  157. defer qu.Catch()
  158. return bson.ObjectIdHex(startId)
  159. }
  160. func StringTOBsonId(id string) primitive.ObjectID {
  161. objectId, _ := primitive.ObjectIDFromHex(id)
  162. return objectId
  163. }
  164. func BsonTOStringId(id interface{}) string {
  165. return id.(primitive.ObjectID).Hex()
  166. }
  167. //开始测试任务抽取
  168. func RunExtractTestTask(ext *ExtractTask, startId, num string) bool {
  169. n, _ := strconv.Atoi(num)
  170. id := IdTrans(startId)
  171. if id.Valid() {
  172. //query := bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(startId)}}
  173. query := bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(startId)}}
  174. list, _ := ext.TaskInfo.FDB.Find(ext.TaskInfo.FromColl, query, nil, Fields, false, 0, n)
  175. for _, v := range *list {
  176. //if qu.ObjToString(v["sensitive"]) != ""||ggtest.MatchString(qu.ObjToString(v[""])) { //去除含敏感词数据
  177. // continue
  178. //}
  179. if spidercode[qu.ObjToString(v["spidercode"])] { //临时开标记录
  180. continue
  181. }
  182. var j, jf *ju.Job
  183. var isSite bool
  184. if ext.IsFileField && (v["projectinfo"] != nil || v["attach_text"] != nil) {
  185. v["isextFile"] = true
  186. j, jf, isSite = ext.PreInfo(v)
  187. } else {//无附件
  188. j, _, isSite = ext.PreInfo(v)
  189. }
  190. go ext.ExtractProcess(j, jf, isSite) //抽取-打分-保存
  191. ext.TaskInfo.ProcessPool <- true
  192. }
  193. return true
  194. } else {
  195. return false
  196. }
  197. }
  198. //启动抽取
  199. func StartExtractTaskId(taskId string) bool {
  200. defer qu.Catch()
  201. isgo := false
  202. ext := TaskList[taskId]
  203. if ext == nil {
  204. ext = &ExtractTask{}
  205. ext.Id = taskId
  206. ext.InitTaskInfo()
  207. isgo = true
  208. } else {
  209. ext.Id = taskId
  210. ext.InitTaskInfo()
  211. }
  212. ext.TaskInfo.FDB = db.MgoFactory(3, 5, 600, ext.TaskInfo.FromDbAddr, ext.TaskInfo.FromDB)
  213. ext.TaskInfo.TDB = db.MgoFactory(3, 5, 600, ext.TaskInfo.ToDbAddr, ext.TaskInfo.ToDB)
  214. ext.InitSite()
  215. ext.InitRulePres()
  216. ext.InitRuleBacks(false)
  217. ext.InitRuleBacks(true)
  218. ext.InitRuleCore(false)
  219. ext.InitRuleCore(true)
  220. ext.InitPkgCore()
  221. ext.InitBlockRule()
  222. ext.InfoTypeList()
  223. ext.InitTag(false)
  224. ext.InitTag(true)
  225. ext.InitClearFn(false)
  226. ext.InitClearFn(true)
  227. ext.Lock()
  228. if ext.IsExtractCity { //版本上控制是否开始城市抽取
  229. //初始化城市DFA信息
  230. //ext.InitCityDFA()
  231. ext.InitCityInfo()
  232. ext.InitAreaCode()
  233. ext.InitPostCode()
  234. }
  235. ext.Unlock()
  236. //质量审核
  237. ext.InitAuditFields()
  238. ext.InitAuditRule()
  239. ext.InitAuditClass()
  240. ext.InitAuditRecogField()
  241. //品牌抽取是否开启
  242. ju.IsBrandGoods, _ = ju.Config["brandgoods"].(bool)
  243. //价格个数抽取是否开启
  244. ju.IsPriceNumber, _ = ju.Config["pricenumber"].(bool)
  245. //附件抽取是否开启
  246. ext.InitFile()
  247. ext.IsRun = true
  248. go ext.ResultSave(true)
  249. go ext.BidSave(true)
  250. if isgo {
  251. go RunExtractTask(taskId)
  252. }
  253. TaskList[taskId] = ext
  254. return true
  255. }
  256. //停止抽取
  257. func StopExtractTaskId(taskId string) bool {
  258. defer qu.Catch()
  259. ext := TaskList[taskId]
  260. if ext != nil {
  261. ext.IsRun = false
  262. TaskList[taskId] = ext
  263. }
  264. //更新task.s_extlastid
  265. db.Mgo.UpdateById("task", taskId, `{"$set":{"s_extlastid":"`+ext.TaskInfo.LastExtId+`"}}`)
  266. return true
  267. }
  268. //开始抽取
  269. func RunExtractTask(taskId string) {
  270. defer qu.Catch()
  271. ext := TaskList[taskId]
  272. query := bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(ext.TaskInfo.LastExtId)}}
  273. count := ext.TaskInfo.FDB.Count(ext.TaskInfo.FromColl, query)
  274. pageNum := (count + PageSize - 1) / PageSize
  275. limit := PageSize
  276. if count < PageSize {
  277. limit = count
  278. }
  279. fmt.Printf("count=%d,pageNum=%d,query=%v", count, pageNum, query)
  280. for i := 0; i < pageNum; i++ {
  281. query = bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(ext.TaskInfo.LastExtId)}}
  282. list, _ := ext.TaskInfo.FDB.Find(ext.TaskInfo.FromColl, query, nil, Fields, false, 0, limit)
  283. fmt.Printf("page=%d,query=%v", i+1, query, len(*list))
  284. for _, v := range *list {
  285. //if qu.ObjToString(v["sensitive"]) != "" { //去除含敏感词数据
  286. // continue
  287. //}
  288. //根据标题判断是否抽取
  289. b := IsExtract("title", qu.ObjToString(v["title"]), "")
  290. if !b {
  291. continue
  292. }
  293. _id := qu.BsonIdToSId(v["_id"])
  294. //log.Debug(_id)
  295. if !ext.IsRun {
  296. break
  297. }
  298. var j, jf *ju.Job
  299. var isSite bool
  300. if ext.IsFileField && (v["projectinfo"] != nil || v["attach_text"] != nil) {
  301. v["isextFile"] = true
  302. j, jf, isSite = ext.PreInfo(v)
  303. } else {
  304. j, _, isSite = ext.PreInfo(v)
  305. }
  306. go ext.ExtractProcess(j, jf, isSite)
  307. ext.TaskInfo.LastExtId = _id
  308. ext.TaskInfo.ProcessPool <- true
  309. }
  310. db.Mgo.UpdateById("task", ext.Id, `{"$set":{"s_extlastid":"`+ext.TaskInfo.LastExtId+`"}}`)
  311. if !ext.IsRun {
  312. break
  313. }
  314. }
  315. //更新task.s_extlastid
  316. time.AfterFunc(1*time.Minute, func() { RunExtractTask(taskId) })
  317. }
  318. //信息预处理-不和版本关联,取最新版本的配置项
  319. func PreInfo(doc map[string]interface{}) (j, jf *ju.Job, isSite bool) {
  320. return (&ExtractTask{}).PreInfo(doc)
  321. }
  322. var clearMoneyReg *regexp.Regexp = regexp.MustCompile("(PPP[\\s]?项目|新城镇建设|国土资源局|基金管理|高速公路|水系生态治理|水生态建设|棚改旧改|棚户区改造|棚改项目|危房改造项目|土地整理|高速公路项目)")
  323. //信息预处理-和版本关联-处理表格-附件-kv标签库-中标候选人
  324. func (e *ExtractTask) PreInfo(doc map[string]interface{}) (j, jf *ju.Job, isSite bool) {
  325. defer qu.Catch()
  326. //判断是否有附件这个字段
  327. var isextFile bool
  328. if doc["isextFile"] != nil {
  329. isextFile = doc["isextFile"].(bool)
  330. }
  331. detail := ""
  332. d1, _ := doc["detail"].(string)
  333. d2, _ := doc["contenthtml"].(string)
  334. if len(d1) >= len(d2) || d2 == "" {
  335. detail = d1
  336. } else {
  337. detail = d2
  338. }
  339. detail = regexp.MustCompile(`<!--[\w\W]*?-->`).ReplaceAllString(detail, "")
  340. d3, _ := doc["summary"].(string)
  341. //全文的需要修复表格
  342. detail = pretreated.RepairCon(detail)
  343. detail = ju.CutLableStr(d3 + "\n" + detail)
  344. detail = cut.ClearHtml(d3 + "\n" + detail)
  345. doc["detail"] = detail
  346. isClearnMoney := !clearMoneyReg.MatchString(detail)
  347. if isClearnMoney {
  348. isClearnMoney = !clearMoneyReg.MatchString(qu.ObjToString(doc["title"]))
  349. }
  350. isClearnMoneystr := qu.ObjToString(qu.If(isClearnMoney, "T", ""))
  351. if isextFile {
  352. file2text(&doc) //附件文本堆一起(后期可以考虑,分开处理),方法里修改了doc["detailfile"]结果
  353. }
  354. //正文小于200个字,有附件把附件内容加到正文
  355. //tmpDeatil := detail
  356. //tmpdocument, err := goquery.NewDocumentFromReader(strings.NewReader(tmpDeatil))
  357. //if err == nil {
  358. // conlen := utf8.RuneCountInString(strings.Trim(tmpdocument.Text(), " "))
  359. // if conlen < 2000 {
  360. // if isextFile {
  361. // detail += qu.ObjToString(doc["detailfile"])
  362. // doc["detail"] = detail
  363. // }
  364. // } else if conlen > qu.IntAllDef(ju.Config["filelength"], 1000000) {
  365. // //防止文本过长,造成抽取阻塞
  366. // log.Debug("文本太长", doc["_id"], conlen)
  367. // doc["detail"] = d3
  368. // }
  369. //}
  370. toptype := qu.ObjToString(doc["toptype"])
  371. subtype := qu.ObjToString(doc["subtype"])
  372. if qu.ObjToString(doc["type"]) == "bid" {
  373. toptype = "结果"
  374. }
  375. if toptype == "" {
  376. toptype = "all"
  377. }
  378. if subtype == "" {
  379. subtype = "all"
  380. }
  381. if subtype == "其他" {
  382. subtype = "其它"
  383. }
  384. toMap := qu.ObjToMap(doc["jsondata"])
  385. //log.Debug("toMap", toMap)
  386. if (*toMap) != nil {
  387. if (*toMap)["extweight"] == nil {
  388. (*toMap)["extweight"] = ju.Config["jsondata_extweight"]
  389. }
  390. if (*toMap)["jsoncontent"] != nil {
  391. delete(*toMap, "jsoncontent")
  392. }
  393. for k, v := range *toMap {
  394. if _, ok := v.(float64); ok {
  395. continue
  396. } else if _, ok := v.(int64); ok {
  397. continue
  398. } else if _, ok2 := v.(string); ok2 {
  399. continue
  400. } else {
  401. delete(*toMap, k)
  402. }
  403. }
  404. }
  405. j = &ju.Job{
  406. SourceMid: qu.BsonIdToSId(doc["_id"]),
  407. Category: toptype,
  408. CategorySecond: subtype,
  409. Content: qu.ObjToString(doc["detail"]),
  410. SpiderCode: qu.ObjToString(doc["spidercode"]),
  411. Site: qu.ObjToString(doc["site"]),
  412. //Domain: qu.ObjToString(doc["domain"]),
  413. //Href: qu.ObjToString(doc["href"]),
  414. Title: qu.ObjToString(doc["title"]),
  415. Data: &doc,
  416. City: qu.ObjToString(doc["city"]),
  417. Province: qu.ObjToString(doc["area"]),
  418. Jsondata: toMap,
  419. Result: map[string][]*ju.ExtField{},
  420. BuyerAddr: qu.ObjToString(doc["buyeraddr"]),
  421. RuleBlock: e.RuleBlock,
  422. Dataging: qu.IntAll(doc["dataging"]),
  423. IsClearnMoney: isClearnMoneystr,
  424. }
  425. if isextFile {
  426. jf = &ju.Job{
  427. SourceMid: qu.BsonIdToSId(doc["_id"]),
  428. Category: toptype,
  429. CategorySecond: subtype,
  430. Content: qu.ObjToString(doc["detailfile"]),
  431. SpiderCode: qu.ObjToString(doc["spidercode"]),
  432. Site: qu.ObjToString(doc["site"]),
  433. Title: qu.ObjToString(doc["title"]),
  434. Data: &doc,
  435. City: qu.ObjToString(doc["city"]),
  436. Province: qu.ObjToString(doc["area"]),
  437. Jsondata: toMap,
  438. Result: map[string][]*ju.ExtField{},
  439. BuyerAddr: qu.ObjToString(doc["buyeraddr"]),
  440. RuleBlock: e.RuleBlock,
  441. IsFile: isextFile,
  442. Dataging: qu.IntAll(doc["dataging"]),
  443. IsClearnMoney: isClearnMoneystr,
  444. }
  445. }
  446. codeSite := j.SpiderCode
  447. //是否启用站点
  448. if value, ok := e.SiteMerge.Load(codeSite); ok {
  449. isSite = value.(bool)
  450. }
  451. if isSite {
  452. //是否配置站点
  453. exp, isSite := e.Luacodes.Load(codeSite)
  454. if isSite {
  455. if exp.(map[string]interface{})["e.SiteClearFn"] != nil {
  456. e.SiteClearFn = exp.(map[string]interface{})["e.SiteClearFn"].(map[string][]string)
  457. }
  458. if exp.(map[string]interface{})["e.SiteTag"] != nil {
  459. e.SiteTag = exp.(map[string]interface{})["e.SiteTag"].(map[string][]*Tag)
  460. }
  461. if exp.(map[string]interface{})["e.SiteRuleCores"] != nil {
  462. e.SiteRuleCores = exp.(map[string]interface{})["e.SiteRuleCores"].(map[string]map[string][]*RuleCore)
  463. }
  464. if exp.(map[string]interface{})["e.SiteRuleBacks"] != nil {
  465. e.SiteRuleBacks = exp.(map[string]interface{})["e.SiteRuleBacks"].([]*RegLuaInfo)
  466. }
  467. }
  468. }
  469. qu.Try(func() {
  470. pretreated.AnalyStart(j, isSite, codeSite) //job.Block分块
  471. if isextFile && strings.TrimSpace(jf.Content) != "" {
  472. pretreated.AnalyStart(jf, isSite, codeSite)
  473. }
  474. }, func(err interface{}) {
  475. log.Debug("pretreated.AnalyStart", err, j.SourceMid)
  476. })
  477. return j, jf, isSite
  478. }
  479. var sortStrReg *regexp.Regexp = regexp.MustCompile("(招标|采购|需求|投标|[竞询议]报价|公示|单一来源|询价|成交|中标)")
  480. var clearStrReg *regexp.Regexp = regexp.MustCompile("((设计|施工|招标)图|业绩|图纸)")
  481. //遍历附件字段内容,拼接在一起;附件文本堆一起(后期可以考虑,分开处理),方法里修改了doc["detailfile"]结果
  482. func file2text(doc *map[string]interface{}) {
  483. mnameone := map[string]bool{}
  484. mname := map[string]bool{}
  485. murl := map[string]string{}
  486. //if attach_text, ok := (*doc)["new_attach_text"].(map[string]interface{}); ok {
  487. if attach_text, ok := (*doc)["attach_text"].(map[string]interface{}); ok {
  488. for _, attachs := range attach_text {
  489. if fileinfos, ok := attachs.(map[string]interface{}); ok {
  490. for _, fileinfo := range fileinfos {
  491. if ff, ok := fileinfo.(map[string]interface{}); ok {
  492. attach_url := qu.ObjToString(ff["attach_url"])
  493. ffname := qu.ObjToString(ff["file_name"])
  494. if clearStrReg.MatchString(ffname) {
  495. continue
  496. }
  497. mname[ffname] = true
  498. murl[ffname] = attach_url
  499. if sortStrReg.MatchString(ffname) {
  500. mnameone[ffname] = true
  501. }
  502. }
  503. }
  504. }
  505. }
  506. }
  507. tmpstr := ""
  508. for k := range mnameone {
  509. if utf8.RuneCountInString(tmpstr) > qu.IntAllDef(ju.Config["filelength"], 150000) {
  510. (*doc)["detailfile"] = tmpstr
  511. return
  512. }
  513. bs := ju.OssGetObject(murl[k])
  514. if utf8.RuneCountInString(bs) < qu.IntAllDef(ju.Config["filelength"], 150000) {
  515. tmpstr += bs + "\n"
  516. }
  517. }
  518. for k := range mname {
  519. if utf8.RuneCountInString(tmpstr) > qu.IntAllDef(ju.Config["filelength"], 150000) {
  520. (*doc)["detailfile"] = tmpstr
  521. return
  522. }
  523. bs := ju.OssGetObject(murl[k])
  524. if utf8.RuneCountInString(bs) < qu.IntAllDef(ju.Config["filelength"], 150000) {
  525. tmpstr += bs + "\n"
  526. }
  527. }
  528. (*doc)["detailfile"] = strings.ReplaceAll(tmpstr, "附件", "")
  529. }
  530. //抽取-正文
  531. func (e *ExtractTask) ExtractProcess(j, jf *ju.Job, isSite bool) {
  532. e.ExtractDetail(j, isSite, j.SpiderCode) //正文抽取属性
  533. if jf != nil && jf.IsFile { //附件jf → j 合并
  534. e.ExtractDetail(jf, isSite, j.SpiderCode)
  535. for tmpk, xs := range jf.Result {
  536. if len(j.Result[tmpk]) == 0 {
  537. if tmpk == "budget" || tmpk == "bidamount" {
  538. for _, v := range xs {
  539. if fv, ok := v.Value.(float64); ok && fv > 100 && fv < 50000000000 {
  540. j.Result[tmpk] = append(j.Result[tmpk], v)
  541. }
  542. }
  543. } else {
  544. j.Result[tmpk] = append(j.Result[tmpk], jf.Result[tmpk]...)
  545. }
  546. }else {
  547. if tmpk=="winner" && len(j.Result[tmpk]) == 1 {
  548. if j.Result[tmpk][0].Value == "" {
  549. j.Result[tmpk] = append(j.Result[tmpk], jf.Result[tmpk]...)
  550. }
  551. }
  552. //if tmpk=="buyer" { //附件数据-没有正文靠谱
  553. // j.Result[tmpk] = append(j.Result[tmpk], jf.Result[tmpk]...)
  554. //}
  555. }
  556. }
  557. if len(j.Winnerorder) == 0 && jf.Winnerorder != nil && len(jf.Winnerorder) > 0 {
  558. j.Winnerorder = append(j.Winnerorder, jf.Winnerorder...)
  559. }
  560. if len(j.PackageInfo) == 0 && jf.PackageInfo != nil && len(jf.PackageInfo) > 0 {
  561. j.PackageInfo = jf.PackageInfo
  562. }
  563. }
  564. if isSite {
  565. ismerge, ok := e.SiteMerge.Load(j.SpiderCode)
  566. if ok && ismerge.(bool) {
  567. tmpj := &ju.Job{
  568. SourceMid: j.SourceMid,
  569. Category: j.Category,
  570. CategorySecond: j.CategorySecond,
  571. Content: j.Content,
  572. SpiderCode: j.SpiderCode,
  573. //Domain: qu.ObjToString(doc["domain"]),
  574. //Href: qu.ObjToString(doc["href"]),
  575. Title: j.Title,
  576. Data: j.Data,
  577. City: j.City,
  578. Province: j.Province,
  579. Jsondata: j.Jsondata,
  580. Result: map[string][]*ju.ExtField{},
  581. BuyerAddr: j.BuyerAddr,
  582. RuleBlock: e.RuleBlock,
  583. }
  584. qu.Try(func() {
  585. pretreated.AnalyStart(tmpj, false, "") //job.Block分块
  586. }, func(err interface{}) {
  587. log.Debug("pretreated.AnalyStart.ExtractProcess", err, j.SourceMid)
  588. })
  589. e.ExtractDetail(tmpj, false, "")
  590. //if jf != nil && jf.IsFile {
  591. // e.ExtractFile(jf, false, "")
  592. //}
  593. //合并数据
  594. j.Block = append(j.Block, tmpj.Block...)
  595. j.Winnerorder = append(j.Winnerorder, tmpj.Winnerorder...)
  596. for tmpk, _ := range j.Result {
  597. if len(tmpj.Result[tmpk]) > 0 {
  598. j.Result[tmpk] = append(j.Result[tmpk], tmpj.Result[tmpk]...)
  599. }
  600. }
  601. for tmpk, _ := range tmpj.Result {
  602. if len(j.Result[tmpk]) == 0 {
  603. j.Result[tmpk] = append(j.Result[tmpk], tmpj.Result[tmpk]...)
  604. }
  605. }
  606. }
  607. }
  608. //分析抽取结果并保存
  609. AnalysisSaveResult(j, jf, e)
  610. <-e.TaskInfo.ProcessPool
  611. }
  612. //抽取-正文-规则等 detail
  613. func (e *ExtractTask) ExtractDetail(j *ju.Job, isSite bool, codeSite string) {
  614. qu.Try(func() {
  615. doc := *j.Data
  616. //全局前置规则,结果覆盖doc属性
  617. //for _, v := range e.RulePres {
  618. // doc = ExtRegPre(doc, j, v, e.TaskInfo)
  619. //}
  620. tmprules := map[string][]*RuleCore{}
  621. lockrule.Lock()
  622. //加载分类抽取配置
  623. if j.Category == "all" || j.CategorySecond == "all" {
  624. if isSite {
  625. for k, vc1 := range e.SiteRuleCores["all_all"] {
  626. tmprules[k] = vc1
  627. }
  628. } else {
  629. for k, vc1 := range e.RuleCores["all_all"] {
  630. tmprules[k] = vc1
  631. }
  632. }
  633. } else {
  634. if isSite {
  635. for k, vc1 := range e.SiteRuleCores[j.Category+"_"+j.CategorySecond] {
  636. tmprules[k] = vc1
  637. }
  638. } else {
  639. for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
  640. tmprules[k] = vc1
  641. }
  642. }
  643. }
  644. if len(tmprules) < 1 { //分类未覆盖部分
  645. if isSite {
  646. for k, vc1 := range e.RuleCores["all_all"] {
  647. tmprules[k] = vc1
  648. }
  649. } else {
  650. for k, vc1 := range e.SiteRuleCores["all_all"] {
  651. tmprules[k] = vc1
  652. }
  653. }
  654. }
  655. lockrule.Unlock()
  656. //抽取规则
  657. for _, vc1 := range tmprules {
  658. for _, vc := range vc1 {
  659. tmp := ju.DeepCopy(doc).(map[string]interface{})
  660. //是否进入逻辑
  661. if !ju.Logic(vc.LuaLogic, tmp) {
  662. continue
  663. }
  664. if vc.Field =="buyer" {
  665. //log.Debug("调试抽取字段")
  666. }
  667. ////抽取-前置规则
  668. //for _, v := range vc.RulePres {
  669. // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
  670. //}
  671. // log.Debug("抽取-前置规则", tmp)
  672. //抽取-规则
  673. ExtRuleCore(tmp, e, vc, j, isSite)
  674. // log.Debug("抽取-规则", tmp)
  675. //抽取-后置规则
  676. for _, v := range vc.RuleBacks {
  677. ExtRegBack(j, v, e.TaskInfo, vc)
  678. }
  679. //kv规则
  680. for _, v := range vc.KVRuleCores {
  681. ExtRuleKV(j, v, e.TaskInfo)
  682. }
  683. // log.Debug("抽取-后置规则", tmp)
  684. //项目名称未能抽取到,标题来凑
  685. if vc.Field == "projectname" {
  686. if vc.ExtFrom == "title" {
  687. isextitle := true
  688. for _, v := range j.Result[vc.Field] {
  689. if len([]rune(qu.ObjToString(v.Value))) > 5 {
  690. isextitle = false
  691. break
  692. }
  693. }
  694. if isextitle { //标题加入选举
  695. field := &ju.ExtField{Field: vc.Field, Code: vc.Id + "_title", RuleText: "title", Type: "title", MatchType: "title", ExtFrom: vc.ExtFrom, SourceValue: j.Title, Value: j.Title}
  696. if isSite {
  697. field.Score = 1
  698. }
  699. j.Result[vc.Field] = append(j.Result[vc.Field], field)
  700. }
  701. }
  702. for i := 0; i < 3; i++ {
  703. for _, v := range vc.RuleBacks {
  704. ExtRegBack(j, v, e.TaskInfo, vc)
  705. }
  706. }
  707. }
  708. }
  709. }
  710. //全局后置规则
  711. if isSite {
  712. for _, v := range e.SiteRuleBacks {
  713. ExtRegBack(j, v, e.TaskInfo, nil)
  714. }
  715. } else {
  716. for _, v := range e.RuleBacks {
  717. ExtRegBack(j, v, e.TaskInfo, nil)
  718. }
  719. }
  720. //函数清理
  721. for key, val := range j.Result {
  722. for i, v := range val {
  723. if v.Field == "projectname" && v.Type == "table" {
  724. break
  725. }
  726. if key == "budget" || key == "bidamount" {
  727. if _, ok := v.Value.(float64); ok && !v.IsTrue {
  728. continue
  729. }
  730. }
  731. lockclear.Lock()
  732. var cfn = []string{}
  733. if isSite {
  734. cfn = e.SiteClearFn[key]
  735. if len(cfn) == 0 {
  736. cfn = e.ClearFn[key]
  737. }
  738. } else {
  739. cfn = e.ClearFn[key]
  740. }
  741. lockclear.Unlock()
  742. if len(cfn) == 0 {
  743. continue
  744. }
  745. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content}, j.SpiderCode, j.IsClearnMoney)
  746. if key == "budget" || key == "bidamount" {
  747. if istrue, ok := data[len(data)-1].(bool); istrue && ok {
  748. j.Result[key][i].IsTrue = true
  749. } else {
  750. j.Result[key][i].Value = data[0]
  751. continue
  752. }
  753. }
  754. before, _ := v.Value.(string)
  755. v.Value = data[0]
  756. BeforeAddClearFnLog(strings.Join(cfn, ","), "函数清理"+strings.Join(cfn, ","), j.SourceMid, before, v.MatchType, v, e)
  757. //添加行数清理的日志
  758. //清理特殊符号
  759. lockclear.Lock()
  760. if clear.AsyField[key] != nil || clear.SymField[key] != nil || clear.MesField[key] != nil {
  761. text := qu.ObjToString(v.Value)
  762. before = text
  763. //指定清理--新增-函数清理-其他清理
  764. if key=="winner"||key=="agency"||key=="buyer" {
  765. text = strings.ReplaceAll(text,"【","")
  766. text = strings.ReplaceAll(text,"】","")
  767. }
  768. v.Value = clear.OtherClean(key, text)
  769. BeforeAddClearFnLog("clear.OtherClean", "特殊符号清理clear.OtherClean", j.SourceMid, before, v.MatchType, v, e)
  770. }
  771. //AddClearFnLog("clearfn", j.SourceMid, v.Value, extinfo, v.Code, "函数清理", key, e.TaskInfo)
  772. lockclear.Unlock()
  773. }
  774. }
  775. PackageDetail(j, e, isSite, codeSite) //处理分包信息-去重
  776. // bs, _ := json.Marshal(j.Result)
  777. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  778. }, func(err interface{}) {
  779. log.Debug("ExtractProcess err", err, j.SourceMid)
  780. })
  781. }
  782. func (e *ExtractTask) ExtractFile(j *ju.Job, isSite bool, codeSite string) {
  783. qu.Try(func() {
  784. doc := *j.Data
  785. //全局前置规则,结果覆盖doc属性
  786. // for _, v := range e.RulePres {
  787. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  788. // doc = ExtRegPre(doc, j, v, e.TaskInfo)
  789. // }
  790. // }
  791. //抽取规则
  792. tmprules := map[string][]*RuleCore{}
  793. lockrule.Lock()
  794. if j.Category == "all" || j.CategorySecond == "all" {
  795. for k, vc1 := range e.RuleCores["all_all"] {
  796. tmprules[k] = vc1
  797. }
  798. } else {
  799. for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
  800. tmprules[k] = vc1
  801. }
  802. }
  803. lockrule.Unlock()
  804. for _, vc1 := range tmprules {
  805. for _, vc := range vc1 {
  806. tmp := ju.DeepCopy(doc).(map[string]interface{})
  807. //是否进入逻辑
  808. if !ju.Logic(vc.LuaLogic, tmp) {
  809. continue
  810. }
  811. //抽取-前置规则
  812. // for _, v := range vc.RulePres {
  813. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  814. // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
  815. // }
  816. // }
  817. // log.Debug("抽取-前置规则", tmp)
  818. //抽取-规则
  819. if value, ok := e.FileFields.Load(vc.Field); ok && qu.IntAllDef(value, 1) > 0 {
  820. ExtRuleCore(tmp, e, vc, j, isSite)
  821. }
  822. // log.Debug("抽取-规则", tmp)
  823. //抽取-后置规则
  824. for _, v := range vc.RuleBacks {
  825. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  826. ExtRegBack(j, v, e.TaskInfo, vc)
  827. }
  828. }
  829. // log.Debug("抽取-后置规则", tmp)
  830. }
  831. }
  832. //全局后置规则
  833. for _, v := range e.RuleBacks {
  834. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  835. ExtRegBack(j, v, e.TaskInfo, nil)
  836. }
  837. }
  838. //函数清理
  839. for key, val := range j.Result {
  840. for _, v := range val {
  841. lockclear.Lock()
  842. var cfn = []string{}
  843. if isSite {
  844. cfn = e.SiteClearFn[key]
  845. if len(cfn) == 0 {
  846. cfn = e.ClearFn[key]
  847. }
  848. } else {
  849. cfn = e.ClearFn[key]
  850. }
  851. lockclear.Unlock()
  852. if len(cfn) == 0 {
  853. continue
  854. }
  855. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content}, j.SpiderCode, j.IsClearnMoney)
  856. v.Value = data[0]
  857. //清理特殊符号
  858. lockclear.Lock()
  859. if clear.AsyField[key] != nil || clear.SymField[key] != nil ||
  860. clear.MesField[key] != nil {
  861. text := qu.ObjToString(v.Value)
  862. text = clear.OtherClean(key, text)
  863. v.Value = text
  864. }
  865. lockclear.Unlock()
  866. }
  867. }
  868. PackageDetail(j, e, isSite, codeSite) //处理分包信息
  869. // bs, _ := json.Marshal(j.Result)
  870. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  871. }, func(err interface{}) {
  872. log.Debug("ExtractProcess err", err)
  873. })
  874. }
  875. //前置过滤
  876. func ExtRegPre(doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, t *TaskInfo) map[string]interface{} {
  877. defer qu.Catch()
  878. before := ju.DeepCopy(doc).(map[string]interface{})
  879. extinfo := map[string]interface{}{}
  880. if in.IsLua {
  881. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  882. if j != nil {
  883. lua.Block = j.Block
  884. }
  885. extinfo = lua.RunScript("pre")
  886. for k, v := range extinfo { //结果覆盖原doc
  887. doc[k] = v
  888. }
  889. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  890. } else {
  891. var key string
  892. if !j.IsFile {
  893. key = qu.If(in.Field == "", "detail", in.Field).(string)
  894. } else {
  895. key = qu.If(in.Field == "", "detailfile", in.Field).(string)
  896. }
  897. text := qu.ObjToString(doc[key])
  898. extinfo[key] = in.RegPreBac.Reg.ReplaceAllString(text, "")
  899. doc[key] = extinfo[key] //结果覆盖原doc
  900. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  901. }
  902. return doc
  903. }
  904. //抽取-规则
  905. func ExtRuleCore(doc map[string]interface{}, e *ExtractTask, vc *RuleCore, j *ju.Job, isSite bool) {
  906. //候选人加入
  907. var kvMap map[string][]map[string]interface{}
  908. extByReg := true
  909. if vc.ExtFrom != "title" {
  910. kvMap, extByReg = getKvByLuaFields(vc, j, e)
  911. }
  912. for _, v := range vc.RuleCores {
  913. if v.IsLua {
  914. ExtRuleCoreByKv(vc.ExtFrom, doc, j, v, &kvMap, e)
  915. } else if extByReg {
  916. ExtRuleCoreByReg(vc.ExtFrom, doc, j, v, e, isSite)
  917. }
  918. }
  919. //如果只有一个分包,预算没有抽取到,把分包中的预算保存到外面
  920. if vc.Field == "budget" && len(kvMap) == 0 {
  921. if len(j.BlockPackage) == 1 {
  922. for _, bp := range j.BlockPackage {
  923. for fieldname, field := range vc.LFields {
  924. if field != vc.Field {
  925. continue
  926. }
  927. tp := ""
  928. for k, v := range []*ju.JobKv{bp.ColonKV, bp.SpaceKV, bp.TableKV} {
  929. if k == 0 {
  930. tp = "colon"
  931. } else if k == 1 {
  932. tp = "space"
  933. } else if k == 2 {
  934. tp = "table"
  935. }
  936. if v == nil || v.KvTags == nil {
  937. continue
  938. }
  939. for _, vv := range v.KvTags[fieldname] {
  940. text := ju.TrimLRSpace(vv.Value, "")
  941. if text != "" {
  942. tmp := &ju.ExtField{
  943. ExtFrom: "package",
  944. Field: vc.Field,
  945. Code: "CL_分包",
  946. Type: tp,
  947. MatchType: "package",
  948. RuleText: bp.Text,
  949. SourceValue: vv.Key,
  950. Value: text,
  951. }
  952. if isSite {
  953. tmp.Score = 1
  954. }
  955. j.Result[vc.Field] = append(j.Result[vc.Field], tmp)
  956. }
  957. }
  958. }
  959. }
  960. break
  961. }
  962. }
  963. } else {
  964. for k, v := range kvMap {
  965. if j.Result[k] == nil {
  966. j.Result[k] = [](*ju.ExtField){}
  967. }
  968. for _, tmp := range v {
  969. field := &ju.ExtField{Weight: qu.IntAll(tmp["weight"]),
  970. ExtFrom: qu.ObjToString(tmp["extfrom"]), Field: k,
  971. Code: qu.ObjToString(tmp["code"]), Type: qu.ObjToString(tmp["type"]),
  972. MatchType: qu.ObjToString(tmp["matchtype"]),
  973. RuleText: qu.ObjToString(tmp["ruletext"]),
  974. SourceValue: tmp["sourcevalue"],
  975. Value: tmp["value"]}
  976. if k == "bidamount" && field.ExtFrom == "第一候选人" {
  977. field.Score = 1
  978. }
  979. if isSite {
  980. field.Score = 1
  981. }
  982. if (field.Field == "bidamount" || field.Field == "budget") && field.Type == "table" {
  983. moneys := clear.ObjToMoney([]interface{}{field.Value, ""}, j.SpiderCode, j.IsClearnMoney)
  984. if len(moneys) > 0 {
  985. if vf, ok := moneys[0].(float64); ok {
  986. field.Value = vf
  987. field.IsTrue = moneys[len(moneys)-1].(bool)
  988. } else if vi, ok := moneys[0].(int); ok {
  989. field.Value = float64(vi)
  990. field.IsTrue = moneys[len(moneys)-1].(bool)
  991. }
  992. }
  993. }
  994. if tmp["blocktag"] != nil {
  995. btag := make(map[string]string)
  996. for k := range tmp["blocktag"].(map[string]bool) {
  997. blocktag.Lock()
  998. if TagConfigDesc[k] != "" {
  999. btag[k] = TagConfigDesc[k]
  1000. }
  1001. blocktag.Unlock()
  1002. }
  1003. field.BlockTag = btag
  1004. }
  1005. j.Result[k] = append(j.Result[k], field)
  1006. }
  1007. }
  1008. }
  1009. }
  1010. //抽取-规则-kv
  1011. func ExtRuleCoreByKv(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, kvMap *map[string][]map[string]interface{}, et *ExtractTask) {
  1012. defer qu.Catch()
  1013. if extfrom == "title" || !in.IsLua {
  1014. return
  1015. }
  1016. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  1017. lua.KvMap = *kvMap
  1018. lua.Block = j.Block
  1019. extinfo := lua.RunScript("core")
  1020. if tmps, ok := extinfo[in.Field].([]map[string]interface{}); ok {
  1021. for _, v := range tmps {
  1022. v["core"] = in.Code
  1023. }
  1024. (*kvMap)[in.Field] = append((*kvMap)[in.Field], tmps...)
  1025. }
  1026. if len(extinfo) > 0 {
  1027. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1028. }
  1029. }
  1030. //抽取-规则-正则
  1031. func ExtRuleCoreByReg(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, et *ExtractTask, isSite bool) {
  1032. defer qu.Catch()
  1033. //根据field配置项目,是否抽取。例如:废标、流标等跳过,
  1034. b := IsExtract(in.Field, j.Title, j.Content)
  1035. if !b {
  1036. return
  1037. }
  1038. //全文正则
  1039. //text := qu.ObjToString(doc[extfrom])
  1040. //if in.Field != "" {
  1041. // extinfo := extRegCoreToResult(extfrom, text, j, in)
  1042. // if len(extinfo) > 0 {
  1043. // AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1044. // }
  1045. //}
  1046. //块抽取
  1047. if in.Field != "" {
  1048. if extfrom == "title" {
  1049. extinfo := extRegCoreToResult(extfrom, qu.ObjToString(doc[extfrom]), &map[string]string{}, j, in, isSite)
  1050. if len(extinfo) > 0 {
  1051. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1052. }
  1053. } else if in.Field == "qualifies" {
  1054. extinfo := extRegCoreToResult(extfrom, pretreated.HtmlToText(qu.ObjToString(doc[extfrom])), &map[string]string{}, j, in, isSite)
  1055. if len(extinfo) > 0 {
  1056. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1057. }
  1058. } else {
  1059. for _, v := range j.Block {
  1060. btag := make(map[string]string)
  1061. for k := range v.Classify {
  1062. blocktag.Lock()
  1063. btag[k] = TagConfigDesc[k]
  1064. blocktag.Unlock()
  1065. }
  1066. extinfo := extRegCoreToResult(extfrom, v.Text, &btag, j, in, isSite)
  1067. if len(extinfo) > 0 {
  1068. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1069. }
  1070. }
  1071. }
  1072. }
  1073. }
  1074. //pkg抽取-规则-正则
  1075. func ExtRuleCoreByPkgReg(j *ju.Job, in *RegLuaInfo, e *ExtractTask) {
  1076. defer qu.Catch()
  1077. //根据field配置项目,是否抽取。例如:废标、流标等跳过,
  1078. b := IsExtract(in.Field, j.Title, j.Content)
  1079. if !b {
  1080. return
  1081. }
  1082. //块抽取
  1083. if in.Field != "" {
  1084. for k, vbpkg := range j.BlockPackage {
  1085. rep := map[string]string{}
  1086. if in.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
  1087. if in.Field == "budget" && vbpkg.Budget > 0 {
  1088. continue
  1089. }
  1090. if in.Field == "agencyfee" && vbpkg.Agencyfee > 0 {
  1091. continue
  1092. }
  1093. if in.Field == "bidamount" && vbpkg.Bidamount > 0 {
  1094. continue
  1095. }
  1096. if in.Field == "winner" && vbpkg.Winner != "" {
  1097. continue
  1098. }
  1099. if in.Field == "bidstatus" && vbpkg.BidStatus != "" {
  1100. continue
  1101. }
  1102. if in.Field == "projectname" && vbpkg.Name != "" {
  1103. continue
  1104. }
  1105. if in.Field == "winner" && vbpkg.Winner != "" {
  1106. continue
  1107. }
  1108. if in.Field == "winnerperson" {
  1109. if vbpkg.Winner == "" || len(vbpkg.Winner) < 4 {
  1110. continue
  1111. }
  1112. if !strings.Contains(vbpkg.Text, vbpkg.Winner) {
  1113. continue
  1114. }
  1115. }
  1116. if in.Field == "winnertel" {
  1117. if vbpkg.WinnerPerson == "" {
  1118. continue
  1119. }
  1120. }
  1121. //处理正负数修正
  1122. ptmp := strings.Split(in.RuleText, "#")
  1123. sign := 0
  1124. if len(ptmp) == 2 {
  1125. if ptmp[1] == "正" {
  1126. sign = 1
  1127. } else if ptmp[1] == "负" {
  1128. sign = -1
  1129. }
  1130. }
  1131. tmp := strings.Split(ptmp[0], "__")
  1132. if len(tmp) == 2 {
  1133. epos := strings.Split(tmp[1], ",")
  1134. posm := map[string]int{}
  1135. for _, v := range epos {
  1136. ks := strings.Split(v, ":")
  1137. if len(ks) == 2 { //(.*)招标公告(.*)__2:projectname,4:area
  1138. posm[ks[1]] = qu.IntAll(ks[0])
  1139. } else {
  1140. posm[in.Field] = qu.IntAll(ks[0])
  1141. }
  1142. }
  1143. var pattern string
  1144. if strings.Contains(tmp[0], "\\u") {
  1145. tmp[0] = strings.Replace(tmp[0], "\\", "\\\\", -1)
  1146. tmp[0] = strings.Replace(tmp[0], "\\\\u", "\\u", -1)
  1147. pattern, _ = strconv.Unquote(`"` + tmp[0] + `"`)
  1148. } else {
  1149. pattern = tmp[0]
  1150. }
  1151. //log.Debug("pattern", pattern)
  1152. //fmt.Println(text)
  1153. reg := regexp.MustCompile(pattern)
  1154. apos := reg.FindAllStringSubmatchIndex(vbpkg.Text, -1)
  1155. for i, _ := range apos {
  1156. pos := apos[i]
  1157. for k, p := range posm {
  1158. if len(pos) > p {
  1159. if pos[p] == -1 || pos[p+1] == -1 {
  1160. continue
  1161. }
  1162. val := vbpkg.Text[pos[p]:pos[p+1]]
  1163. if string(val) == "" {
  1164. continue
  1165. }
  1166. if sign == -1 {
  1167. rep[k+"_"+fmt.Sprint(i)] = "-" + val
  1168. } else {
  1169. rep[k+"_"+fmt.Sprint(i)] = val
  1170. }
  1171. }
  1172. }
  1173. }
  1174. //fmt.Println(text)
  1175. for i := 0; i < len(apos); i++ {
  1176. if strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]) != "" {
  1177. if in.Field == "budget" && vbpkg.Budget <= 0 {
  1178. lock.Lock()
  1179. cfn := e.ClearFn[in.Field]
  1180. lock.Unlock()
  1181. data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content}, j.SpiderCode, j.IsClearnMoney)
  1182. if data[len(data)-1].(bool) {
  1183. j.BlockPackage[k].Budget = qu.Float64All(data[0])
  1184. j.BlockPackage[k].IsTrueBudget = true
  1185. }
  1186. break
  1187. } else if in.Field == "agencyfee" && vbpkg.Agencyfee <= 0 {
  1188. lock.Lock()
  1189. cfn := e.ClearFn[in.Field]
  1190. lock.Unlock()
  1191. data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content}, j.SpiderCode, j.IsClearnMoney)
  1192. if data[len(data)-1].(bool) {
  1193. j.BlockPackage[k].Agencyfee = qu.Float64All(data[0])
  1194. j.BlockPackage[k].IsTrueAgencyfee = true
  1195. }
  1196. break
  1197. }else if in.Field == "bidamount" && vbpkg.Bidamount <= 0 {
  1198. lock.Lock()
  1199. cfn := e.ClearFn[in.Field]
  1200. lock.Unlock()
  1201. data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content}, j.SpiderCode, j.IsClearnMoney)
  1202. if data[len(data)-1].(bool) {
  1203. j.BlockPackage[k].Bidamount = qu.Float64All(data[0])
  1204. j.BlockPackage[k].IsTrueBidamount = true
  1205. }
  1206. break
  1207. } else if in.Field == "winner" {
  1208. if j.BlockPackage[k].Winner == "" {
  1209. j.BlockPackage[k].Winner = rep[in.Field+"_"+fmt.Sprint(i)]
  1210. break
  1211. }
  1212. } else if in.Field == "winnertel" {
  1213. if j.BlockPackage[k].WinnerTel == "" {
  1214. j.BlockPackage[k].WinnerTel = rep[in.Field+"_"+fmt.Sprint(i)]
  1215. break
  1216. }
  1217. } else if in.Field == "winnerperson" {
  1218. if j.BlockPackage[k].WinnerPerson == "" {
  1219. j.BlockPackage[k].WinnerPerson = rep[in.Field+"_"+fmt.Sprint(i)]
  1220. break
  1221. }
  1222. } else if in.Field == "bidstatus" {
  1223. if j.BlockPackage[k].BidStatus == "" {
  1224. j.BlockPackage[k].BidStatus = rep[in.Field+"_"+fmt.Sprint(i)]
  1225. break
  1226. }
  1227. } else if in.Field == "projectname" {
  1228. if j.BlockPackage[k].Name == "" {
  1229. j.BlockPackage[k].Name = rep[in.Field+"_"+fmt.Sprint(i)]
  1230. break
  1231. }
  1232. } else if in.Field == "winnerperson" {
  1233. if j.BlockPackage[k].WinnerPerson == "" {
  1234. j.BlockPackage[k].WinnerPerson = rep[in.Field+"_"+fmt.Sprint(i)]
  1235. break
  1236. }
  1237. } else if in.Field == "winnertel" {
  1238. if j.BlockPackage[k].WinnerTel == "" && j.BlockPackage[k].Winner != "" && j.BlockPackage[k].WinnerPerson != "" {
  1239. j.BlockPackage[k].WinnerTel = rep[in.Field+"_"+fmt.Sprint(i)]
  1240. break
  1241. }
  1242. }
  1243. }
  1244. }
  1245. }
  1246. } else {
  1247. pos := in.RegCore.Reg.FindStringIndex(vbpkg.Text)
  1248. val := ""
  1249. if len(pos) == 2 {
  1250. //"text" = "text"[pos[1]:]
  1251. val = "text"[pos[1]:]
  1252. rs := regexp.MustCompile("[^\r\n\t]+")
  1253. tmp := rs.FindAllString("text", -1)
  1254. if len(tmp) > 0 {
  1255. val = tmp[0]
  1256. }
  1257. }
  1258. if val != "" {
  1259. if in.Field == "budget" && vbpkg.Budget <= 0 {
  1260. lock.Lock()
  1261. cfn := e.ClearFn[in.Field]
  1262. lock.Unlock()
  1263. data := clear.DoClearFn(cfn, []interface{}{val, j.Content}, j.SpiderCode, j.IsClearnMoney)
  1264. if data[len(data)-1].(bool) {
  1265. j.BlockPackage[k].Budget = qu.Float64All(data[0])
  1266. j.BlockPackage[k].IsTrueBudget = true
  1267. }
  1268. break
  1269. }
  1270. if in.Field == "bidamount" && vbpkg.Bidamount <= 0 {
  1271. lock.Lock()
  1272. cfn := e.ClearFn[in.Field]
  1273. lock.Unlock()
  1274. data := clear.DoClearFn(cfn, []interface{}{val, j.Content}, j.SpiderCode, j.IsClearnMoney)
  1275. if data[len(data)-1].(bool) {
  1276. j.BlockPackage[k].Bidamount = qu.Float64All(data[0])
  1277. j.BlockPackage[k].IsTrueBidamount = true
  1278. }
  1279. break
  1280. } else if in.Field == "bidstatus" {
  1281. if j.BlockPackage[k].BidStatus == "" {
  1282. j.BlockPackage[k].BidStatus = val
  1283. break
  1284. }
  1285. } else if in.Field == "projectname" {
  1286. if j.BlockPackage[k].Name == "" {
  1287. j.BlockPackage[k].Name = val
  1288. break
  1289. }
  1290. }
  1291. }
  1292. }
  1293. }
  1294. }
  1295. }
  1296. //lua脚本根据属性设置提取kv值
  1297. func getKvByLuaFields(vc *RuleCore, j *ju.Job, et *ExtractTask) (map[string][]map[string]interface{}, bool) {
  1298. kvmap := map[string][]map[string]interface{}{}
  1299. if len(j.Winnerorder) > 1 && qu.Float64All(j.Winnerorder[0]["sort"]) == 1 {
  1300. if vc.Field == "bidamount" {
  1301. for _, v := range j.Winnerorder {
  1302. if v["price"] == nil {
  1303. continue
  1304. }
  1305. kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
  1306. "code": "winnerorder",
  1307. "field": vc.Field,
  1308. "ruletext": "中标候选人_" + fmt.Sprint(v["sortstr"]),
  1309. "extfrom": v["sortstr"],
  1310. "sourcevalue": v["price"],
  1311. "value": v["price"],
  1312. "type": "winnerorder",
  1313. "matchtype": "winnerorder",
  1314. })
  1315. return kvmap, false
  1316. }
  1317. //候选人中标金额
  1318. if price := j.Winnerorder[0]["price"]; price != nil {
  1319. kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
  1320. "code": "CL_中标候选人",
  1321. "field": vc.Field,
  1322. "ruletext": "中标候选人",
  1323. "extfrom": j.Winnerorder[0]["sortstr"],
  1324. "sourcevalue": price,
  1325. "value": price,
  1326. "type": "winnerorder",
  1327. "matchtype": "winnerorder",
  1328. })
  1329. return kvmap, false
  1330. }
  1331. }
  1332. }
  1333. for fieldname, field := range vc.LFields {
  1334. if field != vc.Field {
  1335. continue
  1336. }
  1337. extractFromKv(field, fieldname, j.Block, vc, kvmap, j.Category)
  1338. }
  1339. AddExtLog("extract", j.SourceMid, nil, kvmap, &RegLuaInfo{Field: vc.Field}, et.TaskInfo) //抽取日志
  1340. return kvmap, true
  1341. }
  1342. func extractFromKv(field, fieldname string, blocks []*ju.Block, vc *RuleCore, kvmap map[string][]map[string]interface{}, Category string) {
  1343. //qu.Debug("fieldname+++", fieldname)
  1344. for _, bl := range blocks {
  1345. tp := ""
  1346. if strings.Contains(bl.Title, "保证金") && (field == "bid_bond" || field == "contract_bond") {
  1347. if text := ju.TrimLRSpace(bl.Text, ""); text != "" {
  1348. if Category == "招标" || Category == "拟建" || Category == "预告" {
  1349. kvmap[field] = append(kvmap[field], map[string]interface{}{
  1350. "code": "CL_块内容",
  1351. "field": field,
  1352. "ruletext": "投标保证金",
  1353. "extfrom": "投标保证金_块内容",
  1354. "sourcevalue": bl.Text,
  1355. "value": text,
  1356. "type": "投标保证金_块内容",
  1357. "matchtype": "tag_string",
  1358. "blocktag": bl.Classify,
  1359. "weight": 0,
  1360. })
  1361. } else if Category == "结果" {
  1362. kvmap[field] = append(kvmap[field], map[string]interface{}{
  1363. "code": "CL_",
  1364. "field": field,
  1365. "ruletext": "履约保证金",
  1366. "extfrom": "履约保证金_块内容",
  1367. "sourcevalue": bl.Text,
  1368. "value": text,
  1369. "type": "履约保证金_块内容",
  1370. "matchtype": "tag_string",
  1371. "blocktag": bl.Classify,
  1372. "weight": 0,
  1373. })
  1374. }
  1375. }
  1376. return
  1377. }
  1378. for k, v := range []*ju.JobKv{bl.ColonKV, bl.SpaceKV, bl.TableKV} {
  1379. if k == 0 {
  1380. tp = "colon"
  1381. } else if k == 1 {
  1382. tp = "space"
  1383. } else if k == 2 {
  1384. tp = "table"
  1385. }
  1386. if v == nil || v.KvTags == nil {
  1387. continue
  1388. }
  1389. for _, vv := range v.KvTags[fieldname] {
  1390. text := ju.TrimLRSpace(vv.Value, "")
  1391. if text != "" {
  1392. kvmap[field] = append(kvmap[field], map[string]interface{}{
  1393. "code": "CL_" + vv.Key,
  1394. "field": field,
  1395. "ruletext": vv.Key,
  1396. "extfrom": vc.ExtFrom,
  1397. "sourcevalue": text,
  1398. "value": text,
  1399. "type": tp,
  1400. "matchtype": "tag_string",
  1401. "blocktag": bl.Classify,
  1402. "weight": vv.Weight,
  1403. })
  1404. //if field != "winnertel" && field != "winnerperson" {
  1405. // //break //暂定取第一个
  1406. //}
  1407. }
  1408. }
  1409. }
  1410. if len(kvmap[field]) == 0 {
  1411. extractFromKv(field, fieldname, bl.Block, vc, kvmap, Category)
  1412. }
  1413. }
  1414. }
  1415. //正则提取结果
  1416. func extRegCoreToResult(extfrom, text string, tag *map[string]string, j *ju.Job, vre *RegLuaInfo, isSite bool) map[string][]map[string]interface{} {
  1417. defer qu.Catch()
  1418. var score float64
  1419. score = vre.Score
  1420. if isSite {
  1421. score = score + 1.0
  1422. }
  1423. extinfo := map[string][]map[string]interface{}{}
  1424. rep := map[string]string{}
  1425. if vre.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
  1426. //处理正负数修正
  1427. ptmp := strings.Split(vre.RuleText, "#")
  1428. sign := 0
  1429. if len(ptmp) == 2 {
  1430. if ptmp[1] == "正" {
  1431. sign = 1
  1432. } else if ptmp[1] == "负" {
  1433. sign = -1
  1434. }
  1435. }
  1436. tmp := strings.Split(ptmp[0], "__")
  1437. if len(tmp) == 2 {
  1438. epos := strings.Split(tmp[1], ",")
  1439. posm := map[string]int{}
  1440. for _, v := range epos {
  1441. ks := strings.Split(v, ":")
  1442. if len(ks) == 2 { //(.*)招标公告(.*)__2:projectname,4:area
  1443. posm[ks[1]] = qu.IntAll(ks[0])
  1444. } else {
  1445. posm[vre.Field] = qu.IntAll(ks[0])
  1446. }
  1447. }
  1448. var pattern string
  1449. if strings.Contains(tmp[0], "\\u") {
  1450. tmp[0] = strings.Replace(tmp[0], "\\", "\\\\", -1)
  1451. tmp[0] = strings.Replace(tmp[0], "\\\\u", "\\u", -1)
  1452. pattern, _ = strconv.Unquote(`"` + tmp[0] + `"`)
  1453. } else {
  1454. pattern = tmp[0]
  1455. }
  1456. //log.Debug("pattern", pattern)
  1457. //fmt.Println(text)
  1458. reg := regexp.MustCompile(pattern)
  1459. apos := reg.FindAllStringSubmatchIndex(text, -1)
  1460. for i, _ := range apos {
  1461. pos := apos[i]
  1462. for k, p := range posm {
  1463. if len(pos) > p {
  1464. if pos[p] == -1 || pos[p+1] == -1 {
  1465. continue
  1466. }
  1467. val := text[pos[p]:pos[p+1]]
  1468. if string(val) == "" {
  1469. continue
  1470. }
  1471. if sign == -1 {
  1472. rep[k+"_"+fmt.Sprint(i)] = "-" + val
  1473. } else {
  1474. rep[k+"_"+fmt.Sprint(i)] = val
  1475. }
  1476. }
  1477. }
  1478. }
  1479. tmps := []map[string]interface{}{}
  1480. for i := 0; i < len(apos); i++ {
  1481. if strings.TrimSpace(rep[vre.Field+"_"+fmt.Sprint(i)]) != "" {
  1482. tmp := map[string]interface{}{
  1483. "field": vre.Field,
  1484. "code": vre.Code,
  1485. "ruletext": vre.RuleText,
  1486. "extfrom": text,
  1487. "value": rep[vre.Field+"_"+fmt.Sprint(i)],
  1488. "type": "regexp",
  1489. "matchtype": "regcontent",
  1490. "blocktag": *tag,
  1491. "score": score,
  1492. }
  1493. exfield := ju.ExtField{
  1494. BlockTag: *tag,
  1495. Field: vre.Field,
  1496. Code: vre.Code,
  1497. RuleText: vre.RuleText,
  1498. Type: "regexp",
  1499. MatchType: "regcontent",
  1500. ExtFrom: extfrom,
  1501. SourceValue: rep[vre.Field+"_"+fmt.Sprint(i)],
  1502. Value: rep[vre.Field+"_"+fmt.Sprint(i)],
  1503. Score: score,
  1504. }
  1505. if vre.Field == "qualifies" {
  1506. if len(rep) >= 2 {
  1507. tmp["ruletext"] = rep[vre.Field+"_key_"+fmt.Sprint(i)]
  1508. exfield.RuleText = rep[vre.Field+"_key_"+fmt.Sprint(i)]
  1509. }
  1510. }
  1511. tmps = append(tmps, tmp)
  1512. if tmp["blocktag"] != nil {
  1513. exfield.BlockTag = tmp["blocktag"].(map[string]string)
  1514. }
  1515. j.Result[vre.Field] = append(j.Result[vre.Field], &exfield)
  1516. }
  1517. }
  1518. if len(tmps) > 0 {
  1519. //fmt.Println(tmps)
  1520. extinfo[vre.Field] = tmps
  1521. }
  1522. }
  1523. } else {
  1524. pos := vre.RegCore.Reg.FindStringIndex(text)
  1525. val := ""
  1526. if len(pos) == 2 {
  1527. text = text[pos[1]:]
  1528. rs := regexp.MustCompile("[^\r\n\t]+")
  1529. tmp := rs.FindAllString(text, -1)
  1530. if len(tmp) > 0 {
  1531. val = tmp[0]
  1532. }
  1533. }
  1534. if val != "" {
  1535. tmps := []map[string]interface{}{}
  1536. tmp := map[string]interface{}{
  1537. "field": vre.Field,
  1538. "code": vre.Code,
  1539. "ruletext": vre.RuleText,
  1540. "extfrom": text,
  1541. "value": val,
  1542. "type": "regexp",
  1543. "matchtype": "regcontent",
  1544. "blocktag": *tag,
  1545. "score": score,
  1546. }
  1547. tmps = append(tmps, tmp)
  1548. extinfo[vre.Field] = tmps
  1549. if j.Result[vre.Field] == nil {
  1550. j.Result[vre.Field] = [](*ju.ExtField){}
  1551. }
  1552. field := &ju.ExtField{BlockTag: *tag, Field: vre.Field, Code: vre.Code, RuleText: vre.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: text,
  1553. Value: val,
  1554. Score: score}
  1555. if tmp["blocktag"] != nil {
  1556. field.BlockTag = tmp["blocktag"].(map[string]string)
  1557. }
  1558. j.Result[vre.Field] = append(j.Result[vre.Field], field)
  1559. }
  1560. }
  1561. return extinfo
  1562. }
  1563. //后置过滤
  1564. func ExtRegBack(j *ju.Job, in *RegLuaInfo, t *TaskInfo, vc *RuleCore) {
  1565. defer qu.Catch()
  1566. if in.IsLua {
  1567. result := GetResultMapForLua(j)
  1568. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Result: result, Script: in.RuleText}
  1569. if j != nil {
  1570. lua.Block = j.Block
  1571. }
  1572. extinfo := lua.RunScript("back")
  1573. for k, v := range extinfo {
  1574. if tmps, ok := v.([]map[string]interface{}); ok {
  1575. j.Result[k] = [](*ju.ExtField){}
  1576. for _, tmp := range tmps {
  1577. field := &ju.ExtField{Field: k, Code: qu.ObjToString(tmp["code"]), RuleText: qu.ObjToString(tmp["ruletext"]), Type: qu.ObjToString(tmp["type"]), MatchType: qu.ObjToString(tmp["matchtype"]),
  1578. ExtFrom: qu.ObjToString(tmp["extfrom"]),
  1579. Value: tmp["value"]}
  1580. if tmp["blocktag"] != nil {
  1581. field.BlockTag = tmp["blocktag"].(map[string]string)
  1582. }
  1583. j.Result[k] = append(j.Result[k], field)
  1584. //j.Result[k] = append(j.Result[k], &ju.ExtField{tmp["blocktag"].(map[string]bool), k, qu.ObjToString(tmp["code"]), qu.ObjToString(tmp["ruletext"]), qu.ObjToString(tmp["type"]), qu.ObjToString(tmp["matchtype"]), qu.ObjToString(tmp["extfrom"]), tmp["value"], 0})
  1585. }
  1586. }
  1587. }
  1588. if len(extinfo) > 0 {
  1589. AddExtLog("clear", j.SourceMid, result, extinfo, in, t) //抽取日志
  1590. }
  1591. } else {
  1592. extinfo := map[string]interface{}{}
  1593. if in.Field != "" {
  1594. clearByTitle := false
  1595. if vc != nil && vc.ExtFrom == "title" && in.Field == "buyer" { //buyer从title抽取到的单独走titile的清理
  1596. clearByTitle = true
  1597. }
  1598. if j.Result[in.Field] != nil {
  1599. tmp := j.Result[in.Field]
  1600. exts := []interface{}{}
  1601. for k, v := range tmp {
  1602. if clearByTitle && v.ExtFrom != "title" {
  1603. continue
  1604. }
  1605. //table抽取到的数据不清理
  1606. if v.Type == "table" && v.Field == "projectname" {
  1607. return
  1608. }
  1609. text := qu.ObjToString(v.Value)
  1610. if v.Field == "bidamount" || v.Field == "budget" {
  1611. if (strings.Contains(qu.ObjToString(v.SourceValue), "费率")||
  1612. strings.Contains(qu.ObjToString(v.SourceValue), "税率") ||
  1613. strings.Contains(qu.ObjToString(v.SourceValue), "(%)") ) &&
  1614. !strings.Contains(qu.ObjToString(v.SourceValue), "工程设计费"){
  1615. j.Result[in.Field][k].IsTrue = false
  1616. continue
  1617. }
  1618. }
  1619. if text != "" {
  1620. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  1621. }
  1622. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  1623. continue
  1624. }
  1625. j.Result[in.Field][k].Value = text
  1626. exts = append(exts, map[string]interface{}{
  1627. "field": v.Field,
  1628. "code": v.Code,
  1629. "ruletext": v.RuleText,
  1630. "type": v.Type,
  1631. "matchtype": v.MatchType,
  1632. "extfrom": v.ExtFrom,
  1633. "value": text,
  1634. })
  1635. }
  1636. if len(exts) > 0 {
  1637. extinfo[in.Field] = exts
  1638. AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
  1639. }
  1640. }
  1641. } else {
  1642. for key, tmp := range j.Result {
  1643. exts := []interface{}{}
  1644. for k, v := range tmp {
  1645. //table抽取到的数据不清理
  1646. if v.Type == "table" && v.Field == "projectname" {
  1647. return
  1648. }
  1649. text := qu.ObjToString(v.Value)
  1650. if text != "" {
  1651. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  1652. }
  1653. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  1654. continue
  1655. }
  1656. j.Result[key][k].Value = text
  1657. exts = append(exts, map[string]interface{}{
  1658. "field": v.Field,
  1659. "code": v.Code,
  1660. "ruletext": v.RuleText,
  1661. "type": v.Type,
  1662. "matchtype": v.MatchType,
  1663. "extfrom": v.ExtFrom,
  1664. "value": text,
  1665. })
  1666. }
  1667. if len(exts) > 0 {
  1668. extinfo[key] = exts
  1669. AddExtLog("clear", j.SourceMid, j.Result, extinfo, in, t) //抽取日志
  1670. }
  1671. }
  1672. }
  1673. }
  1674. }
  1675. //后置过滤
  1676. func ExtRegBackPkg(j *ju.Job, in *RegLuaInfo) {
  1677. defer qu.Catch()
  1678. for k, v := range j.BlockPackage {
  1679. if in.Field == "winner" {
  1680. j.BlockPackage[k].Winner = in.RegPreBac.Reg.ReplaceAllString(v.Winner, in.RegPreBac.Replace)
  1681. } else if in.Field == "bidstatus" {
  1682. j.BlockPackage[k].BidStatus = in.RegPreBac.Reg.ReplaceAllString(v.BidStatus, in.RegPreBac.Replace)
  1683. } else if in.Field == "" {
  1684. j.BlockPackage[k].Text = in.RegPreBac.Reg.ReplaceAllString(v.Text, in.RegPreBac.Replace)
  1685. } else if in.Field == "projectname" {
  1686. j.BlockPackage[k].Name = in.RegPreBac.Reg.ReplaceAllString(v.Name, in.RegPreBac.Replace)
  1687. } else if in.Field == "winnerperson" {
  1688. j.BlockPackage[k].WinnerPerson = in.RegPreBac.Reg.ReplaceAllString(v.WinnerPerson, in.RegPreBac.Replace)
  1689. } else if in.Field == "winnertel" {
  1690. j.BlockPackage[k].WinnerTel = in.RegPreBac.Reg.ReplaceAllString(v.WinnerTel, in.RegPreBac.Replace)
  1691. }
  1692. }
  1693. }
  1694. //KV过滤
  1695. func ExtRuleKV(j *ju.Job, in *RegLuaInfo, t *TaskInfo) {
  1696. defer qu.Catch()
  1697. extinfo := map[string]interface{}{}
  1698. if in.Field != "" {
  1699. if j.Result[in.Field] != nil {
  1700. tmp := j.Result[in.Field]
  1701. exts := []interface{}{}
  1702. for k, v := range tmp {
  1703. if v.Type != "table" && !strings.Contains(v.Type, "colon") && !strings.Contains(v.Type, "space") {
  1704. continue
  1705. }
  1706. if v.Field=="中标金额" ||v.Field=="bidamount" {
  1707. //log.Debug("调试字段...")
  1708. }
  1709. text := qu.ObjToString(v.Value)
  1710. if text != "" {
  1711. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  1712. }
  1713. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  1714. continue
  1715. }
  1716. j.Result[in.Field][k].Value = text
  1717. exts = append(exts, map[string]interface{}{
  1718. "field": v.Field,
  1719. "code": v.Code,
  1720. "ruletext": v.RuleText,
  1721. "type": v.Type,
  1722. "matchtype": v.MatchType,
  1723. "extfrom": v.ExtFrom,
  1724. "value": text,
  1725. })
  1726. }
  1727. if len(exts) > 0 {
  1728. extinfo[in.Field] = exts
  1729. AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
  1730. }
  1731. }
  1732. }
  1733. }
  1734. //获取抽取结果map[string][]interface{},lua脚本使用
  1735. func GetResultMapForLua(j *ju.Job) map[string][]map[string]interface{} {
  1736. defer qu.Catch()
  1737. result := map[string][]map[string]interface{}{}
  1738. for key, val := range j.Result {
  1739. if result[key] == nil {
  1740. result[key] = []map[string]interface{}{}
  1741. }
  1742. for _, v := range val {
  1743. tmp := map[string]interface{}{
  1744. "field": v.Field,
  1745. "code": v.Code,
  1746. "ruletext": v.RuleText,
  1747. "value": v.Value,
  1748. "type": v.Type,
  1749. "matchtype": v.MatchType,
  1750. "extfrom": v.ExtFrom,
  1751. }
  1752. result[key] = append(result[key], tmp)
  1753. }
  1754. }
  1755. return result
  1756. }
  1757. //抽取日志
  1758. func AddExtLog(ftype, sid string, before interface{}, extinfo interface{}, v *RegLuaInfo, t *TaskInfo) {
  1759. defer qu.Catch()
  1760. if !t.IsEtxLog {
  1761. return
  1762. }
  1763. logdata := map[string]interface{}{
  1764. "code": qu.If(v.Code == "", "kv", v.Code),
  1765. "name": v.Name,
  1766. "type": ftype,
  1767. "ruletext": v.RuleText,
  1768. "islua": v.IsLua,
  1769. "field": v.Field,
  1770. "version": t.Version,
  1771. "taskname": t.Name,
  1772. "before": before,
  1773. "extinfo": extinfo,
  1774. "sid": sid,
  1775. "comeintime": time.Now().Unix(),
  1776. }
  1777. lock.Lock()
  1778. ExtLogs[t] = append(ExtLogs[t], logdata)
  1779. lock.Unlock()
  1780. }
  1781. func BeforeAddClearFnLog(ftype, name, sid, before, matchtype string, ext *ju.ExtField, e *ExtractTask) {
  1782. exts := []map[string]interface{}{}
  1783. exts = append(exts, map[string]interface{}{
  1784. "field": ext.Field,
  1785. "code": ext.Code,
  1786. "type": ftype,
  1787. "matchtype": matchtype,
  1788. "extfrom": ext.ExtFrom,
  1789. "value": ext.Value,
  1790. })
  1791. extinfo := map[string]interface{}{
  1792. ext.Field: exts,
  1793. }
  1794. AddClearFnLog(ftype, sid, before, extinfo, ext.Code, name, ext.Field, e.TaskInfo)
  1795. }
  1796. func AddClearFnLog(ftype, sid string, before interface{}, extinfo interface{}, code, name, field string, t *TaskInfo) {
  1797. defer qu.Catch()
  1798. if !t.IsEtxLog {
  1799. return
  1800. }
  1801. logdata := map[string]interface{}{
  1802. "code": code,
  1803. "name": name,
  1804. "type": ftype,
  1805. "ruletext": "",
  1806. "islua": false,
  1807. "field": field,
  1808. "version": t.Version,
  1809. "taskname": t.Name,
  1810. "before": before,
  1811. "extinfo": extinfo,
  1812. "sid": sid,
  1813. "comeintime": time.Now().Unix(),
  1814. }
  1815. lock.Lock()
  1816. ExtLogs[t] = append(ExtLogs[t], logdata)
  1817. lock.Unlock()
  1818. }
  1819. //保存抽取日志
  1820. func SaveExtLog() {
  1821. defer qu.Catch()
  1822. tmpLogs := map[*TaskInfo][]map[string]interface{}{}
  1823. lock.Lock()
  1824. tmpLogs = ExtLogs
  1825. ExtLogs = map[*TaskInfo][]map[string]interface{}{}
  1826. lock.Unlock()
  1827. for k, v := range tmpLogs {
  1828. if len(v) < saveLimit {
  1829. db.Mgo.SaveBulk(k.TrackColl, v...)
  1830. } else {
  1831. for {
  1832. if len(v) > saveLimit {
  1833. tmp := v[:saveLimit]
  1834. db.Mgo.SaveBulk(k.TrackColl, tmp...)
  1835. v = v[saveLimit:]
  1836. } else {
  1837. db.Mgo.SaveBulk(k.TrackColl, v...)
  1838. break
  1839. }
  1840. }
  1841. }
  1842. }
  1843. time.AfterFunc(10*time.Second, SaveExtLog)
  1844. }
  1845. type FieldValue struct {
  1846. Value interface{}
  1847. Count int
  1848. }
  1849. var clearWinnerReg = regexp.MustCompile("名称|施工|拟定供应商名称|:|:")
  1850. var unPackageWinnerReg = regexp.MustCompile("(重新招标)")
  1851. //分析抽取结果并保存
  1852. func AnalysisSaveResult(j, jf *ju.Job, e *ExtractTask) {
  1853. qu.Try(func() {
  1854. if (j.Category == "招标" || j.Category == "预告") && (len(j.BlockPackage) > 0 || len(j.PackageInfo) > 0 || len(j.Result) > 0) {
  1855. if j.CategorySecond != "单一" {
  1856. delete(j.Result, "winner")
  1857. delete(j.Result, "bidamount")
  1858. for _, v := range j.BlockPackage {
  1859. v.Bidamount = 0
  1860. v.IsTrueBidamount = false
  1861. if v.Winner != "" {
  1862. v.Winner = ""
  1863. if v.SpaceKV != nil {
  1864. delete(v.SpaceKV.KvTags, "中标单位")
  1865. }
  1866. if v.TableKV != nil {
  1867. delete(v.TableKV.KvTags, "中标单位")
  1868. }
  1869. if v.ColonKV != nil {
  1870. delete(v.ColonKV.KvTags, "中标单位")
  1871. }
  1872. }
  1873. }
  1874. for _, v := range j.PackageInfo {
  1875. delete(v, "winner")
  1876. delete(v, "bidamount")
  1877. }
  1878. j.Winnerorder = nil
  1879. if jf != nil && jf.Winnerorder != nil {
  1880. jf.Winnerorder = nil
  1881. }
  1882. }
  1883. }
  1884. //重新取出清理过后的中标候选人
  1885. resetWinnerorder(j)
  1886. //打分
  1887. doc, result, _id := funcAnalysis(j, e)
  1888. //_, result, _id := funcAnalysis(j, e)
  1889. if ju.IsSaveTag {
  1890. go otherNeedSave(j, result, e)
  1891. }
  1892. //从排序结果中取值
  1893. tmp := map[string]interface{}{} //抽取值
  1894. tmp["spidercode"] = j.SpiderCode
  1895. tmp["site"] = j.Site
  1896. if len(*j.Jsondata) > 0 {
  1897. tmp["jsondata"] = j.Jsondata
  1898. }
  1899. //字段-抽取来源
  1900. fieldSource := make(map[string]interface{},0)
  1901. //字段-抽取来源
  1902. for k, val := range result {
  1903. if k == "qualifies" {
  1904. squalifies := make([]interface{}, 0)
  1905. squalifiesMap := make(map[string]*scoreIndex, 0)
  1906. for _, kv := range val {
  1907. skey := kv.RuleText
  1908. if kv.Score > 0 {
  1909. if squalifiesMap[skey] == nil {
  1910. squalifiesMap = map[string]*scoreIndex{
  1911. skey: &scoreIndex{
  1912. Score: kv.Score,
  1913. Index: len(squalifies),
  1914. },
  1915. }
  1916. squalifies = append(squalifies, map[string]interface{}{
  1917. "key": skey,
  1918. "value": kv.Value,
  1919. })
  1920. } else {
  1921. if squalifiesMap[skey].Score < kv.Score {
  1922. squalifies[squalifiesMap[skey].Index] = map[string]interface{}{
  1923. "key": skey,
  1924. "value": kv.Value,
  1925. }
  1926. }
  1927. }
  1928. }
  1929. }
  1930. tmp[k] = squalifies
  1931. continue
  1932. }
  1933. for _, v := range val { //取第一个非负数,项目名称除外
  1934. //存0是否有效
  1935. if (v.Field == "bidamount" || v.Field == "budget") && v.IsTrue && v.Score > -1 {
  1936. tmp[v.Field] = v.Value
  1937. fieldSource[v.Field] = map[string]interface{}{
  1938. "ext_type":v.Type,
  1939. "ext_from":v.ExtFrom,
  1940. }
  1941. break
  1942. }
  1943. if v.Score > -1 && (v.Field != "bidamount" && v.Field != "budget") && len(strings.TrimSpace(fmt.Sprint(v.Value))) > 0 {
  1944. tmp[v.Field] = v.Value
  1945. fieldSource[v.Field] = map[string]interface{}{
  1946. "ext_type":v.Type,
  1947. "ext_from":v.ExtFrom,
  1948. }
  1949. break
  1950. }
  1951. }
  1952. }
  1953. tmp["winner"] = strings.ReplaceAll(qu.ObjToString(tmp["winner"]), ",,", ",")
  1954. if len(j.PackageInfo) > 15 {
  1955. for k, v := range j.PackageInfo {
  1956. j.PackageInfo = map[string]map[string]interface{}{}
  1957. j.PackageInfo[k] = v
  1958. break
  1959. }
  1960. }
  1961. if len(j.PackageInfo) > 0 { //分包信息
  1962. tmp["package"] = j.PackageInfo
  1963. //包预算,中标金额合并大于抽取就覆盖
  1964. tmpBidamount, tmpBudget,tmpAgencyfee:=qu.Float64All(0),qu.Float64All(0),qu.Float64All(0)
  1965. //s_winner逗号分隔拼接,分包中标人
  1966. var tmpstr, savewinner []string
  1967. //按包排序
  1968. for b, v := range j.PackageInfo {
  1969. if v["winner"] != nil && v["winner"] != "" {
  1970. tmpstr = append(tmpstr, b)
  1971. }
  1972. }
  1973. //包预算,中标金额合并大于抽取就覆盖
  1974. if len(j.PackageInfo) >= 1 {
  1975. //包数大于1累加
  1976. for _, v := range j.PackageInfo {
  1977. if v["budget"] != nil {
  1978. tmpBudget = precisionAddFloat(tmpBudget,qu.Float64All(v["budget"]))
  1979. }
  1980. if v["bidamount"] != nil {
  1981. tmpBidamount = precisionAddFloat(tmpBidamount,qu.Float64All(v["bidamount"]))
  1982. }
  1983. if v["agencyfee"] != nil {
  1984. tmpAgencyfee = precisionAddFloat(tmpAgencyfee,qu.Float64All(v["agencyfee"]))
  1985. }
  1986. }
  1987. if qu.Float64All(tmp["budget"]) < tmpBudget {
  1988. fieldSource["budget"] = map[string]interface{}{
  1989. "ext_type":"",
  1990. "ext_from":"package",
  1991. }
  1992. tmp["budget"] = tmpBudget
  1993. }
  1994. if qu.Float64All(tmp["agencyfee"]) < tmpAgencyfee {
  1995. fieldSource["agencyfee"] = map[string]interface{}{
  1996. "ext_type":"",
  1997. "ext_from":"package",
  1998. }
  1999. tmp["agencyfee"] = tmpAgencyfee
  2000. }
  2001. if qu.Float64All(tmp["bidamount"]) > 0 && qu.Float64All(tmp["budget"]) > 0 && (qu.Float64All(tmp["bidamount"])/10 > qu.Float64All(tmp["budget"])) {
  2002. fieldSource["bidamount"] = map[string]interface{}{
  2003. "ext_type":"",
  2004. "ext_from":"package",
  2005. }
  2006. tmp["bidamount"] = tmpBidamount
  2007. } else if qu.Float64All(tmp["bidamount"]) < tmpBidamount {
  2008. fieldSource["bidamount"] = map[string]interface{}{
  2009. "ext_type":"",
  2010. "ext_from":"package",
  2011. }
  2012. tmp["bidamount"] = tmpBidamount
  2013. }
  2014. } else {
  2015. //包数等于1,tmp没有值取包里的值
  2016. if tmp["budget"] == nil || tmp["budget"] == 0 {
  2017. for _, v := range j.PackageInfo {
  2018. if v["budget"] != nil {
  2019. fieldSource["budget"] = map[string]interface{}{
  2020. "ext_type":"",
  2021. "ext_from":"package",
  2022. }
  2023. tmp["budget"] = v["budget"]
  2024. }
  2025. }
  2026. }
  2027. if tmp["agencyfee"] == nil || tmp["agencyfee"] == 0 {
  2028. for _, v := range j.PackageInfo {
  2029. if v["agencyfee"] != nil {
  2030. fieldSource["agencyfee"] = map[string]interface{}{
  2031. "ext_type":"",
  2032. "ext_from":"package",
  2033. }
  2034. tmp["agencyfee"] = v["agencyfee"]
  2035. }
  2036. }
  2037. }
  2038. if tmp["bidamount"] == nil || tmp["bidamount"] == 0 {
  2039. for _, v := range j.PackageInfo {
  2040. if v["bidamount"] != nil {
  2041. fieldSource["bidamount"] = map[string]interface{}{
  2042. "ext_type":"",
  2043. "ext_from":"package",
  2044. }
  2045. tmp["bidamount"] = v["bidamount"]
  2046. }
  2047. }
  2048. }
  2049. }
  2050. //s_winner逗号分隔拼接,分包中标人
  2051. sort.Strings(tmpstr)
  2052. for _, v := range tmpstr {
  2053. winner := qu.ObjToString(j.PackageInfo[v]["winner"])
  2054. new_winner := clearWinnerReg.ReplaceAllString(winner, "")
  2055. if new_winner == "" {
  2056. continue
  2057. }
  2058. //名称黑名单
  2059. if unPackageWinnerReg.MatchString(new_winner) {
  2060. continue
  2061. }
  2062. savewinner = append(savewinner, new_winner)
  2063. }
  2064. if (savewinner == nil || len(savewinner) == 0) && tmp["winner"] != nil {
  2065. tmp["s_winner"] = tmp["winner"]
  2066. fieldSource["s_winner"] = fieldSource["winner"]
  2067. } else if savewinner != nil {
  2068. savewinner = RemoveReplicaSliceString(savewinner)
  2069. tmp["s_winner"] = strings.Join(savewinner, ",")
  2070. if len(savewinner)==1 {
  2071. fieldSource["s_winner"] = fieldSource["winner"]
  2072. }else if len(savewinner)>1{
  2073. fieldSource["s_winner"] = map[string]interface{}{
  2074. "ext_type":"",
  2075. "ext_from":"package",
  2076. }
  2077. }
  2078. }
  2079. } else if tmp["winner"] != nil && tmp["winner"] != "" {
  2080. //没有分包取winner
  2081. tmp["s_winner"] = tmp["winner"]
  2082. fieldSource["s_winner"] = fieldSource["winner"]
  2083. }
  2084. if len(j.Winnerorder) > 0 { //候选人信息
  2085. for i, v := range j.Winnerorder {
  2086. if v["price"] != nil {
  2087. tmpPrice := clear.ObjToMoney([]interface{}{v["price"], ""}, j.SpiderCode, j.IsClearnMoney)
  2088. if tmpPrice[len(tmpPrice)-1].(bool) {
  2089. j.Winnerorder[i]["price"] = tmpPrice[0]
  2090. } else {
  2091. delete(j.Winnerorder[i], "price")
  2092. }
  2093. }
  2094. }
  2095. tmp["winnerorder"] = j.Winnerorder
  2096. }
  2097. //处理附件
  2098. var resultf map[string][]*ju.ExtField
  2099. ffield := map[string]interface{}{}
  2100. if jf != nil {
  2101. _, resultf, _ = funcAnalysis(jf, e)
  2102. for _, val := range resultf {
  2103. for _, v := range val { //取第一个非负数
  2104. if v.Score > -1 {
  2105. ffield[v.Field] = v.Value
  2106. if tmp[v.Field] == nil {
  2107. if (v.Field == "bidamount" || v.Field == "budget") && v.IsTrue && v.Value.(float64) > 100 && v.Value.(float64) < 50000000000 {
  2108. tmp[v.Field] = v.Value
  2109. fieldSource[v.Field] = map[string]interface{}{
  2110. "ext_type":v.Type,
  2111. "ext_from":"ff",
  2112. }
  2113. break
  2114. }
  2115. if v.Score > -1 && (v.Field != "bidamount" && v.Field != "budget") && len(strings.TrimSpace(fmt.Sprint(v.Value))) > 0 {
  2116. tmp[v.Field] = v.Value
  2117. fieldSource[v.Field] = map[string]interface{}{
  2118. "ext_type":v.Type,
  2119. "ext_from":"ff",
  2120. }
  2121. break
  2122. }
  2123. }
  2124. break
  2125. }
  2126. }
  2127. }
  2128. if len(jf.PackageInfo) > 0 { //分包信息
  2129. ffield["package"] = jf.PackageInfo
  2130. }
  2131. if len(jf.Winnerorder) > 0 { //候选人信息
  2132. ffield["winnerorder"] = jf.Winnerorder
  2133. }
  2134. }
  2135. //添加字段来源
  2136. tmp["field_source"] = fieldSource
  2137. //添加字段来源
  2138. for k, v := range *doc {
  2139. if utf8.RuneCountInString(qu.ObjToString(v)) > 100000 {
  2140. (*doc)[k] = []rune(qu.ObjToString(v))[:100000]
  2141. }
  2142. //去重冗余字段
  2143. if delFiled(k) {
  2144. continue
  2145. }
  2146. if tmp[k] == nil {
  2147. tmp[k] = v
  2148. }
  2149. }
  2150. //质量审核
  2151. if ju.QualityAudit {
  2152. e.QualityAudit(tmp)
  2153. }
  2154. //城市抽取
  2155. if e.IsExtractCity {
  2156. e.NewExtractCity(j, &tmp, _id)
  2157. }
  2158. //品牌抽取
  2159. if ju.IsBrandGoods {
  2160. tmp["checkhas"] = map[string]int{
  2161. "hastable": j.HasTable,
  2162. "hasgoods": j.HasGoods,
  2163. "hasbrand": j.HasBrand,
  2164. "haskey": j.HasKey,
  2165. }
  2166. if len(j.BrandData) > 0 {
  2167. tmp["tablebrand"] = j.BrandData
  2168. }
  2169. }
  2170. //prince和number抽取
  2171. if ju.IsPriceNumber {
  2172. priceNumberLen := len(j.PriceNumberData)
  2173. if priceNumberLen > 1 { //table数据去重
  2174. tmpPriceNumberData := []map[string]interface{}{}
  2175. tableStrs := map[string]bool{}
  2176. for _, tb := range j.PriceNumberData {
  2177. has := false
  2178. bytes, _ := json.Marshal(tb)
  2179. str := string(bytes)
  2180. if len(tableStrs) > 0 && tableStrs[str] {
  2181. has = true
  2182. } else {
  2183. tableStrs[str] = true
  2184. }
  2185. if !has {
  2186. for _, data := range tb {
  2187. tmpPriceNumberData = append(tmpPriceNumberData, data)
  2188. }
  2189. }
  2190. }
  2191. tmp["pricenumber"] = tmpPriceNumberData
  2192. } else if priceNumberLen == 1 {
  2193. tmp["pricenumber"] = j.PriceNumberData[0]
  2194. }
  2195. }
  2196. //所有kv组成的字符串
  2197. var kvtext bytes.Buffer
  2198. blocks := make([]ju.BlockAndTag, 0)
  2199. for _, v := range j.Block {
  2200. //分包和标签
  2201. if ju.SaveBlock {
  2202. xx, _ := json.Marshal(v)
  2203. tmpblock := new(ju.TmpBlock)
  2204. err := json.Unmarshal(xx, &tmpblock)
  2205. if err != nil {
  2206. if v.BPackage != nil {
  2207. bpb, _ := json.Marshal(v.BPackage)
  2208. tmpblock.BPackage = string(bpb)
  2209. }
  2210. tmpblock = rangeBlockToJson(v, *tmpblock)
  2211. }
  2212. blocks = append(blocks, ju.BlockAndTag{v.Tag, tmpblock})
  2213. }
  2214. //把所有kv组装成一个字符串,存库
  2215. for _, jv := range []*ju.JobKv{v.ColonKV, v.SpaceKV, v.TableKV} {
  2216. if jv == nil {
  2217. continue
  2218. }
  2219. for jv_k, jv_v := range jv.KvTags {
  2220. for _, jv_vv := range jv_v {
  2221. kvtext.WriteString(jv_k)
  2222. kvtext.WriteString(":")
  2223. kvtext.WriteString(jv_vv.Value)
  2224. kvtext.WriteString("\n")
  2225. }
  2226. }
  2227. }
  2228. }
  2229. if kvtext.Len() > 0 {
  2230. tmp["kvtext"] = kvtext.String()
  2231. }
  2232. if len(blocks) > 0 {
  2233. if blocksBytes, err := json.Marshal(blocks); err == nil {
  2234. if utf8.RuneCount(blocksBytes) < 100000 {
  2235. tmp["blocks"] = string(blocksBytes)
  2236. }
  2237. }
  2238. }
  2239. tmp["dataging"] = j.Dataging
  2240. /*for k, v := range *j.Data {
  2241. if f[k] {
  2242. tmp[k] = v
  2243. }
  2244. }
  2245. for k := range tmp {
  2246. if !f[k]{
  2247. delete(tmp,k)
  2248. }
  2249. }*/
  2250. //检查字段
  2251. tmp = checkFields(tmp)
  2252. if tmp["projectname"] == nil || tmp["projectname"] == "" {
  2253. tmp["projectname"] = j.Title
  2254. }
  2255. tmp["repeat"] = 0
  2256. if ju.Ffield {
  2257. if len(ffield) > 0 {
  2258. tmp["ffield"] = ffield
  2259. }
  2260. }
  2261. if e.TaskInfo.TestColl == "" {
  2262. if len(tmp) > 0 { //保存抽取结果
  2263. delete(tmp, "_id")
  2264. tmparr := []map[string]interface{}{
  2265. map[string]interface{}{
  2266. "_id": qu.StringTOBsonId(_id),
  2267. },
  2268. map[string]interface{}{"$set": tmp},
  2269. }
  2270. e.RWMutex.Lock()
  2271. e.BidArr = append(e.BidArr, tmparr)
  2272. e.BidTotal++
  2273. e.RWMutex.Unlock()
  2274. }
  2275. if ju.SaveResult {
  2276. id := tmp["_id"]
  2277. tmp["result"] = result
  2278. tmp["resultf"] = resultf
  2279. delete(tmp, "_id")
  2280. tmparr := []map[string]interface{}{
  2281. map[string]interface{}{
  2282. "_id": id,
  2283. },
  2284. map[string]interface{}{"$set": tmp},
  2285. }
  2286. e.RWMutex.Lock()
  2287. e.ResultArr = append(e.ResultArr, tmparr)
  2288. e.RWMutex.Unlock()
  2289. }
  2290. } else { //测试结果
  2291. delete(tmp, "_id")
  2292. delete(tmp, "fieldall")
  2293. if len(j.BlockPackage) > 0 { //分包详情
  2294. if len(j.BlockPackage) > 10 {
  2295. tmp["epackage"] = "分包异常"
  2296. } else {
  2297. bs, _ := json.Marshal(j.BlockPackage)
  2298. tmp["epackage"] = string(bs)
  2299. }
  2300. }
  2301. tmp["result"] = result
  2302. //tmp["resultf"] = resultf
  2303. //_,err :=db.Mgo.Get().DB("zhengkun").C("result_data").Upsert(`{"_id":"`+_id+`"}`,map[string]interface{}{"$set": tmp})
  2304. //log.Debug("save:",err)
  2305. b := db.Mgo.Update(e.TaskInfo.TestColl, `{"_id":"`+_id+`"}`, map[string]interface{}{"$set": tmp}, true, false)
  2306. if !b {
  2307. log.Debug(e.TaskInfo.TestColl, _id)
  2308. }
  2309. }
  2310. }, func(err interface{}) {
  2311. log.Debug("AnalysisSaveResult err", err)
  2312. })
  2313. }
  2314. //检查字段-
  2315. func checkFields(tmp map[string]interface{}) map[string]interface{} {
  2316. delete(tmp, "contenthtml")
  2317. delete(tmp, "detail")
  2318. tmp["repeat"] = 0
  2319. //指定爬虫-金额处理-预算-中标金额异常
  2320. if qu.ObjToString(tmp["spidercode"])=="xz_xzzzqjzscjgycxxxpt_zbtzs" {
  2321. if budget, ok := tmp["budget"].(float64); ok && budget>0 && budget < 1000000{
  2322. tmp["budget"] = budget*10000.0
  2323. }
  2324. if bidamount, ok := tmp["bidamount"].(float64); ok && bidamount>0 && bidamount > 1000000000{
  2325. tmp["bidamount"] = bidamount/10000.0
  2326. }
  2327. }
  2328. if qu.ObjToString(tmp["spidercode"])=="js_jsszbtbw_zbhxrgs" {
  2329. if bidamount, ok := tmp["bidamount"].(float64); ok && bidamount>0 && bidamount > 1000000000{
  2330. tmp["bidamount"] = bidamount/10000.0
  2331. }
  2332. }
  2333. if _, ok := tmp["bidamount"].(string); ok {
  2334. delete(tmp, "bidamount")
  2335. } else if fb, ok := tmp["bidamount"].(float64); ok && fb > 0 && qu.Float64All(tmp["budget"]) > 0 && (fb/5 > qu.Float64All(tmp["budget"]) || qu.Float64All(tmp["budget"])/1000 > fb) {
  2336. delete(tmp, "bidamount")
  2337. }
  2338. if _, ok := tmp["budget"].(string); ok {
  2339. delete(tmp, "budget")
  2340. }
  2341. if _, ok := tmp["unitprice"].(string); ok {
  2342. delete(tmp, "unitprice")
  2343. }
  2344. if _, ok := tmp["bidopentime"].(string); ok {
  2345. delete(tmp, "bidopentime")
  2346. }
  2347. if _, ok := tmp["signaturedate"].(string); ok {
  2348. delete(tmp, "signaturedate")
  2349. }
  2350. if _, ok := tmp["supervisorrate"].(string); ok {
  2351. delete(tmp, "supervisorrate")
  2352. }
  2353. for k, v := range tmp {
  2354. if k == "qualifies" {
  2355. continue
  2356. }
  2357. if k == "contract_guarantee" || k == "bid_guarantee" {
  2358. if len(fmt.Sprint(v)) > 0 {
  2359. tmp[k] = true
  2360. } else {
  2361. delete(tmp, k)
  2362. }
  2363. }
  2364. if v == "" || len(strings.TrimSpace(fmt.Sprint(v))) == 0 || strings.Contains(fmt.Sprint(v), "**") {
  2365. delete(tmp, k)
  2366. }
  2367. }
  2368. //项目周期-有效值
  2369. projectperiod := qu.ObjToString(tmp["projectperiod"])
  2370. if projectperiod !="" {
  2371. //项目周期包含日期,数字及日期单位可保留,其余可清洗
  2372. isNeedValueReg := regexp.MustCompile(`([0-9俩两一二三四五六七八九年月日天周]|合同)`)
  2373. if !isNeedValueReg.MatchString(projectperiod) {
  2374. delete(tmp, "projectperiod")
  2375. }
  2376. }
  2377. //工期单位是否有效-清理
  2378. if project_timeunit, ok := tmp["project_timeunit"].(string); ok {
  2379. dateReg := regexp.MustCompile(`[年|月|日|天|周]`)
  2380. if !dateReg.MatchString(project_timeunit) || utf8.RuneCountInString(project_timeunit)>4 {
  2381. delete(tmp, "project_timeunit")
  2382. }
  2383. //年-0 >5 删除
  2384. if project_timeunit == "年" && (qu.Int64All(tmp["project_duration"])==0 || qu.Int64All(tmp["project_duration"])>5 ){
  2385. delete(tmp, "project_timeunit")
  2386. }
  2387. }
  2388. if tmp["winner"] != nil && tmp["s_winner"] != nil {
  2389. strwin := qu.ObjToString(tmp["winner"])
  2390. strwin_s := qu.ObjToString(tmp["s_winner"])
  2391. if !strings.Contains(strwin_s, strwin) {
  2392. tmp["s_winner"] = strwin
  2393. }
  2394. }
  2395. //budget bidamount
  2396. if bg, ok := tmp["budget"].(float64); ok {
  2397. if bg >= 50000000000 {
  2398. tmp["budget_max_err"] = bg
  2399. delete(tmp, "budget")
  2400. }
  2401. }
  2402. if bg, ok := tmp["bidamount"].(float64); ok && bg >= 50000000000 {
  2403. code := qu.ObjToString(tmp["spidercode"])
  2404. if bg >= 50000000000 && code != "xz_xzzzqjzscjgycxxxpt_zbtzs" &&
  2405. code != "js_jsszbtbw_zbhxrgs"{
  2406. tmp["bidamount_max_err"] = bg
  2407. delete(tmp, "bidamount")
  2408. }
  2409. }
  2410. //投标方式-
  2411. bidway := qu.IntAll(tmp["bidway"])
  2412. if bidway == 1 {
  2413. tmp["bidway"] = "纸质投标"
  2414. }else if bidway == 2 {
  2415. tmp["bidway"] = "电子投标"
  2416. }else {
  2417. delete(tmp, "bidway")
  2418. }
  2419. //折扣系数
  2420. discount := dealWithDiscountBid(tmp)
  2421. if discount >0.0 {
  2422. tmp["biddiscount"] = discount
  2423. }else {
  2424. delete(tmp, "biddiscount")
  2425. }
  2426. delete(tmp, "biddiscount_up")
  2427. delete(tmp, "biddiscount_down")
  2428. //临时
  2429. //bidopentime := qu.Int64All(tmp["bidopentime"])
  2430. //bidendtime := qu.Int64All(tmp["bidendtime"])
  2431. //timeLayout := "2006-01-02 15:04:05"
  2432. //
  2433. //if bidopentime>0 {
  2434. // bidopentime_str := time.Unix(bidopentime, 0).Format(timeLayout) //设置时间戳 使用模板格式化为日期字符串
  2435. // tmp["bidopentime"] = bidopentime_str
  2436. //}
  2437. //if bidendtime>0 {
  2438. // bidendtime_str := time.Unix(bidendtime, 0).Format(timeLayout) //设置时间戳 使用模板格式化为日期字符串
  2439. // tmp["bidendtime"] = bidendtime_str
  2440. //}
  2441. jyhref:= fmt.Sprintf(JYUrl, qu.CommonEncodeArticle("content", qu.BsonIdToSId(tmp["_id"])))
  2442. tmp["jytest_href"] = jyhref
  2443. return tmp
  2444. }
  2445. //处理折扣系数
  2446. func dealWithDiscountBid(tmp map[string]interface{}) float64 {
  2447. biddiscount := qu.Float64All(tmp["biddiscount"])
  2448. biddiscount_up := qu.Float64All(tmp["biddiscount_up"])
  2449. biddiscount_down := qu.Float64All(tmp["biddiscount_down"])
  2450. baseCount := float64(1)
  2451. if biddiscount_down >0.0 {
  2452. num1:=decimal.NewFromFloat(baseCount)
  2453. num2:=decimal.NewFromFloat(biddiscount_down)
  2454. decimalValue := num1.Sub(num2)
  2455. res,_ := decimalValue.Float64()
  2456. //log.Debug("下浮后折扣系数:",res)
  2457. return res
  2458. }
  2459. if biddiscount_up >0.0 {
  2460. num1:=decimal.NewFromFloat(baseCount)
  2461. num2:=decimal.NewFromFloat(biddiscount_up)
  2462. decimalValue := num1.Add(num2)
  2463. res,_ := decimalValue.Float64()
  2464. //log.Debug("上浮后折扣系数:",res)
  2465. return res
  2466. }
  2467. if biddiscount>0.0 {
  2468. if biddiscount > 1.0 && biddiscount<=10.0 {
  2469. num1:=decimal.NewFromFloat(10.0)
  2470. num2:=decimal.NewFromFloat(biddiscount_up)
  2471. decimalValue := num2.Div(num1)
  2472. res,_ := decimalValue.Float64()
  2473. //log.Debug("标准-①折扣系数:",res)
  2474. return res
  2475. }else if biddiscount>10.0 {
  2476. num1:=decimal.NewFromFloat(100.0)
  2477. num2:=decimal.NewFromFloat(biddiscount_up)
  2478. decimalValue := num2.Div(num1)
  2479. res,_ := decimalValue.Float64()
  2480. //log.Debug("标准-⑩折扣系数:",res)
  2481. return res
  2482. }else {
  2483. //log.Debug("标准折扣系数:",biddiscount)
  2484. return biddiscount
  2485. }
  2486. }
  2487. return 0.0
  2488. }
  2489. //精度丢失-相加
  2490. func precisionAddFloat(tmp1,tmp2 float64)float64{
  2491. num1:=decimal.NewFromFloat(tmp1)
  2492. num2:=decimal.NewFromFloat(tmp2)
  2493. decimalValue := num2.Add(num1)
  2494. res,_ := decimalValue.Float64()
  2495. return res
  2496. }
  2497. //保存其他
  2498. //kv、表格、块上的标签凡是新的标签都入库
  2499. //val type times firstid createtime 判定field
  2500. func otherNeedSave(j *ju.Job, result map[string][]*ju.ExtField, e *ExtractTask) {
  2501. now := time.Now().Unix()
  2502. coll := e.TaskInfo.TestColl
  2503. if coll == "" {
  2504. coll = "extract_tag_result"
  2505. } else {
  2506. coll += "_tag"
  2507. }
  2508. datas := []map[string]interface{}{}
  2509. kv := map[string]int{}
  2510. for _, v := range j.Block {
  2511. //
  2512. for _, vv := range []*ju.JobKv{v.ColonKV, v.TableKV, v.SpaceKV} {
  2513. if vv == nil || vv.KvTags == nil {
  2514. continue
  2515. }
  2516. for kkk, vvv := range vv.KvTags {
  2517. for _, vvvv := range vvv {
  2518. if vvvv.IsInvalid {
  2519. kv[kkk] = kv[kkk] + 1
  2520. break
  2521. }
  2522. }
  2523. }
  2524. }
  2525. for _, vv := range v.NotClassifyTitles {
  2526. datas = append(datas, map[string]interface{}{
  2527. "val": vv,
  2528. "times": 0,
  2529. "type": "block",
  2530. "firstid": j.SourceMid,
  2531. "createtime": now,
  2532. })
  2533. if len(datas) == saveLimit {
  2534. db.Mgo.SaveBulk(coll, datas...)
  2535. datas = []map[string]interface{}{}
  2536. }
  2537. }
  2538. }
  2539. for k, v := range kv {
  2540. datas = append(datas, map[string]interface{}{
  2541. "val": k,
  2542. "times": v,
  2543. "type": "kv",
  2544. "firstid": j.SourceMid,
  2545. "createtime": now,
  2546. })
  2547. if len(datas) == saveLimit {
  2548. db.Mgo.SaveBulk(coll, datas...)
  2549. datas = []map[string]interface{}{}
  2550. }
  2551. }
  2552. if len(datas) > 0 {
  2553. db.Mgo.SaveBulk(coll, datas...)
  2554. }
  2555. }
  2556. func rangeBlockToJson(j *ju.Block, tmpblock ju.TmpBlock) (b *ju.TmpBlock) {
  2557. if j == nil {
  2558. return nil
  2559. }
  2560. if len(j.Block) > 0 {
  2561. for i, v := range j.Block {
  2562. rangetmp := new(ju.TmpBlock)
  2563. vb, _ := json.Marshal(v)
  2564. json.Unmarshal(vb, &rangetmp)
  2565. tmpblock.Block[i] = rangeBlockToJson(v, *rangetmp)
  2566. }
  2567. }
  2568. if j.ColonKV != nil {
  2569. cb, _ := json.Marshal(j.ColonKV)
  2570. tmpblock.ColonKV = string(cb)
  2571. }
  2572. if j.SpaceKV != nil {
  2573. sb, _ := json.Marshal(j.SpaceKV)
  2574. tmpblock.SpaceKV = string(sb)
  2575. }
  2576. if j.TableKV != nil {
  2577. tb, _ := json.Marshal(j.TableKV)
  2578. tmpblock.TableKV = string(tb)
  2579. }
  2580. return &tmpblock
  2581. }
  2582. //去重冗余字段
  2583. func delFiled(k string) bool {
  2584. return k == "detailfile" || k == "summary" || k == "detail" || k == "contenthtml" || k == "site" || k == "spidercode" || k == "projectinfo" || k == "jsondata"
  2585. }
  2586. //分析-打分排序
  2587. func funcAnalysis(j *ju.Job, e *ExtractTask) (*map[string]interface{}, map[string][]*ju.ExtField, string) {
  2588. defer qu.Catch()
  2589. doc := j.Data
  2590. result := j.Result
  2591. _id := qu.BsonIdToSId((*doc)["_id"])
  2592. result = ScoreFields(j, e.Tag) //正负面词打分
  2593. //结果排序
  2594. for _, val := range result {
  2595. ju.Sort(val)
  2596. }
  2597. if !(len(j.Result) <= 0 || j.Jsondata == nil || len(*j.Jsondata) <= 0) {
  2598. clearJd(j.Jsondata, e, j.SpiderCode, j.IsClearnMoney)
  2599. marshalbt, _ := json.Marshal(j.Jsondata)
  2600. tmpjddata := make(map[string]interface{})
  2601. json.Unmarshal(marshalbt, &tmpjddata)
  2602. for _, jdkey := range ju.JsonData {
  2603. if (*j.Jsondata)[jdkey] != nil && (*j.Jsondata)[jdkey] != "" && len(j.Result[jdkey]) >= 5 {
  2604. for tmpk, tmpv := range j.Result[jdkey][:5] {
  2605. if jdkey == "budget" || jdkey == "bidamount" {
  2606. lockclear.Lock()
  2607. cfn := e.ClearFn[jdkey]
  2608. lockclear.Unlock()
  2609. if len(cfn) == 0 {
  2610. continue
  2611. }
  2612. newNum := clear.DoClearFn(cfn, []interface{}{(*j.Jsondata)[jdkey], ""}, j.SpiderCode, j.IsClearnMoney)
  2613. if tmpv.Value == newNum[0] {
  2614. extField := &ju.ExtField{Code: "JsonData_" + jdkey + "_j.Result" + fmt.Sprint(tmpk), Field: jdkey, ExtFrom: "JsonData_" + jdkey + "_j.Result" + fmt.Sprint(tmpk), SourceValue: (*j.Jsondata)[jdkey], Value: newNum[0], Score: 100, IsTrue: newNum[len(newNum)-1].(bool)}
  2615. j.Result[jdkey] = append(j.Result[jdkey], extField)
  2616. ju.Sort(j.Result[jdkey])
  2617. delete((*j.Jsondata), jdkey)
  2618. break
  2619. }
  2620. } else {
  2621. if (*j.Jsondata)[jdkey] == tmpv.Value {
  2622. extField := &ju.ExtField{Code: "JsonData_" + jdkey + "_j.Result" + fmt.Sprint(tmpk), Field: jdkey, ExtFrom: "JsonData_" + jdkey + "_j.Result" + fmt.Sprint(tmpk), SourceValue: (*j.Jsondata)[jdkey], Value: tmpv.Value, Score: 100}
  2623. j.Result[jdkey] = append(j.Result[jdkey], extField)
  2624. ju.Sort(j.Result[jdkey])
  2625. delete((*j.Jsondata), jdkey)
  2626. break
  2627. }
  2628. }
  2629. }
  2630. }
  2631. }
  2632. if len(*j.Jsondata) > 0 {
  2633. j.Result = JsonDataMergeProcessing(j, e)
  2634. }
  2635. j.Jsondata = &tmpjddata
  2636. }
  2637. return doc, result, _id
  2638. }
  2639. //辅助信息,如果没有排序先排序
  2640. func auxInfo(j *ju.Job) map[string][]map[string]interface{} {
  2641. fieldalls := map[string][]map[string]interface{}{}
  2642. if j == nil {
  2643. return fieldalls
  2644. }
  2645. qykredis := redis.RedisPool[ju.QYK_RedisName].Get()
  2646. defer qykredis.Close()
  2647. db := 0
  2648. for field, val := range j.Result {
  2649. //ju.Sort(val)
  2650. if field == "buyer" {
  2651. db = ju.BuyerDB
  2652. } else if field == "winner" {
  2653. db = ju.WinnerDB
  2654. } else if field == "agency" {
  2655. db = ju.AgencyDB
  2656. }
  2657. sfields := []map[string]interface{}{}
  2658. for _, v := range val {
  2659. standardized := false
  2660. if _, err := qykredis.Do("SELECT", db); err != nil {
  2661. fmt.Println("redis select err", err)
  2662. } else {
  2663. rep, err := qykredis.Do("GET", v.Value)
  2664. if rep != nil && err == nil {
  2665. standardized = true
  2666. }
  2667. }
  2668. if field == "budget" || field == "bidamount" {
  2669. if !v.IsTrue {
  2670. continue
  2671. }
  2672. }
  2673. sfield := map[string]interface{}{
  2674. "val": v.Value,
  2675. "type": v.Type,
  2676. "score": v.Score,
  2677. "blocktag": v.BlockTag,
  2678. "sourceval": v.SourceValue,
  2679. "standardized": standardized,
  2680. }
  2681. sfields = append(sfields, sfield)
  2682. }
  2683. fieldalls[field] = sfields
  2684. }
  2685. return fieldalls
  2686. }
  2687. func (e *ExtractTask) QualityAudit(resulttmp map[string]interface{}) {
  2688. defer qu.Catch()
  2689. //获取审核字段
  2690. for _, field := range e.AuditFields {
  2691. //1.分包
  2692. if resulttmp["package"] != nil {
  2693. packagedata := resulttmp["package"].(map[string]map[string]interface{})
  2694. for _, val := range packagedata {
  2695. if val[field] != nil {
  2696. fv := qu.ObjToString(val[field])
  2697. if fv != "" {
  2698. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  2699. e.RedisMatch(field, fv, val) //redis匹配
  2700. } else { //除了buyer和winner,其他字段走规则匹配
  2701. e.RuleMatch(field, fv, val)
  2702. }
  2703. }
  2704. }
  2705. }
  2706. }
  2707. //2.外围
  2708. if resulttmp[field] != nil {
  2709. fv := qu.ObjToString(resulttmp[field])
  2710. if fv != "" {
  2711. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  2712. e.RedisMatch(field, fv, resulttmp) //redis匹配
  2713. } else { //除了buyer和winner,其他字段走规则匹配
  2714. e.RuleMatch(field, fv, resulttmp)
  2715. }
  2716. }
  2717. }
  2718. }
  2719. }
  2720. //Redis匹配
  2721. func (e *ExtractTask) RedisMatch(field, fv string, val map[string]interface{}) {
  2722. defer qu.Catch()
  2723. i := redis.GetInt(field, field+"_"+fv) //查找redis
  2724. if i == 0 { //reids未找到,执行规则匹配
  2725. val[field+"_isredis"] = false
  2726. e.RuleMatch(field, fv, val) //规则匹配
  2727. } else { //redis找到,打标识存库
  2728. val[field+"_isredis"] = true
  2729. }
  2730. }
  2731. //规则匹配
  2732. func (e *ExtractTask) RuleMatch(field, fieldval string, tmpMap map[string]interface{}) {
  2733. defer qu.Catch()
  2734. if fieldval != "" {
  2735. SMap := e.StartMatch(field, fieldval)
  2736. //SMap.AddKey(field+"_isaudit", false)
  2737. for _, k := range SMap.Keys {
  2738. tmpMap[k] = SMap.Map[k]
  2739. }
  2740. tmpMap[field+"_isaudit"] = false //添加字段未审核信息
  2741. }
  2742. }
  2743. //开始规则匹配
  2744. func (e *ExtractTask) StartMatch(field, text string) *pretreated.SortMap {
  2745. defer qu.Catch()
  2746. SMap := pretreated.NewSortMap()
  2747. lock.Lock()
  2748. f := e.RecogFieldMap[field]
  2749. lock.Unlock()
  2750. if len(f) > 0 {
  2751. fid := qu.BsonIdToSId(f["_id"])
  2752. recogFieldPreRule := qu.ObjToString(f["s_recogfield_prerule"])
  2753. textAfterRecogFieldPrerule := ju.PreFilter(text, recogFieldPreRule) //识别字段的前置过滤
  2754. if textAfterRecogFieldPrerule != "" {
  2755. lock.Lock()
  2756. classMap := e.FidClassMap[fid]
  2757. lock.Unlock()
  2758. L:
  2759. for _, c := range classMap { //class
  2760. classid := qu.BsonIdToSId(c["_id"])
  2761. classPrerule := qu.ObjToString(c["s_class_prerule"])
  2762. savefield := qu.ObjToString(c["s_savefield"]) //保存字段
  2763. textAfterClassPrerule := ju.PreFilter(textAfterRecogFieldPrerule, classPrerule) //class的前置过滤
  2764. if textAfterClassPrerule != "" {
  2765. lock.Lock()
  2766. ruleMap := e.CidRuleMap[classid]
  2767. lock.Unlock()
  2768. for _, r := range ruleMap { //rule
  2769. rulePrerule := qu.ObjToString(r["s_rule_prerule"])
  2770. s_name := qu.ObjToString(r["s_name"])
  2771. rule := r["rule"].([]interface{})
  2772. textAfterRulePrerule := ju.PreFilter(textAfterClassPrerule, rulePrerule) //class的前置过滤
  2773. if textAfterRulePrerule != "" {
  2774. b, _ := ju.RecogAnalyRules(textAfterRulePrerule, rule)
  2775. if b { //匹配到一个分类下某个规则时,不再继续匹配
  2776. if savefield != "" { //保存字段不为空,存储代码信息
  2777. SMap.AddKey(field+"_"+savefield, s_name)
  2778. }
  2779. break L
  2780. }
  2781. }
  2782. }
  2783. }
  2784. }
  2785. }
  2786. }
  2787. return SMap
  2788. }
  2789. //筛选重复候选人-相关
  2790. func filterRepeatWinArr(j *ju.Job) {
  2791. if j.SpiderCode=="sh_shszfhcxjsglwyh_jsgc_zhbhxrgs" {
  2792. sort_WinOrder_Arr := make([][]map[string]interface{},0)
  2793. sort_arr := make([]map[string]interface{},0)
  2794. for _,v := range j.Winnerorder{
  2795. sort := qu.IntAll(v["sort"])
  2796. if sort==1 { //为一组
  2797. if len(sort_arr)>0 {
  2798. sort_WinOrder_Arr = append(sort_WinOrder_Arr,sort_arr)
  2799. }
  2800. sort_arr = make([]map[string]interface{},0)
  2801. }
  2802. sort_arr = append(sort_arr,v)
  2803. }
  2804. if len(sort_arr)>0 {
  2805. sort_WinOrder_Arr = append(sort_WinOrder_Arr,sort_arr)
  2806. }
  2807. if len(sort_WinOrder_Arr)>0 { //有重复排序组-开始筛选清理
  2808. isIndex :=0
  2809. for index,winArr := range sort_WinOrder_Arr {
  2810. if len(winArr)>0 {
  2811. if qu.ObjToString(winArr[0]["price"])!=""&&
  2812. qu.ObjToString(winArr[0]["entname"])!="" {
  2813. isIndex = index
  2814. break
  2815. }
  2816. }
  2817. }
  2818. j.Winnerorder = sort_WinOrder_Arr[isIndex]
  2819. }
  2820. }
  2821. }
  2822. //中标候选人经过清理之后,重新取出赋值
  2823. func resetWinnerorder(j *ju.Job) {
  2824. if len(j.Winnerorder) == 0 {
  2825. return
  2826. }
  2827. maxlen := len(j.Winnerorder) - 1
  2828. //中标单位
  2829. //i := 0
  2830. winners := []*ju.ExtField{}
  2831. bidamounts := []*ju.ExtField{}
  2832. if maxlen > 0 {
  2833. //新增-指定爬虫中标候选人过滤
  2834. filterRepeatWinArr(j)
  2835. if qu.Float64All(j.Winnerorder[0]["sort"]) != 1 {
  2836. return
  2837. }
  2838. winners = append(winners, &ju.ExtField{Code: "winnerorder", Field: "winner", ExtFrom: "j.Winnerorder", Value: j.Winnerorder[0]["entname"], Score: 0.5})
  2839. if j.Winnerorder[0]["price"] != nil {
  2840. tmpPrice := clear.ObjToMoney([]interface{}{j.Winnerorder[0]["price"], ""}, j.SpiderCode, j.IsClearnMoney)
  2841. if tmpPrice[len(tmpPrice)-1].(bool) {
  2842. bidamounts = append(bidamounts, &ju.ExtField{Code: "winnerorder", Field: "bidamount", ExtFrom: "j.Winnerorder", SourceValue: j.Winnerorder[0]["price"], Value: tmpPrice[0], Score: 2.5, IsTrue: true})
  2843. }
  2844. }
  2845. }
  2846. if j.Result["winner"] == nil && len(winners) > 0 {
  2847. j.Result["winner"] = winners
  2848. } else if len(winners) > 0 {
  2849. j.Result["winner"] = append(j.Result["winner"], winners...)
  2850. }
  2851. if j.Result["bidamount"] == nil && len(bidamounts) > 0 {
  2852. j.Result["bidamount"] = bidamounts
  2853. } else if len(bidamounts) > 0 {
  2854. j.Result["bidamount"] = append(j.Result["bidamount"], bidamounts...)
  2855. }
  2856. if j.Result["winner"] == nil && len(j.Winnerorder) > 0 && qu.Float64All(j.Winnerorder[0]["sort"]) == 1 {
  2857. winners = append(winners, &ju.ExtField{Code: "winnerorder", Field: "winner", ExtFrom: "j.Winnerorder", Value: j.Winnerorder[0]["entname"], Score: 0.5})
  2858. j.Result["winner"] = winners
  2859. if j.Winnerorder[0]["price"] != nil {
  2860. tmpPrice := clear.ObjToMoney([]interface{}{j.Winnerorder[0]["price"], ""}, j.SpiderCode, j.IsClearnMoney)
  2861. if tmpPrice[len(tmpPrice)-1].(bool) {
  2862. bidamounts = append(bidamounts, &ju.ExtField{Code: "winnerorder", Field: "bidamount", ExtFrom: "j.Winnerorder", SourceValue: j.Winnerorder[0]["price"], Value: tmpPrice[0], Score: 2.5, IsTrue: true})
  2863. }
  2864. j.Result["bidamount"] = bidamounts
  2865. }
  2866. }
  2867. }
  2868. func RemoveReplicaSliceString(slc []string) []string {
  2869. result := make([]string, 0)
  2870. tempMap := make(map[string]bool, len(slc))
  2871. for _, e := range slc {
  2872. if tempMap[e] == false {
  2873. tempMap[e] = true
  2874. result = append(result, e)
  2875. }
  2876. }
  2877. return result
  2878. }
  2879. type scoreIndex struct {
  2880. Score float64
  2881. Index int
  2882. }