smart_report.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. package services
  2. import (
  3. "encoding/json"
  4. "eta/eta_api/models"
  5. "eta/eta_api/models/smart_report"
  6. "eta/eta_api/services/alarm_msg"
  7. "eta/eta_api/utils"
  8. "fmt"
  9. "html"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "strconv"
  14. "time"
  15. )
  16. // SmartReportBuildVideoAndUpdate 生成音频
  17. func SmartReportBuildVideoAndUpdate(item *smart_report.SmartReport) {
  18. if item == nil {
  19. return
  20. }
  21. var err error
  22. defer func() {
  23. if err != nil {
  24. tips := fmt.Sprintf("智能研报-音频生成, errMsg: %s", err.Error())
  25. go alarm_msg.SendAlarmMsg(tips, 2)
  26. }
  27. }()
  28. videoUrl, videoName, videoSize, videoPlaySeconds, e := CreateReportVideo(item.Title, item.Content, time.Now().Local().Format(utils.FormatDateTime))
  29. if e != nil {
  30. err = fmt.Errorf("create audio err: %s", e.Error())
  31. return
  32. }
  33. item.VideoUrl = videoUrl
  34. item.VideoName = videoName
  35. item.VideoSize = videoSize
  36. item.VideoPlaySeconds = videoPlaySeconds
  37. item.ModifyTime = time.Now().Local()
  38. cols := []string{"VideoUrl", "VideoName", "VideoSize", "VideoPlaySeconds", "ModifyTime"}
  39. if e = item.Update(cols); e != nil {
  40. err = fmt.Errorf("smart report update err: %s", e.Error())
  41. return
  42. }
  43. }
  44. // UpdateSmartReportEditing 更新研报当前更新状态
  45. // status 枚举值 1:编辑中,0:完成编辑, 2:只做查询
  46. func UpdateSmartReportEditing(reportId, status, thisUserId int, thisUserName string, adminIdName map[int]string, lang string) (ret models.MarkReportResp, err error) {
  47. key := fmt.Sprint(utils.CACHE_SMART_REPORT_EDITING, reportId)
  48. ret.Status = 0
  49. ret.Msg = "无人编辑"
  50. opUserId, e := utils.Rc.RedisInt(key)
  51. var opUser models.MarkReportItem
  52. var classifyNameFirst string
  53. if e != nil {
  54. opUserInfoStr, tErr := utils.Rc.RedisString(key)
  55. if tErr == nil {
  56. tErr = json.Unmarshal([]byte(opUserInfoStr), &opUser)
  57. if tErr == nil {
  58. opUserId = opUser.AdminId
  59. }
  60. }
  61. }
  62. if opUserId > 0 && opUserId != thisUserId {
  63. editor := opUser.Editor
  64. if editor == "" {
  65. editor = adminIdName[opUserId]
  66. }
  67. ret.Status = 1
  68. if lang == utils.EnLangVersion {
  69. ret.Msg = fmt.Sprintf("%s is currently editing the report", editor)
  70. } else {
  71. ret.Msg = fmt.Sprintf("当前%s正在编辑报告", editor)
  72. }
  73. ret.Editor = editor
  74. return
  75. }
  76. if status == 1 {
  77. nowUser := &models.MarkReportItem{AdminId: thisUserId, Editor: thisUserName, ReportClassifyNameFirst: classifyNameFirst}
  78. bt, e := json.Marshal(nowUser)
  79. if e != nil {
  80. err = fmt.Errorf("格式化编辑者信息失败")
  81. return
  82. }
  83. if opUserId > 0 {
  84. utils.Rc.Do("SETEX", key, int64(180), string(bt)) //3分钟缓存
  85. } else {
  86. utils.Rc.SetNX(key, string(bt), time.Second*60*3) //3分钟缓存
  87. }
  88. } else if status == 0 {
  89. //清除编辑缓存
  90. _ = utils.Rc.Delete(key)
  91. }
  92. return
  93. }
  94. // SmartReportElasticUpsert 新增/编辑报告es
  95. func SmartReportElasticUpsert(smartReportId int, state int) (err error) {
  96. if smartReportId <= 0 {
  97. return
  98. }
  99. reportOB := new(smart_report.SmartReport)
  100. item, e := reportOB.GetItemById(smartReportId)
  101. if e != nil {
  102. if e.Error() == utils.ErrNoRow() {
  103. // 可能被删了就直接忽略掉
  104. return
  105. }
  106. err = fmt.Errorf("获取报告失败, Err: %s", e.Error())
  107. return
  108. }
  109. esReport := new(smart_report.ElasticSmartReport)
  110. esReport.SmartReportId = item.SmartReportId
  111. esReport.Title = item.Title
  112. esReport.Abstract = item.Abstract
  113. esReport.BodyContent = utils.TrimHtml(html.UnescapeString(item.Content))
  114. esReport.PublishTime = item.PublishTime.Format(utils.FormatDateTime)
  115. esReport.PublishState = state
  116. esReport.Author = item.Author
  117. esReport.ClassifyIdFirst = item.ClassifyIdFirst
  118. esReport.ClassifyNameFirst = item.ClassifyNameFirst
  119. esReport.ClassifyIdSecond = item.ClassifyIdSecond
  120. esReport.ClassifyNameSecond = item.ClassifyNameSecond
  121. esReport.StageStr = strconv.Itoa(item.Stage)
  122. esReport.Frequency = item.Frequency
  123. if err = EsAddOrEditSmartReport(utils.SmartReportIndexName, strconv.Itoa(item.SmartReportId), esReport); err != nil {
  124. return
  125. }
  126. return
  127. }
  128. func ReportToPdf(width int, reportUrl, filePath string) (err error) {
  129. pyCode := `
  130. import asyncio
  131. from pyppeteer import launch
  132. async def main():
  133. # 异步代码
  134. browser = await launch({
  135. 'executablePath': '%s',
  136. 'headless': True,
  137. 'args': ['--disable-infobars', '--no-sandbox']
  138. })
  139. page = await browser.newPage()
  140. await page.setViewport({
  141. 'width': %d,
  142. 'height': 1080,
  143. })
  144. await page.goto('%s', {
  145. 'waitUntil': 'networkidle0',
  146. 'timeout': 3000000 # 设置超时时间为 100 秒
  147. })
  148. # 在生成PDF之前等待2秒
  149. await asyncio.sleep(15)
  150. await page.pdf({
  151. 'width': %d,
  152. 'path': "%s",
  153. 'printBackground': True,
  154. 'margin': {
  155. 'top': '10mm',
  156. 'bottom': '10mm',
  157. 'left': '10mm',
  158. 'right': '10mm'
  159. }
  160. })
  161. await browser.close()
  162. # 创建事件循环
  163. loop = asyncio.get_event_loop()
  164. # 使用事件循环运行main函数
  165. try:
  166. loop.run_until_complete(main())
  167. finally:
  168. # 关闭事件循环
  169. loop.close()
  170. `
  171. pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, width, filePath)
  172. utils.FileLog.Info("pdf pyCode: \n" + pyCode)
  173. cmd := exec.Command("python3", "-c", pyCode)
  174. output, e := cmd.CombinedOutput()
  175. if e != nil {
  176. err = e
  177. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  178. utils.FileLog.Info("Output: %s\n", string(output))
  179. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  180. go alarm_msg.SendAlarmMsg("Output :"+string(output), 3)
  181. }
  182. defer func() {
  183. cmd.Process.Kill()
  184. }()
  185. return
  186. }
  187. func ReportToJpeg(width int, reportUrl, filePath string) (err error) {
  188. pyCode := `
  189. import asyncio
  190. from pyppeteer import launch, errors
  191. async def main():
  192. try:
  193. # 启动浏览器
  194. browser = await launch({
  195. 'executablePath': '%s',
  196. 'headless': True,
  197. 'args': ['--disable-infobars', '--no-sandbox']
  198. })
  199. # 新建页面
  200. page = await browser.newPage()
  201. # 设置视口大小
  202. await page.setViewport({
  203. 'width': %d,
  204. 'height': 1080
  205. })
  206. # 导航到页面
  207. await page.goto('%s', {
  208. 'waitUntil': 'networkidle0',
  209. 'timeout': 3000000 # 设置超时时间为 100 秒
  210. })
  211. # Customizing footer for page numbers starting from page 2
  212. # 在这里添加两秒的等待
  213. await asyncio.sleep(5)
  214. await page.screenshot({
  215. 'path': "%s",
  216. 'fullPage': True,
  217. 'quality':80
  218. })
  219. except errors.BrowserError as e:
  220. print('Browser closed unexpectedly:', e)
  221. except Exception as e:
  222. print('An error occurred:', e)
  223. finally:
  224. # 确保浏览器关闭
  225. if browser is not None:
  226. await browser.close()
  227. # 获取当前事件循环
  228. loop = asyncio.get_event_loop()
  229. # 运行事件循环直到main协程完成
  230. try:
  231. loop.run_until_complete(main())
  232. except Exception as e:
  233. print('Error during event loop execution:', e)
  234. finally:
  235. # 关闭事件循环
  236. loop.close()
  237. `
  238. pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, filePath)
  239. utils.FileLog.Info("jpeg pyCode: \n" + pyCode)
  240. cmd := exec.Command("python3", "-c", pyCode)
  241. output, e := cmd.CombinedOutput()
  242. if e != nil {
  243. err = e
  244. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  245. utils.FileLog.Info("Output: %s\n", string(output))
  246. go alarm_msg.SendAlarmMsg("ReportToJpeg failed:"+err.Error(), 3)
  247. go alarm_msg.SendAlarmMsg("Output :"+string(output), 3)
  248. }
  249. defer func() {
  250. cmd.Process.Kill()
  251. }()
  252. return
  253. }
  254. // Report2pdfAndJpeg
  255. // @Description: 报告转pdf和图片
  256. // @author: Roc
  257. // @datetime 2024-07-19 14:11:38
  258. // @param reportUrl string
  259. // @param reportId int
  260. // @param reportType int
  261. func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
  262. var err error
  263. defer func() {
  264. if err != nil {
  265. go alarm_msg.SendAlarmMsg("Report2pdfAndJpeg failed:"+err.Error(), 3)
  266. utils.FileLog.Info("Report2pdfAndJpeg failed: , error: \n" + err.Error())
  267. }
  268. }()
  269. if reportUrl == `` {
  270. return
  271. }
  272. // 先清空字段
  273. if reportType == 1 {
  274. err = models.UpdatePdfUrlReportById(reportId)
  275. if err != nil {
  276. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  277. return
  278. }
  279. } else if reportType == 2 {
  280. err = models.UpdatePdfUrlEnglishReportById(reportId)
  281. if err != nil {
  282. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  283. return
  284. }
  285. } else if reportType == 3 {
  286. err = smart_report.UpdatePdfUrlSmartReportById(reportId)
  287. if err != nil {
  288. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  289. return
  290. }
  291. }
  292. reportCode := utils.MD5(strconv.Itoa(reportId))
  293. // pc端
  294. go func() {
  295. pdfPath := `./static/` + reportCode + "_1200.pdf"
  296. jpegPath := `./static/` + reportCode + "_1200.jpg"
  297. width := 1200
  298. //if reportType == 3 {
  299. // width = 800
  300. //}
  301. err = ReportToPdf(width, reportUrl, pdfPath)
  302. if err != nil {
  303. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  304. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  305. }
  306. file, err := os.Open(pdfPath)
  307. if err != nil {
  308. utils.FileLog.Info("Open failed: , error: \n" + err.Error())
  309. go alarm_msg.SendAlarmMsg("Open failed:"+err.Error(), 3)
  310. return
  311. }
  312. ext := path.Ext(file.Name())
  313. randStr := utils.GetRandStringNoSpecialChar(28)
  314. fileName := randStr + ext
  315. defer file.Close() //关闭上传文件
  316. resourceUrl := ``
  317. ossClient := NewOssClient()
  318. if ossClient == nil {
  319. utils.FileLog.Info("初始化OSS服务失败")
  320. return
  321. }
  322. resourceUrl, err = ossClient.UploadFile(fileName, pdfPath, "")
  323. if err != nil {
  324. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  325. go alarm_msg.SendAlarmMsg("文件上传失败:"+err.Error(), 3)
  326. return
  327. }
  328. defer func() {
  329. _ = os.Remove(pdfPath)
  330. }()
  331. if reportType == 3 {
  332. // 更新pdf url
  333. ob := new(smart_report.SmartReport)
  334. ob.SmartReportId = reportId
  335. ob.DetailPdfUrl = resourceUrl
  336. if err = ob.Update([]string{"DetailPdfUrl"}); err != nil {
  337. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  338. return
  339. }
  340. } else if reportType == 2 {
  341. err = models.ModifyEnglishReportPdfUrl(reportId, resourceUrl)
  342. if err != nil {
  343. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  344. return
  345. }
  346. } else if reportType == 1 {
  347. err = models.ModifyReportPdfUrl(reportId, resourceUrl)
  348. if err != nil {
  349. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  350. return
  351. }
  352. }
  353. time.Sleep(1 * time.Minute)
  354. err = ReportToJpeg(width, reportUrl, jpegPath)
  355. if err != nil {
  356. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  357. }
  358. file, err = os.Open(jpegPath)
  359. if err != nil {
  360. utils.FileLog.Info("open file failed: , error: \n" + err.Error())
  361. return
  362. }
  363. ext = path.Ext(file.Name())
  364. randStr = utils.GetRandStringNoSpecialChar(28)
  365. fileName = randStr + ext
  366. defer file.Close() //关闭上传文件
  367. resourceUrl = ``
  368. ossClient = NewOssClient()
  369. if ossClient == nil {
  370. utils.FileLog.Info("初始化OSS服务失败")
  371. return
  372. }
  373. resourceUrl, err = ossClient.UploadFile(fileName, jpegPath, "")
  374. if err != nil {
  375. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  376. return
  377. }
  378. defer func() {
  379. _ = os.Remove(jpegPath)
  380. }()
  381. if reportType == 3 {
  382. // 更新jpeg url
  383. ob := new(smart_report.SmartReport)
  384. ob.SmartReportId = reportId
  385. ob.DetailImgUrl = resourceUrl
  386. if err = ob.Update([]string{"DetailImgUrl"}); err != nil {
  387. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  388. return
  389. }
  390. } else if reportType == 2 {
  391. err = models.ModifyEnglishReportImgUrl(reportId, resourceUrl)
  392. if err != nil {
  393. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  394. return
  395. }
  396. } else if reportType == 1 {
  397. err = models.ModifyReportImgUrl(reportId, resourceUrl)
  398. if err != nil {
  399. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  400. return
  401. }
  402. }
  403. }()
  404. // 移动端
  405. go func() {
  406. pdfPathMobile := `./static/` + reportCode + "_600.pdf"
  407. jpegPathMobile := `./static/` + reportCode + "_600.jpg"
  408. width := 600
  409. err = ReportToPdf(width, reportUrl, pdfPathMobile)
  410. if err != nil {
  411. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  412. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  413. }
  414. file, err := os.Open(pdfPathMobile)
  415. if err != nil {
  416. utils.FileLog.Info("Open failed: , error: \n" + err.Error())
  417. go alarm_msg.SendAlarmMsg("Open failed:"+err.Error(), 3)
  418. return
  419. }
  420. ext := path.Ext(file.Name())
  421. randStr := utils.GetRandStringNoSpecialChar(28)
  422. fileName := randStr + ext
  423. defer file.Close() //关闭上传文件
  424. resourceUrl := ``
  425. ossClient := NewOssClient()
  426. if ossClient == nil {
  427. utils.FileLog.Info("初始化OSS服务失败")
  428. return
  429. }
  430. resourceUrl, err = ossClient.UploadFile(fileName, pdfPathMobile, "")
  431. if err != nil {
  432. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  433. go alarm_msg.SendAlarmMsg("文件上传失败:"+err.Error(), 3)
  434. return
  435. }
  436. defer func() {
  437. _ = os.Remove(pdfPathMobile)
  438. }()
  439. if reportType == 3 {
  440. // 更新pdf url
  441. ob := new(smart_report.SmartReport)
  442. ob.SmartReportId = reportId
  443. ob.DetailPdfUrlMobile = resourceUrl
  444. if err = ob.Update([]string{"DetailPdfUrlMobile"}); err != nil {
  445. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  446. return
  447. }
  448. } else if reportType == 2 {
  449. err = models.ModifyEnglishReportPdfUrlMobile(reportId, resourceUrl)
  450. if err != nil {
  451. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  452. return
  453. }
  454. } else if reportType == 1 {
  455. err = models.ModifyReportPdfUrlMobile(reportId, resourceUrl)
  456. if err != nil {
  457. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  458. return
  459. }
  460. }
  461. time.Sleep(1 * time.Minute)
  462. err = ReportToJpeg(width, reportUrl, jpegPathMobile)
  463. if err != nil {
  464. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  465. }
  466. file, err = os.Open(jpegPathMobile)
  467. if err != nil {
  468. utils.FileLog.Info("open file failed: , error: \n" + err.Error())
  469. return
  470. }
  471. ext = path.Ext(file.Name())
  472. randStr = utils.GetRandStringNoSpecialChar(28)
  473. fileName = randStr + ext
  474. defer file.Close() //关闭上传文件
  475. resourceUrl = ``
  476. ossClient = NewOssClient()
  477. if ossClient == nil {
  478. utils.FileLog.Info("初始化OSS服务失败")
  479. return
  480. }
  481. resourceUrl, err = ossClient.UploadFile(fileName, jpegPathMobile, "")
  482. if err != nil {
  483. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  484. return
  485. }
  486. defer func() {
  487. _ = os.Remove(jpegPathMobile)
  488. }()
  489. if reportType == 3 {
  490. // 更新jpeg url
  491. ob := new(smart_report.SmartReport)
  492. ob.SmartReportId = reportId
  493. ob.DetailImgUrlMobile = resourceUrl
  494. if err = ob.Update([]string{"DetailImgUrlMobile"}); err != nil {
  495. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  496. return
  497. }
  498. } else if reportType == 2 {
  499. err = models.ModifyEnglishReportImgUrlMobile(reportId, resourceUrl)
  500. if err != nil {
  501. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  502. return
  503. }
  504. } else if reportType == 1 {
  505. err = models.ModifyReportImgUrlMobile(reportId, resourceUrl)
  506. if err != nil {
  507. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  508. return
  509. }
  510. }
  511. }()
  512. }