wechat_platform.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. _, err = abstractObj.GetByWechatArticleId(item.WechatArticleId)
  221. if err == nil {
  222. // 摘要已经生成,不需要重复生成
  223. return
  224. }
  225. if !utils.IsErrNoRow(err) {
  226. return
  227. }
  228. // 生成临时文件
  229. dateDir := time.Now().Format("20060102")
  230. uploadDir := utils.STATIC_DIR + "ai/" + dateDir
  231. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  232. if err != nil {
  233. err = fmt.Errorf("存储目录创建失败,Err:" + err.Error())
  234. return
  235. }
  236. randStr := utils.GetRandStringNoSpecialChar(28)
  237. fileName := randStr + `.md`
  238. tmpFilePath := uploadDir + "/" + fileName
  239. err = utils.SaveToFile(item.TextContent, tmpFilePath)
  240. if err != nil {
  241. err = fmt.Errorf("生成临时文件失败,Err:" + err.Error())
  242. return
  243. }
  244. defer func() {
  245. os.Remove(tmpFilePath)
  246. }()
  247. // 上传临时文件到LLM
  248. tmpFileResp, err := llm.UploadTempDocs(tmpFilePath)
  249. if err != nil {
  250. err = fmt.Errorf("上传临时文件到LLM失败,Err:" + err.Error())
  251. return
  252. }
  253. if tmpFileResp.Data.Id == `` {
  254. err = fmt.Errorf("上传临时文件到LLM失败,Err:上传失败")
  255. return
  256. }
  257. tmpDocId := tmpFileResp.Data.Id
  258. //tmpDocId := `c4d2ee902808408c8b8ed398b33be103` // 钢材
  259. //tmpDocId := `2dde8afe62d24525a814e74e0a5e35e4` // 钢材
  260. //tmpDocId := `7634cc1086c04b3687682220a2cf1a48` //
  261. //开始对话
  262. abstract, addArticleChatRecordList, tmpErr := getAnswerByContent(item.WechatArticleId, tmpDocId)
  263. if tmpErr != nil {
  264. err = fmt.Errorf("LLM对话失败,Err:" + tmpErr.Error())
  265. return
  266. }
  267. // 添加问答记录
  268. if len(addArticleChatRecordList) > 0 {
  269. recordObj := rag.WechatArticleChatRecord{}
  270. err = recordObj.CreateInBatches(addArticleChatRecordList)
  271. if err != nil {
  272. return
  273. }
  274. }
  275. if abstract != `` {
  276. if abstract == `sorry` || strings.Index(abstract, `根据已知信息无法回答该问题`) == 0 {
  277. item.AbstractStatus = 2
  278. item.ModifyTime = time.Now()
  279. err = item.Update([]string{"AbstractStatus", "ModifyTime"})
  280. return
  281. }
  282. item.AbstractStatus = 1
  283. item.ModifyTime = time.Now()
  284. err = item.Update([]string{"AbstractStatus", "ModifyTime"})
  285. abstractItem := &rag.WechatArticleAbstract{
  286. WechatArticleAbstractId: 0,
  287. WechatArticleId: item.WechatArticleId,
  288. Content: abstract,
  289. Version: 0,
  290. VectorKey: "",
  291. ModifyTime: time.Now(),
  292. CreateTime: time.Now(),
  293. }
  294. err = abstractItem.Create()
  295. if err != nil {
  296. return
  297. }
  298. AbstractToKnowledge(item, abstractItem, false)
  299. }
  300. }
  301. // ReGenerateArticleAbstract
  302. // @Description: 文章摘要重新生成
  303. // @author: Roc
  304. // @datetime 2025-03-10 16:17:53
  305. // @param item *rag.WechatArticle
  306. func ReGenerateArticleAbstract(item *rag.WechatArticle) {
  307. var err error
  308. defer func() {
  309. if err != nil {
  310. utils.FileLog.Error("文章转临时文件失败,err:%v", err)
  311. fmt.Println("文章转临时文件失败,err:", err)
  312. }
  313. }()
  314. abstractObj := rag.WechatArticleAbstract{}
  315. abstractItem, err := abstractObj.GetByWechatArticleId(item.WechatArticleId)
  316. if err != nil {
  317. if utils.IsErrNoRow(err) {
  318. // 直接生成
  319. GenerateArticleAbstract(item)
  320. return
  321. }
  322. // 异常了
  323. return
  324. }
  325. // 生成临时文件
  326. dateDir := time.Now().Format("20060102")
  327. uploadDir := utils.STATIC_DIR + "ai/" + dateDir
  328. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  329. if err != nil {
  330. err = fmt.Errorf("存储目录创建失败,Err:" + err.Error())
  331. return
  332. }
  333. randStr := utils.GetRandStringNoSpecialChar(28)
  334. fileName := randStr + `.md`
  335. tmpFilePath := uploadDir + "/" + fileName
  336. err = utils.SaveToFile(item.TextContent, tmpFilePath)
  337. if err != nil {
  338. err = fmt.Errorf("生成临时文件失败,Err:" + err.Error())
  339. return
  340. }
  341. defer func() {
  342. os.Remove(tmpFilePath)
  343. }()
  344. // 上传临时文件到LLM
  345. tmpFileResp, err := llm.UploadTempDocs(tmpFilePath)
  346. if err != nil {
  347. err = fmt.Errorf("上传临时文件到LLM失败,Err:" + err.Error())
  348. return
  349. }
  350. if tmpFileResp.Data.Id == `` {
  351. err = fmt.Errorf("上传临时文件到LLM失败,Err:上传失败")
  352. return
  353. }
  354. tmpDocId := tmpFileResp.Data.Id
  355. //tmpDocId := `c4d2ee902808408c8b8ed398b33be103` // 钢材
  356. //tmpDocId := `2dde8afe62d24525a814e74e0a5e35e4` // 钢材
  357. //tmpDocId := `7634cc1086c04b3687682220a2cf1a48` //
  358. //开始对话
  359. abstract, addArticleChatRecordList, tmpErr := getAnswerByContent(item.WechatArticleId, tmpDocId)
  360. if tmpErr != nil {
  361. err = fmt.Errorf("LLM对话失败,Err:" + tmpErr.Error())
  362. return
  363. }
  364. // 添加问答记录
  365. if len(addArticleChatRecordList) > 0 {
  366. recordObj := rag.WechatArticleChatRecord{}
  367. err = recordObj.CreateInBatches(addArticleChatRecordList)
  368. if err != nil {
  369. return
  370. }
  371. }
  372. if abstract != `` {
  373. if abstract == `sorry` || strings.Index(abstract, `根据已知信息无法回答该问题`) == 0 {
  374. item.AbstractStatus = 2
  375. item.ModifyTime = time.Now()
  376. err = item.Update([]string{"AbstractStatus", "ModifyTime"})
  377. return
  378. }
  379. item.AbstractStatus = 1
  380. item.ModifyTime = time.Now()
  381. err = item.Update([]string{"AbstractStatus", "ModifyTime"})
  382. abstractItem.Content = abstract
  383. abstractItem.Version = abstractObj.Version + 1
  384. abstractItem.ModifyTime = time.Now()
  385. err = abstractItem.Update([]string{"content", "version", "modify_time"})
  386. if err != nil {
  387. return
  388. }
  389. AbstractToKnowledge(item, abstractItem, true)
  390. }
  391. }
  392. // DelDoc
  393. // @Description: 删除摘要向量库
  394. // @author: Roc
  395. // @datetime 2025-03-12 16:55:05
  396. // @param wechatArticleAbstractList []*rag.WechatArticleAbstract
  397. // @return err error
  398. func DelDoc(wechatArticleAbstractList []*rag.WechatArticleAbstract) (err error) {
  399. defer func() {
  400. if err != nil {
  401. utils.FileLog.Error("删除摘要向量库文件失败,err:%v", err)
  402. fmt.Println("删除摘要向量库文件失败,err:", err)
  403. }
  404. }()
  405. vectorKeyList := make([]string, 0)
  406. wechatArticleAbstractIdList := make([]int, 0)
  407. for _, v := range wechatArticleAbstractList {
  408. vectorKeyList = append(vectorKeyList, v.VectorKey)
  409. wechatArticleAbstractIdList = append(wechatArticleAbstractIdList, v.WechatArticleAbstractId)
  410. }
  411. _, err = llm.DelDocsToKnowledge(models.BusinessConfMap[models.KnowledgeBaseName], vectorKeyList)
  412. if err != nil {
  413. err = fmt.Errorf("删除LLM摘要向量库文件失败,Err:" + err.Error())
  414. return
  415. }
  416. //fmt.Println(resp)
  417. obj := rag.WechatArticleAbstract{}
  418. err = obj.DelVectorKey(wechatArticleAbstractIdList)
  419. return
  420. }
  421. func getAnswerByContent(wechatArticleId int, docId string) (answer string, addArticleChatRecordList []*rag.WechatArticleChatRecord, err error) {
  422. historyList := make([]eta_llm_http.HistoryContent, 0)
  423. addArticleChatRecordList = make([]*rag.WechatArticleChatRecord, 0)
  424. questionObj := rag.Question{}
  425. questionList, err := questionObj.GetListByCondition(``, []interface{}{}, 0, 100)
  426. if err != nil {
  427. err = fmt.Errorf("获取问题列表失败,Err:" + err.Error())
  428. return
  429. }
  430. //你现在是一名资深的期货行业分析师,请基于以下的问题进行汇总总结,如果不能正常总结出来,那么就只需要回复我:sorry
  431. questionStrList := []string{`你现在是一名资深的期货行业分析师,请基于以下的问题进行汇总总结,如果不能正常总结出来,那么就只需要回复我:sorry。以下是问题:`}
  432. for _, v := range questionList {
  433. questionStrList = append(questionStrList, v.QuestionContent)
  434. }
  435. questionStr := strings.Join(questionStrList, "\n")
  436. originalAnswer, result, err := llm.ChatByFile(docId, questionStr, historyList)
  437. fmt.Println(result)
  438. if err != nil {
  439. err = fmt.Errorf("LLM对话失败,Err:" + err.Error())
  440. return
  441. }
  442. // 提取 </think> 后面的内容
  443. thinkEndIndex := strings.Index(result.Answer, "</think>")
  444. if thinkEndIndex != -1 {
  445. answer = strings.TrimSpace(result.Answer[thinkEndIndex+len("</think>"):])
  446. } else {
  447. answer = result.Answer
  448. }
  449. answer = strings.TrimSpace(answer)
  450. // 待入库的数据
  451. addArticleChatRecordList = append(addArticleChatRecordList, &rag.WechatArticleChatRecord{
  452. WechatArticleChatRecordId: 0,
  453. WechatArticleId: wechatArticleId,
  454. ChatUserType: "user",
  455. Content: questionStr,
  456. SendTime: time.Now(),
  457. CreatedTime: time.Now(),
  458. UpdateTime: time.Now(),
  459. }, &rag.WechatArticleChatRecord{
  460. WechatArticleChatRecordId: 0,
  461. WechatArticleId: wechatArticleId,
  462. ChatUserType: "assistant",
  463. Content: originalAnswer,
  464. SendTime: time.Now(),
  465. CreatedTime: time.Now(),
  466. UpdateTime: time.Now(),
  467. })
  468. return
  469. }
  470. // ArticleToKnowledge
  471. // @Description: 原文入向量库
  472. // @author: Roc
  473. // @datetime 2025-03-10 16:13:16
  474. // @param item *rag.WechatArticle
  475. func ArticleToKnowledge(item *rag.WechatArticle) {
  476. if item.TextContent == `` {
  477. return
  478. }
  479. var err error
  480. defer func() {
  481. if err != nil {
  482. utils.FileLog.Error("上传文章原文到知识库失败,err:%v", err)
  483. fmt.Println("上传文章原文到知识库失败,err:", err)
  484. }
  485. }()
  486. // 生成临时文件
  487. //dateDir := time.Now().Format("20060102")
  488. //uploadDir := utils.STATIC_DIR + "ai/article/" + dateDir
  489. uploadDir := utils.STATIC_DIR + "ai/article"
  490. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  491. if err != nil {
  492. err = fmt.Errorf("存储目录创建失败,Err:" + err.Error())
  493. return
  494. }
  495. fileName := utils.RemoveSpecialChars(item.Title) + `.md`
  496. tmpFilePath := uploadDir + "/" + fileName
  497. err = utils.SaveToFile(item.TextContent, tmpFilePath)
  498. if err != nil {
  499. err = fmt.Errorf("生成临时文件失败,Err:" + err.Error())
  500. return
  501. }
  502. defer func() {
  503. os.Remove(tmpFilePath)
  504. }()
  505. knowledgeArticleName := models.BusinessConfMap[models.KnowledgeArticleName]
  506. // 上传临时文件到LLM
  507. uploadFileResp, err := llm.UploadDocsToKnowledge(tmpFilePath, knowledgeArticleName)
  508. if err != nil {
  509. err = fmt.Errorf("上传文章原文到知识库失败,Err:" + err.Error())
  510. return
  511. }
  512. if len(uploadFileResp.FailedFiles) > 0 {
  513. for _, v := range uploadFileResp.FailedFiles {
  514. err = fmt.Errorf("上传文章原文到知识库失败,Err:" + v)
  515. }
  516. }
  517. item.VectorKey = tmpFilePath
  518. item.ModifyTime = time.Now()
  519. err = item.Update([]string{"vector_key", "modify_time"})
  520. }
  521. // AbstractToKnowledge
  522. // @Description: 摘要入向量库
  523. // @author: Roc
  524. // @datetime 2025-03-10 16:14:59
  525. // @param wechatArticleItem *rag.WechatArticle
  526. // @param item *rag.WechatArticleAbstract
  527. func AbstractToKnowledge(wechatArticleItem *rag.WechatArticle, item *rag.WechatArticleAbstract, isReUpload bool) {
  528. if item.Content == `` {
  529. return
  530. }
  531. // 已经生成了,那就不处理了
  532. if item.VectorKey != `` && !isReUpload {
  533. return
  534. }
  535. var err error
  536. defer func() {
  537. if err != nil {
  538. utils.FileLog.Error("摘要入向量库失败,err:%v", err)
  539. fmt.Println("摘要入向量库失败,err:", err)
  540. }
  541. }()
  542. // 生成临时文件
  543. //dateDir := time.Now().Format("20060102")
  544. //uploadDir := utils.STATIC_DIR + "ai/article/" + dateDir
  545. uploadDir := utils.STATIC_DIR + "ai/abstract"
  546. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  547. if err != nil {
  548. err = fmt.Errorf("存储目录创建失败,Err:" + err.Error())
  549. return
  550. }
  551. fileName := utils.RemoveSpecialChars(wechatArticleItem.Title) + `.md`
  552. tmpFilePath := uploadDir + "/" + fileName
  553. err = utils.SaveToFile(item.Content, tmpFilePath)
  554. if err != nil {
  555. err = fmt.Errorf("生成临时文件失败,Err:" + err.Error())
  556. return
  557. }
  558. defer func() {
  559. os.Remove(tmpFilePath)
  560. }()
  561. knowledgeArticleName := models.BusinessConfMap[models.KnowledgeBaseName]
  562. // 上传临时文件到LLM
  563. uploadFileResp, err := llm.UploadDocsToKnowledge(tmpFilePath, knowledgeArticleName)
  564. if err != nil {
  565. err = fmt.Errorf("上传文章原文到知识库失败,Err:" + err.Error())
  566. return
  567. }
  568. if len(uploadFileResp.FailedFiles) > 0 {
  569. for _, v := range uploadFileResp.FailedFiles {
  570. err = fmt.Errorf("上传文章原文到知识库失败,Err:" + v)
  571. }
  572. }
  573. item.VectorKey = tmpFilePath
  574. item.ModifyTime = time.Now()
  575. err = item.Update([]string{"vector_key", "modify_time"})
  576. }
  577. // replaceWechatPlatformPic
  578. // @Description: 替换公众号头像
  579. // @author: Roc
  580. // @datetime 2025-03-11 09:38:24
  581. // @param item *rag.WechatPlatform
  582. func replaceWechatPlatformPic(item *rag.WechatPlatform) {
  583. var err error
  584. defer func() {
  585. if err != nil {
  586. utils.FileLog.Error("替换公众号头像失败,err:%v", err)
  587. fmt.Println("替换公众号头像失败,err:", err)
  588. }
  589. }()
  590. if item.RoundHeadImg == `` {
  591. return
  592. }
  593. resourceUrl, err := downloadWxPicAndUploadToOss(item.RoundHeadImg, `head_img`)
  594. if err != nil {
  595. return
  596. }
  597. item.RoundHeadImg = resourceUrl
  598. err = item.Update([]string{"round_head_img"})
  599. }
  600. // replaceWechatArticleCoverPic
  601. // @Description: 替换文章封面图
  602. // @author: Roc
  603. // @datetime 2025-03-11 09:38:35
  604. // @param item *rag.WechatArticle
  605. func replaceWechatArticleCoverPic(item *rag.WechatArticle) {
  606. var err error
  607. defer func() {
  608. if err != nil {
  609. utils.FileLog.Error("替换公众号头像失败,err:%v", err)
  610. fmt.Println("替换公众号头像失败,err:", err)
  611. }
  612. // 数据入ES库
  613. AddOrEditEsWechatArticle(item.WechatArticleId)
  614. }()
  615. if item.CoverUrl == `` {
  616. return
  617. }
  618. resourceUrl, err := downloadWxPicAndUploadToOss(item.CoverUrl, `cover_url`)
  619. if err != nil {
  620. return
  621. }
  622. item.CoverUrl = resourceUrl
  623. err = item.Update([]string{"cover_url"})
  624. }
  625. // replaceWechatArticlePic
  626. // @Description: 替换文章内容图
  627. // @author: Roc
  628. // @datetime 2025-03-11 09:38:35
  629. // @param item *rag.WechatArticle
  630. func ReplaceWechatArticlePic(item *rag.WechatArticle) {
  631. var err error
  632. defer func() {
  633. if err != nil {
  634. utils.FileLog.Error("替换公众号头像失败,err:%v", err)
  635. fmt.Println("替换公众号头像失败,err:", err)
  636. }
  637. }()
  638. if item.Content == `` {
  639. return
  640. }
  641. content, err := ReplaceHtmlImg(html.UnescapeString(item.Content))
  642. if err != nil {
  643. return
  644. }
  645. item.Content = html.EscapeString(content)
  646. err = item.Update([]string{"content"})
  647. return
  648. }
  649. // downloadWxPicAndUploadToOss
  650. // @Description: 下载微信图片并上传到OSS
  651. // @author: Roc
  652. // @datetime 2025-03-11 09:28:49
  653. // @param wxPicUrl string
  654. // @return resourceUrl string
  655. // @return err error
  656. func downloadWxPicAndUploadToOss(wxPicUrl, source string) (resourceUrl string, err error) {
  657. localFilePath, err := utils.DownloadWxImage(wxPicUrl)
  658. if err != nil {
  659. return
  660. }
  661. defer func() {
  662. os.Remove(localFilePath)
  663. }()
  664. ossClient := NewOssClient()
  665. if ossClient == nil {
  666. err = fmt.Errorf(`初始化OSS服务失败`)
  667. return
  668. }
  669. ext := path.Ext(localFilePath)
  670. fileName := fmt.Sprintf(`%s%s%s`, time.Now().Format(utils.FormatShortDateTimeUnSpace), utils.GetRandStringNoSpecialChar(16), ext)
  671. //savePath := utils.UploadDir + `wx/wx_article/` + time.Now().Format("200601/20060102/") + fileName
  672. savePath := fmt.Sprintf(`%swx/%s/%s%s`, utils.UploadDir, source, time.Now().Format("200601/20060102/"), fileName)
  673. resourceUrl, err = ossClient.UploadFile(fileName, localFilePath, savePath)
  674. if err != nil {
  675. err = fmt.Errorf("文件上传失败,Err:" + err.Error())
  676. return
  677. }
  678. return
  679. }
  680. // ReplaceHtmlImg
  681. // @Description: 将html中的图片替换成自己的
  682. // @author: Roc
  683. // @datetime 2025-03-11 14:32:00
  684. // @param htmlStr string
  685. // @return newHtml string
  686. // @return err error
  687. func ReplaceHtmlImg(htmlStr string) (newHtml string, err error) {
  688. doc, err := html2.Parse(strings.NewReader(htmlStr))
  689. if err != nil {
  690. return
  691. }
  692. if err != nil {
  693. return
  694. }
  695. handleNode(doc)
  696. // 将处理后的HTML节点重新渲染为HTML字符串
  697. var buf bytes.Buffer
  698. if err = html2.Render(&buf, doc); err != nil {
  699. fmt.Println(err)
  700. return
  701. }
  702. newHtml = buf.String()
  703. return
  704. }
  705. // handleNode
  706. // @Description: html节点处理
  707. // @author: Roc
  708. // @datetime 2025-03-11 14:32:45
  709. // @param n *html2.Node
  710. func handleNode(n *html2.Node) {
  711. if n.Type == html2.ElementNode {
  712. if n.Data == "img" {
  713. for k, attr := range n.Attr {
  714. // 新增代码:如果标签是img且存在data-src属性,则将data-src的值赋给src
  715. if n.Data == "img" && attr.Key == "src" {
  716. resourceUrl, tmpErr := downloadWxPicAndUploadToOss(attr.Val, `article`)
  717. if tmpErr != nil {
  718. continue
  719. }
  720. attr.Val = resourceUrl
  721. }
  722. n.Attr[k] = attr
  723. }
  724. }
  725. }
  726. for c := n.FirstChild; c != nil; c = c.NextSibling {
  727. handleNode(c)
  728. }
  729. }
  730. // AddOrEditEsWechatPlatformId
  731. // @Description: 批量处理某个公众号下的文章到ES
  732. // @author: Roc
  733. // @datetime 2025-03-13 11:01:28
  734. // @param articleId int
  735. func AddOrEditEsWechatPlatformId(wechatPlatformId int) {
  736. if utils.EsWechatArticleName == `` {
  737. return
  738. }
  739. obj := rag.WechatArticle{}
  740. list, _ := obj.GetListByCondition(` wechat_article_id `, ` AND wechat_platform_id = ? `, []interface{}{wechatPlatformId}, 0, 1000000)
  741. for _, item := range list {
  742. AddOrEditEsWechatArticle(item.WechatArticleId)
  743. }
  744. }
  745. // AddOrEditEsWechatArticle
  746. // @Description: 新增/编辑微信文章入ES
  747. // @author: Roc
  748. // @datetime 2025-03-13 11:01:28
  749. // @param articleId int
  750. func AddOrEditEsWechatArticle(articleId int) {
  751. if utils.EsWechatArticleName == `` {
  752. return
  753. }
  754. var err error
  755. defer func() {
  756. if err != nil {
  757. utils.FileLog.Error("添加公众号微信信息到ES失败,err:%v", err)
  758. fmt.Println("添加公众号微信信息到ES失败,err:", err)
  759. }
  760. }()
  761. obj := rag.WechatArticle{}
  762. articleInfo, err := obj.GetById(articleId)
  763. if err != nil {
  764. err = fmt.Errorf("获取公众号文章信息失败,Err:" + err.Error())
  765. return
  766. }
  767. platformObj := rag.WechatPlatform{}
  768. platformInfo, err := platformObj.GetById(articleInfo.WechatPlatformId)
  769. if err != nil {
  770. err = fmt.Errorf("获取公众号文章信息失败,Err:" + err.Error())
  771. return
  772. }
  773. esItem := elastic.WechatArticleAndPlatform{
  774. WechatArticleId: articleInfo.WechatArticleId,
  775. WechatPlatformId: articleInfo.WechatPlatformId,
  776. FakeId: articleInfo.FakeId,
  777. Title: articleInfo.Title,
  778. Link: articleInfo.Link,
  779. CoverUrl: articleInfo.CoverUrl,
  780. Description: articleInfo.Description,
  781. //Content: articleInfo.Content,
  782. //TextContent: articleInfo.TextContent,
  783. //AbstractStatus: articleInfo.AbstractStatus,
  784. Country: articleInfo.Country,
  785. Province: articleInfo.Province,
  786. City: articleInfo.City,
  787. ArticleCreateTime: articleInfo.ArticleCreateTime,
  788. IsDeleted: articleInfo.IsDeleted,
  789. ModifyTime: articleInfo.ModifyTime,
  790. CreateTime: articleInfo.CreateTime,
  791. Nickname: platformInfo.Nickname,
  792. Alias: platformInfo.Alias,
  793. RoundHeadImg: platformInfo.RoundHeadImg,
  794. }
  795. err = elastic.WechatArticleEsAddOrEdit(strconv.Itoa(articleInfo.WechatArticleId), esItem)
  796. }