extract.go 46 KB

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