Compare View
Commits (3)
Showing
6 changed files
Show diff stats
config.py
offline_tasks/scripts/debug_utils.py
| @@ -21,8 +21,9 @@ def setup_debug_logger(script_name, debug=False): | @@ -21,8 +21,9 @@ def setup_debug_logger(script_name, debug=False): | ||
| 21 | """ | 21 | """ |
| 22 | logger = logging.getLogger(script_name) | 22 | logger = logging.getLogger(script_name) |
| 23 | 23 | ||
| 24 | - # 清除已有的handlers | ||
| 25 | - logger.handlers.clear() | 24 | + # 避免重复添加handler |
| 25 | + if logger.handlers: | ||
| 26 | + return logger | ||
| 26 | 27 | ||
| 27 | # 设置日志级别 | 28 | # 设置日志级别 |
| 28 | if debug: | 29 | if debug: |
| @@ -40,20 +41,20 @@ def setup_debug_logger(script_name, debug=False): | @@ -40,20 +41,20 @@ def setup_debug_logger(script_name, debug=False): | ||
| 40 | console_handler.setFormatter(console_format) | 41 | console_handler.setFormatter(console_format) |
| 41 | logger.addHandler(console_handler) | 42 | logger.addHandler(console_handler) |
| 42 | 43 | ||
| 43 | - # 文件输出(如果开启debug) | 44 | + # 文件输出(总是输出到logs目录) |
| 45 | + log_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs') | ||
| 46 | + os.makedirs(log_dir, exist_ok=True) | ||
| 47 | + | ||
| 48 | + log_file = os.path.join( | ||
| 49 | + log_dir, | ||
| 50 | + f"{script_name}_{datetime.now().strftime('%Y%m%d')}.log" | ||
| 51 | + ) | ||
| 52 | + file_handler = logging.FileHandler(log_file, encoding='utf-8') | ||
| 53 | + file_handler.setLevel(logging.DEBUG) | ||
| 54 | + file_handler.setFormatter(console_format) | ||
| 55 | + logger.addHandler(file_handler) | ||
| 56 | + | ||
| 44 | if debug: | 57 | if debug: |
| 45 | - log_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs', 'debug') | ||
| 46 | - os.makedirs(log_dir, exist_ok=True) | ||
| 47 | - | ||
| 48 | - log_file = os.path.join( | ||
| 49 | - log_dir, | ||
| 50 | - f"{script_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log" | ||
| 51 | - ) | ||
| 52 | - file_handler = logging.FileHandler(log_file, encoding='utf-8') | ||
| 53 | - file_handler.setLevel(logging.DEBUG) | ||
| 54 | - file_handler.setFormatter(console_format) | ||
| 55 | - logger.addHandler(file_handler) | ||
| 56 | - | ||
| 57 | logger.debug(f"Debug log file: {log_file}") | 58 | logger.debug(f"Debug log file: {log_file}") |
| 58 | 59 | ||
| 59 | return logger | 60 | return logger |
offline_tasks/scripts/i2i_item_behavior.py
| @@ -7,6 +7,41 @@ from db_service import create_db_connection | @@ -7,6 +7,41 @@ from db_service import create_db_connection | ||
| 7 | import argparse | 7 | import argparse |
| 8 | from datetime import datetime | 8 | from datetime import datetime |
| 9 | from scripts.debug_utils import save_readable_index | 9 | from scripts.debug_utils import save_readable_index |
| 10 | +import logging | ||
| 11 | + | ||
| 12 | +def setup_logger(): | ||
| 13 | + """设置logger配置""" | ||
| 14 | + # 创建logs目录 | ||
| 15 | + logs_dir = 'logs' | ||
| 16 | + os.makedirs(logs_dir, exist_ok=True) | ||
| 17 | + | ||
| 18 | + # 创建logger | ||
| 19 | + logger = logging.getLogger('i2i_item_behavior') | ||
| 20 | + logger.setLevel(logging.INFO) | ||
| 21 | + | ||
| 22 | + # 避免重复添加handler | ||
| 23 | + if logger.handlers: | ||
| 24 | + return logger | ||
| 25 | + | ||
| 26 | + # 创建文件handler | ||
| 27 | + log_file = os.path.join(logs_dir, f'i2i_item_behavior_{datetime.now().strftime("%Y%m%d")}.log') | ||
| 28 | + file_handler = logging.FileHandler(log_file, encoding='utf-8') | ||
| 29 | + file_handler.setLevel(logging.INFO) | ||
| 30 | + | ||
| 31 | + # 创建控制台handler | ||
| 32 | + console_handler = logging.StreamHandler() | ||
| 33 | + console_handler.setLevel(logging.INFO) | ||
| 34 | + | ||
| 35 | + # 创建formatter | ||
| 36 | + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | ||
| 37 | + file_handler.setFormatter(formatter) | ||
| 38 | + console_handler.setFormatter(formatter) | ||
| 39 | + | ||
| 40 | + # 添加handler到logger | ||
| 41 | + logger.addHandler(file_handler) | ||
| 42 | + logger.addHandler(console_handler) | ||
| 43 | + | ||
| 44 | + return logger | ||
| 10 | 45 | ||
| 11 | def clean_text_field(text): | 46 | def clean_text_field(text): |
| 12 | if pd.isna(text): | 47 | if pd.isna(text): |
| @@ -21,6 +56,9 @@ parser.add_argument('--top_n', type=int, default=50, help='每个商品保留的 | @@ -21,6 +56,9 @@ parser.add_argument('--top_n', type=int, default=50, help='每个商品保留的 | ||
| 21 | parser.add_argument('--debug', action='store_true', help='开启debug模式') | 56 | parser.add_argument('--debug', action='store_true', help='开启debug模式') |
| 22 | args = parser.parse_args() | 57 | args = parser.parse_args() |
| 23 | 58 | ||
| 59 | +# 初始化logger | ||
| 60 | +logger = setup_logger() | ||
| 61 | + | ||
| 24 | # 数据库连接配置 | 62 | # 数据库连接配置 |
| 25 | host = 'selectdb-cn-wuf3vsokg05-public.selectdbfe.rds.aliyuncs.com' | 63 | host = 'selectdb-cn-wuf3vsokg05-public.selectdbfe.rds.aliyuncs.com' |
| 26 | port = '9030' | 64 | port = '9030' |
| @@ -49,9 +87,14 @@ ORDER BY | @@ -49,9 +87,14 @@ ORDER BY | ||
| 49 | se.create_time; | 87 | se.create_time; |
| 50 | """ | 88 | """ |
| 51 | 89 | ||
| 90 | +logger.info("="*80) | ||
| 91 | +logger.info("I2I商品行为相似度计算开始") | ||
| 92 | +logger.info("="*80) | ||
| 93 | +logger.info(f"参数配置: lookback_days={args.lookback_days}, top_n={args.top_n}") | ||
| 94 | + | ||
| 52 | if args.debug: | 95 | if args.debug: |
| 53 | - print(f"[DEBUG] 参数配置: lookback_days={args.lookback_days}, top_n={args.top_n}") | ||
| 54 | - print(f"[DEBUG] 开始查询数据库...") | 96 | + logger.debug(f"[DEBUG] 参数配置: lookback_days={args.lookback_days}, top_n={args.top_n}") |
| 97 | + logger.debug(f"[DEBUG] 开始查询数据库...") | ||
| 55 | 98 | ||
| 56 | # 执行 SQL 查询并将结果加载到 pandas DataFrame | 99 | # 执行 SQL 查询并将结果加载到 pandas DataFrame |
| 57 | df = pd.read_sql(sql_query, engine) | 100 | df = pd.read_sql(sql_query, engine) |
| @@ -60,10 +103,14 @@ df = pd.read_sql(sql_query, engine) | @@ -60,10 +103,14 @@ df = pd.read_sql(sql_query, engine) | ||
| 60 | df['item_id'] = df['item_id'].astype(int) | 103 | df['item_id'] = df['item_id'].astype(int) |
| 61 | df['user_id'] = df['user_id'].astype(str) # user_id保持为字符串 | 104 | df['user_id'] = df['user_id'].astype(str) # user_id保持为字符串 |
| 62 | 105 | ||
| 106 | +logger.info(f"数据库查询完成,共 {len(df)} 条记录") | ||
| 107 | +logger.info(f"唯一用户数: {df['user_id'].nunique()}") | ||
| 108 | +logger.info(f"唯一商品数: {df['item_id'].nunique()}") | ||
| 109 | + | ||
| 63 | if args.debug: | 110 | if args.debug: |
| 64 | - print(f"[DEBUG] 查询完成,共 {len(df)} 条记录") | ||
| 65 | - print(f"[DEBUG] 唯一用户数: {df['user_id'].nunique()}") | ||
| 66 | - print(f"[DEBUG] 唯一商品数: {df['item_id'].nunique()}") | 111 | + logger.debug(f"[DEBUG] 查询完成,共 {len(df)} 条记录") |
| 112 | + logger.debug(f"[DEBUG] 唯一用户数: {df['user_id'].nunique()}") | ||
| 113 | + logger.debug(f"[DEBUG] 唯一商品数: {df['item_id'].nunique()}") | ||
| 67 | 114 | ||
| 68 | # 处理点击序列,计算共现关系 | 115 | # 处理点击序列,计算共现关系 |
| 69 | cooccur = defaultdict(lambda: defaultdict(int)) | 116 | cooccur = defaultdict(lambda: defaultdict(int)) |
| @@ -87,8 +134,10 @@ for (user_id, date), group in df.groupby(['user_id', 'date']): | @@ -87,8 +134,10 @@ for (user_id, date), group in df.groupby(['user_id', 'date']): | ||
| 87 | cooccur[item2][item1] += 1 | 134 | cooccur[item2][item1] += 1 |
| 88 | 135 | ||
| 89 | # 计算余弦相似度 | 136 | # 计算余弦相似度 |
| 137 | +logger.info("开始计算商品相似度...") | ||
| 138 | + | ||
| 90 | if args.debug: | 139 | if args.debug: |
| 91 | - print(f"[DEBUG] 开始计算相似度...") | 140 | + logger.debug(f"[DEBUG] 开始计算相似度...") |
| 92 | 141 | ||
| 93 | result = {} | 142 | result = {} |
| 94 | for item1 in cooccur: | 143 | for item1 in cooccur: |
| @@ -103,8 +152,10 @@ for item1 in cooccur: | @@ -103,8 +152,10 @@ for item1 in cooccur: | ||
| 103 | # 只保留top_n个相似商品 | 152 | # 只保留top_n个相似商品 |
| 104 | result[item1] = sim_scores[:args.top_n] | 153 | result[item1] = sim_scores[:args.top_n] |
| 105 | 154 | ||
| 155 | +logger.info(f"相似度计算完成,共 {len(result)} 个商品有相似推荐") | ||
| 156 | + | ||
| 106 | if args.debug: | 157 | if args.debug: |
| 107 | - print(f"[DEBUG] 相似度计算完成,共 {len(result)} 个商品有相似推荐") | 158 | + logger.debug(f"[DEBUG] 相似度计算完成,共 {len(result)} 个商品有相似推荐") |
| 108 | 159 | ||
| 109 | # 创建item_id到name的映射 | 160 | # 创建item_id到name的映射 |
| 110 | item_name_map = dict(zip(df['item_id'], df['item_name'])) | 161 | item_name_map = dict(zip(df['item_id'], df['item_name'])) |
| @@ -116,8 +167,10 @@ os.makedirs(output_dir, exist_ok=True) | @@ -116,8 +167,10 @@ os.makedirs(output_dir, exist_ok=True) | ||
| 116 | output_file = os.path.join(output_dir, f'i2i_item_behavior_{date_str}.txt') | 167 | output_file = os.path.join(output_dir, f'i2i_item_behavior_{date_str}.txt') |
| 117 | 168 | ||
| 118 | # 输出相似商品到文件 | 169 | # 输出相似商品到文件 |
| 170 | +logger.info(f"开始写入输出文件: {output_file}") | ||
| 171 | + | ||
| 119 | if args.debug: | 172 | if args.debug: |
| 120 | - print(f"[DEBUG] 开始写入文件: {output_file}") | 173 | + logger.debug(f"[DEBUG] 开始写入文件: {output_file}") |
| 121 | 174 | ||
| 122 | with open(output_file, 'w', encoding='utf-8') as f: | 175 | with open(output_file, 'w', encoding='utf-8') as f: |
| 123 | for item_id, sims in sorted(result.items()): | 176 | for item_id, sims in sorted(result.items()): |
| @@ -126,16 +179,32 @@ with open(output_file, 'w', encoding='utf-8') as f: | @@ -126,16 +179,32 @@ with open(output_file, 'w', encoding='utf-8') as f: | ||
| 126 | sim_str = ','.join([f'{sim_id}:{score:.4f}' for sim_id, score in sims]) | 179 | sim_str = ','.join([f'{sim_id}:{score:.4f}' for sim_id, score in sims]) |
| 127 | f.write(f'{item_id}\t{item_name}\t{sim_str}\n') | 180 | f.write(f'{item_id}\t{item_name}\t{sim_str}\n') |
| 128 | 181 | ||
| 129 | -print(f"✓ Item相似度计算完成") | ||
| 130 | -print(f" - 输出文件: {output_file}") | ||
| 131 | -print(f" - 商品数: {len(result)}") | ||
| 132 | -if result: | ||
| 133 | - avg_sims = sum(len(sims) for sims in result.values()) / len(result) | ||
| 134 | - print(f" - 平均相似商品数: {avg_sims:.1f}") | 182 | +logger.info(f"输出文件写入完成: {output_file}") |
| 183 | + | ||
| 184 | +# 统计信息 | ||
| 185 | +total_similarity_pairs = sum(len(sims) for sims in result.values()) | ||
| 186 | +avg_sims = total_similarity_pairs / len(result) if result else 0 | ||
| 187 | + | ||
| 188 | +logger.info("="*80) | ||
| 189 | +logger.info("I2I商品行为相似度计算 - 关键统计信息") | ||
| 190 | +logger.info("="*80) | ||
| 191 | +logger.info(f"📊 数据概览:") | ||
| 192 | +logger.info(f" - 总行为记录数: {len(df):,}") | ||
| 193 | +logger.info(f" - 唯一用户数: {df['user_id'].nunique():,}") | ||
| 194 | +logger.info(f" - 唯一商品数: {df['item_id'].nunique():,}") | ||
| 195 | +logger.info(f" - 有相似度的商品数: {len(result):,}") | ||
| 196 | +logger.info(f" - 总相似度对数量: {total_similarity_pairs:,}") | ||
| 197 | +logger.info(f" - 平均每商品相似数: {avg_sims:.1f}") | ||
| 198 | + | ||
| 199 | +logger.info(f"📁 输出文件:") | ||
| 200 | +logger.info(f" - 输出文件: {output_file}") | ||
| 201 | + | ||
| 202 | +logger.info(f"✅ I2I商品行为相似度计算完成") | ||
| 203 | +logger.info("="*80) | ||
| 135 | 204 | ||
| 136 | # 如果启用debug模式,保存可读格式 | 205 | # 如果启用debug模式,保存可读格式 |
| 137 | if args.debug and result: | 206 | if args.debug and result: |
| 138 | - print("[DEBUG] 保存可读格式文件...") | 207 | + logger.debug("[DEBUG] 保存可读格式文件...") |
| 139 | 208 | ||
| 140 | # 准备name_mappings | 209 | # 准备name_mappings |
| 141 | name_mappings = { | 210 | name_mappings = { |
offline_tasks/scripts/load_index_to_redis.py
| @@ -10,11 +10,41 @@ import sys | @@ -10,11 +10,41 @@ import sys | ||
| 10 | from datetime import datetime | 10 | from datetime import datetime |
| 11 | from config.offline_config import REDIS_CONFIG, OUTPUT_DIR | 11 | from config.offline_config import REDIS_CONFIG, OUTPUT_DIR |
| 12 | 12 | ||
| 13 | -logging.basicConfig( | ||
| 14 | - level=logging.INFO, | ||
| 15 | - format='%(asctime)s - %(levelname)s - %(message)s' | ||
| 16 | -) | ||
| 17 | -logger = logging.getLogger(__name__) | 13 | +def setup_logger(): |
| 14 | + """设置logger配置""" | ||
| 15 | + # 创建logs目录 | ||
| 16 | + logs_dir = 'logs' | ||
| 17 | + os.makedirs(logs_dir, exist_ok=True) | ||
| 18 | + | ||
| 19 | + # 创建logger | ||
| 20 | + logger = logging.getLogger('load_index_to_redis') | ||
| 21 | + logger.setLevel(logging.INFO) | ||
| 22 | + | ||
| 23 | + # 避免重复添加handler | ||
| 24 | + if logger.handlers: | ||
| 25 | + return logger | ||
| 26 | + | ||
| 27 | + # 创建文件handler | ||
| 28 | + log_file = os.path.join(logs_dir, f'load_index_to_redis_{datetime.now().strftime("%Y%m%d")}.log') | ||
| 29 | + file_handler = logging.FileHandler(log_file, encoding='utf-8') | ||
| 30 | + file_handler.setLevel(logging.INFO) | ||
| 31 | + | ||
| 32 | + # 创建控制台handler | ||
| 33 | + console_handler = logging.StreamHandler() | ||
| 34 | + console_handler.setLevel(logging.INFO) | ||
| 35 | + | ||
| 36 | + # 创建formatter | ||
| 37 | + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | ||
| 38 | + file_handler.setFormatter(formatter) | ||
| 39 | + console_handler.setFormatter(formatter) | ||
| 40 | + | ||
| 41 | + # 添加handler到logger | ||
| 42 | + logger.addHandler(file_handler) | ||
| 43 | + logger.addHandler(console_handler) | ||
| 44 | + | ||
| 45 | + return logger | ||
| 46 | + | ||
| 47 | +logger = setup_logger() | ||
| 18 | 48 | ||
| 19 | 49 | ||
| 20 | def load_index_file(file_path, redis_client, key_prefix, expire_seconds=None): | 50 | def load_index_file(file_path, redis_client, key_prefix, expire_seconds=None): |
offline_tasks/scripts/tag_category_similar.py
| @@ -6,6 +6,42 @@ from sqlalchemy import create_engine | @@ -6,6 +6,42 @@ from sqlalchemy import create_engine | ||
| 6 | from db_service import create_db_connection | 6 | from db_service import create_db_connection |
| 7 | import argparse | 7 | import argparse |
| 8 | from datetime import datetime | 8 | from datetime import datetime |
| 9 | +import json | ||
| 10 | +import logging | ||
| 11 | + | ||
| 12 | +def setup_logger(): | ||
| 13 | + """设置logger配置""" | ||
| 14 | + # 创建logs目录 | ||
| 15 | + logs_dir = 'logs' | ||
| 16 | + os.makedirs(logs_dir, exist_ok=True) | ||
| 17 | + | ||
| 18 | + # 创建logger | ||
| 19 | + logger = logging.getLogger('tag_category_similar') | ||
| 20 | + logger.setLevel(logging.INFO) | ||
| 21 | + | ||
| 22 | + # 避免重复添加handler | ||
| 23 | + if logger.handlers: | ||
| 24 | + return logger | ||
| 25 | + | ||
| 26 | + # 创建文件handler | ||
| 27 | + log_file = os.path.join(logs_dir, f'tag_category_similar_{datetime.now().strftime("%Y%m%d")}.log') | ||
| 28 | + file_handler = logging.FileHandler(log_file, encoding='utf-8') | ||
| 29 | + file_handler.setLevel(logging.INFO) | ||
| 30 | + | ||
| 31 | + # 创建控制台handler | ||
| 32 | + console_handler = logging.StreamHandler() | ||
| 33 | + console_handler.setLevel(logging.INFO) | ||
| 34 | + | ||
| 35 | + # 创建formatter | ||
| 36 | + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | ||
| 37 | + file_handler.setFormatter(formatter) | ||
| 38 | + console_handler.setFormatter(formatter) | ||
| 39 | + | ||
| 40 | + # 添加handler到logger | ||
| 41 | + logger.addHandler(file_handler) | ||
| 42 | + logger.addHandler(console_handler) | ||
| 43 | + | ||
| 44 | + return logger | ||
| 9 | 45 | ||
| 10 | def clean_text_field(text): | 46 | def clean_text_field(text): |
| 11 | if pd.isna(text): | 47 | if pd.isna(text): |
| @@ -20,6 +56,9 @@ parser.add_argument('--top_n', type=int, default=50, help='每个分类保留的 | @@ -20,6 +56,9 @@ parser.add_argument('--top_n', type=int, default=50, help='每个分类保留的 | ||
| 20 | parser.add_argument('--debug', action='store_true', help='开启debug模式') | 56 | parser.add_argument('--debug', action='store_true', help='开启debug模式') |
| 21 | args = parser.parse_args() | 57 | args = parser.parse_args() |
| 22 | 58 | ||
| 59 | +# 初始化logger | ||
| 60 | +logger = setup_logger() | ||
| 61 | + | ||
| 23 | bpms_host = '120.76.244.158' | 62 | bpms_host = '120.76.244.158' |
| 24 | bpms_port = '3325' | 63 | bpms_port = '3325' |
| 25 | bpms_database = 'bpms' | 64 | bpms_database = 'bpms' |
| @@ -51,9 +90,14 @@ WHERE spi.quantity > 0 | @@ -51,9 +90,14 @@ WHERE spi.quantity > 0 | ||
| 51 | GROUP BY sp.code, psm.name, bb.code; | 90 | GROUP BY sp.code, psm.name, bb.code; |
| 52 | """ | 91 | """ |
| 53 | 92 | ||
| 93 | +logger.info("="*80) | ||
| 94 | +logger.info("Tag分类相似度计算开始") | ||
| 95 | +logger.info("="*80) | ||
| 96 | +logger.info(f"参数配置: lookback_days={args.lookback_days}, top_n={args.top_n}") | ||
| 97 | + | ||
| 54 | if args.debug: | 98 | if args.debug: |
| 55 | - print(f"[DEBUG] 参数配置: lookback_days={args.lookback_days}, top_n={args.top_n}") | ||
| 56 | - print(f"[DEBUG] 开始查询数据库...") | 99 | + logger.debug(f"[DEBUG] 参数配置: lookback_days={args.lookback_days}, top_n={args.top_n}") |
| 100 | + logger.debug(f"[DEBUG] 开始查询数据库...") | ||
| 57 | 101 | ||
| 58 | # 执行 SQL 查询并将结果加载到 pandas DataFrame | 102 | # 执行 SQL 查询并将结果加载到 pandas DataFrame |
| 59 | df = pd.read_sql(sql_query, engine) | 103 | df = pd.read_sql(sql_query, engine) |
| @@ -64,8 +108,23 @@ if 'category_id' in df.columns: | @@ -64,8 +108,23 @@ if 'category_id' in df.columns: | ||
| 64 | if 'supplier_id' in df.columns: | 108 | if 'supplier_id' in df.columns: |
| 65 | df['supplier_id'] = df['supplier_id'].astype(int) | 109 | df['supplier_id'] = df['supplier_id'].astype(int) |
| 66 | 110 | ||
| 111 | +# 统计信息收集 | ||
| 112 | +stats = { | ||
| 113 | + 'start_time': datetime.now(), | ||
| 114 | + 'total_orders': len(df), | ||
| 115 | + 'unique_regions': 0, | ||
| 116 | + 'unique_customers': 0, | ||
| 117 | + 'total_categories': 0, | ||
| 118 | + 'categories_with_similarities': 0, | ||
| 119 | + 'total_similarity_pairs': 0, | ||
| 120 | + 'avg_similarities_per_category': 0, | ||
| 121 | + 'file_stats': {} | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +logger.info(f"数据库查询完成,共 {len(df)} 条订单记录") | ||
| 125 | + | ||
| 67 | if args.debug: | 126 | if args.debug: |
| 68 | - print(f"[DEBUG] 查询完成,共 {len(df)} 条订单记录") | 127 | + logger.debug(f"[DEBUG] 查询完成,共 {len(df)} 条订单记录") |
| 69 | 128 | ||
| 70 | # 处理商品信息,分割并去重 | 129 | # 处理商品信息,分割并去重 |
| 71 | # 构建ID到名称的映射 | 130 | # 构建ID到名称的映射 |
| @@ -73,6 +132,10 @@ cat_id_to_name = {} | @@ -73,6 +132,10 @@ cat_id_to_name = {} | ||
| 73 | cooccur = defaultdict(lambda: defaultdict(int)) | 132 | cooccur = defaultdict(lambda: defaultdict(int)) |
| 74 | freq = defaultdict(int) | 133 | freq = defaultdict(int) |
| 75 | 134 | ||
| 135 | +# 统计唯一区域和客户 | ||
| 136 | +stats['unique_regions'] = df['区域'].nunique() if '区域' in df.columns else 0 | ||
| 137 | +stats['unique_customers'] = df['客户编码'].nunique() if '客户编码' in df.columns else 0 | ||
| 138 | + | ||
| 76 | for _, row in df.iterrows(): | 139 | for _, row in df.iterrows(): |
| 77 | # Handle None values in 商品信息 | 140 | # Handle None values in 商品信息 |
| 78 | if pd.isna(row['商品信息']): | 141 | if pd.isna(row['商品信息']): |
| @@ -93,11 +156,17 @@ for _, row in df.iterrows(): | @@ -93,11 +156,17 @@ for _, row in df.iterrows(): | ||
| 93 | if c1 != c2: | 156 | if c1 != c2: |
| 94 | cooccur[c1][c2] += 1 | 157 | cooccur[c1][c2] += 1 |
| 95 | 158 | ||
| 159 | +# 更新统计信息 | ||
| 160 | +stats['total_categories'] = len(freq) | ||
| 161 | + | ||
| 96 | # 计算余弦相似度 | 162 | # 计算余弦相似度 |
| 163 | +logger.info("开始计算分类相似度...") | ||
| 164 | + | ||
| 97 | if args.debug: | 165 | if args.debug: |
| 98 | - print(f"[DEBUG] 开始计算分类相似度...") | 166 | + logger.debug(f"[DEBUG] 开始计算分类相似度...") |
| 99 | 167 | ||
| 100 | result = {} | 168 | result = {} |
| 169 | +total_similarity_pairs = 0 | ||
| 101 | for c1 in cooccur: | 170 | for c1 in cooccur: |
| 102 | sim_scores = [] | 171 | sim_scores = [] |
| 103 | for c2 in cooccur[c1]: | 172 | for c2 in cooccur[c1]: |
| @@ -109,14 +178,22 @@ for c1 in cooccur: | @@ -109,14 +178,22 @@ for c1 in cooccur: | ||
| 109 | sim_scores.sort(key=lambda x: -x[1]) # 按分数排序 | 178 | sim_scores.sort(key=lambda x: -x[1]) # 按分数排序 |
| 110 | # 只保留top_n个相似分类 | 179 | # 只保留top_n个相似分类 |
| 111 | result[c1] = sim_scores[:args.top_n] | 180 | result[c1] = sim_scores[:args.top_n] |
| 181 | + total_similarity_pairs += len(sim_scores[:args.top_n]) | ||
| 182 | + | ||
| 183 | +# 更新统计信息 | ||
| 184 | +stats['categories_with_similarities'] = len(result) | ||
| 185 | +stats['total_similarity_pairs'] = total_similarity_pairs | ||
| 186 | +stats['avg_similarities_per_category'] = total_similarity_pairs / len(result) if result else 0 | ||
| 187 | + | ||
| 188 | +logger.info(f"相似度计算完成,共 {len(result)} 个分类有相似推荐") | ||
| 112 | 189 | ||
| 113 | if args.debug: | 190 | if args.debug: |
| 114 | - print(f"[DEBUG] 相似度计算完成,共 {len(result)} 个分类有相似推荐") | 191 | + logger.debug(f"[DEBUG] 相似度计算完成,共 {len(result)} 个分类有相似推荐") |
| 115 | unique_cats = set() | 192 | unique_cats = set() |
| 116 | for cats in result.values(): | 193 | for cats in result.values(): |
| 117 | for cat, _ in cats: | 194 | for cat, _ in cats: |
| 118 | unique_cats.add(cat) | 195 | unique_cats.add(cat) |
| 119 | - print(f"[DEBUG] 唯一分类数: {len(unique_cats)}") | 196 | + logger.debug(f"[DEBUG] 唯一分类数: {len(unique_cats)}") |
| 120 | 197 | ||
| 121 | # 准备输出 | 198 | # 准备输出 |
| 122 | date_str = datetime.now().strftime('%Y%m%d') | 199 | date_str = datetime.now().strftime('%Y%m%d') |
| @@ -128,8 +205,10 @@ output_file = os.path.join(output_dir, f'tag_category_similar_{date_str}.txt') | @@ -128,8 +205,10 @@ output_file = os.path.join(output_dir, f'tag_category_similar_{date_str}.txt') | ||
| 128 | debug_file = os.path.join(debug_dir, f'tag_category_similar_{date_str}_readable.txt') | 205 | debug_file = os.path.join(debug_dir, f'tag_category_similar_{date_str}_readable.txt') |
| 129 | 206 | ||
| 130 | # 输出相似分类到文件(ID格式) | 207 | # 输出相似分类到文件(ID格式) |
| 208 | +logger.info(f"开始写入输出文件: {output_file}") | ||
| 209 | + | ||
| 131 | if args.debug: | 210 | if args.debug: |
| 132 | - print(f"[DEBUG] 开始写入文件: {output_file}") | 211 | + logger.debug(f"[DEBUG] 开始写入文件: {output_file}") |
| 133 | 212 | ||
| 134 | with open(output_file, 'w', encoding='utf-8') as f: | 213 | with open(output_file, 'w', encoding='utf-8') as f: |
| 135 | for cat_id, sims in sorted(result.items()): | 214 | for cat_id, sims in sorted(result.items()): |
| @@ -137,9 +216,22 @@ with open(output_file, 'w', encoding='utf-8') as f: | @@ -137,9 +216,22 @@ with open(output_file, 'w', encoding='utf-8') as f: | ||
| 137 | sim_str = ','.join([f'{sim_id}:{score:.4f}' for sim_id, score in sims]) | 216 | sim_str = ','.join([f'{sim_id}:{score:.4f}' for sim_id, score in sims]) |
| 138 | f.write(f'{cat_id}\t{sim_str}\n') | 217 | f.write(f'{cat_id}\t{sim_str}\n') |
| 139 | 218 | ||
| 219 | +logger.info(f"输出文件写入完成: {output_file}") | ||
| 220 | + | ||
| 221 | +# 获取文件统计信息 | ||
| 222 | +if os.path.exists(output_file): | ||
| 223 | + file_size = os.path.getsize(output_file) | ||
| 224 | + stats['file_stats']['output_file'] = { | ||
| 225 | + 'path': output_file, | ||
| 226 | + 'size_bytes': file_size, | ||
| 227 | + 'size_mb': round(file_size / (1024 * 1024), 2) | ||
| 228 | + } | ||
| 229 | + | ||
| 140 | # 输出可读版本到debug目录(ID+名称格式) | 230 | # 输出可读版本到debug目录(ID+名称格式) |
| 231 | +logger.info(f"开始写入可读文件: {debug_file}") | ||
| 232 | + | ||
| 141 | if args.debug: | 233 | if args.debug: |
| 142 | - print(f"[DEBUG] 开始写入可读文件: {debug_file}") | 234 | + logger.debug(f"[DEBUG] 开始写入可读文件: {debug_file}") |
| 143 | 235 | ||
| 144 | with open(debug_file, 'w', encoding='utf-8') as f: | 236 | with open(debug_file, 'w', encoding='utf-8') as f: |
| 145 | # 写入文件头信息 | 237 | # 写入文件头信息 |
| @@ -162,10 +254,45 @@ with open(debug_file, 'w', encoding='utf-8') as f: | @@ -162,10 +254,45 @@ with open(debug_file, 'w', encoding='utf-8') as f: | ||
| 162 | sim_str = ','.join(sim_parts) | 254 | sim_str = ','.join(sim_parts) |
| 163 | f.write(f'{cat_id}:{cat_clean}\t{sim_str}\n') | 255 | f.write(f'{cat_id}:{cat_clean}\t{sim_str}\n') |
| 164 | 256 | ||
| 165 | -print(f"✓ Tag相似度计算完成") | ||
| 166 | -print(f" - 输出文件: {output_file}") | ||
| 167 | -print(f" - 可读文件: {debug_file}") | ||
| 168 | -print(f" - 分类数: {len(result)}") | ||
| 169 | -if result: | ||
| 170 | - avg_sims = sum(len(sims) for sims in result.values()) / len(result) | ||
| 171 | - print(f" - 平均相似分类数: {avg_sims:.1f}") | 257 | +logger.info(f"可读文件写入完成: {debug_file}") |
| 258 | + | ||
| 259 | +# 获取debug文件统计信息 | ||
| 260 | +if os.path.exists(debug_file): | ||
| 261 | + file_size = os.path.getsize(debug_file) | ||
| 262 | + stats['file_stats']['debug_file'] = { | ||
| 263 | + 'path': debug_file, | ||
| 264 | + 'size_bytes': file_size, | ||
| 265 | + 'size_mb': round(file_size / (1024 * 1024), 2) | ||
| 266 | + } | ||
| 267 | + | ||
| 268 | +# 计算处理时间 | ||
| 269 | +stats['end_time'] = datetime.now() | ||
| 270 | +stats['processing_time_seconds'] = (stats['end_time'] - stats['start_time']).total_seconds() | ||
| 271 | + | ||
| 272 | +# 输出统计信息 | ||
| 273 | +logger.info("="*80) | ||
| 274 | +logger.info("Tag分类相似度计算 - 关键统计信息") | ||
| 275 | +logger.info("="*80) | ||
| 276 | +logger.info(f"📊 数据概览:") | ||
| 277 | +logger.info(f" - 总订单数: {stats['total_orders']:,}") | ||
| 278 | +logger.info(f" - 唯一区域数: {stats['unique_regions']:,}") | ||
| 279 | +logger.info(f" - 唯一客户数: {stats['unique_customers']:,}") | ||
| 280 | +logger.info(f" - 总分类数: {stats['total_categories']:,}") | ||
| 281 | +logger.info(f" - 有相似度的分类数: {stats['categories_with_similarities']:,}") | ||
| 282 | +logger.info(f" - 总相似度对数量: {stats['total_similarity_pairs']:,}") | ||
| 283 | +logger.info(f" - 平均每分类相似数: {stats['avg_similarities_per_category']:.1f}") | ||
| 284 | + | ||
| 285 | +logger.info(f"📁 输出文件:") | ||
| 286 | +for file_type, file_info in stats['file_stats'].items(): | ||
| 287 | + logger.info(f" - {file_type}: {file_info['path']}") | ||
| 288 | + logger.info(f" 大小: {file_info['size_mb']} MB ({file_info['size_bytes']:,} bytes)") | ||
| 289 | + | ||
| 290 | +logger.info(f"⏱️ 处理时间:") | ||
| 291 | +logger.info(f" - 开始时间: {stats['start_time'].strftime('%Y-%m-%d %H:%M:%S')}") | ||
| 292 | +logger.info(f" - 结束时间: {stats['end_time'].strftime('%Y-%m-%d %H:%M:%S')}") | ||
| 293 | +logger.info(f" - 总耗时: {stats['processing_time_seconds']:.2f} 秒") | ||
| 294 | + | ||
| 295 | +logger.info(f"✅ Tag相似度计算完成") | ||
| 296 | +logger.info(f" - 输出文件: {output_file}") | ||
| 297 | +logger.info(f" - 可读文件: {debug_file}") | ||
| 298 | +logger.info("="*80) |
requirements.txt