smart_report.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package services
  2. import (
  3. "encoding/json"
  4. "eta_gn/eta_api/models"
  5. "eta_gn/eta_api/models/smart_report"
  6. "eta_gn/eta_api/services/alarm_msg"
  7. "eta_gn/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. @asyncio.coroutine
  133. async def main():
  134. # 异步代码
  135. browser = await launch({
  136. 'executablePath': '%s',
  137. 'headless': True,
  138. 'args': ['--disable-infobars', '--no-sandbox']
  139. })
  140. page = await browser.newPage()
  141. await page.setViewport({
  142. 'width': %d,
  143. 'height': 1080,
  144. })
  145. await page.goto('%s', {
  146. 'waitUntil': 'networkidle0',
  147. 'timeout': 3000000 # 设置超时时间为 100 秒
  148. })
  149. # 在生成PDF之前等待2秒
  150. await asyncio.sleep(10)
  151. await page.pdf({
  152. 'path': "%s",
  153. 'printBackground': True,
  154. 'format': "A2",
  155. 'margin': {
  156. 'top': '10mm',
  157. 'bottom': '10mm',
  158. 'left': '10mm',
  159. 'right': '10mm'
  160. }
  161. })
  162. await browser.close()
  163. # 创建事件循环
  164. loop = asyncio.get_event_loop()
  165. # 使用事件循环运行main函数
  166. try:
  167. loop.run_until_complete(main())
  168. finally:
  169. # 关闭事件循环
  170. loop.close()
  171. `
  172. pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, filePath)
  173. utils.FileLog.Info("pdf pyCode: \n" + pyCode)
  174. cmd := exec.Command("python3", "-c", pyCode)
  175. output, e := cmd.CombinedOutput()
  176. if e != nil {
  177. err = e
  178. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  179. utils.FileLog.Info("Output: %s\n", string(output))
  180. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  181. go alarm_msg.SendAlarmMsg("Output :"+string(output), 3)
  182. }
  183. defer func() {
  184. cmd.Process.Kill()
  185. }()
  186. return
  187. }
  188. func ReportToJpeg(width int, reportUrl, filePath string) (err error) {
  189. pyCode := `
  190. import asyncio
  191. from pyppeteer import launch, errors
  192. async def main():
  193. try:
  194. # 启动浏览器
  195. browser = await launch({
  196. 'executablePath': '%s',
  197. 'headless': True,
  198. 'args': ['--disable-infobars', '--no-sandbox']
  199. })
  200. # 新建页面
  201. page = await browser.newPage()
  202. # 设置视口大小
  203. await page.setViewport({
  204. 'width': %d,
  205. 'height': 1080
  206. })
  207. # 导航到页面
  208. await page.goto('%s', {
  209. 'waitUntil': 'networkidle0',
  210. 'timeout': 3000000 # 设置超时时间为 100 秒
  211. })
  212. # Customizing footer for page numbers starting from page 2
  213. # 在这里添加两秒的等待
  214. await asyncio.sleep(5)
  215. await page.screenshot({
  216. 'path': "%s",
  217. 'fullPage': True,
  218. 'quality':80
  219. })
  220. except errors.BrowserError as e:
  221. print('Browser closed unexpectedly:', e)
  222. except Exception as e:
  223. print('An error occurred:', e)
  224. finally:
  225. # 确保浏览器关闭
  226. if browser is not None:
  227. await browser.close()
  228. # 获取当前事件循环
  229. loop = asyncio.get_event_loop()
  230. # 运行事件循环直到main协程完成
  231. try:
  232. loop.run_until_complete(main())
  233. except Exception as e:
  234. print('Error during event loop execution:', e)
  235. finally:
  236. # 关闭事件循环
  237. loop.close()
  238. `
  239. pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, filePath)
  240. utils.FileLog.Info("jpeg pyCode: \n" + pyCode)
  241. cmd := exec.Command("python3", "-c", pyCode)
  242. output, e := cmd.CombinedOutput()
  243. if e != nil {
  244. err = e
  245. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  246. utils.FileLog.Info("Output: %s\n", string(output))
  247. go alarm_msg.SendAlarmMsg("ReportToJpeg failed:"+err.Error(), 3)
  248. go alarm_msg.SendAlarmMsg("Output :"+string(output), 3)
  249. }
  250. defer func() {
  251. cmd.Process.Kill()
  252. }()
  253. return
  254. }
  255. // Report2pdfAndJpeg
  256. // @Description: 报告转pdf和图片
  257. // @author: Roc
  258. // @datetime 2024-07-19 14:11:38
  259. // @param reportUrl string
  260. // @param reportId int
  261. // @param reportType int
  262. func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
  263. var err error
  264. defer func() {
  265. if err != nil {
  266. go alarm_msg.SendAlarmMsg("Report2pdfAndJpeg failed:"+err.Error(), 3)
  267. utils.FileLog.Info("Report2pdfAndJpeg failed: , error: \n" + err.Error())
  268. }
  269. }()
  270. if reportUrl == `` {
  271. return
  272. }
  273. // 先清空字段
  274. if reportType == 1 {
  275. err = models.UpdatePdfUrlReportById(reportId)
  276. if err != nil {
  277. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  278. return
  279. }
  280. } else if reportType == 2 {
  281. err = models.UpdatePdfUrlEnglishReportById(reportId)
  282. if err != nil {
  283. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  284. return
  285. }
  286. } else if reportType == 3 {
  287. err = smart_report.UpdatePdfUrlSmartReportById(reportId)
  288. if err != nil {
  289. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  290. return
  291. }
  292. }
  293. reportCode := utils.MD5(strconv.Itoa(reportId))
  294. pdfPath := `./static/` + reportCode + ".pdf"
  295. jpegPath := `./static/` + reportCode + ".jpg"
  296. width := 1560
  297. if reportType == 3 {
  298. width = 800
  299. }
  300. err = ReportToPdf(width, reportUrl, pdfPath)
  301. if err != nil {
  302. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  303. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  304. }
  305. file, err := os.Open(pdfPath)
  306. if err != nil {
  307. utils.FileLog.Info("Open failed: , error: \n" + err.Error())
  308. go alarm_msg.SendAlarmMsg("Open failed:"+err.Error(), 3)
  309. return
  310. }
  311. ext := path.Ext(file.Name())
  312. randStr := utils.GetRandStringNoSpecialChar(28)
  313. fileName := randStr + ext
  314. defer file.Close() //关闭上传文件
  315. resourceUrl := ``
  316. ossClient := NewOssClient()
  317. if ossClient == nil {
  318. utils.FileLog.Info("初始化OSS服务失败")
  319. return
  320. }
  321. resourceUrl, err = ossClient.UploadFile(fileName, pdfPath, "")
  322. if err != nil {
  323. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  324. go alarm_msg.SendAlarmMsg("文件上传失败:"+err.Error(), 3)
  325. return
  326. }
  327. defer func() {
  328. _ = os.Remove(pdfPath)
  329. }()
  330. if reportType == 3 {
  331. // 更新pdf url
  332. ob := new(smart_report.SmartReport)
  333. ob.SmartReportId = reportId
  334. ob.DetailPdfUrl = resourceUrl
  335. if err = ob.Update([]string{"DetailPdfUrl"}); err != nil {
  336. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  337. return
  338. }
  339. } else if reportType == 2 {
  340. err = models.ModifyEnglishReportPdfUrl(reportId, resourceUrl)
  341. if err != nil {
  342. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  343. return
  344. }
  345. } else if reportType == 1 {
  346. err = models.ModifyReportPdfUrl(reportId, resourceUrl)
  347. if err != nil {
  348. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  349. return
  350. }
  351. }
  352. time.Sleep(1 * time.Minute)
  353. err = ReportToJpeg(width, reportUrl, jpegPath)
  354. if err != nil {
  355. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  356. }
  357. file, err = os.Open(jpegPath)
  358. if err != nil {
  359. utils.FileLog.Info("open file failed: , error: \n" + err.Error())
  360. return
  361. }
  362. ext = path.Ext(file.Name())
  363. randStr = utils.GetRandStringNoSpecialChar(28)
  364. fileName = randStr + ext
  365. defer file.Close() //关闭上传文件
  366. resourceUrl = ``
  367. ossClient = NewOssClient()
  368. if ossClient == nil {
  369. utils.FileLog.Info("初始化OSS服务失败")
  370. return
  371. }
  372. resourceUrl, err = ossClient.UploadFile(fileName, jpegPath, "")
  373. if err != nil {
  374. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  375. return
  376. }
  377. defer func() {
  378. _ = os.Remove(jpegPath)
  379. }()
  380. if reportType == 3 {
  381. // 更新jpeg url
  382. ob := new(smart_report.SmartReport)
  383. ob.SmartReportId = reportId
  384. ob.DetailImgUrl = resourceUrl
  385. if err = ob.Update([]string{"DetailImgUrl"}); err != nil {
  386. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  387. return
  388. }
  389. } else if reportType == 2 {
  390. err = models.ModifyEnglishReportImgUrl(reportId, resourceUrl)
  391. if err != nil {
  392. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  393. return
  394. }
  395. } else if reportType == 1 {
  396. err = models.ModifyReportImgUrl(reportId, resourceUrl)
  397. if err != nil {
  398. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  399. return
  400. }
  401. }
  402. }