report_generate.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ##################################################################
  4. #
  5. # Copyright (c) 2023 CICV, Inc. All Rights Reserved
  6. #
  7. ##################################################################
  8. """
  9. @Authors: yangzihao(yangzihao@china-icv.cn)
  10. @Data: 2024/04/17
  11. @Last Modified: 2024/08/01
  12. @Summary: This file is for PDF report generate.
  13. Refer to the CSDN: https://blog.csdn.net/cainiao_python/article/details/128928298
  14. """
  15. from reportlab.pdfbase import pdfmetrics # 注册字体
  16. from reportlab.pdfbase.ttfonts import TTFont # 字体类
  17. from reportlab.platypus import Table, SimpleDocTemplate, Paragraph, Image, Spacer, PageBreak # 报告内容相关类
  18. from reportlab.lib.pagesizes import A4 # 页面的标志尺寸(8.5*inch, 11*inch)
  19. from reportlab.lib.styles import getSampleStyleSheet # 文本样式
  20. from reportlab.lib import colors # 颜色模块
  21. from reportlab.graphics.charts.barcharts import VerticalBarChart # 图表类
  22. from reportlab.graphics.charts.legends import Legend # 图例类
  23. from reportlab.graphics.shapes import Drawing # 绘图工具
  24. from reportlab.lib.units import cm # 单位:cm
  25. from reportlab.lib import utils
  26. import json
  27. import pandas as pd
  28. # 注册字体(提前准备好字体文件, 如果同一个文件需要多种字体可以注册多个)
  29. pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))
  30. pdfmetrics.registerFont(TTFont('Arial', 'arial.ttf'))
  31. class ReportPDF:
  32. """
  33. This class is for PDF report generate.
  34. """
  35. # 绘制标题
  36. @staticmethod
  37. def draw_title(title: str):
  38. # 获取所有样式表
  39. style = getSampleStyleSheet()
  40. # 拿到标题样式
  41. ct = style['Heading4']
  42. # 单独设置样式相关属性
  43. ct.fontName = 'SimSun' # 字体名
  44. ct.fontSize = 18 # 字体大小
  45. ct.leading = 24 # 行间距
  46. ct.textColor = colors.black # 字体颜色
  47. ct.alignment = 1 # 居中
  48. ct.bold = True
  49. # 创建标题对应的段落,并且返回
  50. return Paragraph(title, ct)
  51. # 绘制小标题
  52. @staticmethod
  53. def draw_little_title(title: str):
  54. # 获取所有样式表
  55. style = getSampleStyleSheet()
  56. # 拿到标题样式
  57. ct = style['Normal']
  58. # 单独设置样式相关属性
  59. ct.fontName = 'SimSun' # 字体名
  60. ct.fontSize = 15 # 字体大小
  61. # ct.leading = 15 # 行间距
  62. ct.textColor = colors.darkblue # 字体颜色
  63. # 创建标题对应的段落,并且返回
  64. return Paragraph(title, ct)
  65. # 绘制普通段落内容
  66. @staticmethod
  67. def draw_text(text: str, style_='Normal', font_size=10):
  68. # 获取所有样式表
  69. style = getSampleStyleSheet()
  70. # 获取普通样式
  71. ct = style[style_]
  72. ct.fontName = 'SimSun'
  73. ct.fontSize = font_size
  74. ct.wordWrap = 'CJK' # 设置自动换行
  75. ct.alignment = 0 # 左对齐
  76. # ct.firstLineIndent = 32 # 第一行开头空格
  77. ct.leading = 15
  78. return Paragraph(text, ct)
  79. # 绘制普通段落内容
  80. @staticmethod
  81. def draw_line_feed(text: str, font_size=10):
  82. # 获取所有样式表
  83. style = getSampleStyleSheet()
  84. # 获取普通样式
  85. ct = style['Normal']
  86. ct.fontName = 'SimSun'
  87. ct.fontSize = font_size
  88. ct.textColor = colors.white
  89. # ct.wordWrap = 'CJK' # 设置自动换行
  90. ct.alignment = 0 # 左对齐
  91. # ct.firstLineIndent = 32 # 第一行开头空格
  92. ct.leading = 15
  93. return Paragraph(text, ct)
  94. # 绘制表格
  95. @staticmethod
  96. def draw_table(*args):
  97. # 列宽度
  98. # col_width = 120
  99. style = [
  100. ('FONTNAME', (0, 0), (-1, -1), 'SimSun'), # 字体
  101. ('FONTSIZE', (0, 0), (-1, 0), 9), # 第一行的字体大小
  102. ('FONTSIZE', (0, 1), (-1, -1), 9), # 第二行到最后一行的字体大小
  103. ('BACKGROUND', (0, 0), (-1, 0), '#d5dae6'), # 设置第一行背景颜色
  104. ('BACKGROUND', (0, 0), (-1, 0), '#d5dae6'), # 设置第一行背景颜色
  105. ('ALIGN', (0, 0), (-1, -1), 'CENTER'), # 第一行水平居中
  106. ('ALIGN', (0, 1), (-1, -1), 'CENTER'), # 第二行到最后一行左右左对齐
  107. ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # 所有表格上下居中对齐
  108. ('TEXTCOLOR', (0, 0), (-1, -1), colors.darkslategray), # 设置表格内文字颜色
  109. ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), # 设置表格框线为grey色,线宽为0.5
  110. # ('SPAN', (0, 1), (0, 2)), # 合并第一列二三行
  111. # ('SPAN', (0, 3), (0, 4)), # 合并第一列三四行
  112. # ('SPAN', (0, 5), (0, 6)), # 合并第一列五六行
  113. # ('SPAN', (0, 7), (0, 8)), # 合并第一列五六行
  114. ]
  115. # table = Table(args, colWidths=col_width, style=style)
  116. table = Table(args, style=style)
  117. return table
  118. # 创建图表
  119. @staticmethod
  120. def draw_bar(bar_data: list, ax: list, items: list):
  121. drawing = Drawing(500, 250)
  122. bc = VerticalBarChart()
  123. bc.x = 45 # 整个图表的x坐标
  124. bc.y = 45 # 整个图表的y坐标
  125. bc.height = 200 # 图表的高度
  126. bc.width = 350 # 图表的宽度
  127. bc.data = bar_data
  128. bc.strokeColor = colors.black # 顶部和右边轴线的颜色
  129. bc.valueAxis.valueMin = 5000 # 设置y坐标的最小值
  130. bc.valueAxis.valueMax = 26000 # 设置y坐标的最大值
  131. bc.valueAxis.valueStep = 2000 # 设置y坐标的步长
  132. bc.categoryAxis.labels.dx = 2
  133. bc.categoryAxis.labels.dy = -8
  134. bc.categoryAxis.labels.angle = 20
  135. bc.categoryAxis.categoryNames = ax
  136. # 图示
  137. leg = Legend()
  138. leg.fontName = 'SimSun'
  139. leg.alignment = 'right'
  140. leg.boxAnchor = 'ne'
  141. leg.x = 475 # 图例的x坐标
  142. leg.y = 240
  143. leg.dxTextSpace = 10
  144. leg.columnMaximum = 3
  145. leg.colorNamePairs = items
  146. drawing.add(leg)
  147. drawing.add(bc)
  148. return drawing
  149. # 绘制图片
  150. @staticmethod
  151. def draw_img(path):
  152. img = Image(path) # 读取指定路径下的图片
  153. img.drawWidth = 0.8 * cm # 设置图片的宽度
  154. img.drawHeight = 0.8 * cm # 设置图片的高度
  155. img.hAlign = 0
  156. return img
  157. def get_trajectory_image(path, width=400):
  158. img = utils.ImageReader(path)
  159. iw, ih = img.getSize()
  160. aspect = ih / float(iw)
  161. # 按照图片限宽锁定纵横比之后计算高度
  162. height = (width * aspect)
  163. # 如果高度过高,报告可能超出此页,则限高300,宽度按比例调整
  164. HEIGHT_LIMIT = 300
  165. if height > HEIGHT_LIMIT:
  166. height = HEIGHT_LIMIT
  167. width = height / aspect
  168. return Image(path, width=width, height=height)
  169. def report_generate(reportDict, reportPdf, trackPath):
  170. # with open(f'{reportJson}', 'r', encoding='utf-8') as f:
  171. # data = json.load(f)
  172. styles = getSampleStyleSheet()
  173. style_arial = styles['Normal']
  174. style_arial.fontName = 'Arial' # 设置字体为Arial
  175. style_simsun = styles['Normal']
  176. style_simsun.fontName = 'SimSun' # 设置字体为SimSun
  177. data = reportDict # dict
  178. # 创建PDF文档
  179. # 提取数据
  180. name = data["name"]
  181. test_mileage = data["testMileage"]
  182. test_duration = data["testDuration"]
  183. algorithm_result_description = data["algorithmResultDescription"]
  184. # dimension description
  185. safe_description = data["details"]["safe"]["description"]
  186. comfort_description = data["details"]["comfort"]["description"]
  187. accurate_description = data["details"]["accurate"]["description"]
  188. efficient_description = data["details"]["efficient"]["description"]
  189. # score
  190. collisionCount_score = data["details"]["safe"]["indexes"]["collisionCount"]["score"]
  191. collisionRisk_score = data["details"]["safe"]["indexes"]["collisionRisk"]["score"]
  192. collisionSeverity_score = data["details"]["safe"]["indexes"]["collisionSeverity"]["score"]
  193. overSpeed_score = data["details"]["safe"]["indexes"]["overSpeed"]["score"]
  194. comfortzigzag_score = data["details"]["comfort"]["indexes"]["zigzag"]["score"]
  195. comfortcadence_score = data["details"]["comfort"]["indexes"]["cadence"]["score"]
  196. comfortsharpchangeofspeed_score = data["details"]["comfort"]["indexes"]["sharpchangeofspeed"]["score"]
  197. comfortSpeed_score = data["details"]["comfort"]["indexes"]["comfortSpeed"]["score"]
  198. positionError_score = data["details"]["accurate"]["indexes"]["positionError"]["score"]
  199. executeAccurateError_score = data["details"]["accurate"]["indexes"]["executeAccurateError"]["score"]
  200. efficientDrive_score = data["details"]["efficient"]["indexes"]["efficientDrive"]["score"]
  201. averageSpeed_score = data["details"]["efficient"]["indexes"]["averageSpeed"]["score"]
  202. stopDuration_score = data["details"]["efficient"]["indexes"]["obstaclestopDuration"]["score"]
  203. # metric description
  204. collisionCount_description = data["details"]["safe"]["indexes"]["collisionCount"]["description"]
  205. collisionRisk_description = data["details"]["safe"]["indexes"]["collisionRisk"]["description"]
  206. collisionSeverity_description = data["details"]["safe"]["indexes"]["collisionSeverity"]["description"]
  207. overSpeed_description = data["details"]["safe"]["indexes"]["overSpeed"]["description"]
  208. comfortzigzag_description = data["details"]["comfort"]["indexes"]["zigzag"]["description"]
  209. comfortcadence_description = data["details"]["comfort"]["indexes"]["cadence"]["description"]
  210. comfortsharpchangeofspeed_description = data["details"]["comfort"]["indexes"]["sharpchangeofspeed"]["description"]
  211. comfortSpeed_description = data["details"]["comfort"]["indexes"]["comfortSpeed"]["description"]
  212. positionError_description = data["details"]["accurate"]["indexes"]["positionError"]["description"]
  213. executeAccurateError_description = data["details"]["accurate"]["indexes"]["executeAccurateError"]["description"]
  214. efficientDrive_description = data["details"]["efficient"]["indexes"]["efficientDrive"]["description"]
  215. averageSpeed_description = data["details"]["efficient"]["indexes"]["averageSpeed"]["description"]
  216. stopDuration_description = data["details"]["efficient"]["indexes"]["obstaclestopDuration"]["description"]
  217. # score level instruction
  218. level_instruction_parts = [
  219. "说明:优秀("
  220. "<span fontName=Arial>90≤</span>"
  221. "分值"
  222. "<span fontName=Arial>≤100</span>"
  223. "),良好("
  224. "<span fontName=Arial>80≤</span>"
  225. "分值"
  226. "<span fontName=Arial><90</span>"
  227. "),一般("
  228. "<span fontName=Arial>60≤</span>"
  229. "分值"
  230. "<span fontName=Arial><80</span>"
  231. "),较差("
  232. "<span fontName=Arial>0≤</span>"
  233. "分值"
  234. "<span fontName=Arial><60</span>"
  235. ")。"
  236. ]
  237. level_instruction = " ".join(
  238. [part for part in level_instruction_parts]
  239. )
  240. # 创建表格数据
  241. table_data = [
  242. ("评价维度", "评价指标", "基准值", "权重", "分数", "指标描述"),
  243. ("安全性", "碰撞次数", "0次", "50%", "{:.02f}".format(collisionCount_score), collisionCount_description),
  244. ("安全性", "碰撞风险概率", "10%", "5%", "{:.02f}".format(collisionRisk_score), collisionRisk_description),
  245. ("安全性", "碰撞严重程度", "10%", "5%", "{:.02f}".format(collisionSeverity_score), collisionSeverity_description),
  246. ("安全性", "超速比例", "0%", "5%", "{:.02f}".format(overSpeed_score), overSpeed_description),
  247. ("平顺性", "画龙", "0次", "5%", "{:.02f}".format(comfortzigzag_score), comfortzigzag_description),
  248. ("平顺性", "顿挫", "0次", "5%", "{:.02f}".format(comfortcadence_score), comfortcadence_description),
  249. ("平顺性", "急加减速", "0次", "5%", "{:.02f}".format(comfortsharpchangeofspeed_score), comfortsharpchangeofspeed_description),
  250. ("平顺性", "指令跳变次数", "0次", "5%", "{:.02f}".format(comfortSpeed_score), comfortSpeed_description),
  251. ("准确性", "位置偏移误差", "0.3m", "5%", "{:.02f}".format(positionError_score), positionError_description),
  252. ("准确性", "任务执行错误次数", "0次", "5%", "{:.02f}".format(executeAccurateError_score), executeAccurateError_description),
  253. ("高效性", "无障碍物停止", "0次", "5%", "{:.02f}".format(efficientDrive_score), efficientDrive_description),
  254. ("高效性", "有障碍物停止", "5s", "5%", "{:.02f}".format(stopDuration_score), stopDuration_description)
  255. ]
  256. # level_instruction = " ".join(
  257. # [str(part) if not isinstance(part, Paragraph) else part for part in level_instruction_parts])
  258. # 创建内容对应的空列表
  259. content = list()
  260. content.append(ReportPDF.draw_img('Pji.png'))
  261. content.append(ReportPDF.draw_title('朴津室外AMR算法评价报告'))
  262. # content.append(ReportPDF.draw_line_feed("换行"))
  263. # content.append(ReportPDF.draw_line_feed("换行"))
  264. ### 报告内容填充
  265. # 综述
  266. base_info = f"数据包: {name}, 行驶时长: {test_duration}, 行驶里程: {test_mileage}"
  267. content.append(ReportPDF.draw_text(base_info))
  268. content.append(ReportPDF.draw_text(algorithm_result_description))
  269. content.append(ReportPDF.draw_text(safe_description))
  270. content.append(ReportPDF.draw_text(comfort_description))
  271. content.append(ReportPDF.draw_text(accurate_description))
  272. content.append(ReportPDF.draw_text(efficient_description))
  273. # for item in level_instruction_parts:
  274. # content.append(item)
  275. content.append(ReportPDF.draw_text(level_instruction))
  276. # 表格
  277. content.append(ReportPDF.draw_line_feed("换行"))
  278. content.append(ReportPDF.draw_table(*table_data))
  279. content.append(ReportPDF.draw_line_feed("换行"))
  280. # 图片
  281. # 添加图片到PDF文档
  282. content.append(PageBreak())
  283. # content.append(ReportPDF.draw_line_feed("换行"))
  284. # content.append(ReportPDF.draw_line_feed("换行"))
  285. # content.append(ReportPDF.draw_line_feed("换行"))
  286. # content.append(ReportPDF.draw_line_feed("换行"))
  287. # content.append(ReportPDF.draw_line_feed("换行"))
  288. for key, value in data["graphPath"].items():
  289. # 特判轨迹图片情况
  290. if "track.png" in value: # 评价工具生成轨迹图片
  291. trackPath = value
  292. continue
  293. if "trajectory.png" in value: # ros生成带地图轨迹图片
  294. continue
  295. content.append(ReportPDF.draw_text(key, 'Heading5'))
  296. content.append(Image(value, width=480, height=120))
  297. # content.append(ReportPDF.draw_line_feed("换行"))
  298. content.append(ReportPDF.draw_line_feed("换行"))
  299. # content.append(PageBreak())
  300. # 添加轨迹图片
  301. content.append(PageBreak())
  302. content.append(ReportPDF.draw_text("轨迹", 'Heading5'))
  303. content.append(get_trajectory_image(trackPath))
  304. if "track.png" in trackPath:
  305. content.append(
  306. ReportPDF.draw_text(" 说明:轨迹起点为黄色点,随后颜色逐渐加深。", 'Normal', 8))
  307. else:
  308. content.append(
  309. ReportPDF.draw_text(" 说明:轨迹起点为绿色点,终点为红色点。", 'Normal', 8))
  310. # content.append(ReportPDF.draw_line_feed("换行"))
  311. # content.append(ReportPDF.draw_line_feed("换行"))
  312. # 创建PDF文档
  313. pdf_file = reportPdf
  314. doc = SimpleDocTemplate(pdf_file, pagesize=A4)
  315. # 构建文档
  316. doc.build(content)
  317. print("PDF报告已生成!")
  318. if __name__ == '__main__':
  319. # reportJson = './report.json'
  320. reportJson = '/home/server/桌面/virtualEnv_yzh/virtual_pji/pji_outdoor_robot_evaluate_real-0808/task/test_0807-1/report.json'
  321. reportPdf = "./report0809.pdf"
  322. trackPath = './track.png'
  323. with open(reportJson, 'r', encoding='utf-8') as f:
  324. reportJson = json.load(f)
  325. report_generate(reportJson, reportPdf, trackPath)
  326. print('over')