File size: 22,300 Bytes
c55ff91 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 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 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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 | import os
import json
import gzip
import pickle
import logging
from collections import defaultdict
from typing import Dict, List, Tuple, Optional
import pandas as pd
from tqdm import tqdm
import numpy as np
from scipy.sparse import lil_matrix, save_npz
from huggingface_hub import HfApi, hf_hub_download
def _open_any(path: str):
if path.endswith(".gz"):
return gzip.open(path, "rt", encoding="utf-8")
return open(path, "r", encoding="utf-8")
def _clean_title(s: str) -> str:
if not isinstance(s, str):
return ""
import html as _html
s = _html.unescape(s)
return " ".join(s.split())
def _load_asin2title(meta_file_path: str) -> Dict[str, str]:
"""meta_{dataset}.json(.gz) line-delimited JSON에서 asin→cleaned title 맵 생성"""
asin2title = {}
with _open_any(meta_file_path) as f:
for line in f:
line = line.strip()
if not line:
continue
try:
d = json.loads(line)
except json.JSONDecodeError:
continue
# parent_asin 또는 asin 키 모두 지원
asin = d.get("parent_asin") or d.get("asin")
title = _clean_title(d.get("title", ""))
if asin:
asin2title[asin] = (title if title else "empty title")
return asin2title
# ---------------------------------------------------
def _download_hf_csv(repo_id: str, path: str, repo_type: str = "dataset") -> str:
return hf_hub_download(repo_id=repo_id, repo_type=repo_type, filename=path)
def _load_hf_last_out_splits(
fname: str,
core: str,
repo_id: str,
user_col: str,
item_col: str,
time_col: str,
rating_col: Optional[str] = None,
logger=None,
):
log = logger or logging.getLogger(__name__)
api = HfApi()
log.info("Listing HF repo files for last_out splits...")
files = set(api.list_repo_files(repo_id=repo_id, repo_type="dataset"))
prefix = f"benchmark/{core}/last_out/"
split_paths = {
"train": f"{prefix}{fname}.train.csv",
"valid": f"{prefix}{fname}.valid.csv",
"test": f"{prefix}{fname}.test.csv",
}
dfs = {}
for split, path in split_paths.items():
if path not in files:
raise RuntimeError(f"Missing HF file: {path}")
log.info(f"Downloading split file: {path}")
local_path = _download_hf_csv(repo_id, path, repo_type="dataset")
df = pd.read_csv(local_path)
log.info(f"Loaded split {split}: {len(df)} rows")
keep_cols = [user_col, item_col, time_col]
if rating_col and rating_col in df.columns:
keep_cols.append(rating_col)
missing = [c for c in keep_cols if c not in df.columns]
if missing:
raise ValueError(f"Missing columns {missing} in {path}. cols={list(df.columns)}")
df = df[keep_cols].copy()
rename_map = {
user_col: "user_id",
item_col: "parent_asin",
time_col: "timestamp",
}
if rating_col:
rename_map[rating_col] = "rating"
df = df.rename(columns=rename_map)
dfs[split] = df
return dfs
def _build_rating_lookup_from_reviews(
review_json_path: str,
keys: set[tuple[str, str, int]],
logger=None,
):
log = logger or logging.getLogger(__name__)
rating_map: dict[tuple[str, str, int], int] = {}
if not keys:
return rating_map
with _open_any(review_json_path) as f:
for line in tqdm(f, desc="Building rating lookup from reviews"):
line = line.strip()
if not line:
continue
try:
d = json.loads(line)
except json.JSONDecodeError:
continue
uid = d.get("reviewerID")
asin = d.get("asin")
ts = d.get("unixReviewTime")
if uid is None or asin is None or ts is None:
continue
key = (str(uid), str(asin), int(ts))
if key not in keys:
continue
score = d.get("overall", d.get("rating", d.get("stars", 0)))
try:
rating = int(float(score))
except Exception:
rating = 0
rating_map[key] = rating
log.info(f"Loaded ratings for {len(rating_map)} interactions.")
return rating_map
def _build_user_sequences(df: pd.DataFrame) -> dict[str, list[tuple[str, int, int]]]:
seqs: dict[str, list[tuple[str, int, int]]] = {}
for uid, sub in df.groupby("user_id", sort=False):
sub = sub.sort_values("timestamp")
items = sub["parent_asin"].astype(str).tolist()
times = sub["timestamp"].astype(int).tolist()
ratings = sub["rating"].astype(int).tolist()
seqs[str(uid)] = list(zip(items, times, ratings))
return seqs
def process_hf_last_out_to_llara(
fname: str,
dataset: str,
output_dir: str,
core: str = "5core",
repo_id: str = "McAuley-Lab/Amazon-Reviews-2023",
user_col: str = "user_id",
item_col: str = "parent_asin",
time_col: str = "timestamp",
rating_col: Optional[str] = None,
review_json_path: Optional[str] = None,
meta_file_path: Optional[str] = None,
default_rating: int = 0,
logger=None,
):
"""
HF last_out(train/valid/test)을 그대로 사용해 LLaRA 입력(train_one/val/test + item_meta) 생성.
"""
log = logger or logging.getLogger(__name__)
os.makedirs(os.path.join(output_dir, dataset), exist_ok=True)
dataset_output_dir = os.path.join(output_dir, dataset)
# meta 파일 경로: 로컬에 없으면 HuggingFace에서 다운로드
if meta_file_path is None:
meta_file_path = os.path.join(os.path.dirname(output_dir), f"meta_{dataset}.json")
if not os.path.exists(meta_file_path) and os.path.exists(meta_file_path + ".gz"):
meta_file_path = meta_file_path + ".gz"
if meta_file_path is None or not os.path.exists(meta_file_path):
# HuggingFace에서 meta 파일 다운로드 시도
hf_meta_filename = f"raw/meta_categories/meta_{dataset}.jsonl"
log.info(f"Downloading meta file from HuggingFace: {repo_id}/{hf_meta_filename}")
try:
meta_file_path = hf_hub_download(
repo_id=repo_id,
repo_type="dataset",
filename=hf_meta_filename,
)
log.info(f"Meta file downloaded to: {meta_file_path}")
except Exception as e:
log.warning(f"Failed to download meta file from HF: {e} (title은 'empty title'로 대체)")
meta_file_path = None
if meta_file_path is None or not os.path.exists(meta_file_path):
log.warning(f"Meta file not found (title은 'empty title'로 대체)")
asin2title = {}
else:
asin2title = _load_asin2title(meta_file_path)
splits = _load_hf_last_out_splits(
fname=fname,
core=core,
repo_id=repo_id,
user_col=user_col,
item_col=item_col,
time_col=time_col,
rating_col=rating_col,
logger=log,
)
for split, df in splits.items():
df = df.dropna(subset=["user_id", "parent_asin", "timestamp"]).copy()
df["timestamp"] = pd.to_numeric(df["timestamp"], errors="coerce")
df = df.dropna(subset=["timestamp"]).copy()
df["timestamp"] = df["timestamp"].astype(np.int64)
splits[split] = df
# review data로 rating 채우기 (필요 시)
if review_json_path:
key_set = set()
for df in splits.values():
for uid, asin, ts in zip(df["user_id"], df["parent_asin"], df["timestamp"]):
key_set.add((str(uid), str(asin), int(ts)))
rating_map = _build_rating_lookup_from_reviews(review_json_path, key_set, logger=log)
for df in splits.values():
df["rating"] = [
int(rating_map.get((str(u), str(a), int(t)), default_rating))
for u, a, t in zip(df["user_id"], df["parent_asin"], df["timestamp"])
]
else:
if rating_col and "rating" in splits["train"].columns:
for df in splits.values():
df["rating"] = pd.to_numeric(df["rating"], errors="coerce").fillna(default_rating).astype(int)
else:
for df in splits.values():
df["rating"] = int(default_rating)
# user/item id mapping (string -> int)
all_users = sorted(set(pd.concat([splits[s]["user_id"] for s in splits]).astype(str)))
all_items = sorted(set(pd.concat([splits[s]["parent_asin"] for s in splits]).astype(str)))
user_id_to_idx = {u: i for i, u in enumerate(all_users)}
asin_to_idx = {a: i for i, a in enumerate(all_items)}
# item_meta.parquet (id, title)
meta_rows = []
for asin, idx in asin_to_idx.items():
title = asin2title.get(asin, "empty title") if asin2title else "empty title"
meta_rows.append({"id": idx, "title": title})
meta_df = pd.DataFrame(meta_rows)
meta_df.to_parquet(os.path.join(dataset_output_dir, "item_meta.parquet"), index=False)
# build per-user sequences
train_seqs = _build_user_sequences(splits["train"])
val_seqs = _build_user_sequences(splits["valid"])
test_seqs = _build_user_sequences(splits["test"])
train_rows = []
val_rows = []
test_rows = []
for u in all_users:
uid = str(u)
uidx = user_id_to_idx[uid]
train_items = [asin_to_idx[a] for a, _, _ in train_seqs.get(uid, [])]
train_ratings = [r for _, _, r in train_seqs.get(uid, [])]
val_items = [asin_to_idx[a] for a, _, _ in val_seqs.get(uid, [])]
val_ratings = [r for _, _, r in val_seqs.get(uid, [])]
test_items = [asin_to_idx[a] for a, _, _ in test_seqs.get(uid, [])]
test_ratings = [r for _, _, r in test_seqs.get(uid, [])]
# train (one per user)
if len(train_items) >= 2:
seq = train_items[:-1]
seq_rating = train_ratings[:-1] if train_ratings else [default_rating] * len(seq)
target = train_items[-1]
target_rating = train_ratings[-1] if train_ratings else default_rating
train_rows.append(
{
"user_id": uidx,
"seq": seq,
"next": int(target),
"len_seq": int(len(seq)),
"seq_rating": seq_rating,
"target_rating": int(target_rating),
}
)
# val (one per user)
if len(val_items) >= 1:
hist = train_items + val_items[:-1]
hist_r = train_ratings + val_ratings[:-1]
if not hist_r:
hist_r = [default_rating] * len(hist)
target = val_items[-1]
target_rating = val_ratings[-1] if val_ratings else default_rating
val_rows.append(
{
"user_id": uidx,
"seq": hist,
"next": int(target),
"len_seq": int(len(hist)),
"seq_rating": hist_r,
"target_rating": int(target_rating),
}
)
# test (one per user)
if len(test_items) >= 1:
hist = train_items + val_items + test_items[:-1]
hist_r = train_ratings + val_ratings + test_ratings[:-1]
if not hist_r:
hist_r = [default_rating] * len(hist)
target = test_items[-1]
target_rating = test_ratings[-1] if test_ratings else default_rating
test_rows.append(
{
"user_id": uidx,
"seq": hist,
"next": int(target),
"len_seq": int(len(hist)),
"seq_rating": hist_r,
"target_rating": int(target_rating),
}
)
train_df = pd.DataFrame(train_rows)
val_df = pd.DataFrame(val_rows)
test_df = pd.DataFrame(test_rows)
train_df.to_pickle(os.path.join(dataset_output_dir, "train_one_data.df"))
val_df.to_pickle(os.path.join(dataset_output_dir, "val_data.df"))
test_df.to_pickle(os.path.join(dataset_output_dir, "test_data.df"))
# mapping files for reference
with open(os.path.join(dataset_output_dir, f"{dataset}_user_id_to_idx.json"), "w") as f:
json.dump(user_id_to_idx, f)
with open(os.path.join(dataset_output_dir, f"{dataset}_item_id_to_idx.json"), "w") as f:
json.dump(asin_to_idx, f)
log.info("HF last_out preprocessing finished.")
return True
def process_data(
json_file_path: str,
dataset: str,
output_dir: str,
count_threshold: int = 5,
logger=None,
meta_file_path: str = None
):
"""
아이템 식별자는 asin.
idx는 asin을 정렬/열거하여 부여하고, title을 매핑(없으면 'empty title').
"""
log = logger or logging.getLogger(__name__)
os.makedirs(os.path.join(output_dir, dataset), exist_ok=True)
dataset_output_dir = os.path.join(output_dir, dataset)
# meta 파일 경로 기본값 추정
if meta_file_path is None:
meta_file_path = os.path.join(os.path.dirname(json_file_path), f"meta_{dataset}.json")
if not os.path.exists(meta_file_path) and os.path.exists(meta_file_path + ".gz"):
meta_file_path = meta_file_path + ".gz"
if not os.path.exists(meta_file_path):
log.warning(f"Meta file not found: {meta_file_path} (title은 'empty title'로 대체)")
asin2title = {}
else:
asin2title = _load_asin2title(meta_file_path)
# 1) Pass1: overall>=3 기준으로 사용자/아이템(asin) 카운팅
user_cnt = defaultdict(int)
item_cnt = defaultdict(int)
try:
with _open_any(json_file_path) as f:
for line in tqdm(f, desc="Pass1: counting (overall>=3)"):
try:
d = json.loads(line)
except json.JSONDecodeError:
continue
try:
score = d.get("overall", d.get("rating", d.get("stars", 0)))
score = float(score)
except Exception:
score = 0
if score < 3:
continue
uid = d.get("reviewerID")
iid_asin = d.get("asin")
if uid is None or iid_asin is None:
continue
user_cnt[uid] += 1
item_cnt[iid_asin] += 1
except Exception as e:
log.error(f"Error during counting pass: {e}")
return False
# 2) Pass2: threshold 통과 상호작용 수집 (asin 기준)
interactions = []
try:
with _open_any(json_file_path) as f:
for line in tqdm(f, desc="Pass2: collect (threshold ok, no rating filter)"):
try:
d = json.loads(line)
except json.JSONDecodeError:
continue
uid = d.get("reviewerID")
iid_asin = d.get("asin")
t = d.get("unixReviewTime")
if uid is None or iid_asin is None or t is None:
continue
if user_cnt[uid] < count_threshold or item_cnt[iid_asin] < count_threshold:
continue
title = _clean_title(asin2title.get(iid_asin, "")) if asin2title else ""
if not title:
title = "empty title"
interactions.append({"user": uid, "asin": iid_asin, "title": title, "time": int(t)})
except Exception as e:
log.error(f"Error during filtering pass: {e}")
return False
if not interactions:
log.error("No interactions left after threshold filtering.")
return False
data_df = pd.DataFrame(interactions)
log.info(f"Collected {len(data_df)} interactions after filtering.")
# 3) 유저별 시간 정렬 시퀀스 (asin, time)
interactions_by_user_timed: Dict[str, List[Tuple[str, int]]] = (
data_df.groupby("user", sort=False)
.apply(lambda x: sorted(list(zip(x["asin"], x["time"])), key=lambda k: k[1]))
.to_dict()
)
# 4) asin 기반 인덱스 부여
final_users = list(interactions_by_user_timed.keys())
final_asins = {asin for seq in interactions_by_user_timed.values() for asin, _ in seq}
user_id_list = sorted(final_users)
asin_list = sorted(final_asins)
user_id_to_idx = {u: i for i, u in enumerate(user_id_list)}
asin_to_idx = {a: i for i, a in enumerate(asin_list)}
idx_to_asin = {i: a for a, i in asin_to_idx.items()}
# idx → title 매핑 만들기 (없으면 'empty title')
idx_to_title = {i: (asin2title.get(idx_to_asin[i], "empty title")) for i in range(len(asin_list))}
num_users = len(user_id_list)
num_items = len(asin_list)
log.info(f"[ASIN-INDEXED] Final num_users={num_users}, num_items={num_items}")
# 5) 행렬/시퀀스 구성 (열=asin index)
interaction_matrix = lil_matrix((num_users, num_items), dtype=np.float32)
eval_sequences: Dict[int, List[int]] = {}
for user_id, seq_tuples in tqdm(interactions_by_user_timed.items(), desc="Build matrix & sequences (asin-indexed)"):
uidx = user_id_to_idx[user_id]
item_idx_sequence = []
for asin, _t in seq_tuples:
if asin in asin_to_idx:
item_idx_sequence.append(asin_to_idx[asin])
if not item_idx_sequence:
continue
eval_sequences[uidx] = item_idx_sequence
for itx in item_idx_sequence[:-1]:
interaction_matrix[uidx, itx] = 1.0
log.info(f"Final interaction count for matrix: {interaction_matrix.nnz}")
log.info(f"Final matrix shape: ({num_users}, {num_items})")
print(f"Final matrix shape: ({num_users}, {num_items})")
if not eval_sequences:
log.error("Failed to generate any evaluation sequences (asin-indexed).")
return False
# 6) 아이템(asin idx) 인기 저장
# - 모든 인터랙션에서 등장한 아이템을 카운트(마지막 타깃 포함)
# - 등장하지 않은 아이템도 0으로 채워 전체 아이템 풀(0..num_items-1) 커버
try:
from collections import Counter
pop_counter = Counter()
# interactions_by_user_timed: user -> [(asin, time), ...]
for seq in interactions_by_user_timed.values():
for asin, _t in seq:
if asin in asin_to_idx:
pop_counter[asin_to_idx[asin]] += 1
# 전체 아이템 인덱스(0-based) 범위에 대해 0 채움
popularity_dict = {i: int(pop_counter.get(i, 0)) for i in range(num_items)}
popularity_path = os.path.join(dataset_output_dir, f"{dataset}_item_popularity.json")
with open(popularity_path, "w") as f:
json.dump(popularity_dict, f)
log.info(f"[Beauty-style] Item popularity saved to: {popularity_path}")
except Exception as e:
log.warning(f"Saving item popularity failed (continuing): {e}")
# 7) 저장 (asin-indexed)
try:
# 시퀀스
seq_path = os.path.join(dataset_output_dir, f"{dataset}_eval_sequences.pkl")
with open(seq_path, "wb") as f:
pickle.dump(eval_sequences, f)
log.info(f"Evaluation sequences saved to: {seq_path}")
# 행렬
matrix_path = os.path.join(dataset_output_dir, f"{dataset}_interaction_matrix.npz")
save_npz(matrix_path, interaction_matrix.tocsr())
log.info(f"Interaction matrix saved to: {matrix_path}")
# 유저 맵
user_map_path = os.path.join(dataset_output_dir, f"{dataset}_user_id_to_idx.json")
with open(user_map_path, "w") as f:
json.dump(user_id_to_idx, f)
log.info(f"User ID map saved to: {user_map_path}")
# 아이템 맵들 (asin/idx/title)
item_id_map_path = os.path.join(dataset_output_dir, f"{dataset}_item_id_to_idx.json") # asin→idx
with open(item_id_map_path, "w") as f:
json.dump(asin_to_idx, f)
log.info(f"ASIN→idx map saved to: {item_id_map_path}")
idx_to_asin_path = os.path.join(dataset_output_dir, f"{dataset}_idx_to_asin.json")
with open(idx_to_asin_path, "w") as f:
json.dump(idx_to_asin, f)
log.info(f"idx→ASIN map saved to: {idx_to_asin_path}")
idx_to_title_path = os.path.join(dataset_output_dir, f"{dataset}_idx_to_title.json")
with open(idx_to_title_path, "w", encoding="utf-8") as f:
json.dump({int(k): v for k, v in idx_to_title.items()}, f, ensure_ascii=False)
log.info(f"idx→title map saved to: {idx_to_title_path}")
# TSV: index \t asin \t title (후속 파이프라인 호환용)
tsv_map_path = os.path.join(dataset_output_dir, f"{dataset}_item_index_to_title.txt")
with open(tsv_map_path, "w", encoding="utf-8") as f:
f.write("index\tasin\ttitle\n")
for idx in range(num_items):
asin = idx_to_asin[idx]
title = idx_to_title[idx]
f.write(f"{idx}\t{asin}\t{title}\n")
log.info(f"Item index/asin/title TSV saved to: {tsv_map_path}")
except Exception as e:
log.error(f"Error during file saving: {e}")
return False
log.info("Data processing (asin-indexed) finished successfully.")
return True
if __name__ == "__main__":
# Example: HF last_out -> LLaRA input
dataset = "Industrial_and_Scientific"
output_dir = "/mnt/data0/woosung/KDD2026/LLaRA/data"
print(f"Start HF last_out processing {dataset} ...")
success = process_hf_last_out_to_llara(
fname=dataset,
dataset=dataset,
output_dir=output_dir,
core="5core",
repo_id="McAuley-Lab/Amazon-Reviews-2023",
user_col="user_id",
item_col="parent_asin",
time_col="timestamp",
rating_col=None,
review_json_path=None,
meta_file_path=None,
default_rating=0,
)
if success:
print("HF last_out processing finished!")
else:
print("HF last_out processing failed!")
|