extract.go 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914
  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. }
  547. }
  548. if len(j.Winnerorder) == 0 && jf.Winnerorder != nil && len(jf.Winnerorder) > 0 {
  549. j.Winnerorder = append(j.Winnerorder, jf.Winnerorder...)
  550. }
  551. }
  552. if isSite {
  553. ismerge, ok := e.SiteMerge.Load(j.SpiderCode)
  554. if ok && ismerge.(bool) {
  555. tmpj := &ju.Job{
  556. SourceMid: j.SourceMid,
  557. Category: j.Category,
  558. CategorySecond: j.CategorySecond,
  559. Content: j.Content,
  560. SpiderCode: j.SpiderCode,
  561. //Domain: qu.ObjToString(doc["domain"]),
  562. //Href: qu.ObjToString(doc["href"]),
  563. Title: j.Title,
  564. Data: j.Data,
  565. City: j.City,
  566. Province: j.Province,
  567. Jsondata: j.Jsondata,
  568. Result: map[string][]*ju.ExtField{},
  569. BuyerAddr: j.BuyerAddr,
  570. RuleBlock: e.RuleBlock,
  571. }
  572. qu.Try(func() {
  573. pretreated.AnalyStart(tmpj, false, "") //job.Block分块
  574. }, func(err interface{}) {
  575. log.Debug("pretreated.AnalyStart.ExtractProcess", err, j.SourceMid)
  576. })
  577. e.ExtractDetail(tmpj, false, "")
  578. //if jf != nil && jf.IsFile {
  579. // e.ExtractFile(jf, false, "")
  580. //}
  581. //合并数据
  582. j.Block = append(j.Block, tmpj.Block...)
  583. j.Winnerorder = append(j.Winnerorder, tmpj.Winnerorder...)
  584. for tmpk, _ := range j.Result {
  585. if len(tmpj.Result[tmpk]) > 0 {
  586. j.Result[tmpk] = append(j.Result[tmpk], tmpj.Result[tmpk]...)
  587. }
  588. }
  589. for tmpk, _ := range tmpj.Result {
  590. if len(j.Result[tmpk]) == 0 {
  591. j.Result[tmpk] = append(j.Result[tmpk], tmpj.Result[tmpk]...)
  592. }
  593. }
  594. }
  595. }
  596. //分析抽取结果并保存
  597. AnalysisSaveResult(j, jf, e)
  598. <-e.TaskInfo.ProcessPool
  599. }
  600. //抽取-正文-规则等 detail
  601. func (e *ExtractTask) ExtractDetail(j *ju.Job, isSite bool, codeSite string) {
  602. qu.Try(func() {
  603. doc := *j.Data
  604. //全局前置规则,结果覆盖doc属性
  605. //for _, v := range e.RulePres {
  606. // doc = ExtRegPre(doc, j, v, e.TaskInfo)
  607. //}
  608. tmprules := map[string][]*RuleCore{}
  609. lockrule.Lock()
  610. //加载分类抽取配置
  611. if j.Category == "all" || j.CategorySecond == "all" {
  612. if isSite {
  613. for k, vc1 := range e.SiteRuleCores["all_all"] {
  614. tmprules[k] = vc1
  615. }
  616. } else {
  617. for k, vc1 := range e.RuleCores["all_all"] {
  618. tmprules[k] = vc1
  619. }
  620. }
  621. } else {
  622. if isSite {
  623. for k, vc1 := range e.SiteRuleCores[j.Category+"_"+j.CategorySecond] {
  624. tmprules[k] = vc1
  625. }
  626. } else {
  627. for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
  628. tmprules[k] = vc1
  629. }
  630. }
  631. }
  632. if len(tmprules) < 1 { //分类未覆盖部分
  633. if isSite {
  634. for k, vc1 := range e.RuleCores["all_all"] {
  635. tmprules[k] = vc1
  636. }
  637. } else {
  638. for k, vc1 := range e.SiteRuleCores["all_all"] {
  639. tmprules[k] = vc1
  640. }
  641. }
  642. }
  643. lockrule.Unlock()
  644. //抽取规则
  645. for _, vc1 := range tmprules {
  646. for _, vc := range vc1 {
  647. tmp := ju.DeepCopy(doc).(map[string]interface{})
  648. //是否进入逻辑
  649. if !ju.Logic(vc.LuaLogic, tmp) {
  650. continue
  651. }
  652. if vc.Field =="winner" {
  653. //log.Debug("调试抽取字段")
  654. }
  655. ////抽取-前置规则
  656. //for _, v := range vc.RulePres {
  657. // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
  658. //}
  659. // log.Debug("抽取-前置规则", tmp)
  660. //抽取-规则
  661. ExtRuleCore(tmp, e, vc, j, isSite)
  662. // log.Debug("抽取-规则", tmp)
  663. //抽取-后置规则
  664. for _, v := range vc.RuleBacks {
  665. ExtRegBack(j, v, e.TaskInfo, vc)
  666. }
  667. //kv规则
  668. for _, v := range vc.KVRuleCores {
  669. ExtRuleKV(j, v, e.TaskInfo)
  670. }
  671. // log.Debug("抽取-后置规则", tmp)
  672. //项目名称未能抽取到,标题来凑
  673. if vc.Field == "projectname" {
  674. if vc.ExtFrom == "title" {
  675. isextitle := true
  676. for _, v := range j.Result[vc.Field] {
  677. if len([]rune(qu.ObjToString(v.Value))) > 5 {
  678. isextitle = false
  679. break
  680. }
  681. }
  682. if isextitle { //标题加入选举
  683. 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}
  684. if isSite {
  685. field.Score = 1
  686. }
  687. j.Result[vc.Field] = append(j.Result[vc.Field], field)
  688. }
  689. }
  690. for i := 0; i < 3; i++ {
  691. for _, v := range vc.RuleBacks {
  692. ExtRegBack(j, v, e.TaskInfo, vc)
  693. }
  694. }
  695. }
  696. }
  697. }
  698. //全局后置规则
  699. if isSite {
  700. for _, v := range e.SiteRuleBacks {
  701. ExtRegBack(j, v, e.TaskInfo, nil)
  702. }
  703. } else {
  704. for _, v := range e.RuleBacks {
  705. ExtRegBack(j, v, e.TaskInfo, nil)
  706. }
  707. }
  708. //函数清理
  709. for key, val := range j.Result {
  710. for i, v := range val {
  711. if v.Field == "projectname" && v.Type == "table" {
  712. break
  713. }
  714. if key == "budget" || key == "bidamount" {
  715. if _, ok := v.Value.(float64); ok && !v.IsTrue {
  716. continue
  717. }
  718. }
  719. lockclear.Lock()
  720. var cfn = []string{}
  721. if isSite {
  722. cfn = e.SiteClearFn[key]
  723. if len(cfn) == 0 {
  724. cfn = e.ClearFn[key]
  725. }
  726. } else {
  727. cfn = e.ClearFn[key]
  728. }
  729. lockclear.Unlock()
  730. if len(cfn) == 0 {
  731. continue
  732. }
  733. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content}, j.SpiderCode, j.IsClearnMoney)
  734. if key == "budget" || key == "bidamount" {
  735. if istrue, ok := data[len(data)-1].(bool); istrue && ok {
  736. j.Result[key][i].IsTrue = true
  737. } else {
  738. j.Result[key][i].Value = data[0]
  739. continue
  740. }
  741. }
  742. before, _ := v.Value.(string)
  743. v.Value = data[0]
  744. BeforeAddClearFnLog(strings.Join(cfn, ","), "函数清理"+strings.Join(cfn, ","), j.SourceMid, before, v.MatchType, v, e)
  745. //添加行数清理的日志
  746. //清理特殊符号
  747. lockclear.Lock()
  748. if clear.AsyField[key] != nil || clear.SymField[key] != nil || clear.MesField[key] != nil {
  749. text := qu.ObjToString(v.Value)
  750. before = text
  751. v.Value = clear.OtherClean(key, text)
  752. BeforeAddClearFnLog("clear.OtherClean", "特殊符号清理clear.OtherClean", j.SourceMid, before, v.MatchType, v, e)
  753. }
  754. //AddClearFnLog("clearfn", j.SourceMid, v.Value, extinfo, v.Code, "函数清理", key, e.TaskInfo)
  755. lockclear.Unlock()
  756. }
  757. }
  758. PackageDetail(j, e, isSite, codeSite) //处理分包信息-去重
  759. // bs, _ := json.Marshal(j.Result)
  760. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  761. }, func(err interface{}) {
  762. log.Debug("ExtractProcess err", err, j.SourceMid)
  763. })
  764. }
  765. func (e *ExtractTask) ExtractFile(j *ju.Job, isSite bool, codeSite string) {
  766. qu.Try(func() {
  767. doc := *j.Data
  768. //全局前置规则,结果覆盖doc属性
  769. // for _, v := range e.RulePres {
  770. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  771. // doc = ExtRegPre(doc, j, v, e.TaskInfo)
  772. // }
  773. // }
  774. //抽取规则
  775. tmprules := map[string][]*RuleCore{}
  776. lockrule.Lock()
  777. if j.Category == "all" || j.CategorySecond == "all" {
  778. for k, vc1 := range e.RuleCores["all_all"] {
  779. tmprules[k] = vc1
  780. }
  781. } else {
  782. for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
  783. tmprules[k] = vc1
  784. }
  785. }
  786. lockrule.Unlock()
  787. for _, vc1 := range tmprules {
  788. for _, vc := range vc1 {
  789. tmp := ju.DeepCopy(doc).(map[string]interface{})
  790. //是否进入逻辑
  791. if !ju.Logic(vc.LuaLogic, tmp) {
  792. continue
  793. }
  794. //抽取-前置规则
  795. // for _, v := range vc.RulePres {
  796. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  797. // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
  798. // }
  799. // }
  800. // log.Debug("抽取-前置规则", tmp)
  801. //抽取-规则
  802. if value, ok := e.FileFields.Load(vc.Field); ok && qu.IntAllDef(value, 1) > 0 {
  803. ExtRuleCore(tmp, e, vc, j, isSite)
  804. }
  805. // log.Debug("抽取-规则", tmp)
  806. //抽取-后置规则
  807. for _, v := range vc.RuleBacks {
  808. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  809. ExtRegBack(j, v, e.TaskInfo, vc)
  810. }
  811. }
  812. // log.Debug("抽取-后置规则", tmp)
  813. }
  814. }
  815. //全局后置规则
  816. for _, v := range e.RuleBacks {
  817. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  818. ExtRegBack(j, v, e.TaskInfo, nil)
  819. }
  820. }
  821. //函数清理
  822. for key, val := range j.Result {
  823. for _, v := range val {
  824. lockclear.Lock()
  825. var cfn = []string{}
  826. if isSite {
  827. cfn = e.SiteClearFn[key]
  828. if len(cfn) == 0 {
  829. cfn = e.ClearFn[key]
  830. }
  831. } else {
  832. cfn = e.ClearFn[key]
  833. }
  834. lockclear.Unlock()
  835. if len(cfn) == 0 {
  836. continue
  837. }
  838. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content}, j.SpiderCode, j.IsClearnMoney)
  839. v.Value = data[0]
  840. //清理特殊符号
  841. lockclear.Lock()
  842. if clear.AsyField[key] != nil || clear.SymField[key] != nil ||
  843. clear.MesField[key] != nil {
  844. text := qu.ObjToString(v.Value)
  845. text = clear.OtherClean(key, text)
  846. v.Value = text
  847. }
  848. lockclear.Unlock()
  849. }
  850. }
  851. PackageDetail(j, e, isSite, codeSite) //处理分包信息
  852. // bs, _ := json.Marshal(j.Result)
  853. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  854. }, func(err interface{}) {
  855. log.Debug("ExtractProcess err", err)
  856. })
  857. }
  858. //前置过滤
  859. func ExtRegPre(doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, t *TaskInfo) map[string]interface{} {
  860. defer qu.Catch()
  861. before := ju.DeepCopy(doc).(map[string]interface{})
  862. extinfo := map[string]interface{}{}
  863. if in.IsLua {
  864. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  865. if j != nil {
  866. lua.Block = j.Block
  867. }
  868. extinfo = lua.RunScript("pre")
  869. for k, v := range extinfo { //结果覆盖原doc
  870. doc[k] = v
  871. }
  872. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  873. } else {
  874. var key string
  875. if !j.IsFile {
  876. key = qu.If(in.Field == "", "detail", in.Field).(string)
  877. } else {
  878. key = qu.If(in.Field == "", "detailfile", in.Field).(string)
  879. }
  880. text := qu.ObjToString(doc[key])
  881. extinfo[key] = in.RegPreBac.Reg.ReplaceAllString(text, "")
  882. doc[key] = extinfo[key] //结果覆盖原doc
  883. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  884. }
  885. return doc
  886. }
  887. //抽取-规则
  888. func ExtRuleCore(doc map[string]interface{}, e *ExtractTask, vc *RuleCore, j *ju.Job, isSite bool) {
  889. //候选人加入
  890. var kvMap map[string][]map[string]interface{}
  891. extByReg := true
  892. if vc.ExtFrom != "title" {
  893. kvMap, extByReg = getKvByLuaFields(vc, j, e)
  894. }
  895. for _, v := range vc.RuleCores {
  896. if v.IsLua {
  897. ExtRuleCoreByKv(vc.ExtFrom, doc, j, v, &kvMap, e)
  898. } else if extByReg {
  899. ExtRuleCoreByReg(vc.ExtFrom, doc, j, v, e, isSite)
  900. }
  901. }
  902. //如果只有一个分包,预算没有抽取到,把分包中的预算保存到外面
  903. if vc.Field == "budget" && len(kvMap) == 0 {
  904. if len(j.BlockPackage) == 1 {
  905. for _, bp := range j.BlockPackage {
  906. for fieldname, field := range vc.LFields {
  907. if field != vc.Field {
  908. continue
  909. }
  910. tp := ""
  911. for k, v := range []*ju.JobKv{bp.ColonKV, bp.SpaceKV, bp.TableKV} {
  912. if k == 0 {
  913. tp = "colon"
  914. } else if k == 1 {
  915. tp = "space"
  916. } else if k == 2 {
  917. tp = "table"
  918. }
  919. if v == nil || v.KvTags == nil {
  920. continue
  921. }
  922. for _, vv := range v.KvTags[fieldname] {
  923. text := ju.TrimLRSpace(vv.Value, "")
  924. if text != "" {
  925. tmp := &ju.ExtField{
  926. ExtFrom: "package",
  927. Field: vc.Field,
  928. Code: "CL_分包",
  929. Type: tp,
  930. MatchType: "package",
  931. RuleText: bp.Text,
  932. SourceValue: vv.Key,
  933. Value: text,
  934. }
  935. if isSite {
  936. tmp.Score = 1
  937. }
  938. j.Result[vc.Field] = append(j.Result[vc.Field], tmp)
  939. }
  940. }
  941. }
  942. }
  943. break
  944. }
  945. }
  946. } else {
  947. for k, v := range kvMap {
  948. if j.Result[k] == nil {
  949. j.Result[k] = [](*ju.ExtField){}
  950. }
  951. for _, tmp := range v {
  952. field := &ju.ExtField{Weight: qu.IntAll(tmp["weight"]),
  953. ExtFrom: qu.ObjToString(tmp["extfrom"]), Field: k,
  954. Code: qu.ObjToString(tmp["code"]), Type: qu.ObjToString(tmp["type"]),
  955. MatchType: qu.ObjToString(tmp["matchtype"]),
  956. RuleText: qu.ObjToString(tmp["ruletext"]),
  957. SourceValue: tmp["sourcevalue"],
  958. Value: tmp["value"]}
  959. if k == "bidamount" && field.ExtFrom == "第一候选人" {
  960. field.Score = 1
  961. }
  962. if isSite {
  963. field.Score = 1
  964. }
  965. if (field.Field == "bidamount" || field.Field == "budget") && field.Type == "table" {
  966. moneys := clear.ObjToMoney([]interface{}{field.Value, ""}, j.SpiderCode, j.IsClearnMoney)
  967. if len(moneys) > 0 {
  968. if vf, ok := moneys[0].(float64); ok {
  969. field.Value = vf
  970. field.IsTrue = moneys[len(moneys)-1].(bool)
  971. } else if vi, ok := moneys[0].(int); ok {
  972. field.Value = float64(vi)
  973. field.IsTrue = moneys[len(moneys)-1].(bool)
  974. }
  975. }
  976. }
  977. if tmp["blocktag"] != nil {
  978. btag := make(map[string]string)
  979. for k := range tmp["blocktag"].(map[string]bool) {
  980. blocktag.Lock()
  981. if TagConfigDesc[k] != "" {
  982. btag[k] = TagConfigDesc[k]
  983. }
  984. blocktag.Unlock()
  985. }
  986. field.BlockTag = btag
  987. }
  988. j.Result[k] = append(j.Result[k], field)
  989. }
  990. }
  991. }
  992. }
  993. //抽取-规则-kv
  994. func ExtRuleCoreByKv(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, kvMap *map[string][]map[string]interface{}, et *ExtractTask) {
  995. defer qu.Catch()
  996. if extfrom == "title" || !in.IsLua {
  997. return
  998. }
  999. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  1000. lua.KvMap = *kvMap
  1001. lua.Block = j.Block
  1002. extinfo := lua.RunScript("core")
  1003. if tmps, ok := extinfo[in.Field].([]map[string]interface{}); ok {
  1004. for _, v := range tmps {
  1005. v["core"] = in.Code
  1006. }
  1007. (*kvMap)[in.Field] = append((*kvMap)[in.Field], tmps...)
  1008. }
  1009. if len(extinfo) > 0 {
  1010. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1011. }
  1012. }
  1013. //抽取-规则-正则
  1014. func ExtRuleCoreByReg(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, et *ExtractTask, isSite bool) {
  1015. defer qu.Catch()
  1016. //根据field配置项目,是否抽取。例如:废标、流标等跳过,
  1017. b := IsExtract(in.Field, j.Title, j.Content)
  1018. if !b {
  1019. return
  1020. }
  1021. //全文正则
  1022. //text := qu.ObjToString(doc[extfrom])
  1023. //if in.Field != "" {
  1024. // extinfo := extRegCoreToResult(extfrom, text, j, in)
  1025. // if len(extinfo) > 0 {
  1026. // AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1027. // }
  1028. //}
  1029. //块抽取
  1030. if in.Field != "" {
  1031. if extfrom == "title" {
  1032. extinfo := extRegCoreToResult(extfrom, qu.ObjToString(doc[extfrom]), &map[string]string{}, j, in, isSite)
  1033. if len(extinfo) > 0 {
  1034. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1035. }
  1036. } else if in.Field == "qualifies" {
  1037. extinfo := extRegCoreToResult(extfrom, pretreated.HtmlToText(qu.ObjToString(doc[extfrom])), &map[string]string{}, j, in, isSite)
  1038. if len(extinfo) > 0 {
  1039. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1040. }
  1041. } else {
  1042. for _, v := range j.Block {
  1043. btag := make(map[string]string)
  1044. for k := range v.Classify {
  1045. blocktag.Lock()
  1046. btag[k] = TagConfigDesc[k]
  1047. blocktag.Unlock()
  1048. }
  1049. extinfo := extRegCoreToResult(extfrom, v.Text, &btag, j, in, isSite)
  1050. if len(extinfo) > 0 {
  1051. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  1052. }
  1053. }
  1054. }
  1055. }
  1056. }
  1057. //pkg抽取-规则-正则
  1058. func ExtRuleCoreByPkgReg(j *ju.Job, in *RegLuaInfo, e *ExtractTask) {
  1059. defer qu.Catch()
  1060. //根据field配置项目,是否抽取。例如:废标、流标等跳过,
  1061. b := IsExtract(in.Field, j.Title, j.Content)
  1062. if !b {
  1063. return
  1064. }
  1065. //块抽取
  1066. if in.Field != "" {
  1067. for k, vbpkg := range j.BlockPackage {
  1068. rep := map[string]string{}
  1069. if in.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
  1070. if in.Field == "budget" && vbpkg.Budget > 0 {
  1071. continue
  1072. }
  1073. if in.Field == "agencyfee" && vbpkg.Agencyfee > 0 {
  1074. continue
  1075. }
  1076. if in.Field == "bidamount" && vbpkg.Bidamount > 0 {
  1077. continue
  1078. }
  1079. if in.Field == "winner" && vbpkg.Winner != "" {
  1080. continue
  1081. }
  1082. if in.Field == "bidstatus" && vbpkg.BidStatus != "" {
  1083. continue
  1084. }
  1085. if in.Field == "projectname" && vbpkg.Name != "" {
  1086. continue
  1087. }
  1088. if in.Field == "winner" && vbpkg.Winner != "" {
  1089. continue
  1090. }
  1091. if in.Field == "winnerperson" {
  1092. if vbpkg.Winner == "" || len(vbpkg.Winner) < 4 {
  1093. continue
  1094. }
  1095. if !strings.Contains(vbpkg.Text, vbpkg.Winner) {
  1096. continue
  1097. }
  1098. }
  1099. if in.Field == "winnertel" {
  1100. if vbpkg.WinnerPerson == "" {
  1101. continue
  1102. }
  1103. }
  1104. //处理正负数修正
  1105. ptmp := strings.Split(in.RuleText, "#")
  1106. sign := 0
  1107. if len(ptmp) == 2 {
  1108. if ptmp[1] == "正" {
  1109. sign = 1
  1110. } else if ptmp[1] == "负" {
  1111. sign = -1
  1112. }
  1113. }
  1114. tmp := strings.Split(ptmp[0], "__")
  1115. if len(tmp) == 2 {
  1116. epos := strings.Split(tmp[1], ",")
  1117. posm := map[string]int{}
  1118. for _, v := range epos {
  1119. ks := strings.Split(v, ":")
  1120. if len(ks) == 2 { //(.*)招标公告(.*)__2:projectname,4:area
  1121. posm[ks[1]] = qu.IntAll(ks[0])
  1122. } else {
  1123. posm[in.Field] = qu.IntAll(ks[0])
  1124. }
  1125. }
  1126. var pattern string
  1127. if strings.Contains(tmp[0], "\\u") {
  1128. tmp[0] = strings.Replace(tmp[0], "\\", "\\\\", -1)
  1129. tmp[0] = strings.Replace(tmp[0], "\\\\u", "\\u", -1)
  1130. pattern, _ = strconv.Unquote(`"` + tmp[0] + `"`)
  1131. } else {
  1132. pattern = tmp[0]
  1133. }
  1134. //log.Debug("pattern", pattern)
  1135. //fmt.Println(text)
  1136. reg := regexp.MustCompile(pattern)
  1137. apos := reg.FindAllStringSubmatchIndex(vbpkg.Text, -1)
  1138. for i, _ := range apos {
  1139. pos := apos[i]
  1140. for k, p := range posm {
  1141. if len(pos) > p {
  1142. if pos[p] == -1 || pos[p+1] == -1 {
  1143. continue
  1144. }
  1145. val := vbpkg.Text[pos[p]:pos[p+1]]
  1146. if string(val) == "" {
  1147. continue
  1148. }
  1149. if sign == -1 {
  1150. rep[k+"_"+fmt.Sprint(i)] = "-" + val
  1151. } else {
  1152. rep[k+"_"+fmt.Sprint(i)] = val
  1153. }
  1154. }
  1155. }
  1156. }
  1157. //fmt.Println(text)
  1158. for i := 0; i < len(apos); i++ {
  1159. if strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]) != "" {
  1160. if in.Field == "budget" && vbpkg.Budget <= 0 {
  1161. lock.Lock()
  1162. cfn := e.ClearFn[in.Field]
  1163. lock.Unlock()
  1164. data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content}, j.SpiderCode, j.IsClearnMoney)
  1165. if data[len(data)-1].(bool) {
  1166. j.BlockPackage[k].Budget = qu.Float64All(data[0])
  1167. j.BlockPackage[k].IsTrueBudget = true
  1168. }
  1169. break
  1170. } else if in.Field == "agencyfee" && vbpkg.Agencyfee <= 0 {
  1171. lock.Lock()
  1172. cfn := e.ClearFn[in.Field]
  1173. lock.Unlock()
  1174. data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content}, j.SpiderCode, j.IsClearnMoney)
  1175. if data[len(data)-1].(bool) {
  1176. j.BlockPackage[k].Agencyfee = qu.Float64All(data[0])
  1177. j.BlockPackage[k].IsTrueAgencyfee = true
  1178. }
  1179. break
  1180. }else if in.Field == "bidamount" && vbpkg.Bidamount <= 0 {
  1181. lock.Lock()
  1182. cfn := e.ClearFn[in.Field]
  1183. lock.Unlock()
  1184. data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content}, j.SpiderCode, j.IsClearnMoney)
  1185. if data[len(data)-1].(bool) {
  1186. j.BlockPackage[k].Bidamount = qu.Float64All(data[0])
  1187. j.BlockPackage[k].IsTrueBidamount = true
  1188. }
  1189. break
  1190. } else if in.Field == "winner" {
  1191. if j.BlockPackage[k].Winner == "" {
  1192. j.BlockPackage[k].Winner = rep[in.Field+"_"+fmt.Sprint(i)]
  1193. break
  1194. }
  1195. } else if in.Field == "winnertel" {
  1196. if j.BlockPackage[k].WinnerTel == "" {
  1197. j.BlockPackage[k].WinnerTel = rep[in.Field+"_"+fmt.Sprint(i)]
  1198. break
  1199. }
  1200. } else if in.Field == "winnerperson" {
  1201. if j.BlockPackage[k].WinnerPerson == "" {
  1202. j.BlockPackage[k].WinnerPerson = rep[in.Field+"_"+fmt.Sprint(i)]
  1203. break
  1204. }
  1205. } else if in.Field == "bidstatus" {
  1206. if j.BlockPackage[k].BidStatus == "" {
  1207. j.BlockPackage[k].BidStatus = rep[in.Field+"_"+fmt.Sprint(i)]
  1208. break
  1209. }
  1210. } else if in.Field == "projectname" {
  1211. if j.BlockPackage[k].Name == "" {
  1212. j.BlockPackage[k].Name = rep[in.Field+"_"+fmt.Sprint(i)]
  1213. break
  1214. }
  1215. } else if in.Field == "winnerperson" {
  1216. if j.BlockPackage[k].WinnerPerson == "" {
  1217. j.BlockPackage[k].WinnerPerson = rep[in.Field+"_"+fmt.Sprint(i)]
  1218. break
  1219. }
  1220. } else if in.Field == "winnertel" {
  1221. if j.BlockPackage[k].WinnerTel == "" && j.BlockPackage[k].Winner != "" && j.BlockPackage[k].WinnerPerson != "" {
  1222. j.BlockPackage[k].WinnerTel = rep[in.Field+"_"+fmt.Sprint(i)]
  1223. break
  1224. }
  1225. }
  1226. }
  1227. }
  1228. }
  1229. } else {
  1230. pos := in.RegCore.Reg.FindStringIndex(vbpkg.Text)
  1231. val := ""
  1232. if len(pos) == 2 {
  1233. //"text" = "text"[pos[1]:]
  1234. val = "text"[pos[1]:]
  1235. rs := regexp.MustCompile("[^\r\n\t]+")
  1236. tmp := rs.FindAllString("text", -1)
  1237. if len(tmp) > 0 {
  1238. val = tmp[0]
  1239. }
  1240. }
  1241. if val != "" {
  1242. if in.Field == "budget" && vbpkg.Budget <= 0 {
  1243. lock.Lock()
  1244. cfn := e.ClearFn[in.Field]
  1245. lock.Unlock()
  1246. data := clear.DoClearFn(cfn, []interface{}{val, j.Content}, j.SpiderCode, j.IsClearnMoney)
  1247. if data[len(data)-1].(bool) {
  1248. j.BlockPackage[k].Budget = qu.Float64All(data[0])
  1249. j.BlockPackage[k].IsTrueBudget = true
  1250. }
  1251. break
  1252. }
  1253. if in.Field == "bidamount" && vbpkg.Bidamount <= 0 {
  1254. lock.Lock()
  1255. cfn := e.ClearFn[in.Field]
  1256. lock.Unlock()
  1257. data := clear.DoClearFn(cfn, []interface{}{val, j.Content}, j.SpiderCode, j.IsClearnMoney)
  1258. if data[len(data)-1].(bool) {
  1259. j.BlockPackage[k].Bidamount = qu.Float64All(data[0])
  1260. j.BlockPackage[k].IsTrueBidamount = true
  1261. }
  1262. break
  1263. } else if in.Field == "bidstatus" {
  1264. if j.BlockPackage[k].BidStatus == "" {
  1265. j.BlockPackage[k].BidStatus = val
  1266. break
  1267. }
  1268. } else if in.Field == "projectname" {
  1269. if j.BlockPackage[k].Name == "" {
  1270. j.BlockPackage[k].Name = val
  1271. break
  1272. }
  1273. }
  1274. }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. //lua脚本根据属性设置提取kv值
  1280. func getKvByLuaFields(vc *RuleCore, j *ju.Job, et *ExtractTask) (map[string][]map[string]interface{}, bool) {
  1281. kvmap := map[string][]map[string]interface{}{}
  1282. if len(j.Winnerorder) > 1 && qu.Float64All(j.Winnerorder[0]["sort"]) == 1 {
  1283. if vc.Field == "bidamount" {
  1284. for _, v := range j.Winnerorder {
  1285. if v["price"] == nil {
  1286. continue
  1287. }
  1288. kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
  1289. "code": "winnerorder",
  1290. "field": vc.Field,
  1291. "ruletext": "中标候选人_" + fmt.Sprint(v["sortstr"]),
  1292. "extfrom": v["sortstr"],
  1293. "sourcevalue": v["price"],
  1294. "value": v["price"],
  1295. "type": "winnerorder",
  1296. "matchtype": "winnerorder",
  1297. })
  1298. return kvmap, false
  1299. }
  1300. //候选人中标金额
  1301. if price := j.Winnerorder[0]["price"]; price != nil {
  1302. kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
  1303. "code": "CL_中标候选人",
  1304. "field": vc.Field,
  1305. "ruletext": "中标候选人",
  1306. "extfrom": j.Winnerorder[0]["sortstr"],
  1307. "sourcevalue": price,
  1308. "value": price,
  1309. "type": "winnerorder",
  1310. "matchtype": "winnerorder",
  1311. })
  1312. return kvmap, false
  1313. }
  1314. }
  1315. }
  1316. for fieldname, field := range vc.LFields {
  1317. if field != vc.Field {
  1318. continue
  1319. }
  1320. extractFromKv(field, fieldname, j.Block, vc, kvmap, j.Category)
  1321. }
  1322. AddExtLog("extract", j.SourceMid, nil, kvmap, &RegLuaInfo{Field: vc.Field}, et.TaskInfo) //抽取日志
  1323. return kvmap, true
  1324. }
  1325. func extractFromKv(field, fieldname string, blocks []*ju.Block, vc *RuleCore, kvmap map[string][]map[string]interface{}, Category string) {
  1326. //qu.Debug("fieldname+++", fieldname)
  1327. for _, bl := range blocks {
  1328. tp := ""
  1329. if strings.Contains(bl.Title, "保证金") && (field == "bid_bond" || field == "contract_bond") {
  1330. if text := ju.TrimLRSpace(bl.Text, ""); text != "" {
  1331. if Category == "招标" || Category == "拟建" || Category == "预告" {
  1332. kvmap[field] = append(kvmap[field], map[string]interface{}{
  1333. "code": "CL_块内容",
  1334. "field": field,
  1335. "ruletext": "投标保证金",
  1336. "extfrom": "投标保证金_块内容",
  1337. "sourcevalue": bl.Text,
  1338. "value": text,
  1339. "type": "投标保证金_块内容",
  1340. "matchtype": "tag_string",
  1341. "blocktag": bl.Classify,
  1342. "weight": 0,
  1343. })
  1344. } else if Category == "结果" {
  1345. kvmap[field] = append(kvmap[field], map[string]interface{}{
  1346. "code": "CL_",
  1347. "field": field,
  1348. "ruletext": "履约保证金",
  1349. "extfrom": "履约保证金_块内容",
  1350. "sourcevalue": bl.Text,
  1351. "value": text,
  1352. "type": "履约保证金_块内容",
  1353. "matchtype": "tag_string",
  1354. "blocktag": bl.Classify,
  1355. "weight": 0,
  1356. })
  1357. }
  1358. }
  1359. return
  1360. }
  1361. for k, v := range []*ju.JobKv{bl.ColonKV, bl.SpaceKV, bl.TableKV} {
  1362. if k == 0 {
  1363. tp = "colon"
  1364. } else if k == 1 {
  1365. tp = "space"
  1366. } else if k == 2 {
  1367. tp = "table"
  1368. }
  1369. if v == nil || v.KvTags == nil {
  1370. continue
  1371. }
  1372. for _, vv := range v.KvTags[fieldname] {
  1373. text := ju.TrimLRSpace(vv.Value, "")
  1374. if text != "" {
  1375. kvmap[field] = append(kvmap[field], map[string]interface{}{
  1376. "code": "CL_" + vv.Key,
  1377. "field": field,
  1378. "ruletext": vv.Key,
  1379. "extfrom": vc.ExtFrom,
  1380. "sourcevalue": text,
  1381. "value": text,
  1382. "type": tp,
  1383. "matchtype": "tag_string",
  1384. "blocktag": bl.Classify,
  1385. "weight": vv.Weight,
  1386. })
  1387. //if field != "winnertel" && field != "winnerperson" {
  1388. // //break //暂定取第一个
  1389. //}
  1390. }
  1391. }
  1392. }
  1393. if len(kvmap[field]) == 0 {
  1394. extractFromKv(field, fieldname, bl.Block, vc, kvmap, Category)
  1395. }
  1396. }
  1397. }
  1398. //正则提取结果
  1399. func extRegCoreToResult(extfrom, text string, tag *map[string]string, j *ju.Job, vre *RegLuaInfo, isSite bool) map[string][]map[string]interface{} {
  1400. defer qu.Catch()
  1401. var score float64
  1402. score = vre.Score
  1403. if isSite {
  1404. score = score + 1.0
  1405. }
  1406. extinfo := map[string][]map[string]interface{}{}
  1407. rep := map[string]string{}
  1408. if vre.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
  1409. //处理正负数修正
  1410. ptmp := strings.Split(vre.RuleText, "#")
  1411. sign := 0
  1412. if len(ptmp) == 2 {
  1413. if ptmp[1] == "正" {
  1414. sign = 1
  1415. } else if ptmp[1] == "负" {
  1416. sign = -1
  1417. }
  1418. }
  1419. tmp := strings.Split(ptmp[0], "__")
  1420. if len(tmp) == 2 {
  1421. epos := strings.Split(tmp[1], ",")
  1422. posm := map[string]int{}
  1423. for _, v := range epos {
  1424. ks := strings.Split(v, ":")
  1425. if len(ks) == 2 { //(.*)招标公告(.*)__2:projectname,4:area
  1426. posm[ks[1]] = qu.IntAll(ks[0])
  1427. } else {
  1428. posm[vre.Field] = qu.IntAll(ks[0])
  1429. }
  1430. }
  1431. var pattern string
  1432. if strings.Contains(tmp[0], "\\u") {
  1433. tmp[0] = strings.Replace(tmp[0], "\\", "\\\\", -1)
  1434. tmp[0] = strings.Replace(tmp[0], "\\\\u", "\\u", -1)
  1435. pattern, _ = strconv.Unquote(`"` + tmp[0] + `"`)
  1436. } else {
  1437. pattern = tmp[0]
  1438. }
  1439. //log.Debug("pattern", pattern)
  1440. //fmt.Println(text)
  1441. reg := regexp.MustCompile(pattern)
  1442. apos := reg.FindAllStringSubmatchIndex(text, -1)
  1443. for i, _ := range apos {
  1444. pos := apos[i]
  1445. for k, p := range posm {
  1446. if len(pos) > p {
  1447. if pos[p] == -1 || pos[p+1] == -1 {
  1448. continue
  1449. }
  1450. val := text[pos[p]:pos[p+1]]
  1451. if string(val) == "" {
  1452. continue
  1453. }
  1454. if sign == -1 {
  1455. rep[k+"_"+fmt.Sprint(i)] = "-" + val
  1456. } else {
  1457. rep[k+"_"+fmt.Sprint(i)] = val
  1458. }
  1459. }
  1460. }
  1461. }
  1462. tmps := []map[string]interface{}{}
  1463. for i := 0; i < len(apos); i++ {
  1464. if strings.TrimSpace(rep[vre.Field+"_"+fmt.Sprint(i)]) != "" {
  1465. tmp := map[string]interface{}{
  1466. "field": vre.Field,
  1467. "code": vre.Code,
  1468. "ruletext": vre.RuleText,
  1469. "extfrom": text,
  1470. "value": rep[vre.Field+"_"+fmt.Sprint(i)],
  1471. "type": "regexp",
  1472. "matchtype": "regcontent",
  1473. "blocktag": *tag,
  1474. "score": score,
  1475. }
  1476. exfield := ju.ExtField{
  1477. BlockTag: *tag,
  1478. Field: vre.Field,
  1479. Code: vre.Code,
  1480. RuleText: vre.RuleText,
  1481. Type: "regexp",
  1482. MatchType: "regcontent",
  1483. ExtFrom: extfrom,
  1484. SourceValue: rep[vre.Field+"_"+fmt.Sprint(i)],
  1485. Value: rep[vre.Field+"_"+fmt.Sprint(i)],
  1486. Score: score,
  1487. }
  1488. if vre.Field == "qualifies" {
  1489. if len(rep) >= 2 {
  1490. tmp["ruletext"] = rep[vre.Field+"_key_"+fmt.Sprint(i)]
  1491. exfield.RuleText = rep[vre.Field+"_key_"+fmt.Sprint(i)]
  1492. }
  1493. }
  1494. tmps = append(tmps, tmp)
  1495. if tmp["blocktag"] != nil {
  1496. exfield.BlockTag = tmp["blocktag"].(map[string]string)
  1497. }
  1498. j.Result[vre.Field] = append(j.Result[vre.Field], &exfield)
  1499. }
  1500. }
  1501. if len(tmps) > 0 {
  1502. //fmt.Println(tmps)
  1503. extinfo[vre.Field] = tmps
  1504. }
  1505. }
  1506. } else {
  1507. pos := vre.RegCore.Reg.FindStringIndex(text)
  1508. val := ""
  1509. if len(pos) == 2 {
  1510. text = text[pos[1]:]
  1511. rs := regexp.MustCompile("[^\r\n\t]+")
  1512. tmp := rs.FindAllString(text, -1)
  1513. if len(tmp) > 0 {
  1514. val = tmp[0]
  1515. }
  1516. }
  1517. if val != "" {
  1518. tmps := []map[string]interface{}{}
  1519. tmp := map[string]interface{}{
  1520. "field": vre.Field,
  1521. "code": vre.Code,
  1522. "ruletext": vre.RuleText,
  1523. "extfrom": text,
  1524. "value": val,
  1525. "type": "regexp",
  1526. "matchtype": "regcontent",
  1527. "blocktag": *tag,
  1528. "score": score,
  1529. }
  1530. tmps = append(tmps, tmp)
  1531. extinfo[vre.Field] = tmps
  1532. if j.Result[vre.Field] == nil {
  1533. j.Result[vre.Field] = [](*ju.ExtField){}
  1534. }
  1535. field := &ju.ExtField{BlockTag: *tag, Field: vre.Field, Code: vre.Code, RuleText: vre.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: text,
  1536. Value: val,
  1537. Score: score}
  1538. if tmp["blocktag"] != nil {
  1539. field.BlockTag = tmp["blocktag"].(map[string]string)
  1540. }
  1541. j.Result[vre.Field] = append(j.Result[vre.Field], field)
  1542. }
  1543. }
  1544. return extinfo
  1545. }
  1546. //后置过滤
  1547. func ExtRegBack(j *ju.Job, in *RegLuaInfo, t *TaskInfo, vc *RuleCore) {
  1548. defer qu.Catch()
  1549. if in.IsLua {
  1550. result := GetResultMapForLua(j)
  1551. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Result: result, Script: in.RuleText}
  1552. if j != nil {
  1553. lua.Block = j.Block
  1554. }
  1555. extinfo := lua.RunScript("back")
  1556. for k, v := range extinfo {
  1557. if tmps, ok := v.([]map[string]interface{}); ok {
  1558. j.Result[k] = [](*ju.ExtField){}
  1559. for _, tmp := range tmps {
  1560. 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"]),
  1561. ExtFrom: qu.ObjToString(tmp["extfrom"]),
  1562. Value: tmp["value"]}
  1563. if tmp["blocktag"] != nil {
  1564. field.BlockTag = tmp["blocktag"].(map[string]string)
  1565. }
  1566. j.Result[k] = append(j.Result[k], field)
  1567. //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})
  1568. }
  1569. }
  1570. }
  1571. if len(extinfo) > 0 {
  1572. AddExtLog("clear", j.SourceMid, result, extinfo, in, t) //抽取日志
  1573. }
  1574. } else {
  1575. extinfo := map[string]interface{}{}
  1576. if in.Field != "" {
  1577. clearByTitle := false
  1578. if vc != nil && vc.ExtFrom == "title" && in.Field == "buyer" { //buyer从title抽取到的单独走titile的清理
  1579. clearByTitle = true
  1580. }
  1581. if j.Result[in.Field] != nil {
  1582. tmp := j.Result[in.Field]
  1583. exts := []interface{}{}
  1584. for k, v := range tmp {
  1585. if clearByTitle && v.ExtFrom != "title" {
  1586. continue
  1587. }
  1588. //table抽取到的数据不清理
  1589. if v.Type == "table" && v.Field == "projectname" {
  1590. return
  1591. }
  1592. text := qu.ObjToString(v.Value)
  1593. if v.Field == "bidamount" || v.Field == "budget" {
  1594. if (strings.Contains(qu.ObjToString(v.SourceValue), "费率")||
  1595. strings.Contains(qu.ObjToString(v.SourceValue), "税率") ||
  1596. strings.Contains(qu.ObjToString(v.SourceValue), "(%)") ) &&
  1597. !strings.Contains(qu.ObjToString(v.SourceValue), "工程设计费"){
  1598. j.Result[in.Field][k].IsTrue = false
  1599. continue
  1600. }
  1601. }
  1602. if text != "" {
  1603. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  1604. }
  1605. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  1606. continue
  1607. }
  1608. j.Result[in.Field][k].Value = text
  1609. exts = append(exts, map[string]interface{}{
  1610. "field": v.Field,
  1611. "code": v.Code,
  1612. "ruletext": v.RuleText,
  1613. "type": v.Type,
  1614. "matchtype": v.MatchType,
  1615. "extfrom": v.ExtFrom,
  1616. "value": text,
  1617. })
  1618. }
  1619. if len(exts) > 0 {
  1620. extinfo[in.Field] = exts
  1621. AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
  1622. }
  1623. }
  1624. } else {
  1625. for key, tmp := range j.Result {
  1626. exts := []interface{}{}
  1627. for k, v := range tmp {
  1628. //table抽取到的数据不清理
  1629. if v.Type == "table" && v.Field == "projectname" {
  1630. return
  1631. }
  1632. text := qu.ObjToString(v.Value)
  1633. if text != "" {
  1634. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  1635. }
  1636. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  1637. continue
  1638. }
  1639. j.Result[key][k].Value = text
  1640. exts = append(exts, map[string]interface{}{
  1641. "field": v.Field,
  1642. "code": v.Code,
  1643. "ruletext": v.RuleText,
  1644. "type": v.Type,
  1645. "matchtype": v.MatchType,
  1646. "extfrom": v.ExtFrom,
  1647. "value": text,
  1648. })
  1649. }
  1650. if len(exts) > 0 {
  1651. extinfo[key] = exts
  1652. AddExtLog("clear", j.SourceMid, j.Result, extinfo, in, t) //抽取日志
  1653. }
  1654. }
  1655. }
  1656. }
  1657. }
  1658. //后置过滤
  1659. func ExtRegBackPkg(j *ju.Job, in *RegLuaInfo) {
  1660. defer qu.Catch()
  1661. for k, v := range j.BlockPackage {
  1662. if in.Field == "winner" {
  1663. j.BlockPackage[k].Winner = in.RegPreBac.Reg.ReplaceAllString(v.Winner, in.RegPreBac.Replace)
  1664. } else if in.Field == "bidstatus" {
  1665. j.BlockPackage[k].BidStatus = in.RegPreBac.Reg.ReplaceAllString(v.BidStatus, in.RegPreBac.Replace)
  1666. } else if in.Field == "" {
  1667. j.BlockPackage[k].Text = in.RegPreBac.Reg.ReplaceAllString(v.Text, in.RegPreBac.Replace)
  1668. } else if in.Field == "projectname" {
  1669. j.BlockPackage[k].Name = in.RegPreBac.Reg.ReplaceAllString(v.Name, in.RegPreBac.Replace)
  1670. } else if in.Field == "winnerperson" {
  1671. j.BlockPackage[k].WinnerPerson = in.RegPreBac.Reg.ReplaceAllString(v.WinnerPerson, in.RegPreBac.Replace)
  1672. } else if in.Field == "winnertel" {
  1673. j.BlockPackage[k].WinnerTel = in.RegPreBac.Reg.ReplaceAllString(v.WinnerTel, in.RegPreBac.Replace)
  1674. }
  1675. }
  1676. }
  1677. //KV过滤
  1678. func ExtRuleKV(j *ju.Job, in *RegLuaInfo, t *TaskInfo) {
  1679. defer qu.Catch()
  1680. extinfo := map[string]interface{}{}
  1681. if in.Field != "" {
  1682. if j.Result[in.Field] != nil {
  1683. tmp := j.Result[in.Field]
  1684. exts := []interface{}{}
  1685. for k, v := range tmp {
  1686. if v.Type != "table" && !strings.Contains(v.Type, "colon") && !strings.Contains(v.Type, "space") {
  1687. continue
  1688. }
  1689. text := qu.ObjToString(v.Value)
  1690. if text != "" {
  1691. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  1692. }
  1693. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  1694. continue
  1695. }
  1696. j.Result[in.Field][k].Value = text
  1697. exts = append(exts, map[string]interface{}{
  1698. "field": v.Field,
  1699. "code": v.Code,
  1700. "ruletext": v.RuleText,
  1701. "type": v.Type,
  1702. "matchtype": v.MatchType,
  1703. "extfrom": v.ExtFrom,
  1704. "value": text,
  1705. })
  1706. }
  1707. if len(exts) > 0 {
  1708. extinfo[in.Field] = exts
  1709. AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
  1710. }
  1711. }
  1712. }
  1713. }
  1714. //获取抽取结果map[string][]interface{},lua脚本使用
  1715. func GetResultMapForLua(j *ju.Job) map[string][]map[string]interface{} {
  1716. defer qu.Catch()
  1717. result := map[string][]map[string]interface{}{}
  1718. for key, val := range j.Result {
  1719. if result[key] == nil {
  1720. result[key] = []map[string]interface{}{}
  1721. }
  1722. for _, v := range val {
  1723. tmp := map[string]interface{}{
  1724. "field": v.Field,
  1725. "code": v.Code,
  1726. "ruletext": v.RuleText,
  1727. "value": v.Value,
  1728. "type": v.Type,
  1729. "matchtype": v.MatchType,
  1730. "extfrom": v.ExtFrom,
  1731. }
  1732. result[key] = append(result[key], tmp)
  1733. }
  1734. }
  1735. return result
  1736. }
  1737. //抽取日志
  1738. func AddExtLog(ftype, sid string, before interface{}, extinfo interface{}, v *RegLuaInfo, t *TaskInfo) {
  1739. defer qu.Catch()
  1740. if !t.IsEtxLog {
  1741. return
  1742. }
  1743. logdata := map[string]interface{}{
  1744. "code": qu.If(v.Code == "", "kv", v.Code),
  1745. "name": v.Name,
  1746. "type": ftype,
  1747. "ruletext": v.RuleText,
  1748. "islua": v.IsLua,
  1749. "field": v.Field,
  1750. "version": t.Version,
  1751. "taskname": t.Name,
  1752. "before": before,
  1753. "extinfo": extinfo,
  1754. "sid": sid,
  1755. "comeintime": time.Now().Unix(),
  1756. }
  1757. lock.Lock()
  1758. ExtLogs[t] = append(ExtLogs[t], logdata)
  1759. lock.Unlock()
  1760. }
  1761. func BeforeAddClearFnLog(ftype, name, sid, before, matchtype string, ext *ju.ExtField, e *ExtractTask) {
  1762. exts := []map[string]interface{}{}
  1763. exts = append(exts, map[string]interface{}{
  1764. "field": ext.Field,
  1765. "code": ext.Code,
  1766. "type": ftype,
  1767. "matchtype": matchtype,
  1768. "extfrom": ext.ExtFrom,
  1769. "value": ext.Value,
  1770. })
  1771. extinfo := map[string]interface{}{
  1772. ext.Field: exts,
  1773. }
  1774. AddClearFnLog(ftype, sid, before, extinfo, ext.Code, name, ext.Field, e.TaskInfo)
  1775. }
  1776. func AddClearFnLog(ftype, sid string, before interface{}, extinfo interface{}, code, name, field string, t *TaskInfo) {
  1777. defer qu.Catch()
  1778. if !t.IsEtxLog {
  1779. return
  1780. }
  1781. logdata := map[string]interface{}{
  1782. "code": code,
  1783. "name": name,
  1784. "type": ftype,
  1785. "ruletext": "",
  1786. "islua": false,
  1787. "field": field,
  1788. "version": t.Version,
  1789. "taskname": t.Name,
  1790. "before": before,
  1791. "extinfo": extinfo,
  1792. "sid": sid,
  1793. "comeintime": time.Now().Unix(),
  1794. }
  1795. lock.Lock()
  1796. ExtLogs[t] = append(ExtLogs[t], logdata)
  1797. lock.Unlock()
  1798. }
  1799. //保存抽取日志
  1800. func SaveExtLog() {
  1801. defer qu.Catch()
  1802. tmpLogs := map[*TaskInfo][]map[string]interface{}{}
  1803. lock.Lock()
  1804. tmpLogs = ExtLogs
  1805. ExtLogs = map[*TaskInfo][]map[string]interface{}{}
  1806. lock.Unlock()
  1807. for k, v := range tmpLogs {
  1808. if len(v) < saveLimit {
  1809. db.Mgo.SaveBulk(k.TrackColl, v...)
  1810. } else {
  1811. for {
  1812. if len(v) > saveLimit {
  1813. tmp := v[:saveLimit]
  1814. db.Mgo.SaveBulk(k.TrackColl, tmp...)
  1815. v = v[saveLimit:]
  1816. } else {
  1817. db.Mgo.SaveBulk(k.TrackColl, v...)
  1818. break
  1819. }
  1820. }
  1821. }
  1822. }
  1823. time.AfterFunc(10*time.Second, SaveExtLog)
  1824. }
  1825. type FieldValue struct {
  1826. Value interface{}
  1827. Count int
  1828. }
  1829. var clearWinnerReg = regexp.MustCompile("名称|施工|拟定供应商名称|:|:")
  1830. var unPackageWinnerReg = regexp.MustCompile("(重新招标)")
  1831. //分析抽取结果并保存
  1832. func AnalysisSaveResult(j, jf *ju.Job, e *ExtractTask) {
  1833. qu.Try(func() {
  1834. if (j.Category == "招标" || j.Category == "预告") && (len(j.BlockPackage) > 0 || len(j.PackageInfo) > 0 || len(j.Result) > 0) {
  1835. if j.CategorySecond != "单一" {
  1836. delete(j.Result, "winner")
  1837. delete(j.Result, "bidamount")
  1838. for _, v := range j.BlockPackage {
  1839. v.Bidamount = 0
  1840. v.IsTrueBidamount = false
  1841. if v.Winner != "" {
  1842. v.Winner = ""
  1843. if v.SpaceKV != nil {
  1844. delete(v.SpaceKV.KvTags, "中标单位")
  1845. }
  1846. if v.TableKV != nil {
  1847. delete(v.TableKV.KvTags, "中标单位")
  1848. }
  1849. if v.ColonKV != nil {
  1850. delete(v.ColonKV.KvTags, "中标单位")
  1851. }
  1852. }
  1853. }
  1854. for _, v := range j.PackageInfo {
  1855. delete(v, "winner")
  1856. delete(v, "bidamount")
  1857. }
  1858. j.Winnerorder = nil
  1859. if jf != nil && jf.Winnerorder != nil {
  1860. jf.Winnerorder = nil
  1861. }
  1862. }
  1863. }
  1864. //重新取出清理过后的中标候选人
  1865. resetWinnerorder(j)
  1866. //打分
  1867. doc, result, _id := funcAnalysis(j, e)
  1868. //_, result, _id := funcAnalysis(j, e)
  1869. if ju.IsSaveTag {
  1870. go otherNeedSave(j, result, e)
  1871. }
  1872. //从排序结果中取值
  1873. tmp := map[string]interface{}{} //抽取值
  1874. tmp["spidercode"] = j.SpiderCode
  1875. tmp["site"] = j.Site
  1876. if len(*j.Jsondata) > 0 {
  1877. tmp["jsondata"] = j.Jsondata
  1878. }
  1879. //字段-抽取来源
  1880. fieldSource := make(map[string]interface{},0)
  1881. //字段-抽取来源
  1882. for k, val := range result {
  1883. if k == "qualifies" {
  1884. squalifies := make([]interface{}, 0)
  1885. squalifiesMap := make(map[string]*scoreIndex, 0)
  1886. for _, kv := range val {
  1887. skey := kv.RuleText
  1888. if kv.Score > 0 {
  1889. if squalifiesMap[skey] == nil {
  1890. squalifiesMap = map[string]*scoreIndex{
  1891. skey: &scoreIndex{
  1892. Score: kv.Score,
  1893. Index: len(squalifies),
  1894. },
  1895. }
  1896. squalifies = append(squalifies, map[string]interface{}{
  1897. "key": skey,
  1898. "value": kv.Value,
  1899. })
  1900. } else {
  1901. if squalifiesMap[skey].Score < kv.Score {
  1902. squalifies[squalifiesMap[skey].Index] = map[string]interface{}{
  1903. "key": skey,
  1904. "value": kv.Value,
  1905. }
  1906. }
  1907. }
  1908. }
  1909. }
  1910. tmp[k] = squalifies
  1911. continue
  1912. }
  1913. for _, v := range val { //取第一个非负数,项目名称除外
  1914. //存0是否有效
  1915. if (v.Field == "bidamount" || v.Field == "budget") && v.IsTrue && v.Score > -1 {
  1916. tmp[v.Field] = v.Value
  1917. fieldSource[v.Field] = map[string]interface{}{
  1918. "ext_type":v.Type,
  1919. "ext_from":v.ExtFrom,
  1920. }
  1921. break
  1922. }
  1923. if v.Score > -1 && (v.Field != "bidamount" && v.Field != "budget") && len(strings.TrimSpace(fmt.Sprint(v.Value))) > 0 {
  1924. tmp[v.Field] = v.Value
  1925. fieldSource[v.Field] = map[string]interface{}{
  1926. "ext_type":v.Type,
  1927. "ext_from":v.ExtFrom,
  1928. }
  1929. break
  1930. }
  1931. }
  1932. }
  1933. tmp["winner"] = strings.ReplaceAll(qu.ObjToString(tmp["winner"]), ",,", ",")
  1934. if len(j.PackageInfo) > 15 {
  1935. for k, v := range j.PackageInfo {
  1936. j.PackageInfo = map[string]map[string]interface{}{}
  1937. j.PackageInfo[k] = v
  1938. break
  1939. }
  1940. }
  1941. if len(j.PackageInfo) > 0 { //分包信息
  1942. tmp["package"] = j.PackageInfo
  1943. //包预算,中标金额合并大于抽取就覆盖
  1944. var tmpBidamount, tmpBudget,tmpAgencyfee float64
  1945. //s_winner逗号分隔拼接,分包中标人
  1946. var tmpstr, savewinner []string
  1947. //按包排序
  1948. for b, v := range j.PackageInfo {
  1949. if v["winner"] != nil && v["winner"] != "" {
  1950. tmpstr = append(tmpstr, b)
  1951. }
  1952. }
  1953. //包预算,中标金额合并大于抽取就覆盖
  1954. if len(j.PackageInfo) >= 1 {
  1955. //包数大于1累加
  1956. for _, v := range j.PackageInfo {
  1957. if v["budget"] != nil {
  1958. tmpBudget += qu.Float64All(v["budget"])
  1959. }
  1960. if v["bidamount"] != nil {
  1961. tmpBidamount += qu.Float64All(v["bidamount"])
  1962. }
  1963. if v["agencyfee"] != nil {
  1964. tmpAgencyfee += qu.Float64All(v["agencyfee"])
  1965. }
  1966. }
  1967. if qu.Float64All(tmp["budget"]) < tmpBudget {
  1968. fieldSource["budget"] = map[string]interface{}{
  1969. "ext_type":"",
  1970. "ext_from":"package",
  1971. }
  1972. tmp["budget"] = tmpBudget
  1973. }
  1974. if qu.Float64All(tmp["agencyfee"]) < tmpAgencyfee {
  1975. fieldSource["agencyfee"] = map[string]interface{}{
  1976. "ext_type":"",
  1977. "ext_from":"package",
  1978. }
  1979. tmp["agencyfee"] = tmpAgencyfee
  1980. }
  1981. if qu.Float64All(tmp["bidamount"]) > 0 && qu.Float64All(tmp["budget"]) > 0 && (qu.Float64All(tmp["bidamount"])/10 > qu.Float64All(tmp["budget"])) {
  1982. fieldSource["bidamount"] = map[string]interface{}{
  1983. "ext_type":"",
  1984. "ext_from":"package",
  1985. }
  1986. tmp["bidamount"] = tmpBidamount
  1987. } else if qu.Float64All(tmp["bidamount"]) < tmpBidamount {
  1988. fieldSource["bidamount"] = map[string]interface{}{
  1989. "ext_type":"",
  1990. "ext_from":"package",
  1991. }
  1992. tmp["bidamount"] = tmpBidamount
  1993. }
  1994. } else {
  1995. //包数等于1,tmp没有值取包里的值
  1996. if tmp["budget"] == nil || tmp["budget"] == 0 {
  1997. for _, v := range j.PackageInfo {
  1998. if v["budget"] != nil {
  1999. fieldSource["budget"] = map[string]interface{}{
  2000. "ext_type":"",
  2001. "ext_from":"package",
  2002. }
  2003. tmp["budget"] = v["budget"]
  2004. }
  2005. }
  2006. }
  2007. if tmp["agencyfee"] == nil || tmp["agencyfee"] == 0 {
  2008. for _, v := range j.PackageInfo {
  2009. if v["agencyfee"] != nil {
  2010. fieldSource["agencyfee"] = map[string]interface{}{
  2011. "ext_type":"",
  2012. "ext_from":"package",
  2013. }
  2014. tmp["agencyfee"] = v["agencyfee"]
  2015. }
  2016. }
  2017. }
  2018. if tmp["bidamount"] == nil || tmp["bidamount"] == 0 {
  2019. for _, v := range j.PackageInfo {
  2020. if v["bidamount"] != nil {
  2021. fieldSource["bidamount"] = map[string]interface{}{
  2022. "ext_type":"",
  2023. "ext_from":"package",
  2024. }
  2025. tmp["bidamount"] = v["bidamount"]
  2026. }
  2027. }
  2028. }
  2029. }
  2030. //s_winner逗号分隔拼接,分包中标人
  2031. sort.Strings(tmpstr)
  2032. for _, v := range tmpstr {
  2033. winner := qu.ObjToString(j.PackageInfo[v]["winner"])
  2034. new_winner := clearWinnerReg.ReplaceAllString(winner, "")
  2035. if new_winner == "" {
  2036. continue
  2037. }
  2038. //名称黑名单
  2039. if unPackageWinnerReg.MatchString(new_winner) {
  2040. continue
  2041. }
  2042. savewinner = append(savewinner, new_winner)
  2043. }
  2044. if (savewinner == nil || len(savewinner) == 0) && tmp["winner"] != nil {
  2045. tmp["s_winner"] = tmp["winner"]
  2046. fieldSource["s_winner"] = fieldSource["winner"]
  2047. } else if savewinner != nil {
  2048. savewinner = RemoveReplicaSliceString(savewinner)
  2049. tmp["s_winner"] = strings.Join(savewinner, ",")
  2050. if len(savewinner)==1 {
  2051. fieldSource["s_winner"] = fieldSource["winner"]
  2052. }else if len(savewinner)>1{
  2053. fieldSource["s_winner"] = map[string]interface{}{
  2054. "ext_type":"",
  2055. "ext_from":"package",
  2056. }
  2057. }
  2058. }
  2059. } else if tmp["winner"] != nil && tmp["winner"] != "" {
  2060. //没有分包取winner
  2061. tmp["s_winner"] = tmp["winner"]
  2062. fieldSource["s_winner"] = fieldSource["winner"]
  2063. }
  2064. if len(j.Winnerorder) > 0 { //候选人信息
  2065. for i, v := range j.Winnerorder {
  2066. if v["price"] != nil {
  2067. tmpPrice := clear.ObjToMoney([]interface{}{v["price"], ""}, j.SpiderCode, j.IsClearnMoney)
  2068. if tmpPrice[len(tmpPrice)-1].(bool) {
  2069. j.Winnerorder[i]["price"] = tmpPrice[0]
  2070. } else {
  2071. delete(j.Winnerorder[i], "price")
  2072. }
  2073. }
  2074. }
  2075. tmp["winnerorder"] = j.Winnerorder
  2076. }
  2077. //处理附件
  2078. var resultf map[string][]*ju.ExtField
  2079. ffield := map[string]interface{}{}
  2080. if jf != nil {
  2081. _, resultf, _ = funcAnalysis(jf, e)
  2082. for _, val := range resultf {
  2083. for _, v := range val { //取第一个非负数
  2084. if v.Score > -1 {
  2085. ffield[v.Field] = v.Value
  2086. if tmp[v.Field] == nil {
  2087. if (v.Field == "bidamount" || v.Field == "budget") && v.IsTrue && v.Value.(float64) > 100 && v.Value.(float64) < 50000000000 {
  2088. tmp[v.Field] = v.Value
  2089. fieldSource[v.Field] = map[string]interface{}{
  2090. "ext_type":v.Type,
  2091. "ext_from":"ff",
  2092. }
  2093. break
  2094. }
  2095. if v.Score > -1 && (v.Field != "bidamount" && v.Field != "budget") && len(strings.TrimSpace(fmt.Sprint(v.Value))) > 0 {
  2096. tmp[v.Field] = v.Value
  2097. fieldSource[v.Field] = map[string]interface{}{
  2098. "ext_type":v.Type,
  2099. "ext_from":"ff",
  2100. }
  2101. break
  2102. }
  2103. }
  2104. break
  2105. }
  2106. }
  2107. }
  2108. if len(jf.PackageInfo) > 0 { //分包信息
  2109. ffield["package"] = jf.PackageInfo
  2110. }
  2111. if len(jf.Winnerorder) > 0 { //候选人信息
  2112. ffield["winnerorder"] = jf.Winnerorder
  2113. }
  2114. }
  2115. //添加字段来源
  2116. tmp["field_source"] = fieldSource
  2117. //添加字段来源
  2118. for k, v := range *doc {
  2119. if utf8.RuneCountInString(qu.ObjToString(v)) > 100000 {
  2120. (*doc)[k] = []rune(qu.ObjToString(v))[:100000]
  2121. }
  2122. //去重冗余字段
  2123. if delFiled(k) {
  2124. continue
  2125. }
  2126. if tmp[k] == nil {
  2127. tmp[k] = v
  2128. }
  2129. }
  2130. //质量审核
  2131. if ju.QualityAudit {
  2132. e.QualityAudit(tmp)
  2133. }
  2134. //城市抽取
  2135. if e.IsExtractCity {
  2136. e.NewExtractCity(j, &tmp, _id)
  2137. }
  2138. //品牌抽取
  2139. if ju.IsBrandGoods {
  2140. tmp["checkhas"] = map[string]int{
  2141. "hastable": j.HasTable,
  2142. "hasgoods": j.HasGoods,
  2143. "hasbrand": j.HasBrand,
  2144. "haskey": j.HasKey,
  2145. }
  2146. if len(j.BrandData) > 0 {
  2147. tmp["tablebrand"] = j.BrandData
  2148. }
  2149. }
  2150. //prince和number抽取
  2151. if ju.IsPriceNumber {
  2152. priceNumberLen := len(j.PriceNumberData)
  2153. if priceNumberLen > 1 { //table数据去重
  2154. tmpPriceNumberData := []map[string]interface{}{}
  2155. tableStrs := map[string]bool{}
  2156. for _, tb := range j.PriceNumberData {
  2157. has := false
  2158. bytes, _ := json.Marshal(tb)
  2159. str := string(bytes)
  2160. if len(tableStrs) > 0 && tableStrs[str] {
  2161. has = true
  2162. } else {
  2163. tableStrs[str] = true
  2164. }
  2165. if !has {
  2166. for _, data := range tb {
  2167. tmpPriceNumberData = append(tmpPriceNumberData, data)
  2168. }
  2169. }
  2170. }
  2171. tmp["pricenumber"] = tmpPriceNumberData
  2172. } else if priceNumberLen == 1 {
  2173. tmp["pricenumber"] = j.PriceNumberData[0]
  2174. }
  2175. }
  2176. //所有kv组成的字符串
  2177. var kvtext bytes.Buffer
  2178. blocks := make([]ju.BlockAndTag, 0)
  2179. for _, v := range j.Block {
  2180. //分包和标签
  2181. if ju.SaveBlock {
  2182. xx, _ := json.Marshal(v)
  2183. tmpblock := new(ju.TmpBlock)
  2184. err := json.Unmarshal(xx, &tmpblock)
  2185. if err != nil {
  2186. if v.BPackage != nil {
  2187. bpb, _ := json.Marshal(v.BPackage)
  2188. tmpblock.BPackage = string(bpb)
  2189. }
  2190. tmpblock = rangeBlockToJson(v, *tmpblock)
  2191. }
  2192. blocks = append(blocks, ju.BlockAndTag{v.Tag, tmpblock})
  2193. }
  2194. //把所有kv组装成一个字符串,存库
  2195. for _, jv := range []*ju.JobKv{v.ColonKV, v.SpaceKV, v.TableKV} {
  2196. if jv == nil {
  2197. continue
  2198. }
  2199. for jv_k, jv_v := range jv.KvTags {
  2200. for _, jv_vv := range jv_v {
  2201. kvtext.WriteString(jv_k)
  2202. kvtext.WriteString(":")
  2203. kvtext.WriteString(jv_vv.Value)
  2204. kvtext.WriteString("\n")
  2205. }
  2206. }
  2207. }
  2208. }
  2209. if kvtext.Len() > 0 {
  2210. tmp["kvtext"] = kvtext.String()
  2211. }
  2212. if len(blocks) > 0 {
  2213. if blocksBytes, err := json.Marshal(blocks); err == nil {
  2214. if utf8.RuneCount(blocksBytes) < 100000 {
  2215. tmp["blocks"] = string(blocksBytes)
  2216. }
  2217. }
  2218. }
  2219. tmp["dataging"] = j.Dataging
  2220. /*for k, v := range *j.Data {
  2221. if f[k] {
  2222. tmp[k] = v
  2223. }
  2224. }
  2225. for k := range tmp {
  2226. if !f[k]{
  2227. delete(tmp,k)
  2228. }
  2229. }*/
  2230. //检查字段
  2231. tmp = checkFields(tmp)
  2232. if tmp["projectname"] == nil || tmp["projectname"] == "" {
  2233. tmp["projectname"] = j.Title
  2234. }
  2235. tmp["repeat"] = 0
  2236. if ju.Ffield {
  2237. if len(ffield) > 0 {
  2238. tmp["ffield"] = ffield
  2239. }
  2240. }
  2241. if e.TaskInfo.TestColl == "" {
  2242. if len(tmp) > 0 { //保存抽取结果
  2243. tmparr := []map[string]interface{}{
  2244. map[string]interface{}{
  2245. "_id": qu.StringTOBsonId(_id),
  2246. },
  2247. map[string]interface{}{"$set": tmp},
  2248. }
  2249. e.RWMutex.Lock()
  2250. e.BidArr = append(e.BidArr, tmparr)
  2251. e.BidTotal++
  2252. e.RWMutex.Unlock()
  2253. }
  2254. if ju.SaveResult {
  2255. id := tmp["_id"]
  2256. tmp["result"] = result
  2257. tmp["resultf"] = resultf
  2258. delete(tmp, "_id")
  2259. tmparr := []map[string]interface{}{
  2260. map[string]interface{}{
  2261. "_id": id,
  2262. },
  2263. map[string]interface{}{"$set": tmp},
  2264. }
  2265. e.RWMutex.Lock()
  2266. e.ResultArr = append(e.ResultArr, tmparr)
  2267. e.RWMutex.Unlock()
  2268. }
  2269. } else { //测试结果
  2270. delete(tmp, "_id")
  2271. delete(tmp, "fieldall")
  2272. if len(j.BlockPackage) > 0 { //分包详情
  2273. if len(j.BlockPackage) > 10 {
  2274. tmp["epackage"] = "分包异常"
  2275. } else {
  2276. bs, _ := json.Marshal(j.BlockPackage)
  2277. tmp["epackage"] = string(bs)
  2278. }
  2279. }
  2280. tmp["result"] = result
  2281. //tmp["resultf"] = resultf
  2282. //_,err :=db.Mgo.Get().DB("zhengkun").C("result_data").Upsert(`{"_id":"`+_id+`"}`,map[string]interface{}{"$set": tmp})
  2283. //log.Debug("save:",err)
  2284. b := db.Mgo.Update(e.TaskInfo.TestColl, `{"_id":"`+_id+`"}`, map[string]interface{}{"$set": tmp}, true, false)
  2285. if !b {
  2286. log.Debug(e.TaskInfo.TestColl, _id)
  2287. }
  2288. }
  2289. }, func(err interface{}) {
  2290. log.Debug("AnalysisSaveResult err", err)
  2291. })
  2292. }
  2293. //检查字段-
  2294. func checkFields(tmp map[string]interface{}) map[string]interface{} {
  2295. delete(tmp, "contenthtml")
  2296. delete(tmp, "detail")
  2297. tmp["repeat"] = 0
  2298. //指定爬虫-金额处理-预算-中标金额异常
  2299. if qu.ObjToString(tmp["spidercode"])=="xz_xzzzqjzscjgycxxxpt_zbtzs" {
  2300. if budget, ok := tmp["budget"].(float64); ok && budget>0 && budget < 1000000{
  2301. tmp["budget"] = budget*10000.0
  2302. }
  2303. if bidamount, ok := tmp["bidamount"].(float64); ok && bidamount>0 && bidamount > 1000000000{
  2304. tmp["bidamount"] = bidamount/10000.0
  2305. }
  2306. }
  2307. if qu.ObjToString(tmp["spidercode"])=="js_jsszbtbw_zbhxrgs" {
  2308. if bidamount, ok := tmp["bidamount"].(float64); ok && bidamount>0 && bidamount > 1000000000{
  2309. tmp["bidamount"] = bidamount/10000.0
  2310. }
  2311. }
  2312. if _, ok := tmp["bidamount"].(string); ok {
  2313. delete(tmp, "bidamount")
  2314. } 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) {
  2315. delete(tmp, "bidamount")
  2316. }
  2317. if _, ok := tmp["budget"].(string); ok {
  2318. delete(tmp, "budget")
  2319. }
  2320. if _, ok := tmp["unitprice"].(string); ok {
  2321. delete(tmp, "unitprice")
  2322. }
  2323. if _, ok := tmp["bidopentime"].(string); ok {
  2324. delete(tmp, "bidopentime")
  2325. }
  2326. if _, ok := tmp["signaturedate"].(string); ok {
  2327. delete(tmp, "signaturedate")
  2328. }
  2329. if _, ok := tmp["supervisorrate"].(string); ok {
  2330. delete(tmp, "supervisorrate")
  2331. }
  2332. for k, v := range tmp {
  2333. if k == "qualifies" {
  2334. continue
  2335. }
  2336. if k == "contract_guarantee" || k == "bid_guarantee" {
  2337. if len(fmt.Sprint(v)) > 0 {
  2338. tmp[k] = true
  2339. } else {
  2340. delete(tmp, k)
  2341. }
  2342. }
  2343. if v == "" || len(strings.TrimSpace(fmt.Sprint(v))) == 0 || strings.Contains(fmt.Sprint(v), "**") {
  2344. delete(tmp, k)
  2345. }
  2346. }
  2347. //项目周期-有效值
  2348. projectperiod := qu.ObjToString(tmp["projectperiod"])
  2349. if projectperiod !="" {
  2350. //项目周期包含日期,数字及日期单位可保留,其余可清洗
  2351. isNeedValueReg := regexp.MustCompile(`([0-9俩两一二三四五六七八九年月日天周]|合同)`)
  2352. if !isNeedValueReg.MatchString(projectperiod) {
  2353. delete(tmp, "projectperiod")
  2354. }
  2355. }
  2356. //工期单位是否有效-清理
  2357. if project_timeunit, ok := tmp["project_timeunit"].(string); ok {
  2358. dateReg := regexp.MustCompile(`[年|月|日|天|周]`)
  2359. if !dateReg.MatchString(project_timeunit) || utf8.RuneCountInString(project_timeunit)>4 {
  2360. delete(tmp, "project_timeunit")
  2361. }
  2362. //年-0 >5 删除
  2363. if project_timeunit == "年" && (qu.Int64All(tmp["project_duration"])==0 || qu.Int64All(tmp["project_duration"])>5 ){
  2364. delete(tmp, "project_timeunit")
  2365. }
  2366. }
  2367. if tmp["winner"] != nil && tmp["s_winner"] != nil {
  2368. strwin := qu.ObjToString(tmp["winner"])
  2369. strwin_s := qu.ObjToString(tmp["s_winner"])
  2370. if !strings.Contains(strwin_s, strwin) {
  2371. tmp["s_winner"] = strwin
  2372. }
  2373. }
  2374. //budget bidamount
  2375. if bg, ok := tmp["budget"].(float64); ok {
  2376. if bg >= 50000000000 {
  2377. tmp["budget_max_err"] = bg
  2378. delete(tmp, "budget")
  2379. }
  2380. }
  2381. if bg, ok := tmp["bidamount"].(float64); ok && bg >= 50000000000 {
  2382. code := qu.ObjToString(tmp["spidercode"])
  2383. if bg >= 50000000000 && code != "xz_xzzzqjzscjgycxxxpt_zbtzs" &&
  2384. code != "js_jsszbtbw_zbhxrgs"{
  2385. tmp["bidamount_max_err"] = bg
  2386. delete(tmp, "bidamount")
  2387. }
  2388. }
  2389. //投标方式-
  2390. bidway := qu.IntAll(tmp["bidway"])
  2391. if bidway == 1 {
  2392. tmp["bidway"] = "纸质投标"
  2393. }else if bidway == 2 {
  2394. tmp["bidway"] = "电子投标"
  2395. }else {
  2396. delete(tmp, "bidway")
  2397. }
  2398. //折扣系数
  2399. discount := dealWithDiscountBid(tmp)
  2400. if discount >0.0 {
  2401. tmp["biddiscount"] = discount
  2402. }else {
  2403. delete(tmp, "biddiscount")
  2404. }
  2405. delete(tmp, "biddiscount_up")
  2406. delete(tmp, "biddiscount_down")
  2407. //临时
  2408. //bidopentime := qu.Int64All(tmp["bidopentime"])
  2409. //bidendtime := qu.Int64All(tmp["bidendtime"])
  2410. //timeLayout := "2006-01-02 15:04:05"
  2411. //
  2412. //if bidopentime>0 {
  2413. // bidopentime_str := time.Unix(bidopentime, 0).Format(timeLayout) //设置时间戳 使用模板格式化为日期字符串
  2414. // tmp["bidopentime"] = bidopentime_str
  2415. //}
  2416. //if bidendtime>0 {
  2417. // bidendtime_str := time.Unix(bidendtime, 0).Format(timeLayout) //设置时间戳 使用模板格式化为日期字符串
  2418. // tmp["bidendtime"] = bidendtime_str
  2419. //}
  2420. jyhref:= fmt.Sprintf(JYUrl, qu.CommonEncodeArticle("content", qu.BsonIdToSId(tmp["_id"])))
  2421. tmp["jytest_href"] = jyhref
  2422. return tmp
  2423. }
  2424. //处理折扣系数
  2425. func dealWithDiscountBid(tmp map[string]interface{}) float64 {
  2426. biddiscount := qu.Float64All(tmp["biddiscount"])
  2427. biddiscount_up := qu.Float64All(tmp["biddiscount_up"])
  2428. biddiscount_down := qu.Float64All(tmp["biddiscount_down"])
  2429. baseCount := float64(1)
  2430. if biddiscount_down >0.0 {
  2431. num1:=decimal.NewFromFloat(baseCount)
  2432. num2:=decimal.NewFromFloat(biddiscount_down)
  2433. decimalValue := num1.Sub(num2)
  2434. res,_ := decimalValue.Float64()
  2435. //log.Debug("下浮后折扣系数:",res)
  2436. return res
  2437. }
  2438. if biddiscount_up >0.0 {
  2439. num1:=decimal.NewFromFloat(baseCount)
  2440. num2:=decimal.NewFromFloat(biddiscount_up)
  2441. decimalValue := num1.Add(num2)
  2442. res,_ := decimalValue.Float64()
  2443. //log.Debug("上浮后折扣系数:",res)
  2444. return res
  2445. }
  2446. if biddiscount>0.0 {
  2447. if biddiscount > 1.0 && biddiscount<=10.0 {
  2448. num1:=decimal.NewFromFloat(10.0)
  2449. num2:=decimal.NewFromFloat(biddiscount_up)
  2450. decimalValue := num2.Div(num1)
  2451. res,_ := decimalValue.Float64()
  2452. //log.Debug("标准-①折扣系数:",res)
  2453. return res
  2454. }else if biddiscount>10.0 {
  2455. num1:=decimal.NewFromFloat(100.0)
  2456. num2:=decimal.NewFromFloat(biddiscount_up)
  2457. decimalValue := num2.Div(num1)
  2458. res,_ := decimalValue.Float64()
  2459. //log.Debug("标准-⑩折扣系数:",res)
  2460. return res
  2461. }else {
  2462. //log.Debug("标准折扣系数:",biddiscount)
  2463. return biddiscount
  2464. }
  2465. }
  2466. return 0.0
  2467. }
  2468. //保存其他
  2469. //kv、表格、块上的标签凡是新的标签都入库
  2470. //val type times firstid createtime 判定field
  2471. func otherNeedSave(j *ju.Job, result map[string][]*ju.ExtField, e *ExtractTask) {
  2472. now := time.Now().Unix()
  2473. coll := e.TaskInfo.TestColl
  2474. if coll == "" {
  2475. coll = "extract_tag_result"
  2476. } else {
  2477. coll += "_tag"
  2478. }
  2479. datas := []map[string]interface{}{}
  2480. kv := map[string]int{}
  2481. for _, v := range j.Block {
  2482. //
  2483. for _, vv := range []*ju.JobKv{v.ColonKV, v.TableKV, v.SpaceKV} {
  2484. if vv == nil || vv.KvTags == nil {
  2485. continue
  2486. }
  2487. for kkk, vvv := range vv.KvTags {
  2488. for _, vvvv := range vvv {
  2489. if vvvv.IsInvalid {
  2490. kv[kkk] = kv[kkk] + 1
  2491. break
  2492. }
  2493. }
  2494. }
  2495. }
  2496. for _, vv := range v.NotClassifyTitles {
  2497. datas = append(datas, map[string]interface{}{
  2498. "val": vv,
  2499. "times": 0,
  2500. "type": "block",
  2501. "firstid": j.SourceMid,
  2502. "createtime": now,
  2503. })
  2504. if len(datas) == saveLimit {
  2505. db.Mgo.SaveBulk(coll, datas...)
  2506. datas = []map[string]interface{}{}
  2507. }
  2508. }
  2509. }
  2510. for k, v := range kv {
  2511. datas = append(datas, map[string]interface{}{
  2512. "val": k,
  2513. "times": v,
  2514. "type": "kv",
  2515. "firstid": j.SourceMid,
  2516. "createtime": now,
  2517. })
  2518. if len(datas) == saveLimit {
  2519. db.Mgo.SaveBulk(coll, datas...)
  2520. datas = []map[string]interface{}{}
  2521. }
  2522. }
  2523. if len(datas) > 0 {
  2524. db.Mgo.SaveBulk(coll, datas...)
  2525. }
  2526. }
  2527. func rangeBlockToJson(j *ju.Block, tmpblock ju.TmpBlock) (b *ju.TmpBlock) {
  2528. if j == nil {
  2529. return nil
  2530. }
  2531. if len(j.Block) > 0 {
  2532. for i, v := range j.Block {
  2533. rangetmp := new(ju.TmpBlock)
  2534. vb, _ := json.Marshal(v)
  2535. json.Unmarshal(vb, &rangetmp)
  2536. tmpblock.Block[i] = rangeBlockToJson(v, *rangetmp)
  2537. }
  2538. }
  2539. if j.ColonKV != nil {
  2540. cb, _ := json.Marshal(j.ColonKV)
  2541. tmpblock.ColonKV = string(cb)
  2542. }
  2543. if j.SpaceKV != nil {
  2544. sb, _ := json.Marshal(j.SpaceKV)
  2545. tmpblock.SpaceKV = string(sb)
  2546. }
  2547. if j.TableKV != nil {
  2548. tb, _ := json.Marshal(j.TableKV)
  2549. tmpblock.TableKV = string(tb)
  2550. }
  2551. return &tmpblock
  2552. }
  2553. //去重冗余字段
  2554. func delFiled(k string) bool {
  2555. return k == "detailfile" || k == "summary" || k == "detail" || k == "contenthtml" || k == "site" || k == "spidercode" || k == "projectinfo" || k == "jsondata"
  2556. }
  2557. //分析-打分排序
  2558. func funcAnalysis(j *ju.Job, e *ExtractTask) (*map[string]interface{}, map[string][]*ju.ExtField, string) {
  2559. defer qu.Catch()
  2560. doc := j.Data
  2561. result := j.Result
  2562. _id := qu.BsonIdToSId((*doc)["_id"])
  2563. result = ScoreFields(j, e.Tag) //正负面词打分
  2564. //结果排序
  2565. for _, val := range result {
  2566. ju.Sort(val)
  2567. }
  2568. if !(len(j.Result) <= 0 || j.Jsondata == nil || len(*j.Jsondata) <= 0) {
  2569. clearJd(j.Jsondata, e, j.SpiderCode, j.IsClearnMoney)
  2570. marshalbt, _ := json.Marshal(j.Jsondata)
  2571. tmpjddata := make(map[string]interface{})
  2572. json.Unmarshal(marshalbt, &tmpjddata)
  2573. for _, jdkey := range ju.JsonData {
  2574. if (*j.Jsondata)[jdkey] != nil && (*j.Jsondata)[jdkey] != "" && len(j.Result[jdkey]) >= 5 {
  2575. for tmpk, tmpv := range j.Result[jdkey][:5] {
  2576. if jdkey == "budget" || jdkey == "bidamount" {
  2577. lockclear.Lock()
  2578. cfn := e.ClearFn[jdkey]
  2579. lockclear.Unlock()
  2580. if len(cfn) == 0 {
  2581. continue
  2582. }
  2583. newNum := clear.DoClearFn(cfn, []interface{}{(*j.Jsondata)[jdkey], ""}, j.SpiderCode, j.IsClearnMoney)
  2584. if tmpv.Value == newNum[0] {
  2585. 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)}
  2586. j.Result[jdkey] = append(j.Result[jdkey], extField)
  2587. ju.Sort(j.Result[jdkey])
  2588. delete((*j.Jsondata), jdkey)
  2589. break
  2590. }
  2591. } else {
  2592. if (*j.Jsondata)[jdkey] == tmpv.Value {
  2593. 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}
  2594. j.Result[jdkey] = append(j.Result[jdkey], extField)
  2595. ju.Sort(j.Result[jdkey])
  2596. delete((*j.Jsondata), jdkey)
  2597. break
  2598. }
  2599. }
  2600. }
  2601. }
  2602. }
  2603. if len(*j.Jsondata) > 0 {
  2604. j.Result = JsonDataMergeProcessing(j, e)
  2605. }
  2606. j.Jsondata = &tmpjddata
  2607. }
  2608. return doc, result, _id
  2609. }
  2610. //辅助信息,如果没有排序先排序
  2611. func auxInfo(j *ju.Job) map[string][]map[string]interface{} {
  2612. fieldalls := map[string][]map[string]interface{}{}
  2613. if j == nil {
  2614. return fieldalls
  2615. }
  2616. qykredis := redis.RedisPool[ju.QYK_RedisName].Get()
  2617. defer qykredis.Close()
  2618. db := 0
  2619. for field, val := range j.Result {
  2620. //ju.Sort(val)
  2621. if field == "buyer" {
  2622. db = ju.BuyerDB
  2623. } else if field == "winner" {
  2624. db = ju.WinnerDB
  2625. } else if field == "agency" {
  2626. db = ju.AgencyDB
  2627. }
  2628. sfields := []map[string]interface{}{}
  2629. for _, v := range val {
  2630. standardized := false
  2631. if _, err := qykredis.Do("SELECT", db); err != nil {
  2632. fmt.Println("redis select err", err)
  2633. } else {
  2634. rep, err := qykredis.Do("GET", v.Value)
  2635. if rep != nil && err == nil {
  2636. standardized = true
  2637. }
  2638. }
  2639. if field == "budget" || field == "bidamount" {
  2640. if !v.IsTrue {
  2641. continue
  2642. }
  2643. }
  2644. sfield := map[string]interface{}{
  2645. "val": v.Value,
  2646. "type": v.Type,
  2647. "score": v.Score,
  2648. "blocktag": v.BlockTag,
  2649. "sourceval": v.SourceValue,
  2650. "standardized": standardized,
  2651. }
  2652. sfields = append(sfields, sfield)
  2653. }
  2654. fieldalls[field] = sfields
  2655. }
  2656. return fieldalls
  2657. }
  2658. func (e *ExtractTask) QualityAudit(resulttmp map[string]interface{}) {
  2659. defer qu.Catch()
  2660. //获取审核字段
  2661. for _, field := range e.AuditFields {
  2662. //1.分包
  2663. if resulttmp["package"] != nil {
  2664. packagedata := resulttmp["package"].(map[string]map[string]interface{})
  2665. for _, val := range packagedata {
  2666. if val[field] != nil {
  2667. fv := qu.ObjToString(val[field])
  2668. if fv != "" {
  2669. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  2670. e.RedisMatch(field, fv, val) //redis匹配
  2671. } else { //除了buyer和winner,其他字段走规则匹配
  2672. e.RuleMatch(field, fv, val)
  2673. }
  2674. }
  2675. }
  2676. }
  2677. }
  2678. //2.外围
  2679. if resulttmp[field] != nil {
  2680. fv := qu.ObjToString(resulttmp[field])
  2681. if fv != "" {
  2682. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  2683. e.RedisMatch(field, fv, resulttmp) //redis匹配
  2684. } else { //除了buyer和winner,其他字段走规则匹配
  2685. e.RuleMatch(field, fv, resulttmp)
  2686. }
  2687. }
  2688. }
  2689. }
  2690. }
  2691. //Redis匹配
  2692. func (e *ExtractTask) RedisMatch(field, fv string, val map[string]interface{}) {
  2693. defer qu.Catch()
  2694. i := redis.GetInt(field, field+"_"+fv) //查找redis
  2695. if i == 0 { //reids未找到,执行规则匹配
  2696. val[field+"_isredis"] = false
  2697. e.RuleMatch(field, fv, val) //规则匹配
  2698. } else { //redis找到,打标识存库
  2699. val[field+"_isredis"] = true
  2700. }
  2701. }
  2702. //规则匹配
  2703. func (e *ExtractTask) RuleMatch(field, fieldval string, tmpMap map[string]interface{}) {
  2704. defer qu.Catch()
  2705. if fieldval != "" {
  2706. SMap := e.StartMatch(field, fieldval)
  2707. //SMap.AddKey(field+"_isaudit", false)
  2708. for _, k := range SMap.Keys {
  2709. tmpMap[k] = SMap.Map[k]
  2710. }
  2711. tmpMap[field+"_isaudit"] = false //添加字段未审核信息
  2712. }
  2713. }
  2714. //开始规则匹配
  2715. func (e *ExtractTask) StartMatch(field, text string) *pretreated.SortMap {
  2716. defer qu.Catch()
  2717. SMap := pretreated.NewSortMap()
  2718. lock.Lock()
  2719. f := e.RecogFieldMap[field]
  2720. lock.Unlock()
  2721. if len(f) > 0 {
  2722. fid := qu.BsonIdToSId(f["_id"])
  2723. recogFieldPreRule := qu.ObjToString(f["s_recogfield_prerule"])
  2724. textAfterRecogFieldPrerule := ju.PreFilter(text, recogFieldPreRule) //识别字段的前置过滤
  2725. if textAfterRecogFieldPrerule != "" {
  2726. lock.Lock()
  2727. classMap := e.FidClassMap[fid]
  2728. lock.Unlock()
  2729. L:
  2730. for _, c := range classMap { //class
  2731. classid := qu.BsonIdToSId(c["_id"])
  2732. classPrerule := qu.ObjToString(c["s_class_prerule"])
  2733. savefield := qu.ObjToString(c["s_savefield"]) //保存字段
  2734. textAfterClassPrerule := ju.PreFilter(textAfterRecogFieldPrerule, classPrerule) //class的前置过滤
  2735. if textAfterClassPrerule != "" {
  2736. lock.Lock()
  2737. ruleMap := e.CidRuleMap[classid]
  2738. lock.Unlock()
  2739. for _, r := range ruleMap { //rule
  2740. rulePrerule := qu.ObjToString(r["s_rule_prerule"])
  2741. s_name := qu.ObjToString(r["s_name"])
  2742. rule := r["rule"].([]interface{})
  2743. textAfterRulePrerule := ju.PreFilter(textAfterClassPrerule, rulePrerule) //class的前置过滤
  2744. if textAfterRulePrerule != "" {
  2745. b, _ := ju.RecogAnalyRules(textAfterRulePrerule, rule)
  2746. if b { //匹配到一个分类下某个规则时,不再继续匹配
  2747. if savefield != "" { //保存字段不为空,存储代码信息
  2748. SMap.AddKey(field+"_"+savefield, s_name)
  2749. }
  2750. break L
  2751. }
  2752. }
  2753. }
  2754. }
  2755. }
  2756. }
  2757. }
  2758. return SMap
  2759. }
  2760. //中标候选人经过清理之后,重新取出赋值
  2761. func resetWinnerorder(j *ju.Job) {
  2762. if len(j.Winnerorder) == 0 {
  2763. return
  2764. }
  2765. maxlen := len(j.Winnerorder) - 1
  2766. //中标单位
  2767. //i := 0
  2768. winners := []*ju.ExtField{}
  2769. bidamounts := []*ju.ExtField{}
  2770. if maxlen > 0 {
  2771. if qu.Float64All(j.Winnerorder[0]["sort"]) != 1 {
  2772. return
  2773. }
  2774. winners = append(winners, &ju.ExtField{Code: "winnerorder", Field: "winner", ExtFrom: "j.Winnerorder", Value: j.Winnerorder[0]["entname"], Score: 0.5})
  2775. if j.Winnerorder[0]["price"] != nil {
  2776. tmpPrice := clear.ObjToMoney([]interface{}{j.Winnerorder[0]["price"], ""}, j.SpiderCode, j.IsClearnMoney)
  2777. if tmpPrice[len(tmpPrice)-1].(bool) {
  2778. 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})
  2779. }
  2780. }
  2781. }
  2782. if j.Result["winner"] == nil && len(winners) > 0 {
  2783. j.Result["winner"] = winners
  2784. } else if len(winners) > 0 {
  2785. j.Result["winner"] = append(j.Result["winner"], winners...)
  2786. }
  2787. if j.Result["bidamount"] == nil && len(bidamounts) > 0 {
  2788. j.Result["bidamount"] = bidamounts
  2789. } else if len(bidamounts) > 0 {
  2790. j.Result["bidamount"] = append(j.Result["bidamount"], bidamounts...)
  2791. }
  2792. if j.Result["winner"] == nil && len(j.Winnerorder) > 0 && qu.Float64All(j.Winnerorder[0]["sort"]) == 1 {
  2793. winners = append(winners, &ju.ExtField{Code: "winnerorder", Field: "winner", ExtFrom: "j.Winnerorder", Value: j.Winnerorder[0]["entname"], Score: 0.5})
  2794. j.Result["winner"] = winners
  2795. if j.Winnerorder[0]["price"] != nil {
  2796. tmpPrice := clear.ObjToMoney([]interface{}{j.Winnerorder[0]["price"], ""}, j.SpiderCode, j.IsClearnMoney)
  2797. if tmpPrice[len(tmpPrice)-1].(bool) {
  2798. 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})
  2799. }
  2800. j.Result["bidamount"] = bidamounts
  2801. }
  2802. }
  2803. }
  2804. func RemoveReplicaSliceString(slc []string) []string {
  2805. result := make([]string, 0)
  2806. tempMap := make(map[string]bool, len(slc))
  2807. for _, e := range slc {
  2808. if tempMap[e] == false {
  2809. tempMap[e] = true
  2810. result = append(result, e)
  2811. }
  2812. }
  2813. return result
  2814. }
  2815. type scoreIndex struct {
  2816. Score float64
  2817. Index int
  2818. }