extract.go 70 KB

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