smart_report.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 utils.IsErrNoRow(e) {
  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': 1697
  144. })
  145. await page.goto('%s', {
  146. 'waitUntil': 'networkidle0',
  147. 'timeout': 3000000 # 设置超时时间为 100 秒
  148. })
  149. # 在生成PDF之前等待2秒
  150. await asyncio.sleep(15)
  151. await page.pdf({
  152. 'width': %d,
  153. 'height': 1697,
  154. 'path': "%s",
  155. 'printBackground': True,
  156. 'margin': {
  157. 'top': '20px',
  158. 'bottom': '20px',
  159. 'left': '20px',
  160. 'right': '20px'
  161. }
  162. })
  163. await browser.close()
  164. # 创建事件循环
  165. loop = asyncio.get_event_loop()
  166. # 使用事件循环运行main函数
  167. try:
  168. loop.run_until_complete(main())
  169. finally:
  170. # 关闭事件循环
  171. loop.close()
  172. `
  173. pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, width, filePath)
  174. utils.FileLog.Info("pdf pyCode: \n" + pyCode)
  175. cmd := exec.Command(utils.CommandPython, "-c", pyCode)
  176. output, e := cmd.CombinedOutput()
  177. if e != nil {
  178. err = e
  179. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  180. utils.FileLog.Info("Output: %s\n", string(output))
  181. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  182. go alarm_msg.SendAlarmMsg("Output :"+string(output), 3)
  183. }
  184. defer func() {
  185. cmd.Process.Kill()
  186. }()
  187. return
  188. }
  189. func ReportToJpeg(width int, reportUrl, filePath string) (err error) {
  190. pyCode := `
  191. import asyncio
  192. from pyppeteer import launch, errors
  193. async def main():
  194. try:
  195. # 启动浏览器
  196. browser = await launch({
  197. 'executablePath': '%s',
  198. 'headless': True,
  199. 'args': ['--disable-infobars', '--no-sandbox']
  200. })
  201. # 新建页面
  202. page = await browser.newPage()
  203. # 设置视口大小
  204. await page.setViewport({
  205. 'width': %d,
  206. 'height': 1697
  207. })
  208. # 导航到页面
  209. await page.goto('%s', {
  210. 'waitUntil': 'networkidle0',
  211. 'timeout': 3000000 # 设置超时时间为 100 秒
  212. })
  213. # Customizing footer for page numbers starting from page 2
  214. # 在这里添加两秒的等待
  215. await asyncio.sleep(5)
  216. await page.screenshot({
  217. 'path': "%s",
  218. 'fullPage': True,
  219. 'quality':80
  220. })
  221. except errors.BrowserError as e:
  222. print('Browser closed unexpectedly:', e)
  223. except Exception as e:
  224. print('An error occurred:', e)
  225. finally:
  226. # 确保浏览器关闭
  227. if browser is not None:
  228. await browser.close()
  229. # 获取当前事件循环
  230. loop = asyncio.get_event_loop()
  231. # 运行事件循环直到main协程完成
  232. try:
  233. loop.run_until_complete(main())
  234. except Exception as e:
  235. print('Error during event loop execution:', e)
  236. finally:
  237. # 关闭事件循环
  238. loop.close()
  239. `
  240. pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, filePath)
  241. utils.FileLog.Info("jpeg pyCode: \n" + pyCode)
  242. cmd := exec.Command(utils.CommandPython, "-c", pyCode)
  243. output, e := cmd.CombinedOutput()
  244. if e != nil {
  245. err = e
  246. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  247. utils.FileLog.Info("Output: %s\n", string(output))
  248. go alarm_msg.SendAlarmMsg("ReportToJpeg failed:"+err.Error(), 3)
  249. go alarm_msg.SendAlarmMsg("Output :"+string(output), 3)
  250. }
  251. defer func() {
  252. cmd.Process.Kill()
  253. }()
  254. return
  255. }
  256. // Report2pdfAndJpeg
  257. // @Description: 报告转pdf和图片
  258. // @author: Roc
  259. // @datetime 2024-07-19 14:11:38
  260. // @param reportUrl string
  261. // @param reportId int
  262. // @param reportType int
  263. func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
  264. var err error
  265. defer func() {
  266. if err != nil {
  267. go alarm_msg.SendAlarmMsg("Report2pdfAndJpeg failed:"+err.Error(), 3)
  268. utils.FileLog.Info("Report2pdfAndJpeg failed: , error: \n" + err.Error())
  269. }
  270. }()
  271. if reportUrl == `` {
  272. return
  273. }
  274. // 先清空字段
  275. if reportType == 1 {
  276. err = models.UpdatePdfUrlReportById(reportId)
  277. if err != nil {
  278. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  279. return
  280. }
  281. } else if reportType == 2 {
  282. err = models.UpdatePdfUrlEnglishReportById(reportId)
  283. if err != nil {
  284. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  285. return
  286. }
  287. } else if reportType == 3 {
  288. err = smart_report.UpdatePdfUrlSmartReportById(reportId)
  289. if err != nil {
  290. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  291. return
  292. }
  293. }
  294. reportCode := utils.MD5(strconv.Itoa(reportId))
  295. // pc端
  296. go func() {
  297. pdfPath := `./static/` + reportCode + "_1200.pdf"
  298. jpegPath := `./static/` + reportCode + "_1200.jpg"
  299. width := 1200
  300. //if reportType == 3 {
  301. // width = 800
  302. //}
  303. err = ReportToPdf(width, reportUrl, pdfPath)
  304. if err != nil {
  305. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  306. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  307. }
  308. file, err := os.Open(pdfPath)
  309. if err != nil {
  310. utils.FileLog.Info("Open failed: , error: \n" + err.Error())
  311. go alarm_msg.SendAlarmMsg("Open failed:"+err.Error(), 3)
  312. return
  313. }
  314. ext := path.Ext(file.Name())
  315. randStr := utils.GetRandStringNoSpecialChar(28)
  316. fileName := randStr + ext
  317. defer file.Close() //关闭上传文件
  318. resourceUrl := ``
  319. ossClient := NewOssClient()
  320. if ossClient == nil {
  321. utils.FileLog.Info("初始化OSS服务失败")
  322. return
  323. }
  324. resourceUrl, err = ossClient.UploadFile(fileName, pdfPath, "")
  325. if err != nil {
  326. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  327. go alarm_msg.SendAlarmMsg("文件上传失败:"+err.Error(), 3)
  328. return
  329. }
  330. defer func() {
  331. _ = os.Remove(pdfPath)
  332. }()
  333. if reportType == 3 {
  334. // 更新pdf url
  335. ob := new(smart_report.SmartReport)
  336. ob.SmartReportId = reportId
  337. ob.DetailPdfUrl = resourceUrl
  338. if err = ob.Update([]string{"DetailPdfUrl"}); err != nil {
  339. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  340. return
  341. }
  342. } else if reportType == 2 {
  343. err = models.ModifyEnglishReportPdfUrl(reportId, resourceUrl)
  344. if err != nil {
  345. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  346. return
  347. }
  348. } else if reportType == 1 {
  349. err = models.ModifyReportPdfUrl(reportId, resourceUrl)
  350. if err != nil {
  351. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  352. return
  353. }
  354. }
  355. time.Sleep(1 * time.Minute)
  356. err = ReportToJpeg(width, reportUrl, jpegPath)
  357. if err != nil {
  358. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  359. }
  360. file, err = os.Open(jpegPath)
  361. if err != nil {
  362. utils.FileLog.Info("open file failed: , error: \n" + err.Error())
  363. return
  364. }
  365. ext = path.Ext(file.Name())
  366. randStr = utils.GetRandStringNoSpecialChar(28)
  367. fileName = randStr + ext
  368. defer file.Close() //关闭上传文件
  369. resourceUrl = ``
  370. ossClient = NewOssClient()
  371. if ossClient == nil {
  372. utils.FileLog.Info("初始化OSS服务失败")
  373. return
  374. }
  375. resourceUrl, err = ossClient.UploadFile(fileName, jpegPath, "")
  376. if err != nil {
  377. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  378. return
  379. }
  380. defer func() {
  381. _ = os.Remove(jpegPath)
  382. }()
  383. if reportType == 3 {
  384. // 更新jpeg url
  385. ob := new(smart_report.SmartReport)
  386. ob.SmartReportId = reportId
  387. ob.DetailImgUrl = resourceUrl
  388. if err = ob.Update([]string{"DetailImgUrl"}); err != nil {
  389. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  390. return
  391. }
  392. } else if reportType == 2 {
  393. err = models.ModifyEnglishReportImgUrl(reportId, resourceUrl)
  394. if err != nil {
  395. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  396. return
  397. }
  398. } else if reportType == 1 {
  399. err = models.ModifyReportImgUrl(reportId, resourceUrl)
  400. if err != nil {
  401. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  402. return
  403. }
  404. }
  405. }()
  406. // 移动端
  407. go func() {
  408. pdfPathMobile := `./static/` + reportCode + "_600.pdf"
  409. jpegPathMobile := `./static/` + reportCode + "_600.jpg"
  410. width := 600
  411. err = ReportToPdf(width, reportUrl, pdfPathMobile)
  412. if err != nil {
  413. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  414. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  415. }
  416. file, err := os.Open(pdfPathMobile)
  417. if err != nil {
  418. utils.FileLog.Info("Open failed: , error: \n" + err.Error())
  419. go alarm_msg.SendAlarmMsg("Open failed:"+err.Error(), 3)
  420. return
  421. }
  422. ext := path.Ext(file.Name())
  423. randStr := utils.GetRandStringNoSpecialChar(28)
  424. fileName := randStr + ext
  425. defer file.Close() //关闭上传文件
  426. resourceUrl := ``
  427. ossClient := NewOssClient()
  428. if ossClient == nil {
  429. utils.FileLog.Info("初始化OSS服务失败")
  430. return
  431. }
  432. resourceUrl, err = ossClient.UploadFile(fileName, pdfPathMobile, "")
  433. if err != nil {
  434. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  435. go alarm_msg.SendAlarmMsg("文件上传失败:"+err.Error(), 3)
  436. return
  437. }
  438. defer func() {
  439. _ = os.Remove(pdfPathMobile)
  440. }()
  441. if reportType == 3 {
  442. // 更新pdf url
  443. ob := new(smart_report.SmartReport)
  444. ob.SmartReportId = reportId
  445. ob.DetailPdfUrlMobile = resourceUrl
  446. if err = ob.Update([]string{"DetailPdfUrlMobile"}); err != nil {
  447. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  448. return
  449. }
  450. } else if reportType == 2 {
  451. err = models.ModifyEnglishReportPdfUrlMobile(reportId, resourceUrl)
  452. if err != nil {
  453. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  454. return
  455. }
  456. } else if reportType == 1 {
  457. err = models.ModifyReportPdfUrlMobile(reportId, resourceUrl)
  458. if err != nil {
  459. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  460. return
  461. }
  462. }
  463. time.Sleep(1 * time.Minute)
  464. err = ReportToJpeg(width, reportUrl, jpegPathMobile)
  465. if err != nil {
  466. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  467. }
  468. file, err = os.Open(jpegPathMobile)
  469. if err != nil {
  470. utils.FileLog.Info("open file failed: , error: \n" + err.Error())
  471. return
  472. }
  473. ext = path.Ext(file.Name())
  474. randStr = utils.GetRandStringNoSpecialChar(28)
  475. fileName = randStr + ext
  476. defer file.Close() //关闭上传文件
  477. resourceUrl = ``
  478. ossClient = NewOssClient()
  479. if ossClient == nil {
  480. utils.FileLog.Info("初始化OSS服务失败")
  481. return
  482. }
  483. resourceUrl, err = ossClient.UploadFile(fileName, jpegPathMobile, "")
  484. if err != nil {
  485. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  486. return
  487. }
  488. defer func() {
  489. _ = os.Remove(jpegPathMobile)
  490. }()
  491. if reportType == 3 {
  492. // 更新jpeg url
  493. ob := new(smart_report.SmartReport)
  494. ob.SmartReportId = reportId
  495. ob.DetailImgUrlMobile = resourceUrl
  496. if err = ob.Update([]string{"DetailImgUrlMobile"}); err != nil {
  497. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  498. return
  499. }
  500. } else if reportType == 2 {
  501. err = models.ModifyEnglishReportImgUrlMobile(reportId, resourceUrl)
  502. if err != nil {
  503. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  504. return
  505. }
  506. } else if reportType == 1 {
  507. err = models.ModifyReportImgUrlMobile(reportId, resourceUrl)
  508. if err != nil {
  509. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  510. return
  511. }
  512. }
  513. }()
  514. }