report_generate_1122.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. 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 = 'arial'
  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. data = reportDict # dict
  173. # 创建PDF文档
  174. styles = getSampleStyleSheet()
  175. # 提取数据
  176. name = data["name"]
  177. # algorithm_score = data["algorithmComprehensiveScore"]
  178. # algorithm_level = data["algorithmLevel"]
  179. test_mileage = data["testMileage"]
  180. test_duration = data["testDuration"]
  181. algorithm_result_description = data["algorithmResultDescription"]
  182. # dimension description
  183. safe_description = data["details"]["safe"]["description"]
  184. comfort_description = data["details"]["comfort"]["description"]
  185. accurate_description = data["details"]["accurate"]["description"]
  186. efficient_description = data["details"]["efficient"]["description"]
  187. # weight
  188. # collisionCount_weight = data["details"]["safe"]["indexes"]["collisionCount"]["weight"]
  189. # collisionRisk_weight = data["details"]["safe"]["indexes"]["collisionRisk"]["weight"]
  190. # collisionSeverity_weight = data["details"]["safe"]["indexes"]["collisionSeverity"]["weight"]
  191. # overSpeed_weight = data["details"]["safe"]["indexes"]["overSpeed"]["weight"]
  192. #
  193. # comfortLat_weight = data["details"]["comfort"]["indexes"]["comfortLat"]["weight"]
  194. # comfortLon_weight = data["details"]["comfort"]["indexes"]["comfortLon"]["weight"]
  195. # comfortSpeed_weight = data["details"]["comfort"]["indexes"]["comfortSpeed"]["weight"]
  196. #
  197. # positionError_weight = data["details"]["accurate"]["indexes"]["positionError"]["weight"]
  198. # executeAccurateError_weight = data["details"]["accurate"]["indexes"]["executeAccurateError"]["weight"]
  199. # score
  200. collisionCount_score = data["details"]["safe"]["indexes"]["collisionCount"]["score"]
  201. collisionRisk_score = data["details"]["safe"]["indexes"]["collisionRisk"]["score"]
  202. collisionSeverity_score = data["details"]["safe"]["indexes"]["collisionSeverity"]["score"]
  203. overSpeed_score = data["details"]["safe"]["indexes"]["overSpeed"]["score"]
  204. comfortzigzag_score = data["details"]["comfort"]["indexes"]["zigzag"]["score"]
  205. comfortcadence_score = data["details"]["comfort"]["indexes"]["cadence"]["score"]
  206. comfortsharpchangeofspeed_score = data["details"]["comfort"]["indexes"]["sharpchangeofspeed"]["score"]
  207. comfortSpeed_score = data["details"]["comfort"]["indexes"]["comfortSpeed"]["score"]
  208. positionError_score = data["details"]["accurate"]["indexes"]["positionError"]["score"]
  209. executeAccurateError_score = data["details"]["accurate"]["indexes"]["executeAccurateError"]["score"]
  210. efficientDrive_score = data["details"]["efficient"]["indexes"]["efficientDrive"]["score"]
  211. averageSpeed_score = data["details"]["efficient"]["indexes"]["averageSpeed"]["score"]
  212. stopDuration_score = data["details"]["efficient"]["indexes"]["obstaclestopDuration"]["score"]
  213. # metric description
  214. collisionCount_description = data["details"]["safe"]["indexes"]["collisionCount"]["description"]
  215. collisionRisk_description = data["details"]["safe"]["indexes"]["collisionRisk"]["description"]
  216. collisionSeverity_description = data["details"]["safe"]["indexes"]["collisionSeverity"]["description"]
  217. overSpeed_description = data["details"]["safe"]["indexes"]["overSpeed"]["description"]
  218. comfortzigzag_description = data["details"]["comfort"]["indexes"]["zigzag"]["description"]
  219. comfortcadence_description = data["details"]["comfort"]["indexes"]["cadence"]["description"]
  220. comfortsharpchangeofspeed_description = data["details"]["comfort"]["indexes"]["sharpchangeofspeed"]["description"]
  221. comfortSpeed_description = data["details"]["comfort"]["indexes"]["comfortSpeed"]["description"]
  222. positionError_description = data["details"]["accurate"]["indexes"]["positionError"]["description"]
  223. executeAccurateError_description = data["details"]["accurate"]["indexes"]["executeAccurateError"]["description"]
  224. efficientDrive_description = data["details"]["efficient"]["indexes"]["efficientDrive"]["description"]
  225. averageSpeed_description = data["details"]["efficient"]["indexes"]["averageSpeed"]["description"]
  226. stopDuration_description = data["details"]["efficient"]["indexes"]["obstaclestopDuration"]["description"]
  227. # score level instruction
  228. level_instruction = "说明:优秀(90\u2264分值\u2264100),良好(80≤分值\u003c90),一般(60≤分值<80),较差(0≤分值<60)。"
  229. # # 创建表格数据
  230. # table_data = [
  231. # ("评价维度", "评价类型", "评价指标", "权重", "指标描述"),
  232. # ("安全性", "碰撞安全性", "碰撞次数", f"{collisionCount_weight * 100}%", collisionCount_description),
  233. # ("安全性", "碰撞安全性", "碰撞风险概率", f"{collisionRisk_weight * 100}%", collisionRisk_description),
  234. # ("安全性", "碰撞安全性", "碰撞严重程度", f"{collisionSeverity_weight * 100}%", collisionSeverity_description),
  235. # ("安全性", "超速安全性", "超速比例", f"{overSpeed_weight * 100}%", overSpeed_description),
  236. # ("平顺性", "纵向平顺性", "线加速度", f"{comfortLat_weight * 100}%", comfortLat_description),
  237. # ("平顺性", "横向平顺性", "角加速度", f"{comfortLon_weight * 100}%", comfortLon_description),
  238. # ("平顺性", "速度控制指令", "速度控制指令跳变次数", f"{comfortSpeed_weight * 100}%", comfortSpeed_description),
  239. # ("准确性", "执行准确性", "位置偏移误差", f"{positionError_weight * 100}%", positionError_description),
  240. # ("准确性", "执行准确性", "任务执行状态错误次数", f"{executeAccurateError_weight * 100}%",
  241. # executeAccurateError_description)
  242. # ]
  243. # 创建表格数据
  244. table_data = [
  245. ("评价维度", "评价指标", "基准值", "权重", "分数", "指标描述"),
  246. ("安全性", "碰撞次数", "0次", "50%", "{:.02f}".format(collisionCount_score), collisionCount_description),
  247. ("安全性", "碰撞风险概率", "10%", "5%", "{:.02f}".format(collisionRisk_score), collisionRisk_description),
  248. ("安全性", "碰撞严重程度", "10%", "5%", "{:.02f}".format(collisionSeverity_score), collisionSeverity_description),
  249. ("安全性", "超速比例", "0%", "5%", "{:.02f}".format(overSpeed_score), overSpeed_description),
  250. ("平顺性", "画龙", "0次", "5%", "{:.02f}".format(comfortzigzag_score), comfortzigzag_description),
  251. ("平顺性", "顿挫", "0次", "5%", "{:.02f}".format(comfortcadence_score), comfortcadence_description),
  252. ("平顺性", "急加减速", "0次", "5%", "{:.02f}".format(comfortsharpchangeofspeed_score), comfortsharpchangeofspeed_description),
  253. ("平顺性", "指令跳变次数", "0次", "5%", "{:.02f}".format(comfortSpeed_score), comfortSpeed_description),
  254. ("准确性", "位置偏移误差", "0.3m", "5%", "{:.02f}".format(positionError_score), positionError_description),
  255. ("准确性", "任务执行错误次数", "0次", "5%", "{:.02f}".format(executeAccurateError_score), executeAccurateError_description),
  256. ("高效性", "无障碍物停止", "0次", "5%", "{:.02f}".format(efficientDrive_score), efficientDrive_description),
  257. ("高效性", "有障碍物停止", "5s", "5%", "{:.02f}".format(stopDuration_score), stopDuration_description)
  258. ]
  259. # 创建内容对应的空列表
  260. content = list()
  261. content.append(ReportPDF.draw_img('Pji.png'))
  262. content.append(ReportPDF.draw_title('朴津室外AMR算法评价报告'))
  263. # content.append(ReportPDF.draw_line_feed("换行"))
  264. # content.append(ReportPDF.draw_line_feed("换行"))
  265. ### 报告内容填充
  266. # 综述
  267. base_info = f"数据包: {name}, 行驶时长: {test_duration}, 行驶里程: {test_mileage}"
  268. content.append(ReportPDF.draw_text(base_info))
  269. content.append(ReportPDF.draw_text(algorithm_result_description))
  270. content.append(ReportPDF.draw_text(safe_description))
  271. content.append(ReportPDF.draw_text(comfort_description))
  272. content.append(ReportPDF.draw_text(accurate_description))
  273. content.append(ReportPDF.draw_text(efficient_description))
  274. content.append(ReportPDF.draw_text(level_instruction, style_='Normal', font_size=8))
  275. # 表格
  276. content.append(ReportPDF.draw_line_feed("换行"))
  277. content.append(ReportPDF.draw_table(*table_data))
  278. content.append(ReportPDF.draw_line_feed("换行"))
  279. # 图片
  280. # 添加图片到PDF文档
  281. content.append(ReportPDF.draw_line_feed("换行"))
  282. content.append(ReportPDF.draw_line_feed("换行"))
  283. content.append(ReportPDF.draw_line_feed("换行"))
  284. for key, value in data["graphPath"].items():
  285. # 特判轨迹图片情况
  286. if "track.png" in value: # 评价工具生成轨迹图片
  287. trackPath = value
  288. continue
  289. if "trajectory.png" in value: # ros生成带地图轨迹图片
  290. continue
  291. content.append(ReportPDF.draw_text(key, 'Heading5'))
  292. content.append(Image(value, width=480, height=120))
  293. content.append(ReportPDF.draw_line_feed("换行"))
  294. # 添加轨迹图片
  295. content.append(ReportPDF.draw_text("轨迹", 'Heading5'))
  296. content.append(get_trajectory_image(trackPath))
  297. if "track.png" in trackPath:
  298. content.append(
  299. ReportPDF.draw_text(" 说明:轨迹起点为黄色点,随后颜色逐渐加深。", 'Normal', 8))
  300. else:
  301. content.append(
  302. ReportPDF.draw_text(" 说明:轨迹起点为绿色点,终点为红色点。", 'Normal', 8))
  303. # content.append(ReportPDF.draw_line_feed("换行"))
  304. # content.append(ReportPDF.draw_line_feed("换行"))
  305. # 创建PDF文档
  306. pdf_file = reportPdf
  307. doc = SimpleDocTemplate(pdf_file, pagesize=A4)
  308. # 构建文档
  309. doc.build(content)
  310. print("PDF报告已生成!")
  311. if __name__ == '__main__':
  312. # reportJson = './report.json'
  313. reportJson = '/home/server/桌面/virtualEnv_yzh/virtual_pji/pji_outdoor_robot_evaluate_real-0808/task/test_0807-1/report.json'
  314. reportPdf = "./report0809.pdf"
  315. trackPath = './track.png'
  316. with open(reportJson, 'r', encoding='utf-8') as f:
  317. reportJson = json.load(f)
  318. report_generate(reportJson, reportPdf, trackPath)
  319. print('over')