wechat_platform.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. package services
  2. import (
  3. "bytes"
  4. "eta/eta_api/cache"
  5. "eta/eta_api/models"
  6. "eta/eta_api/models/rag"
  7. "eta/eta_api/services/elastic"
  8. "eta/eta_api/services/llm"
  9. "eta/eta_api/utils"
  10. "eta/eta_api/utils/llm/eta_llm/eta_llm_http"
  11. "fmt"
  12. html2 "golang.org/x/net/html"
  13. "html"
  14. "os"
  15. "path"
  16. "strconv"
  17. "strings"
  18. "time"
  19. )
  20. // AddWechatPlatform
  21. // @Description: 添加新的公众号
  22. // @param item
  23. func AddWechatPlatform(item *rag.WechatPlatform) {
  24. var err error
  25. defer func() {
  26. if err != nil {
  27. utils.FileLog.Error("公众号入库后查找最新记录失败,err:%v", err)
  28. }
  29. }()
  30. if item.FakeId != `` {
  31. return
  32. }
  33. if item.ArticleLink == `` {
  34. return
  35. }
  36. articleLink := item.ArticleLink
  37. articleDetail, err := llm.SearchByWechatArticle(item.ArticleLink)
  38. if err != nil {
  39. return
  40. }
  41. if articleDetail.Appuin == `` {
  42. err = fmt.Errorf("文章内未匹配到公众号唯一标识")
  43. return
  44. }
  45. wechatPlatform := new(rag.WechatPlatform)
  46. // 查找是否存在这个公众号id的
  47. wechatPlatformInfo, tmpErr := wechatPlatform.GetByFakeID(articleDetail.Appuin)
  48. if tmpErr != nil && !utils.IsErrNoRow(tmpErr) {
  49. err = tmpErr
  50. return
  51. }
  52. if tmpErr == nil {
  53. // 如果找到了,那么需要将当前的给移除掉
  54. err = item.Del()
  55. if err != nil {
  56. return
  57. }
  58. // 并将查出来的微信公众号摘出来的数据重新赋值
  59. item = wechatPlatformInfo
  60. } else if utils.IsErrNoRow(tmpErr) {
  61. // 如果没找到,那么就变更当前的信息
  62. item.FakeId = articleDetail.Appuin
  63. item.Nickname = articleDetail.Nickname
  64. //item.Alias = req.Alias
  65. item.RoundHeadImg = articleDetail.RoundHeadImg
  66. //item.ServiceType = req.ServiceType
  67. item.Signature = articleDetail.ProfileSignature
  68. //item.Verified = verified
  69. item.ModifyTime = time.Now()
  70. err = item.Update([]string{rag.WechatPlatformColumns.FakeID, rag.WechatPlatformColumns.Nickname, rag.WechatPlatformColumns.RoundHeadImg, rag.WechatPlatformColumns.Signature, rag.WechatPlatformColumns.ModifyTime})
  71. if err != nil {
  72. return
  73. }
  74. // 修改公众号头像
  75. go replaceWechatPlatformPic(item)
  76. }
  77. // 把刚搜索的文章加入到文章库中
  78. AddWechatArticle(item, articleLink, articleDetail, nil)
  79. BeachAddWechatArticle(item, 10)
  80. fmt.Println("公众号入库完成")
  81. return
  82. }
  83. // AddWechatArticle
  84. // @Description: 添加公众号文章入库
  85. // @author: Roc
  86. // @datetime 2025-03-05 13:24:14
  87. // @param item *rag.WechatPlatform
  88. // @param link string
  89. // @param articleDetail WechatArticleDataResp
  90. func AddWechatArticle(item *rag.WechatPlatform, articleLink string, articleDetail llm.WechatArticleDataResp, articleMenu *llm.ArticleMenu) {
  91. var err error
  92. defer func() {
  93. if err != nil {
  94. utils.FileLog.Error("公众号文章入库失败,文章链接:%s ,err:%v", articleLink, err)
  95. }
  96. }()
  97. obj := new(rag.WechatArticle)
  98. _, err = obj.GetByLink(articleLink)
  99. if err == nil {
  100. // 文章已经入库了,不需要重复入库
  101. return
  102. }
  103. // 如果不是 ErrNoRow 的时候,那么就是查询数据库出问题了,需要直接返回
  104. if !utils.IsErrNoRow(err) {
  105. return
  106. }
  107. // 这个时候,说明数据库中没有这个文章,那么需要文章入库
  108. err = nil
  109. var publishAt time.Time
  110. if articleDetail.CreateAt != `` {
  111. createAtInt, tmpErr := strconv.Atoi(articleDetail.CreateAt)
  112. if tmpErr == nil {
  113. publishAt = time.Unix(int64(createAtInt), 1000)
  114. }
  115. } else if articleMenu != nil {
  116. publishAt = time.Unix(int64(articleMenu.UpdateTime), 1000)
  117. }
  118. content := articleDetail.HtmlContent
  119. // 图片下载下来到本地,如果成功了,那么就用新的
  120. tmpContent, err := ReplaceHtmlImg(content)
  121. if tmpContent != `` {
  122. content = tmpContent
  123. }
  124. obj = &rag.WechatArticle{
  125. WechatArticleId: 0,
  126. WechatPlatformId: item.WechatPlatformId,
  127. FakeId: item.FakeId,
  128. Title: articleDetail.Title,
  129. Link: articleLink,
  130. CoverUrl: articleDetail.CoverUrl,
  131. Description: articleDetail.Desc,
  132. Content: html.EscapeString(content),
  133. TextContent: articleDetail.TextContent,
  134. Country: articleDetail.CountryName,
  135. Province: articleDetail.ProvinceName,
  136. City: articleDetail.CityName,
  137. //Abstract: "",
  138. //ArticleCreateTime: createAt,
  139. ModifyTime: time.Now(),
  140. CreateTime: time.Now(),
  141. }
  142. if !publishAt.IsZero() {
  143. obj.ArticleCreateTime = publishAt
  144. }
  145. if articleMenu != nil {
  146. obj.Title = articleMenu.Title
  147. //obj.Link = articleMenu.Link
  148. obj.CoverUrl = articleMenu.Cover
  149. obj.Description = articleMenu.Digest
  150. }
  151. err = obj.Create()
  152. // 修改文章封面图
  153. go replaceWechatArticleCoverPic(obj)
  154. // 文章入库成功后,需要将相关信息入摘要库
  155. go cache.AddWechatArticleLlmOpToCache(obj.WechatArticleId, ``)
  156. }
  157. // BeachAddWechatArticle
  158. // @Description: 批量添加公众号文章
  159. // @param item
  160. // @param num
  161. // @return err
  162. func BeachAddWechatArticle(item *rag.WechatPlatform, num int) {
  163. var err error
  164. defer func() {
  165. //fmt.Println("公众号文章批量入库完成")
  166. if err != nil {
  167. utils.FileLog.Error("公众号文章批量入库失败,err:%v", err)
  168. fmt.Println("公众号文章批量入库失败,err:", err)
  169. }
  170. }()
  171. if item.FakeId == `` {
  172. return
  173. }
  174. wechatArticleObj := new(rag.WechatArticle)
  175. // 获取公众号的文章列表
  176. articleListResp, err := llm.SearchByWechatArticleList(item.FakeId, num)
  177. if err != nil {
  178. return
  179. }
  180. for _, articleMenu := range articleListResp.List {
  181. // 判断文章是否已经入库,如果已经入库了,那么就过滤,不去重复查询微信了
  182. _, err = wechatArticleObj.GetByLink(articleMenu.Link)
  183. if err == nil {
  184. // 文章已经入库了,不需要重复入库
  185. continue
  186. }
  187. if !utils.IsErrNoRow(err) {
  188. return
  189. }
  190. err = nil
  191. articleDetail, tmpErr := llm.SearchByWechatArticle(articleMenu.Link)
  192. if tmpErr != nil {
  193. err = tmpErr
  194. return
  195. }
  196. // 把刚搜索的文章加入到指标库
  197. AddWechatArticle(item, articleMenu.Link, articleDetail, &articleMenu)
  198. time.Sleep(10 * time.Second)
  199. }
  200. return
  201. }
  202. // GenerateArticleAbstract
  203. // @Description: 文章摘要生成
  204. // @author: Roc
  205. // @datetime 2025-03-10 16:17:53
  206. // @param item *rag.WechatArticle
  207. func GenerateArticleAbstract(item *rag.WechatArticle) {
  208. var err error
  209. defer func() {
  210. if err != nil {
  211. utils.FileLog.Error("文章转临时文件失败,err:%v", err)
  212. fmt.Println("文章转临时文件失败,err:", err)
  213. }
  214. }()
  215. // 内容为空,那就不需要生成摘要
  216. if item.TextContent == `` {
  217. return
  218. }
  219. abstractObj := rag.WechatArticleAbstract{}
  220. tmpAbstractItem, err := abstractObj.GetByWechatArticleId(item.WechatArticleId)
  221. if err == nil {
  222. // 摘要已经生成,不需要重复生成
  223. AbstractToKnowledge(item, tmpAbstractItem, false)
  224. return
  225. }
  226. if !utils.IsErrNoRow(err) {
  227. return
  228. }
  229. // 生成临时文件
  230. dateDir := time.Now().Format("20060102")
  231. uploadDir := utils.STATIC_DIR + "ai/" + dateDir
  232. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  233. if err != nil {
  234. err = fmt.Errorf("存储目录创建失败,Err:" + err.Error())
  235. return
  236. }
  237. randStr := utils.GetRandStringNoSpecialChar(28)
  238. fileName := randStr + `.md`
  239. tmpFilePath := uploadDir + "/" + fileName
  240. err = utils.SaveToFile(item.TextContent, tmpFilePath)
  241. if err != nil {
  242. err = fmt.Errorf("生成临时文件失败,Err:" + err.Error())
  243. return
  244. }
  245. defer func() {
  246. os.Remove(tmpFilePath)
  247. }()
  248. // 上传临时文件到LLM
  249. tmpFileResp, err := llm.UploadTempDocs(tmpFilePath)
  250. if err != nil {
  251. err = fmt.Errorf("上传临时文件到LLM失败,Err:" + err.Error())
  252. return
  253. }
  254. if tmpFileResp.Data.Id == `` {
  255. err = fmt.Errorf("上传临时文件到LLM失败,Err:上传失败")
  256. return
  257. }
  258. tmpDocId := tmpFileResp.Data.Id
  259. //tmpDocId := `c4d2ee902808408c8b8ed398b33be103` // 钢材
  260. //tmpDocId := `2dde8afe62d24525a814e74e0a5e35e4` // 钢材
  261. //tmpDocId := `7634cc1086c04b3687682220a2cf1a48` //
  262. //开始对话
  263. abstract, addArticleChatRecordList, tmpErr := getAnswerByContent(item.WechatArticleId, tmpDocId)
  264. if tmpErr != nil {
  265. err = fmt.Errorf("LLM对话失败,Err:" + tmpErr.Error())
  266. return
  267. }
  268. // 添加问答记录
  269. if len(addArticleChatRecordList) > 0 {
  270. recordObj := rag.WechatArticleChatRecord{}
  271. err = recordObj.CreateInBatches(addArticleChatRecordList)
  272. if err != nil {
  273. return
  274. }
  275. }
  276. if abstract != `` {
  277. if abstract == `sorry` || strings.Index(abstract, `根据已知信息无法回答该问题`) == 0 {
  278. item.AbstractStatus = 2
  279. item.ModifyTime = time.Now()
  280. err = item.Update([]string{"AbstractStatus", "ModifyTime"})
  281. return
  282. }
  283. item.AbstractStatus = 1
  284. item.ModifyTime = time.Now()
  285. err = item.Update([]string{"AbstractStatus", "ModifyTime"})
  286. abstractItem := &rag.WechatArticleAbstract{
  287. WechatArticleAbstractId: 0,
  288. WechatArticleId: item.WechatArticleId,
  289. Content: abstract,
  290. Version: 0,
  291. VectorKey: "",
  292. ModifyTime: time.Now(),
  293. CreateTime: time.Now(),
  294. }
  295. err = abstractItem.Create()
  296. if err != nil {
  297. return
  298. }
  299. // 数据入ES库
  300. go AddOrEditEsWechatArticleAbstract(abstractItem.WechatArticleAbstractId)
  301. AbstractToKnowledge(item, abstractItem, false)
  302. }
  303. }
  304. // ReGenerateArticleAbstract
  305. // @Description: 文章摘要重新生成
  306. // @author: Roc
  307. // @datetime 2025-03-10 16:17:53
  308. // @param item *rag.WechatArticle
  309. func ReGenerateArticleAbstract(item *rag.WechatArticle) {
  310. var err error
  311. defer func() {
  312. if err != nil {
  313. utils.FileLog.Error("文章转临时文件失败,err:%v", err)
  314. fmt.Println("文章转临时文件失败,err:", err)
  315. }
  316. }()
  317. abstractObj := rag.WechatArticleAbstract{}
  318. abstractItem, err := abstractObj.GetByWechatArticleId(item.WechatArticleId)
  319. if err != nil {
  320. if utils.IsErrNoRow(err) {
  321. // 直接生成
  322. GenerateArticleAbstract(item)
  323. return
  324. }
  325. // 异常了
  326. return
  327. }
  328. // 生成临时文件
  329. dateDir := time.Now().Format("20060102")
  330. uploadDir := utils.STATIC_DIR + "ai/" + dateDir
  331. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  332. if err != nil {
  333. err = fmt.Errorf("存储目录创建失败,Err:" + err.Error())
  334. return
  335. }
  336. randStr := utils.GetRandStringNoSpecialChar(28)
  337. fileName := randStr + `.md`
  338. tmpFilePath := uploadDir + "/" + fileName
  339. err = utils.SaveToFile(item.TextContent, tmpFilePath)
  340. if err != nil {
  341. err = fmt.Errorf("生成临时文件失败,Err:" + err.Error())
  342. return
  343. }
  344. defer func() {
  345. os.Remove(tmpFilePath)
  346. }()
  347. // 上传临时文件到LLM
  348. tmpFileResp, err := llm.UploadTempDocs(tmpFilePath)
  349. if err != nil {
  350. err = fmt.Errorf("上传临时文件到LLM失败,Err:" + err.Error())
  351. return
  352. }
  353. if tmpFileResp.Data.Id == `` {
  354. err = fmt.Errorf("上传临时文件到LLM失败,Err:上传失败")
  355. return
  356. }
  357. tmpDocId := tmpFileResp.Data.Id
  358. //tmpDocId := `c4d2ee902808408c8b8ed398b33be103` // 钢材
  359. //tmpDocId := `2dde8afe62d24525a814e74e0a5e35e4` // 钢材
  360. //tmpDocId := `7634cc1086c04b3687682220a2cf1a48` //
  361. //开始对话
  362. abstract, addArticleChatRecordList, tmpErr := getAnswerByContent(item.WechatArticleId, tmpDocId)
  363. if tmpErr != nil {
  364. err = fmt.Errorf("LLM对话失败,Err:" + tmpErr.Error())
  365. return
  366. }
  367. // 添加问答记录
  368. if len(addArticleChatRecordList) > 0 {
  369. recordObj := rag.WechatArticleChatRecord{}
  370. err = recordObj.CreateInBatches(addArticleChatRecordList)
  371. if err != nil {
  372. return
  373. }
  374. }
  375. if abstract != `` {
  376. if abstract == `sorry` || strings.Index(abstract, `根据已知信息无法回答该问题`) == 0 {
  377. item.AbstractStatus = 2
  378. item.ModifyTime = time.Now()
  379. err = item.Update([]string{"AbstractStatus", "ModifyTime"})
  380. return
  381. }
  382. item.AbstractStatus = 1
  383. item.ModifyTime = time.Now()
  384. err = item.Update([]string{"AbstractStatus", "ModifyTime"})
  385. abstractItem.Content = abstract
  386. abstractItem.Version = abstractObj.Version + 1
  387. abstractItem.ModifyTime = time.Now()
  388. err = abstractItem.Update([]string{"content", "version", "modify_time"})
  389. if err != nil {
  390. return
  391. }
  392. AbstractToKnowledge(item, abstractItem, true)
  393. }
  394. }
  395. // DelDoc
  396. // @Description: 删除摘要向量库
  397. // @author: Roc
  398. // @datetime 2025-03-12 16:55:05
  399. // @param wechatArticleAbstractList []*rag.WechatArticleAbstract
  400. // @return err error
  401. func DelDoc(wechatArticleAbstractList []*rag.WechatArticleAbstract) (err error) {
  402. defer func() {
  403. if err != nil {
  404. utils.FileLog.Error("删除摘要向量库文件失败,err:%v", err)
  405. fmt.Println("删除摘要向量库文件失败,err:", err)
  406. }
  407. }()
  408. vectorKeyList := make([]string, 0)
  409. wechatArticleAbstractIdList := make([]int, 0)
  410. for _, v := range wechatArticleAbstractList {
  411. if v.VectorKey == `` {
  412. continue
  413. }
  414. vectorKeyList = append(vectorKeyList, v.VectorKey)
  415. wechatArticleAbstractIdList = append(wechatArticleAbstractIdList, v.WechatArticleAbstractId)
  416. }
  417. // 没有就不删除
  418. if len(vectorKeyList) <= 0 {
  419. return
  420. }
  421. _, err = llm.DelDocsToKnowledge(models.BusinessConfMap[models.KnowledgeBaseName], vectorKeyList)
  422. if err != nil {
  423. err = fmt.Errorf("删除LLM摘要向量库文件失败,Err:" + err.Error())
  424. return
  425. }
  426. //fmt.Println(resp)
  427. obj := rag.WechatArticleAbstract{}
  428. err = obj.DelVectorKey(wechatArticleAbstractIdList)
  429. return
  430. }
  431. func getAnswerByContent(wechatArticleId int, docId string) (answer string, addArticleChatRecordList []*rag.WechatArticleChatRecord, err error) {
  432. historyList := make([]eta_llm_http.HistoryContent, 0)
  433. addArticleChatRecordList = make([]*rag.WechatArticleChatRecord, 0)
  434. questionObj := rag.Question{}
  435. questionList, err := questionObj.GetListByCondition(``, []interface{}{}, 0, 100)
  436. if err != nil {
  437. err = fmt.Errorf("获取问题列表失败,Err:" + err.Error())
  438. return
  439. }
  440. // 没问题就不生成了
  441. if len(questionList) <= 0 {
  442. return
  443. }
  444. //你现在是一名资深的期货行业分析师,请基于以下的问题进行汇总总结,如果不能正常总结出来,那么就只需要回复我:sorry
  445. questionStrList := []string{`你现在是一名资深的期货行业分析师,请基于以下的问题进行汇总总结,如果不能正常总结出来,那么就只需要回复我:sorry。以下是问题:`}
  446. for _, v := range questionList {
  447. questionStrList = append(questionStrList, v.QuestionContent)
  448. }
  449. questionStr := strings.Join(questionStrList, "\n")
  450. originalAnswer, result, err := llm.ChatByFile(docId, questionStr, historyList)
  451. fmt.Println(result)
  452. if err != nil {
  453. err = fmt.Errorf("LLM对话失败,Err:" + err.Error())
  454. return
  455. }
  456. // 提取 </think> 后面的内容
  457. thinkEndIndex := strings.Index(result.Answer, "</think>")
  458. if thinkEndIndex != -1 {
  459. answer = strings.TrimSpace(result.Answer[thinkEndIndex+len("</think>"):])
  460. } else {
  461. answer = result.Answer
  462. }
  463. answer = strings.TrimSpace(answer)
  464. // 待入库的数据
  465. addArticleChatRecordList = append(addArticleChatRecordList, &rag.WechatArticleChatRecord{
  466. WechatArticleChatRecordId: 0,
  467. WechatArticleId: wechatArticleId,
  468. ChatUserType: "user",
  469. Content: questionStr,
  470. SendTime: time.Now(),
  471. CreatedTime: time.Now(),
  472. UpdateTime: time.Now(),
  473. }, &rag.WechatArticleChatRecord{
  474. WechatArticleChatRecordId: 0,
  475. WechatArticleId: wechatArticleId,
  476. ChatUserType: "assistant",
  477. Content: originalAnswer,
  478. SendTime: time.Now(),
  479. CreatedTime: time.Now(),
  480. UpdateTime: time.Now(),
  481. })
  482. return
  483. }
  484. // ArticleToKnowledge
  485. // @Description: 原文入向量库
  486. // @author: Roc
  487. // @datetime 2025-03-10 16:13:16
  488. // @param item *rag.WechatArticle
  489. func ArticleToKnowledge(item *rag.WechatArticle) {
  490. if item.TextContent == `` {
  491. return
  492. }
  493. var err error
  494. defer func() {
  495. if err != nil {
  496. utils.FileLog.Error("上传文章原文到知识库失败,err:%v", err)
  497. fmt.Println("上传文章原文到知识库失败,err:", err)
  498. }
  499. }()
  500. // 生成临时文件
  501. //dateDir := time.Now().Format("20060102")
  502. //uploadDir := utils.STATIC_DIR + "ai/article/" + dateDir
  503. uploadDir := utils.STATIC_DIR + "ai/article"
  504. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  505. if err != nil {
  506. err = fmt.Errorf("存储目录创建失败,Err:" + err.Error())
  507. return
  508. }
  509. fileName := utils.RemoveSpecialChars(item.Title) + `.md`
  510. tmpFilePath := uploadDir + "/" + fileName
  511. err = utils.SaveToFile(item.TextContent, tmpFilePath)
  512. if err != nil {
  513. err = fmt.Errorf("生成临时文件失败,Err:" + err.Error())
  514. return
  515. }
  516. defer func() {
  517. os.Remove(tmpFilePath)
  518. }()
  519. knowledgeArticleName := models.BusinessConfMap[models.KnowledgeArticleName]
  520. // 上传临时文件到LLM
  521. uploadFileResp, err := llm.UploadDocsToKnowledge(tmpFilePath, knowledgeArticleName)
  522. if err != nil {
  523. err = fmt.Errorf("上传文章原文到知识库失败,Err:" + err.Error())
  524. return
  525. }
  526. if len(uploadFileResp.FailedFiles) > 0 {
  527. for _, v := range uploadFileResp.FailedFiles {
  528. err = fmt.Errorf("上传文章原文到知识库失败,Err:" + v)
  529. }
  530. }
  531. item.VectorKey = tmpFilePath
  532. item.ModifyTime = time.Now()
  533. err = item.Update([]string{"vector_key", "modify_time"})
  534. }
  535. // AbstractToKnowledge
  536. // @Description: 摘要入向量库
  537. // @author: Roc
  538. // @datetime 2025-03-10 16:14:59
  539. // @param wechatArticleItem *rag.WechatArticle
  540. // @param abstractItem *rag.WechatArticleAbstract
  541. func AbstractToKnowledge(wechatArticleItem *rag.WechatArticle, abstractItem *rag.WechatArticleAbstract, isReUpload bool) {
  542. if abstractItem.Content == `` {
  543. return
  544. }
  545. // 已经生成了,那就不处理了
  546. if abstractItem.VectorKey != `` && !isReUpload {
  547. return
  548. }
  549. var err error
  550. defer func() {
  551. if err != nil {
  552. utils.FileLog.Error("摘要入向量库失败,err:%v", err)
  553. fmt.Println("摘要入向量库失败,err:", err)
  554. }
  555. // 数据入ES库
  556. go AddOrEditEsWechatArticleAbstract(abstractItem.WechatArticleAbstractId)
  557. }()
  558. // 生成临时文件
  559. //dateDir := time.Now().Format("20060102")
  560. //uploadDir := utils.STATIC_DIR + "ai/article/" + dateDir
  561. uploadDir := utils.STATIC_DIR + "ai/abstract"
  562. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  563. if err != nil {
  564. err = fmt.Errorf("存储目录创建失败,Err:" + err.Error())
  565. return
  566. }
  567. fileName := utils.RemoveSpecialChars(wechatArticleItem.Title) + `.md`
  568. tmpFilePath := uploadDir + "/" + fileName
  569. err = utils.SaveToFile(abstractItem.Content, tmpFilePath)
  570. if err != nil {
  571. err = fmt.Errorf("生成临时文件失败,Err:" + err.Error())
  572. return
  573. }
  574. defer func() {
  575. os.Remove(tmpFilePath)
  576. }()
  577. knowledgeArticleName := models.BusinessConfMap[models.KnowledgeBaseName]
  578. // 上传临时文件到LLM
  579. uploadFileResp, err := llm.UploadDocsToKnowledge(tmpFilePath, knowledgeArticleName)
  580. if err != nil {
  581. err = fmt.Errorf("上传文章原文到知识库失败,Err:" + err.Error())
  582. return
  583. }
  584. if len(uploadFileResp.FailedFiles) > 0 {
  585. for _, v := range uploadFileResp.FailedFiles {
  586. err = fmt.Errorf("上传文章原文到知识库失败,Err:" + v)
  587. }
  588. }
  589. abstractItem.VectorKey = tmpFilePath
  590. abstractItem.ModifyTime = time.Now()
  591. err = abstractItem.Update([]string{"vector_key", "modify_time"})
  592. }
  593. // replaceWechatPlatformPic
  594. // @Description: 替换公众号头像
  595. // @author: Roc
  596. // @datetime 2025-03-11 09:38:24
  597. // @param item *rag.WechatPlatform
  598. func replaceWechatPlatformPic(item *rag.WechatPlatform) {
  599. var err error
  600. defer func() {
  601. if err != nil {
  602. utils.FileLog.Error("替换公众号头像失败,err:%v", err)
  603. fmt.Println("替换公众号头像失败,err:", err)
  604. }
  605. }()
  606. if item.RoundHeadImg == `` {
  607. return
  608. }
  609. resourceUrl, err := downloadWxPicAndUploadToOss(item.RoundHeadImg, `head_img`)
  610. if err != nil {
  611. return
  612. }
  613. item.RoundHeadImg = resourceUrl
  614. err = item.Update([]string{"round_head_img"})
  615. }
  616. // replaceWechatArticleCoverPic
  617. // @Description: 替换文章封面图
  618. // @author: Roc
  619. // @datetime 2025-03-11 09:38:35
  620. // @param item *rag.WechatArticle
  621. func replaceWechatArticleCoverPic(item *rag.WechatArticle) {
  622. var err error
  623. defer func() {
  624. if err != nil {
  625. utils.FileLog.Error("替换公众号头像失败,err:%v", err)
  626. fmt.Println("替换公众号头像失败,err:", err)
  627. }
  628. // 数据入ES库
  629. AddOrEditEsWechatArticle(item.WechatArticleId)
  630. }()
  631. if item.CoverUrl == `` {
  632. return
  633. }
  634. resourceUrl, err := downloadWxPicAndUploadToOss(item.CoverUrl, `cover_url`)
  635. if err != nil {
  636. return
  637. }
  638. item.CoverUrl = resourceUrl
  639. err = item.Update([]string{"cover_url"})
  640. }
  641. // replaceWechatArticlePic
  642. // @Description: 替换文章内容图
  643. // @author: Roc
  644. // @datetime 2025-03-11 09:38:35
  645. // @param item *rag.WechatArticle
  646. func ReplaceWechatArticlePic(item *rag.WechatArticle) {
  647. var err error
  648. defer func() {
  649. if err != nil {
  650. utils.FileLog.Error("替换公众号头像失败,err:%v", err)
  651. fmt.Println("替换公众号头像失败,err:", err)
  652. }
  653. }()
  654. if item.Content == `` {
  655. return
  656. }
  657. content, err := ReplaceHtmlImg(html.UnescapeString(item.Content))
  658. if err != nil {
  659. return
  660. }
  661. item.Content = html.EscapeString(content)
  662. err = item.Update([]string{"content"})
  663. return
  664. }
  665. // downloadWxPicAndUploadToOss
  666. // @Description: 下载微信图片并上传到OSS
  667. // @author: Roc
  668. // @datetime 2025-03-11 09:28:49
  669. // @param wxPicUrl string
  670. // @return resourceUrl string
  671. // @return err error
  672. func downloadWxPicAndUploadToOss(wxPicUrl, source string) (resourceUrl string, err error) {
  673. localFilePath, err := utils.DownloadWxImage(wxPicUrl)
  674. if err != nil {
  675. return
  676. }
  677. defer func() {
  678. os.Remove(localFilePath)
  679. }()
  680. ossClient := NewOssClient()
  681. if ossClient == nil {
  682. err = fmt.Errorf(`初始化OSS服务失败`)
  683. return
  684. }
  685. ext := path.Ext(localFilePath)
  686. fileName := fmt.Sprintf(`%s%s%s`, time.Now().Format(utils.FormatShortDateTimeUnSpace), utils.GetRandStringNoSpecialChar(16), ext)
  687. //savePath := utils.UploadDir + `wx/wx_article/` + time.Now().Format("200601/20060102/") + fileName
  688. savePath := fmt.Sprintf(`%swx/%s/%s%s`, utils.UploadDir, source, time.Now().Format("200601/20060102/"), fileName)
  689. resourceUrl, err = ossClient.UploadFile(fileName, localFilePath, savePath)
  690. if err != nil {
  691. err = fmt.Errorf("文件上传失败,Err:" + err.Error())
  692. return
  693. }
  694. return
  695. }
  696. // ReplaceHtmlImg
  697. // @Description: 将html中的图片替换成自己的
  698. // @author: Roc
  699. // @datetime 2025-03-11 14:32:00
  700. // @param htmlStr string
  701. // @return newHtml string
  702. // @return err error
  703. func ReplaceHtmlImg(htmlStr string) (newHtml string, err error) {
  704. doc, err := html2.Parse(strings.NewReader(htmlStr))
  705. if err != nil {
  706. return
  707. }
  708. if err != nil {
  709. return
  710. }
  711. handleNode(doc)
  712. // 将处理后的HTML节点重新渲染为HTML字符串
  713. var buf bytes.Buffer
  714. if err = html2.Render(&buf, doc); err != nil {
  715. fmt.Println(err)
  716. return
  717. }
  718. newHtml = buf.String()
  719. return
  720. }
  721. // handleNode
  722. // @Description: html节点处理
  723. // @author: Roc
  724. // @datetime 2025-03-11 14:32:45
  725. // @param n *html2.Node
  726. func handleNode(n *html2.Node) {
  727. if n.Type == html2.ElementNode {
  728. if n.Data == "img" {
  729. for k, attr := range n.Attr {
  730. // 新增代码:如果标签是img且存在data-src属性,则将data-src的值赋给src
  731. if n.Data == "img" && attr.Key == "src" {
  732. resourceUrl, tmpErr := downloadWxPicAndUploadToOss(attr.Val, `article`)
  733. if tmpErr != nil {
  734. continue
  735. }
  736. attr.Val = resourceUrl
  737. }
  738. n.Attr[k] = attr
  739. }
  740. }
  741. }
  742. for c := n.FirstChild; c != nil; c = c.NextSibling {
  743. handleNode(c)
  744. }
  745. }
  746. // AddOrEditEsWechatPlatformId
  747. // @Description: 批量处理某个公众号下的文章到ES
  748. // @author: Roc
  749. // @datetime 2025-03-13 11:01:28
  750. // @param articleId int
  751. func AddOrEditEsWechatPlatformId(wechatPlatformId int) {
  752. if utils.EsWechatArticleName == `` {
  753. return
  754. }
  755. obj := rag.WechatArticle{}
  756. list, _ := obj.GetListByCondition(` wechat_article_id `, ` AND wechat_platform_id = ? `, []interface{}{wechatPlatformId}, 0, 1000000)
  757. for _, item := range list {
  758. AddOrEditEsWechatArticle(item.WechatArticleId)
  759. }
  760. }
  761. // AddOrEditEsWechatArticle
  762. // @Description: 新增/编辑微信文章入ES
  763. // @author: Roc
  764. // @datetime 2025-03-13 11:01:28
  765. // @param articleId int
  766. func AddOrEditEsWechatArticle(articleId int) {
  767. if utils.EsWechatArticleName == `` {
  768. return
  769. }
  770. var err error
  771. defer func() {
  772. if err != nil {
  773. utils.FileLog.Error("添加公众号微信信息到ES失败,err:%v", err)
  774. fmt.Println("添加公众号微信信息到ES失败,err:", err)
  775. }
  776. }()
  777. obj := rag.WechatArticle{}
  778. articleInfo, err := obj.GetById(articleId)
  779. if err != nil {
  780. err = fmt.Errorf("获取公众号文章信息失败,Err:" + err.Error())
  781. return
  782. }
  783. platformObj := rag.WechatPlatform{}
  784. platformInfo, err := platformObj.GetById(articleInfo.WechatPlatformId)
  785. if err != nil {
  786. err = fmt.Errorf("获取公众号平台信息失败,Err:" + err.Error())
  787. return
  788. }
  789. esItem := elastic.WechatArticleAndPlatform{
  790. WechatArticleId: articleInfo.WechatArticleId,
  791. WechatPlatformId: articleInfo.WechatPlatformId,
  792. FakeId: articleInfo.FakeId,
  793. Title: articleInfo.Title,
  794. Link: articleInfo.Link,
  795. CoverUrl: articleInfo.CoverUrl,
  796. Description: articleInfo.Description,
  797. //Content: articleInfo.Content,
  798. //TextContent: articleInfo.TextContent,
  799. //AbstractStatus: articleInfo.AbstractStatus,
  800. Country: articleInfo.Country,
  801. Province: articleInfo.Province,
  802. City: articleInfo.City,
  803. ArticleCreateTime: articleInfo.ArticleCreateTime,
  804. IsDeleted: articleInfo.IsDeleted,
  805. ModifyTime: articleInfo.ModifyTime,
  806. CreateTime: articleInfo.CreateTime,
  807. Nickname: platformInfo.Nickname,
  808. Alias: platformInfo.Alias,
  809. RoundHeadImg: platformInfo.RoundHeadImg,
  810. }
  811. err = elastic.WechatArticleEsAddOrEdit(strconv.Itoa(articleInfo.WechatArticleId), esItem)
  812. }
  813. // AddOrEditEsWechatArticleAbstract
  814. // @Description: 新增/编辑微信文章摘要入ES
  815. // @author: Roc
  816. // @datetime 2025-03-13 14:13:47
  817. // @param articleAbstractId int
  818. func AddOrEditEsWechatArticleAbstract(articleAbstractId int) {
  819. if utils.EsWechatArticleAbstractName == `` {
  820. return
  821. }
  822. var err error
  823. defer func() {
  824. if err != nil {
  825. utils.FileLog.Error("添加公众号微信信息到ES失败,err:%v", err)
  826. fmt.Println("添加公众号微信信息到ES失败,err:", err)
  827. }
  828. }()
  829. obj := rag.WechatArticleAbstract{}
  830. abstractInfo, err := obj.GetById(articleAbstractId)
  831. if err != nil {
  832. err = fmt.Errorf("获取公众号文章信息失败,Err:" + err.Error())
  833. return
  834. }
  835. articleObj := rag.WechatArticle{}
  836. articleInfo, err := articleObj.GetById(abstractInfo.WechatArticleId)
  837. if err != nil {
  838. err = fmt.Errorf("获取公众号文章信息失败,Err:" + err.Error())
  839. return
  840. }
  841. // 公众号平台关联的标签品种
  842. tagObj := rag.WechatPlatformTagMapping{}
  843. tagMappingList, err := tagObj.GetListByCondition(` AND wechat_platform_id = ? `, []interface{}{articleInfo.WechatPlatformId}, 0, 10000)
  844. if err != nil {
  845. err = fmt.Errorf("获取公众号平台关联的品种信息失败,Err:" + err.Error())
  846. return
  847. }
  848. tagIdList := make([]int, 0)
  849. for _, v := range tagMappingList {
  850. tagIdList = append(tagIdList, v.TagId)
  851. }
  852. esItem := elastic.WechatArticleAbstractItem{
  853. WechatArticleAbstractId: abstractInfo.WechatArticleAbstractId,
  854. WechatArticleId: abstractInfo.WechatArticleId,
  855. WechatPlatformId: articleInfo.WechatPlatformId,
  856. Abstract: abstractInfo.Content,
  857. Version: abstractInfo.Version,
  858. VectorKey: abstractInfo.VectorKey,
  859. ModifyTime: articleInfo.ModifyTime,
  860. CreateTime: articleInfo.CreateTime,
  861. Title: articleInfo.Title,
  862. Link: articleInfo.Link,
  863. TagIdList: tagIdList,
  864. }
  865. err = elastic.WechatArticleAbstractEsAddOrEdit(strconv.Itoa(articleAbstractId), esItem)
  866. }
  867. // AddOrEditEsWechatArticleAbstract
  868. // @Description: 新增/编辑微信文章摘要入ES
  869. // @author: Roc
  870. // @datetime 2025-03-13 14:13:47
  871. // @param articleAbstractId int
  872. func DelEsWechatArticleAbstract(articleAbstractId int) {
  873. if utils.EsWechatArticleAbstractName == `` {
  874. return
  875. }
  876. var err error
  877. defer func() {
  878. if err != nil {
  879. utils.FileLog.Error("添加公众号微信信息到ES失败,err:%v", err)
  880. fmt.Println("添加公众号微信信息到ES失败,err:", err)
  881. }
  882. }()
  883. err = elastic.WechatArticleAbstractEsDel(strconv.Itoa(articleAbstractId))
  884. }