Report_Generate_Server/tools/dataproccess.py

172 lines
6.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from tools.content_tools import add_picture_to_table
from tools.document_tools import add_table_to_document,search_and_replace
from tools.get_pictures import resize_and_reduce_quality
def caculate_work_days(start_date : str, end_date : str) -> str:
"""根据起止日期计算工期
Args:
start_date (str): 格式: yyyy-mm-ddThh:mm:ss
end_date (str): 格式: yyyy-mm-ddThh:mm:ss
Returns:
str: 计算出来的总工期,单位为天
"""
import datetime
if start_date == None or end_date == None:
return f"开始时间{start_date} ---- 结束时间{end_date} 日期格式错误"
start_date = datetime.datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%S')
end_date = datetime.datetime.strptime(end_date, '%Y-%m-%dT%H:%M:%S')
return (end_date - start_date).days
async def add_dynamic_table(output_doc, output_dir, table_num, TABLES, JIANCHA_XIANGQING_DIR, PICTURES, row, col, i, FLAG, xuhao):
"""创建动态表
Args:
output_doc (Document): 文档对象
output_dir (str): 输出目录
table_num (int): 表格序号
TABLES (list): 表格数据
JIANCHA_XIANGQING_DIR (str): 检查详情表目录
PICTURES (dict): 图片数据字典,键为表索引,值为图片路径列表
row (int): 行数
col (int): 列数
i (int): 表格序号
FLAG: 其他标志
Returns:
tuple: (i, table_num) 更新后的表格序号和表格数量
"""
for table_idx, Table in enumerate(TABLES):
print(Table)
output_doc, message = await add_table_to_document(output_dir, JIANCHA_XIANGQING_DIR, row, col, i, Table, FLAG)
print(message)
# 获取当前表格对应的图片
current_table_pictures = PICTURES.get(table_idx, [])
print(f"开始处理图片列表: {current_table_pictures}")
for picturedir in current_table_pictures:
try:
print(f"添加 {picturedir} {type(picturedir)}到表格{table_idx}")
resize_and_reduce_quality(picturedir, picturedir)
await add_picture_to_table(output_doc, output_dir, 4, 0, picturedir, i, 4.7232)
except Exception as e:
print(f"添加图片失败:{e}")
print(await search_and_replace(output_dir, 'tupian_xuhao', f'{xuhao}'))
table_num += 1
i += 1
xuhao += 1
return i, table_num, xuhao
def get_year_month(date):
"""根据格式化date字符串获取年月 'date': '二〇二一年十二月十日 9:00'
Args: date (str): 日期字符串
Returns: 年月字符串 '二〇二一年十二月'
"""
unit_map = {'1' : '', '2' : '', '3' : '', '4' : '', '5' : '', '6' : '', '7' : '', '8' : '', '9' : '', '0' : ''}
unit_map_month = {1 : '', 2 : '', 3 : '', 4 : '', 5 : '', 6 : '', 7 : '', 8 : '', 9 : '', 10 : '', 11 : '十一', 12 : '十二'}
year = date.split('')[0]
month = date.split('')[1].split('')[0]
year = ''.join([unit_map[i] for i in year])
month = unit_map_month[int(month)]
return f"{year}{month}"
def merge_info(frontend_info, default_info):
"""
合并前端传入的 info 和默认 info
新规则以default_info为基础字典用frontend_info完全覆写取两者的并集
Args:
frontend_info: 前端传入的字典
default_info: 默认的完整字典
Returns:
合并后的完整字典
"""
if not isinstance(frontend_info, dict) or frontend_info is None:
return default_info.copy()
# 先复制默认字典
merged_info = default_info.copy()
# 用前端字典完全覆写
merged_info.update(frontend_info)
return merged_info
def merge_dicts(dict1, dict2):
# 创建一个新的字典来存储合并结果
merged_dict = {}
# 遍历第一个字典
for key, value_list in dict1.items():
if key in dict2:
# 如果键在第二个字典中存在,合并两个列表
merged_dict[key] = value_list + dict2[key]
else:
# 如果键在第二个字典中不存在,直接使用第一个字典的值列表
merged_dict[key] = value_list
# 遍历第二个字典
for key, value_list in dict2.items():
if key not in dict1:
# 如果键在第一个字典中不存在,直接使用第二个字典的值列表
merged_dict[key] = value_list
return merged_dict
def get_defect_str(Y_defect_list : list[dict] ) -> list:
"""将叶片缺陷信息转换为一条条描述信息
Args:
Y_defect_list (list):[
{
'record' : {'defectId': '02d892a178a82561bb565559102c7a58', 'imageId': '41543f531be24522b7bec741b9a483a2', 'defectName': '手动添加的缺陷1', 'defectCode': None, 'partName': '叶片1', 'defectTypeLabel': '表面裂纹', 'defectType': 'bmlw', 'defectLevelLabel': '轻微缺陷', 'defectLevel': 'SLIGHT', 'defectPosition': '', 'description': '手动添加的缺陷,请填写详细描述', 'repairIdea': '建议进行进一步检查', 'labelInfo': None, 'markInfo': {'label': None, 'clsId': None, 'bbox': None, 'confidence': 0.0}}
'imagePath' : '/image/path'
},
....
]
Returns:
result (list):
[
"叶片1表面裂纹轻微缺陷位于{defectPosition},建议进行进一步检查",
],
...
"""
result = []
for item in Y_defect_list:
record = item['record']
defect_type_label = record.get('defectTypeLabel', '未知类型')
defect_level_label = record.get('defectLevelLabel', '未知等级')
defect_position = record.get('defectPosition', '未知位置')
repair_idea = record.get('repairIdea', '无建议')
defect_description = f"{defect_type_label}{defect_level_label}缺陷,位于{defect_position}{repair_idea}"
result.append(defect_description)
return result
def safe_get(data, *keys, default=None):
"""
递归安全访问嵌套字典的键,如果中间键不存在,则返回默认值
Args:
data (dict): 要访问的字典
*keys: 要访问的键(可以是多个,如 "叶片1", "裂纹"
default: 如果键不存在返回的默认值默认None
Returns:
如果所有键都存在,返回对应的值;否则返回 default
"""
if not keys or data is None:
return data if data is not None else default
current_key = keys[0]
if isinstance(data, dict):
return safe_get(data.get(current_key), *keys[1:], default=default)
else:
return default