| 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 |
| |
| 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) |
|
|
| |
| 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): |
| |
| 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 |
|
|
| |
| 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) |
|
|
| |
| 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)} |
|
|
| |
| 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) |
|
|
| |
| 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, [])] |
|
|
| |
| 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), |
| } |
| ) |
|
|
| |
| 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), |
| } |
| ) |
|
|
| |
| 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")) |
|
|
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| 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 |
|
|
| |
| 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.") |
|
|
| |
| 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() |
| ) |
|
|
| |
| 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_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}") |
|
|
| |
| 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 |
|
|
| |
| |
| |
| try: |
| from collections import Counter |
| pop_counter = Counter() |
|
|
| |
| 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 |
|
|
| |
| 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}") |
|
|
| |
| 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}") |
|
|
| |
| item_id_map_path = os.path.join(dataset_output_dir, f"{dataset}_item_id_to_idx.json") |
| 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_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__": |
| |
| 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!") |
|
|