extract.go 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  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. "sort"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "unicode/utf8"
  19. "github.com/PuerkitoBio/goquery"
  20. log "github.com/donnie4w/go-logger/logger"
  21. "gopkg.in/mgo.v2/bson"
  22. )
  23. var (
  24. lock, lockrule, lockclear, locktag, blocktag sync.RWMutex
  25. cut = ju.NewCut() //获取正文并清理
  26. ExtLogs map[*TaskInfo][]map[string]interface{} //抽取日志
  27. TaskList map[string]*ExtractTask //任务列表
  28. ClearTaskList map[string]*ClearTask //清理任务列表
  29. saveLimit = 100 //抽取日志批量保存
  30. PageSize = 5000 //查询分页
  31. 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,"infoformat":1,"attach_text":1}`
  32. Fields2 = `{"budget":1,"bidamount":1,"title":1,"projectname":1,"winner":1}`
  33. )
  34. //启动测试抽取
  35. func StartExtractTestTask(taskId, startId, num, resultcoll, trackcoll string) bool {
  36. defer qu.Catch()
  37. ext := &ExtractTask{}
  38. ext.Id = taskId
  39. ext.IsRun = true
  40. ext.InitTestTaskInfo(resultcoll, trackcoll)
  41. ext.TaskInfo.FDB = db.MgoFactory(1, 3, 120, ext.TaskInfo.FromDbAddr, ext.TaskInfo.FromDB)
  42. ext.InitSite()
  43. ext.InitRulePres()
  44. ext.InitRuleBacks(false)
  45. ext.InitRuleBacks(true)
  46. ext.InitRuleCore(false)
  47. ext.InitRuleCore(true)
  48. ext.InitPkgCore()
  49. ext.InitBlockRule()
  50. ext.InfoTypeList()
  51. ext.InitTag(false)
  52. ext.InitTag(true)
  53. ext.InitClearFn(false)
  54. ext.InitClearFn(true)
  55. if ext.IsExtractCity { //版本上控制是否开始城市抽取
  56. //初始化城市DFA信息
  57. ext.InitCityInfo()
  58. //ext.InitCityDFA()
  59. ext.InitAreaCode()
  60. ext.InitPostCode()
  61. }
  62. //质量审核
  63. ext.InitAuditFields()
  64. ext.InitAuditRule()
  65. ext.InitAuditClass()
  66. ext.InitAuditRecogField()
  67. //品牌抽取是否开启
  68. ju.IsBrandGoods, _ = ju.Config["brandgoods"].(bool)
  69. //价格个数抽取是否开启
  70. ju.IsPriceNumber, _ = ju.Config["pricenumber"].(bool)
  71. //附件抽取是否开启
  72. ext.InitFile()
  73. return RunExtractTestTask(ext, startId, num)
  74. }
  75. func IdTrans(startId string) bson.ObjectId {
  76. defer qu.Catch()
  77. return bson.ObjectIdHex(startId)
  78. }
  79. //开始测试任务抽取
  80. func RunExtractTestTask(ext *ExtractTask, startId, num string) bool {
  81. n, _ := strconv.Atoi(num)
  82. id := IdTrans(startId)
  83. if id.Valid() {
  84. query := bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(startId)}}
  85. list, _ := ext.TaskInfo.FDB.Find(ext.TaskInfo.FromColl, query, nil, Fields, false, 0, n)
  86. for _, v := range *list {
  87. if qu.ObjToString(v["sensitive"]) != "" { //去除含敏感词数据
  88. continue
  89. }
  90. var j, jf *ju.Job
  91. var isSite bool
  92. if ext.IsFileField && (v["projectinfo"] != nil || v["attach_text"] != nil) {
  93. v["isextFile"] = true
  94. j, jf, isSite = ext.PreInfo(v)
  95. } else {
  96. j, _, isSite = ext.PreInfo(v)
  97. }
  98. go ext.ExtractProcess(j, jf, isSite)
  99. ext.TaskInfo.ProcessPool <- true
  100. }
  101. return true
  102. } else {
  103. return false
  104. }
  105. }
  106. //启动抽取
  107. func StartExtractTaskId(taskId string) bool {
  108. defer qu.Catch()
  109. isgo := false
  110. ext := TaskList[taskId]
  111. if ext == nil {
  112. ext = &ExtractTask{}
  113. ext.Id = taskId
  114. ext.InitTaskInfo()
  115. isgo = true
  116. } else {
  117. ext.Id = taskId
  118. ext.InitTaskInfo()
  119. }
  120. ext.TaskInfo.FDB = db.MgoFactory(3, 5, 600, ext.TaskInfo.FromDbAddr, ext.TaskInfo.FromDB)
  121. ext.TaskInfo.TDB = db.MgoFactory(3, 5, 600, ext.TaskInfo.ToDbAddr, ext.TaskInfo.ToDB)
  122. ext.InitSite()
  123. ext.InitRulePres()
  124. ext.InitRuleBacks(false)
  125. ext.InitRuleBacks(true)
  126. ext.InitRuleCore(false)
  127. ext.InitRuleCore(true)
  128. ext.InitPkgCore()
  129. ext.InitBlockRule()
  130. ext.InfoTypeList()
  131. ext.InitTag(false)
  132. ext.InitTag(true)
  133. ext.InitClearFn(false)
  134. ext.InitClearFn(true)
  135. if ext.IsExtractCity { //版本上控制是否开始城市抽取
  136. //初始化城市DFA信息
  137. //ext.InitCityDFA()
  138. ext.InitCityInfo()
  139. ext.InitAreaCode()
  140. ext.InitPostCode()
  141. }
  142. //质量审核
  143. ext.InitAuditFields()
  144. ext.InitAuditRule()
  145. ext.InitAuditClass()
  146. ext.InitAuditRecogField()
  147. //品牌抽取是否开启
  148. ju.IsBrandGoods, _ = ju.Config["brandgoods"].(bool)
  149. //价格个数抽取是否开启
  150. ju.IsPriceNumber, _ = ju.Config["pricenumber"].(bool)
  151. //附件抽取是否开启
  152. ext.InitFile()
  153. ext.IsRun = true
  154. go ext.ResultSave(true)
  155. go ext.BidSave(true)
  156. if isgo {
  157. go RunExtractTask(taskId)
  158. }
  159. TaskList[taskId] = ext
  160. return true
  161. }
  162. //停止抽取
  163. func StopExtractTaskId(taskId string) bool {
  164. defer qu.Catch()
  165. ext := TaskList[taskId]
  166. if ext != nil {
  167. ext.IsRun = false
  168. TaskList[taskId] = ext
  169. }
  170. //更新task.s_extlastid
  171. db.Mgo.UpdateById("task", taskId, `{"$set":{"s_extlastid":"`+ext.TaskInfo.LastExtId+`"}}`)
  172. return true
  173. }
  174. //开始抽取
  175. func RunExtractTask(taskId string) {
  176. defer qu.Catch()
  177. ext := TaskList[taskId]
  178. query := bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(ext.TaskInfo.LastExtId)}}
  179. count := ext.TaskInfo.FDB.Count(ext.TaskInfo.FromColl, query)
  180. pageNum := (count + PageSize - 1) / PageSize
  181. limit := PageSize
  182. if count < PageSize {
  183. limit = count
  184. }
  185. fmt.Printf("count=%d,pageNum=%d,query=%v", count, pageNum, query)
  186. for i := 0; i < pageNum; i++ {
  187. query = bson.M{"_id": bson.M{"$gte": bson.ObjectIdHex(ext.TaskInfo.LastExtId)}}
  188. list, _ := ext.TaskInfo.FDB.Find(ext.TaskInfo.FromColl, query, nil, Fields, false, 0, limit)
  189. fmt.Printf("page=%d,query=%v", i+1, query, len(*list))
  190. for _, v := range *list {
  191. if qu.ObjToString(v["sensitive"]) != "" { //去除含敏感词数据
  192. continue
  193. }
  194. //根据标题判断是否抽取
  195. b := IsExtract("title", qu.ObjToString(v["title"]), "")
  196. if !b {
  197. continue
  198. }
  199. _id := qu.BsonIdToSId(v["_id"])
  200. //log.Debug(_id)
  201. if !ext.IsRun {
  202. break
  203. }
  204. var j, jf *ju.Job
  205. var isSite bool
  206. if ext.IsFileField && (v["projectinfo"] != nil || v["attach_text"] != nil) {
  207. v["isextFile"] = true
  208. j, jf, isSite = ext.PreInfo(v)
  209. } else {
  210. j, _, isSite = ext.PreInfo(v)
  211. }
  212. go ext.ExtractProcess(j, jf, isSite)
  213. ext.TaskInfo.LastExtId = _id
  214. ext.TaskInfo.ProcessPool <- true
  215. }
  216. db.Mgo.UpdateById("task", ext.Id, `{"$set":{"s_extlastid":"`+ext.TaskInfo.LastExtId+`"}}`)
  217. if !ext.IsRun {
  218. break
  219. }
  220. }
  221. //更新task.s_extlastid
  222. time.AfterFunc(1*time.Minute, func() { RunExtractTask(taskId) })
  223. }
  224. //信息预处理-不和版本关联,取最新版本的配置项
  225. func PreInfo(doc map[string]interface{}) (j, jf *ju.Job, isSite bool) {
  226. return (&ExtractTask{}).PreInfo(doc)
  227. }
  228. //信息预处理-和版本关联
  229. func (e *ExtractTask) PreInfo(doc map[string]interface{}) (j, jf *ju.Job, isSite bool) {
  230. defer qu.Catch()
  231. //判断是否有附件这个字段
  232. var isextFile bool
  233. if doc["isextFile"] != nil {
  234. isextFile = doc["isextFile"].(bool)
  235. }
  236. detail := ""
  237. d1, _ := doc["detail"].(string)
  238. d2, _ := doc["contenthtml"].(string)
  239. if len(d1) >= len(d2) || d2 == "" {
  240. detail = d1
  241. } else {
  242. detail = d2
  243. }
  244. detail = regexp.MustCompile(`<!--[\w\W]*?-->`).ReplaceAllString(detail, "")
  245. d3, _ := doc["summary"].(string)
  246. //全文的需要修复表格
  247. detail = pretreated.RepairCon(detail)
  248. detail = ju.CutLableStr(d3 + "\n" + detail)
  249. detail = cut.ClearHtml(d3 + "\n" + detail)
  250. doc["detail"] = detail
  251. if isextFile {
  252. file2text(&doc) //附件文本堆一起(后期可以考虑,分开处理),方法里修改了doc["detailfile"]结果
  253. }
  254. if utf8.RuneCountInString(detail) < 2000 {
  255. if doc["detailfile"] == nil || doc["detailfile"] == "" {
  256. file2text(&doc) //附件文本堆一起(后期可以考虑,分开处理),方法里修改了doc["detailfile"]结果
  257. }
  258. detail += qu.ObjToString(doc["detailfile"])
  259. doc["detail"] = detail
  260. } else {
  261. //正文小于200个字,有附件把附件内容加到正文
  262. tmpDeatil := detail
  263. tmpdocument, err := goquery.NewDocumentFromReader(strings.NewReader(tmpDeatil))
  264. if err == nil {
  265. conlen := utf8.RuneCountInString(strings.Trim(tmpdocument.Text(), " "))
  266. if conlen < 2000 {
  267. if isextFile {
  268. detail += qu.ObjToString(doc["detailfile"])
  269. doc["detail"] = detail
  270. }
  271. } else if conlen > qu.IntAllDef(ju.Config["filelength"], 100000) {
  272. //防止文本过长,造成抽取阻塞
  273. log.Debug("文本太长", doc["_id"], conlen)
  274. doc["detail"] = d3
  275. }
  276. }
  277. }
  278. toptype := qu.ObjToString(doc["toptype"])
  279. subtype := qu.ObjToString(doc["subtype"])
  280. if qu.ObjToString(doc["type"]) == "bid" {
  281. toptype = "结果"
  282. }
  283. if toptype == "" {
  284. toptype = "all"
  285. }
  286. if subtype == "" {
  287. subtype = "all"
  288. }
  289. if toptype == "其它" || subtype == "其它" || subtype == "其他" || subtype == "结果变更" {
  290. toptype = "all"
  291. subtype = "all"
  292. }
  293. toMap := qu.ObjToMap(doc["jsondata"])
  294. //log.Debug("toMap", toMap)
  295. if (*toMap) != nil {
  296. if (*toMap)["extweight"] == nil {
  297. (*toMap)["extweight"] = ju.Config["jsondata_extweight"]
  298. }
  299. }
  300. j = &ju.Job{
  301. SourceMid: qu.BsonIdToSId(doc["_id"]),
  302. Category: toptype,
  303. CategorySecond: subtype,
  304. Content: qu.ObjToString(doc["detail"]),
  305. SpiderCode: qu.ObjToString(doc["spidercode"]),
  306. Site: qu.ObjToString(doc["site"]),
  307. //Domain: qu.ObjToString(doc["domain"]),
  308. //Href: qu.ObjToString(doc["href"]),
  309. Title: qu.ObjToString(doc["title"]),
  310. Data: &doc,
  311. City: qu.ObjToString(doc["city"]),
  312. Province: qu.ObjToString(doc["area"]),
  313. Jsondata: toMap,
  314. Result: map[string][]*ju.ExtField{},
  315. BuyerAddr: qu.ObjToString(doc["buyeraddr"]),
  316. RuleBlock: e.RuleBlock,
  317. }
  318. if (j.Jsondata != nil || (*j.Jsondata) != nil) && (*j.Jsondata)["jsoncontent"] != nil {
  319. delete((*j.Jsondata), "jsoncontent")
  320. }
  321. if isextFile {
  322. jf = &ju.Job{
  323. SourceMid: qu.BsonIdToSId(doc["_id"]),
  324. Category: toptype,
  325. CategorySecond: subtype,
  326. Content: qu.ObjToString(doc["detailfile"]),
  327. SpiderCode: qu.ObjToString(doc["spidercode"]),
  328. Site: qu.ObjToString(doc["site"]),
  329. Title: qu.ObjToString(doc["title"]),
  330. Data: &doc,
  331. City: qu.ObjToString(doc["city"]),
  332. Province: qu.ObjToString(doc["area"]),
  333. Jsondata: toMap,
  334. Result: map[string][]*ju.ExtField{},
  335. BuyerAddr: qu.ObjToString(doc["buyeraddr"]),
  336. RuleBlock: e.RuleBlock,
  337. IsFile: isextFile,
  338. }
  339. if (jf.Jsondata != nil || (*jf.Jsondata) != nil) && (*jf.Jsondata)["jsoncontent"] != nil {
  340. delete((*jf.Jsondata), "jsoncontent")
  341. }
  342. }
  343. codeSite := j.SpiderCode
  344. //是否启用站点
  345. if value, ok := e.SiteMerge.Load(codeSite); ok {
  346. isSite = value.(bool)
  347. }
  348. if isSite {
  349. //是否配置站点
  350. exp, isSite := e.Luacodes.Load(codeSite)
  351. if isSite {
  352. if exp.(map[string]interface{})["e.SiteClearFn"] != nil {
  353. e.SiteClearFn = exp.(map[string]interface{})["e.SiteClearFn"].(map[string][]string)
  354. }
  355. if exp.(map[string]interface{})["e.SiteTag"] != nil {
  356. e.SiteTag = exp.(map[string]interface{})["e.SiteTag"].(map[string][]*Tag)
  357. }
  358. if exp.(map[string]interface{})["e.SiteRuleCores"] != nil {
  359. e.SiteRuleCores = exp.(map[string]interface{})["e.SiteRuleCores"].(map[string]map[string][]*RuleCore)
  360. }
  361. if exp.(map[string]interface{})["e.SiteRuleBacks"] != nil {
  362. e.SiteRuleBacks = exp.(map[string]interface{})["e.SiteRuleBacks"].([]*RegLuaInfo)
  363. }
  364. }
  365. }
  366. qu.Try(func() {
  367. pretreated.AnalyStart(j, isSite, codeSite) //job.Block分块
  368. if isextFile {
  369. pretreated.AnalyStart(jf, isSite, codeSite)
  370. }
  371. }, func(err interface{}) {
  372. log.Debug("pretreated.AnalyStart", err, j.SourceMid)
  373. })
  374. return j, jf, isSite
  375. }
  376. //遍历附件字段内容,拼接在一起;附件文本堆一起(后期可以考虑,分开处理),方法里修改了doc["detailfile"]结果
  377. func file2text(doc *map[string]interface{}) {
  378. tmpstr := ""
  379. if attach_text, ok := (*doc)["attach_text"].(map[string]interface{}); ok {
  380. for _, attachs := range attach_text {
  381. if fileinfos, ok := attachs.(map[string]interface{}); ok {
  382. for _, fileinfo := range fileinfos {
  383. if ff, ok := fileinfo.(map[string]interface{}); ok {
  384. attach_url := qu.ObjToString(ff["attach_url"])
  385. bs := ju.OssGetObject(attach_url)
  386. if utf8.RuneCountInString(tmpstr+bs) < qu.IntAllDef(ju.Config["filelength"], 100000) {
  387. tmpstr += bs + "\n"
  388. } else {
  389. break
  390. }
  391. }
  392. }
  393. }
  394. }
  395. }
  396. (*doc)["detailfile"] = tmpstr
  397. }
  398. //抽取
  399. func (e *ExtractTask) ExtractProcess(j, jf *ju.Job, isSite bool) {
  400. e.ExtractDetail(j, isSite, j.SpiderCode)
  401. if jf != nil && jf.IsFile {
  402. e.ExtractFile(jf, isSite, j.SpiderCode)
  403. }
  404. if isSite {
  405. ismerge, ok := e.SiteMerge.Load(j.SpiderCode)
  406. if ok && ismerge.(bool) {
  407. tmpj := &ju.Job{
  408. SourceMid: j.SourceMid,
  409. Category: j.Category,
  410. CategorySecond: j.CategorySecond,
  411. Content: j.Content,
  412. SpiderCode: j.SpiderCode,
  413. //Domain: qu.ObjToString(doc["domain"]),
  414. //Href: qu.ObjToString(doc["href"]),
  415. Title: j.Title,
  416. Data: j.Data,
  417. City: j.City,
  418. Province: j.Province,
  419. Jsondata: j.Jsondata,
  420. Result: map[string][]*ju.ExtField{},
  421. BuyerAddr: j.BuyerAddr,
  422. RuleBlock: e.RuleBlock,
  423. }
  424. qu.Try(func() {
  425. pretreated.AnalyStart(tmpj, false, "") //job.Block分块
  426. }, func(err interface{}) {
  427. log.Debug("pretreated.AnalyStart.ExtractProcess", err, j.SourceMid)
  428. })
  429. e.ExtractDetail(tmpj, false, "")
  430. //if jf != nil && jf.IsFile {
  431. // e.ExtractFile(jf, false, "")
  432. //}
  433. //合并数据
  434. j.Block = append(j.Block, tmpj.Block...)
  435. j.Winnerorder = append(j.Winnerorder, tmpj.Winnerorder...)
  436. for tmpk, _ := range j.Result {
  437. if len(tmpj.Result[tmpk]) > 0 {
  438. j.Result[tmpk] = append(j.Result[tmpk], tmpj.Result[tmpk]...)
  439. }
  440. }
  441. for tmpk, _ := range tmpj.Result {
  442. if len(j.Result[tmpk]) == 0 {
  443. j.Result[tmpk] = append(j.Result[tmpk], tmpj.Result[tmpk]...)
  444. }
  445. }
  446. }
  447. }
  448. //分析抽取结果并保存
  449. AnalysisSaveResult(j, jf, e)
  450. <-e.TaskInfo.ProcessPool
  451. }
  452. func (e *ExtractTask) ExtractDetail(j *ju.Job, isSite bool, codeSite string) {
  453. qu.Try(func() {
  454. doc := *j.Data
  455. //全局前置规则,结果覆盖doc属性
  456. //for _, v := range e.RulePres {
  457. // doc = ExtRegPre(doc, j, v, e.TaskInfo)
  458. //}
  459. tmprules := map[string][]*RuleCore{}
  460. lockrule.Lock()
  461. if j.Category == "all" || j.CategorySecond == "all" {
  462. if isSite {
  463. for k, vc1 := range e.SiteRuleCores["all_all"] {
  464. tmprules[k] = vc1
  465. }
  466. } else {
  467. for k, vc1 := range e.RuleCores["all_all"] {
  468. tmprules[k] = vc1
  469. }
  470. }
  471. } else {
  472. if isSite {
  473. for k, vc1 := range e.SiteRuleCores[j.Category+"_"+j.CategorySecond] {
  474. tmprules[k] = vc1
  475. }
  476. } else {
  477. for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
  478. tmprules[k] = vc1
  479. }
  480. }
  481. }
  482. if len(tmprules) < 1 { //分类未覆盖部分
  483. if isSite {
  484. for k, vc1 := range e.RuleCores["all_all"] {
  485. tmprules[k] = vc1
  486. }
  487. } else {
  488. for k, vc1 := range e.SiteRuleCores["all_all"] {
  489. tmprules[k] = vc1
  490. }
  491. }
  492. }
  493. lockrule.Unlock()
  494. //抽取规则
  495. for _, vc1 := range tmprules {
  496. for _, vc := range vc1 {
  497. tmp := ju.DeepCopy(doc).(map[string]interface{})
  498. //是否进入逻辑
  499. if !ju.Logic(vc.LuaLogic, tmp) {
  500. continue
  501. }
  502. ////抽取-前置规则
  503. //for _, v := range vc.RulePres {
  504. // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
  505. //}
  506. // log.Debug("抽取-前置规则", tmp)
  507. //抽取-规则
  508. ExtRuleCore(tmp, e, vc, j, isSite)
  509. // log.Debug("抽取-规则", tmp)
  510. //抽取-后置规则
  511. for _, v := range vc.RuleBacks {
  512. ExtRegBack(j, v, e.TaskInfo, vc)
  513. }
  514. //kv规则
  515. for _, v := range vc.KVRuleCores {
  516. ExtRuleKV(j, v, e.TaskInfo)
  517. }
  518. // log.Debug("抽取-后置规则", tmp)
  519. //项目名称未能抽取到,标题来凑
  520. if vc.Field == "projectname" {
  521. if vc.ExtFrom == "title" {
  522. isextitle := true
  523. for _, v := range j.Result[vc.Field] {
  524. if len([]rune(qu.ObjToString(v.Value))) > 5 {
  525. isextitle = false
  526. break
  527. }
  528. }
  529. if isextitle { //标题加入选举
  530. 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}
  531. if isSite {
  532. field.Score = 1
  533. }
  534. j.Result[vc.Field] = append(j.Result[vc.Field], field)
  535. }
  536. }
  537. for i := 0; i < 3; i++ {
  538. for _, v := range vc.RuleBacks {
  539. ExtRegBack(j, v, e.TaskInfo, vc)
  540. }
  541. }
  542. }
  543. }
  544. }
  545. //全局后置规则
  546. if isSite {
  547. for _, v := range e.SiteRuleBacks {
  548. ExtRegBack(j, v, e.TaskInfo, nil)
  549. }
  550. } else {
  551. for _, v := range e.RuleBacks {
  552. ExtRegBack(j, v, e.TaskInfo, nil)
  553. }
  554. }
  555. //函数清理
  556. for key, val := range j.Result {
  557. for i, v := range val {
  558. // if v.ExtFrom == "title"&& v.Field == "buyer"{
  559. // qu.Debug("title---",v.Value)
  560. // }else if v.Field == "buyer"{
  561. // qu.Debug("text---",v.Value)
  562. // }
  563. lockclear.Lock()
  564. var cfn = []string{}
  565. if isSite {
  566. cfn = e.SiteClearFn[key]
  567. } else {
  568. cfn = e.ClearFn[key]
  569. }
  570. lockclear.Unlock()
  571. if len(cfn) == 0 {
  572. continue
  573. }
  574. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content})
  575. if key == "budget" || key == "bidamount" {
  576. if istrue, ok := data[len(data)-1].(bool); istrue && ok {
  577. j.Result[key][i].IsTrue = true
  578. } else {
  579. j.Result[key][i].Value = data[0]
  580. continue
  581. }
  582. }
  583. before, _ := v.Value.(string)
  584. v.Value = data[0]
  585. BeforeAddClearFnLog(v.Type, "函数清理", j.SourceMid, before, v.MatchType, v, e)
  586. //添加行数清理的日志
  587. //清理特殊符号
  588. lockclear.Lock()
  589. if clear.AsyField[key] != nil || clear.SymField[key] != nil || clear.MesField[key] != nil {
  590. text := qu.ObjToString(v.Value)
  591. before = text
  592. v.Value = clear.OtherClean(key, text)
  593. BeforeAddClearFnLog(v.Type, "特殊符号清理", j.SourceMid, before, v.MatchType, v, e)
  594. }
  595. //AddClearFnLog("clearfn", j.SourceMid, v.Value, extinfo, v.Code, "函数清理", key, e.TaskInfo)
  596. lockclear.Unlock()
  597. }
  598. }
  599. PackageDetail(j, e, isSite, codeSite) //处理分包信息
  600. // bs, _ := json.Marshal(j.Result)
  601. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  602. }, func(err interface{}) {
  603. log.Debug("ExtractProcess err", err)
  604. })
  605. }
  606. func (e *ExtractTask) ExtractFile(j *ju.Job, isSite bool, codeSite string) {
  607. qu.Try(func() {
  608. doc := *j.Data
  609. //全局前置规则,结果覆盖doc属性
  610. // for _, v := range e.RulePres {
  611. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  612. // doc = ExtRegPre(doc, j, v, e.TaskInfo)
  613. // }
  614. // }
  615. //抽取规则
  616. tmprules := map[string][]*RuleCore{}
  617. lockrule.Lock()
  618. if j.Category == "all" || j.CategorySecond == "all" {
  619. for k, vc1 := range e.RuleCores["all_all"] {
  620. tmprules[k] = vc1
  621. }
  622. } else {
  623. for k, vc1 := range e.RuleCores[j.Category+"_"+j.CategorySecond] {
  624. tmprules[k] = vc1
  625. }
  626. }
  627. lockrule.Unlock()
  628. for _, vc1 := range tmprules {
  629. for _, vc := range vc1 {
  630. tmp := ju.DeepCopy(doc).(map[string]interface{})
  631. //是否进入逻辑
  632. if !ju.Logic(vc.LuaLogic, tmp) {
  633. continue
  634. }
  635. //抽取-前置规则
  636. // for _, v := range vc.RulePres {
  637. // if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  638. // tmp = ExtRegPre(tmp, j, v, e.TaskInfo)
  639. // }
  640. // }
  641. // log.Debug("抽取-前置规则", tmp)
  642. //抽取-规则
  643. if value, ok := e.FileFields.Load(vc.Field); ok && qu.IntAllDef(value, 1) > 0 {
  644. ExtRuleCore(tmp, e, vc, j, isSite)
  645. }
  646. // log.Debug("抽取-规则", tmp)
  647. //抽取-后置规则
  648. for _, v := range vc.RuleBacks {
  649. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  650. ExtRegBack(j, v, e.TaskInfo, vc)
  651. }
  652. }
  653. // log.Debug("抽取-后置规则", tmp)
  654. }
  655. }
  656. //全局后置规则
  657. for _, v := range e.RuleBacks {
  658. if value, ok := e.FileFields.Load(v.Field); ok && qu.IntAllDef(value, 1) > 0 {
  659. ExtRegBack(j, v, e.TaskInfo, nil)
  660. }
  661. }
  662. //函数清理
  663. for key, val := range j.Result {
  664. for _, v := range val {
  665. lockclear.Lock()
  666. cfn := e.ClearFn[key]
  667. lockclear.Unlock()
  668. data := clear.DoClearFn(cfn, []interface{}{v.Value, j.Content})
  669. v.Value = data[0]
  670. //清理特殊符号
  671. lockclear.Lock()
  672. if clear.AsyField[key] != nil || clear.SymField[key] != nil ||
  673. clear.MesField[key] != nil {
  674. text := qu.ObjToString(v.Value)
  675. text = clear.OtherClean(key, text)
  676. v.Value = text
  677. }
  678. lockclear.Unlock()
  679. }
  680. }
  681. PackageDetail(j, e, isSite, codeSite) //处理分包信息
  682. // bs, _ := json.Marshal(j.Result)
  683. // log.Debug("抽取结果", j.Title, j.SourceMid, string(bs))
  684. }, func(err interface{}) {
  685. log.Debug("ExtractProcess err", err)
  686. })
  687. }
  688. //前置过滤
  689. func ExtRegPre(doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, t *TaskInfo) map[string]interface{} {
  690. defer qu.Catch()
  691. before := ju.DeepCopy(doc).(map[string]interface{})
  692. extinfo := map[string]interface{}{}
  693. if in.IsLua {
  694. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  695. if j != nil {
  696. lua.Block = j.Block
  697. }
  698. extinfo = lua.RunScript("pre")
  699. for k, v := range extinfo { //结果覆盖原doc
  700. doc[k] = v
  701. }
  702. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  703. } else {
  704. var key string
  705. if !j.IsFile {
  706. key = qu.If(in.Field == "", "detail", in.Field).(string)
  707. } else {
  708. key = qu.If(in.Field == "", "detailfile", in.Field).(string)
  709. }
  710. text := qu.ObjToString(doc[key])
  711. extinfo[key] = in.RegPreBac.Reg.ReplaceAllString(text, "")
  712. doc[key] = extinfo[key] //结果覆盖原doc
  713. AddExtLog("prereplace", j.SourceMid, before, extinfo, in, t) //抽取日志
  714. }
  715. return doc
  716. }
  717. //抽取-规则
  718. func ExtRuleCore(doc map[string]interface{}, e *ExtractTask, vc *RuleCore, j *ju.Job, isSite bool) {
  719. //候选人加入
  720. var kvMap map[string][]map[string]interface{}
  721. extByReg := true
  722. if vc.ExtFrom != "title" {
  723. kvMap, extByReg = getKvByLuaFields(vc, j, e)
  724. }
  725. for _, v := range vc.RuleCores {
  726. if v.IsLua {
  727. ExtRuleCoreByKv(vc.ExtFrom, doc, j, v, &kvMap, e)
  728. } else if extByReg {
  729. ExtRuleCoreByReg(vc.ExtFrom, doc, j, v, e, isSite)
  730. }
  731. }
  732. //如果只有一个分包,预算没有抽取到,把分包中的预算保存到外面
  733. if vc.Field == "budget" && len(kvMap) == 0 {
  734. if len(j.BlockPackage) == 1 {
  735. for _, bp := range j.BlockPackage {
  736. for fieldname, field := range vc.LFields {
  737. if field != vc.Field {
  738. continue
  739. }
  740. tp := ""
  741. for k, v := range []*ju.JobKv{bp.ColonKV, bp.SpaceKV, bp.TableKV} {
  742. if k == 0 {
  743. tp = "colon"
  744. } else if k == 1 {
  745. tp = "space"
  746. } else if k == 2 {
  747. tp = "table"
  748. }
  749. if v == nil || v.KvTags == nil {
  750. continue
  751. }
  752. for _, vv := range v.KvTags[fieldname] {
  753. text := ju.TrimLRSpace(vv.Value, "")
  754. if text != "" {
  755. tmp := &ju.ExtField{
  756. ExtFrom: "package",
  757. Field: vc.Field,
  758. Code: "CL_分包",
  759. Type: tp,
  760. MatchType: "package",
  761. RuleText: bp.Text,
  762. SourceValue: vv.Key,
  763. Value: text,
  764. }
  765. if isSite {
  766. tmp.Score = 1
  767. }
  768. j.Result[vc.Field] = append(j.Result[vc.Field], tmp)
  769. }
  770. }
  771. }
  772. }
  773. break
  774. }
  775. }
  776. } else {
  777. for k, v := range kvMap {
  778. if j.Result[k] == nil {
  779. j.Result[k] = [](*ju.ExtField){}
  780. }
  781. for _, tmp := range v {
  782. field := &ju.ExtField{Weight: qu.IntAll(tmp["weight"]),
  783. ExtFrom: qu.ObjToString(tmp["extfrom"]), Field: k,
  784. Code: qu.ObjToString(tmp["code"]), Type: qu.ObjToString(tmp["type"]),
  785. MatchType: qu.ObjToString(tmp["matchtype"]),
  786. RuleText: qu.ObjToString(tmp["ruletext"]),
  787. SourceValue: tmp["sourcevalue"],
  788. Value: tmp["value"]}
  789. if k == "bidamount" && field.ExtFrom == "第一候选人" {
  790. field.Score = 1
  791. }
  792. if isSite {
  793. field.Score = 1
  794. }
  795. if tmp["blocktag"] != nil {
  796. btag := make(map[string]string)
  797. for k := range tmp["blocktag"].(map[string]bool) {
  798. blocktag.Lock()
  799. if TagConfigDesc[k] != "" {
  800. btag[k] = TagConfigDesc[k]
  801. }
  802. blocktag.Unlock()
  803. }
  804. field.BlockTag = btag
  805. }
  806. j.Result[k] = append(j.Result[k], field)
  807. }
  808. }
  809. }
  810. }
  811. //抽取-规则-kv
  812. func ExtRuleCoreByKv(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, kvMap *map[string][]map[string]interface{}, et *ExtractTask) {
  813. defer qu.Catch()
  814. if extfrom == "title" || !in.IsLua {
  815. return
  816. }
  817. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Doc: doc, Script: in.RuleText}
  818. lua.KvMap = *kvMap
  819. lua.Block = j.Block
  820. extinfo := lua.RunScript("core")
  821. if tmps, ok := extinfo[in.Field].([]map[string]interface{}); ok {
  822. for _, v := range tmps {
  823. v["core"] = in.Code
  824. }
  825. (*kvMap)[in.Field] = append((*kvMap)[in.Field], tmps...)
  826. }
  827. if len(extinfo) > 0 {
  828. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  829. }
  830. }
  831. //抽取-规则-正则
  832. func ExtRuleCoreByReg(extfrom string, doc map[string]interface{}, j *ju.Job, in *RegLuaInfo, et *ExtractTask, isSite bool) {
  833. defer qu.Catch()
  834. //根据field配置项目,是否抽取。例如:废标、流标等跳过,
  835. b := IsExtract(in.Field, j.Title, j.Content)
  836. if !b {
  837. return
  838. }
  839. //全文正则
  840. //text := qu.ObjToString(doc[extfrom])
  841. //if in.Field != "" {
  842. // extinfo := extRegCoreToResult(extfrom, text, j, in)
  843. // if len(extinfo) > 0 {
  844. // AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  845. // }
  846. //}
  847. //块抽取
  848. if in.Field != "" {
  849. if extfrom == "title" {
  850. extinfo := extRegCoreToResult(extfrom, qu.ObjToString(doc[extfrom]), &map[string]string{}, j, in, isSite)
  851. if len(extinfo) > 0 {
  852. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  853. }
  854. } else {
  855. for _, v := range j.Block {
  856. btag := make(map[string]string)
  857. for k := range v.Classify {
  858. blocktag.Lock()
  859. btag[k] = TagConfigDesc[k]
  860. blocktag.Unlock()
  861. }
  862. extinfo := extRegCoreToResult(extfrom, v.Text, &btag, j, in, isSite)
  863. if len(extinfo) > 0 {
  864. AddExtLog("extract", j.SourceMid, nil, extinfo, in, et.TaskInfo) //抽取日志
  865. }
  866. }
  867. }
  868. }
  869. }
  870. //pkg抽取-规则-正则
  871. func ExtRuleCoreByPkgReg(j *ju.Job, in *RegLuaInfo, e *ExtractTask) {
  872. defer qu.Catch()
  873. //根据field配置项目,是否抽取。例如:废标、流标等跳过,
  874. b := IsExtract(in.Field, j.Title, j.Content)
  875. if !b {
  876. return
  877. }
  878. //块抽取
  879. if in.Field != "" {
  880. for k, vbpkg := range j.BlockPackage {
  881. rep := map[string]string{}
  882. if in.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
  883. if in.Field == "budget" && vbpkg.Budget > 0 {
  884. continue
  885. }
  886. if in.Field == "bidamount" && vbpkg.Bidamount > 0 {
  887. continue
  888. }
  889. if in.Field == "winner" && vbpkg.Winner != "" {
  890. continue
  891. }
  892. if in.Field == "bidstatus" && vbpkg.BidStatus != "" {
  893. continue
  894. }
  895. if in.Field == "projectname" && vbpkg.Name != "" {
  896. continue
  897. }
  898. if in.Field == "winner" && vbpkg.Winner != "" {
  899. continue
  900. }
  901. if in.Field == "winnerperson" {
  902. if vbpkg.Winner == "" || len(vbpkg.Winner) < 4 {
  903. continue
  904. }
  905. if !strings.Contains(vbpkg.Text, vbpkg.Winner) {
  906. continue
  907. }
  908. }
  909. if in.Field == "winnertel" {
  910. if vbpkg.WinnerPerson == "" {
  911. continue
  912. }
  913. }
  914. //处理正负数修正
  915. ptmp := strings.Split(in.RuleText, "#")
  916. sign := 0
  917. if len(ptmp) == 2 {
  918. if ptmp[1] == "正" {
  919. sign = 1
  920. } else if ptmp[1] == "负" {
  921. sign = -1
  922. }
  923. }
  924. tmp := strings.Split(ptmp[0], "__")
  925. if len(tmp) == 2 {
  926. epos := strings.Split(tmp[1], ",")
  927. posm := map[string]int{}
  928. for _, v := range epos {
  929. ks := strings.Split(v, ":")
  930. if len(ks) == 2 { //(.*)招标公告(.*)__2:projectname,4:area
  931. posm[ks[1]] = qu.IntAll(ks[0])
  932. } else {
  933. posm[in.Field] = qu.IntAll(ks[0])
  934. }
  935. }
  936. var pattern string
  937. if strings.Contains(tmp[0], "\\u") {
  938. tmp[0] = strings.Replace(tmp[0], "\\", "\\\\", -1)
  939. tmp[0] = strings.Replace(tmp[0], "\\\\u", "\\u", -1)
  940. pattern, _ = strconv.Unquote(`"` + tmp[0] + `"`)
  941. } else {
  942. pattern = tmp[0]
  943. }
  944. //log.Debug("pattern", pattern)
  945. //fmt.Println(text)
  946. reg := regexp.MustCompile(pattern)
  947. apos := reg.FindAllStringSubmatchIndex(vbpkg.Text, -1)
  948. for i, _ := range apos {
  949. pos := apos[i]
  950. for k, p := range posm {
  951. if len(pos) > p {
  952. if pos[p] == -1 || pos[p+1] == -1 {
  953. continue
  954. }
  955. val := vbpkg.Text[pos[p]:pos[p+1]]
  956. if string(val) == "" {
  957. continue
  958. }
  959. if sign == -1 {
  960. rep[k+"_"+fmt.Sprint(i)] = "-" + val
  961. } else {
  962. rep[k+"_"+fmt.Sprint(i)] = val
  963. }
  964. }
  965. }
  966. }
  967. //fmt.Println(text)
  968. for i := 0; i < len(apos); i++ {
  969. if strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]) != "" {
  970. if in.Field == "budget" && vbpkg.Budget <= 0 {
  971. lock.Lock()
  972. cfn := e.ClearFn[in.Field]
  973. lock.Unlock()
  974. data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content})
  975. if data[len(data)-1].(bool) {
  976. j.BlockPackage[k].Budget = qu.Float64All(data[0])
  977. j.BlockPackage[k].IsTrueBudget = true
  978. }
  979. break
  980. } else if in.Field == "bidamount" && vbpkg.Bidamount <= 0 {
  981. lock.Lock()
  982. cfn := e.ClearFn[in.Field]
  983. lock.Unlock()
  984. data := clear.DoClearFn(cfn, []interface{}{strings.TrimSpace(rep[in.Field+"_"+fmt.Sprint(i)]), j.Content})
  985. if data[len(data)-1].(bool) {
  986. j.BlockPackage[k].Bidamount = qu.Float64All(data[0])
  987. j.BlockPackage[k].IsTrueBidamount = true
  988. }
  989. break
  990. } else if in.Field == "winner" {
  991. if j.BlockPackage[k].Winner == "" {
  992. j.BlockPackage[k].Winner = rep[in.Field+"_"+fmt.Sprint(i)]
  993. break
  994. }
  995. } else if in.Field == "winnertel" {
  996. if j.BlockPackage[k].WinnerTel == "" {
  997. j.BlockPackage[k].WinnerTel = rep[in.Field+"_"+fmt.Sprint(i)]
  998. break
  999. }
  1000. } else if in.Field == "winnerperson" {
  1001. if j.BlockPackage[k].WinnerPerson == "" {
  1002. j.BlockPackage[k].WinnerPerson = rep[in.Field+"_"+fmt.Sprint(i)]
  1003. break
  1004. }
  1005. } else if in.Field == "bidstatus" {
  1006. if j.BlockPackage[k].BidStatus == "" {
  1007. j.BlockPackage[k].BidStatus = rep[in.Field+"_"+fmt.Sprint(i)]
  1008. break
  1009. }
  1010. } else if in.Field == "projectname" {
  1011. if j.BlockPackage[k].Name == "" {
  1012. j.BlockPackage[k].Name = rep[in.Field+"_"+fmt.Sprint(i)]
  1013. break
  1014. }
  1015. } else if in.Field == "winnerperson" {
  1016. if j.BlockPackage[k].WinnerPerson == "" {
  1017. j.BlockPackage[k].WinnerPerson = rep[in.Field+"_"+fmt.Sprint(i)]
  1018. break
  1019. }
  1020. } else if in.Field == "winnertel" {
  1021. if j.BlockPackage[k].WinnerTel == "" && j.BlockPackage[k].Winner != "" && j.BlockPackage[k].WinnerPerson != "" {
  1022. j.BlockPackage[k].WinnerTel = rep[in.Field+"_"+fmt.Sprint(i)]
  1023. break
  1024. }
  1025. }
  1026. }
  1027. }
  1028. }
  1029. } else {
  1030. pos := in.RegCore.Reg.FindStringIndex(vbpkg.Text)
  1031. val := ""
  1032. if len(pos) == 2 {
  1033. //"text" = "text"[pos[1]:]
  1034. val = "text"[pos[1]:]
  1035. rs := regexp.MustCompile("[^\r\n\t]+")
  1036. tmp := rs.FindAllString("text", -1)
  1037. if len(tmp) > 0 {
  1038. val = tmp[0]
  1039. }
  1040. }
  1041. if val != "" {
  1042. if in.Field == "budget" && vbpkg.Budget <= 0 {
  1043. lock.Lock()
  1044. cfn := e.ClearFn[in.Field]
  1045. lock.Unlock()
  1046. data := clear.DoClearFn(cfn, []interface{}{val, j.Content})
  1047. if data[len(data)-1].(bool) {
  1048. j.BlockPackage[k].Budget = qu.Float64All(data[0])
  1049. j.BlockPackage[k].IsTrueBudget = true
  1050. }
  1051. break
  1052. }
  1053. if in.Field == "bidamount" && vbpkg.Bidamount <= 0 {
  1054. lock.Lock()
  1055. cfn := e.ClearFn[in.Field]
  1056. lock.Unlock()
  1057. data := clear.DoClearFn(cfn, []interface{}{val, j.Content})
  1058. if data[len(data)-1].(bool) {
  1059. j.BlockPackage[k].Bidamount = qu.Float64All(data[0])
  1060. j.BlockPackage[k].IsTrueBidamount = true
  1061. }
  1062. break
  1063. } else if in.Field == "bidstatus" {
  1064. if j.BlockPackage[k].BidStatus == "" {
  1065. j.BlockPackage[k].BidStatus = val
  1066. break
  1067. }
  1068. } else if in.Field == "projectname" {
  1069. if j.BlockPackage[k].Name == "" {
  1070. j.BlockPackage[k].Name = val
  1071. break
  1072. }
  1073. }
  1074. }
  1075. }
  1076. }
  1077. }
  1078. }
  1079. //lua脚本根据属性设置提取kv值
  1080. func getKvByLuaFields(vc *RuleCore, j *ju.Job, et *ExtractTask) (map[string][]map[string]interface{}, bool) {
  1081. kvmap := map[string][]map[string]interface{}{}
  1082. if len(j.Winnerorder) > 1 {
  1083. if vc.Field == "bidamount" {
  1084. for _, v := range j.Winnerorder {
  1085. if v["price"] == nil {
  1086. continue
  1087. }
  1088. kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
  1089. "code": "winnerorder",
  1090. "field": vc.Field,
  1091. "ruletext": "中标候选人_" + v["sortstr"].(string),
  1092. "extfrom": v["sortstr"],
  1093. "sourcevalue": v["price"],
  1094. "value": v["price"],
  1095. "type": "winnerorder",
  1096. "matchtype": "winnerorder",
  1097. })
  1098. return kvmap, false
  1099. }
  1100. //候选人中标金额
  1101. if price := j.Winnerorder[0]["price"]; price != nil {
  1102. kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
  1103. "code": "CL_中标候选人",
  1104. "field": vc.Field,
  1105. "ruletext": "中标候选人",
  1106. "extfrom": j.Winnerorder[0]["sortstr"],
  1107. "sourcevalue": price,
  1108. "value": price,
  1109. "type": "winnerorder",
  1110. "matchtype": "winnerorder",
  1111. })
  1112. return kvmap, false
  1113. }
  1114. }
  1115. //else if vc.Field == "winner" {
  1116. // for _, v := range j.Winnerorder {
  1117. // kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
  1118. // "code": "winnerorder",
  1119. // "field": vc.Field,
  1120. // "ruletext": "中标候选人",
  1121. // "extfrom": vc.ExtFrom,
  1122. // "sourcevalue": "中标候选人",
  1123. // "value": v["entname"],
  1124. // "type": "winnerorder",
  1125. // "matchtype": "winnerorder",
  1126. // })
  1127. // }
  1128. // //候选人中标单位
  1129. // if entname := j.Winnerorder[0]["entname"]; entname != nil {
  1130. // kvmap[vc.Field] = append(kvmap[vc.Field], map[string]interface{}{
  1131. // "code": "CL_中标候选人",
  1132. // "field": vc.Field,
  1133. // "ruletext": "中标候选人",
  1134. // "extfrom": vc.ExtFrom,
  1135. // "sourcevalue": "中标候选人",
  1136. // "value": entname,
  1137. // "type": "winnerorder",
  1138. // "matchtype": "winnerorder",
  1139. // })
  1140. // return kvmap, false
  1141. // }
  1142. //}
  1143. }
  1144. for fieldname, field := range vc.LFields {
  1145. if field != vc.Field {
  1146. continue
  1147. }
  1148. extractFromKv(field, fieldname, j.Block, vc, kvmap)
  1149. }
  1150. AddExtLog("extract", j.SourceMid, nil, kvmap, &RegLuaInfo{Field: vc.Field}, et.TaskInfo) //抽取日志
  1151. return kvmap, true
  1152. }
  1153. func extractFromKv(field, fieldname string, blocks []*ju.Block, vc *RuleCore, kvmap map[string][]map[string]interface{}) {
  1154. //qu.Debug("fieldname+++", fieldname)
  1155. for _, bl := range blocks {
  1156. tp := ""
  1157. for k, v := range []*ju.JobKv{bl.ColonKV, bl.SpaceKV, bl.TableKV} {
  1158. if k == 0 {
  1159. tp = "colon"
  1160. // for _, vv := range v.Kvs {
  1161. // qu.Debug("colon-kvs:", vv.Key, vv.Value)
  1162. // }
  1163. // for kkk, vv := range v.KvTags {
  1164. // for _, vvv := range vv {
  1165. // qu.Debug("colon-tags", kkk, vvv.Key, vvv.Value)
  1166. // }
  1167. // }
  1168. } else if k == 1 {
  1169. tp = "space"
  1170. // for _, vv := range v.Kvs {
  1171. // qu.Debug("space-kvs:", vv.Key, vv.Value)
  1172. // }
  1173. // for kkk, vv := range v.KvTags {
  1174. // for _, vvv := range vv {
  1175. // qu.Debug("space-tags", kkk, vvv.Key, vvv.Value)
  1176. // }
  1177. // }
  1178. } else if k == 2 {
  1179. tp = "table"
  1180. // for _, vv := range v.Kvs {
  1181. // qu.Debug("table-kvs:", vv.Key, vv.Value)
  1182. // }
  1183. // for kkk, vv := range v.KvTags {
  1184. // for _, vvv := range vv {
  1185. // qu.Debug("table-tags", kkk, vvv.Key, vvv.Value)
  1186. // }
  1187. // }
  1188. }
  1189. if v == nil || v.KvTags == nil {
  1190. continue
  1191. }
  1192. for _, vv := range v.KvTags[fieldname] {
  1193. text := ju.TrimLRSpace(vv.Value, "")
  1194. if text != "" {
  1195. kvmap[field] = append(kvmap[field], map[string]interface{}{
  1196. "code": "CL_" + vv.Key,
  1197. "field": field,
  1198. "ruletext": vv.Key,
  1199. "extfrom": vc.ExtFrom,
  1200. "sourcevalue": text,
  1201. "value": text,
  1202. "type": tp,
  1203. "matchtype": "tag_string",
  1204. "blocktag": bl.Classify,
  1205. "weight": vv.Weight,
  1206. })
  1207. //if field != "winnertel" && field != "winnerperson" {
  1208. // //break //暂定取第一个
  1209. //}
  1210. }
  1211. }
  1212. }
  1213. if len(kvmap[field]) == 0 {
  1214. extractFromKv(field, fieldname, bl.Block, vc, kvmap)
  1215. }
  1216. }
  1217. }
  1218. //正则提取结果
  1219. func extRegCoreToResult(extfrom, text string, tag *map[string]string, j *ju.Job, vre *RegLuaInfo, isSite bool) map[string][]map[string]interface{} {
  1220. defer qu.Catch()
  1221. var score float64
  1222. score = vre.Score
  1223. if isSite {
  1224. score = score + 1.0
  1225. }
  1226. extinfo := map[string][]map[string]interface{}{}
  1227. rep := map[string]string{}
  1228. if vre.RegCore.Bextract { //正则是两部分的,可以直接抽取的(含下划线)
  1229. //处理正负数修正
  1230. ptmp := strings.Split(vre.RuleText, "#")
  1231. sign := 0
  1232. if len(ptmp) == 2 {
  1233. if ptmp[1] == "正" {
  1234. sign = 1
  1235. } else if ptmp[1] == "负" {
  1236. sign = -1
  1237. }
  1238. }
  1239. tmp := strings.Split(ptmp[0], "__")
  1240. if len(tmp) == 2 {
  1241. epos := strings.Split(tmp[1], ",")
  1242. posm := map[string]int{}
  1243. for _, v := range epos {
  1244. ks := strings.Split(v, ":")
  1245. if len(ks) == 2 { //(.*)招标公告(.*)__2:projectname,4:area
  1246. posm[ks[1]] = qu.IntAll(ks[0])
  1247. } else {
  1248. posm[vre.Field] = qu.IntAll(ks[0])
  1249. }
  1250. }
  1251. var pattern string
  1252. if strings.Contains(tmp[0], "\\u") {
  1253. tmp[0] = strings.Replace(tmp[0], "\\", "\\\\", -1)
  1254. tmp[0] = strings.Replace(tmp[0], "\\\\u", "\\u", -1)
  1255. pattern, _ = strconv.Unquote(`"` + tmp[0] + `"`)
  1256. } else {
  1257. pattern = tmp[0]
  1258. }
  1259. //log.Debug("pattern", pattern)
  1260. //fmt.Println(text)
  1261. reg := regexp.MustCompile(pattern)
  1262. apos := reg.FindAllStringSubmatchIndex(text, -1)
  1263. for i, _ := range apos {
  1264. pos := apos[i]
  1265. for k, p := range posm {
  1266. if len(pos) > p {
  1267. if pos[p] == -1 || pos[p+1] == -1 {
  1268. continue
  1269. }
  1270. val := text[pos[p]:pos[p+1]]
  1271. if string(val) == "" {
  1272. continue
  1273. }
  1274. if sign == -1 {
  1275. rep[k+"_"+fmt.Sprint(i)] = "-" + val
  1276. } else {
  1277. rep[k+"_"+fmt.Sprint(i)] = val
  1278. }
  1279. }
  1280. }
  1281. }
  1282. //fmt.Println(text)
  1283. tmps := []map[string]interface{}{}
  1284. for i := 0; i < len(apos); i++ {
  1285. if strings.TrimSpace(rep[vre.Field+"_"+fmt.Sprint(i)]) != "" {
  1286. tmp := map[string]interface{}{
  1287. "field": vre.Field,
  1288. "code": vre.Code,
  1289. "ruletext": vre.RuleText,
  1290. "extfrom": text,
  1291. "value": rep[vre.Field+"_"+fmt.Sprint(i)],
  1292. "type": "regexp",
  1293. "matchtype": "regcontent",
  1294. "blocktag": *tag,
  1295. "score": score,
  1296. }
  1297. tmps = append(tmps, tmp)
  1298. exfield := ju.ExtField{
  1299. BlockTag: *tag,
  1300. Field: vre.Field,
  1301. Code: vre.Code,
  1302. RuleText: vre.RuleText,
  1303. Type: "regexp",
  1304. MatchType: "regcontent",
  1305. ExtFrom: extfrom,
  1306. SourceValue: rep[vre.Field+"_"+fmt.Sprint(i)],
  1307. Value: rep[vre.Field+"_"+fmt.Sprint(i)],
  1308. Score: score}
  1309. if tmp["blocktag"] != nil {
  1310. exfield.BlockTag = tmp["blocktag"].(map[string]string)
  1311. }
  1312. j.Result[vre.Field] = append(j.Result[vre.Field], &exfield)
  1313. }
  1314. }
  1315. if len(tmps) > 0 {
  1316. //fmt.Println(tmps)
  1317. extinfo[vre.Field] = tmps
  1318. }
  1319. }
  1320. } else {
  1321. pos := vre.RegCore.Reg.FindStringIndex(text)
  1322. val := ""
  1323. if len(pos) == 2 {
  1324. text = text[pos[1]:]
  1325. rs := regexp.MustCompile("[^\r\n\t]+")
  1326. tmp := rs.FindAllString(text, -1)
  1327. if len(tmp) > 0 {
  1328. val = tmp[0]
  1329. }
  1330. }
  1331. if val != "" {
  1332. tmps := []map[string]interface{}{}
  1333. tmp := map[string]interface{}{
  1334. "field": vre.Field,
  1335. "code": vre.Code,
  1336. "ruletext": vre.RuleText,
  1337. "extfrom": text,
  1338. "value": val,
  1339. "type": "regexp",
  1340. "matchtype": "regcontent",
  1341. "blocktag": *tag,
  1342. "score": score,
  1343. }
  1344. tmps = append(tmps, tmp)
  1345. extinfo[vre.Field] = tmps
  1346. if j.Result[vre.Field] == nil {
  1347. j.Result[vre.Field] = [](*ju.ExtField){}
  1348. }
  1349. field := &ju.ExtField{BlockTag: *tag, Field: vre.Field, Code: vre.Code, RuleText: vre.RuleText, Type: "regexp", MatchType: "regcontent", ExtFrom: extfrom, SourceValue: text,
  1350. Value: val,
  1351. Score: score}
  1352. if tmp["blocktag"] != nil {
  1353. field.BlockTag = tmp["blocktag"].(map[string]string)
  1354. }
  1355. j.Result[vre.Field] = append(j.Result[vre.Field], field)
  1356. }
  1357. }
  1358. return extinfo
  1359. }
  1360. //后置过滤
  1361. func ExtRegBack(j *ju.Job, in *RegLuaInfo, t *TaskInfo, vc *RuleCore) {
  1362. defer qu.Catch()
  1363. if in.IsLua {
  1364. result := GetResultMapForLua(j)
  1365. lua := ju.LuaScript{Code: in.Code, Name: in.Name, Result: result, Script: in.RuleText}
  1366. if j != nil {
  1367. lua.Block = j.Block
  1368. }
  1369. extinfo := lua.RunScript("back")
  1370. for k, v := range extinfo {
  1371. if tmps, ok := v.([]map[string]interface{}); ok {
  1372. j.Result[k] = [](*ju.ExtField){}
  1373. for _, tmp := range tmps {
  1374. 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"]),
  1375. ExtFrom: qu.ObjToString(tmp["extfrom"]),
  1376. Value: tmp["value"]}
  1377. if tmp["blocktag"] != nil {
  1378. field.BlockTag = tmp["blocktag"].(map[string]string)
  1379. }
  1380. j.Result[k] = append(j.Result[k], field)
  1381. //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})
  1382. }
  1383. }
  1384. }
  1385. if len(extinfo) > 0 {
  1386. AddExtLog("clear", j.SourceMid, result, extinfo, in, t) //抽取日志
  1387. }
  1388. } else {
  1389. extinfo := map[string]interface{}{}
  1390. if in.Field != "" {
  1391. clearByTitle := false
  1392. if vc != nil && vc.ExtFrom == "title" && in.Field == "buyer" { //buyer从title抽取到的单独走titile的清理
  1393. clearByTitle = true
  1394. }
  1395. if j.Result[in.Field] != nil {
  1396. tmp := j.Result[in.Field]
  1397. exts := []interface{}{}
  1398. for k, v := range tmp {
  1399. if clearByTitle && v.ExtFrom != "title" {
  1400. continue
  1401. }
  1402. //table抽取到的数据不清理
  1403. // if v.Type == "table" && v.Field != "projectname" {
  1404. // continue
  1405. // }
  1406. text := qu.ObjToString(v.Value)
  1407. if text != "" {
  1408. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  1409. }
  1410. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  1411. continue
  1412. }
  1413. j.Result[in.Field][k].Value = text
  1414. exts = append(exts, map[string]interface{}{
  1415. "field": v.Field,
  1416. "code": v.Code,
  1417. "ruletext": v.RuleText,
  1418. "type": v.Type,
  1419. "matchtype": v.MatchType,
  1420. "extfrom": v.ExtFrom,
  1421. "value": text,
  1422. })
  1423. }
  1424. if len(exts) > 0 {
  1425. extinfo[in.Field] = exts
  1426. AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
  1427. }
  1428. }
  1429. } else {
  1430. for key, tmp := range j.Result {
  1431. exts := []interface{}{}
  1432. for k, v := range tmp {
  1433. if v.Type == "table" { //table抽取到的数据不清理
  1434. continue
  1435. }
  1436. text := qu.ObjToString(v.Value)
  1437. if text != "" {
  1438. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  1439. }
  1440. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  1441. continue
  1442. }
  1443. j.Result[key][k].Value = text
  1444. exts = append(exts, map[string]interface{}{
  1445. "field": v.Field,
  1446. "code": v.Code,
  1447. "ruletext": v.RuleText,
  1448. "type": v.Type,
  1449. "matchtype": v.MatchType,
  1450. "extfrom": v.ExtFrom,
  1451. "value": text,
  1452. })
  1453. }
  1454. if len(exts) > 0 {
  1455. extinfo[key] = exts
  1456. AddExtLog("clear", j.SourceMid, j.Result, extinfo, in, t) //抽取日志
  1457. }
  1458. }
  1459. }
  1460. }
  1461. }
  1462. //后置过滤
  1463. func ExtRegBackPkg(j *ju.Job, in *RegLuaInfo) {
  1464. defer qu.Catch()
  1465. for k, v := range j.BlockPackage {
  1466. if in.Field == "winner" {
  1467. j.BlockPackage[k].Winner = in.RegPreBac.Reg.ReplaceAllString(v.Winner, in.RegPreBac.Replace)
  1468. } else if in.Field == "bidstatus" {
  1469. j.BlockPackage[k].BidStatus = in.RegPreBac.Reg.ReplaceAllString(v.BidStatus, in.RegPreBac.Replace)
  1470. } else if in.Field == "" {
  1471. j.BlockPackage[k].Text = in.RegPreBac.Reg.ReplaceAllString(v.Text, in.RegPreBac.Replace)
  1472. } else if in.Field == "projectname" {
  1473. j.BlockPackage[k].Name = in.RegPreBac.Reg.ReplaceAllString(v.Name, in.RegPreBac.Replace)
  1474. } else if in.Field == "winnerperson" {
  1475. j.BlockPackage[k].WinnerPerson = in.RegPreBac.Reg.ReplaceAllString(v.WinnerPerson, in.RegPreBac.Replace)
  1476. } else if in.Field == "winnertel" {
  1477. j.BlockPackage[k].WinnerTel = in.RegPreBac.Reg.ReplaceAllString(v.WinnerTel, in.RegPreBac.Replace)
  1478. }
  1479. }
  1480. }
  1481. //KV过滤
  1482. func ExtRuleKV(j *ju.Job, in *RegLuaInfo, t *TaskInfo) {
  1483. defer qu.Catch()
  1484. extinfo := map[string]interface{}{}
  1485. if in.Field != "" {
  1486. if j.Result[in.Field] != nil {
  1487. tmp := j.Result[in.Field]
  1488. exts := []interface{}{}
  1489. for k, v := range tmp {
  1490. if v.Type != "table" && !strings.Contains(v.Type, "colon") && !strings.Contains(v.Type, "space") {
  1491. continue
  1492. }
  1493. text := qu.ObjToString(v.Value)
  1494. if text != "" {
  1495. text = in.RegPreBac.Reg.ReplaceAllString(text, in.RegPreBac.Replace)
  1496. }
  1497. if text == qu.ObjToString(v.Value) { //值未发生改变,不存日志
  1498. continue
  1499. }
  1500. j.Result[in.Field][k].Value = text
  1501. exts = append(exts, map[string]interface{}{
  1502. "field": v.Field,
  1503. "code": v.Code,
  1504. "ruletext": v.RuleText,
  1505. "type": v.Type,
  1506. "matchtype": v.MatchType,
  1507. "extfrom": v.ExtFrom,
  1508. "value": text,
  1509. })
  1510. }
  1511. if len(exts) > 0 {
  1512. extinfo[in.Field] = exts
  1513. AddExtLog("clear", j.SourceMid, tmp, extinfo, in, t) //抽取日志
  1514. }
  1515. }
  1516. }
  1517. }
  1518. //获取抽取结果map[string][]interface{},lua脚本使用
  1519. func GetResultMapForLua(j *ju.Job) map[string][]map[string]interface{} {
  1520. defer qu.Catch()
  1521. result := map[string][]map[string]interface{}{}
  1522. for key, val := range j.Result {
  1523. if result[key] == nil {
  1524. result[key] = []map[string]interface{}{}
  1525. }
  1526. for _, v := range val {
  1527. tmp := map[string]interface{}{
  1528. "field": v.Field,
  1529. "code": v.Code,
  1530. "ruletext": v.RuleText,
  1531. "value": v.Value,
  1532. "type": v.Type,
  1533. "matchtype": v.MatchType,
  1534. "extfrom": v.ExtFrom,
  1535. }
  1536. result[key] = append(result[key], tmp)
  1537. }
  1538. }
  1539. return result
  1540. }
  1541. //抽取日志
  1542. func AddExtLog(ftype, sid string, before interface{}, extinfo interface{}, v *RegLuaInfo, t *TaskInfo) {
  1543. defer qu.Catch()
  1544. if !t.IsEtxLog {
  1545. return
  1546. }
  1547. logdata := map[string]interface{}{
  1548. "code": qu.If(v.Code == "", "kv", v.Code),
  1549. "name": v.Name,
  1550. "type": ftype,
  1551. "ruletext": v.RuleText,
  1552. "islua": v.IsLua,
  1553. "field": v.Field,
  1554. "version": t.Version,
  1555. "taskname": t.Name,
  1556. "before": before,
  1557. "extinfo": extinfo,
  1558. "sid": sid,
  1559. "comeintime": time.Now().Unix(),
  1560. }
  1561. lock.Lock()
  1562. ExtLogs[t] = append(ExtLogs[t], logdata)
  1563. lock.Unlock()
  1564. }
  1565. func BeforeAddClearFnLog(ftype, name, sid, before, matchtype string, ext *ju.ExtField, e *ExtractTask) {
  1566. exts := []map[string]interface{}{}
  1567. exts = append(exts, map[string]interface{}{
  1568. "field": ext.Field,
  1569. "code": ext.Code,
  1570. "type": ftype,
  1571. "matchtype": matchtype,
  1572. "extfrom": ext.ExtFrom,
  1573. "value": ext.Value,
  1574. })
  1575. extinfo := map[string]interface{}{
  1576. ext.Field: exts,
  1577. }
  1578. AddClearFnLog(ftype, sid, before, extinfo, ext.Code, name, ext.Field, e.TaskInfo)
  1579. }
  1580. func AddClearFnLog(ftype, sid string, before interface{}, extinfo interface{}, code, name, field string, t *TaskInfo) {
  1581. defer qu.Catch()
  1582. if !t.IsEtxLog {
  1583. return
  1584. }
  1585. logdata := map[string]interface{}{
  1586. "code": code,
  1587. "name": name,
  1588. "type": ftype,
  1589. "ruletext": "",
  1590. "islua": false,
  1591. "field": field,
  1592. "version": t.Version,
  1593. "taskname": t.Name,
  1594. "before": before,
  1595. "extinfo": extinfo,
  1596. "sid": sid,
  1597. "comeintime": time.Now().Unix(),
  1598. }
  1599. lock.Lock()
  1600. ExtLogs[t] = append(ExtLogs[t], logdata)
  1601. lock.Unlock()
  1602. }
  1603. //保存抽取日志
  1604. func SaveExtLog() {
  1605. defer qu.Catch()
  1606. tmpLogs := map[*TaskInfo][]map[string]interface{}{}
  1607. lock.Lock()
  1608. tmpLogs = ExtLogs
  1609. ExtLogs = map[*TaskInfo][]map[string]interface{}{}
  1610. lock.Unlock()
  1611. for k, v := range tmpLogs {
  1612. if len(v) < saveLimit {
  1613. db.Mgo.SaveBulk(k.TrackColl, v...)
  1614. } else {
  1615. for {
  1616. if len(v) > saveLimit {
  1617. tmp := v[:saveLimit]
  1618. db.Mgo.SaveBulk(k.TrackColl, tmp...)
  1619. v = v[saveLimit:]
  1620. } else {
  1621. db.Mgo.SaveBulk(k.TrackColl, v...)
  1622. break
  1623. }
  1624. }
  1625. }
  1626. }
  1627. time.AfterFunc(10*time.Second, SaveExtLog)
  1628. }
  1629. type FieldValue struct {
  1630. Value interface{}
  1631. Count int
  1632. }
  1633. var clearWinnerReg = regexp.MustCompile("名称|施工|拟定供应商名称|:|:")
  1634. //分析抽取结果并保存
  1635. func AnalysisSaveResult(j, jf *ju.Job, e *ExtractTask) {
  1636. qu.Try(func() {
  1637. //重新取出清理过后的中标候选人
  1638. resetWinnerorder(j)
  1639. doc, result, _id := funcAnalysis(j, e)
  1640. if ju.IsSaveTag {
  1641. go otherNeedSave(j, result, e)
  1642. }
  1643. auxinfo := auxInfo(j)
  1644. //从排序结果中取值
  1645. tmp := map[string]interface{}{} //抽取值
  1646. tmp["spidercode"] = j.SpiderCode
  1647. tmp["site"] = j.Site
  1648. tmp["jsondata"] = j.Jsondata
  1649. tmp["fieldall"] = auxinfo
  1650. for _, val := range result {
  1651. for _, v := range val { //取第一个非负数,项目名称除外
  1652. //存0是否有效
  1653. if (v.Field == "bidamount" || v.Field == "budget") && v.IsTrue {
  1654. tmp[v.Field] = v.Value
  1655. break
  1656. }
  1657. if v.Score > -1 {
  1658. tmp[v.Field] = v.Value
  1659. break
  1660. } else if v.Field == "projectname" {
  1661. tmp[v.Field] = v.Value
  1662. break
  1663. }
  1664. }
  1665. }
  1666. if len(j.PackageInfo) > 15 {
  1667. for k, v := range j.PackageInfo {
  1668. j.PackageInfo = map[string]map[string]interface{}{}
  1669. j.PackageInfo[k] = v
  1670. break
  1671. }
  1672. }
  1673. if len(j.PackageInfo) > 0 { //分包信息
  1674. tmp["package"] = j.PackageInfo
  1675. //包预算,中标金额合并大于抽取就覆盖
  1676. var tmpBidamount, tmpBudget float64
  1677. //s_winner逗号分隔拼接,分包中标人
  1678. var tmpstr, savewinner []string
  1679. //按包排序
  1680. for b, v := range j.PackageInfo {
  1681. if v["winner"] != nil && v["winner"] != "" {
  1682. tmpstr = append(tmpstr, b)
  1683. }
  1684. }
  1685. //包预算,中标金额合并大于抽取就覆盖
  1686. if len(j.PackageInfo) >= 1 {
  1687. //包数大于1累加
  1688. for _, v := range j.PackageInfo {
  1689. if v["budget"] != nil {
  1690. tmpBudget += qu.Float64All(v["budget"])
  1691. }
  1692. if v["bidamount"] != nil {
  1693. tmpBidamount += qu.Float64All(v["bidamount"])
  1694. }
  1695. }
  1696. if qu.Float64All(tmp["budget"]) < tmpBudget {
  1697. tmp["budget"] = tmpBudget
  1698. }
  1699. if qu.Float64All(tmp["bidamount"]) < tmpBidamount {
  1700. tmp["bidamount"] = tmpBidamount
  1701. }
  1702. } else {
  1703. //包数等于1,tmp没有值取包里的值
  1704. if tmp["budget"] == nil || tmp["budget"] == 0 {
  1705. for _, v := range j.PackageInfo {
  1706. if v["budget"] != nil {
  1707. tmp["budget"] = v["budget"]
  1708. }
  1709. }
  1710. }
  1711. if tmp["bidamount"] == nil || tmp["bidamount"] == 0 {
  1712. for _, v := range j.PackageInfo {
  1713. if v["bidamount"] != nil {
  1714. tmp["bidamount"] = v["bidamount"]
  1715. }
  1716. }
  1717. }
  1718. }
  1719. //s_winner逗号分隔拼接,分包中标人
  1720. sort.Strings(tmpstr)
  1721. for _, v := range tmpstr {
  1722. svvvv := qu.ObjToString(j.PackageInfo[v]["winner"])
  1723. savevvv := clearWinnerReg.ReplaceAllString(svvvv, "")
  1724. if savevvv == "" {
  1725. continue
  1726. }
  1727. savewinner = append(savewinner, savevvv)
  1728. }
  1729. if (savewinner == nil || len(savewinner) == 0) && tmp["winner"] != nil {
  1730. tmp["s_winner"] = tmp["winner"]
  1731. } else if savewinner != nil {
  1732. savewinner = RemoveReplicaSliceString(savewinner)
  1733. tmp["s_winner"] = strings.Join(savewinner, ",")
  1734. }
  1735. } else if tmp["winner"] != nil && tmp["winner"] != "" {
  1736. //没有分包取winner
  1737. tmp["s_winner"] = tmp["winner"]
  1738. }
  1739. if len(j.Winnerorder) > 0 { //候选人信息
  1740. for i, v := range j.Winnerorder {
  1741. if v["price"] != nil {
  1742. j.Winnerorder[i]["price"] = clear.ObjToMoney([]interface{}{v["price"], ""})[0]
  1743. }
  1744. }
  1745. tmp["winnerorder"] = j.Winnerorder
  1746. }
  1747. //处理附件
  1748. var resultf map[string][]*ju.ExtField
  1749. if jf != nil {
  1750. _, resultf, _ = funcAnalysis(jf, e)
  1751. auxinfof := auxInfo(jf)
  1752. tmp["fieldallf"] = auxinfof
  1753. ffield := map[string]interface{}{}
  1754. for _, val := range resultf {
  1755. for _, v := range val { //取第一个非负数
  1756. if v.Score > -1 {
  1757. ffield[v.Field] = v.Value
  1758. break
  1759. }
  1760. }
  1761. }
  1762. if len(jf.PackageInfo) > 0 { //分包信息
  1763. ffield["package"] = jf.PackageInfo
  1764. }
  1765. if len(jf.Winnerorder) > 0 { //候选人信息
  1766. ffield["winnerorder"] = jf.Winnerorder
  1767. }
  1768. tmp["ffield"] = ffield
  1769. }
  1770. for k, v := range *doc {
  1771. //去重冗余字段
  1772. if delFiled(k) {
  1773. continue
  1774. }
  1775. if tmp[k] == nil {
  1776. tmp[k] = v
  1777. }
  1778. }
  1779. //质量审核
  1780. if ju.QualityAudit {
  1781. e.QualityAudit(tmp)
  1782. }
  1783. if e.IsExtractCity { //城市抽取
  1784. //e.ExtractCity(j, tmp, _id)
  1785. e.NewExtractCity(j, tmp, _id)
  1786. // b, p, c, d := e.TransmitData(tmp, _id) //抽取省份城市
  1787. // // log.Debug("省份---", p, "城市---", c, "区---", d)
  1788. // tmp["district"] = d
  1789. // if b {
  1790. // tmp["city"] = c
  1791. // tmp["area"] = p
  1792. // }
  1793. }
  1794. //品牌抽取
  1795. if ju.IsBrandGoods {
  1796. tmp["checkhas"] = map[string]int{
  1797. "hastable": j.HasTable,
  1798. "hasgoods": j.HasGoods,
  1799. "hasbrand": j.HasBrand,
  1800. "haskey": j.HasKey,
  1801. }
  1802. if len(j.BrandData) > 0 {
  1803. tmp["tablebrand"] = j.BrandData
  1804. }
  1805. // log.Debug("============", j.HasBrand, j.HasGoods, j.HasKey, j.HasTable, j.BrandData)
  1806. }
  1807. //prince和number抽取
  1808. if ju.IsPriceNumber {
  1809. priceNumberLen := len(j.PriceNumberData)
  1810. if priceNumberLen > 1 { //table数据去重
  1811. tmpPriceNumberData := []map[string]interface{}{}
  1812. tableStrs := map[string]bool{}
  1813. for _, tb := range j.PriceNumberData {
  1814. has := false
  1815. bytes, _ := json.Marshal(tb)
  1816. str := string(bytes)
  1817. if len(tableStrs) > 0 && tableStrs[str] {
  1818. has = true
  1819. } else {
  1820. tableStrs[str] = true
  1821. }
  1822. if !has {
  1823. for _, data := range tb {
  1824. tmpPriceNumberData = append(tmpPriceNumberData, data)
  1825. }
  1826. }
  1827. }
  1828. tmp["pricenumber"] = tmpPriceNumberData
  1829. } else if priceNumberLen == 1 {
  1830. tmp["pricenumber"] = j.PriceNumberData[0]
  1831. }
  1832. }
  1833. //所有kv组成的字符串
  1834. var kvtext bytes.Buffer
  1835. blocks := make([]ju.BlockAndTag, 0)
  1836. for _, v := range j.Block {
  1837. //分包和标签
  1838. if ju.SaveBlock {
  1839. xx, _ := json.Marshal(v)
  1840. tmpblock := new(ju.TmpBlock)
  1841. err := json.Unmarshal(xx, &tmpblock)
  1842. if err != nil {
  1843. if v.BPackage != nil {
  1844. bpb, _ := json.Marshal(v.BPackage)
  1845. tmpblock.BPackage = string(bpb)
  1846. }
  1847. tmpblock = rangeBlockToJson(v, *tmpblock)
  1848. }
  1849. blocks = append(blocks, ju.BlockAndTag{v.Tag, tmpblock})
  1850. }
  1851. //把所有kv组装成一个字符串,存库
  1852. for _, jv := range []*ju.JobKv{v.ColonKV, v.SpaceKV, v.TableKV} {
  1853. if jv == nil {
  1854. continue
  1855. }
  1856. for jv_k, jv_v := range jv.KvTags {
  1857. for _, jv_vv := range jv_v {
  1858. kvtext.WriteString(jv_k)
  1859. kvtext.WriteString(":")
  1860. kvtext.WriteString(jv_vv.Value)
  1861. kvtext.WriteString(" ")
  1862. }
  1863. }
  1864. }
  1865. }
  1866. if kvtext.Len() > 0 {
  1867. tmp["kvtext"] = kvtext.String()
  1868. }
  1869. if len(blocks) > 0 {
  1870. if blocksBytes, err := json.Marshal(blocks); err == nil {
  1871. if utf8.RuneCount(blocksBytes) < 100000 {
  1872. tmp["blocks"] = string(blocksBytes)
  1873. }
  1874. }
  1875. }
  1876. // fmt.Println("=============抽取结果================")
  1877. // for k, v := range tmp {
  1878. // qu.Debug(k, "---", v)
  1879. // }
  1880. //tmp["extract_content"] = j.Content
  1881. if e.TaskInfo.TestColl == "" {
  1882. if len(tmp) > 0 { //保存抽取结果
  1883. /* if len(e.SiteFields) <= 0 {
  1884. //for field, _ := range e.Fields {
  1885. // if tmp[field] == nil && {
  1886. // tmp[field] = "" //覆盖之前版本数据
  1887. // }
  1888. //}
  1889. } else {
  1890. //for field, _ := range e.SiteFields {
  1891. // if tmp[field] == nil &&{
  1892. // tmp[field] = "" //覆盖之前版本数据
  1893. // }
  1894. //}
  1895. }*/
  1896. tmp["repeat"] = 0
  1897. tmparr := []map[string]interface{}{
  1898. map[string]interface{}{
  1899. "_id": qu.StringTOBsonId(_id),
  1900. },
  1901. map[string]interface{}{"$set": tmp},
  1902. }
  1903. e.RWMutex.Lock()
  1904. e.BidArr = append(e.BidArr, tmparr)
  1905. e.BidTotal++
  1906. e.RWMutex.Unlock()
  1907. }
  1908. if ju.SaveResult {
  1909. id := tmp["_id"]
  1910. tmp["result"] = result
  1911. tmp["resultf"] = resultf
  1912. delete(tmp, "_id")
  1913. tmparr := []map[string]interface{}{
  1914. map[string]interface{}{
  1915. "_id": id,
  1916. },
  1917. map[string]interface{}{"$set": tmp},
  1918. }
  1919. e.RWMutex.Lock()
  1920. e.ResultArr = append(e.ResultArr, tmparr)
  1921. e.RWMutex.Unlock()
  1922. }
  1923. } else { //测试结果
  1924. delete(tmp, "_id")
  1925. delete(tmp, "fieldall")
  1926. if len(j.BlockPackage) > 0 { //分包详情
  1927. if len(j.BlockPackage) > 10 {
  1928. tmp["epackage"] = "分包异常"
  1929. } else {
  1930. bs, _ := json.Marshal(j.BlockPackage)
  1931. tmp["epackage"] = string(bs)
  1932. }
  1933. }
  1934. tmp["result"] = result
  1935. tmp["resultf"] = resultf
  1936. b := db.Mgo.Update(e.TaskInfo.TestColl, `{"_id":"`+_id+`"}`, map[string]interface{}{"$set": tmp}, true, false)
  1937. if !b {
  1938. log.Debug(e.TaskInfo.TestColl, _id)
  1939. }
  1940. }
  1941. }, func(err interface{}) {
  1942. log.Debug("AnalysisSaveResult err", err)
  1943. })
  1944. }
  1945. //保存其他
  1946. //kv、表格、块上的标签凡是新的标签都入库
  1947. //val type times firstid createtime 判定field
  1948. func otherNeedSave(j *ju.Job, result map[string][]*ju.ExtField, e *ExtractTask) {
  1949. now := time.Now().Unix()
  1950. coll := e.TaskInfo.TestColl
  1951. if coll == "" {
  1952. coll = "extract_tag_result"
  1953. } else {
  1954. coll += "_tag"
  1955. }
  1956. datas := []map[string]interface{}{}
  1957. kv := map[string]int{}
  1958. for _, v := range j.Block {
  1959. //
  1960. for _, vv := range []*ju.JobKv{v.ColonKV, v.TableKV, v.SpaceKV} {
  1961. if vv == nil || vv.KvTags == nil {
  1962. continue
  1963. }
  1964. for kkk, vvv := range vv.KvTags {
  1965. for _, vvvv := range vvv {
  1966. if vvvv.IsInvalid {
  1967. kv[kkk] = kv[kkk] + 1
  1968. break
  1969. }
  1970. }
  1971. }
  1972. }
  1973. for _, vv := range v.NotClassifyTitles {
  1974. datas = append(datas, map[string]interface{}{
  1975. "val": vv,
  1976. "times": 0,
  1977. "type": "block",
  1978. "firstid": j.SourceMid,
  1979. "createtime": now,
  1980. })
  1981. if len(datas) == saveLimit {
  1982. db.Mgo.SaveBulk(coll, datas...)
  1983. datas = []map[string]interface{}{}
  1984. }
  1985. }
  1986. }
  1987. for k, v := range kv {
  1988. datas = append(datas, map[string]interface{}{
  1989. "val": k,
  1990. "times": v,
  1991. "type": "kv",
  1992. "firstid": j.SourceMid,
  1993. "createtime": now,
  1994. })
  1995. if len(datas) == saveLimit {
  1996. db.Mgo.SaveBulk(coll, datas...)
  1997. datas = []map[string]interface{}{}
  1998. }
  1999. }
  2000. if len(datas) > 0 {
  2001. db.Mgo.SaveBulk(coll, datas...)
  2002. }
  2003. }
  2004. func rangeBlockToJson(j *ju.Block, tmpblock ju.TmpBlock) (b *ju.TmpBlock) {
  2005. if j == nil {
  2006. return nil
  2007. }
  2008. if len(j.Block) > 0 {
  2009. for i, v := range j.Block {
  2010. rangetmp := new(ju.TmpBlock)
  2011. vb, _ := json.Marshal(v)
  2012. json.Unmarshal(vb, &rangetmp)
  2013. tmpblock.Block[i] = rangeBlockToJson(v, *rangetmp)
  2014. }
  2015. }
  2016. if j.ColonKV != nil {
  2017. cb, _ := json.Marshal(j.ColonKV)
  2018. tmpblock.ColonKV = string(cb)
  2019. }
  2020. if j.SpaceKV != nil {
  2021. sb, _ := json.Marshal(j.SpaceKV)
  2022. tmpblock.SpaceKV = string(sb)
  2023. }
  2024. if j.TableKV != nil {
  2025. tb, _ := json.Marshal(j.TableKV)
  2026. tmpblock.TableKV = string(tb)
  2027. }
  2028. return &tmpblock
  2029. }
  2030. //去重冗余字段
  2031. func delFiled(k string) bool {
  2032. return k == "summary" || k == "detail" || k == "contenthtml" || k == "site" || k == "spidercode" || k == "projectinfo" || k == "jsondata"
  2033. }
  2034. func funcAnalysis(j *ju.Job, e *ExtractTask) (*map[string]interface{}, map[string][]*ju.ExtField, string) {
  2035. defer qu.Catch()
  2036. doc := j.Data
  2037. result := j.Result
  2038. _id := qu.BsonIdToSId((*doc)["_id"])
  2039. result = ScoreFields(j, e.Tag) //正负面词打分
  2040. //结果排序
  2041. for _, val := range result {
  2042. ju.Sort(val)
  2043. }
  2044. if !(len(j.Result) <= 0 || j.Jsondata == nil || len(*j.Jsondata) <= 0) {
  2045. //jsondata清理
  2046. clearJd(j.Jsondata, e)
  2047. marshalbt, _ := json.Marshal(j.Jsondata)
  2048. tmpjddata := make(map[string]interface{})
  2049. json.Unmarshal(marshalbt, &tmpjddata)
  2050. for _, jdkey := range ju.JsonData {
  2051. if (*j.Jsondata)[jdkey] != nil && (*j.Jsondata)[jdkey] != "" && len(j.Result[jdkey]) >= 5 {
  2052. for tmpk, tmpv := range j.Result[jdkey][:5] {
  2053. if jdkey == "budget" || jdkey == "bidamount" {
  2054. lockclear.Lock()
  2055. cfn := e.ClearFn[jdkey]
  2056. lockclear.Unlock()
  2057. if len(cfn) == 0 {
  2058. continue
  2059. }
  2060. newNum := clear.DoClearFn(cfn, []interface{}{(*j.Jsondata)[jdkey], ""})
  2061. if tmpv.Value == newNum[0] {
  2062. extField := &ju.ExtField{Code: "JsonData_" + jdkey + "_j.Result" + fmt.Sprint(tmpk), Field: jdkey, ExtFrom: "JsonData_" + jdkey + "_j.Result" + fmt.Sprint(tmpk), SourceValue: (*j.Jsondata)[jdkey], Value: newNum[0], Score: 100, IsTrue: newNum[len(newNum)-1].(bool)}
  2063. j.Result[jdkey] = append(j.Result[jdkey], extField)
  2064. ju.Sort(j.Result[jdkey])
  2065. delete((*j.Jsondata), jdkey)
  2066. break
  2067. }
  2068. } else {
  2069. if (*j.Jsondata)[jdkey] == tmpv.Value {
  2070. extField := &ju.ExtField{Code: "JsonData_" + jdkey + "_j.Result" + fmt.Sprint(tmpk), Field: jdkey, ExtFrom: "JsonData_" + jdkey + "_j.Result" + fmt.Sprint(tmpk), SourceValue: (*j.Jsondata)[jdkey], Value: tmpv.Value, Score: 100}
  2071. j.Result[jdkey] = append(j.Result[jdkey], extField)
  2072. ju.Sort(j.Result[jdkey])
  2073. delete((*j.Jsondata), jdkey)
  2074. break
  2075. }
  2076. }
  2077. }
  2078. }
  2079. }
  2080. if len(*j.Jsondata) > 0 {
  2081. j.Result = JsonDataMergeProcessing(j, e)
  2082. }
  2083. j.Jsondata = &tmpjddata
  2084. }
  2085. return doc, result, _id
  2086. }
  2087. //辅助信息,如果没有排序先排序
  2088. func auxInfo(j *ju.Job) map[string][]map[string]interface{} {
  2089. fieldalls := map[string][]map[string]interface{}{}
  2090. qykredis := redis.RedisPool[ju.QYK_RedisName].Get()
  2091. defer qykredis.Close()
  2092. db := 0
  2093. for field, val := range j.Result {
  2094. //ju.Sort(val)
  2095. if field == "buyer" {
  2096. db = ju.BuyerDB
  2097. } else if field == "winner" {
  2098. db = ju.WinnerDB
  2099. } else if field == "agency" {
  2100. db = ju.AgencyDB
  2101. }
  2102. sfields := []map[string]interface{}{}
  2103. for _, v := range val {
  2104. standardized := false
  2105. if _, err := qykredis.Do("SELECT", db); err != nil {
  2106. fmt.Println("redis select err", err)
  2107. } else {
  2108. rep, err := qykredis.Do("GET", v.Value)
  2109. if rep != nil && err == nil {
  2110. standardized = true
  2111. }
  2112. }
  2113. if field == "budget" || field == "bidamount" {
  2114. if !v.IsTrue {
  2115. continue
  2116. }
  2117. }
  2118. sfield := map[string]interface{}{
  2119. "val": v.Value,
  2120. "type": v.Type,
  2121. "score": v.Score,
  2122. "blocktag": v.BlockTag,
  2123. "sourceval": v.SourceValue,
  2124. "standardized": standardized,
  2125. }
  2126. sfields = append(sfields, sfield)
  2127. }
  2128. fieldalls[field] = sfields
  2129. }
  2130. return fieldalls
  2131. }
  2132. func (e *ExtractTask) QualityAudit(resulttmp map[string]interface{}) {
  2133. defer qu.Catch()
  2134. //获取审核字段
  2135. for _, field := range e.AuditFields {
  2136. //1.分包
  2137. if resulttmp["package"] != nil {
  2138. packagedata := resulttmp["package"].(map[string]map[string]interface{})
  2139. for _, val := range packagedata {
  2140. if val[field] != nil {
  2141. fv := qu.ObjToString(val[field])
  2142. if fv != "" {
  2143. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  2144. e.RedisMatch(field, fv, val) //redis匹配
  2145. } else { //除了buyer和winner,其他字段走规则匹配
  2146. e.RuleMatch(field, fv, val)
  2147. }
  2148. }
  2149. }
  2150. }
  2151. }
  2152. //2.外围
  2153. if resulttmp[field] != nil {
  2154. fv := qu.ObjToString(resulttmp[field])
  2155. if fv != "" {
  2156. if field == "buyer" || field == "winner" { //field为buyer和winner时特殊处理,先从Redis中查,有直接通过,没有走匹配规则
  2157. e.RedisMatch(field, fv, resulttmp) //redis匹配
  2158. } else { //除了buyer和winner,其他字段走规则匹配
  2159. e.RuleMatch(field, fv, resulttmp)
  2160. }
  2161. }
  2162. }
  2163. }
  2164. }
  2165. //Redis匹配
  2166. func (e *ExtractTask) RedisMatch(field, fv string, val map[string]interface{}) {
  2167. defer qu.Catch()
  2168. i := redis.GetInt(field, field+"_"+fv) //查找redis
  2169. if i == 0 { //reids未找到,执行规则匹配
  2170. val[field+"_isredis"] = false
  2171. e.RuleMatch(field, fv, val) //规则匹配
  2172. } else { //redis找到,打标识存库
  2173. val[field+"_isredis"] = true
  2174. }
  2175. }
  2176. //规则匹配
  2177. func (e *ExtractTask) RuleMatch(field, fieldval string, tmpMap map[string]interface{}) {
  2178. defer qu.Catch()
  2179. if fieldval != "" {
  2180. SMap := e.StartMatch(field, fieldval)
  2181. //SMap.AddKey(field+"_isaudit", false)
  2182. for _, k := range SMap.Keys {
  2183. tmpMap[k] = SMap.Map[k]
  2184. }
  2185. tmpMap[field+"_isaudit"] = false //添加字段未审核信息
  2186. }
  2187. }
  2188. //开始规则匹配
  2189. func (e *ExtractTask) StartMatch(field, text string) *pretreated.SortMap {
  2190. defer qu.Catch()
  2191. SMap := pretreated.NewSortMap()
  2192. lock.Lock()
  2193. f := e.RecogFieldMap[field]
  2194. lock.Unlock()
  2195. if len(f) > 0 {
  2196. fid := qu.BsonIdToSId(f["_id"])
  2197. recogFieldPreRule := qu.ObjToString(f["s_recogfield_prerule"])
  2198. textAfterRecogFieldPrerule := ju.PreFilter(text, recogFieldPreRule) //识别字段的前置过滤
  2199. if textAfterRecogFieldPrerule != "" {
  2200. lock.Lock()
  2201. classMap := e.FidClassMap[fid]
  2202. lock.Unlock()
  2203. L:
  2204. for _, c := range classMap { //class
  2205. classid := qu.BsonIdToSId(c["_id"])
  2206. classPrerule := qu.ObjToString(c["s_class_prerule"])
  2207. savefield := qu.ObjToString(c["s_savefield"]) //保存字段
  2208. textAfterClassPrerule := ju.PreFilter(textAfterRecogFieldPrerule, classPrerule) //class的前置过滤
  2209. if textAfterClassPrerule != "" {
  2210. lock.Lock()
  2211. ruleMap := e.CidRuleMap[classid]
  2212. lock.Unlock()
  2213. for _, r := range ruleMap { //rule
  2214. rulePrerule := qu.ObjToString(r["s_rule_prerule"])
  2215. s_name := qu.ObjToString(r["s_name"])
  2216. rule := r["rule"].([]interface{})
  2217. textAfterRulePrerule := ju.PreFilter(textAfterClassPrerule, rulePrerule) //class的前置过滤
  2218. if textAfterRulePrerule != "" {
  2219. b, _ := ju.RecogAnalyRules(textAfterRulePrerule, rule)
  2220. if b { //匹配到一个分类下某个规则时,不再继续匹配
  2221. if savefield != "" { //保存字段不为空,存储代码信息
  2222. SMap.AddKey(field+"_"+savefield, s_name)
  2223. }
  2224. break L
  2225. }
  2226. }
  2227. }
  2228. }
  2229. }
  2230. }
  2231. }
  2232. return SMap
  2233. }
  2234. //中标候选人经过清理之后,重新取出赋值
  2235. func resetWinnerorder(j *ju.Job) {
  2236. if len(j.Winnerorder) == 0 {
  2237. return
  2238. }
  2239. maxlen := len(j.Winnerorder) - 1
  2240. //中标单位
  2241. //i := 0
  2242. winners := []*ju.ExtField{}
  2243. bidamounts := []*ju.ExtField{}
  2244. //for _, v := range j.Result["winner"] {
  2245. // if v.Code == "winnerorder" {
  2246. // if maxlen < i {
  2247. // continue
  2248. // }
  2249. // j.Winnerorder[i]["entname"] = v.Value
  2250. // i++
  2251. // } else {
  2252. // winners = append(winners, v)
  2253. // }
  2254. //}
  2255. if maxlen > 0 {
  2256. winners = append(winners, &ju.ExtField{Code: "winnerorder", Field: "winner", ExtFrom: "j.Winnerorder", Value: j.Winnerorder[0]["entname"], Score: 0.5})
  2257. if j.Winnerorder[0]["price"] != nil {
  2258. tmpPrice := clear.ObjToMoney([]interface{}{j.Winnerorder[0]["price"], ""})
  2259. if tmpPrice[len(tmpPrice)-1].(bool) {
  2260. bidamounts = append(bidamounts, &ju.ExtField{Code: "winnerorder", Field: "bidamount", ExtFrom: "j.Winnerorder", SourceValue: j.Winnerorder[0]["price"], Value: tmpPrice[0], Score: 0.5})
  2261. }
  2262. }
  2263. }
  2264. if j.Result["winner"] == nil && len(winners) > 0 {
  2265. j.Result["winner"] = winners
  2266. } else if len(winners) > 0 {
  2267. j.Result["winner"] = append(j.Result["winner"], winners...)
  2268. }
  2269. if j.Result["bidamount"] == nil && len(bidamounts) > 0 {
  2270. j.Result["bidamount"] = bidamounts
  2271. } else if len(bidamounts) > 0 {
  2272. j.Result["bidamount"] = append(j.Result["bidamount"], bidamounts...)
  2273. }
  2274. //j.Result["winner"] = winners
  2275. //中标金额
  2276. //i = 0
  2277. //bidamounts := []*ju.ExtField{}
  2278. //for _, v := range j.Result["bidamount"] {
  2279. // if v.Code == "winnerorder" {
  2280. // if maxlen < i {
  2281. // continue
  2282. // }
  2283. // j.Winnerorder[i]["price"] = v.Value
  2284. // i++
  2285. // } else {
  2286. // bidamounts = append(bidamounts, v)
  2287. // }
  2288. //}
  2289. //j.Result["bidamount"] = bidamounts
  2290. }
  2291. func RemoveReplicaSliceString(slc []string) []string {
  2292. result := make([]string, 0)
  2293. tempMap := make(map[string]bool, len(slc))
  2294. for _, e := range slc {
  2295. if tempMap[e] == false {
  2296. tempMap[e] = true
  2297. result = append(result, e)
  2298. }
  2299. }
  2300. return result
  2301. }