Blame view

offline_tasks/scripts/interest_aggregation.py 21.3 KB
5ab1c29c   tangwang   first commit
1
2
3
4
  """
  兴趣点聚合索引生成
  按照多个维度(平台、国家、客户类型、分类、列表类型)生成商品索引
  """
5ab1c29c   tangwang   first commit
5
6
  import pandas as pd
  import math
e89d7a84   tangwang   deepwalk refactor...
7
  import os
5ab1c29c   tangwang   first commit
8
9
10
11
12
  import argparse
  import json
  from datetime import datetime, timedelta
  from collections import defaultdict, Counter
  from db_service import create_db_connection
c9f77c8f   tangwang   deepwalk refactor...
13
  from config.offline_config import (
8b9ea8ee   tangwang   feat(recommendati...
14
      DB_CONFIG, OUTPUT_DIR, INTEREST_AGGREGATION_CONFIG, ITEM_FRESHNESS_CONFIG, get_time_range,
5ab1c29c   tangwang   first commit
15
16
      DEFAULT_LOOKBACK_DAYS, DEFAULT_RECENT_DAYS, DEFAULT_INTEREST_TOP_N
  )
c9f77c8f   tangwang   deepwalk refactor...
17
  from scripts.debug_utils import (
14f3dcbe   tangwang   offline tasks
18
      setup_debug_logger, log_dataframe_info, log_dict_stats,
092804bc   tangwang   fix(offline): 修复离...
19
20
21
      save_readable_index, log_algorithm_params,
      log_processing_step, coerce_required_int_column, coerce_optional_numeric_columns,
      load_item_name_mappings
14f3dcbe   tangwang   offline tasks
22
  )
8b9ea8ee   tangwang   feat(recommendati...
23
  from scripts.item_freshness import get_item_age_cutoff_date
5ab1c29c   tangwang   first commit
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  
  
  def calculate_time_weight(event_time, reference_time, decay_factor=0.95, days_unit=30):
      """
      计算时间衰减权重
      
      Args:
          event_time: 事件发生时间
          reference_time: 参考时间(当前时间)
          decay_factor: 衰减因子
          days_unit: 衰减单位(天)
      
      Returns:
          时间权重
      """
      if pd.isna(event_time):
          return 1.0
      
      time_diff = (reference_time - event_time).days
      if time_diff < 0:
          return 1.0
      
      # 计算衰减权重
      periods = time_diff / days_unit
      weight = math.pow(decay_factor, periods)
      return weight
  
  
8b9ea8ee   tangwang   feat(recommendati...
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
  def add_item_freshness_weights(df, reference_time=None, logger=None):
      """
      按商品上架时间计算新鲜度权重。行业/地域维度使用更短半衰期,top 更偏新。
      """
      reference_time = reference_time or datetime.now()
      default_half_life = ITEM_FRESHNESS_CONFIG['default_half_life_days']
      strong_half_life = min(
          ITEM_FRESHNESS_CONFIG['category_half_life_days'],
          ITEM_FRESHNESS_CONFIG['region_half_life_days'],
          ITEM_FRESHNESS_CONFIG.get('platform_half_life_days', 180),
      )
      min_weight = ITEM_FRESHNESS_CONFIG['min_freshness_weight']
      unknown_weight = ITEM_FRESHNESS_CONFIG['unknown_age_weight']
  
      age_days = (reference_time - df['item_create_time']).dt.days
      age_days = age_days.clip(lower=0)
  
      df['fresh_weight_default'] = (0.5 ** (age_days / float(default_half_life))).clip(lower=min_weight)
      df['fresh_weight_strong'] = (0.5 ** (age_days / float(strong_half_life))).clip(lower=min_weight)
  
      unknown_mask = df['item_create_time'].isna()
      df.loc[unknown_mask, 'fresh_weight_default'] = unknown_weight
      df.loc[unknown_mask, 'fresh_weight_strong'] = unknown_weight
  
      if logger:
          known = (~unknown_mask).sum()
          logger.info(
              f"商品新鲜度权重: known={known}, unknown={int(unknown_mask.sum())}, "
              f"default_half_life={default_half_life}d, strong_half_life={strong_half_life}d, "
              f"avg_default={df['fresh_weight_default'].mean():.4f}, "
              f"avg_strong={df['fresh_weight_strong'].mean():.4f}"
          )
      return df
  
  
5ab1c29c   tangwang   first commit
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
  def aggregate_by_dimensions(df, behavior_weights, time_decay=True, decay_factor=0.95):
      """
      按多维度聚合商品
      
      Args:
          df: DataFrame with necessary columns
          behavior_weights: 行为权重字典
          time_decay: 是否使用时间衰减
          decay_factor: 时间衰减因子
      
      Returns:
          Dict: {dimension_key: {item_id: score}}
      """
      reference_time = datetime.now()
      
      # 添加行为权重
      df['behavior_weight'] = df['event_type'].map(behavior_weights).fillna(1.0)
      
      # 添加时间权重
      if time_decay:
          df['time_weight'] = df['create_time'].apply(
              lambda x: calculate_time_weight(x, reference_time, decay_factor)
          )
      else:
          df['time_weight'] = 1.0
8b9ea8ee   tangwang   feat(recommendati...
112
113
114
  
      if 'fresh_weight_default' not in df.columns or 'fresh_weight_strong' not in df.columns:
          df = add_item_freshness_weights(df, reference_time)
5ab1c29c   tangwang   first commit
115
      
8b9ea8ee   tangwang   feat(recommendati...
116
      # 计算最终权重(事件时间衰减 × 商品新鲜度,行业/地域用更强新鲜度)
5ab1c29c   tangwang   first commit
117
118
119
120
121
122
123
124
      df['final_weight'] = df['behavior_weight'] * df['time_weight']
      
      # 初始化聚合结果
      aggregations = defaultdict(lambda: defaultdict(float))
      
      # 遍历数据,按不同维度聚合
      for _, row in df.iterrows():
          item_id = row['item_id']
8b9ea8ee   tangwang   feat(recommendati...
125
126
127
128
129
130
131
132
          weight_default = row['final_weight'] * row['fresh_weight_default']
          weight_strong = row['final_weight'] * row['fresh_weight_strong']
  
          # 行业/地域/平台:仅 2 年内商品进入这些维度
          allow_strict = True
          if 'is_strict_fresh' in row:
              allow_strict = bool(row['is_strict_fresh'])
  
5ab1c29c   tangwang   first commit
133
          # 维度1: 业务平台 (business_platform)
8b9ea8ee   tangwang   feat(recommendati...
134
          if allow_strict and pd.notna(row.get('platform')):
5ab1c29c   tangwang   first commit
135
              key = f"platform:{row['platform']}"
8b9ea8ee   tangwang   feat(recommendati...
136
              aggregations[key][item_id] += weight_strong
5ab1c29c   tangwang   first commit
137
138
          
          # 维度2: 客户端平台 (client_platform)
8b9ea8ee   tangwang   feat(recommendati...
139
          if allow_strict and pd.notna(row.get('client_platform')):
5ab1c29c   tangwang   first commit
140
              key = f"client_platform:{row['client_platform']}"
8b9ea8ee   tangwang   feat(recommendati...
141
              aggregations[key][item_id] += weight_strong
5ab1c29c   tangwang   first commit
142
143
144
145
          
          # 维度3: 供应商 (supplier_id)
          if pd.notna(row.get('supplier_id')):
              key = f"supplier:{row['supplier_id']}"
8b9ea8ee   tangwang   feat(recommendati...
146
              aggregations[key][item_id] += weight_default
5ab1c29c   tangwang   first commit
147
148
          
          # 维度4: 一级分类 (category_level1)
8b9ea8ee   tangwang   feat(recommendati...
149
          if allow_strict and pd.notna(row.get('category_level1_id')):
5ab1c29c   tangwang   first commit
150
              key = f"category_level1:{row['category_level1_id']}"
8b9ea8ee   tangwang   feat(recommendati...
151
              aggregations[key][item_id] += weight_strong
5ab1c29c   tangwang   first commit
152
153
          
          # 维度5: 二级分类 (category_level2)
8b9ea8ee   tangwang   feat(recommendati...
154
          if allow_strict and pd.notna(row.get('category_level2_id')):
5ab1c29c   tangwang   first commit
155
              key = f"category_level2:{row['category_level2_id']}"
8b9ea8ee   tangwang   feat(recommendati...
156
              aggregations[key][item_id] += weight_strong
5ab1c29c   tangwang   first commit
157
158
          
          # 维度6: 三级分类 (category_level3)
8b9ea8ee   tangwang   feat(recommendati...
159
          if allow_strict and pd.notna(row.get('category_level3_id')):
5ab1c29c   tangwang   first commit
160
              key = f"category_level3:{row['category_level3_id']}"
8b9ea8ee   tangwang   feat(recommendati...
161
              aggregations[key][item_id] += weight_strong
5ab1c29c   tangwang   first commit
162
163
          
          # 维度7: 四级分类 (category_level4)
8b9ea8ee   tangwang   feat(recommendati...
164
          if allow_strict and pd.notna(row.get('category_level4_id')):
5ab1c29c   tangwang   first commit
165
              key = f"category_level4:{row['category_level4_id']}"
8b9ea8ee   tangwang   feat(recommendati...
166
              aggregations[key][item_id] += weight_strong
5ab1c29c   tangwang   first commit
167
168
          
          # 组合维度: 业务平台 + 客户端平台
8b9ea8ee   tangwang   feat(recommendati...
169
          if allow_strict and pd.notna(row.get('platform')) and pd.notna(row.get('client_platform')):
5ab1c29c   tangwang   first commit
170
              key = f"platform_client:{row['platform']}_{row['client_platform']}"
8b9ea8ee   tangwang   feat(recommendati...
171
              aggregations[key][item_id] += weight_strong
5ab1c29c   tangwang   first commit
172
173
          
          # 组合维度: 平台 + 二级分类
8b9ea8ee   tangwang   feat(recommendati...
174
          if allow_strict and pd.notna(row.get('platform')) and pd.notna(row.get('category_level2_id')):
5ab1c29c   tangwang   first commit
175
              key = f"platform_category2:{row['platform']}_{row['category_level2_id']}"
8b9ea8ee   tangwang   feat(recommendati...
176
              aggregations[key][item_id] += weight_strong
5ab1c29c   tangwang   first commit
177
178
          
          # 组合维度: 平台 + 三级分类
8b9ea8ee   tangwang   feat(recommendati...
179
          if allow_strict and pd.notna(row.get('platform')) and pd.notna(row.get('category_level3_id')):
5ab1c29c   tangwang   first commit
180
              key = f"platform_category3:{row['platform']}_{row['category_level3_id']}"
8b9ea8ee   tangwang   feat(recommendati...
181
              aggregations[key][item_id] += weight_strong
5ab1c29c   tangwang   first commit
182
183
          
          # 组合维度: 客户端平台 + 二级分类
8b9ea8ee   tangwang   feat(recommendati...
184
          if allow_strict and pd.notna(row.get('client_platform')) and pd.notna(row.get('category_level2_id')):
5ab1c29c   tangwang   first commit
185
              key = f"client_category2:{row['client_platform']}_{row['category_level2_id']}"
8b9ea8ee   tangwang   feat(recommendati...
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
              aggregations[key][item_id] += weight_strong
  
          # 新增维度:平台 + 国家代码(仅essa和essaone平台)
          if allow_strict and pd.notna(row.get('platform')) and pd.notna(row.get('country_code')):
              platform_val = row['platform']
              # 只为essa和essaone平台生成这些维度
              if platform_val in ['essa', 'essaone']:
                  key = f"platform:{platform_val};country_code:{row['country_code']}"
                  aggregations[key][item_id] += weight_strong
  
          # 新增维度:平台 + 国家代码 + 客户类型(仅essa和essaone平台)
          if allow_strict and pd.notna(row.get('platform')) and pd.notna(row.get('country_code')):
              platform_val = row['platform']
              # 只为essa和essaone平台生成这些维度
              if platform_val in ['essa', 'essaone']:
                  # 根据平台使用不同的客户类型字段
                  customer_type = None
                  if platform_val == 'essa':
                      # essa平台使用buy_buyer.sell_channel
                      customer_type = row.get('customer_type_sell_channel')
                  elif platform_val == 'essaone':
                      # essaone平台使用buy_buyer_extend_option.code
                      customer_type = row.get('customer_type_extend')
  
                  # 如果客户类型不为空,则生成维度
                  if pd.notna(customer_type):
                      key = f"platform:{platform_val};country_code:{row['country_code']};customer_type:{customer_type}"
                      aggregations[key][item_id] += weight_strong
  
5ab1c29c   tangwang   first commit
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
      return aggregations
  
  
  def generate_list_type_indices(df_hot, df_cart, df_new, behavior_weights):
      """
      生成不同列表类型的索引(热门、加购、新品)
      
      Args:
          df_hot: 热门商品数据
          df_cart: 加购商品数据
          df_new: 新品数据
          behavior_weights: 行为权重
      
      Returns:
          Dict: {list_type: aggregations}
      """
      list_type_indices = {}
      
      # 热门商品索引
      if not df_hot.empty:
          print("Generating hot item indices...")
9832fef6   tangwang   offline tasks
236
          # B2B低频场景,不使用时间衰减
5ab1c29c   tangwang   first commit
237
          list_type_indices['hot'] = aggregate_by_dimensions(
9832fef6   tangwang   offline tasks
238
              df_hot, behavior_weights, time_decay=False
5ab1c29c   tangwang   first commit
239
240
241
242
243
          )
      
      # 加购商品索引
      if not df_cart.empty:
          print("Generating cart item indices...")
9832fef6   tangwang   offline tasks
244
          # B2B低频场景,不使用时间衰减
5ab1c29c   tangwang   first commit
245
          list_type_indices['cart'] = aggregate_by_dimensions(
9832fef6   tangwang   offline tasks
246
              df_cart, behavior_weights, time_decay=False
5ab1c29c   tangwang   first commit
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
          )
      
      # 新品索引
      if not df_new.empty:
          print("Generating new item indices...")
          # 新品不使用时间衰减,因为新品本身就是时间敏感的
          list_type_indices['new'] = aggregate_by_dimensions(
              df_new, behavior_weights, time_decay=False
          )
      
      return list_type_indices
  
  
  def output_indices(aggregations, output_prefix, top_n=1000):
      """
      输出索引到文件
      
      Args:
          aggregations: 聚合结果 {dimension_key: {item_id: score}}
          output_prefix: 输出文件前缀
          top_n: 每个维度输出前N个商品
      """
      output_file = os.path.join(OUTPUT_DIR, f'{output_prefix}_{datetime.now().strftime("%Y%m%d")}.txt')
      
      print(f"Writing indices to {output_file}...")
      with open(output_file, 'w', encoding='utf-8') as f:
          for dim_key, items in aggregations.items():
              # 按分数排序,取前N个
              sorted_items = sorted(items.items(), key=lambda x: -x[1])[:top_n]
              
              if not sorted_items:
                  continue
              
              # 格式:dimension_key \t item_id1:score1,item_id2:score2,...
              items_str = ','.join([f'{item_id}:{score:.4f}' for item_id, score in sorted_items])
              f.write(f'{dim_key}\t{items_str}\n')
      
      print(f"Output saved to: {output_file}")
      print(f"Generated indices for {len(aggregations)} dimension keys")
  
  
  def main():
      parser = argparse.ArgumentParser(description='Generate interest aggregation indices')
      parser.add_argument('--top_n', type=int, default=DEFAULT_INTEREST_TOP_N,
                         help=f'Top N items per dimension (default: {DEFAULT_INTEREST_TOP_N})')
      parser.add_argument('--lookback_days', type=int, default=DEFAULT_LOOKBACK_DAYS,
                         help=f'Number of days to look back (default: {DEFAULT_LOOKBACK_DAYS})')
      parser.add_argument('--recent_days', type=int, default=DEFAULT_RECENT_DAYS,
                         help=f'Recent days for hot items (default: {DEFAULT_RECENT_DAYS})')
      parser.add_argument('--new_days', type=int, default=DEFAULT_RECENT_DAYS,
                         help=f'Days for new items (default: {DEFAULT_RECENT_DAYS})')
be0b3c5a   tangwang   /home/tw/recommen...
298
299
300
301
302
303
      parser.add_argument('--max_item_age_days', type=int,
                         default=ITEM_FRESHNESS_CONFIG['max_item_age_days'],
                         help='Drop items older than this many days before indexing (default: 30)')
      parser.add_argument('--strict_item_age_days', type=int,
                         default=ITEM_FRESHNESS_CONFIG.get('strict_item_age_days', 30),
                         help='Category/region/platform dimension cutoff days (default: 30)')
5ab1c29c   tangwang   first commit
304
305
306
307
      parser.add_argument('--decay_factor', type=float, default=INTEREST_AGGREGATION_CONFIG['time_decay_factor'],
                         help='Time decay factor')
      parser.add_argument('--output_prefix', type=str, default='interest_aggregation',
                         help='Output file prefix')
1721766b   tangwang   offline tasks
308
309
      parser.add_argument('--debug', action='store_true',
                         help='Enable debug mode with detailed logging and readable output')
5ab1c29c   tangwang   first commit
310
311
312
      
      args = parser.parse_args()
      
14f3dcbe   tangwang   offline tasks
313
314
315
316
317
318
319
320
321
      # 设置logger
      logger = setup_debug_logger('interest_aggregation', debug=args.debug)
      
      # 记录算法参数
      params = {
          'top_n': args.top_n,
          'lookback_days': args.lookback_days,
          'recent_days': args.recent_days,
          'new_days': args.new_days,
be0b3c5a   tangwang   /home/tw/recommen...
322
323
          'max_item_age_days': args.max_item_age_days,
          'strict_item_age_days': args.strict_item_age_days,
14f3dcbe   tangwang   offline tasks
324
325
326
327
328
          'decay_factor': args.decay_factor,
          'debug': args.debug
      }
      log_algorithm_params(logger, params)
      
5ab1c29c   tangwang   first commit
329
      # 创建数据库连接
14f3dcbe   tangwang   offline tasks
330
      logger.info("连接数据库...")
5ab1c29c   tangwang   first commit
331
332
333
334
335
336
337
338
339
340
341
342
      engine = create_db_connection(
          DB_CONFIG['host'],
          DB_CONFIG['port'],
          DB_CONFIG['database'],
          DB_CONFIG['username'],
          DB_CONFIG['password']
      )
      
      # 获取时间范围
      start_date, end_date = get_time_range(args.lookback_days)
      recent_start_date, _ = get_time_range(args.recent_days)
      new_start_date, _ = get_time_range(args.new_days)
be0b3c5a   tangwang   /home/tw/recommen...
343
344
      item_cutoff_date = get_item_age_cutoff_date(args.max_item_age_days)
      strict_cutoff_date = get_item_age_cutoff_date(args.strict_item_age_days)
5ab1c29c   tangwang   first commit
345
      
14f3dcbe   tangwang   offline tasks
346
      logger.info(f"获取数据范围:{start_date} 到 {end_date}")
be0b3c5a   tangwang   /home/tw/recommen...
347
      logger.info(f"商品新鲜度截断:默认 >= {item_cutoff_date} ({args.max_item_age_days} 天);行业/地域/平台 >= {strict_cutoff_date} ({args.strict_item_age_days} 天)")
14f3dcbe   tangwang   offline tasks
348
349
      logger.debug(f"热门商品起始日期:{recent_start_date}")
      logger.debug(f"新品起始日期:{new_start_date}")
5ab1c29c   tangwang   first commit
350
351
352
      
      # SQL查询 - 获取用户行为数据(包含用户特征和商品分类)
      sql_query = f"""
8b9ea8ee   tangwang   feat(recommendati...
353
      SELECT
5ab1c29c   tangwang   first commit
354
355
356
357
          se.anonymous_id AS user_id,
          se.item_id,
          se.event AS event_type,
          se.create_time,
8b9ea8ee   tangwang   feat(recommendati...
358
          se.login_id,
5ab1c29c   tangwang   first commit
359
360
361
362
363
364
365
366
367
          pgs.name AS item_name,
          pgs.create_time AS item_create_time,
          se.business_platform AS platform,
          se.client_platform,
          pg.supplier_id,
          pg.category_id,
          pc_1.id as category_level1_id,
          pc_2.id as category_level2_id,
          pc_3.id as category_level3_id,
8b9ea8ee   tangwang   feat(recommendati...
368
369
370
371
372
          pc_4.id as category_level4_id,
          bb.countries AS country_code,
          bb.sell_channel AS customer_type_sell_channel,
          bbeo.code AS customer_type_extend
      FROM
5ab1c29c   tangwang   first commit
373
374
375
376
377
378
379
380
          sensors_events se
      LEFT JOIN prd_goods_sku pgs ON se.item_id = pgs.id
      LEFT JOIN prd_goods pg ON pg.id = pgs.goods_id
      LEFT JOIN prd_category as pc ON pc.id = pg.category_id
      LEFT JOIN prd_category AS pc_1 ON pc_1.id = SUBSTRING_INDEX(SUBSTRING_INDEX(pc.path, '.', 2), '.', -1)
      LEFT JOIN prd_category AS pc_2 ON pc_2.id = SUBSTRING_INDEX(SUBSTRING_INDEX(pc.path, '.', 3), '.', -1)
      LEFT JOIN prd_category AS pc_3 ON pc_3.id = SUBSTRING_INDEX(SUBSTRING_INDEX(pc.path, '.', 4), '.', -1)
      LEFT JOIN prd_category AS pc_4 ON pc_4.id = SUBSTRING_INDEX(SUBSTRING_INDEX(pc.path, '.', 5), '.', -1)
8b9ea8ee   tangwang   feat(recommendati...
381
382
383
384
385
386
387
      -- 关联获取买家信息(国家代码和客户类型)
      LEFT JOIN buy_account ba ON ba.id = se.login_id
      LEFT JOIN buy_buyer bb ON bb.id = ba.buyer_id
      -- 关联获取essaone平台的客户类型(从buy_buyer_extend_option表)
      LEFT JOIN buy_buyer_extend bbe ON bbe.buyer_id = bb.id
      LEFT JOIN buy_buyer_extend_option bbeo ON bbe.id = bbeo.buyer_extend_id
      WHERE
5ab1c29c   tangwang   first commit
388
389
390
391
          se.event IN ('click', 'contactFactory', 'addToPool', 'addToCart', 'purchase')
          AND se.create_time >= '{start_date}'
          AND se.create_time <= '{end_date}'
          AND se.item_id IS NOT NULL
8b9ea8ee   tangwang   feat(recommendati...
392
393
          AND (pgs.create_time IS NULL OR pgs.create_time >= '{item_cutoff_date}')
      ORDER BY
5ab1c29c   tangwang   first commit
394
395
396
          se.create_time
      """
      
14f3dcbe   tangwang   offline tasks
397
      logger.info("执行SQL查询...")
5ab1c29c   tangwang   first commit
398
      df = pd.read_sql(sql_query, engine)
14f3dcbe   tangwang   offline tasks
399
400
      logger.info(f"获取到 {len(df)} 条记录")
      
092804bc   tangwang   fix(offline): 修复离...
401
      df = coerce_required_int_column(df, 'item_id', logger=logger)
53fd5f08   tangwang   部分文件id格式不对 fix
402
      df['user_id'] = df['user_id'].astype(str)
092804bc   tangwang   fix(offline): 修复离...
403
404
405
406
407
      df = coerce_optional_numeric_columns(df, [
          'category_id', 'supplier_id', 'login_id',
          'category_level1_id', 'category_level2_id',
          'category_level3_id', 'category_level4_id'
      ])
53fd5f08   tangwang   部分文件id格式不对 fix
408
      
14f3dcbe   tangwang   offline tasks
409
410
      # 记录数据信息
      log_dataframe_info(logger, df, "用户行为数据")
5ab1c29c   tangwang   first commit
411
412
413
414
      
      # 转换时间列
      df['create_time'] = pd.to_datetime(df['create_time'])
      df['item_create_time'] = pd.to_datetime(df['item_create_time'], errors='coerce')
8b9ea8ee   tangwang   feat(recommendati...
415
416
417
418
419
420
421
422
423
424
  
      before_fresh_filter = len(df)
      item_cutoff_ts = pd.Timestamp(item_cutoff_date)
      keep_unknown = ITEM_FRESHNESS_CONFIG['keep_unknown_age']
      if keep_unknown:
          fresh_mask = df['item_create_time'].isna() | (df['item_create_time'] >= item_cutoff_ts)
      else:
          fresh_mask = df['item_create_time'] >= item_cutoff_ts
      df = df[fresh_mask].copy()
      logger.info(
be0b3c5a   tangwang   /home/tw/recommen...
425
          f"按商品创建时间过滤 {args.max_item_age_days} 天前商品: {before_fresh_filter} -> {len(df)} "
8b9ea8ee   tangwang   feat(recommendati...
426
427
428
429
430
431
432
433
          f"(dropped={before_fresh_filter - len(df)}, cutoff={item_cutoff_date})"
      )
      strict_cutoff_ts = pd.Timestamp(strict_cutoff_date)
      if keep_unknown:
          df['is_strict_fresh'] = df['item_create_time'].isna() | (df['item_create_time'] >= strict_cutoff_ts)
      else:
          df['is_strict_fresh'] = df['item_create_time'] >= strict_cutoff_ts
      logger.info(
be0b3c5a   tangwang   /home/tw/recommen...
434
          f"行业/地域/平台 {args.strict_item_age_days} 天可用行: {int(df['is_strict_fresh'].sum())}/{len(df)} "
8b9ea8ee   tangwang   feat(recommendati...
435
436
437
          f"(cutoff={strict_cutoff_date})"
      )
      df = add_item_freshness_weights(df, logger=logger)
5ab1c29c   tangwang   first commit
438
439
440
      
      # 定义行为权重
      behavior_weights = INTEREST_AGGREGATION_CONFIG['behavior_weights']
14f3dcbe   tangwang   offline tasks
441
      logger.debug(f"行为权重: {behavior_weights}")
5ab1c29c   tangwang   first commit
442
443
      
      # 准备不同类型的数据集
14f3dcbe   tangwang   offline tasks
444
      log_processing_step(logger, "准备不同类型的数据集")
5ab1c29c   tangwang   first commit
445
446
447
      
      # 1. 热门商品:最近N天的高交互商品
      df_hot = df[df['create_time'] >= recent_start_date].copy()
14f3dcbe   tangwang   offline tasks
448
      logger.info(f"热门商品数据集:{len(df_hot)} 条记录")
5ab1c29c   tangwang   first commit
449
450
451
      
      # 2. 加购商品:加购行为
      df_cart = df[df['event_type'].isin(['addToCart', 'addToPool'])].copy()
14f3dcbe   tangwang   offline tasks
452
      logger.info(f"加购商品数据集:{len(df_cart)} 条记录")
5ab1c29c   tangwang   first commit
453
454
455
      
      # 3. 新品:商品创建时间在最近N天内
      df_new = df[df['item_create_time'] >= new_start_date].copy()
14f3dcbe   tangwang   offline tasks
456
      logger.info(f"新品数据集:{len(df_new)} 条记录")
5ab1c29c   tangwang   first commit
457
458
      
      # 生成不同列表类型的索引
14f3dcbe   tangwang   offline tasks
459
      log_processing_step(logger, "生成不同列表类型的索引")
5ab1c29c   tangwang   first commit
460
461
462
      list_type_indices = generate_list_type_indices(
          df_hot, df_cart, df_new, behavior_weights
      )
14f3dcbe   tangwang   offline tasks
463
464
465
466
467
      logger.info(f"生成了 {len(list_type_indices)} 种列表类型的索引")
      
      # 获取name mappings用于debug输出
      name_mappings = {}
      if args.debug:
092804bc   tangwang   fix(offline): 修复离...
468
469
          logger.info("加载物品名称映射...")
          name_mappings = load_item_name_mappings(engine=engine, debug=True, logger=logger)
5ab1c29c   tangwang   first commit
470
471
      
      # 输出索引
14f3dcbe   tangwang   offline tasks
472
      log_processing_step(logger, "保存索引文件")
5ab1c29c   tangwang   first commit
473
474
      for list_type, aggregations in list_type_indices.items():
          output_prefix = f'{args.output_prefix}_{list_type}'
14f3dcbe   tangwang   offline tasks
475
          logger.info(f"保存 {list_type} 类型的索引...")
5ab1c29c   tangwang   first commit
476
          output_indices(aggregations, output_prefix, top_n=args.top_n)
14f3dcbe   tangwang   offline tasks
477
478
479
480
481
          
          # 如果启用debug模式,保存可读格式
          if args.debug and aggregations:
              for dim_key, items in aggregations.items():
                  if items:
40442baf   tangwang   offline tasks: fi...
482
483
484
                      # 为每个维度生成可读索引 - 先排序再取前N个
                      sorted_items = sorted(items.items(), key=lambda x: -x[1])[:args.top_n]
                      result_dict = {dim_key: sorted_items}
14f3dcbe   tangwang   offline tasks
485
486
487
488
489
490
                      output_file = os.path.join(OUTPUT_DIR, f'{output_prefix}_{dim_key}_{datetime.now().strftime("%Y%m%d")}.txt')
                      if os.path.exists(output_file):
                          save_readable_index(
                              output_file,
                              result_dict,
                              name_mappings,
40442baf   tangwang   offline tasks: fi...
491
                              description=f'interest:{list_type}:{dim_key}'
14f3dcbe   tangwang   offline tasks
492
                          )
5ab1c29c   tangwang   first commit
493
494
      
      # 生成全局索引(所有数据)
14f3dcbe   tangwang   offline tasks
495
      log_processing_step(logger, "生成全局索引")
9832fef6   tangwang   offline tasks
496
      # B2B低频场景,不使用时间衰减
5ab1c29c   tangwang   first commit
497
      global_aggregations = aggregate_by_dimensions(
9832fef6   tangwang   offline tasks
498
          df, behavior_weights, time_decay=False, decay_factor=args.decay_factor
5ab1c29c   tangwang   first commit
499
      )
14f3dcbe   tangwang   offline tasks
500
      logger.info("保存全局索引...")
5ab1c29c   tangwang   first commit
501
502
      output_indices(global_aggregations, f'{args.output_prefix}_global', top_n=args.top_n)
      
14f3dcbe   tangwang   offline tasks
503
504
505
      logger.info("="*80)
      logger.info("所有索引生成完成!")
      logger.info("="*80)
5ab1c29c   tangwang   first commit
506
507
508
509
  
  
  if __name__ == '__main__':
      main()