123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037 |
- package extract
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "jy/clear"
- db "jy/mongodbutil"
- "jy/pretreated"
- ju "jy/util"
- qu "qfw/util"
- "qfw/util/redis"
- "regexp"
- "strconv"
- "strings"
- "sync"
- "time"
- "unicode/utf8"
- "github.com/PuerkitoBio/goquery"
- log "github.com/donnie4w/go-logger/logger"
- "gopkg.in/mgo.v2/bson"
- )
- var (
- lock, lockrule, lockclear, locktag, blocktag sync.RWMutex
- cut = ju.NewCut() //获取正文并清理
- ExtLogs map[*TaskInfo][]map[string]interface{} //抽取日志
- TaskList map[string]*ExtractTask //任务列表
- ClearTaskList map[string]*ClearTask //清理任务列表
- saveLimit = 100 //抽取日志批量保存
- PageSize = 5000 //查询分页
- Fields = `{"title":1,"summary":1,"detail":1,"contenthtml":1,"site":1,"spidercode":1,"toptype":1,"subtype":1,"bidstatus":1,"area":1,"city":1,"comeintime":1,"publishtime":1,"sensitive":1,"projectinfo":1,"jsondata":1,"href":1}`
- Fields2 = `{"budget":1,"bidamount":1,"title":1,"projectname":1,"winner":1}`
- )
- //启动测试抽取
- func StartExtractTestTask(taskId, startId, num, resultcoll, trackcoll string) bool {
- defer qu.Catch()
- ext := &ExtractTask{}
- ext.Id = taskId
- ext.IsRun = true
- ext.InitTestTaskInfo(resultcoll, trackcoll)
- ext.TaskInfo.FDB = db.MgoFactory(1, 3, 120, ext.TaskInfo.FromDbAddr, ext.TaskInfo.FromDB)
- ext.InitSite()
- ext.InitRulePres()
- ext.InitRuleBacks(false)
- ext.InitRuleBacks(true)
- ext.InitRuleCore(false)
- ext.InitRuleCore(true)
- ext.InitPkgCore()
- ext.InitBlockRule()
- ext.InfoTypeList()
- ext.InitTag(false)
- ext.InitTag(true)
- ext.InitClearFn(false)
- ext.InitClearFn(true)
- if ext.IsExtractCity { //版本上控制是否开始城市抽取
- //初始化城市DFA信息
- ext.InitCityInfo()
- //ext.InitCityDFA()
- ext.InitAreaCode()
- ext.InitPostCode()
- }
- //质量审核
- ext.InitAuditFields()
- ext.InitAuditRule()
- ext.InitAuditClass()
- ext.InitAuditRecogField()
- //品牌抽取是否开启
- ju.IsBrandGoods, _ = ju.Config["brandgoods"].(bool)
- //附件抽取是否开启
- ext.InitFile()
- return RunExtractTestTask(ext, startId, num)
- }
- func IdTrans(startId string) bson.ObjectId {
- defer qu.Catch()
- return bson.ObjectIdHex(startId)
- }
- //开始测试任务抽取
- func RunExtractTestTask(ext *ExtractTask, startId, num string) bool {
- n, _ := strconv.Atoi(num)
- id := IdTrans(startId)
- if id.Valid() {
- query := bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(startId)}}
- list, _ := ext.TaskInfo.FDB.Find(ext.TaskInfo.FromColl, query, nil, Fields, false, 0, n)
- for _, v := range *list {
- if qu.ObjToString(v["sensitive"]) != "" { //去除含敏感词数据
- continue
- }
- var j, jf *ju.Job
- var isSite bool
- if ext.IsFileField && v["projectinfo"] != nil {
- v["isextFile"] = true
- j, jf, isSite = ext.PreInfo(v)
- } else {
- j, _, isSite = ext.PreInfo(v)
- }
- go ext.ExtractProcess(j, jf, isSite)
- ext.TaskInfo.ProcessPool <- true
- }
- return true
- } else {
- return false
- }
- }
- //启动抽取
- func StartExtractTaskId(taskId string) bool {
- defer qu.Catch()
- isgo := false
- ext := TaskList[taskId]
- if ext == nil {
- ext = &ExtractTask{}
- ext.Id = taskId
- ext.InitTaskInfo()
- isgo = true
- } else {
- ext.Id = taskId
- ext.InitTaskInfo()
- }
- ext.TaskInfo.FDB = db.MgoFactory(3, 5, 600, ext.TaskInfo.FromDbAddr, ext.TaskInfo.FromDB)
- ext.TaskInfo.TDB = db.MgoFactory(3, 5, 600, ext.TaskInfo.ToDbAddr, ext.TaskInfo.ToDB)
- ext.InitSite()
- ext.InitRulePres()
- ext.InitRuleBacks(false)
- ext.InitRuleBacks(true)
- ext.InitRuleCore(false)
- ext.InitRuleCore(true)
- ext.InitPkgCore()
- ext.InitBlockRule()
- ext.InfoTypeList()
- ext.InitTag(false)
- ext.InitTag(true)
- ext.InitClearFn(false)
- ext.InitClearFn(true)
- if ext.IsExtractCity { //版本上控制是否开始城市抽取
- //初始化城市DFA信息
- //ext.InitCityDFA()
- ext.InitCityInfo()
- ext.InitAreaCode()
- ext.InitPostCode()
- }
- //质量审核
- ext.InitAuditFields()
- ext.InitAuditRule()
- ext.InitAuditClass()
- ext.InitAuditRecogField()
- //品牌抽取是否开启
- ju.IsBrandGoods, _ = ju.Config["brandgoods"].(bool)
- //附件抽取是否开启
- ext.InitFile()
- ext.IsRun = true
- go ext.ResultSave(true)
- go ext.BidSave(true)
- if isgo {
- go RunExtractTask(taskId)
- }
- TaskList[taskId] = ext
- return true
- }
- //停止抽取
- func StopExtractTaskId(taskId string) bool {
- defer qu.Catch()
- ext := TaskList[taskId]
- if ext != nil {
- ext.IsRun = false
- TaskList[taskId] = ext
- }
- //更新task.s_extlastid
- db.Mgo.UpdateById("task", taskId, `{"$set":{"s_extlastid":"`+ext.TaskInfo.LastExtId+`"}}`)
- return true
- }
- //开始抽取
- func RunExtractTask(taskId string) {
- defer qu.Catch()
- ext := TaskList[taskId]
- query := bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(ext.TaskInfo.LastExtId)}}
- count := ext.TaskInfo.FDB.Count(ext.TaskInfo.FromColl, query)
- pageNum := (count + PageSize - 1) / PageSize
- limit := PageSize
- if count < PageSize {
- limit = count
- }
- fmt.Printf("count=%d,pageNum=%d,query=%v", count, pageNum, query)
- for i := 0; i < pageNum; i++ {
- query = bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(ext.TaskInfo.LastExtId)}}
- list, _ := ext.TaskInfo.FDB.Find(ext.TaskInfo.FromColl, query, nil, Fields, false, 0, limit)
- fmt.Printf("page=%d,query=%v", i+1, query, len(*list))
- for _, v := range *list {
- if qu.ObjToString(v["sensitive"]) != "" { //去除含敏感词数据
- continue
- }
- //根据标题判断是否抽取
- b := IsExtract("title", qu.ObjToString(v["title"]), "")
- if !b {
- continue
- }
- _id := qu.BsonIdToSId(v["_id"])
- //log.Debug(_id)
- if !ext.IsRun {
- break
- }
- var j, jf *ju.Job
- var isSite bool
- if ext.IsFileField && v["projectinfo"] != nil {
- v["isextFile"] = true
- j, jf, isSite = ext.PreInfo(v)
- } else {
- j, _, isSite = ext.PreInfo(v)
- }
- go ext.ExtractProcess(j, jf, isSite)
- ext.TaskInfo.LastExtId = _id
- ext.TaskInfo.ProcessPool <- true
- }
- db.Mgo.UpdateById("task", ext.Id, `{"$set":{"s_extlastid":"`+ext.TaskInfo.LastExtId+`"}}`)
- if !ext.IsRun {
- break
- }
- }
- //更新task.s_extlastid
- time.AfterFunc(1*time.Minute, func() { RunExtractTask(taskId) })
- }
- //信息预处理-不和版本关联,取最新版本的配置项
- func PreInfo(doc map[string]interface{}) (j, jf *ju.Job, isSite bool) {
- return (&ExtractTask{}).PreInfo(doc)
- }
- //信息预处理-和版本关联
- func (e *ExtractTask) PreInfo(doc map[string]interface{}) (j, jf *ju.Job, isSite bool) {
- defer qu.Catch()
- //判断是否有附件这个字段
- var isextFile bool
- if doc["isextFile"] != nil {
- isextFile = doc["isextFile"].(bool)
- }
- detail := ""
- d1, _ := doc["detail"].(string)
- d2, _ := doc["contenthtml"].(string)
- if len(d1) >= len(d2) || d2 == "" {
- detail = d1
- } else {
- detail = d2
- }
- detail = regexp.MustCompile(`<!--[\w\W]*?-->`).ReplaceAllString(detail, "")
- d3, _ := doc["summary"].(string)
- //全文的需要修复表格
- detail = pretreated.RepairCon(detail)
- detail = ju.CutLableStr(d3 + "\n" + detail)
- detail = cut.ClearHtml(d3 + "\n" + detail)
- doc["detail"] = detail
- if isextFile {
- file2text(&doc) //附件文本堆一起(后期可以考虑,分开处理),方法里修改了doc["detailfile"]结果
- }
- //正文小于200个字,有附件把附件内容加到正文
- tmpDeatil := detail
- tmpdocument, err := goquery.NewDocumentFromReader(strings.NewReader(tmpDeatil))
- if err == nil {
- conlen := utf8.RuneCountInString(strings.Trim(tmpdocument.Text(), " "))
- if conlen < 200 {
- if isextFile {
- detail += qu.ObjToString(doc["detailfile"])
- doc["detail"] = detail
- }
- } else if conlen > qu.IntAllDef(ju.Config["filelength"], 100000) {
- //防止文本过长,造成抽取阻塞
- log.Debug("文本太长", doc["_id"], conlen)
- doc["detail"] = d3
- }
- }
- toptype := qu.ObjToString(doc["toptype"])
- subtype := qu.ObjToString(doc["subtype"])
- if qu.ObjToString(doc["type"]) == "bid" {
- toptype = "结果"
- }
- if toptype == "" {
- toptype = "all"
- }
- if subtype == "" {
- subtype = "all"
- }
- if toptype == "其它" || subtype == "其它" || subtype == "其他" || subtype == "结果变更" {
- toptype = "all"
- subtype = "all"
- }
- toMap := qu.ObjToMap(doc["jsondata"])
- //log.Debug("toMap", toMap)
- if (*toMap) != nil {
- if (*toMap)["extweight"] == nil {
- (*toMap)["extweight"] = ju.Config["jsondata_extweight"]
- }
- }
- j = &ju.Job{
- SourceMid: qu.BsonIdToSId(doc["_id"]),
- Category: toptype,
- CategorySecond: subtype,
- Content: qu.ObjToString(doc["detail"]),
- SpiderCode: qu.ObjToString(doc["spidercode"]),
- Site: qu.ObjToString(doc["site"]),
- //Domain: qu.ObjToString(doc["domain"]),
- //Href: qu.ObjToString(doc["href"]),
- Title: qu.ObjToString(doc["title"]),
- Data: &doc,
- City: qu.ObjToString(doc["city"]),
- Province: qu.ObjToString(doc["area"]),
- Jsondata: toMap,
- Result: map[string][]*ju.ExtField{},
- BuyerAddr: qu.ObjToString(doc["buyeraddr"]),
- RuleBlock: e.RuleBlock,
- }
- if isextFile {
- jf = &ju.Job{
- SourceMid: qu.BsonIdToSId(doc["_id"]),
- Category: toptype,
- Content: qu.ObjToString(doc["detailfile"]),
- SpiderCode: qu.ObjToString(doc["spidercode"]),
- Site: qu.ObjToString(doc["site"]),
- Title: qu.ObjToString(doc["title"]),
- Data: &doc,
- City: qu.ObjToString(doc["city"]),
- Province: qu.ObjToString(doc["area"]),
- Jsondata: toMap,
- Result: map[string][]*ju.ExtField{},
- BuyerAddr: qu.ObjToString(doc["buyeraddr"]),
- RuleBlock: e.RuleBlock,
- IsFile: isextFile,
- }
- }
- //是否配置站点
- codeSite := j.SpiderCode
- exp, isSite := e.Luacodes.Load(codeSite)
- if isSite {
- if exp.(map[string]interface{})["e.SiteClearFn"] != nil {
- e.SiteClearFn = exp.(map[string]interface{})["e.SiteClearFn"].(map[string][]string)
- }
- if exp.(map[string]interface{})["e.SiteTag"] != nil {
- e.SiteTag = exp.(map[string]interface{})["e.SiteTag"].(map[string][]*Tag)
- }
- if exp.(map[string]interface{})["e.SiteRuleCores"] != nil {
- e.SiteRuleCores = exp.(map[string]interface{})["e.SiteRuleCores"].(map[string]map[string][]*RuleCore)
- }
- if exp.(map[string]interface{})["e.SiteRuleBacks"] != nil {
- e.SiteRuleBacks = exp.(map[string]interface{})["e.SiteRuleBacks"].([]*RegLuaInfo)
- }
- }
- qu.Try(func() {
- pretreated.AnalyStart(j, isSite, codeSite) //job.Block分块
- if isextFile {
- pretreated.AnalyStart(jf, isSite, codeSite)
- }
- }, func(err interface{}) {
- log.Debug("pretreated.AnalyStart", err, j.SourceMid)
- })
- return j, jf, isSite
- }
- //遍历附件字段内容,拼接在一起;附件文本堆一起(后期可以考虑,分开处理),方法里修改了doc["detailfile"]结果
- func file2text(doc *map[string]interface{}) {
- var strfileinfo bytes.Buffer
- if v, ok := (*doc)["projectinfo"].(map[string]interface{}); ok {
- if va, ok := v["attachments"].(map[string]interface{}); ok {
- for _, vaatt := range va {
- if fileinfo, ok := vaatt.(map[string]interface{}); ok {
- if qu.ObjToString(fileinfo["content"]) != "" {
- switch fileinfo["content"].(type) {
- case string:
- lock.Lock()
- strfileinfo.WriteString(fileinfo["content"].(string) + " \n")
- lock.Unlock()
- case []map[string]interface{}:
- for _, fv := range fileinfo["content"].([]map[string]interface{}) {
- if fv["context"] != nil {
- lock.Lock()
- strfileinfo.WriteString(fv["context"].(string) + " \n")
- lock.Unlock()
- }
- }
- }
- }
- }
- }
- }
- }
- if utf8.RuneCountInString(strfileinfo.String()) < qu.IntAllDef(ju.Config["filelength"], 100000) {
- (*doc)["detailfile"] = strfileinfo.String() //附件文本堆一起(后期可以考虑,分开处理)
- }
- }
- //抽取
- func (e *ExtractTask) ExtractProcess(j, jf *ju.Job, isSite bool) {
- e.ExtractDetail(j, isSite, j.SpiderCode)
- if jf != nil && jf.IsFile {
- e.ExtractFile(jf, isSite, j.SpiderCode)
- }
- if isSite {
- ismerge, ok := e.SiteMerge.Load(j.SpiderCode)
- if ok && ismerge.(bool) {
- tmpj := &ju.Job{
- SourceMid: j.SourceMid,
- Category: j.Category,
- CategorySecond: j.CategorySecond,
- Content: j.Content,
- SpiderCode: j.SpiderCode,
- //Domain: qu.ObjToString(doc["domain"]),
- //Href: qu.ObjToString(doc["href"]),
- Title: j.Title,
- Data: j.Data,
- City: j.City,
- Province: j.Province,
- Jsondata: j.Jsondata,
- Result: map[string][]*ju.ExtField{},
- BuyerAddr: j.BuyerAddr,
- RuleBlock: e.RuleBlock,
- }
- qu.Try(func() {
- pretreated.AnalyStart(tmpj, false, "") //job.Block分块
- }, func(err interface{}) {
- log.Debug("pretreated.AnalyStart.ExtractProcess", err, j.SourceMid)
- })
- e.ExtractDetail(tmpj, false, "")
- //if jf != nil && jf.IsFile {
- // e.ExtractFile(jf, false, "")
- //}
- //合并数据
- j.Block = append(j.Block, tmpj.Block...)
- j.Winnerorder = append(j.Winnerorder, tmpj.Winnerorder...)
- for tmpk, _ := range j.Result {
- if len(tmpj.Result[tmpk]) > 0 {
- j.Result[tmpk] = append(j.Result[tmpk], tmpj.Result[tmpk]...)
- }
- }
- for tmpk, _ := range tmpj.Result {
- if len(j.Result[tmpk]) == 0 {
- j.Result[tmpk] = append(j.Result[tmpk], tmpj.Result[tmpk]...)
- }
- }
- }
- }
- // for _, b := range j.Block {
- // for _, vv := range b.ColonKV.Kvs {
- // qu.Debug(vv.Key, vv.Value)
- // }
- // for _, vv := range b.SpaceKV.Kvs {
- // qu.Debug(vv.Key, vv.Value)
- // }
- // // for _, vv := range b.TableKV.Kvs {
- // // qu.Debug(vv.Key, vv.Value)
- // // }
- // }
- //分析抽取结果并保存
- AnalysisSaveResult(j, jf, e)
- <-e.TaskInfo.ProcessPool
- }
- func (e *ExtractTask) ExtractDetail(j *ju.Job, isSite bool, codeSite string) {
- qu.Try(func() {
- doc := *j.Data
- //全局前置规则,结果覆盖doc属性
- //for _, v := range e.RulePres {
- // doc = ExtRegPre(doc, j, v, e.TaskInfo)
- //}
- tmprules := map[string][]*RuleCore{}
- lockrule.Lock()
- if j.Category == "all" || j.CategorySecond == "all" {
- if isSite {
- for k, vc1 := range e.SiteRuleCores["all_all"] {
- tmprules[k] = vc1
- }
- } else {
- for k, vc1 := range e.RuleCores["all_all"] {
- tmprules[k] = vc1
- }
- }
- } else {
- if isSite {
- for k, vc1 := range e.SiteRuleCores[j.Category+"_"+j.CategorySecond] {
- tmprules[k] = vc1
- }
- } else {
- for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
- tmprules[k] = vc1
- }
- }
- }
- if len(tmprules) < 1 { //分类未覆盖部分
- if isSite {
- for k, vc1 := range e.RuleCores["all_all"] {
- tmprules[k] = vc1
- }
- } else {
- for k, vc1 := range e.SiteRuleCores["all_all"] {
- tmprules[k] = vc1
- }
- }
- }
- lockrule.Unlock()
- //抽取规则
- for _, vc1 := range tmprules {
- for _, vc := range vc1 {
- tmp := ju.DeepCopy(doc).(map[string]interface{})
- //是否进入逻辑
- if !ju.Logic(vc.LuaLogic, tmp) {
- continue
- }
- ////抽取-前置规则
- //for _, v := range vc.RulePres {
- // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
- //}
- // log.Debug("抽取-前置规则", tmp)
- //抽取-规则
- ExtRuleCore(tmp, e, vc, j, isSite)
- // log.Debug("抽取-规则", tmp)
- //抽取-后置规则
- for _, v := range vc.RuleBacks {
- ExtRegBack(j, v, e.TaskInfo)
- }
- //kv规则
- for _, v := range vc.KVRuleCores {
- ExtRuleKV(j, v, e.TaskInfo)
- }
- // log.Debug("抽取-后置规则", tmp)
- //项目名称未能抽取到,标题来凑
- if vc.Field == "projectname" {
- if vc.ExtFrom == "title" {
- isextitle := true
- for _, v := range j.Result[vc.Field] {
- if len([]rune(qu.ObjToString(v.Value))) > 5 {
- isextitle = false
- break
- }
- }
- if isextitle { //标题加入选举
- 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}
- if isSite {
- field.Score = 1
- }
- j.Result[vc.Field] = append(j.Result[vc.Field], field)
- }
- }
- for i := 0; i < 3; i++ {
- for _, v := range vc.RuleBacks {
- ExtRegBack(j, v, e.TaskInfo)
- }
- }
- }
- }
- }
- //全局后置规则
- if isSite {
- for _, v := range e.SiteRuleBacks {
- ExtRegBack(j, v, e.TaskInfo)
- }
- } else {
- for _, v := range e.RuleBacks {
- ExtRegBack(j, v, e.TaskInfo)
- }
- }
- //函数清理
- for key, val := range j.Result {
- for _, v := range val {
- //qu.Debug(key, v.Value)
- lockclear.Lock()
- var cfn = []string{}
- if isSite {
- cfn = e.SiteClearFn[key]
- } else {
- cfn = e.ClearFn[key]
- }
- lockclear.Unlock()
- if len(cfn) == 0 {
- continue
- }
- data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content})
- before, _ := v.Value.(string)
- v.Value = data[0]
- BeforeAddClearFnLog(v.Type, "函数清理", j.SourceMid, before, v.MatchType, v, e)
- //添加行数清理的日志
- //清理特殊符号
- lockclear.Lock()
- if clear.AsyField[key] != nil || clear.SymField[key] != nil || clear.MesField[key] != nil {
- text := qu.ObjToString(v.Value)
- before = text
- v.Value = clear.OtherClean(key, text)
- BeforeAddClearFnLog(v.Type, "特殊符号清理", j.SourceMid, before, v.MatchType, v, e)
- }
- //AddClearFnLog("clearfn", j.SourceMid, v.Value, extinfo, v.Code, "函数清理", key, e.TaskInfo)
- lockclear.Unlock()
- }
- }
- PackageDetail(j, e, isSite, codeSite) //处理分包信息
- // bs, _ := json.Marshal(j.Result)
- // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
- }, func(err interface{}) {
- log.Debug("ExtractProcess err", err)
- })
- }
- func (e *ExtractTask) ExtractFile(j *ju.Job, isSite bool, codeSite string) {
- qu.Try(func() {
- doc := *j.Data
- //全局前置规则,结果覆盖doc属性
- // for _, v := range e.RulePres {
- // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
- // doc = ExtRegPre(doc, j, v, e.TaskInfo)
- // }
- // }
- //抽取规则
- tmprules := map[string][]*RuleCore{}
- lockrule.Lock()
- if j.Category == "all" || j.CategorySecond == "all" {
- for k, vc1 := range e.RuleCores["all_all"] {
- tmprules[k] = vc1
- }
- } else {
- for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
- tmprules[k] = vc1
- }
- }
- lockrule.Unlock()
- for _, vc1 := range tmprules {
- for _, vc := range vc1 {
- tmp := ju.DeepCopy(doc).(map[string]interface{})
- //是否进入逻辑
- if !ju.Logic(vc.LuaLogic, tmp) {
- continue
- }
- //抽取-前置规则
- // for _, v := range vc.RulePres {
- // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
- // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
- // }
- // }
- // log.Debug("抽取-前置规则", tmp)
- //抽取-规则
- if value, ok := e.FileFields.Load(vc.Field); ok && qu.IntAllDef(value, 1) > 0 {
- ExtRuleCore(tmp, e, vc, j, isSite)
- }
- // log.Debug("抽取-规则", tmp)
- //抽取-后置规则
- for _, v := range vc.RuleBacks {
- if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
- ExtRegBack(j, v, e.TaskInfo)
- }
- }
- // log.Debug("抽取-后置规则", tmp)
- }
- }
- //全局后置规则
- for _, v := range e.RuleBacks {
- if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
- ExtRegBack(j, v, e.TaskInfo)
- }
- }
- //函数清理
- for key, val := range j.Result {
- for _, v := range val {
- lockclear.Lock()
- cfn := e.ClearFn[key]
- lockclear.Unlock()
- data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content})
- v.Value = data[0]
- //清理特殊符号
- lockclear.Lock()
- if clear.AsyField[key] != nil || clear.SymField[key] != nil ||
- clear.MesField[key] != nil {
- text := qu.ObjToString(v.Value)
- text = clear.OtherClean(key, text)
- v.Value = text
- }
- lockclear.Unlock()
- }
- }
- PackageDetail(j, e, isSite, codeSite) //处理分包信息
- // bs, _ := json.Marshal(j.Result)
- // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
- }, func(err interface{}) {
- log.Debug("ExtractProcess err", err)
- })
- }
- //前置过滤
- func ExtRegPre(doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, t *TaskInfo) map[string]interface{} {
- defer qu.Catch()
- before := ju.DeepCopy(doc).(map[string]interface{})
- extinfo := map[string]interface{}{}
- if in.IsLua {
- lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
- if j != nil {
- lua.Block = j.Block
- }
- extinfo = lua.RunScript("pre")
- for k, v := range extinfo { //结果覆盖原doc
- doc[k] = v
- }
- AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
- } else {
- var key string
- if !j.IsFile {
- key = qu.If(in.Field == "", "detail", in.Field).(string)
- } else {
- key = qu.If(in.Field == "", "detailfile", in.Field).(string)
- }
- text := qu.ObjToString(doc[key])
- extinfo[key] = in.RegPreBac.Reg.ReplaceAllString(text, "")
- doc[key] = extinfo[key] //结果覆盖原doc
- AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
- }
- return doc
- }
- //抽取-规则
- func ExtRuleCore(doc map[string]interface{}, e *ExtractTask, vc *RuleCore, j *ju.Job, isSite bool) {
- //候选人加入
- var kvMap map[string][]map[string]interface{}
- extByReg := true
- if vc.ExtFrom != "title" {
- kvMap, extByReg = getKvByLuaFields(vc, j, e)
- }
- for _, v := range vc.RuleCores {
- if v.IsLua {
- ExtRuleCoreByKv(vc.ExtFrom, doc, j, v, &kvMap, e)
- } else if extByReg {
- ExtRuleCoreByReg(vc.ExtFrom, doc, j, v, e, isSite)
- }
- }
- //如果只有一个分包,预算没有抽取到,把分包中的预算保存到外面
- if vc.Field == "budget" && len(kvMap) == 0 {
- if len(j.BlockPackage) == 1 {
- for _, bp := range j.BlockPackage {
- for fieldname, field := range vc.LFields {
- if field != vc.Field {
- continue
- }
- tp := ""
- for k, v := range []*ju.JobKv{bp.ColonKV, bp.SpaceKV, bp.TableKV} {
- if k == 0 {
- tp = "colon"
- // for _, vv := range v.Kvs {
- // qu.Debug(vv.Key, vv.Value)
- // }
- } else if k == 1 {
- tp = "space"
- } else if k == 2 {
- tp = "table"
- }
- if v == nil || v.KvTags == nil {
- continue
- }
- for _, vv := range v.KvTags[fieldname] {
- text := ju.TrimLRSpace(vv.Value, "")
- if text != "" {
- tmp := &ju.ExtField{
- Field: vc.Field,
- Code: "CL_分包",
- Type: tp,
- MatchType: "package",
- RuleText: bp.Text,
- SourceValue: vv.Key,
- Value: text,
- }
- if isSite {
- tmp.Score = 1
- }
- j.Result[vc.Field] = append(j.Result[vc.Field], tmp)
- }
- }
- }
- }
- break
- }
- }
- } else {
- for k, v := range kvMap {
- if j.Result[k] == nil {
- j.Result[k] = [](*ju.ExtField){}
- }
- for _, tmp := range v {
- 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"]}
- if isSite {
- field.Score = 1
- }
- if tmp["blocktag"] != nil {
- btag := make(map[string]string)
- for k := range tmp["blocktag"].(map[string]bool) {
- blocktag.Lock()
- if TagConfigDesc[k] != "" {
- btag[k] = TagConfigDesc[k]
- }
- blocktag.Unlock()
- }
- field.BlockTag = btag
- }
- j.Result[k] = append(j.Result[k], field)
- }
- }
- }
- }
- //抽取-规则-kv
- func ExtRuleCoreByKv(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, kvMap *map[string][]map[string]interface{}, et *ExtractTask) {
- defer qu.Catch()
- if extfrom == "title" || !in.IsLua {
- return
- }
- lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
- lua.KvMap = *kvMap
- lua.Block = j.Block
- extinfo := lua.RunScript("core")
- if tmps, ok := extinfo[in.Field].([]map[string]interface{}); ok {
- for _, v := range tmps {
- v["core"] = in.Code
- }
- (*kvMap)[in.Field] = append((*kvMap)[in.Field], tmps...)
- }
- if len(extinfo) > 0 {
- AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
- }
- }
- //抽取-规则-正则
- func ExtRuleCoreByReg(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, et *ExtractTask, isSite bool) {
- defer qu.Catch()
- //根据field配置项目,是否抽取。例如:废标、流标等跳过,
- b := IsExtract(in.Field, j.Title, j.Content)
- if !b {
- return
- }
- //全文正则
- //text := qu.ObjToString(doc[extfrom])
- //if in.Field != "" {
- // extinfo := extRegCoreToResult(extfrom, text, j, in)
- // if len(extinfo) > 0 {
- // AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
- // }
- //}
- //块抽取
- if in.Field != "" {
- if extfrom == "title" {
- extinfo := extRegCoreToResult(extfrom, qu.ObjToString(doc[extfrom]), &map[string]string{}, j, in, isSite)
- if len(extinfo) > 0 {
- AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
- }
- } else {
- for _, v := range j.Block {
- btag := make(map[string]string)
- for k := range v.Classify {
- blocktag.Lock()
- btag[k] = TagConfigDesc[k]
- blocktag.Unlock()
- }
- extinfo := extRegCoreToResult(extfrom, v.Text, &btag, j, in, isSite)
- if len(extinfo) > 0 {
- AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
- }
- }
- }
- }
- }
- //pkg抽取-规则-正则
- func ExtRuleCoreByPkgReg(j *ju.Job, in *RegLuaInfo, e *ExtractTask) {
- defer qu.Catch()
- //根据field配置项目,是否抽取。例如:废标、流标等跳过,
- b := IsExtract(in.Field, j.Title, j.Content)
- if !b {
- return
- }
- //块抽取
- if in.Field != "" {
- for k, vbpkg := range j.BlockPackage {
- rep := map[string]string{}
- if in.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
- if !((in.Field == "budget" && vbpkg.Budget > 0) || (in.Field == "bidamount" && vbpkg.Bidamount > 0) ||
- (in.Field == "winner" && vbpkg.Winner == "") || (in.Field == "bidstatus" && vbpkg.BidStatus == "") ||
- (in.Field == "projectname" && vbpkg.Name == "")) {
- continue
- }
- //处理正负数修正
- ptmp := strings.Split(in.RuleText, "#")
- sign := 0
- if len(ptmp) == 2 {
- if ptmp[1] == "正" {
- sign = 1
- } else if ptmp[1] == "负" {
- sign = -1
- }
- }
- tmp := strings.Split(ptmp[0], "__")
- if len(tmp) == 2 {
- epos := strings.Split(tmp[1], ",")
- posm := map[string]int{}
- for _, v := range epos {
- ks := strings.Split(v, ":")
- if len(ks) == 2 { //(.*)招标公告(.*)__2:projectname,4:area
- posm[ks[1]] = qu.IntAll(ks[0])
- } else {
- posm[in.Field] = qu.IntAll(ks[0])
- }
- }
- var pattern string
- if strings.Contains(tmp[0], "\\u") {
- tmp[0] = strings.Replace(tmp[0], "\\", "\\\\", -1)
- tmp[0] = strings.Replace(tmp[0], "\\\\u", "\\u", -1)
- pattern, _ = strconv.Unquote(`"` + tmp[0] + `"`)
- } else {
- pattern = tmp[0]
- }
- //log.Debug("pattern", pattern)
- //fmt.Println(text)
- reg := regexp.MustCompile(pattern)
- apos := reg.FindAllStringSubmatchIndex(vbpkg.Text, -1)
- for i, _ := range apos {
- pos := apos[i]
- for k, p := range posm {
- if len(pos) > p {
- if pos[p] == -1 || pos[p+1] == -1 {
- continue
- }
- val := vbpkg.Text[pos[p]:pos[p+1]]
- if string(val) == "" {
- continue
- }
- if sign == -1 {
- rep[k+"_"+fmt.Sprint(i)] = "-" + val
- } else {
- rep[k+"_"+fmt.Sprint(i)] = val
- }
- }
- }
- }
- //fmt.Println(text)
- for i := 0; i < len(apos); i++ {
- if strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]) != "" {
- if in.Field == "budget" && vbpkg.Budget <= 0 {
- lock.Lock()
- cfn := e.ClearFn[in.Field]
- lock.Unlock()
- data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content})
- j.BlockPackage[k].Budget = qu.Float64All(data[0])
- break
- } else if in.Field == "bidamount" && vbpkg.Bidamount <= 0 {
- lock.Lock()
- cfn := e.ClearFn[in.Field]
- lock.Unlock()
- data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content})
- j.BlockPackage[k].Bidamount = qu.Float64All(data[0])
- break
- } else if in.Field == "winner" {
- if j.BlockPackage[k].Winner == "" {
- j.BlockPackage[k].Winner = rep[in.Field+"_"+fmt.Sprint(i)]
- break
- }
- } else if in.Field == "bidstatus" {
- if j.BlockPackage[k].BidStatus == "" {
- j.BlockPackage[k].BidStatus = rep[in.Field+"_"+fmt.Sprint(i)]
- break
- }
- } else if in.Field == "projectname" {
- if j.BlockPackage[k].Name == "" {
- j.BlockPackage[k].Name = rep[in.Field+"_"+fmt.Sprint(i)]
- break
- }
- }
- }
- }
- }
- } else {
- pos := in.RegCore.Reg.FindStringIndex(vbpkg.Text)
- val := ""
- if len(pos) == 2 {
- //"text" = "text"[pos[1]:]
- val = "text"[pos[1]:]
- rs := regexp.MustCompile("[^\r\n\t]+")
- tmp := rs.FindAllString("text", -1)
- if len(tmp) > 0 {
- val = tmp[0]
- }
- }
- if val != "" {
- if in.Field == "budget" && vbpkg.Budget <= 0 {
- lock.Lock()
- cfn := e.ClearFn[in.Field]
- lock.Unlock()
- data := clear.DoClearFn(cfn, []interface{}{val, j.Content})
- j.BlockPackage[k].Budget = qu.Float64All(data[0])
- break
- }
- if in.Field == "bidamount" && vbpkg.Bidamount <= 0 {
- lock.Lock()
- cfn := e.ClearFn[in.Field]
- lock.Unlock()
- data := clear.DoClearFn(cfn, []interface{}{val, j.Content})
- j.BlockPackage[k].Bidamount = qu.Float64All(data[0])
- break
- } else if in.Field == "bidstatus" {
- if j.BlockPackage[k].BidStatus == "" {
- j.BlockPackage[k].BidStatus = val
- break
- }
- } else if in.Field == "projectname" {
- if j.BlockPackage[k].Name == "" {
- j.BlockPackage[k].Name = val
- break
- }
- }
- }
- }
- }
- }
- }
- //lua脚本根据属性设置提取kv值
- func getKvByLuaFields(vc *RuleCore, j *ju.Job, et *ExtractTask) (map[string][]map[string]interface{}, bool) {
- kvmap := map[string][]map[string]interface{}{}
- if len(j.Winnerorder) > 1 {
- if vc.Field == "bidamount" {
- for _, v := range j.Winnerorder {
- kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
- "code": "winnerorder",
- "field": vc.Field,
- "ruletext": "中标候选人",
- "extfrom": vc.ExtFrom,
- "sourcevalue": "中标候选人",
- "value": v["price"],
- "type": "winnerorder",
- "matchtype": "winnerorder",
- })
- }
- //候选人中标金额
- if price := j.Winnerorder[0]["price"]; price != nil {
- kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
- "code": "CL_中标候选人",
- "field": vc.Field,
- "ruletext": "中标候选人",
- "extfrom": vc.ExtFrom,
- "sourcevalue": "中标候选人",
- "value": price,
- "type": "winnerorder",
- "matchtype": "winnerorder",
- })
- return kvmap, false
- }
- }
- //else if vc.Field == "winner" {
- // for _, v := range j.Winnerorder {
- // kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
- // "code": "winnerorder",
- // "field": vc.Field,
- // "ruletext": "中标候选人",
- // "extfrom": vc.ExtFrom,
- // "sourcevalue": "中标候选人",
- // "value": v["entname"],
- // "type": "winnerorder",
- // "matchtype": "winnerorder",
- // })
- // }
- // //候选人中标单位
- // if entname := j.Winnerorder[0]["entname"]; entname != nil {
- // kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
- // "code": "CL_中标候选人",
- // "field": vc.Field,
- // "ruletext": "中标候选人",
- // "extfrom": vc.ExtFrom,
- // "sourcevalue": "中标候选人",
- // "value": entname,
- // "type": "winnerorder",
- // "matchtype": "winnerorder",
- // })
- // return kvmap, false
- // }
- //}
- }
- for fieldname, field := range vc.LFields {
- if field != vc.Field {
- continue
- }
- extractFromKv(field, fieldname, j.Block, vc, kvmap)
- }
- AddExtLog("extract", j.SourceMid, nil, kvmap, &RegLuaInfo{Field: vc.Field}, et.TaskInfo) //抽取日志
- return kvmap, true
- }
- func extractFromKv(field, fieldname string, blocks []*ju.Block, vc *RuleCore, kvmap map[string][]map[string]interface{}) {
- //qu.Debug("fieldname+++", fieldname)
- for _, bl := range blocks {
- tp := ""
- for k, v := range []*ju.JobKv{bl.ColonKV, bl.SpaceKV, bl.TableKV} {
- if k == 0 {
- tp = "colon"
- // for _, vv := range v.Kvs {
- // qu.Debug("colon-kvs:", vv.Key, vv.Value)
- // }
- // for kkk, vv := range v.KvTags {
- // for _, vvv := range vv {
- // qu.Debug("colon-tags", kkk, vvv.Key, vvv.Value)
- // }
- // }
- } else if k == 1 {
- tp = "space"
- } else if k == 2 {
- tp = "table"
- // for _, vv := range v.Kvs {
- // qu.Debug("table-kvs:", vv.Key, vv.Value)
- // }
- // for kkk, vv := range v.KvTags {
- // for _, vvv := range vv {
- // qu.Debug("table-tags", kkk, vvv.Key, vvv.Value)
- // }
- // }
- }
- if v == nil || v.KvTags == nil {
- continue
- }
- for _, vv := range v.KvTags[fieldname] {
- text := ju.TrimLRSpace(vv.Value, "")
- if text != "" {
- kvmap[field] = append(kvmap[field], map[string]interface{}{
- "code": "CL_" + vv.Key,
- "field": field,
- "ruletext": vv.Key,
- "extfrom": vc.ExtFrom,
- "sourcevalue": text,
- "value": text,
- "type": tp,
- "matchtype": "tag_string",
- "blocktag": bl.Classify,
- "weight": vv.Weight,
- })
- //if field != "winnertel" && field != "winnerperson" {
- // //break //暂定取第一个
- //}
- }
- }
- }
- if len(kvmap[field]) == 0 {
- extractFromKv(field, fieldname, bl.Block, vc, kvmap)
- }
- }
- }
- //正则提取结果
- func extRegCoreToResult(extfrom, text string, tag *map[string]string, j *ju.Job, vre *RegLuaInfo, isSite bool) map[string][]map[string]interface{} {
- defer qu.Catch()
- var score int
- if isSite {
- score = 1
- }
- extinfo := map[string][]map[string]interface{}{}
- rep := map[string]string{}
- if vre.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
- //处理正负数修正
- ptmp := strings.Split(vre.RuleText, "#")
- sign := 0
- if len(ptmp) == 2 {
- if ptmp[1] == "正" {
- sign = 1
- } else if ptmp[1] == "负" {
- sign = -1
- }
- }
- tmp := strings.Split(ptmp[0], "__")
- if len(tmp) == 2 {
- epos := strings.Split(tmp[1], ",")
- posm := map[string]int{}
- for _, v := range epos {
- ks := strings.Split(v, ":")
- if len(ks) == 2 { //(.*)招标公告(.*)__2:projectname,4:area
- posm[ks[1]] = qu.IntAll(ks[0])
- } else {
- posm[vre.Field] = qu.IntAll(ks[0])
- }
- }
- var pattern string
- if strings.Contains(tmp[0], "\\u") {
- tmp[0] = strings.Replace(tmp[0], "\\", "\\\\", -1)
- tmp[0] = strings.Replace(tmp[0], "\\\\u", "\\u", -1)
- pattern, _ = strconv.Unquote(`"` + tmp[0] + `"`)
- } else {
- pattern = tmp[0]
- }
- //log.Debug("pattern", pattern)
- //fmt.Println(text)
- reg := regexp.MustCompile(pattern)
- apos := reg.FindAllStringSubmatchIndex(text, -1)
- for i, _ := range apos {
- pos := apos[i]
- for k, p := range posm {
- if len(pos) > p {
- if pos[p] == -1 || pos[p+1] == -1 {
- continue
- }
- val := text[pos[p]:pos[p+1]]
- if string(val) == "" {
- continue
- }
- if sign == -1 {
- rep[k+"_"+fmt.Sprint(i)] = "-" + val
- } else {
- rep[k+"_"+fmt.Sprint(i)] = val
- }
- }
- }
- }
- //fmt.Println(text)
- tmps := []map[string]interface{}{}
- for i := 0; i < len(apos); i++ {
- if strings.TrimSpace(rep[vre.Field+"_"+fmt.Sprint(i)]) != "" {
- tmp := map[string]interface{}{
- "field": vre.Field,
- "code": vre.Code,
- "ruletext": vre.RuleText,
- "extfrom": text,
- "value": rep[vre.Field+"_"+fmt.Sprint(i)],
- "type": "regexp",
- "matchtype": "regcontent",
- "blocktag": *tag,
- "score": score,
- }
- tmps = append(tmps, tmp)
- exfield := ju.ExtField{BlockTag: *tag, Field: vre.Field, Code: vre.Code, RuleText: vre.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: rep[vre.Field+"_"+fmt.Sprint(i)], Value: rep[vre.Field+"_"+fmt.Sprint(i)]}
- if tmp["blocktag"] != nil {
- exfield.BlockTag = tmp["blocktag"].(map[string]string)
- }
- j.Result[vre.Field] = append(j.Result[vre.Field], &exfield)
- }
- }
- if len(tmps) > 0 {
- extinfo[vre.Field] = tmps
- }
- }
- } else {
- pos := vre.RegCore.Reg.FindStringIndex(text)
- val := ""
- if len(pos) == 2 {
- text = text[pos[1]:]
- rs := regexp.MustCompile("[^\r\n\t]+")
- tmp := rs.FindAllString(text, -1)
- if len(tmp) > 0 {
- val = tmp[0]
- }
- }
- if val != "" {
- tmps := []map[string]interface{}{}
- tmp := map[string]interface{}{
- "field": vre.Field,
- "code": vre.Code,
- "ruletext": vre.RuleText,
- "extfrom": text,
- "value": val,
- "type": "regexp",
- "matchtype": "regcontent",
- "blocktag": *tag,
- "score": score,
- }
- tmps = append(tmps, tmp)
- extinfo[vre.Field] = tmps
- if j.Result[vre.Field] == nil {
- j.Result[vre.Field] = [](*ju.ExtField){}
- }
- field := &ju.ExtField{BlockTag: *tag, Field: vre.Field, Code: vre.Code, RuleText: vre.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: text, Value: val}
- if tmp["blocktag"] != nil {
- field.BlockTag = tmp["blocktag"].(map[string]string)
- }
- j.Result[vre.Field] = append(j.Result[vre.Field], field)
- }
- }
- return extinfo
- }
- //后置过滤
- func ExtRegBack(j *ju.Job, in *RegLuaInfo, t *TaskInfo) {
- defer qu.Catch()
- if in.IsLua {
- result := GetResultMapForLua(j)
- lua := ju.LuaScript{Code: in.Code, Name: in.Name, Result: result, Script: in.RuleText}
- if j != nil {
- lua.Block = j.Block
- }
- extinfo := lua.RunScript("back")
- for k, v := range extinfo {
- if tmps, ok := v.([]map[string]interface{}); ok {
- j.Result[k] = [](*ju.ExtField){}
- for _, tmp := range tmps {
- 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"]}
- if tmp["blocktag"] != nil {
- field.BlockTag = tmp["blocktag"].(map[string]string)
- }
- j.Result[k] = append(j.Result[k], field)
- //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})
- }
- }
- }
- if len(extinfo) > 0 {
- AddExtLog("clear", j.SourceMid, result, extinfo, in, t) //抽取日志
- }
- } else {
- extinfo := map[string]interface{}{}
- if in.Field != "" {
- if j.Result[in.Field] != nil {
- tmp := j.Result[in.Field]
- exts := []interface{}{}
- for k, v := range tmp {
- //table抽取到的数据不清理
- // if v.Type == "table" && v.Field != "projectname" {
- // continue
- // }
- text := qu.ObjToString(v.Value)
- if text != "" {
- text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
- }
- if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
- continue
- }
- j.Result[in.Field][k].Value = text
- exts = append(exts, map[string]interface{}{
- "field": v.Field,
- "code": v.Code,
- "ruletext": v.RuleText,
- "type": v.Type,
- "matchtype": v.MatchType,
- "extfrom": v.ExtFrom,
- "value": text,
- })
- }
- if len(exts) > 0 {
- extinfo[in.Field] = exts
- AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
- }
- }
- } else {
- for key, tmp := range j.Result {
- exts := []interface{}{}
- for k, v := range tmp {
- if v.Type == "table" { //table抽取到的数据不清理
- continue
- }
- text := qu.ObjToString(v.Value)
- if text != "" {
- text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
- }
- if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
- continue
- }
- j.Result[key][k].Value = text
- exts = append(exts, map[string]interface{}{
- "field": v.Field,
- "code": v.Code,
- "ruletext": v.RuleText,
- "type": v.Type,
- "matchtype": v.MatchType,
- "extfrom": v.ExtFrom,
- "value": text,
- })
- }
- if len(exts) > 0 {
- extinfo[key] = exts
- AddExtLog("clear", j.SourceMid, j.Result, extinfo, in, t) //抽取日志
- }
- }
- }
- }
- }
- //后置过滤
- func ExtRegBackPkg(j *ju.Job, in *RegLuaInfo) {
- defer qu.Catch()
- for k, v := range j.BlockPackage {
- if in.Field == "winner" {
- j.BlockPackage[k].Winner = in.RegPreBac.Reg.ReplaceAllString(v.Winner, in.RegPreBac.Replace)
- } else if in.Field == "bidstatus" {
- j.BlockPackage[k].BidStatus = in.RegPreBac.Reg.ReplaceAllString(v.BidStatus, in.RegPreBac.Replace)
- } else if in.Field == "" {
- j.BlockPackage[k].Text = in.RegPreBac.Reg.ReplaceAllString(v.Text, in.RegPreBac.Replace)
- } else if in.Field == "projectname" {
- j.BlockPackage[k].Name = in.RegPreBac.Reg.ReplaceAllString(v.Name, in.RegPreBac.Replace)
- }
- }
- }
- //KV过滤
- func ExtRuleKV(j *ju.Job, in *RegLuaInfo, t *TaskInfo) {
- defer qu.Catch()
- extinfo := map[string]interface{}{}
- if in.Field != "" {
- if j.Result[in.Field] != nil {
- tmp := j.Result[in.Field]
- exts := []interface{}{}
- for k, v := range tmp {
- if v.Type != "table" && !strings.Contains(v.Type, "colon") && !strings.Contains(v.Type, "space") {
- continue
- }
- text := qu.ObjToString(v.Value)
- if text != "" {
- text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
- }
- if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
- continue
- }
- j.Result[in.Field][k].Value = text
- exts = append(exts, map[string]interface{}{
- "field": v.Field,
- "code": v.Code,
- "ruletext": v.RuleText,
- "type": v.Type,
- "matchtype": v.MatchType,
- "extfrom": v.ExtFrom,
- "value": text,
- })
- }
- if len(exts) > 0 {
- extinfo[in.Field] = exts
- AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
- }
- }
- }
- }
- //获取抽取结果map[string][]interface{},lua脚本使用
- func GetResultMapForLua(j *ju.Job) map[string][]map[string]interface{} {
- defer qu.Catch()
- result := map[string][]map[string]interface{}{}
- for key, val := range j.Result {
- if result[key] == nil {
- result[key] = []map[string]interface{}{}
- }
- for _, v := range val {
- tmp := map[string]interface{}{
- "field": v.Field,
- "code": v.Code,
- "ruletext": v.RuleText,
- "value": v.Value,
- "type": v.Type,
- "matchtype": v.MatchType,
- "extfrom": v.ExtFrom,
- }
- result[key] = append(result[key], tmp)
- }
- }
- return result
- }
- //抽取日志
- func AddExtLog(ftype, sid string, before interface{}, extinfo interface{}, v *RegLuaInfo, t *TaskInfo) {
- defer qu.Catch()
- if !t.IsEtxLog {
- return
- }
- logdata := map[string]interface{}{
- "code": qu.If(v.Code == "", "kv", v.Code),
- "name": v.Name,
- "type": ftype,
- "ruletext": v.RuleText,
- "islua": v.IsLua,
- "field": v.Field,
- "version": t.Version,
- "taskname": t.Name,
- "before": before,
- "extinfo": extinfo,
- "sid": sid,
- "comeintime": time.Now().Unix(),
- }
- lock.Lock()
- ExtLogs[t] = append(ExtLogs[t], logdata)
- lock.Unlock()
- }
- func BeforeAddClearFnLog(ftype, name, sid, before, matchtype string, ext *ju.ExtField, e *ExtractTask) {
- exts := []map[string]interface{}{}
- exts = append(exts, map[string]interface{}{
- "field": ext.Field,
- "code": ext.Code,
- "type": ftype,
- "matchtype": matchtype,
- "extfrom": ext.ExtFrom,
- "value": ext.Value,
- })
- extinfo := map[string]interface{}{
- ext.Field: exts,
- }
- AddClearFnLog(ftype, sid, before, extinfo, ext.Code, name, ext.Field, e.TaskInfo)
- }
- func AddClearFnLog(ftype, sid string, before interface{}, extinfo interface{}, code, name, field string, t *TaskInfo) {
- defer qu.Catch()
- if !t.IsEtxLog {
- return
- }
- logdata := map[string]interface{}{
- "code": code,
- "name": name,
- "type": ftype,
- "ruletext": "",
- "islua": false,
- "field": field,
- "version": t.Version,
- "taskname": t.Name,
- "before": before,
- "extinfo": extinfo,
- "sid": sid,
- "comeintime": time.Now().Unix(),
- }
- lock.Lock()
- ExtLogs[t] = append(ExtLogs[t], logdata)
- lock.Unlock()
- }
- //保存抽取日志
- func SaveExtLog() {
- defer qu.Catch()
- tmpLogs := map[*TaskInfo][]map[string]interface{}{}
- lock.Lock()
- tmpLogs = ExtLogs
- ExtLogs = map[*TaskInfo][]map[string]interface{}{}
- lock.Unlock()
- for k, v := range tmpLogs {
- if len(v) < saveLimit {
- db.Mgo.SaveBulk(k.TrackColl, v...)
- } else {
- for {
- if len(v) > saveLimit {
- tmp := v[:saveLimit]
- db.Mgo.SaveBulk(k.TrackColl, tmp...)
- v = v[saveLimit:]
- } else {
- db.Mgo.SaveBulk(k.TrackColl, v...)
- break
- }
- }
- }
- }
- time.AfterFunc(10*time.Second, SaveExtLog)
- }
- type FieldValue struct {
- Value interface{}
- Count int
- }
- //分析抽取结果并保存
- func AnalysisSaveResult(j, jf *ju.Job, e *ExtractTask) {
- qu.Try(func() {
- //重新取出清理过后的中标候选人
- resetWinnerorder(j)
- doc, result, _id := funcAnalysis(j, e)
- if ju.IsSaveTag {
- go otherNeedSave(j, result, e)
- }
- auxinfo := auxInfo(j)
- //从排序结果中取值
- tmp := map[string]interface{}{} //抽取值
- tmp["spidercode"] = j.SpiderCode
- tmp["site"] = j.Site
- tmp["jsondata"] = j.Jsondata
- tmp["fieldall"] = auxinfo
- for _, val := range result {
- for _, v := range val { //取第一个非负数,项目名称除外
- if v.Score > -1 {
- tmp[v.Field] = v.Value
- break
- } else if v.Field == "projectname" {
- tmp[v.Field] = v.Value
- break
- }
- }
- }
- if len(j.PackageInfo) > 0 { //分包信息
- tmp["package"] = j.PackageInfo
- }
- if len(j.Winnerorder) > 0 { //候选人信息
- tmp["winnerorder"] = j.Winnerorder
- }
- //处理附件
- var resultf map[string][]*ju.ExtField
- if jf != nil {
- _, resultf, _ = funcAnalysis(jf, e)
- auxinfof := auxInfo(jf)
- tmp["fieldallf"] = auxinfof
- ffield := map[string]interface{}{}
- for _, val := range resultf {
- for _, v := range val { //取第一个非负数
- if v.Score > -1 {
- ffield[v.Field] = v.Value
- break
- }
- }
- }
- if len(jf.PackageInfo) > 0 { //分包信息
- ffield["package"] = jf.PackageInfo
- }
- if len(jf.Winnerorder) > 0 { //候选人信息
- ffield["winnerorder"] = jf.Winnerorder
- }
- tmp["ffield"] = ffield
- }
- for k, v := range *doc {
- //去重冗余字段
- if delFiled(k) {
- continue
- }
- if tmp[k] == nil {
- tmp[k] = v
- }
- }
- //质量审核
- if ju.QualityAudit {
- e.QualityAudit(tmp)
- }
- if e.IsExtractCity { //城市抽取
- //e.ExtractCity(j, tmp, _id)
- e.NewExtractCity(j, tmp, _id)
- // b, p, c, d := e.TransmitData(tmp, _id) //抽取省份城市
- // // log.Debug("省份---", p, "城市---", c, "区---", d)
- // tmp["district"] = d
- // if b {
- // tmp["city"] = c
- // tmp["area"] = p
- // }
- }
- //品牌抽取
- if ju.IsBrandGoods {
- tmp["checkhas"] = map[string]int{
- "hastable": j.HasTable,
- "hasgoods": j.HasGoods,
- "hasbrand": j.HasBrand,
- "haskey": j.HasKey,
- }
- if len(j.BrandData) > 0 {
- tmp["tablebrand"] = j.BrandData
- }
- // log.Debug("============", j.HasBrand, j.HasGoods, j.HasKey, j.HasTable, j.BrandData)
- }
- //所有kv组成的字符串
- var kvtext bytes.Buffer
- blocks := make([]ju.BlockAndTag, 0)
- for _, v := range j.Block {
- //分包和标签
- if ju.SaveBlock {
- xx, _ := json.Marshal(v)
- tmpblock := new(ju.TmpBlock)
- err := json.Unmarshal(xx, &tmpblock)
- if err != nil {
- if v.BPackage != nil {
- bpb, _ := json.Marshal(v.BPackage)
- tmpblock.BPackage = string(bpb)
- }
- tmpblock = rangeBlockToJson(v, *tmpblock)
- }
- blocks = append(blocks, ju.BlockAndTag{v.Tag, tmpblock})
- }
- //把所有kv组装成一个字符串,存库
- for _, jv := range []*ju.JobKv{v.ColonKV, v.SpaceKV, v.TableKV} {
- if jv == nil {
- continue
- }
- for jv_k, jv_v := range jv.KvTags {
- for _, jv_vv := range jv_v {
- kvtext.WriteString(jv_k)
- kvtext.WriteString(":")
- kvtext.WriteString(jv_vv.Value)
- kvtext.WriteString(" ")
- }
- }
- }
- }
- if kvtext.Len() > 0 {
- tmp["kvtext"] = kvtext.String()
- }
- if len(blocks) > 0 {
- if blocksBytes, err := json.Marshal(blocks); err == nil {
- if utf8.RuneCount(blocksBytes) < 100000 {
- tmp["blocks"] = string(blocksBytes)
- }
- }
- }
- //tmp["extract_content"] = j.Content
- if e.TaskInfo.TestColl == "" {
- if len(tmp) > 0 { //保存抽取结果
- /* if len(e.SiteFields) <= 0 {
- //for field, _ := range e.Fields {
- // if tmp[field] == nil && {
- // tmp[field] = "" //覆盖之前版本数据
- // }
- //}
- } else {
- //for field, _ := range e.SiteFields {
- // if tmp[field] == nil &&{
- // tmp[field] = "" //覆盖之前版本数据
- // }
- //}
- }*/
- tmp["repeat"] = 0
- tmparr := []map[string]interface{}{
- map[string]interface{}{
- "_id": qu.StringTOBsonId(_id),
- },
- map[string]interface{}{"$set": tmp},
- }
- e.RWMutex.Lock()
- e.BidArr = append(e.BidArr, tmparr)
- e.BidTotal++
- e.RWMutex.Unlock()
- }
- if ju.SaveResult {
- id := tmp["_id"]
- tmp["result"] = result
- tmp["resultf"] = resultf
- delete(tmp, "_id")
- tmparr := []map[string]interface{}{
- map[string]interface{}{
- "_id": id,
- },
- map[string]interface{}{"$set": tmp},
- }
- e.RWMutex.Lock()
- e.ResultArr = append(e.ResultArr, tmparr)
- e.RWMutex.Unlock()
- }
- } else { //测试结果
- // fmt.Println("=============抽取结果================")
- // for k, v := range tmp {
- // qu.Debug(k, "---", v)
- // }
- // for field, _ := range e.Fields {
- // qu.Debug(field, "---", tmp[field])
- // }
- delete(tmp, "_id")
- if len(j.BlockPackage) > 0 { //分包详情
- bs, _ := json.Marshal(j.BlockPackage)
- tmp["epackage"] = string(bs)
- }
- tmp["result"] = result
- tmp["resultf"] = resultf
- b := db.Mgo.Update(e.TaskInfo.TestColl, `{"_id":"`+_id+`"}`, map[string]interface{}{"$set": tmp}, true, false)
- if !b {
- log.Debug(e.TaskInfo.TestColl, _id)
- }
- }
- }, func(err interface{}) {
- log.Debug("AnalysisSaveResult err", err)
- })
- }
- //保存其他
- //kv、表格、块上的标签凡是新的标签都入库
- //val type times firstid createtime 判定field
- func otherNeedSave(j *ju.Job, result map[string][]*ju.ExtField, e *ExtractTask) {
- now := time.Now().Unix()
- coll := e.TaskInfo.TestColl
- if coll == "" {
- coll = "extract_tag_result"
- } else {
- coll += "_tag"
- }
- datas := []map[string]interface{}{}
- kv := map[string]int{}
- for _, v := range j.Block {
- //
- for _, vv := range []*ju.JobKv{v.ColonKV, v.TableKV, v.SpaceKV} {
- if vv == nil || vv.KvTags == nil {
- continue
- }
- for kkk, vvv := range vv.KvTags {
- for _, vvvv := range vvv {
- if vvvv.IsInvalid {
- kv[kkk] = kv[kkk] + 1
- break
- }
- }
- }
- }
- for _, vv := range v.NotClassifyTitles {
- datas = append(datas, map[string]interface{}{
- "val": vv,
- "times": 0,
- "type": "block",
- "firstid": j.SourceMid,
- "createtime": now,
- })
- if len(datas) == saveLimit {
- db.Mgo.SaveBulk(coll, datas...)
- datas = []map[string]interface{}{}
- }
- }
- }
- for k, v := range kv {
- datas = append(datas, map[string]interface{}{
- "val": k,
- "times": v,
- "type": "kv",
- "firstid": j.SourceMid,
- "createtime": now,
- })
- if len(datas) == saveLimit {
- db.Mgo.SaveBulk(coll, datas...)
- datas = []map[string]interface{}{}
- }
- }
- if len(datas) > 0 {
- db.Mgo.SaveBulk(coll, datas...)
- }
- }
- func rangeBlockToJson(j *ju.Block, tmpblock ju.TmpBlock) (b *ju.TmpBlock) {
- if j == nil {
- return nil
- }
- if len(j.Block) > 0 {
- for i, v := range j.Block {
- rangetmp := new(ju.TmpBlock)
- vb, _ := json.Marshal(v)
- json.Unmarshal(vb, &rangetmp)
- tmpblock.Block[i] = rangeBlockToJson(v, *rangetmp)
- }
- }
- if j.ColonKV != nil {
- cb, _ := json.Marshal(j.ColonKV)
- tmpblock.ColonKV = string(cb)
- }
- if j.SpaceKV != nil {
- sb, _ := json.Marshal(j.SpaceKV)
- tmpblock.SpaceKV = string(sb)
- }
- if j.TableKV != nil {
- tb, _ := json.Marshal(j.TableKV)
- tmpblock.TableKV = string(tb)
- }
- return &tmpblock
- }
- //去重冗余字段
- func delFiled(k string) bool {
- return k == "summary" || k == "detail" || k == "contenthtml" || k == "site" || k == "spidercode" || k == "projectinfo" || k == "jsondata"
- }
- func funcAnalysis(j *ju.Job, e *ExtractTask) (*map[string]interface{}, map[string][]*ju.ExtField, string) {
- defer qu.Catch()
- doc := j.Data
- result := j.Result
- _id := qu.BsonIdToSId((*doc)["_id"])
- result = ScoreFields(j, e.Tag) //正负面词打分
- //结果排序
- for _, val := range result {
- ju.Sort(val)
- }
- j.Result = JsonDataMergeProcessing(j, e)
- return doc, result, _id
- }
- //辅助信息,如果没有排序先排序
- func auxInfo(j *ju.Job) map[string][]map[string]interface{} {
- fieldalls := map[string][]map[string]interface{}{}
- for field, val := range j.Result {
- //ju.Sort(val)
- sfields := []map[string]interface{}{}
- for _, v := range val {
- standardized := false
- if field == "buyer" || field == "winner" || field == "agency" {
- i := redis.GetInt(field, field+"_"+qu.ObjToString(v.Value))
- if i > 0 {
- standardized = true
- }
- }
- sfield := map[string]interface{}{
- "val": v.Value,
- "type": v.Type,
- "score": v.Score,
- "blocktag": v.BlockTag,
- "sourceval": v.SourceValue,
- "standardized": standardized,
- }
- sfields = append(sfields, sfield)
- }
- fieldalls[field] = sfields
- }
- return fieldalls
- }
- func (e *ExtractTask) QualityAudit(resulttmp map[string]interface{}) {
- defer qu.Catch()
- //获取审核字段
- for _, field := range e.AuditFields {
- //1.分包
- if resulttmp["package"] != nil {
- packagedata := resulttmp["package"].(map[string]map[string]interface{})
- for _, val := range packagedata {
- if val[field] != nil {
- fv := qu.ObjToString(val[field])
- if fv != "" {
- if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
- e.RedisMatch(field, fv, val) //redis匹配
- } else { //除了buyer和winner,其他字段走规则匹配
- e.RuleMatch(field, fv, val)
- }
- }
- }
- }
- }
- //2.外围
- if resulttmp[field] != nil {
- fv := qu.ObjToString(resulttmp[field])
- if fv != "" {
- if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
- e.RedisMatch(field, fv, resulttmp) //redis匹配
- } else { //除了buyer和winner,其他字段走规则匹配
- e.RuleMatch(field, fv, resulttmp)
- }
- }
- }
- }
- }
- //Redis匹配
- func (e *ExtractTask) RedisMatch(field, fv string, val map[string]interface{}) {
- defer qu.Catch()
- i := redis.GetInt(field, field+"_"+fv) //查找redis
- if i == 0 { //reids未找到,执行规则匹配
- val[field+"_isredis"] = false
- e.RuleMatch(field, fv, val) //规则匹配
- } else { //redis找到,打标识存库
- val[field+"_isredis"] = true
- }
- }
- //规则匹配
- func (e *ExtractTask) RuleMatch(field, fieldval string, tmpMap map[string]interface{}) {
- defer qu.Catch()
- if fieldval != "" {
- SMap := e.StartMatch(field, fieldval)
- //SMap.AddKey(field+"_isaudit", false)
- for _, k := range SMap.Keys {
- tmpMap[k] = SMap.Map[k]
- }
- tmpMap[field+"_isaudit"] = false //添加字段未审核信息
- }
- }
- //开始规则匹配
- func (e *ExtractTask) StartMatch(field, text string) *pretreated.SortMap {
- defer qu.Catch()
- SMap := pretreated.NewSortMap()
- lock.Lock()
- f := e.RecogFieldMap[field]
- lock.Unlock()
- if len(f) > 0 {
- fid := qu.BsonIdToSId(f["_id"])
- recogFieldPreRule := qu.ObjToString(f["s_recogfield_prerule"])
- textAfterRecogFieldPrerule := ju.PreFilter(text, recogFieldPreRule) //识别字段的前置过滤
- if textAfterRecogFieldPrerule != "" {
- lock.Lock()
- classMap := e.FidClassMap[fid]
- lock.Unlock()
- L:
- for _, c := range classMap { //class
- classid := qu.BsonIdToSId(c["_id"])
- classPrerule := qu.ObjToString(c["s_class_prerule"])
- savefield := qu.ObjToString(c["s_savefield"]) //保存字段
- textAfterClassPrerule := ju.PreFilter(textAfterRecogFieldPrerule, classPrerule) //class的前置过滤
- if textAfterClassPrerule != "" {
- lock.Lock()
- ruleMap := e.CidRuleMap[classid]
- lock.Unlock()
- for _, r := range ruleMap { //rule
- rulePrerule := qu.ObjToString(r["s_rule_prerule"])
- s_name := qu.ObjToString(r["s_name"])
- rule := r["rule"].([]interface{})
- textAfterRulePrerule := ju.PreFilter(textAfterClassPrerule, rulePrerule) //class的前置过滤
- if textAfterRulePrerule != "" {
- b, _ := ju.RecogAnalyRules(textAfterRulePrerule, rule)
- if b { //匹配到一个分类下某个规则时,不再继续匹配
- if savefield != "" { //保存字段不为空,存储代码信息
- SMap.AddKey(field+"_"+savefield, s_name)
- }
- break L
- }
- }
- }
- }
- }
- }
- }
- return SMap
- }
- //中标候选人经过清理之后,重新取出赋值
- func resetWinnerorder(j *ju.Job) {
- if len(j.Winnerorder) == 0 {
- return
- }
- maxlen := len(j.Winnerorder) - 1
- //中标单位
- i := 0
- winners := []*ju.ExtField{}
- for _, v := range j.Result["winner"] {
- if v.Code == "winnerorder" {
- if maxlen < i {
- continue
- }
- j.Winnerorder[i]["entname"] = v.Value
- i++
- } else {
- winners = append(winners, v)
- }
- }
- j.Result["winner"] = winners
- //中标金额
- i = 0
- bidamounts := []*ju.ExtField{}
- for _, v := range j.Result["bidamount"] {
- if v.Code == "winnerorder" {
- if maxlen < i {
- continue
- }
- j.Winnerorder[i]["price"] = v.Value
- i++
- } else {
- bidamounts = append(bidamounts, v)
- }
- }
- j.Result["bidamount"] = bidamounts
- }
|