smart_report.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. pdfPath := `./static/` + reportCode + ".pdf"
  294. jpegPath := `./static/` + reportCode + ".jpg"
  295. width := 1200
  296. //if reportType == 3 {
  297. // width = 800
  298. //}
  299. err = ReportToPdf(width, reportUrl, pdfPath)
  300. if err != nil {
  301. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  302. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  303. }
  304. file, err := os.Open(pdfPath)
  305. if err != nil {
  306. utils.FileLog.Info("Open failed: , error: \n" + err.Error())
  307. go alarm_msg.SendAlarmMsg("Open failed:"+err.Error(), 3)
  308. return
  309. }
  310. ext := path.Ext(file.Name())
  311. randStr := utils.GetRandStringNoSpecialChar(28)
  312. fileName := randStr + ext
  313. defer file.Close() //关闭上传文件
  314. resourceUrl := ``
  315. ossClient := NewOssClient()
  316. if ossClient == nil {
  317. utils.FileLog.Info("初始化OSS服务失败")
  318. return
  319. }
  320. resourceUrl, err = ossClient.UploadFile(fileName, pdfPath, "")
  321. if err != nil {
  322. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  323. go alarm_msg.SendAlarmMsg("文件上传失败:"+err.Error(), 3)
  324. return
  325. }
  326. defer func() {
  327. _ = os.Remove(pdfPath)
  328. }()
  329. if reportType == 3 {
  330. // 更新pdf url
  331. ob := new(smart_report.SmartReport)
  332. ob.SmartReportId = reportId
  333. ob.DetailPdfUrl = resourceUrl
  334. if err = ob.Update([]string{"DetailPdfUrl"}); err != nil {
  335. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  336. return
  337. }
  338. } else if reportType == 2 {
  339. err = models.ModifyEnglishReportPdfUrl(reportId, resourceUrl)
  340. if err != nil {
  341. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  342. return
  343. }
  344. } else if reportType == 1 {
  345. err = models.ModifyReportPdfUrl(reportId, resourceUrl)
  346. if err != nil {
  347. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  348. return
  349. }
  350. }
  351. time.Sleep(1 * time.Minute)
  352. err = ReportToJpeg(width, reportUrl, jpegPath)
  353. if err != nil {
  354. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  355. }
  356. file, err = os.Open(jpegPath)
  357. if err != nil {
  358. utils.FileLog.Info("open file failed: , error: \n" + err.Error())
  359. return
  360. }
  361. ext = path.Ext(file.Name())
  362. randStr = utils.GetRandStringNoSpecialChar(28)
  363. fileName = randStr + ext
  364. defer file.Close() //关闭上传文件
  365. resourceUrl = ``
  366. ossClient = NewOssClient()
  367. if ossClient == nil {
  368. utils.FileLog.Info("初始化OSS服务失败")
  369. return
  370. }
  371. resourceUrl, err = ossClient.UploadFile(fileName, jpegPath, "")
  372. if err != nil {
  373. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  374. return
  375. }
  376. defer func() {
  377. _ = os.Remove(jpegPath)
  378. }()
  379. if reportType == 3 {
  380. // 更新jpeg url
  381. ob := new(smart_report.SmartReport)
  382. ob.SmartReportId = reportId
  383. ob.DetailImgUrl = resourceUrl
  384. if err = ob.Update([]string{"DetailImgUrl"}); err != nil {
  385. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  386. return
  387. }
  388. } else if reportType == 2 {
  389. err = models.ModifyEnglishReportImgUrl(reportId, resourceUrl)
  390. if err != nil {
  391. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  392. return
  393. }
  394. } else if reportType == 1 {
  395. err = models.ModifyReportImgUrl(reportId, resourceUrl)
  396. if err != nil {
  397. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  398. return
  399. }
  400. }
  401. }