extract.go 46 KB

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