extract.go 79 KB

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