extract.go 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  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, locktag, blocktag 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. ExtRuleCore(tmp, e, vc, j)
  366. // log.Debug("抽取-规则", tmp)
  367. //抽取-后置规则
  368. for _, v := range vc.RuleBacks {
  369. ExtRegBack(j, v, e.TaskInfo)
  370. }
  371. // log.Debug("抽取-后置规则", tmp)
  372. //项目名称未能抽取到,标题来凑
  373. if vc.Field == "projectname" && vc.ExtFrom == "title" {
  374. isextitle := true
  375. for _, v := range j.Result[vc.Field] {
  376. if len([]rune(qu.ObjToString(v.Value))) > 5 {
  377. isextitle = false
  378. break
  379. }
  380. }
  381. if isextitle { //标题加入选举
  382. 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}
  383. j.Result[vc.Field] = append(j.Result[vc.Field], field)
  384. }
  385. for i := 0; i < 3; i++ {
  386. for _, v := range vc.RuleBacks {
  387. ExtRegBack(j, v, e.TaskInfo)
  388. }
  389. }
  390. }
  391. }
  392. }
  393. //全局后置规则
  394. for _, v := range e.RuleBacks {
  395. ExtRegBack(j, v, e.TaskInfo)
  396. }
  397. //候选人加入
  398. if len(j.Winnerorder) > 0 {
  399. //候选人中标金额
  400. if price := j.Winnerorder[0]["price"]; price != nil {
  401. bidamount := &ju.ExtField{
  402. Field: "bidamount",
  403. Code: "",
  404. RuleText: "",
  405. Type: "winnerorder",
  406. MatchType: "winnerorder",
  407. ExtFrom: "",
  408. Value: price,
  409. Score: 0,
  410. }
  411. j.Result["bidamount"] = []*ju.ExtField{bidamount}
  412. }
  413. //候选人中标单位
  414. if entname := j.Winnerorder[0]["entname"]; entname != nil {
  415. winner := &ju.ExtField{
  416. Field: "winner",
  417. Code: "",
  418. RuleText: "",
  419. Type: "winnerorder",
  420. MatchType: "winnerorder",
  421. ExtFrom: "",
  422. Value: entname,
  423. Score: 0,
  424. }
  425. j.Result["winner"] = []*ju.ExtField{winner}
  426. }
  427. }
  428. //函数清理
  429. for key, val := range j.Result {
  430. for _, v := range val {
  431. lockclear.Lock()
  432. cfn := e.ClearFn[key]
  433. lockclear.Unlock()
  434. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content})
  435. before, _ := v.Value.(string)
  436. v.Value = data[0]
  437. BeforeAddClearFnLog(v.Type, "函数清理", j.SourceMid, before, v.MatchType, v, e)
  438. //添加行数清理的日志
  439. //清理特殊符号
  440. lockclear.Lock()
  441. if clear.AsyField[key] != nil || clear.SymField[key] != nil || clear.MesField[key] != nil {
  442. text := qu.ObjToString(v.Value)
  443. before = text
  444. v.Value = clear.OtherClean(key, text)
  445. BeforeAddClearFnLog(v.Type, "特殊符号清理", j.SourceMid, before, v.MatchType, v, e)
  446. }
  447. //AddClearFnLog("clearfn", j.SourceMid, v.Value, extinfo, v.Code, "函数清理", key, e.TaskInfo)
  448. lockclear.Unlock()
  449. }
  450. }
  451. PackageDetail(j, e) //处理分包信息
  452. // bs, _ := json.Marshal(j.Result)
  453. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  454. }, func(err interface{}) {
  455. log.Debug("ExtractProcess err", err)
  456. })
  457. }
  458. func (e *ExtractTask) ExtractFile(j *ju.Job) {
  459. qu.Try(func() {
  460. doc := *j.Data
  461. //全局前置规则,结果覆盖doc属性
  462. // for _, v := range e.RulePres {
  463. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  464. // doc = ExtRegPre(doc, j, v, e.TaskInfo)
  465. // }
  466. // }
  467. //抽取规则
  468. tmprules := map[string][]*RuleCore{}
  469. lockrule.Lock()
  470. if j.Category == "all" || j.CategorySecond == "all" {
  471. for k, vc1 := range e.RuleCores["all_all"] {
  472. tmprules[k] = vc1
  473. }
  474. } else {
  475. for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
  476. tmprules[k] = vc1
  477. }
  478. }
  479. lockrule.Unlock()
  480. for _, vc1 := range tmprules {
  481. for _, vc := range vc1 {
  482. tmp := ju.DeepCopy(doc).(map[string]interface{})
  483. //是否进入逻辑
  484. if !ju.Logic(vc.LuaLogic, tmp) {
  485. continue
  486. }
  487. //抽取-前置规则
  488. // for _, v := range vc.RulePres {
  489. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  490. // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
  491. // }
  492. // }
  493. // log.Debug("抽取-前置规则", tmp)
  494. //抽取-规则
  495. if value, ok := e.FileFields.Load(vc.Field); ok && qu.IntAllDef(value, 1) > 0 {
  496. ExtRuleCore(tmp, e, vc, j)
  497. }
  498. // log.Debug("抽取-规则", tmp)
  499. //抽取-后置规则
  500. for _, v := range vc.RuleBacks {
  501. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  502. ExtRegBack(j, v, e.TaskInfo)
  503. }
  504. }
  505. // log.Debug("抽取-后置规则", tmp)
  506. }
  507. }
  508. //全局后置规则
  509. for _, v := range e.RuleBacks {
  510. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  511. ExtRegBack(j, v, e.TaskInfo)
  512. }
  513. }
  514. //候选人加入
  515. if len(j.Winnerorder) > 0 {
  516. //候选人中标金额
  517. if price := j.Winnerorder[0]["price"]; price != nil {
  518. bidamount := &ju.ExtField{
  519. Field: "bidamount",
  520. Code: "",
  521. RuleText: "",
  522. Type: "winnerorder",
  523. MatchType: "winnerorder",
  524. ExtFrom: "",
  525. Value: price,
  526. Score: 0,
  527. }
  528. j.Result["bidamount"] = []*ju.ExtField{bidamount}
  529. }
  530. //候选人中标单位
  531. if entname := j.Winnerorder[0]["entname"]; entname != nil {
  532. winner := &ju.ExtField{
  533. Field: "winner",
  534. Code: "",
  535. RuleText: "",
  536. Type: "winnerorder",
  537. MatchType: "winnerorder",
  538. ExtFrom: "",
  539. Value: entname,
  540. Score: 0,
  541. }
  542. j.Result["winner"] = []*ju.ExtField{winner}
  543. }
  544. }
  545. //函数清理
  546. for key, val := range j.Result {
  547. for _, v := range val {
  548. lockclear.Lock()
  549. cfn := e.ClearFn[key]
  550. lockclear.Unlock()
  551. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content})
  552. v.Value = data[0]
  553. //清理特殊符号
  554. lockclear.Lock()
  555. if clear.AsyField[key] != nil || clear.SymField[key] != nil ||
  556. clear.MesField[key] != nil {
  557. text := qu.ObjToString(v.Value)
  558. text = clear.OtherClean(key, text)
  559. v.Value = text
  560. }
  561. lockclear.Unlock()
  562. }
  563. }
  564. PackageDetail(j, e) //处理分包信息
  565. // bs, _ := json.Marshal(j.Result)
  566. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  567. }, func(err interface{}) {
  568. log.Debug("ExtractProcess err", err)
  569. })
  570. }
  571. //前置过滤
  572. func ExtRegPre(doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, t *TaskInfo) map[string]interface{} {
  573. defer qu.Catch()
  574. before := ju.DeepCopy(doc).(map[string]interface{})
  575. extinfo := map[string]interface{}{}
  576. if in.IsLua {
  577. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  578. if j != nil {
  579. lua.Block = j.Block
  580. }
  581. extinfo = lua.RunScript("pre")
  582. for k, v := range extinfo { //结果覆盖原doc
  583. doc[k] = v
  584. }
  585. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  586. } else {
  587. var key string
  588. if !j.IsFile {
  589. key = qu.If(in.Field == "", "detail", in.Field).(string)
  590. } else {
  591. key = qu.If(in.Field == "", "detailfile", in.Field).(string)
  592. }
  593. text := qu.ObjToString(doc[key])
  594. extinfo[key] = in.RegPreBac.Reg.ReplaceAllString(text, "")
  595. doc[key] = extinfo[key] //结果覆盖原doc
  596. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  597. }
  598. return doc
  599. }
  600. //抽取-规则
  601. func ExtRuleCore(doc map[string]interface{}, e *ExtractTask, vc *RuleCore, j *ju.Job) {
  602. var kvMap map[string][]map[string]interface{}
  603. if vc.ExtFrom != "title" {
  604. kvMap = getKvByLuaFields(vc, j, e)
  605. }
  606. for _, v := range vc.RuleCores {
  607. if v.IsLua {
  608. ExtRuleCoreByKv(vc.ExtFrom, doc, j, v, kvMap)
  609. } else {
  610. ExtRuleCoreByReg(vc.ExtFrom, doc, j, v, e)
  611. }
  612. }
  613. for k, v := range kvMap {
  614. if j.Result[k] == nil {
  615. j.Result[k] = [](*ju.ExtField){}
  616. }
  617. for _, tmp := range v {
  618. field := &ju.ExtField{Weight: qu.IntAll(tmp["weight"]), Field: k, Code: qu.ObjToString(tmp["code"]), Type: qu.ObjToString(tmp["type"]), MatchType: qu.ObjToString(tmp["matchtype"]), RuleText: qu.ObjToString(tmp["ruletext"]), SourceValue: tmp["sourcevalue"], Value: tmp["value"]}
  619. if tmp["blocktag"] != nil {
  620. btag := make(map[string]string)
  621. for k := range tmp["blocktag"].(map[string]bool) {
  622. blocktag.Lock()
  623. if TagConfigDesc[k] != "" {
  624. btag[k] = TagConfigDesc[k]
  625. }
  626. blocktag.Unlock()
  627. }
  628. field.BlockTag = btag
  629. }
  630. j.Result[k] = append(j.Result[k], field)
  631. }
  632. }
  633. }
  634. //抽取-规则-kv
  635. func ExtRuleCoreByKv(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, kvMap map[string][]map[string]interface{}) {
  636. defer qu.Catch()
  637. if extfrom == "title" || !in.IsLua {
  638. return
  639. }
  640. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  641. lua.KvMap = kvMap
  642. lua.Block = j.Block
  643. extinfo := lua.RunScript("core")
  644. if tmps, ok := extinfo[in.Field].([]map[string]interface{}); ok {
  645. for _, v := range tmps {
  646. v["core"] = in.Code
  647. }
  648. kvMap[in.Field] = tmps
  649. }
  650. }
  651. //抽取-规则-正则
  652. func ExtRuleCoreByReg(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, et *ExtractTask) {
  653. defer qu.Catch()
  654. //根据field配置项目,是否抽取。例如:废标、流标等跳过,
  655. b := IsExtract(in.Field, j.Title, j.Content)
  656. if !b {
  657. return
  658. }
  659. //全文正则
  660. //text := qu.ObjToString(doc[extfrom])
  661. //if in.Field != "" {
  662. // extinfo := extRegCoreToResult(extfrom, text, j, in)
  663. // if len(extinfo) > 0 {
  664. // AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  665. // }
  666. //}
  667. //块抽取
  668. if in.Field != "" {
  669. if extfrom == "title" {
  670. extinfo := extRegCoreToResult(extfrom, qu.ObjToString(doc[extfrom]), &map[string]string{}, j, in)
  671. if len(extinfo) > 0 {
  672. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  673. }
  674. } else {
  675. for _, v := range j.Block {
  676. btag := make(map[string]string)
  677. for k := range v.Classify {
  678. blocktag.Lock()
  679. btag[k] = TagConfigDesc[k]
  680. blocktag.Unlock()
  681. }
  682. extinfo := extRegCoreToResult(extfrom, v.Text, &btag, j, in)
  683. if len(extinfo) > 0 {
  684. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  685. }
  686. }
  687. }
  688. }
  689. }
  690. //lua脚本根据属性设置提取kv值
  691. func getKvByLuaFields(vc *RuleCore, j *ju.Job, et *ExtractTask) map[string][]map[string]interface{} {
  692. kvmap := map[string][]map[string]interface{}{}
  693. for fieldname, field := range vc.LFields {
  694. if field != vc.Field {
  695. continue
  696. }
  697. extractFromKv(field, fieldname, j.Block, vc, kvmap)
  698. }
  699. AddExtLog("extract", j.SourceMid, nil, kvmap, &RegLuaInfo{Field: vc.Field}, et.TaskInfo) //抽取日志
  700. return kvmap
  701. }
  702. func extractFromKv(field, fieldname string, blocks []*ju.Block, vc *RuleCore, kvmap map[string][]map[string]interface{}) {
  703. for _, bl := range blocks {
  704. tp := ""
  705. for k, v := range []*ju.JobKv{bl.ColonKV, bl.SpaceKV, bl.TableKV} {
  706. if k == 0 {
  707. tp = "colon"
  708. } else if k == 1 {
  709. tp = "space"
  710. } else if k == 2 {
  711. tp = "table"
  712. }
  713. if v == nil || v.KvTags == nil {
  714. continue
  715. }
  716. for _, vv := range v.KvTags[fieldname] {
  717. text := ju.TrimLRSpace(vv.Value, "")
  718. if text != "" {
  719. kvmap[field] = append(kvmap[field], map[string]interface{}{
  720. "code": "CL_" + vv.Key,
  721. "field": field,
  722. "ruletext": vv.Key,
  723. "extfrom": vc.ExtFrom,
  724. "sourcevalue": text,
  725. "value": text,
  726. "type": tp,
  727. "matchtype": "tag_string",
  728. "blocktag": bl.Classify,
  729. "weight": vv.Weight,
  730. })
  731. }
  732. }
  733. }
  734. if len(kvmap[field]) == 0 {
  735. extractFromKv(field, fieldname, bl.Block, vc, kvmap)
  736. }
  737. }
  738. }
  739. //正则提取结果
  740. func extRegCoreToResult(extfrom, text string, tag *map[string]string, j *ju.Job, v *RegLuaInfo) map[string][]map[string]interface{} {
  741. defer qu.Catch()
  742. extinfo := map[string][]map[string]interface{}{}
  743. if v.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
  744. apos := v.RegCore.Reg.FindAllStringSubmatchIndex(text, -1)
  745. if len(apos) > 0 {
  746. pos := apos[0]
  747. for k, p := range v.RegCore.ExtractPos {
  748. if len(pos) > p {
  749. if pos[p] == -1 || pos[p+1] == -1 {
  750. continue
  751. }
  752. val := text[pos[p]:pos[p+1]]
  753. sourcevalue := val
  754. if val == "招标公告" {
  755. return extinfo
  756. }
  757. if utf8.RuneCountInString(val) < 2 && extfrom == "title" {
  758. val = text
  759. }
  760. tmps := []map[string]interface{}{}
  761. tmp := map[string]interface{}{
  762. "field": v.Field,
  763. "code": v.Code,
  764. "ruletext": v.RuleText,
  765. "extfrom": text,
  766. "value": val,
  767. "type": "regexp",
  768. "matchtype": "regcontent",
  769. "blocktag": *tag,
  770. }
  771. tmps = append(tmps, tmp)
  772. extinfo[k] = tmps
  773. if strings.TrimSpace(val) != "" {
  774. if v.RegCore.NumSign == -1 { //正负值修正
  775. val = "-" + val
  776. }
  777. exfield := ju.ExtField{BlockTag: *tag, Field: k, Code: v.Code, RuleText: v.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: sourcevalue, Value: val}
  778. if tmp["blocktag"] != nil {
  779. exfield.BlockTag = tmp["blocktag"].(map[string]string)
  780. }
  781. j.Result[k] = append(j.Result[k], &exfield)
  782. //j.Result[k] = append(j.Result[k], &ju.ExtField{tmp["blocktag"].(map[string]bool), k, v.Code, v.RuleText, "regexp", "regcontent", extfrom, val, 0})
  783. }
  784. }
  785. }
  786. if len(extinfo) == 0 {
  787. regArr := strings.Split(v.RuleText, "__")
  788. //fmt.Println(regArr[0])
  789. if len(regArr) > 0 {
  790. reg, err := regexp.Compile(regArr[0])
  791. if err == nil {
  792. datavals := reg.FindStringSubmatch(text)
  793. tmps := []map[string]interface{}{}
  794. for _, value := range datavals {
  795. if value == "" {
  796. continue
  797. }
  798. tmp := map[string]interface{}{
  799. "field": v.Field,
  800. "code": v.Code,
  801. "ruletext": regArr[0],
  802. "extfrom": text,
  803. "value": value,
  804. "type": "regexp",
  805. "matchtype": "regcontent",
  806. "blocktag": *tag,
  807. }
  808. tmps = append(tmps, tmp)
  809. extinfo[v.Field] = tmps
  810. exfield := ju.ExtField{BlockTag: *tag, Field: v.Field, Code: v.Code + "去除__*后", RuleText: v.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: text, Value: value}
  811. if tmp["blocktag"] != nil {
  812. exfield.BlockTag = tmp["blocktag"].(map[string]string)
  813. }
  814. j.Result[v.Field] = append(j.Result[v.Field], &exfield)
  815. //j.Result[k] = append(j.Result[k], &ju.ExtField{tmp["blocktag"].(map[string]bool), k, v.Code, v.RuleText, "regexp", "regcontent", extfrom, val, 0})
  816. }
  817. }
  818. }
  819. }
  820. }
  821. } else {
  822. pos := v.RegCore.Reg.FindStringIndex(text)
  823. val := ""
  824. if len(pos) == 2 {
  825. text = text[pos[1]:]
  826. rs := regexp.MustCompile("[^\r\n\t]+")
  827. tmp := rs.FindAllString(text, -1)
  828. if len(tmp) > 0 {
  829. val = tmp[0]
  830. }
  831. }
  832. if val != "" {
  833. tmps := []map[string]interface{}{}
  834. tmp := map[string]interface{}{
  835. "field": v.Field,
  836. "code": v.Code,
  837. "ruletext": v.RuleText,
  838. "extfrom": text,
  839. "value": val,
  840. "type": "regexp",
  841. "matchtype": "regcontent",
  842. "blocktag": *tag,
  843. }
  844. tmps = append(tmps, tmp)
  845. extinfo[v.Field] = tmps
  846. if j.Result[v.Field] == nil {
  847. j.Result[v.Field] = [](*ju.ExtField){}
  848. }
  849. field := &ju.ExtField{BlockTag: *tag, Field: v.Field, Code: v.Code, RuleText: v.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: text, Value: val}
  850. if tmp["blocktag"] != nil {
  851. field.BlockTag = tmp["blocktag"].(map[string]string)
  852. }
  853. j.Result[v.Field] = append(j.Result[v.Field], field)
  854. }
  855. }
  856. return extinfo
  857. }
  858. //后置过滤
  859. func ExtRegBack(j *ju.Job, in *RegLuaInfo, t *TaskInfo) {
  860. defer qu.Catch()
  861. if in.IsLua {
  862. result := GetResultMapForLua(j)
  863. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Result: result, Script: in.RuleText}
  864. if j != nil {
  865. lua.Block = j.Block
  866. }
  867. extinfo := lua.RunScript("back")
  868. for k, v := range extinfo {
  869. if tmps, ok := v.([]map[string]interface{}); ok {
  870. j.Result[k] = [](*ju.ExtField){}
  871. for _, tmp := range tmps {
  872. 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}
  873. if tmp["blocktag"] != nil {
  874. field.BlockTag = tmp["blocktag"].(map[string]string)
  875. }
  876. j.Result[k] = append(j.Result[k], field)
  877. //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})
  878. }
  879. }
  880. }
  881. if len(extinfo) > 0 {
  882. AddExtLog("clear", j.SourceMid, result, extinfo, in, t) //抽取日志
  883. }
  884. } else {
  885. extinfo := map[string]interface{}{}
  886. if in.Field != "" {
  887. if j.Result[in.Field] != nil {
  888. tmp := j.Result[in.Field]
  889. exts := []interface{}{}
  890. for k, v := range tmp {
  891. //table抽取到的数据不清理
  892. // if v.Type == "table" && v.Field != "projectname" {
  893. // continue
  894. // }
  895. text := qu.ObjToString(v.Value)
  896. if text != "" {
  897. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  898. }
  899. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  900. continue
  901. }
  902. j.Result[in.Field][k].Value = text
  903. exts = append(exts, map[string]interface{}{
  904. "field": v.Field,
  905. "code": v.Code,
  906. "ruletext": v.RuleText,
  907. "type": v.Type,
  908. "matchtype": v.MatchType,
  909. "extfrom": v.ExtFrom,
  910. "value": text,
  911. })
  912. }
  913. extinfo[in.Field] = exts
  914. if len(extinfo) > 0 {
  915. AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
  916. }
  917. }
  918. } else {
  919. for key, tmp := range j.Result {
  920. exts := []interface{}{}
  921. for k, v := range tmp {
  922. if v.Type == "table" { //table抽取到的数据不清理
  923. continue
  924. }
  925. text := qu.ObjToString(v.Value)
  926. if text != "" {
  927. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  928. }
  929. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  930. continue
  931. }
  932. j.Result[key][k].Value = text
  933. exts = append(exts, map[string]interface{}{
  934. "field": v.Field,
  935. "code": v.Code,
  936. "ruletext": v.RuleText,
  937. "type": v.Type,
  938. "matchtype": v.MatchType,
  939. "extfrom": v.ExtFrom,
  940. "value": text,
  941. })
  942. }
  943. extinfo[key] = exts
  944. }
  945. if len(extinfo) > 0 {
  946. AddExtLog("clear", j.SourceMid, j.Result, extinfo, in, t) //抽取日志
  947. }
  948. }
  949. }
  950. }
  951. //获取抽取结果map[string][]interface{},lua脚本使用
  952. func GetResultMapForLua(j *ju.Job) map[string][]map[string]interface{} {
  953. defer qu.Catch()
  954. result := map[string][]map[string]interface{}{}
  955. for key, val := range j.Result {
  956. if result[key] == nil {
  957. result[key] = []map[string]interface{}{}
  958. }
  959. for _, v := range val {
  960. tmp := map[string]interface{}{
  961. "field": v.Field,
  962. "code": v.Code,
  963. "ruletext": v.RuleText,
  964. "value": v.Value,
  965. "type": v.Type,
  966. "matchtype": v.MatchType,
  967. "extfrom": v.ExtFrom,
  968. }
  969. result[key] = append(result[key], tmp)
  970. }
  971. }
  972. return result
  973. }
  974. //抽取日志
  975. func AddExtLog(ftype, sid string, before interface{}, extinfo interface{}, v *RegLuaInfo, t *TaskInfo) {
  976. defer qu.Catch()
  977. if !t.IsEtxLog {
  978. return
  979. }
  980. logdata := map[string]interface{}{
  981. "code": qu.If(v.Code == "", "kv", v.Code),
  982. "name": v.Name,
  983. "type": ftype,
  984. "ruletext": v.RuleText,
  985. "islua": v.IsLua,
  986. "field": v.Field,
  987. "version": t.Version,
  988. "taskname": t.Name,
  989. "before": before,
  990. "extinfo": extinfo,
  991. "sid": sid,
  992. "comeintime": time.Now().Unix(),
  993. }
  994. lock.Lock()
  995. ExtLogs[t] = append(ExtLogs[t], logdata)
  996. lock.Unlock()
  997. }
  998. func BeforeAddClearFnLog(ftype, name, sid, before, matchtype string, ext *ju.ExtField, e *ExtractTask) {
  999. exts := []map[string]interface{}{}
  1000. exts = append(exts, map[string]interface{}{
  1001. "field": ext.Field,
  1002. "code": ext.Code,
  1003. "type": ftype,
  1004. "matchtype": matchtype,
  1005. "extfrom": ext.ExtFrom,
  1006. "value": ext.Value,
  1007. })
  1008. extinfo := map[string]interface{}{
  1009. ext.Field: exts,
  1010. }
  1011. AddClearFnLog(ftype, sid, before, extinfo, ext.Code, name, ext.Field, e.TaskInfo)
  1012. }
  1013. func AddClearFnLog(ftype, sid string, before interface{}, extinfo interface{}, code, name, field string, t *TaskInfo) {
  1014. defer qu.Catch()
  1015. if !t.IsEtxLog {
  1016. return
  1017. }
  1018. logdata := map[string]interface{}{
  1019. "code": code,
  1020. "name": name,
  1021. "type": ftype,
  1022. "ruletext": "",
  1023. "islua": false,
  1024. "field": field,
  1025. "version": t.Version,
  1026. "taskname": t.Name,
  1027. "before": before,
  1028. "extinfo": extinfo,
  1029. "sid": sid,
  1030. "comeintime": time.Now().Unix(),
  1031. }
  1032. lock.Lock()
  1033. ExtLogs[t] = append(ExtLogs[t], logdata)
  1034. lock.Unlock()
  1035. }
  1036. //保存抽取日志
  1037. func SaveExtLog() {
  1038. defer qu.Catch()
  1039. tmpLogs := map[*TaskInfo][]map[string]interface{}{}
  1040. lock.Lock()
  1041. tmpLogs = ExtLogs
  1042. ExtLogs = map[*TaskInfo][]map[string]interface{}{}
  1043. lock.Unlock()
  1044. for k, v := range tmpLogs {
  1045. if len(v) < saveLimit {
  1046. db.Mgo.SaveBulk(k.TrackColl, v...)
  1047. } else {
  1048. for {
  1049. if len(v) > saveLimit {
  1050. tmp := v[:saveLimit]
  1051. db.Mgo.SaveBulk(k.TrackColl, tmp...)
  1052. v = v[saveLimit:]
  1053. } else {
  1054. db.Mgo.SaveBulk(k.TrackColl, v...)
  1055. break
  1056. }
  1057. }
  1058. }
  1059. }
  1060. time.AfterFunc(10*time.Second, SaveExtLog)
  1061. }
  1062. type FieldValue struct {
  1063. Value interface{}
  1064. Count int
  1065. }
  1066. //分析抽取结果并保存
  1067. func AnalysisSaveResult(j, jf *ju.Job, e *ExtractTask) {
  1068. qu.Try(func() {
  1069. doc, result, _id := funcAnalysis(j, e.Tag)
  1070. if isSaveTag, _ := ju.Config["isSaveTag"].(bool); isSaveTag {
  1071. go otherNeedSave(j, result, e)
  1072. }
  1073. auxinfo := auxInfo(j)
  1074. //从排序结果中取值
  1075. tmp := map[string]interface{}{} //抽取值
  1076. tmp["fieldall"] = auxinfo
  1077. for _, val := range result {
  1078. for _, v := range val { //取第一个非负数,项目名称除外
  1079. if v.Score > -1 {
  1080. tmp[v.Field] = v.Value
  1081. break
  1082. } else if v.Field == "projectname" {
  1083. tmp[v.Field] = v.Value
  1084. break
  1085. }
  1086. }
  1087. }
  1088. if len(j.PackageInfo) > 0 { //分包信息
  1089. tmp["package"] = j.PackageInfo
  1090. }
  1091. if len(j.Winnerorder) > 0 { //候选人信息
  1092. tmp["winnerorder"] = j.Winnerorder
  1093. }
  1094. //处理附件
  1095. var resultf map[string][]*ju.ExtField
  1096. if jf != nil {
  1097. _, resultf, _ = funcAnalysis(jf, e.Tag)
  1098. auxinfof := auxInfo(jf)
  1099. tmp["fieldallf"] = auxinfof
  1100. ffield := map[string]interface{}{}
  1101. for _, val := range resultf {
  1102. for _, v := range val { //取第一个非负数
  1103. if v.Score > -1 {
  1104. ffield[v.Field] = v.Value
  1105. break
  1106. }
  1107. }
  1108. }
  1109. if len(jf.PackageInfo) > 0 { //分包信息
  1110. ffield["package"] = jf.PackageInfo
  1111. }
  1112. if len(jf.Winnerorder) > 0 { //候选人信息
  1113. ffield["winnerorder"] = jf.Winnerorder
  1114. }
  1115. tmp["ffield"] = ffield
  1116. }
  1117. for k, v := range *doc {
  1118. //去重冗余字段
  1119. if delFiled(k) {
  1120. continue
  1121. }
  1122. if tmp[k] == nil {
  1123. tmp[k] = v
  1124. }
  1125. }
  1126. //质量审核
  1127. if ok, _ := ju.Config["qualityaudit"].(bool); ok {
  1128. e.QualityAudit(tmp)
  1129. }
  1130. if e.IsExtractCity { //城市抽取
  1131. e.ExtractCity(j, tmp, _id)
  1132. // b, p, c, d := e.TransmitData(tmp, _id) //抽取省份城市
  1133. // // log.Debug("省份---", p, "城市---", c, "区---", d)
  1134. // tmp["district"] = d
  1135. // if b {
  1136. // tmp["city"] = c
  1137. // tmp["area"] = p
  1138. // }
  1139. }
  1140. //品牌抽取
  1141. if ju.IsBrandGoods {
  1142. tmp["checkhas"] = map[string]int{
  1143. "hastable": j.HasTable,
  1144. "hasgoods": j.HasGoods,
  1145. "hasbrand": j.HasBrand,
  1146. "haskey": j.HasKey,
  1147. }
  1148. if len(j.BrandData) > 0 {
  1149. tmp["tablebrand"] = j.BrandData
  1150. }
  1151. // log.Debug("============", j.HasBrand, j.HasGoods, j.HasKey, j.HasTable, j.BrandData)
  1152. }
  1153. //所有kv组成的字符串
  1154. var kvtext bytes.Buffer
  1155. blocks := make([]ju.BlockAndTag, 0)
  1156. for _, v := range j.Block {
  1157. //分包和标签
  1158. if ju.Config["saveblock"].(bool) {
  1159. xx, _ := json.Marshal(v)
  1160. tmpblock := new(ju.TmpBlock)
  1161. err := json.Unmarshal(xx, &tmpblock)
  1162. if err != nil {
  1163. if v.BPackage != nil {
  1164. bpb, _ := json.Marshal(v.BPackage)
  1165. tmpblock.BPackage = string(bpb)
  1166. }
  1167. tmpblock = rangeBlockToJson(v, *tmpblock)
  1168. }
  1169. blocks = append(blocks, ju.BlockAndTag{v.Tag, tmpblock})
  1170. }
  1171. //把所有kv组装成一个字符串,存库
  1172. for _, jv := range []*ju.JobKv{v.ColonKV, v.SpaceKV, v.TableKV} {
  1173. if jv == nil {
  1174. continue
  1175. }
  1176. for jv_k, jv_v := range jv.KvTags {
  1177. for _, jv_vv := range jv_v {
  1178. kvtext.WriteString(jv_k)
  1179. kvtext.WriteString(":")
  1180. kvtext.WriteString(jv_vv.Value)
  1181. kvtext.WriteString(" ")
  1182. }
  1183. }
  1184. }
  1185. }
  1186. if kvtext.Len() > 0 {
  1187. tmp["kvtext"] = kvtext.String()
  1188. }
  1189. if len(blocks) > 0 {
  1190. tmp["blocks"] = blocks
  1191. }
  1192. //tmp["extract_content"] = j.Content
  1193. if e.TaskInfo.TestColl == "" {
  1194. if len(tmp) > 0 { //保存抽取结果
  1195. for field, _ := range e.Fields {
  1196. if tmp[field] == nil {
  1197. tmp[field] = "" //覆盖之前版本数据
  1198. }
  1199. }
  1200. tmp["repeat"] = 0
  1201. tmparr := []map[string]interface{}{
  1202. map[string]interface{}{
  1203. "_id": qu.StringTOBsonId(_id),
  1204. },
  1205. map[string]interface{}{"$set": tmp},
  1206. }
  1207. e.BidArr = append(e.BidArr, tmparr)
  1208. e.BidTotal++
  1209. }
  1210. if b, ok := ju.Config["saveresult"].(bool); ok && b {
  1211. id := tmp["_id"]
  1212. tmp["result"] = result
  1213. tmp["resultf"] = resultf
  1214. delete(tmp, "_id")
  1215. tmparr := []map[string]interface{}{
  1216. map[string]interface{}{
  1217. "_id": id,
  1218. },
  1219. map[string]interface{}{"$set": tmp},
  1220. }
  1221. e.ResultArr = append(e.ResultArr, tmparr)
  1222. }
  1223. } else { //测试结果
  1224. delete(tmp, "_id")
  1225. if len(j.BlockPackage) > 0 { //分包详情
  1226. bs, _ := json.Marshal(j.BlockPackage)
  1227. tmp["epackage"] = string(bs)
  1228. }
  1229. tmp["result"] = result
  1230. tmp["resultf"] = resultf
  1231. b := db.Mgo.Update(e.TaskInfo.TestColl, `{"_id":"`+_id+`"}`, map[string]interface{}{"$set": tmp}, true, false)
  1232. if !b {
  1233. log.Debug(e.TaskInfo.TestColl, _id)
  1234. }
  1235. }
  1236. }, func(err interface{}) {
  1237. log.Debug("AnalysisSaveResult err", err)
  1238. })
  1239. }
  1240. //保存其他
  1241. //kv、表格、块上的标签凡是新的标签都入库
  1242. //val type times firstid createtime 判定field
  1243. func otherNeedSave(j *ju.Job, result map[string][]*ju.ExtField, e *ExtractTask) {
  1244. now := time.Now().Unix()
  1245. coll := e.TaskInfo.TestColl
  1246. if coll == "" {
  1247. coll = "extract_tag_result"
  1248. } else {
  1249. coll += "_tag"
  1250. }
  1251. datas := []map[string]interface{}{}
  1252. kv := map[string]int{}
  1253. for _, v := range j.Block {
  1254. //
  1255. for _, vv := range []*ju.JobKv{v.ColonKV, v.TableKV, v.SpaceKV} {
  1256. if vv == nil || vv.KvTags == nil {
  1257. continue
  1258. }
  1259. for kkk, vvv := range vv.KvTags {
  1260. for _, vvvv := range vvv {
  1261. if vvvv.IsInvalid {
  1262. kv[kkk] = kv[kkk] + 1
  1263. break
  1264. }
  1265. }
  1266. }
  1267. }
  1268. for _, vv := range v.NotClassifyTitles {
  1269. datas = append(datas, map[string]interface{}{
  1270. "val": vv,
  1271. "times": 0,
  1272. "type": "block",
  1273. "firstid": j.SourceMid,
  1274. "createtime": now,
  1275. })
  1276. if len(datas) == 200 {
  1277. db.Mgo.SaveBulk(coll, datas...)
  1278. datas = []map[string]interface{}{}
  1279. }
  1280. }
  1281. }
  1282. for k, v := range kv {
  1283. datas = append(datas, map[string]interface{}{
  1284. "val": k,
  1285. "times": v,
  1286. "type": "kv",
  1287. "firstid": j.SourceMid,
  1288. "createtime": now,
  1289. })
  1290. if len(datas) == 200 {
  1291. db.Mgo.SaveBulk(coll, datas...)
  1292. datas = []map[string]interface{}{}
  1293. }
  1294. }
  1295. if len(datas) > 0 {
  1296. db.Mgo.SaveBulk(coll, datas...)
  1297. }
  1298. }
  1299. func rangeBlockToJson(j *ju.Block, tmpblock ju.TmpBlock) (b *ju.TmpBlock) {
  1300. if j == nil {
  1301. return nil
  1302. }
  1303. if len(j.Block) > 0 {
  1304. for i, v := range j.Block {
  1305. rangetmp := new(ju.TmpBlock)
  1306. vb, _ := json.Marshal(v)
  1307. json.Unmarshal(vb, &rangetmp)
  1308. tmpblock.Block[i] = rangeBlockToJson(v, *rangetmp)
  1309. }
  1310. }
  1311. if j.ColonKV != nil {
  1312. cb, _ := json.Marshal(j.ColonKV)
  1313. tmpblock.ColonKV = string(cb)
  1314. }
  1315. if j.SpaceKV != nil {
  1316. sb, _ := json.Marshal(j.SpaceKV)
  1317. tmpblock.SpaceKV = string(sb)
  1318. }
  1319. if j.TableKV != nil {
  1320. tb, _ := json.Marshal(j.TableKV)
  1321. tmpblock.TableKV = string(tb)
  1322. }
  1323. return &tmpblock
  1324. }
  1325. //去重冗余字段
  1326. func delFiled(k string) bool {
  1327. return k == "summary" || k == "detail" || k == "contenthtml" || k == "site" || k == "spidercode" || k == "projectinfo" || k == "jsondata"
  1328. }
  1329. func funcAnalysis(j *ju.Job, ftag map[string][]*Tag) (*map[string]interface{}, map[string][]*ju.ExtField, string) {
  1330. defer qu.Catch()
  1331. doc := j.Data
  1332. result := j.Result
  1333. _id := qu.BsonIdToSId((*doc)["_id"])
  1334. result = ScoreFields(j, ftag)
  1335. //结果排序
  1336. for _, val := range result {
  1337. ju.Sort(val)
  1338. }
  1339. return doc, result, _id
  1340. }
  1341. //辅助信息,如果没有排序先排序
  1342. func auxInfo(j *ju.Job) map[string][]map[string]interface{} {
  1343. fieldalls := map[string][]map[string]interface{}{}
  1344. for field, val := range j.Result {
  1345. //ju.Sort(val)
  1346. sfields := []map[string]interface{}{}
  1347. for _, v := range val {
  1348. standardized := false
  1349. if field == "buyer" || field == "winner" || field == "agency" {
  1350. i := redis.GetInt(field, field+"_"+qu.ObjToString(v.Value))
  1351. if i > 0 {
  1352. standardized = true
  1353. }
  1354. }
  1355. sfield := map[string]interface{}{
  1356. "val": v.Value,
  1357. "type": v.Type,
  1358. "score": v.Score,
  1359. "blocktag": v.BlockTag,
  1360. "sourceval": v.SourceValue,
  1361. "standardized": standardized,
  1362. }
  1363. sfields = append(sfields, sfield)
  1364. }
  1365. fieldalls[field] = sfields
  1366. }
  1367. return fieldalls
  1368. }
  1369. func (e *ExtractTask) QualityAudit(resulttmp map[string]interface{}) {
  1370. defer qu.Catch()
  1371. //获取审核字段
  1372. for _, field := range e.AuditFields {
  1373. //1.分包
  1374. if resulttmp["package"] != nil {
  1375. packagedata := resulttmp["package"].(map[string]map[string]interface{})
  1376. for _, val := range packagedata {
  1377. if val[field] != nil {
  1378. fv := qu.ObjToString(val[field])
  1379. if fv != "" {
  1380. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  1381. e.RedisMatch(field, fv, val) //redis匹配
  1382. } else { //除了buyer和winner,其他字段走规则匹配
  1383. e.RuleMatch(field, fv, val)
  1384. }
  1385. }
  1386. }
  1387. }
  1388. }
  1389. //2.外围
  1390. if resulttmp[field] != nil {
  1391. fv := qu.ObjToString(resulttmp[field])
  1392. if fv != "" {
  1393. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  1394. e.RedisMatch(field, fv, resulttmp) //redis匹配
  1395. } else { //除了buyer和winner,其他字段走规则匹配
  1396. e.RuleMatch(field, fv, resulttmp)
  1397. }
  1398. }
  1399. }
  1400. }
  1401. }
  1402. //Redis匹配
  1403. func (e *ExtractTask) RedisMatch(field, fv string, val map[string]interface{}) {
  1404. defer qu.Catch()
  1405. i := redis.GetInt(field, field+"_"+fv) //查找redis
  1406. if i == 0 { //reids未找到,执行规则匹配
  1407. val[field+"_isredis"] = false
  1408. e.RuleMatch(field, fv, val) //规则匹配
  1409. } else { //redis找到,打标识存库
  1410. val[field+"_isredis"] = true
  1411. }
  1412. }
  1413. //规则匹配
  1414. func (e *ExtractTask) RuleMatch(field, fieldval string, tmpMap map[string]interface{}) {
  1415. defer qu.Catch()
  1416. if fieldval != "" {
  1417. SMap := e.StartMatch(field, fieldval)
  1418. //SMap.AddKey(field+"_isaudit", false)
  1419. for _, k := range SMap.Keys {
  1420. tmpMap[k] = SMap.Map[k]
  1421. }
  1422. tmpMap[field+"_isaudit"] = false //添加字段未审核信息
  1423. }
  1424. }
  1425. //开始规则匹配
  1426. func (e *ExtractTask) StartMatch(field, text string) *pretreated.SortMap {
  1427. defer qu.Catch()
  1428. SMap := pretreated.NewSortMap()
  1429. lock.Lock()
  1430. f := e.RecogFieldMap[field]
  1431. lock.Unlock()
  1432. if len(f) > 0 {
  1433. fid := qu.BsonIdToSId(f["_id"])
  1434. recogFieldPreRule := qu.ObjToString(f["s_recogfield_prerule"])
  1435. textAfterRecogFieldPrerule := ju.PreFilter(text, recogFieldPreRule) //识别字段的前置过滤
  1436. if textAfterRecogFieldPrerule != "" {
  1437. lock.Lock()
  1438. classMap := e.FidClassMap[fid]
  1439. lock.Unlock()
  1440. L:
  1441. for _, c := range classMap { //class
  1442. classid := qu.BsonIdToSId(c["_id"])
  1443. classPrerule := qu.ObjToString(c["s_class_prerule"])
  1444. savefield := qu.ObjToString(c["s_savefield"]) //保存字段
  1445. textAfterClassPrerule := ju.PreFilter(textAfterRecogFieldPrerule, classPrerule) //class的前置过滤
  1446. if textAfterClassPrerule != "" {
  1447. lock.Lock()
  1448. ruleMap := e.CidRuleMap[classid]
  1449. lock.Unlock()
  1450. for _, r := range ruleMap { //rule
  1451. rulePrerule := qu.ObjToString(r["s_rule_prerule"])
  1452. s_name := qu.ObjToString(r["s_name"])
  1453. rule := r["rule"].([]interface{})
  1454. textAfterRulePrerule := ju.PreFilter(textAfterClassPrerule, rulePrerule) //class的前置过滤
  1455. if textAfterRulePrerule != "" {
  1456. b, _ := ju.RecogAnalyRules(textAfterRulePrerule, rule)
  1457. if b { //匹配到一个分类下某个规则时,不再继续匹配
  1458. if savefield != "" { //保存字段不为空,存储代码信息
  1459. SMap.AddKey(field+"_"+savefield, s_name)
  1460. }
  1461. break L
  1462. }
  1463. }
  1464. }
  1465. }
  1466. }
  1467. }
  1468. }
  1469. return SMap
  1470. }