extract.go 76 KB

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