report_generate.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 = 30 # 行间距
  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):
  67. # 获取所有样式表
  68. style = getSampleStyleSheet()
  69. # 获取普通样式
  70. ct = style['Normal']
  71. ct.fontName = 'SimSun'
  72. ct.fontSize = 10
  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):
  81. # 获取所有样式表
  82. style = getSampleStyleSheet()
  83. # 获取普通样式
  84. ct = style['Normal']
  85. ct.fontName = 'SimSun'
  86. ct.fontSize = 10
  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. comfortLat_weight = data["details"]["comfort"]["indexes"]["comfortLat"]["weight"]
  190. comfortLon_weight = data["details"]["comfort"]["indexes"]["comfortLon"]["weight"]
  191. comfortSpeed_weight = data["details"]["comfort"]["indexes"]["comfortSpeed"]["weight"]
  192. positionError_weight = data["details"]["accurate"]["indexes"]["positionError"]["weight"]
  193. executeAccurateError_weight = data["details"]["accurate"]["indexes"]["executeAccurateError"]["weight"]
  194. # metric description
  195. collisionCount_description = data["details"]["safe"]["indexes"]["collisionCount"]["description"]
  196. collisionRisk_description = data["details"]["safe"]["indexes"]["collisionRisk"]["description"]
  197. collisionSeverity_description = data["details"]["safe"]["indexes"]["collisionSeverity"]["description"]
  198. overSpeed_description = data["details"]["safe"]["indexes"]["overSpeed"]["description"]
  199. comfortLat_description = data["details"]["comfort"]["indexes"]["comfortLat"]["description"]
  200. comfortLon_description = data["details"]["comfort"]["indexes"]["comfortLon"]["description"]
  201. comfortSpeed_description = data["details"]["comfort"]["indexes"]["comfortSpeed"]["description"]
  202. positionError_description = data["details"]["accurate"]["indexes"]["positionError"]["description"]
  203. executeAccurateError_description = data["details"]["accurate"]["indexes"]["executeAccurateError"]["description"]
  204. # score level instruction
  205. level_instruction = "优秀(90≤分值≤100),良好(80≤分值<90),一般(60≤分值<80),较差(0≤分值<60)。"
  206. # 创建表格数据
  207. table_data = [
  208. ("评价维度", "评价类型", "评价指标", "权重", "指标描述"),
  209. ("安全性", "碰撞安全性", "碰撞次数", collisionCount_weight, collisionCount_description),
  210. ("安全性", "碰撞安全性", "碰撞风险概率", collisionRisk_weight, collisionRisk_description),
  211. ("安全性", "碰撞安全性", "碰撞严重程度", collisionSeverity_weight, collisionSeverity_description),
  212. ("安全性", "超速安全性", "超速比例", overSpeed_weight, overSpeed_description),
  213. ("平顺性", "纵向平顺性", "线加速度", comfortLat_weight, comfortLat_description),
  214. ("平顺性", "横向平顺性", "角加速度", comfortLon_weight, comfortLon_description),
  215. ("平顺性", "速度控制指令", "速度控制指令跳变次数", comfortSpeed_weight, comfortSpeed_description),
  216. ("准确性", "执行准确性", "位置偏移误差", positionError_weight, positionError_description),
  217. ("准确性", "执行准确性", "任务执行状态错误次数", executeAccurateError_weight, executeAccurateError_description)
  218. ]
  219. # 创建内容对应的空列表
  220. content = list()
  221. content.append(ReportPDF.draw_img('Pji.png'))
  222. content.append(ReportPDF.draw_title('朴津AMR算法评价报告'))
  223. # content.append(ReportPDF.draw_line_feed("换行"))
  224. # content.append(ReportPDF.draw_line_feed("换行"))
  225. ### 报告内容填充
  226. # 综述
  227. base_info = f"数据包: {name}, 行驶时长: {test_duration}, 行驶里程: {test_mileage}"
  228. content.append(ReportPDF.draw_text(base_info))
  229. content.append(ReportPDF.draw_text(algorithm_result_description))
  230. content.append(ReportPDF.draw_text(safe_description))
  231. content.append(ReportPDF.draw_text(comfort_description))
  232. content.append(ReportPDF.draw_text(accurate_description))
  233. # 表格
  234. content.append(ReportPDF.draw_line_feed("换行"))
  235. content.append(ReportPDF.draw_table(*table_data))
  236. content.append(ReportPDF.draw_text(level_instruction))
  237. content.append(ReportPDF.draw_line_feed("换行"))
  238. # 图片
  239. # 添加图片到PDF文档
  240. for key, value in data["graphPath"].items():
  241. # 特判轨迹图片情况
  242. if "track.png" in value: # 评价工具生成轨迹图片
  243. trackPath = value
  244. continue
  245. if "trajectory.png" in value: # ros生成带地图轨迹图片
  246. continue
  247. content.append(Paragraph(key, styles['Heading5']))
  248. content.append(Image(value, width=480, height=120))
  249. content.append(ReportPDF.draw_line_feed("换行"))
  250. # content.append(ReportPDF.draw_line_feed("换行"))
  251. # content.append(ReportPDF.draw_line_feed("换行"))
  252. # content.append(ReportPDF.draw_line_feed("换行"))
  253. # 添加轨迹图片
  254. # content.append(Image(trackPath, width=300, height=200))
  255. content.append(Paragraph("trajectory", styles['Heading5']))
  256. content.append(get_trajectory_image(trackPath))
  257. content.append(ReportPDF.draw_line_feed("换行"))
  258. if "track.png" in trackPath:
  259. content.append(
  260. Paragraph("The trajectory starts with the yellow dot, then the color deepened.", styles['Normal']))
  261. else:
  262. content.append(
  263. Paragraph("The trajectory starts with the green dot and ends with the red dot.", styles['Normal']))
  264. # content.append(ReportPDF.draw_line_feed("换行"))
  265. # content.append(ReportPDF.draw_line_feed("换行"))
  266. # 创建PDF文档
  267. # pdf_file = "./report123.pdf"
  268. pdf_file = reportPdf
  269. doc = SimpleDocTemplate(pdf_file, pagesize=A4)
  270. doc.build(content)
  271. print("PDF报告已生成!")
  272. # if __name__ == '__main__':
  273. # reportJson = './report.json'
  274. # reportJson = '/home/server/桌面/virtualEnv_yzh/virtual_pji/PJI_outdoor_robot_evaluate_real/task/case0613/report.json'
  275. # reportPdf = "./report0730.pdf"
  276. # trackPath = './track.png'
  277. #
  278. # with open(reportJson, 'r', encoding='utf-8') as f:
  279. # reportJson = json.load(f)
  280. #
  281. # report_generate(reportJson, reportPdf, trackPath)
  282. # print('over')