extract.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501
  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. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "unicode/utf8"
  18. log "github.com/donnie4w/go-logger/logger"
  19. "gopkg.in/mgo.v2/bson"
  20. )
  21. var (
  22. lock, lockrule, lockclear sync.RWMutex
  23. cut = ju.NewCut() //获取正文并清理
  24. ExtLogs map[*TaskInfo][]map[string]interface{} //抽取日志
  25. TaskList map[string]*ExtractTask //任务列表
  26. ClearTaskList map[string]*ClearTask //清理任务列表
  27. saveLimit = 200 //抽取日志批量保存
  28. PageSize = 5000 //查询分页
  29. Fields = `{"title":1,"summary":1,"detail":1,"contenthtml":1,"site":1,"spidercode":1,"toptype":1,"subtype":1,"area":1,"city":1,"comeintime":1,"publishtime":1,"sensitive":1,"projectinfo":1,"jsondata":1}`
  30. Fields2 = `{"budget":1,"bidamount":1,"title":1,"projectname":1,"winner":1}`
  31. )
  32. //启动测试抽取
  33. func StartExtractTestTask(taskId, startId, num, resultcoll, trackcoll string) bool {
  34. defer qu.Catch()
  35. ext := &ExtractTask{}
  36. ext.Id = taskId
  37. ext.IsRun = true
  38. ext.InitTestTaskInfo(resultcoll, trackcoll)
  39. ext.TaskInfo.FDB = db.MgoFactory(1, 3, 120, ext.TaskInfo.FromDbAddr, ext.TaskInfo.FromDB)
  40. ext.InitRulePres()
  41. ext.InitRuleBacks()
  42. ext.InitRuleCore()
  43. ext.InitPkgCore()
  44. ext.InitBlockRule()
  45. ext.InfoTypeList()
  46. ext.InitTag()
  47. ext.InitClearFn()
  48. if ext.IsExtractCity { //版本上控制是否开始城市抽取
  49. //初始化城市DFA信息
  50. ext.InitCityDFA()
  51. ext.InitAreaCode()
  52. ext.InitPostCode()
  53. }
  54. //质量审核
  55. ext.InitAuditFields()
  56. ext.InitAuditRule()
  57. ext.InitAuditClass()
  58. ext.InitAuditRecogField()
  59. //品牌抽取是否开启
  60. ju.IsBrandGoods, _ = ju.Config["brandgoods"].(bool)
  61. //附件抽取是否开启
  62. ext.InitFile()
  63. return RunExtractTestTask(ext, startId, num)
  64. }
  65. func IdTrans(startId string) bson.ObjectId {
  66. defer qu.Catch()
  67. return bson.ObjectIdHex(startId)
  68. }
  69. //开始测试任务抽取
  70. func RunExtractTestTask(ext *ExtractTask, startId, num string) bool {
  71. n, _ := strconv.Atoi(num)
  72. id := IdTrans(startId)
  73. if id.Valid() {
  74. query := bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(startId)}}
  75. list, _ := ext.TaskInfo.FDB.Find(ext.TaskInfo.FromColl, query, nil, Fields, false, 0, n)
  76. for _, v := range *list {
  77. if qu.ObjToString(v["sensitive"]) != "" { //去除含敏感词数据
  78. continue
  79. }
  80. var j, jf *ju.Job
  81. if ext.IsFileField && v["projectinfo"] != nil {
  82. v["isextFile"] = true
  83. j, jf = ext.PreInfo(v)
  84. } else {
  85. j, _ = ext.PreInfo(v)
  86. }
  87. ext.TaskInfo.ProcessPool <- true
  88. go ext.ExtractProcess(j, jf)
  89. }
  90. return true
  91. } else {
  92. return false
  93. }
  94. }
  95. //启动抽取
  96. func StartExtractTaskId(taskId string) bool {
  97. defer qu.Catch()
  98. isgo := false
  99. ext := TaskList[taskId]
  100. if ext == nil {
  101. ext = &ExtractTask{}
  102. ext.Id = taskId
  103. ext.InitTaskInfo()
  104. isgo = true
  105. } else {
  106. ext.Id = taskId
  107. ext.InitTaskInfo()
  108. }
  109. ext.TaskInfo.FDB = db.MgoFactory(3, 5, 600, ext.TaskInfo.FromDbAddr, ext.TaskInfo.FromDB)
  110. ext.TaskInfo.TDB = db.MgoFactory(3, 5, 600, ext.TaskInfo.ToDbAddr, ext.TaskInfo.ToDB)
  111. ext.InitRulePres()
  112. ext.InitRuleBacks()
  113. ext.InitRuleCore()
  114. ext.InitPkgCore()
  115. ext.InitBlockRule()
  116. ext.InfoTypeList()
  117. ext.InitTag()
  118. ext.InitClearFn()
  119. if ext.IsExtractCity { //版本上控制是否开始城市抽取
  120. //初始化城市DFA信息
  121. ext.InitCityDFA()
  122. ext.InitAreaCode()
  123. ext.InitPostCode()
  124. }
  125. //质量审核
  126. ext.InitAuditFields()
  127. ext.InitAuditRule()
  128. ext.InitAuditClass()
  129. ext.InitAuditRecogField()
  130. //品牌抽取是否开启
  131. ju.IsBrandGoods, _ = ju.Config["brandgoods"].(bool)
  132. //附件抽取是否开启
  133. ext.InitFile()
  134. ext.IsRun = true
  135. go ext.ResultSave(true)
  136. go ext.BidSave(true)
  137. if isgo {
  138. go RunExtractTask(taskId)
  139. }
  140. TaskList[taskId] = ext
  141. return true
  142. }
  143. //停止抽取
  144. func StopExtractTaskId(taskId string) bool {
  145. defer qu.Catch()
  146. ext := TaskList[taskId]
  147. if ext != nil {
  148. ext.IsRun = false
  149. TaskList[taskId] = ext
  150. }
  151. //更新task.s_extlastid
  152. db.Mgo.UpdateById("task", taskId, `{"$set":{"s_extlastid":"`+ext.TaskInfo.LastExtId+`"}}`)
  153. return true
  154. }
  155. //开始抽取
  156. func RunExtractTask(taskId string) {
  157. defer qu.Catch()
  158. ext := TaskList[taskId]
  159. query := bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(ext.TaskInfo.LastExtId)}}
  160. count := ext.TaskInfo.FDB.Count(ext.TaskInfo.FromColl, query)
  161. pageNum := (count + PageSize - 1) / PageSize
  162. limit := PageSize
  163. if count < PageSize {
  164. limit = count
  165. }
  166. fmt.Printf("count=%d,pageNum=%d,query=%v", count, pageNum, query)
  167. for i := 0; i < pageNum; i++ {
  168. query = bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(ext.TaskInfo.LastExtId)}}
  169. fmt.Printf("page=%d,query=%v", i+1, query)
  170. list, _ := ext.TaskInfo.FDB.Find(ext.TaskInfo.FromColl, query, nil, Fields, false, 0, limit)
  171. for _, v := range *list {
  172. if qu.ObjToString(v["sensitive"]) != "" { //去除含敏感词数据
  173. continue
  174. }
  175. //根据标题判断是否抽取
  176. b := IsExtract("title", qu.ObjToString(v["title"]), "")
  177. if !b {
  178. continue
  179. }
  180. _id := qu.BsonIdToSId(v["_id"])
  181. //log.Debug(_id)
  182. if !ext.IsRun {
  183. break
  184. }
  185. var j, jf *ju.Job
  186. if ext.IsFileField && v["projectinfo"] != nil {
  187. v["isextFile"] = true
  188. j, jf = ext.PreInfo(v)
  189. } else {
  190. j, _ = ext.PreInfo(v)
  191. }
  192. ext.TaskInfo.ProcessPool <- true
  193. go ext.ExtractProcess(j, jf)
  194. ext.TaskInfo.LastExtId = _id
  195. }
  196. db.Mgo.UpdateById("task", ext.Id, `{"$set":{"s_extlastid":"`+ext.TaskInfo.LastExtId+`"}}`)
  197. if !ext.IsRun {
  198. break
  199. }
  200. }
  201. //更新task.s_extlastid
  202. time.AfterFunc(1*time.Minute, func() { RunExtractTask(taskId) })
  203. }
  204. //信息预处理-不和版本关联,取最新版本的配置项
  205. func PreInfo(doc map[string]interface{}) (j, jf *ju.Job) {
  206. return (&ExtractTask{}).PreInfo(doc)
  207. }
  208. //信息预处理-和版本关联
  209. func (e *ExtractTask) PreInfo(doc map[string]interface{}) (j, jf *ju.Job) {
  210. defer qu.Catch()
  211. //判断是否有附件这个字段
  212. var isextFile bool
  213. if doc["isextFile"] != nil {
  214. isextFile = doc["isextFile"].(bool)
  215. }
  216. detail := ""
  217. d1, _ := doc["detail"].(string)
  218. d2, _ := doc["contenthtml"].(string)
  219. if len(d1) >= len(d2) || d2 == "" {
  220. detail = d1
  221. } else {
  222. detail = d2
  223. }
  224. d3, _ := doc["summary"].(string)
  225. detail = ju.CutLableStr(d3 + "\n" + detail)
  226. detail = cut.ClearHtml(d3 + "\n" + detail)
  227. doc["detail"] = detail
  228. if isextFile {
  229. file2text(&doc) //附件文本堆一起(后期可以考虑,分开处理),方法里修改了doc["detailfile"]结果
  230. }
  231. toptype := qu.ObjToString(doc["toptype"])
  232. subtype := qu.ObjToString(doc["subtype"])
  233. if qu.ObjToString(doc["type"]) == "bid" {
  234. toptype = "结果"
  235. }
  236. if toptype == "" {
  237. toptype = "all"
  238. }
  239. if subtype == "" {
  240. subtype = "all"
  241. }
  242. j = &ju.Job{
  243. SourceMid: qu.BsonIdToSId(doc["_id"]),
  244. Category: toptype,
  245. CategorySecond: subtype,
  246. Content: qu.ObjToString(doc["detail"]),
  247. SpiderCode: qu.ObjToString(doc["spidercode"]),
  248. //Domain: qu.ObjToString(doc["domain"]),
  249. //Href: qu.ObjToString(doc["href"]),
  250. Title: qu.ObjToString(doc["title"]),
  251. Data: &doc,
  252. City: qu.ObjToString(doc["city"]),
  253. Province: qu.ObjToString(doc["area"]),
  254. Jsondata: qu.ObjToMap(doc["jsondata"]),
  255. Result: map[string][]*ju.ExtField{},
  256. BuyerAddr: qu.ObjToString(doc["buyeraddr"]),
  257. RuleBlock: e.RuleBlock,
  258. }
  259. if isextFile {
  260. jf = &ju.Job{
  261. SourceMid: qu.BsonIdToSId(doc["_id"]),
  262. Category: toptype,
  263. Content: qu.ObjToString(doc["detailfile"]),
  264. SpiderCode: qu.ObjToString(doc["spidercode"]),
  265. Title: qu.ObjToString(doc["title"]),
  266. Data: &doc,
  267. City: qu.ObjToString(doc["city"]),
  268. Province: qu.ObjToString(doc["area"]),
  269. Jsondata: qu.ObjToMap(doc["jsondata"]),
  270. Result: map[string][]*ju.ExtField{},
  271. BuyerAddr: qu.ObjToString(doc["buyeraddr"]),
  272. RuleBlock: e.RuleBlock,
  273. IsFile: isextFile,
  274. }
  275. }
  276. qu.Try(func() {
  277. pretreated.AnalyStart(j) //job.Block分块
  278. if isextFile {
  279. pretreated.AnalyStart(jf)
  280. }
  281. }, func(err interface{}) {
  282. log.Debug("pretreated.AnalyStart", err, j.SourceMid)
  283. })
  284. return j, jf
  285. }
  286. //遍历附件字段内容,拼接在一起;附件文本堆一起(后期可以考虑,分开处理),方法里修改了doc["detailfile"]结果
  287. func file2text(doc *map[string]interface{}) {
  288. var strfileinfo bytes.Buffer
  289. if v, ok := (*doc)["projectinfo"].(map[string]interface{}); ok {
  290. if va, ok := v["attachments"].(map[string]interface{}); ok {
  291. for _, vaatt := range va {
  292. if fileinfo, ok := vaatt.(map[string]interface{}); ok {
  293. if qu.ObjToString(fileinfo["content"]) != "" {
  294. switch fileinfo["content"].(type) {
  295. case string:
  296. lock.Lock()
  297. strfileinfo.WriteString(fileinfo["content"].(string) + " \n")
  298. lock.Unlock()
  299. case []map[string]interface{}:
  300. for _, fv := range fileinfo["content"].([]map[string]interface{}) {
  301. if fv["context"] != nil {
  302. lock.Lock()
  303. strfileinfo.WriteString(fv["context"].(string) + " \n")
  304. lock.Unlock()
  305. }
  306. }
  307. }
  308. }
  309. }
  310. }
  311. }
  312. }
  313. if utf8.RuneCountInString(strfileinfo.String()) < qu.IntAllDef(ju.Config["filelength"], 100000) {
  314. (*doc)["detailfile"] = strfileinfo.String() //附件文本堆一起(后期可以考虑,分开处理)
  315. }
  316. }
  317. //抽取
  318. func (e *ExtractTask) ExtractProcess(j, jf *ju.Job) {
  319. e.ExtractDetail(j)
  320. if jf != nil && jf.IsFile {
  321. e.ExtractFile(jf)
  322. }
  323. //分析抽取结果并保存 todo
  324. AnalysisSaveResult(j, jf, e)
  325. <-e.TaskInfo.ProcessPool
  326. }
  327. func (e *ExtractTask) ExtractDetail(j *ju.Job) {
  328. qu.Try(func() {
  329. doc := *j.Data
  330. //全局前置规则,结果覆盖doc属性
  331. //for _, v := range e.RulePres {
  332. // doc = ExtRegPre(doc, j, v, e.TaskInfo)
  333. //}
  334. tmprules := map[string][]*RuleCore{}
  335. lockrule.Lock()
  336. if j.Category == "all" || j.CategorySecond == "all" {
  337. for k, vc1 := range e.RuleCores["all_all"] {
  338. tmprules[k] = vc1
  339. }
  340. } else {
  341. for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
  342. tmprules[k] = vc1
  343. }
  344. }
  345. if len(tmprules) < 1 { //分类未覆盖部分
  346. for k, vc1 := range e.RuleCores["all_all"] {
  347. tmprules[k] = vc1
  348. }
  349. }
  350. lockrule.Unlock()
  351. //抽取规则
  352. for _, vc1 := range tmprules {
  353. for _, vc := range vc1 {
  354. tmp := ju.DeepCopy(doc).(map[string]interface{})
  355. //是否进入逻辑
  356. if !ju.Logic(vc.LuaLogic, tmp) {
  357. continue
  358. }
  359. ////抽取-前置规则
  360. //for _, v := range vc.RulePres {
  361. // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
  362. //}
  363. // log.Debug("抽取-前置规则", tmp)
  364. //抽取-规则
  365. for _, v := range vc.RuleCores {
  366. ExtRegCore(vc.ExtFrom, tmp, j, v, e)
  367. }
  368. // log.Debug("抽取-规则", tmp)
  369. //项目名称未能抽取到,标题来凑
  370. if vc.Field == "projectname" {
  371. //if len(j.Result[vc.Field]) < 1 {//如果抽取有结果,不走标题。待验证,暂时标题加入选举逻辑
  372. 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}
  373. if tmp["blocktag"] != nil {
  374. btag := make(map[string]string)
  375. for k := range tmp["blocktag"].(map[string]bool) {
  376. btag[k] = TagConfigDesc[k]
  377. }
  378. field.BlockTag = btag
  379. }
  380. j.Result[vc.Field] = append(j.Result[vc.Field], field)
  381. //}
  382. }
  383. //抽取-后置规则
  384. for _, v := range vc.RuleBacks {
  385. ExtRegBack(j, v, e.TaskInfo)
  386. }
  387. // log.Debug("抽取-后置规则", tmp)
  388. }
  389. }
  390. //for _, vvc := range j.Result["budget"] {
  391. //log.Debug("-----", fmt.Sprintf("%+v", vvc))
  392. //}
  393. //全局后置规则
  394. for _, v := range e.RuleBacks {
  395. ExtRegBack(j, v, e.TaskInfo)
  396. }
  397. //候选人加入
  398. if len(j.Winnerorder) > 0 {
  399. winner := &ju.ExtField{
  400. Field: "winner",
  401. Code: "",
  402. RuleText: "",
  403. Type: "winnerorder",
  404. MatchType: "winnerorder",
  405. ExtFrom: "",
  406. Value: j.Winnerorder[0]["entname"],
  407. Score: 0,
  408. }
  409. if len([]rune(qu.ObjToString(j.Winnerorder[0]["entname"]))) < 4 {
  410. winner.Score = -5
  411. }
  412. winners := j.Result["winner"]
  413. if winners != nil {
  414. winners = append(winners, winner)
  415. } else {
  416. winners = []*ju.ExtField{}
  417. winners = append(winners, winner)
  418. }
  419. j.Result["winner"] = winners
  420. }
  421. //函数清理
  422. for key, val := range j.Result {
  423. tmpExtFields := make([]*ju.ExtField, 0)
  424. tmpWeight := -999 //记录最大权重
  425. tmpIndex := -999 //记录最大权重下标
  426. for _, v := range val {
  427. lockclear.Lock()
  428. cfn := e.ClearFn[key]
  429. lockclear.Unlock()
  430. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content})
  431. before, _ := v.Value.(string)
  432. v.Value = data[0]
  433. BeforeAddClearFnLog("clearcfn", "函数清理", j.SourceMid, before, "clear_cfn", v, e)
  434. //添加行数清理的日志
  435. //清理特殊符号
  436. lockclear.Lock()
  437. if clear.AsyField[key] != nil || clear.SymField[key] != nil || clear.MesField[key] != nil {
  438. text := qu.ObjToString(v.Value)
  439. before = text
  440. text = clear.OtherClean(key, text)
  441. if text != "" {
  442. v.Value = text
  443. }
  444. BeforeAddClearFnLog("clearsymbol", "特殊符号清理", j.SourceMid, before, "clear_symbol", v, e)
  445. }
  446. //AddClearFnLog("clearfn", j.SourceMid, v.Value, extinfo, v.Code, "函数清理", key, e.TaskInfo)
  447. lockclear.Unlock()
  448. }
  449. //项目编号,采购单位权重清理
  450. if (key == "projectcode" || key == "buyer") && len(val) > 1 {
  451. for i, v := range val {
  452. if v.Weight == 0 {
  453. tmpExtFields = append(tmpExtFields, v)
  454. continue
  455. } else if v.Weight > tmpWeight {
  456. tmpWeight = v.Weight
  457. tmpIndex = i
  458. }
  459. }
  460. if tmpIndex != -999 {
  461. tmpExtFields = append(tmpExtFields, val[tmpIndex])
  462. j.Result[key] = tmpExtFields
  463. }
  464. }
  465. }
  466. PackageDetail(j, e) //处理分包信息
  467. // bs, _ := json.Marshal(j.Result)
  468. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  469. }, func(err interface{}) {
  470. log.Debug("ExtractProcess err", err)
  471. })
  472. }
  473. func (e *ExtractTask) ExtractFile(j *ju.Job) {
  474. qu.Try(func() {
  475. doc := *j.Data
  476. //全局前置规则,结果覆盖doc属性
  477. // for _, v := range e.RulePres {
  478. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  479. // doc = ExtRegPre(doc, j, v, e.TaskInfo)
  480. // }
  481. // }
  482. //抽取规则
  483. tmprules := map[string][]*RuleCore{}
  484. lockrule.Lock()
  485. if j.Category == "all" || j.CategorySecond == "all" {
  486. for k, vc1 := range e.RuleCores["all_all"] {
  487. tmprules[k] = vc1
  488. }
  489. } else {
  490. for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
  491. tmprules[k] = vc1
  492. }
  493. }
  494. lockrule.Unlock()
  495. for _, vc1 := range tmprules {
  496. for _, vc := range vc1 {
  497. tmp := ju.DeepCopy(doc).(map[string]interface{})
  498. //是否进入逻辑
  499. if !ju.Logic(vc.LuaLogic, tmp) {
  500. continue
  501. }
  502. //抽取-前置规则
  503. // for _, v := range vc.RulePres {
  504. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  505. // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
  506. // }
  507. // }
  508. // log.Debug("抽取-前置规则", tmp)
  509. //抽取-规则
  510. for _, v := range vc.RuleCores {
  511. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  512. ExtRegCore(vc.ExtFrom, tmp, j, v, e)
  513. }
  514. }
  515. // log.Debug("抽取-规则", tmp)
  516. //抽取-后置规则
  517. for _, v := range vc.RuleBacks {
  518. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  519. ExtRegBack(j, v, e.TaskInfo)
  520. }
  521. }
  522. // log.Debug("抽取-后置规则", tmp)
  523. }
  524. }
  525. //全局后置规则
  526. for _, v := range e.RuleBacks {
  527. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  528. ExtRegBack(j, v, e.TaskInfo)
  529. }
  530. }
  531. //候选人加入
  532. if len(j.Winnerorder) > 0 {
  533. winner := &ju.ExtField{
  534. Field: "winner",
  535. Code: "",
  536. RuleText: "",
  537. Type: "winnerorder",
  538. MatchType: "winnerorder",
  539. ExtFrom: "",
  540. Value: j.Winnerorder[0]["entname"],
  541. Score: 0,
  542. }
  543. if len([]rune(qu.ObjToString(j.Winnerorder[0]["entname"]))) < 4 {
  544. winner.Score = -5
  545. }
  546. winners := j.Result["winner"]
  547. if winners != nil {
  548. winners = append(winners, winner)
  549. } else {
  550. winners = []*ju.ExtField{}
  551. winners = append(winners, winner)
  552. }
  553. j.Result["winner"] = winners
  554. }
  555. //函数清理
  556. for key, val := range j.Result {
  557. for _, v := range val {
  558. lockclear.Lock()
  559. cfn := e.ClearFn[key]
  560. lockclear.Unlock()
  561. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content})
  562. v.Value = data[0]
  563. //清理特殊符号
  564. lockclear.Lock()
  565. if clear.AsyField[key] != nil || clear.SymField[key] != nil ||
  566. clear.MesField[key] != nil {
  567. text := qu.ObjToString(v.Value)
  568. text = clear.OtherClean(key, text)
  569. v.Value = text
  570. }
  571. lockclear.Unlock()
  572. }
  573. }
  574. PackageDetail(j, e) //处理分包信息
  575. // bs, _ := json.Marshal(j.Result)
  576. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  577. }, func(err interface{}) {
  578. log.Debug("ExtractProcess err", err)
  579. })
  580. }
  581. //前置过滤
  582. func ExtRegPre(doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, t *TaskInfo) map[string]interface{} {
  583. defer qu.Catch()
  584. before := ju.DeepCopy(doc).(map[string]interface{})
  585. extinfo := map[string]interface{}{}
  586. if in.IsLua {
  587. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  588. if j != nil {
  589. lua.Block = j.Block
  590. }
  591. extinfo = lua.RunScript("pre")
  592. for k, v := range extinfo { //结果覆盖原doc
  593. doc[k] = v
  594. }
  595. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  596. } else {
  597. var key string
  598. if !j.IsFile {
  599. key = qu.If(in.Field == "", "detail", in.Field).(string)
  600. } else {
  601. key = qu.If(in.Field == "", "detailfile", in.Field).(string)
  602. }
  603. text := qu.ObjToString(doc[key])
  604. extinfo[key] = in.RegPreBac.Reg.ReplaceAllString(text, "")
  605. doc[key] = extinfo[key] //结果覆盖原doc
  606. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  607. }
  608. return doc
  609. }
  610. //抽取-规则
  611. func ExtRegCore(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, et *ExtractTask) {
  612. defer qu.Catch()
  613. //根据field配置项目,是否抽取。例如:废标、流标等跳过,
  614. b := IsExtract(in.Field, j.Title, j.Content)
  615. if !b {
  616. return
  617. }
  618. kvMap := getKvByLuaFields(extfrom, j, in, et.Tag)
  619. if in.IsLua {
  620. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  621. lua.KvMap = kvMap
  622. lua.Block = j.Block
  623. extinfo := lua.RunScript("core")
  624. if tmps, ok := extinfo[in.Field].([]map[string]interface{}); ok {
  625. kvMap[in.Field] = tmps
  626. }
  627. }
  628. if len(kvMap) > 0 {
  629. if j.Result[in.Field] == nil {
  630. j.Result[in.Field] = [](*ju.ExtField){}
  631. }
  632. for _, tmp := range kvMap[in.Field] {
  633. field := &ju.ExtField{Weight: qu.IntAll(tmp["weight"]), Field: in.Field, Code: qu.ObjToString(tmp["code"]), Type: qu.ObjToString(tmp["type"]), RuleText: qu.ObjToString(tmp["ruletext"]), SourceValue: tmp["sourcevalue"], Value: tmp["value"]}
  634. if tmp["blocktag"] != nil {
  635. btag := make(map[string]string)
  636. for k := range tmp["blocktag"].(map[string]bool) {
  637. if TagConfigDesc[k] != "" {
  638. btag[k] = TagConfigDesc[k]
  639. }
  640. }
  641. field.BlockTag = btag
  642. }
  643. j.Result[in.Field] = append(j.Result[in.Field], field)
  644. }
  645. AddExtLog("extract", j.SourceMid, nil, kvMap, in, et.TaskInfo) //抽取日志
  646. } else if !in.IsLua {
  647. //全文正则
  648. //text := qu.ObjToString(doc[extfrom])
  649. //if in.Field != "" {
  650. // extinfo := extRegCoreToResult(extfrom, text, j, in)
  651. // if len(extinfo) > 0 {
  652. // AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  653. // }
  654. //}
  655. //块抽取
  656. if in.Field != "" {
  657. if extfrom == "title" {
  658. extinfo := extRegCoreToResult(extfrom, qu.ObjToString(doc[extfrom]), &map[string]string{}, j, in)
  659. if len(extinfo) > 0 {
  660. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  661. }
  662. } else {
  663. for _, v := range j.Block {
  664. btag := make(map[string]string)
  665. for k := range v.Classify {
  666. btag[k] = TagConfigDesc[k]
  667. }
  668. extinfo := extRegCoreToResult(extfrom, v.Text, &btag, j, in)
  669. if len(extinfo) > 0 {
  670. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  671. }
  672. }
  673. }
  674. }
  675. }
  676. }
  677. //lua脚本根据属性设置提取kv值
  678. func getKvByLuaFields(extfrom string, j *ju.Job, in *RegLuaInfo, t map[string][]*Tag) map[string][]map[string]interface{} {
  679. kvmap := map[string][]map[string]interface{}{}
  680. blocks := []*ju.Block{}
  681. for _, bl := range j.Block {
  682. if len(bl.Block) > 0 {
  683. blocks = append(blocks, bl.Block...)
  684. } else {
  685. blocks = append(blocks, bl)
  686. }
  687. }
  688. for fieldname, field := range in.LFields {
  689. if field != in.Field {
  690. continue
  691. }
  692. for _, bl := range blocks {
  693. tp := ""
  694. for k, v := range []*ju.JobKv{bl.ColonKV, bl.SpaceKV, bl.TableKV} {
  695. if k == 0 {
  696. tp = "colon"
  697. } else if k == 1 {
  698. tp = "space"
  699. } else if k == 2 {
  700. tp = "table"
  701. }
  702. if v == nil || v.KvTags == nil {
  703. continue
  704. }
  705. for _, vv := range v.KvTags[fieldname] {
  706. text := ju.TrimLRSpace(vv.Value, "")
  707. if text != "" {
  708. kvmap[field] = append(kvmap[field], map[string]interface{}{
  709. "field": field,
  710. "code": in.Code,
  711. "ruletext": vv.Key,
  712. "extfrom": extfrom,
  713. "sourcevalue": text,
  714. "value": text,
  715. "type": tp,
  716. "matchtype": "tag_string",
  717. "blocktag": bl.Classify,
  718. "weight": vv.Weight,
  719. })
  720. }
  721. }
  722. }
  723. }
  724. }
  725. return kvmap
  726. }
  727. //正则提取结果
  728. func extRegCoreToResult(extfrom, text string, tag *map[string]string, j *ju.Job, v *RegLuaInfo) map[string][]map[string]interface{} {
  729. defer qu.Catch()
  730. extinfo := map[string][]map[string]interface{}{}
  731. if v.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
  732. apos := v.RegCore.Reg.FindAllStringSubmatchIndex(text, -1)
  733. if len(apos) > 0 {
  734. pos := apos[0]
  735. for k, p := range v.RegCore.ExtractPos {
  736. if len(pos) > p {
  737. if pos[p] == -1 || pos[p+1] == -1 {
  738. continue
  739. }
  740. val := text[pos[p]:pos[p+1]]
  741. sourcevalue := val
  742. if val == "招标公告" {
  743. return extinfo
  744. }
  745. if utf8.RuneCountInString(val) < 2 && extfrom == "title" {
  746. val = text
  747. }
  748. tmps := []map[string]interface{}{}
  749. tmp := map[string]interface{}{
  750. "field": v.Field,
  751. "code": v.Code,
  752. "ruletext": v.RuleText,
  753. "extfrom": extfrom,
  754. "value": val,
  755. "type": "regexp",
  756. "matchtype": "regcontent",
  757. "blocktag": *tag,
  758. }
  759. tmps = append(tmps, tmp)
  760. extinfo[k] = tmps
  761. if strings.TrimSpace(val) != "" {
  762. if v.RegCore.NumSign == -1 { //正负值修正
  763. val = "-" + val
  764. }
  765. exfield := ju.ExtField{BlockTag: *tag, Field: k, Code: v.Code, RuleText: v.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: sourcevalue, Value: val}
  766. if tmp["blocktag"] != nil {
  767. exfield.BlockTag = tmp["blocktag"].(map[string]string)
  768. }
  769. j.Result[k] = append(j.Result[k], &exfield)
  770. //j.Result[k] = append(j.Result[k], &ju.ExtField{tmp["blocktag"].(map[string]bool), k, v.Code, v.RuleText, "regexp", "regcontent", extfrom, val, 0})
  771. }
  772. }
  773. }
  774. if len(extinfo) == 0 {
  775. regArr := strings.Split(v.RuleText, "__")
  776. //fmt.Println(regArr[0])
  777. if len(regArr) > 0 {
  778. reg, err := regexp.Compile(regArr[0])
  779. if err == nil {
  780. datavals := reg.FindStringSubmatch(text)
  781. tmps := []map[string]interface{}{}
  782. for _, value := range datavals {
  783. if value == "" {
  784. continue
  785. }
  786. tmp := map[string]interface{}{
  787. "field": v.Field,
  788. "code": v.Code,
  789. "ruletext": regArr[0],
  790. "extfrom": extfrom,
  791. "value": value,
  792. "type": "regexp",
  793. "matchtype": "regcontent",
  794. "blocktag": *tag,
  795. }
  796. tmps = append(tmps, tmp)
  797. extinfo[v.Field] = tmps
  798. exfield := ju.ExtField{BlockTag: *tag, Field: v.Field, Code: v.Code + "去除__*后", RuleText: v.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: text, Value: value}
  799. if tmp["blocktag"] != nil {
  800. exfield.BlockTag = tmp["blocktag"].(map[string]string)
  801. }
  802. j.Result[v.Field] = append(j.Result[v.Field], &exfield)
  803. //j.Result[k] = append(j.Result[k], &ju.ExtField{tmp["blocktag"].(map[string]bool), k, v.Code, v.RuleText, "regexp", "regcontent", extfrom, val, 0})
  804. }
  805. }
  806. }
  807. }
  808. }
  809. } else {
  810. pos := v.RegCore.Reg.FindStringIndex(text)
  811. val := ""
  812. if len(pos) == 2 {
  813. text = text[pos[1]:]
  814. rs := regexp.MustCompile("[^\r\n\t]+")
  815. tmp := rs.FindAllString(text, -1)
  816. if len(tmp) > 0 {
  817. val = tmp[0]
  818. }
  819. }
  820. if val != "" {
  821. tmps := []map[string]interface{}{}
  822. tmp := map[string]interface{}{
  823. "field": v.Field,
  824. "code": v.Code,
  825. "ruletext": v.RuleText,
  826. "extfrom": extfrom,
  827. "value": val,
  828. "type": "regexp",
  829. "matchtype": "regcontent",
  830. "blocktag": *tag,
  831. }
  832. tmps = append(tmps, tmp)
  833. extinfo[v.Field] = tmps
  834. if j.Result[v.Field] == nil {
  835. j.Result[v.Field] = [](*ju.ExtField){}
  836. }
  837. field := &ju.ExtField{BlockTag: *tag, Field: v.Field, Code: v.Code, RuleText: v.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: text, Value: val}
  838. if tmp["blocktag"] != nil {
  839. field.BlockTag = tmp["blocktag"].(map[string]string)
  840. }
  841. j.Result[v.Field] = append(j.Result[v.Field], field)
  842. }
  843. }
  844. return extinfo
  845. }
  846. //后置过滤
  847. func ExtRegBack(j *ju.Job, in *RegLuaInfo, t *TaskInfo) {
  848. defer qu.Catch()
  849. if in.IsLua {
  850. result := GetResultMapForLua(j)
  851. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Result: result, Script: in.RuleText}
  852. if j != nil {
  853. lua.Block = j.Block
  854. }
  855. extinfo := lua.RunScript("back")
  856. for k, v := range extinfo {
  857. if tmps, ok := v.([]map[string]interface{}); ok {
  858. j.Result[k] = [](*ju.ExtField){}
  859. for _, tmp := range tmps {
  860. 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"]), ExtFrom: qu.ObjToString(tmp["extfrom"]), Value: tmp["value"], Score: 0}
  861. if tmp["blocktag"] != nil {
  862. field.BlockTag = tmp["blocktag"].(map[string]string)
  863. }
  864. j.Result[k] = append(j.Result[k], field)
  865. //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})
  866. }
  867. }
  868. }
  869. if len(extinfo) > 0 {
  870. AddExtLog("clear", j.SourceMid, result, extinfo, in, t) //抽取日志
  871. }
  872. } else {
  873. extinfo := map[string]interface{}{}
  874. if in.Field != "" {
  875. if j.Result[in.Field] != nil {
  876. tmp := j.Result[in.Field]
  877. exts := []interface{}{}
  878. for k, v := range tmp {
  879. //table抽取到的数据不清理
  880. // if v.Type == "table" && v.Field != "projectname" {
  881. // continue
  882. // }
  883. text := qu.ObjToString(v.Value)
  884. if text != "" {
  885. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  886. }
  887. j.Result[in.Field][k].Value = text
  888. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  889. continue
  890. }
  891. exts = append(exts, map[string]interface{}{
  892. "field": v.Field,
  893. "code": v.Code,
  894. "ruletext": v.RuleText,
  895. "type": v.Type,
  896. "matchtype": v.MatchType,
  897. "extfrom": v.ExtFrom,
  898. "value": text,
  899. })
  900. }
  901. extinfo[in.Field] = exts
  902. if len(extinfo) > 0 {
  903. AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
  904. }
  905. }
  906. } else {
  907. for key, tmp := range j.Result {
  908. exts := []interface{}{}
  909. for k, v := range tmp {
  910. if v.Type == "table" { //table抽取到的数据不清理
  911. continue
  912. }
  913. text := qu.ObjToString(v.Value)
  914. if text != "" {
  915. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  916. }
  917. j.Result[key][k].Value = text
  918. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  919. continue
  920. }
  921. exts = append(exts, map[string]interface{}{
  922. "field": v.Field,
  923. "code": v.Code,
  924. "ruletext": v.RuleText,
  925. "type": v.Type,
  926. "matchtype": v.MatchType,
  927. "extfrom": v.ExtFrom,
  928. "value": text,
  929. })
  930. }
  931. extinfo[key] = exts
  932. }
  933. if len(extinfo) > 0 {
  934. AddExtLog("clear", j.SourceMid, j.Result, extinfo, in, t) //抽取日志
  935. }
  936. }
  937. }
  938. }
  939. //获取抽取结果map[string][]interface{},lua脚本使用
  940. func GetResultMapForLua(j *ju.Job) map[string][]map[string]interface{} {
  941. defer qu.Catch()
  942. result := map[string][]map[string]interface{}{}
  943. for key, val := range j.Result {
  944. if result[key] == nil {
  945. result[key] = []map[string]interface{}{}
  946. }
  947. for _, v := range val {
  948. tmp := map[string]interface{}{
  949. "field": v.Field,
  950. "code": v.Code,
  951. "ruletext": v.RuleText,
  952. "value": v.Value,
  953. "type": v.Type,
  954. "matchtype": v.MatchType,
  955. "extfrom": v.ExtFrom,
  956. }
  957. result[key] = append(result[key], tmp)
  958. }
  959. }
  960. return result
  961. }
  962. //抽取日志
  963. func AddExtLog(ftype, sid string, before interface{}, extinfo interface{}, v *RegLuaInfo, t *TaskInfo) {
  964. defer qu.Catch()
  965. if !t.IsEtxLog {
  966. return
  967. }
  968. logdata := map[string]interface{}{
  969. "code": v.Code,
  970. "name": v.Name,
  971. "type": ftype,
  972. "ruletext": v.RuleText,
  973. "islua": v.IsLua,
  974. "field": v.Field,
  975. "version": t.Version,
  976. "taskname": t.Name,
  977. "before": before,
  978. "extinfo": extinfo,
  979. "sid": sid,
  980. "comeintime": time.Now().Unix(),
  981. }
  982. lock.Lock()
  983. ExtLogs[t] = append(ExtLogs[t], logdata)
  984. lock.Unlock()
  985. }
  986. func BeforeAddClearFnLog(ftype, name, sid, before, matchtype string, ext *ju.ExtField, e *ExtractTask) {
  987. exts := []map[string]interface{}{}
  988. exts = append(exts, map[string]interface{}{
  989. "field": ext.Field,
  990. "code": ext.Code,
  991. "type": ftype,
  992. "matchtype": matchtype,
  993. "extfrom": ext.ExtFrom,
  994. "value": ext.Value,
  995. })
  996. extinfo := map[string]interface{}{
  997. ext.Field: exts,
  998. }
  999. AddClearFnLog(ftype, sid, before, extinfo, ext.Code, name, ext.Field, e.TaskInfo)
  1000. }
  1001. func AddClearFnLog(ftype, sid string, before interface{}, extinfo interface{}, code, name, field string, t *TaskInfo) {
  1002. defer qu.Catch()
  1003. if !t.IsEtxLog {
  1004. return
  1005. }
  1006. logdata := map[string]interface{}{
  1007. "code": code,
  1008. "name": name,
  1009. "type": ftype,
  1010. "ruletext": "",
  1011. "islua": false,
  1012. "field": field,
  1013. "version": t.Version,
  1014. "taskname": t.Name,
  1015. "before": before,
  1016. "extinfo": extinfo,
  1017. "sid": sid,
  1018. "comeintime": time.Now().Unix(),
  1019. }
  1020. lock.Lock()
  1021. ExtLogs[t] = append(ExtLogs[t], logdata)
  1022. lock.Unlock()
  1023. }
  1024. //保存抽取日志
  1025. func SaveExtLog() {
  1026. defer qu.Catch()
  1027. tmpLogs := map[*TaskInfo][]map[string]interface{}{}
  1028. lock.Lock()
  1029. tmpLogs = ExtLogs
  1030. ExtLogs = map[*TaskInfo][]map[string]interface{}{}
  1031. lock.Unlock()
  1032. for k, v := range tmpLogs {
  1033. if len(v) < saveLimit {
  1034. db.Mgo.SaveBulk(k.TrackColl, v...)
  1035. } else {
  1036. for {
  1037. if len(v) > saveLimit {
  1038. tmp := v[:saveLimit]
  1039. db.Mgo.SaveBulk(k.TrackColl, tmp...)
  1040. v = v[saveLimit:]
  1041. } else {
  1042. db.Mgo.SaveBulk(k.TrackColl, v...)
  1043. break
  1044. }
  1045. }
  1046. }
  1047. }
  1048. time.AfterFunc(10*time.Second, SaveExtLog)
  1049. }
  1050. type FieldValue struct {
  1051. Value interface{}
  1052. Count int
  1053. }
  1054. //分析抽取结果并保存
  1055. func AnalysisSaveResult(j, jf *ju.Job, e *ExtractTask) {
  1056. qu.Try(func() {
  1057. doc, result, _id := funcAnalysis(j)
  1058. if isSaveTag, _ := ju.Config["isSaveTag"].(bool); isSaveTag {
  1059. go otherNeedSave(j, result, e)
  1060. }
  1061. auxinfo := auxInfo(j)
  1062. //从排序结果中取值
  1063. tmp := map[string]interface{}{} //抽取值
  1064. tmp["fieldall"] = auxinfo
  1065. for _, val := range result {
  1066. for _, v := range val { //取第一个非负数
  1067. if v.Score > -1 {
  1068. tmp[v.Field] = v.Value
  1069. break
  1070. }
  1071. }
  1072. }
  1073. if len(j.PackageInfo) > 0 { //分包信息
  1074. tmp["package"] = j.PackageInfo
  1075. }
  1076. if len(j.Winnerorder) > 0 { //候选人信息
  1077. tmp["winnerorder"] = j.Winnerorder
  1078. }
  1079. //处理附件
  1080. var resultf map[string][]*ju.ExtField
  1081. if jf != nil {
  1082. _, resultf, _ = funcAnalysis(jf)
  1083. auxinfof := auxInfo(jf)
  1084. tmp["fieldallf"] = auxinfof
  1085. ffield := map[string]interface{}{}
  1086. for _, val := range resultf {
  1087. for _, v := range val { //取第一个非负数
  1088. if v.Score > -1 {
  1089. ffield[v.Field] = v.Value
  1090. break
  1091. }
  1092. }
  1093. }
  1094. if len(jf.PackageInfo) > 0 { //分包信息
  1095. ffield["package"] = jf.PackageInfo
  1096. }
  1097. if len(jf.Winnerorder) > 0 { //候选人信息
  1098. ffield["winnerorder"] = jf.Winnerorder
  1099. }
  1100. tmp["ffield"] = ffield
  1101. }
  1102. for k, v := range *doc {
  1103. //去重冗余字段
  1104. if delFiled(k) {
  1105. continue
  1106. }
  1107. if tmp[k] == nil {
  1108. tmp[k] = v
  1109. }
  1110. }
  1111. //质量审核
  1112. if ok, _ := ju.Config["qualityaudit"].(bool); ok {
  1113. e.QualityAudit(tmp)
  1114. }
  1115. if e.IsExtractCity { //城市抽取
  1116. e.ExtractCity(j, tmp, _id)
  1117. // b, p, c, d := e.TransmitData(tmp, _id) //抽取省份城市
  1118. // // log.Debug("省份---", p, "城市---", c, "区---", d)
  1119. // tmp["district"] = d
  1120. // if b {
  1121. // tmp["city"] = c
  1122. // tmp["area"] = p
  1123. // }
  1124. }
  1125. //品牌抽取
  1126. if ju.IsBrandGoods {
  1127. tmp["checkhas"] = map[string]int{
  1128. "hastable": j.HasTable,
  1129. "hasgoods": j.HasGoods,
  1130. "hasbrand": j.HasBrand,
  1131. "haskey": j.HasKey,
  1132. }
  1133. if len(j.BrandData) > 0 {
  1134. tmp["tablebrand"] = j.BrandData
  1135. }
  1136. // log.Debug("============", j.HasBrand, j.HasGoods, j.HasKey, j.HasTable, j.BrandData)
  1137. }
  1138. //所有kv组成的字符串
  1139. var kvtext bytes.Buffer
  1140. blocks := make([]ju.BlockAndTag, 0)
  1141. for _, v := range j.Block {
  1142. //分包和标签
  1143. if ju.Config["saveblock"].(bool) {
  1144. xx, _ := json.Marshal(v)
  1145. tmpblock := new(ju.TmpBlock)
  1146. err := json.Unmarshal(xx, &tmpblock)
  1147. if err != nil {
  1148. if v.BPackage != nil {
  1149. bpb, _ := json.Marshal(v.BPackage)
  1150. tmpblock.BPackage = string(bpb)
  1151. }
  1152. tmpblock = rangeBlockToJson(v, *tmpblock)
  1153. }
  1154. blocks = append(blocks, ju.BlockAndTag{v.Tag, tmpblock})
  1155. }
  1156. //把所有kv组装成一个字符串,存库
  1157. for _, jv := range []*ju.JobKv{v.ColonKV, v.SpaceKV, v.TableKV} {
  1158. if jv == nil {
  1159. continue
  1160. }
  1161. for jv_k, jv_v := range jv.KvTags {
  1162. for _, jv_vv := range jv_v {
  1163. kvtext.WriteString(jv_k)
  1164. kvtext.WriteString(":")
  1165. kvtext.WriteString(jv_vv.Value)
  1166. kvtext.WriteString(" ")
  1167. }
  1168. }
  1169. }
  1170. }
  1171. if kvtext.Len() > 0 {
  1172. tmp["kvtext"] = kvtext.String()
  1173. }
  1174. if len(blocks) > 0 {
  1175. tmp["blocks"] = blocks
  1176. }
  1177. //tmp["extract_content"] = j.Content
  1178. if e.TaskInfo.TestColl == "" {
  1179. if len(tmp) > 0 { //保存抽取结果
  1180. for field, _ := range e.Fields {
  1181. if tmp[field] == nil {
  1182. tmp[field] = "" //覆盖之前版本数据
  1183. }
  1184. }
  1185. tmp["repeat"] = 0
  1186. tmparr := []map[string]interface{}{
  1187. map[string]interface{}{
  1188. "_id": qu.StringTOBsonId(_id),
  1189. },
  1190. map[string]interface{}{"$set": tmp},
  1191. }
  1192. e.BidArr = append(e.BidArr, tmparr)
  1193. e.BidTotal++
  1194. }
  1195. if b, ok := ju.Config["saveresult"].(bool); ok && b {
  1196. id := tmp["_id"]
  1197. tmp["result"] = result
  1198. tmp["resultf"] = resultf
  1199. delete(tmp, "_id")
  1200. tmparr := []map[string]interface{}{
  1201. map[string]interface{}{
  1202. "_id": id,
  1203. },
  1204. map[string]interface{}{"$set": tmp},
  1205. }
  1206. e.ResultArr = append(e.ResultArr, tmparr)
  1207. }
  1208. } else { //测试结果
  1209. delete(tmp, "_id")
  1210. if len(j.BlockPackage) > 0 { //分包详情
  1211. bs, _ := json.Marshal(j.BlockPackage)
  1212. tmp["epackage"] = string(bs)
  1213. }
  1214. tmp["result"] = result
  1215. tmp["resultf"] = resultf
  1216. b := db.Mgo.Update(e.TaskInfo.TestColl, `{"_id":"`+_id+`"}`, map[string]interface{}{"$set": tmp}, true, false)
  1217. if !b {
  1218. log.Debug(e.TaskInfo.TestColl, _id)
  1219. }
  1220. }
  1221. }, func(err interface{}) {
  1222. log.Debug("AnalysisSaveResult err", err)
  1223. })
  1224. }
  1225. //保存其他
  1226. //kv、表格、块上的标签凡是新的标签都入库
  1227. //val type times firstid createtime 判定field
  1228. func otherNeedSave(j *ju.Job, result map[string][]*ju.ExtField, e *ExtractTask) {
  1229. now := time.Now().Unix()
  1230. coll := e.TaskInfo.TestColl
  1231. if coll == "" {
  1232. coll = "extract_tag_result"
  1233. } else {
  1234. coll += "_tag"
  1235. }
  1236. datas := []map[string]interface{}{}
  1237. kv := map[string]int{}
  1238. for _, v := range j.Block {
  1239. //
  1240. for _, vv := range []*ju.JobKv{v.ColonKV, v.TableKV, v.SpaceKV} {
  1241. if vv == nil || vv.KvTags == nil {
  1242. continue
  1243. }
  1244. for kkk, vvv := range vv.KvTags {
  1245. for _, vvvv := range vvv {
  1246. if vvvv.IsInvalid {
  1247. kv[kkk] = kv[kkk] + 1
  1248. break
  1249. }
  1250. }
  1251. }
  1252. }
  1253. for _, vv := range v.NotClassifyTitles {
  1254. datas = append(datas, map[string]interface{}{
  1255. "val": vv,
  1256. "times": 0,
  1257. "type": "block",
  1258. "firstid": j.SourceMid,
  1259. "createtime": now,
  1260. })
  1261. if len(datas) == 200 {
  1262. db.Mgo.SaveBulk(coll, datas...)
  1263. datas = []map[string]interface{}{}
  1264. }
  1265. }
  1266. }
  1267. for k, v := range kv {
  1268. datas = append(datas, map[string]interface{}{
  1269. "val": k,
  1270. "times": v,
  1271. "type": "kv",
  1272. "firstid": j.SourceMid,
  1273. "createtime": now,
  1274. })
  1275. if len(datas) == 200 {
  1276. db.Mgo.SaveBulk(coll, datas...)
  1277. datas = []map[string]interface{}{}
  1278. }
  1279. }
  1280. if len(datas) > 0 {
  1281. db.Mgo.SaveBulk(coll, datas...)
  1282. }
  1283. }
  1284. func rangeBlockToJson(j *ju.Block, tmpblock ju.TmpBlock) (b *ju.TmpBlock) {
  1285. if j == nil {
  1286. return nil
  1287. }
  1288. if len(j.Block) > 0 {
  1289. for i, v := range j.Block {
  1290. rangetmp := new(ju.TmpBlock)
  1291. vb, _ := json.Marshal(v)
  1292. json.Unmarshal(vb, &rangetmp)
  1293. tmpblock.Block[i] = rangeBlockToJson(v, *rangetmp)
  1294. }
  1295. }
  1296. if j.ColonKV != nil {
  1297. cb, _ := json.Marshal(j.ColonKV)
  1298. tmpblock.ColonKV = string(cb)
  1299. }
  1300. if j.SpaceKV != nil {
  1301. sb, _ := json.Marshal(j.SpaceKV)
  1302. tmpblock.SpaceKV = string(sb)
  1303. }
  1304. if j.TableKV != nil {
  1305. tb, _ := json.Marshal(j.TableKV)
  1306. tmpblock.TableKV = string(tb)
  1307. }
  1308. return &tmpblock
  1309. }
  1310. //去重冗余字段
  1311. func delFiled(k string) bool {
  1312. return k == "summary" || k == "detail" || k == "contenthtml" || k == "site" || k == "spidercode" || k == "projectinfo" || k == "jsondata"
  1313. }
  1314. func funcAnalysis(j *ju.Job) (*map[string]interface{}, map[string][]*ju.ExtField, string) {
  1315. defer qu.Catch()
  1316. doc := j.Data
  1317. result := j.Result
  1318. _id := qu.BsonIdToSId((*doc)["_id"])
  1319. result = ScoreFields(j)
  1320. //结果排序
  1321. for _, val := range result {
  1322. ju.Sort(val)
  1323. }
  1324. return doc, result, _id
  1325. }
  1326. //辅助信息,如果没有排序先排序
  1327. func auxInfo(j *ju.Job) map[string][]map[string]interface{} {
  1328. fieldalls := map[string][]map[string]interface{}{}
  1329. for field, val := range j.Result {
  1330. //ju.Sort(val)
  1331. sfields := []map[string]interface{}{}
  1332. for _, v := range val {
  1333. standardized := false
  1334. if field == "buyer" || field == "winner" || field == "agency" {
  1335. i := redis.GetInt(field, field+"_"+qu.ObjToString(v.Value))
  1336. if i > 0 {
  1337. standardized = true
  1338. }
  1339. }
  1340. sfield := map[string]interface{}{
  1341. "val": v.Value,
  1342. "type": v.Type,
  1343. "score": v.Score,
  1344. "blocktag": v.BlockTag,
  1345. "sourceval": v.SourceValue,
  1346. "standardized": standardized,
  1347. }
  1348. sfields = append(sfields, sfield)
  1349. }
  1350. fieldalls[field] = sfields
  1351. }
  1352. return fieldalls
  1353. }
  1354. func (e *ExtractTask) QualityAudit(resulttmp map[string]interface{}) {
  1355. defer qu.Catch()
  1356. //获取审核字段
  1357. for _, field := range e.AuditFields {
  1358. //1.分包
  1359. if resulttmp["package"] != nil {
  1360. packagedata := resulttmp["package"].(map[string]map[string]interface{})
  1361. for _, val := range packagedata {
  1362. if val[field] != nil {
  1363. fv := qu.ObjToString(val[field])
  1364. if fv != "" {
  1365. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  1366. e.RedisMatch(field, fv, val) //redis匹配
  1367. } else { //除了buyer和winner,其他字段走规则匹配
  1368. e.RuleMatch(field, fv, val)
  1369. }
  1370. }
  1371. }
  1372. }
  1373. }
  1374. //2.外围
  1375. if resulttmp[field] != nil {
  1376. fv := qu.ObjToString(resulttmp[field])
  1377. if fv != "" {
  1378. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  1379. e.RedisMatch(field, fv, resulttmp) //redis匹配
  1380. } else { //除了buyer和winner,其他字段走规则匹配
  1381. e.RuleMatch(field, fv, resulttmp)
  1382. }
  1383. }
  1384. }
  1385. }
  1386. }
  1387. //Redis匹配
  1388. func (e *ExtractTask) RedisMatch(field, fv string, val map[string]interface{}) {
  1389. defer qu.Catch()
  1390. i := redis.GetInt(field, field+"_"+fv) //查找redis
  1391. if i == 0 { //reids未找到,执行规则匹配
  1392. val[field+"_isredis"] = false
  1393. e.RuleMatch(field, fv, val) //规则匹配
  1394. } else { //redis找到,打标识存库
  1395. val[field+"_isredis"] = true
  1396. }
  1397. }
  1398. //规则匹配
  1399. func (e *ExtractTask) RuleMatch(field, fieldval string, tmpMap map[string]interface{}) {
  1400. defer qu.Catch()
  1401. if fieldval != "" {
  1402. SMap := e.StartMatch(field, fieldval)
  1403. //SMap.AddKey(field+"_isaudit", false)
  1404. for _, k := range SMap.Keys {
  1405. tmpMap[k] = SMap.Map[k]
  1406. }
  1407. tmpMap[field+"_isaudit"] = false //添加字段未审核信息
  1408. }
  1409. }
  1410. //开始规则匹配
  1411. func (e *ExtractTask) StartMatch(field, text string) *pretreated.SortMap {
  1412. defer qu.Catch()
  1413. SMap := pretreated.NewSortMap()
  1414. lock.Lock()
  1415. f := e.RecogFieldMap[field]
  1416. lock.Unlock()
  1417. if len(f) > 0 {
  1418. fid := qu.BsonIdToSId(f["_id"])
  1419. recogFieldPreRule := qu.ObjToString(f["s_recogfield_prerule"])
  1420. textAfterRecogFieldPrerule := ju.PreFilter(text, recogFieldPreRule) //识别字段的前置过滤
  1421. if textAfterRecogFieldPrerule != "" {
  1422. lock.Lock()
  1423. classMap := e.FidClassMap[fid]
  1424. lock.Unlock()
  1425. L:
  1426. for _, c := range classMap { //class
  1427. classid := qu.BsonIdToSId(c["_id"])
  1428. classPrerule := qu.ObjToString(c["s_class_prerule"])
  1429. savefield := qu.ObjToString(c["s_savefield"]) //保存字段
  1430. textAfterClassPrerule := ju.PreFilter(textAfterRecogFieldPrerule, classPrerule) //class的前置过滤
  1431. if textAfterClassPrerule != "" {
  1432. lock.Lock()
  1433. ruleMap := e.CidRuleMap[classid]
  1434. lock.Unlock()
  1435. for _, r := range ruleMap { //rule
  1436. rulePrerule := qu.ObjToString(r["s_rule_prerule"])
  1437. s_name := qu.ObjToString(r["s_name"])
  1438. rule := r["rule"].([]interface{})
  1439. textAfterRulePrerule := ju.PreFilter(textAfterClassPrerule, rulePrerule) //class的前置过滤
  1440. if textAfterRulePrerule != "" {
  1441. b, _ := ju.RecogAnalyRules(textAfterRulePrerule, rule)
  1442. if b { //匹配到一个分类下某个规则时,不再继续匹配
  1443. if savefield != "" { //保存字段不为空,存储代码信息
  1444. SMap.AddKey(field+"_"+savefield, s_name)
  1445. }
  1446. break L
  1447. }
  1448. }
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. return SMap
  1455. }