program/tag_names.py

140 lines
4.1 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.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
标签点位名称映射模块
从CSV文件中读取TagName到中文Description的映射关系
"""
import csv
import os
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
# 全局缓存
_tag_name_map = {}
_tag_description_cache_loaded = False
def load_tag_name_map(csv_dir=None):
"""
从CSV文件加载标签名称映射
:param csv_dir: CSV文件目录默认为 ../name/
:return: dict {TagName: Description}
"""
global _tag_name_map, _tag_description_cache_loaded
if _tag_description_cache_loaded:
return _tag_name_map
if csv_dir is None:
# 默认 CSV 目录:相对于本项目目录的 ../name/
base_dir = Path(__file__).parent
csv_dir = base_dir.parent / 'name'
csv_dir = Path(csv_dir)
if not csv_dir.exists():
logger.warning(f"标签名称CSV目录不存在: {csv_dir}")
_tag_description_cache_loaded = True
return _tag_name_map
_tag_name_map = {}
csv_files = list(csv_dir.glob('*.csv'))
for csv_file in csv_files:
try:
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
count = 0
for row in reader:
tag_name = row.get('TagName', '').strip()
description = row.get('Description', '').strip()
if tag_name and description:
_tag_name_map[tag_name] = description
count += 1
logger.info(f"{csv_file.name} 加载 {count} 个标签名称映射")
except Exception as e:
logger.error(f"读取CSV文件失败 {csv_file}: {e}")
_tag_description_cache_loaded = True
logger.info(f"标签名称映射加载完成,共 {len(_tag_name_map)} 个标签")
return _tag_name_map
def get_tag_description(tag_name):
"""
获取标签的中文描述
:param tag_name: 标签英文名称
:return: 中文描述,如果找不到则返回原标签名
"""
global _tag_name_map, _tag_description_cache_loaded
if not _tag_description_cache_loaded:
load_tag_name_map()
if tag_name in _tag_name_map:
return _tag_name_map[tag_name]
# 尝试模糊匹配 - 提取短名称
if '.' in tag_name:
short_name = tag_name.split('.')[-1]
if short_name in _tag_name_map:
return _tag_name_map[short_name]
# 返回原名称
return tag_name
def get_all_tag_names():
"""获取所有已加载的标签名称映射"""
global _tag_description_cache_loaded
if not _tag_description_cache_loaded:
load_tag_name_map()
return _tag_name_map.copy()
def enrich_data_with_names(data):
"""
为数据列表添加中文名称字段
:param data: 数据列表,每个元素包含 tag_full_name / tag_name / tag_short_name
:return: 添加了 chinese_name 字段的数据列表
"""
global _tag_description_cache_loaded
if not _tag_description_cache_loaded:
load_tag_name_map()
enriched = []
for item in data:
item_copy = item.copy()
# 优先使用 tag_full_name完整标签名匹配CSV中的TagName
# 因为CSV名称映射文件中的TagName是完整标签名含前缀
tag_name = (
item.get('tag_full_name') or
item.get('tag_name') or
item.get('TagName') or
item.get('tag') or
item.get('tag_short_name') or
''
)
chinese_name = get_tag_description(tag_name)
item_copy['chinese_name'] = chinese_name
enriched.append(item_copy)
return enriched
# 应用启动时预加载
def init_for_app(app=None):
"""
在Flask应用启动时预加载标签名称映射
"""
logger.info("正在预加载标签名称映射...")
tag_map = load_tag_name_map()
logger.info(f"标签名称映射预加载完成: {len(tag_map)} 个标签")
# 如果提供了Flask应用将映射加入配置
if app:
app.config['TAG_NAME_MAP'] = tag_map