report_generate.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 # 报告内容相关类
  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. class ReportPDF:
  31. """
  32. This class is for PDF report generate.
  33. """
  34. # 绘制标题
  35. @staticmethod
  36. def draw_title(title: str):
  37. # 获取所有样式表
  38. style = getSampleStyleSheet()
  39. # 拿到标题样式
  40. ct = style['Heading4']
  41. # 单独设置样式相关属性
  42. ct.fontName = 'SimSun' # 字体名
  43. ct.fontSize = 18 # 字体大小
  44. ct.leading = 24 # 行间距
  45. ct.textColor = colors.black # 字体颜色
  46. ct.alignment = 1 # 居中
  47. ct.bold = True
  48. # 创建标题对应的段落,并且返回
  49. return Paragraph(title, ct)
  50. # 绘制小标题
  51. @staticmethod
  52. def draw_little_title(title: str):
  53. # 获取所有样式表
  54. style = getSampleStyleSheet()
  55. # 拿到标题样式
  56. ct = style['Normal']
  57. # 单独设置样式相关属性
  58. ct.fontName = 'SimSun' # 字体名
  59. ct.fontSize = 15 # 字体大小
  60. # ct.leading = 15 # 行间距
  61. ct.textColor = colors.darkblue # 字体颜色
  62. # 创建标题对应的段落,并且返回
  63. return Paragraph(title, ct)
  64. # 绘制普通段落内容
  65. @staticmethod
  66. def draw_text(text: str, style_='Normal', font_size=10):
  67. # 获取所有样式表
  68. style = getSampleStyleSheet()
  69. # 获取普通样式
  70. ct = style[style_]
  71. ct.fontName = 'SimSun'
  72. ct.fontSize = font_size
  73. # ct.wordWrap = 'CJK' # 设置自动换行
  74. ct.alignment = 0 # 左对齐
  75. # ct.firstLineIndent = 32 # 第一行开头空格
  76. ct.leading = 15
  77. return Paragraph(text, ct)
  78. # 绘制普通段落内容
  79. @staticmethod
  80. def draw_line_feed(text: str, font_size=10):
  81. # 获取所有样式表
  82. style = getSampleStyleSheet()
  83. # 获取普通样式
  84. ct = style['Normal']
  85. ct.fontName = 'SimSun'
  86. ct.fontSize = font_size
  87. ct.textColor = colors.white
  88. # ct.wordWrap = 'CJK' # 设置自动换行
  89. ct.alignment = 0 # 左对齐
  90. # ct.firstLineIndent = 32 # 第一行开头空格
  91. ct.leading = 15
  92. return Paragraph(text, ct)
  93. # 绘制表格
  94. @staticmethod
  95. def draw_table(*args):
  96. # 列宽度
  97. # col_width = 120
  98. style = [
  99. ('FONTNAME', (0, 0), (-1, -1), 'SimSun'), # 字体
  100. ('FONTSIZE', (0, 0), (-1, 0), 9), # 第一行的字体大小
  101. ('FONTSIZE', (0, 1), (-1, -1), 9), # 第二行到最后一行的字体大小
  102. ('BACKGROUND', (0, 0), (-1, 0), '#d5dae6'), # 设置第一行背景颜色
  103. ('ALIGN', (0, 0), (-1, -1), 'CENTER'), # 第一行水平居中
  104. ('ALIGN', (0, 1), (-1, -1), 'CENTER'), # 第二行到最后一行左右左对齐
  105. ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # 所有表格上下居中对齐
  106. ('TEXTCOLOR', (0, 0), (-1, -1), colors.darkslategray), # 设置表格内文字颜色
  107. ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), # 设置表格框线为grey色,线宽为0.5
  108. # ('SPAN', (0, 1), (0, 2)), # 合并第一列二三行
  109. # ('SPAN', (0, 3), (0, 4)), # 合并第一列三四行
  110. # ('SPAN', (0, 5), (0, 6)), # 合并第一列五六行
  111. # ('SPAN', (0, 7), (0, 8)), # 合并第一列五六行
  112. ]
  113. # table = Table(args, colWidths=col_width, style=style)
  114. table = Table(args, style=style)
  115. return table
  116. # 创建图表
  117. @staticmethod
  118. def draw_bar(bar_data: list, ax: list, items: list):
  119. drawing = Drawing(500, 250)
  120. bc = VerticalBarChart()
  121. bc.x = 45 # 整个图表的x坐标
  122. bc.y = 45 # 整个图表的y坐标
  123. bc.height = 200 # 图表的高度
  124. bc.width = 350 # 图表的宽度
  125. bc.data = bar_data
  126. bc.strokeColor = colors.black # 顶部和右边轴线的颜色
  127. bc.valueAxis.valueMin = 5000 # 设置y坐标的最小值
  128. bc.valueAxis.valueMax = 26000 # 设置y坐标的最大值
  129. bc.valueAxis.valueStep = 2000 # 设置y坐标的步长
  130. bc.categoryAxis.labels.dx = 2
  131. bc.categoryAxis.labels.dy = -8
  132. bc.categoryAxis.labels.angle = 20
  133. bc.categoryAxis.categoryNames = ax
  134. # 图示
  135. leg = Legend()
  136. leg.fontName = 'SimSun'
  137. leg.alignment = 'right'
  138. leg.boxAnchor = 'ne'
  139. leg.x = 475 # 图例的x坐标
  140. leg.y = 240
  141. leg.dxTextSpace = 10
  142. leg.columnMaximum = 3
  143. leg.colorNamePairs = items
  144. drawing.add(leg)
  145. drawing.add(bc)
  146. return drawing
  147. # 绘制图片
  148. @staticmethod
  149. def draw_img(path):
  150. img = Image(path) # 读取指定路径下的图片
  151. img.drawWidth = 0.8 * cm # 设置图片的宽度
  152. img.drawHeight = 0.8 * cm # 设置图片的高度
  153. img.hAlign = 0
  154. return img
  155. def get_trajectory_image(path, width=400):
  156. img = utils.ImageReader(path)
  157. iw, ih = img.getSize()
  158. aspect = ih / float(iw)
  159. # 按照图片限宽锁定纵横比之后计算高度
  160. height = (width * aspect)
  161. # 如果高度过高,报告可能超出此页,则限高300,宽度按比例调整
  162. HEIGHT_LIMIT = 300
  163. if height > HEIGHT_LIMIT:
  164. height = HEIGHT_LIMIT
  165. width = height / aspect
  166. return Image(path, width=width, height=height)
  167. def report_generate(reportDict, reportPdf, trackPath):
  168. # with open(f'{reportJson}', 'r', encoding='utf-8') as f:
  169. # data = json.load(f)
  170. data = reportDict # dict
  171. # 创建PDF文档
  172. styles = getSampleStyleSheet()
  173. # 提取数据
  174. name = data["name"]
  175. # algorithm_score = data["algorithmComprehensiveScore"]
  176. # algorithm_level = data["algorithmLevel"]
  177. test_mileage = data["testMileage"]
  178. test_duration = data["testDuration"]
  179. algorithm_result_description = data["algorithmResultDescription"]
  180. # dimension description
  181. safe_description = data["details"]["safe"]["description"]
  182. comfort_description = data["details"]["comfort"]["description"]
  183. accurate_description = data["details"]["accurate"]["description"]
  184. # weight
  185. # collisionCount_weight = data["details"]["safe"]["indexes"]["collisionCount"]["weight"]
  186. # collisionRisk_weight = data["details"]["safe"]["indexes"]["collisionRisk"]["weight"]
  187. # collisionSeverity_weight = data["details"]["safe"]["indexes"]["collisionSeverity"]["weight"]
  188. # overSpeed_weight = data["details"]["safe"]["indexes"]["overSpeed"]["weight"]
  189. #
  190. # comfortLat_weight = data["details"]["comfort"]["indexes"]["comfortLat"]["weight"]
  191. # comfortLon_weight = data["details"]["comfort"]["indexes"]["comfortLon"]["weight"]
  192. # comfortSpeed_weight = data["details"]["comfort"]["indexes"]["comfortSpeed"]["weight"]
  193. #
  194. # positionError_weight = data["details"]["accurate"]["indexes"]["positionError"]["weight"]
  195. # executeAccurateError_weight = data["details"]["accurate"]["indexes"]["executeAccurateError"]["weight"]
  196. # score
  197. collisionCount_score = data["details"]["safe"]["indexes"]["collisionCount"]["score"]
  198. collisionRisk_score = data["details"]["safe"]["indexes"]["collisionRisk"]["score"]
  199. collisionSeverity_score = data["details"]["safe"]["indexes"]["collisionSeverity"]["score"]
  200. overSpeed_score = data["details"]["safe"]["indexes"]["overSpeed"]["score"]
  201. comfortLat_score = data["details"]["comfort"]["indexes"]["comfortLat"]["score"]
  202. comfortLon_score = data["details"]["comfort"]["indexes"]["comfortLon"]["score"]
  203. comfortSpeed_score = data["details"]["comfort"]["indexes"]["comfortSpeed"]["score"]
  204. positionError_score = data["details"]["accurate"]["indexes"]["positionError"]["score"]
  205. executeAccurateError_score = data["details"]["accurate"]["indexes"]["executeAccurateError"]["score"]
  206. # metric description
  207. collisionCount_description = data["details"]["safe"]["indexes"]["collisionCount"]["description"]
  208. collisionRisk_description = data["details"]["safe"]["indexes"]["collisionRisk"]["description"]
  209. collisionSeverity_description = data["details"]["safe"]["indexes"]["collisionSeverity"]["description"]
  210. overSpeed_description = data["details"]["safe"]["indexes"]["overSpeed"]["description"]
  211. comfortLat_description = data["details"]["comfort"]["indexes"]["comfortLat"]["description"]
  212. comfortLon_description = data["details"]["comfort"]["indexes"]["comfortLon"]["description"]
  213. comfortSpeed_description = data["details"]["comfort"]["indexes"]["comfortSpeed"]["description"]
  214. positionError_description = data["details"]["accurate"]["indexes"]["positionError"]["description"]
  215. executeAccurateError_description = data["details"]["accurate"]["indexes"]["executeAccurateError"]["description"]
  216. # score level instruction
  217. level_instruction = "优秀(90≤分值≤100),良好(80≤分值<90),一般(60≤分值<80),较差(0≤分值<60)。"
  218. # # 创建表格数据
  219. # table_data = [
  220. # ("评价维度", "评价类型", "评价指标", "权重", "指标描述"),
  221. # ("安全性", "碰撞安全性", "碰撞次数", f"{collisionCount_weight * 100}%", collisionCount_description),
  222. # ("安全性", "碰撞安全性", "碰撞风险概率", f"{collisionRisk_weight * 100}%", collisionRisk_description),
  223. # ("安全性", "碰撞安全性", "碰撞严重程度", f"{collisionSeverity_weight * 100}%", collisionSeverity_description),
  224. # ("安全性", "超速安全性", "超速比例", f"{overSpeed_weight * 100}%", overSpeed_description),
  225. # ("平顺性", "纵向平顺性", "线加速度", f"{comfortLat_weight * 100}%", comfortLat_description),
  226. # ("平顺性", "横向平顺性", "角加速度", f"{comfortLon_weight * 100}%", comfortLon_description),
  227. # ("平顺性", "速度控制指令", "速度控制指令跳变次数", f"{comfortSpeed_weight * 100}%", comfortSpeed_description),
  228. # ("准确性", "执行准确性", "位置偏移误差", f"{positionError_weight * 100}%", positionError_description),
  229. # ("准确性", "执行准确性", "任务执行状态错误次数", f"{executeAccurateError_weight * 100}%",
  230. # executeAccurateError_description)
  231. # ]
  232. # 创建表格数据
  233. table_data = [
  234. ("评价维度", "评价类型", "评价指标", "权重", "分数", "指标描述"),
  235. ("安全性", "碰撞", "碰撞次数", "60%", collisionCount_score, collisionCount_description),
  236. ("安全性", "碰撞", "碰撞风险概率", "5%", collisionRisk_score, collisionRisk_description),
  237. ("安全性", "碰撞", "碰撞严重程度", "5%", collisionSeverity_score, collisionSeverity_description),
  238. ("安全性", "超速", "超速比例", "5%", overSpeed_score, overSpeed_description),
  239. ("平顺性", "纵向", "线加速度", "5%", comfortLat_score, comfortLat_description),
  240. ("平顺性", "横向", "角加速度", "5%", comfortLon_score, comfortLon_description),
  241. ("平顺性", "速度控制", "指令跳变次数", "5%", comfortSpeed_score, comfortSpeed_description),
  242. ("准确性", "执行", "位置偏移误差", "5%", positionError_score, positionError_description),
  243. ("准确性", "执行", "任务执行错误次数", "5%", executeAccurateError_score, executeAccurateError_description)
  244. ]
  245. # 创建内容对应的空列表
  246. content = list()
  247. content.append(ReportPDF.draw_img('Pji.png'))
  248. content.append(ReportPDF.draw_title('朴津AMR算法评价报告'))
  249. # content.append(ReportPDF.draw_line_feed("换行"))
  250. # content.append(ReportPDF.draw_line_feed("换行"))
  251. ### 报告内容填充
  252. # 综述
  253. base_info = f"数据包: {name}, 行驶时长: {test_duration}, 行驶里程: {test_mileage}"
  254. content.append(ReportPDF.draw_text(base_info))
  255. content.append(ReportPDF.draw_text(algorithm_result_description))
  256. content.append(ReportPDF.draw_text(safe_description))
  257. content.append(ReportPDF.draw_text(comfort_description))
  258. content.append(ReportPDF.draw_text(accurate_description))
  259. content.append(ReportPDF.draw_text(level_instruction, style_='Normal', font_size=8))
  260. # 表格
  261. content.append(ReportPDF.draw_line_feed("换行"))
  262. content.append(ReportPDF.draw_table(*table_data))
  263. content.append(ReportPDF.draw_line_feed("换行"))
  264. # 图片
  265. # 添加图片到PDF文档
  266. for key, value in data["graphPath"].items():
  267. # 特判轨迹图片情况
  268. if "track.png" in value: # 评价工具生成轨迹图片
  269. trackPath = value
  270. continue
  271. if "trajectory.png" in value: # ros生成带地图轨迹图片
  272. continue
  273. content.append(ReportPDF.draw_text(key, 'Heading5'))
  274. content.append(Image(value, width=480, height=120))
  275. content.append(ReportPDF.draw_line_feed("换行"))
  276. # 添加轨迹图片
  277. content.append(ReportPDF.draw_text("轨迹", 'Heading5'))
  278. content.append(get_trajectory_image(trackPath))
  279. if "track.png" in trackPath:
  280. content.append(
  281. ReportPDF.draw_text(" 轨迹起点为黄色点,随后颜色逐渐加深。", 'Normal', 8))
  282. else:
  283. content.append(
  284. ReportPDF.draw_text(" 轨迹起点为绿色点,终点为红色点。", 'Normal', 8))
  285. # content.append(ReportPDF.draw_line_feed("换行"))
  286. # content.append(ReportPDF.draw_line_feed("换行"))
  287. # 创建PDF文档
  288. pdf_file = reportPdf
  289. doc = SimpleDocTemplate(pdf_file, pagesize=A4)
  290. # 构建文档
  291. doc.build(content)
  292. print("PDF报告已生成!")
  293. if __name__ == '__main__':
  294. # reportJson = './report.json'
  295. reportJson = '/home/server/桌面/virtualEnv_yzh/virtual_pji/pji_outdoor_robot_evaluate_real-0808/task/test_0807-1/report.json'
  296. reportPdf = "./report0809.pdf"
  297. trackPath = './track.png'
  298. with open(reportJson, 'r', encoding='utf-8') as f:
  299. reportJson = json.load(f)
  300. report_generate(reportJson, reportPdf, trackPath)
  301. print('over')