Compare View

switch
from
...
to
 
Commits (3)
offline_tasks/FIXES_SUMMARY.md deleted
@@ -1,211 +0,0 @@ @@ -1,211 +0,0 @@
1 -# 离线任务修复总结  
2 -  
3 -## 修复日期  
4 -2025-10-21  
5 -  
6 -## 问题和解决方案  
7 -  
8 -### 1. Task 5 和 Task 6: ModuleNotFoundError: No module named 'db_service'  
9 -  
10 -**问题**:  
11 -- `i2i_item_behavior.py` 和 `tag_category_similar.py` 无法导入 `db_service` 模块  
12 -- 所有脚本都使用了丑陋的 `sys.path.append()` hack  
13 -  
14 -**解决方案**:  
15 -- 将 `db_service.py` 移动到 `offline_tasks/` 根目录(Python 运行根目录)  
16 -- 删除所有脚本中的 `sys.path.append()` 代码  
17 -- 在 `run.sh` 中设置 `PYTHONPATH=/home/tw/recommendation/offline_tasks`  
18 -- 现在所有脚本都使用标准导入:`from db_service import create_db_connection`  
19 -  
20 -**影响的文件**:  
21 -- `db_service.py` (移动到 offline_tasks 根目录)  
22 -- `run.sh` (添加 PYTHONPATH 设置)  
23 -- 所有 scripts/ 目录下的 12 个 Python 脚本 (清理了 sys.path 代码)  
24 -  
25 ----  
26 -  
27 -### 2. Task 3: DeepWalk 内存溢出 (OOM Kill - 退出码 137)  
28 -  
29 -**问题**:  
30 -- DeepWalk 在"构建物品图"步骤时被系统杀死  
31 -- 处理 348,043 条记录时内存消耗超过 35GB 限制  
32 -- 原实现使用纯 Python 构建图,效率低  
33 -  
34 -**解决方案**:  
35 -1. **复用高效实现**: 将 `graphembedding/deepwalk/` 的实现移动到 `offline_tasks/deepwalk/`  
36 - - 使用 Alias 采样算法,比纯 Python 快 5-10 倍  
37 - - 使用 joblib 多进程并行,避免 GIL  
38 - - 使用 networkx 的高效图结构  
39 -  
40 -2. **完全重构** `i2i_deepwalk.py`:  
41 - - 只负责数据适配(从数据库生成边文件)  
42 - - 复用 `DeepWalk` 类进行随机游走  
43 - - 添加内存保护:限制每个用户最多 100 个物品(按权重排序)  
44 -  
45 -3. **流程优化**:  
46 - ```  
47 - 数据库数据 → 边文件 → DeepWalk 随机游走 → Word2Vec 训练 → 相似度生成  
48 - ```  
49 -  
50 -**新增文件**:  
51 -- `offline_tasks/deepwalk/deepwalk.py` - DeepWalk 核心实现(Alias 采样)  
52 -- `offline_tasks/deepwalk/alias.py` - Alias 采样算法  
53 -  
54 -**性能提升**:  
55 -- 内存使用降低 60-70%  
56 -- 速度提升 3-5 倍  
57 -- 不会再被 OOM Kill  
58 -  
59 ----  
60 -  
61 -## 最终架构  
62 -  
63 -### 文件结构  
64 -```  
65 -offline_tasks/ (Python 根目录,通过 PYTHONPATH 设置)  
66 - ├── db_service.py ✓  
67 - ├── config/  
68 - │ └── offline_config.py ✓  
69 - ├── deepwalk/ ✓  
70 - │ ├── deepwalk.py (高效实现)  
71 - │ └── alias.py (Alias 采样)  
72 - ├── scripts/  
73 - │ ├── debug_utils.py  
74 - │ ├── fetch_item_attributes.py  
75 - │ ├── generate_session.py  
76 - │ ├── i2i_swing.py  
77 - │ ├── i2i_session_w2v.py  
78 - │ ├── i2i_deepwalk.py ✓ (重构)  
79 - │ ├── i2i_content_similar.py  
80 - │ ├── i2i_item_behavior.py ✓ (修复)  
81 - │ ├── tag_category_similar.py ✓ (修复)  
82 - │ └── interest_aggregation.py  
83 - └── run.sh ✓ (设置 PYTHONPATH)  
84 -```  
85 -  
86 -### 导入规范  
87 -所有脚本使用标准导入,无 `sys.path` hack:  
88 -  
89 -```python  
90 -# 标准导入  
91 -from db_service import create_db_connection  
92 -from config.offline_config import DB_CONFIG, OUTPUT_DIR  
93 -from scripts.debug_utils import setup_debug_logger  
94 -from deepwalk.deepwalk import DeepWalk  
95 -```  
96 -  
97 -### run.sh 配置  
98 -```bash  
99 -#!/bin/bash  
100 -  
101 -# 设置 Python 路径,让脚本能找到 db_service, config, deepwalk 等模块  
102 -export PYTHONPATH=/home/tw/recommendation/offline_tasks:$PYTHONPATH  
103 -  
104 -cd /home/tw/recommendation/offline_tasks  
105 -# ... 其他代码  
106 -```  
107 -  
108 ----  
109 -  
110 -## 测试  
111 -  
112 -### 运行测试脚本  
113 -```bash  
114 -cd /home/tw/recommendation/offline_tasks  
115 -./test_fixes.sh  
116 -```  
117 -  
118 -### 测试单个任务  
119 -```bash  
120 -cd /home/tw/recommendation/offline_tasks  
121 -  
122 -# 测试 Task 5  
123 -python3 scripts/i2i_item_behavior.py --lookback_days 400 --top_n 50 --debug  
124 -  
125 -# 测试 Task 6  
126 -python3 scripts/tag_category_similar.py --lookback_days 400 --top_n 50 --debug  
127 -  
128 -# 测试 Task 3 (建议先用较小参数测试)  
129 -python3 scripts/i2i_deepwalk.py --lookback_days 200 --top_n 30 --num_walks 5 --walk_length 20 --save_model --save_graph --debug  
130 -```  
131 -  
132 -### 运行完整流程  
133 -```bash  
134 -cd /home/tw/recommendation/offline_tasks  
135 -bash run.sh  
136 -```  
137 -  
138 ----  
139 -  
140 -## DeepWalk 参数调优建议  
141 -  
142 -### 内存充足 (>50GB 可用)  
143 -```bash  
144 ---lookback_days 400  
145 ---num_walks 10  
146 ---walk_length 40  
147 ---top_n 50  
148 -```  
149 -  
150 -### 内存有限 (30-50GB)  
151 -```bash  
152 ---lookback_days 200  
153 ---num_walks 5  
154 ---walk_length 30  
155 ---top_n 50  
156 -```  
157 -  
158 -### 内存紧张 (<30GB)  
159 -```bash  
160 ---lookback_days 100  
161 ---num_walks 3  
162 ---walk_length 20  
163 ---top_n 30  
164 -```  
165 -  
166 -### run.sh 推荐配置  
167 -修改 `run.sh` 第 164 行(根据实际内存情况调整):  
168 -```bash  
169 -# 内存优化版本 (推荐)  
170 -run_task "Task 3: DeepWalk" \  
171 - "python3 scripts/i2i_deepwalk.py --lookback_days 200 --top_n 50 --num_walks 5 --walk_length 30 --save_model --save_graph $DEBUG_MODE"  
172 -```  
173 -  
174 ----  
175 -  
176 -## 代码质量提升  
177 -  
178 -1. ✅ **移除所有 `sys.path` hack** - 使用标准 Python 模块导入  
179 -2. ✅ **清晰的模块结构** - offline_tasks 作为 Python 根目录  
180 -3. ✅ **更好的代码复用** - 复用 graphembedding/deepwalk 的高效实现  
181 -4. ✅ **内存优化** - 添加保护机制,避免 OOM  
182 -5. ✅ **性能提升** - 使用 Alias 采样和多进程并行  
183 -  
184 ----  
185 -  
186 -## 注意事项  
187 -  
188 -1. **PYTHONPATH**: 必须在 `offline_tasks/` 目录下运行脚本,或者设置 `PYTHONPATH`  
189 -2. **临时文件**: DeepWalk 会在 `output/temp/` 生成临时文件,运行完会自动清理  
190 -3. **日志**: 所有 debug 日志在 `logs/debug/` 目录  
191 -4. **内存监控**: run.sh 会持续监控内存,超过 35GB 会自动终止进程  
192 -  
193 ----  
194 -  
195 -## 验证清单  
196 -  
197 -✅ 所有 `sys.path.append()` 已清理  
198 -✅ `db_service.py` 在 offline_tasks 根目录  
199 -✅ `deepwalk/` 已移动到 offline_tasks  
200 -✅ `run.sh` 设置了 PYTHONPATH  
201 -✅ 所有脚本语法检查通过  
202 -✅ 所有导入语句正确  
203 -✅ i2i_deepwalk.py 已重构  
204 -  
205 ----  
206 -  
207 -## 下一步  
208 -  
209 -1. 运行 `bash run.sh` 测试完整流程  
210 -2. 根据实际运行情况调整 DeepWalk 参数  
211 -3. 监控内存使用情况,必要时进一步优化  
offline_tasks/IMPORT_FIXES.md deleted
@@ -1,96 +0,0 @@ @@ -1,96 +0,0 @@
1 -# Import 修复报告  
2 -  
3 -## 修复日期  
4 -2025-10-21  
5 -  
6 -## 修复内容  
7 -  
8 -### 添加缺失的 `import os`  
9 -  
10 -以下文件缺少 `import os` 导入,已全部修复:  
11 -  
12 -1. ✅ **add_names_to_swing.py** - 添加了 `import os`  
13 -2. ✅ **generate_session.py** - 规范化了导入(从 `import json,os` 改为单独的 `import os`)  
14 -3. ✅ **i2i_session_w2v.py** - 添加了 `import os`  
15 -4. ✅ **i2i_swing.py** - 添加了 `import os`  
16 -5. ✅ **interest_aggregation.py** - 添加了 `import os`  
17 -6. ✅ **tag_category_similar.py** - 添加了 `import os`  
18 -  
19 -## 验证结果  
20 -  
21 -### 所有脚本状态  
22 -  
23 -```  
24 -✓ add_names_to_swing.py  
25 -✓ debug_utils_backup.py  
26 -✓ debug_utils.py  
27 -✓ fetch_item_attributes.py  
28 -✓ generate_session.py  
29 -✓ i2i_content_similar.py  
30 -✓ i2i_deepwalk.py  
31 -✓ i2i_item_behavior.py  
32 -✓ i2i_session_w2v.py  
33 -✓ i2i_swing.py  
34 -✓ interest_aggregation.py  
35 -✓ load_index_to_redis.py  
36 -✓ tag_category_similar.py  
37 -```  
38 -  
39 -### 编译检查  
40 -  
41 -所有核心任务脚本编译通过,无语法错误。  
42 -  
43 -**注意**: `test_es_connection.py` 有语法错误(第183行),但这是测试文件,不影响主要任务运行。  
44 -  
45 -## 最终结构检查  
46 -  
47 -```  
48 -✓ db_service.py 存在于 offline_tasks/ 根目录  
49 -✓ config/offline_config.py 存在  
50 -✓ deepwalk 模块完整 (deepwalk.py + alias.py)  
51 -✓ run.sh 已设置 PYTHONPATH  
52 -✓ 共 14 个脚本文件  
53 -✓ 所有使用 os 模块的文件都已正确导入  
54 -```  
55 -  
56 -## 导入规范  
57 -  
58 -所有脚本现在遵循标准导入规范:  
59 -  
60 -```python  
61 -# 标准库导入  
62 -import os  
63 -import json  
64 -import argparse  
65 -from datetime import datetime  
66 -from collections import defaultdict  
67 -  
68 -# 第三方库导入  
69 -import pandas as pd  
70 -import numpy as np  
71 -from gensim.models import Word2Vec  
72 -  
73 -# 本地模块导入  
74 -from db_service import create_db_connection  
75 -from config.offline_config import DB_CONFIG, OUTPUT_DIR  
76 -from scripts.debug_utils import setup_debug_logger  
77 -from deepwalk.deepwalk import DeepWalk  
78 -```  
79 -  
80 -## 完成清单  
81 -  
82 -- [x] 所有缺少 `import os` 的文件已修复  
83 -- [x] 所有核心脚本编译通过  
84 -- [x] 导入语句规范化  
85 -- [x] 文件结构验证完成  
86 -- [x] PYTHONPATH 设置正确  
87 -  
88 -## 可以运行了!  
89 -  
90 -```bash  
91 -cd /home/tw/recommendation/offline_tasks  
92 -bash run.sh  
93 -```  
94 -  
95 -所有 Task 3, Task 5, Task 6 的问题都已解决!  
96 -  
offline_tasks/doc/详细设计文档.md
@@ -615,24 +615,27 @@ crontab -e @@ -615,24 +615,27 @@ crontab -e
615 615
616 ## 📊 数据量统计 616 ## 📊 数据量统计
617 617
618 -### 索引数量估算 618 +### 索引数量统计(基于真实数据)
619 619
620 -| 索引类型 | 索引数量 | 单条大小 | 总大小 | 更新频率 | 620 +| 索引类型 | 索引数量 | 单条平均大小 | 总大小 | 更新频率 |
621 |---------|---------|---------|--------|---------| 621 |---------|---------|---------|--------|---------|
622 -| i2i_swing_cpp | ~50,000 | ~400B | ~20MB | 每天 |  
623 -| i2i_swing | ~50,000 | ~500B | ~25MB | 每天 |  
624 -| i2i_session_w2v | ~50,000 | ~500B | ~25MB | 每天 |  
625 -| i2i_deepwalk | ~50,000 | ~500B | ~25MB | 每天 |  
626 -| i2i_content | ~50,000 | ~500B | ~25MB | 每周 |  
627 -| interest_hot | ~10,000 | ~1KB | ~10MB | 每天 |  
628 -| interest_cart | ~10,000 | ~1KB | ~10MB | 每天 |  
629 -| interest_new | ~5,000 | ~1KB | ~5MB | 每天 |  
630 -| interest_global | ~10,000 | ~1KB | ~10MB | 每天 |  
631 -| **总计** | **~295,000** | - | **~155MB** | - | 622 +| i2i_deepwalk | 48,376 | ~780B | 36MB | 每天 |
  623 +| i2i_session_w2v | 50,990 | ~840B | 41MB | 每天 |
  624 +| i2i_content_name | 127,720 | ~830B | 101MB | 每周 |
  625 +| i2i_content_pic | 0 | - | 0 | 每周 |
  626 +| i2i_item_behavior | 178,775 | ~750B | 128MB | 每天 |
  627 +| interest_hot | 14,001 | ~520B | 6.9MB | 每天 |
  628 +| interest_cart | 15,563 | ~670B | 10MB | 每天 |
  629 +| interest_new | 6,463 | ~500B | 3.1MB | 每天 |
  630 +| interest_global | 17,533 | ~660B | 11MB | 每天 |
  631 +| tag_category_similar | 708 | ~930B | 630KB | 每周 |
  632 +| **总计** | **~460,000** | - | **~338MB** | - |
  633 +
  634 +> 注:统计数据基于 2025-10-22 的实际输出文件
632 635
633 ### Redis内存占用 636 ### Redis内存占用
634 637
635 -加载到Redis后的内存占用约 **180MB**(包含key开销) 638 +加载到Redis后的内存占用约 **400MB**(包含key开销和Redis数据结构开销)
636 639
637 --- 640 ---
638 641
offline_tasks/run.sh
@@ -168,7 +168,7 @@ fi @@ -168,7 +168,7 @@ fi
168 168
169 # Task 4: 内容相似度 169 # Task 4: 内容相似度
170 run_task "Task 4: 内容相似度" \ 170 run_task "Task 4: 内容相似度" \
171 - "python3 scripts/i2i_content_similar.py" 171 + "python3 scripts/i2i_content_similar.py --top_n $TOP_N $DEBUG_MODE"
172 if [ $? -ne 0 ]; then 172 if [ $? -ne 0 ]; then
173 echo "⚠️ 内容相似度失败,但继续执行" 173 echo "⚠️ 内容相似度失败,但继续执行"
174 fi 174 fi
offline_tasks/scripts/i2i_content_similar.py
@@ -6,12 +6,16 @@ i2i - 基于ES向量的内容相似索引 @@ -6,12 +6,16 @@ i2i - 基于ES向量的内容相似索引
6 """ 6 """
7 import json 7 import json
8 import os 8 import os
  9 +import argparse
9 import pandas as pd 10 import pandas as pd
10 from datetime import datetime, timedelta 11 from datetime import datetime, timedelta
11 from elasticsearch import Elasticsearch 12 from elasticsearch import Elasticsearch
12 from db_service import create_db_connection 13 from db_service import create_db_connection
13 from config.offline_config import DB_CONFIG, OUTPUT_DIR 14 from config.offline_config import DB_CONFIG, OUTPUT_DIR
14 -from scripts.debug_utils import setup_debug_logger, log_processing_step 15 +from scripts.debug_utils import (
  16 + setup_debug_logger, log_processing_step,
  17 + save_readable_index, fetch_name_mappings
  18 +)
15 19
16 # ES配置 20 # ES配置
17 ES_CONFIG = { 21 ES_CONFIG = {
@@ -150,7 +154,7 @@ def find_similar_by_vector(es, vector, field_name, k=KNN_K, num_candidates=KNN_C @@ -150,7 +154,7 @@ def find_similar_by_vector(es, vector, field_name, k=KNN_K, num_candidates=KNN_C
150 return [] 154 return []
151 155
152 156
153 -def generate_similarity_index(es, active_items, vector_field, field_name, logger): 157 +def generate_similarity_index(es, active_items, vector_field, field_name, logger, top_n=50):
154 """ 158 """
155 生成一种向量的相似度索引 159 生成一种向量的相似度索引
156 160
@@ -160,6 +164,7 @@ def generate_similarity_index(es, active_items, vector_field, field_name, logger @@ -160,6 +164,7 @@ def generate_similarity_index(es, active_items, vector_field, field_name, logger
160 vector_field: 向量字段名 (embedding_name_zh 或 embedding_pic_h14) 164 vector_field: 向量字段名 (embedding_name_zh 或 embedding_pic_h14)
161 field_name: 字段简称 (name 或 pic) 165 field_name: 字段简称 (name 或 pic)
162 logger: 日志记录器 166 logger: 日志记录器
  167 + top_n: 返回的相似商品数量
163 168
164 Returns: 169 Returns:
165 dict: {item_id: [(similar_id, score, name), ...]} 170 dict: {item_id: [(similar_id, score, name), ...]}
@@ -201,7 +206,7 @@ def generate_similarity_index(es, active_items, vector_field, field_name, logger @@ -201,7 +206,7 @@ def generate_similarity_index(es, active_items, vector_field, field_name, logger
201 for sim_id, boosted_score, name in similar_items: 206 for sim_id, boosted_score, name in similar_items:
202 if sim_id != str(item_id): 207 if sim_id != str(item_id):
203 filtered_items.append((sim_id, boosted_score, name)) 208 filtered_items.append((sim_id, boosted_score, name))
204 - if len(filtered_items) >= TOP_N: 209 + if len(filtered_items) >= top_n:
205 break 210 break
206 211
207 if filtered_items: 212 if filtered_items:
@@ -236,14 +241,23 @@ def save_index_file(result, es, output_file, logger): @@ -236,14 +241,23 @@ def save_index_file(result, es, output_file, logger):
236 241
237 def main(): 242 def main():
238 """主函数""" 243 """主函数"""
  244 + # 解析命令行参数
  245 + parser = argparse.ArgumentParser(description='Generate content-based similarity using ES vectors')
  246 + parser.add_argument('--debug', action='store_true', help='Enable debug mode with readable output')
  247 + parser.add_argument('--top_n', type=int, default=50, help='Number of similar items per item (default: 50)')
  248 + args = parser.parse_args()
  249 +
  250 + # 使用参数中的top_n值
  251 + top_n = args.top_n
  252 +
239 # 设置logger 253 # 设置logger
240 - logger = setup_debug_logger('i2i_content_similar', debug=True) 254 + logger = setup_debug_logger('i2i_content_similar', debug=args.debug)
241 255
242 logger.info("="*80) 256 logger.info("="*80)
243 logger.info("开始生成基于ES向量的内容相似索引") 257 logger.info("开始生成基于ES向量的内容相似索引")
244 logger.info(f"ES地址: {ES_CONFIG['host']}") 258 logger.info(f"ES地址: {ES_CONFIG['host']}")
245 logger.info(f"索引名: {ES_CONFIG['index_name']}") 259 logger.info(f"索引名: {ES_CONFIG['index_name']}")
246 - logger.info(f"Top N: {TOP_N}") 260 + logger.info(f"Top N: {top_n}")
247 logger.info("="*80) 261 logger.info("="*80)
248 262
249 # 创建数据库连接 263 # 创建数据库连接
@@ -269,22 +283,60 @@ def main(): @@ -269,22 +283,60 @@ def main():
269 # 生成两份相似度索引 283 # 生成两份相似度索引
270 date_str = datetime.now().strftime("%Y%m%d") 284 date_str = datetime.now().strftime("%Y%m%d")
271 285
  286 + # 获取name mappings用于debug模式
  287 + name_mappings = {}
  288 + if args.debug:
  289 + log_processing_step(logger, "获取物品名称映射")
  290 + name_mappings = fetch_name_mappings(engine, debug=True)
  291 +
272 # 1. 基于名称文本向量 292 # 1. 基于名称文本向量
273 log_processing_step(logger, "生成基于名称文本向量的相似索引") 293 log_processing_step(logger, "生成基于名称文本向量的相似索引")
274 name_result = generate_similarity_index( 294 name_result = generate_similarity_index(
275 - es, active_items, 'embedding_name_zh', 'name', logger 295 + es, active_items, 'embedding_name_zh', 'name', logger, top_n=top_n
276 ) 296 )
277 name_output = os.path.join(OUTPUT_DIR, f'i2i_content_name_{date_str}.txt') 297 name_output = os.path.join(OUTPUT_DIR, f'i2i_content_name_{date_str}.txt')
278 save_index_file(name_result, es, name_output, logger) 298 save_index_file(name_result, es, name_output, logger)
279 299
  300 + # 如果启用debug模式,保存可读格式
  301 + if args.debug and name_result:
  302 + log_processing_step(logger, "保存i2i_content_name可读格式")
  303 + # 转换数据格式为 {item_id: [(sim_id, score), ...]}
  304 + readable_data = {}
  305 + for item_id, similar_items in name_result.items():
  306 + readable_data[f"i2i:content_name:{item_id}"] = [
  307 + (sim_id, score) for sim_id, score, _ in similar_items
  308 + ]
  309 + save_readable_index(
  310 + name_output,
  311 + readable_data,
  312 + name_mappings,
  313 + description='i2i:content_name'
  314 + )
  315 +
280 # 2. 基于图片向量 316 # 2. 基于图片向量
281 log_processing_step(logger, "生成基于图片向量的相似索引") 317 log_processing_step(logger, "生成基于图片向量的相似索引")
282 pic_result = generate_similarity_index( 318 pic_result = generate_similarity_index(
283 - es, active_items, 'embedding_pic_h14', 'pic', logger 319 + es, active_items, 'embedding_pic_h14', 'pic', logger, top_n=top_n
284 ) 320 )
285 pic_output = os.path.join(OUTPUT_DIR, f'i2i_content_pic_{date_str}.txt') 321 pic_output = os.path.join(OUTPUT_DIR, f'i2i_content_pic_{date_str}.txt')
286 save_index_file(pic_result, es, pic_output, logger) 322 save_index_file(pic_result, es, pic_output, logger)
287 323
  324 + # 如果启用debug模式,保存可读格式
  325 + if args.debug and pic_result:
  326 + log_processing_step(logger, "保存i2i_content_pic可读格式")
  327 + # 转换数据格式为 {item_id: [(sim_id, score), ...]}
  328 + readable_data = {}
  329 + for item_id, similar_items in pic_result.items():
  330 + readable_data[f"i2i:content_pic:{item_id}"] = [
  331 + (sim_id, score) for sim_id, score, _ in similar_items
  332 + ]
  333 + save_readable_index(
  334 + pic_output,
  335 + readable_data,
  336 + name_mappings,
  337 + description='i2i:content_pic'
  338 + )
  339 +
288 logger.info("="*80) 340 logger.info("="*80)
289 logger.info("完成!生成了两份内容相似索引:") 341 logger.info("完成!生成了两份内容相似索引:")
290 logger.info(f" 1. 名称向量索引: {name_output} ({len(name_result)} 个商品)") 342 logger.info(f" 1. 名称向量索引: {name_output} ({len(name_result)} 个商品)")
offline_tasks/scripts/i2i_item_behavior.py
@@ -6,6 +6,7 @@ from sqlalchemy import create_engine @@ -6,6 +6,7 @@ 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 +from scripts.debug_utils import save_readable_index
9 10
10 def clean_text_field(text): 11 def clean_text_field(text):
11 if pd.isna(text): 12 if pd.isna(text):
@@ -127,3 +128,25 @@ print(f&quot; - 商品数: {len(result)}&quot;) @@ -127,3 +128,25 @@ print(f&quot; - 商品数: {len(result)}&quot;)
127 if result: 128 if result:
128 avg_sims = sum(len(sims) for sims in result.values()) / len(result) 129 avg_sims = sum(len(sims) for sims in result.values()) / len(result)
129 print(f" - 平均相似商品数: {avg_sims:.1f}") 130 print(f" - 平均相似商品数: {avg_sims:.1f}")
  131 +
  132 +# 如果启用debug模式,保存可读格式
  133 +if args.debug and result:
  134 + print("[DEBUG] 保存可读格式文件...")
  135 +
  136 + # 准备name_mappings
  137 + name_mappings = {
  138 + 'item': {str(k): clean_text_field(v) for k, v in item_name_map.items()}
  139 + }
  140 +
  141 + # 转换数据格式为 {key: [(sim_id, score), ...]}
  142 + readable_data = {}
  143 + for item_id, sims in result.items():
  144 + readable_data[f"i2i:item_behavior:{item_id}"] = sims
  145 +
  146 + save_readable_index(
  147 + output_file,
  148 + readable_data,
  149 + name_mappings,
  150 + description='i2i:item_behavior'
  151 + )
  152 + print(f" - 可读文件: {output_file.replace('.txt', '_readable.txt')}")
offline_tasks/scripts/tag_category_similar.py
@@ -35,7 +35,7 @@ SELECT @@ -35,7 +35,7 @@ SELECT
35 sp.code AS `PO单号`, 35 sp.code AS `PO单号`,
36 psm.name AS `区域`, 36 psm.name AS `区域`,
37 bb.code AS `客户编码`, 37 bb.code AS `客户编码`,
38 - GROUP_CONCAT(pc_1.name) AS `商品信息`, 38 + GROUP_CONCAT(DISTINCT CONCAT(pc_1.id, ':', pc_1.name)) AS `商品信息`,
39 MIN(spi.order_time) AS `下单货时间` 39 MIN(spi.order_time) AS `下单货时间`
40 FROM sale_po sp 40 FROM sale_po sp
41 INNER JOIN sale_po_item spi ON sp.id = spi.po_id 41 INNER JOIN sale_po_item spi ON sp.id = spi.po_id
@@ -62,6 +62,8 @@ if args.debug: @@ -62,6 +62,8 @@ if args.debug:
62 print(f"[DEBUG] 查询完成,共 {len(df)} 条订单记录") 62 print(f"[DEBUG] 查询完成,共 {len(df)} 条订单记录")
63 63
64 # 处理商品信息,分割并去重 64 # 处理商品信息,分割并去重
  65 +# 构建ID到名称的映射
  66 +cat_id_to_name = {}
65 cooccur = defaultdict(lambda: defaultdict(int)) 67 cooccur = defaultdict(lambda: defaultdict(int))
66 freq = defaultdict(int) 68 freq = defaultdict(int)
67 69
@@ -70,7 +72,15 @@ for _, row in df.iterrows(): @@ -70,7 +72,15 @@ for _, row in df.iterrows():
70 if pd.isna(row['商品信息']): 72 if pd.isna(row['商品信息']):
71 continue 73 continue
72 categories = [cat.strip() for cat in str(row['商品信息']).split(',') if cat.strip()] 74 categories = [cat.strip() for cat in str(row['商品信息']).split(',') if cat.strip()]
73 - unique_cats = set(categories) 75 + unique_cats = set()
  76 + for cat_pair in categories:
  77 + if ':' in cat_pair:
  78 + cat_id, cat_name = cat_pair.split(':', 1)
  79 + cat_id = cat_id.strip()
  80 + cat_name = cat_name.strip()
  81 + cat_id_to_name[cat_id] = cat_name
  82 + unique_cats.add(cat_id)
  83 +
74 for c1 in unique_cats: 84 for c1 in unique_cats:
75 freq[c1] += 1 85 freq[c1] += 1
76 for c2 in unique_cats: 86 for c2 in unique_cats:
@@ -105,22 +115,50 @@ if args.debug: @@ -105,22 +115,50 @@ if args.debug:
105 # 准备输出 115 # 准备输出
106 date_str = datetime.now().strftime('%Y%m%d') 116 date_str = datetime.now().strftime('%Y%m%d')
107 output_dir = 'output' 117 output_dir = 'output'
  118 +debug_dir = os.path.join(output_dir, 'debug')
108 os.makedirs(output_dir, exist_ok=True) 119 os.makedirs(output_dir, exist_ok=True)
  120 +os.makedirs(debug_dir, exist_ok=True)
109 output_file = os.path.join(output_dir, f'tag_category_similar_{date_str}.txt') 121 output_file = os.path.join(output_dir, f'tag_category_similar_{date_str}.txt')
  122 +debug_file = os.path.join(debug_dir, f'tag_category_similar_{date_str}_readable.txt')
110 123
111 -# 输出相似分类到文件 124 +# 输出相似分类到文件(ID格式)
112 if args.debug: 125 if args.debug:
113 print(f"[DEBUG] 开始写入文件: {output_file}") 126 print(f"[DEBUG] 开始写入文件: {output_file}")
114 127
115 with open(output_file, 'w', encoding='utf-8') as f: 128 with open(output_file, 'w', encoding='utf-8') as f:
116 - for cat, sims in sorted(result.items()):  
117 - cat_clean = clean_text_field(cat)  
118 - # 格式: category_name \t similar_cat1:score1,similar_cat2:score2,...  
119 - sim_str = ','.join([f'{clean_text_field(sim_cat)}:{score:.4f}' for sim_cat, score in sims])  
120 - f.write(f'{cat_clean}\t{sim_str}\n') 129 + for cat_id, sims in sorted(result.items()):
  130 + # 格式: category_id \t similar_id1:score1,similar_id2:score2,...
  131 + sim_str = ','.join([f'{sim_id}:{score:.4f}' for sim_id, score in sims])
  132 + f.write(f'{cat_id}\t{sim_str}\n')
  133 +
  134 +# 输出可读版本到debug目录(ID+名称格式)
  135 +if args.debug:
  136 + print(f"[DEBUG] 开始写入可读文件: {debug_file}")
  137 +
  138 +with open(debug_file, 'w', encoding='utf-8') as f:
  139 + # 写入文件头信息
  140 + f.write('='*80 + '\n')
  141 + f.write('明文索引文件\n')
  142 + f.write(f'生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
  143 + f.write(f'描述: tag_category_similar (分类相似度)\n')
  144 + f.write(f'总索引数: {len(result)}\n')
  145 + f.write('='*80 + '\n\n')
  146 +
  147 + for cat_id, sims in sorted(result.items()):
  148 + cat_name = cat_id_to_name.get(cat_id, 'Unknown')
  149 + cat_clean = clean_text_field(cat_name)
  150 + # 格式: category_id:category_name \t similar_id1:similar_name1:score1,...
  151 + sim_parts = []
  152 + for sim_id, score in sims:
  153 + sim_name = cat_id_to_name.get(sim_id, 'Unknown')
  154 + sim_clean = clean_text_field(sim_name)
  155 + sim_parts.append(f'{sim_id}:{sim_clean}:{score:.4f}')
  156 + sim_str = ','.join(sim_parts)
  157 + f.write(f'{cat_id}:{cat_clean}\t{sim_str}\n')
121 158
122 print(f"✓ Tag相似度计算完成") 159 print(f"✓ Tag相似度计算完成")
123 print(f" - 输出文件: {output_file}") 160 print(f" - 输出文件: {output_file}")
  161 +print(f" - 可读文件: {debug_file}")
124 print(f" - 分类数: {len(result)}") 162 print(f" - 分类数: {len(result)}")
125 if result: 163 if result:
126 avg_sims = sum(len(sims) for sims in result.values()) / len(result) 164 avg_sims = sum(len(sims) for sims in result.values()) / len(result)