Spaces:
Sleeping
Sleeping
| import os | |
| import random | |
| import json | |
| from datetime import datetime, timezone, timedelta | |
| from typing import Dict, List, Optional | |
| import pandas as pd | |
| import numpy as np | |
| from datasets import Dataset, DatasetDict, load_dataset | |
| from huggingface_hub import HfApi | |
| from dotenv import load_dotenv | |
| TARGET_USERS = 20 | |
| RECORDS_PER_USER = 500 | |
| def require_env(var_name: str) -> str: | |
| value = os.getenv(var_name) | |
| if not value: | |
| raise RuntimeError(f"ํ๊ฒฝ๋ณ์ {var_name}๊ฐ ํ์ํฉ๋๋ค.") | |
| return value | |
| def jitter(value: float, scale: float = 0.02) -> float: | |
| """๊ฐ์ ยฑscale ๋น์จ์ ๋ ธ์ด์ฆ๋ฅผ ์ถ๊ฐ""" | |
| if value is None: | |
| return None | |
| return value * (1 + random.uniform(-scale, scale)) | |
| def jitter_abs(value: float, amount: float) -> float: | |
| """์ ๋๊ฐ ๊ธฐ์ค ๋ ธ์ด์ฆ ์ถ๊ฐ""" | |
| if value is None: | |
| return None | |
| return value + random.uniform(-amount, amount) | |
| def augment_sensor_vector(x: float, y: float, z: float, noise: float = 0.02) -> tuple: | |
| """ | |
| 3์ถ ์ผ์ ๋ฐ์ดํฐ๋ฅผ ๋ฌผ๋ฆฌ์ ์ผ๋ก ์์ฐ์ค๋ฝ๊ฒ ์ฆํญ | |
| โ 3์ถ์ ๋์ผํ ๋น์จ๋ก scaling + ๊ฐ๋ณ ์์ ๋ ธ์ด์ฆ | |
| """ | |
| if x is None or y is None or z is None: | |
| return (x, y, z) | |
| scale = 1 + random.uniform(-noise, noise) | |
| return ( | |
| round(x * scale + random.uniform(-0.01, 0.01), 4), | |
| round(y * scale + random.uniform(-0.01, 0.01), 4), | |
| round(z * scale + random.uniform(-0.01, 0.01), 4), | |
| ) | |
| def compute_rms(x: float, y: float, z: float, base_noise: float = 0.02) -> float: | |
| """3์ถ mean ๊ธฐ๋ฐ์ผ๋ก RMS ์ฌ๊ณ์ฐ""" | |
| if x is None or y is None or z is None: | |
| return None | |
| base = np.sqrt(x**2 + y**2 + z**2) | |
| return round(base * (1 + random.uniform(-base_noise, base_noise)), 4) | |
| def augment_record_strict(row: dict) -> dict: | |
| """๋ฌผ๋ฆฌ์ ์ ์ฝ์ ์งํค๋ฉด์ ์ผ์ ๋ฐ์ดํฐ๋ฅผ ์์ฐ์ค๋ฝ๊ฒ ์ฆํญ""" | |
| new = row.copy() | |
| # timestamp jitter | |
| if "timestamp_utc" in row and isinstance(row["timestamp_utc"], str): | |
| try: | |
| t = datetime.fromisoformat(row["timestamp_utc"].replace("Z", "+00:00")) | |
| t = t + timedelta(milliseconds=random.randint(-150, 150)) | |
| new["timestamp_utc"] = t.isoformat() | |
| except: | |
| pass | |
| # window jitter | |
| if "window_id" in row and row["window_id"] is not None: | |
| new["window_id"] = int(row["window_id"] + random.randint(-1, 1)) | |
| if "window_start_ms" in row and row["window_start_ms"] is not None: | |
| new["window_start_ms"] = row["window_start_ms"] + random.randint(-50, 50) | |
| if "window_end_ms" in row and row["window_end_ms"] is not None: | |
| new["window_end_ms"] = new["window_start_ms"] + 2000 # window_size_ms์ ์ผ์น | |
| # --- Accelerometer mean --- | |
| if all(f in row and row[f] is not None for f in ["acc_x_mean", "acc_y_mean", "acc_z_mean"]): | |
| new["acc_x_mean"], new["acc_y_mean"], new["acc_z_mean"] = augment_sensor_vector( | |
| row["acc_x_mean"], row["acc_y_mean"], row["acc_z_mean"], noise=0.03 | |
| ) | |
| # --- Gyro mean --- | |
| if all(f in row and row[f] is not None for f in ["gyro_x_mean", "gyro_y_mean", "gyro_z_mean"]): | |
| new["gyro_x_mean"], new["gyro_y_mean"], new["gyro_z_mean"] = augment_sensor_vector( | |
| row["gyro_x_mean"], row["gyro_y_mean"], row["gyro_z_mean"], noise=0.03 | |
| ) | |
| # --- Linear accel mean --- | |
| if all(f in row and row[f] is not None for f in ["linacc_x_mean", "linacc_y_mean", "linacc_z_mean"]): | |
| new["linacc_x_mean"], new["linacc_y_mean"], new["linacc_z_mean"] = augment_sensor_vector( | |
| row["linacc_x_mean"], row["linacc_y_mean"], row["linacc_z_mean"], noise=0.03 | |
| ) | |
| # --- Gravity vector (๋ฌผ๋ฆฌ์ ์ ์ฝ: ํฌ๊ธฐ๊ฐ ์ฝ 9.8) --- | |
| if all(f in row and row[f] is not None for f in ["gravity_x_mean", "gravity_y_mean", "gravity_z_mean"]): | |
| gx, gy, gz = augment_sensor_vector( | |
| row["gravity_x_mean"], row["gravity_y_mean"], row["gravity_z_mean"], noise=0.01 | |
| ) | |
| g_mag = np.sqrt(gx**2 + gy**2 + gz**2) | |
| if g_mag > 0: | |
| scale = 9.8 / g_mag | |
| new["gravity_x_mean"] = round(gx * scale, 4) | |
| new["gravity_y_mean"] = round(gy * scale, 4) | |
| new["gravity_z_mean"] = round(gz * scale, 4) | |
| # --- Recompute RMS from sensor means --- | |
| if all(f in new and new[f] is not None for f in ["acc_x_mean", "acc_y_mean", "acc_z_mean"]): | |
| new["rms_acc"] = compute_rms( | |
| new["acc_x_mean"], new["acc_y_mean"], new["acc_z_mean"], base_noise=0.03 | |
| ) | |
| elif "rms_acc" in row and row["rms_acc"] is not None: | |
| new["rms_acc"] = jitter(row["rms_acc"], 0.03) | |
| if all(f in new and new[f] is not None for f in ["gyro_x_mean", "gyro_y_mean", "gyro_z_mean"]): | |
| new["rms_gyro"] = compute_rms( | |
| new["gyro_x_mean"], new["gyro_y_mean"], new["gyro_z_mean"], base_noise=0.03 | |
| ) | |
| elif "rms_gyro" in row and row["rms_gyro"] is not None: | |
| new["rms_gyro"] = jitter(row["rms_gyro"], 0.03) | |
| # --- std values scale with RMS --- | |
| if "rms_acc" in new and new["rms_acc"] is not None and "rms_acc" in row and row["rms_acc"] is not None and row["rms_acc"] > 0: | |
| rms_ratio = new["rms_acc"] / row["rms_acc"] | |
| for col in ["acc_x_std", "acc_y_std", "acc_z_std"]: | |
| if col in row and row[col] is not None: | |
| new[col] = max(0.01, row[col] * rms_ratio * jitter(1, 0.1)) | |
| if "rms_gyro" in new and new["rms_gyro"] is not None and "rms_gyro" in row and row["rms_gyro"] is not None and row["rms_gyro"] > 0: | |
| rms_ratio = new["rms_gyro"] / row["rms_gyro"] | |
| for col in ["gyro_x_std", "gyro_y_std", "gyro_z_std"]: | |
| if col in row and row[col] is not None: | |
| new[col] = max(0.001, row[col] * rms_ratio * jitter(1, 0.1)) | |
| # --- frequency (weak positive correlation with RMS) --- | |
| if "mean_freq_acc" in row and row["mean_freq_acc"] is not None and "rms_acc" in new and new["rms_acc"] is not None: | |
| new["mean_freq_acc"] = round(jitter_abs(row["mean_freq_acc"], new["rms_acc"] * 0.3), 2) | |
| elif "mean_freq_acc" in row and row["mean_freq_acc"] is not None: | |
| new["mean_freq_acc"] = round(jitter(row["mean_freq_acc"], 0.02), 2) | |
| if "mean_freq_gyro" in row and row["mean_freq_gyro"] is not None and "rms_gyro" in new and new["rms_gyro"] is not None: | |
| new["mean_freq_gyro"] = round(jitter_abs(row["mean_freq_gyro"], new["rms_gyro"] * 0.3), 2) | |
| elif "mean_freq_gyro" in row and row["mean_freq_gyro"] is not None: | |
| new["mean_freq_gyro"] = round(jitter(row["mean_freq_gyro"], 0.02), 2) | |
| # --- entropy: increases when RMS increases --- | |
| if "entropy_acc" in row and row["entropy_acc"] is not None and "rms_acc" in new and new["rms_acc"] is not None and "rms_acc" in row and row["rms_acc"] is not None and row["rms_acc"] > 0: | |
| new["entropy_acc"] = min(1.0, max(0.05, row["entropy_acc"] * (new["rms_acc"] / row["rms_acc"]) * jitter(1, 0.1))) | |
| elif "entropy_acc" in row and row["entropy_acc"] is not None: | |
| new["entropy_acc"] = min(1.0, max(0.05, jitter(row["entropy_acc"], 0.02))) | |
| if "entropy_gyro" in row and row["entropy_gyro"] is not None and "rms_gyro" in new and new["rms_gyro"] is not None and "rms_gyro" in row and row["rms_gyro"] is not None and row["rms_gyro"] > 0: | |
| new["entropy_gyro"] = min(1.0, max(0.05, row["entropy_gyro"] * (new["rms_gyro"] / row["rms_gyro"]) * jitter(1, 0.1))) | |
| elif "entropy_gyro" in row and row["entropy_gyro"] is not None: | |
| new["entropy_gyro"] = min(1.0, max(0.05, jitter(row["entropy_gyro"], 0.02))) | |
| # --- jerk: depends on std and RMS --- | |
| if "jerk_mean" in row and row["jerk_mean"] is not None: | |
| if "acc_x_std" in row and row["acc_x_std"] is not None: | |
| new["jerk_mean"] = round(jitter_abs(row["jerk_mean"], row["acc_x_std"] * 0.3), 4) | |
| else: | |
| new["jerk_mean"] = round(jitter(row["jerk_mean"], 0.02), 4) | |
| if "jerk_std" in row and row["jerk_std"] is not None: | |
| if "acc_x_std" in row and row["acc_x_std"] is not None: | |
| new["jerk_std"] = max(0.001, round(jitter_abs(row["jerk_std"], row["acc_x_std"] * 0.1), 4)) | |
| else: | |
| new["jerk_std"] = max(0.001, round(jitter(row["jerk_std"], 0.01), 4)) | |
| # --- stability index (inverse to entropy) --- | |
| entropy_avg = 0.5 | |
| if "entropy_acc" in new and new["entropy_acc"] is not None and "entropy_gyro" in new and new["entropy_gyro"] is not None: | |
| entropy_avg = (new["entropy_acc"] + new["entropy_gyro"]) / 2 | |
| elif "entropy_acc" in new and new["entropy_acc"] is not None: | |
| entropy_avg = new["entropy_acc"] | |
| elif "entropy_gyro" in new and new["entropy_gyro"] is not None: | |
| entropy_avg = new["entropy_gyro"] | |
| new["stability_index"] = round(max(0.4, min(0.99, 1 - entropy_avg * 0.3)), 4) | |
| # --- fatigue model (RMS, ์ฃผํ์ ๊ธฐ๋ฐ) --- | |
| # fatigue๋ augment_user_data์์ ์๊ฐ์ ์ฐ์์ฑ์ ๊ณ ๋ คํ์ฌ ๊ณ์ฐ | |
| # ์ฌ๊ธฐ์๋ ๊ธฐ๋ณธ๊ฐ๋ง ์ค์ (๋์ค์ ๋ฎ์ด์์์ง) | |
| if "fatigue" in row and row["fatigue"] is not None: | |
| # ๊ธฐ๋ณธ์ ์ผ๋ก RMS์ ์ฃผํ์ ๊ธฐ๋ฐ์ผ๋ก ์ฝ๊ฐ ์กฐ์ | |
| if "rms_acc" in new and new["rms_acc"] is not None and "rms_acc" in row and row["rms_acc"] is not None and row["rms_acc"] > 0.1: | |
| rms_factor = new["rms_acc"] / row["rms_acc"] | |
| else: | |
| rms_factor = 1.0 | |
| if "mean_freq_acc" in new and new["mean_freq_acc"] is not None and "mean_freq_acc" in row and row["mean_freq_acc"] is not None and row["mean_freq_acc"] > 1: | |
| freq_factor = row["mean_freq_acc"] / new["mean_freq_acc"] | |
| else: | |
| freq_factor = 1.0 | |
| fatigue_delta = rms_factor * 0.05 - freq_factor * 0.03 | |
| new["fatigue"] = min(0.95, max(0.05, row["fatigue"] + fatigue_delta + random.uniform(-0.02, 0.02))) | |
| new["fatigue_level"] = 0 if new["fatigue"] < 0.3 else 1 if new["fatigue"] < 0.6 else 2 | |
| else: | |
| # fatigue๊ฐ ์์ผ๋ฉด ๊ธฐ๋ณธ๊ฐ ์ค์ | |
| new["fatigue"] = 0.1 | |
| new["fatigue_level"] = 0 | |
| # fatigue_prev๋ augment_user_data์์ ์ค์ ๋จ | |
| if "fatigue_prev" in row and row["fatigue_prev"] is not None: | |
| new["fatigue_prev"] = row["fatigue_prev"] | |
| else: | |
| new["fatigue_prev"] = 0.05 | |
| # --- baseline values (preserve) --- | |
| if "rms_base" in row: | |
| new["rms_base"] = row["rms_base"] | |
| if "freq_base" in row: | |
| new["freq_base"] = row["freq_base"] | |
| # --- user_emb: NEVER change --- | |
| if "user_emb" in row: | |
| new["user_emb"] = row["user_emb"] | |
| # --- other fields --- | |
| if "overlap_rate" in row and row["overlap_rate"] is not None: | |
| new["overlap_rate"] = max(0.3, min(0.7, jitter(row["overlap_rate"], 0.02))) | |
| if "window_size_ms" in row: | |
| new["window_size_ms"] = row.get("window_size_ms", 2000) | |
| if "quality_flag" in row: | |
| if random.random() < 0.05: # 5% ํ๋ฅ ๋ก ๋ณ๊ฒฝ | |
| new["quality_flag"] = 0 if row["quality_flag"] == 1 else 1 | |
| else: | |
| new["quality_flag"] = row["quality_flag"] | |
| # session_id ์ฝ๊ฐ ๋ณํ | |
| if "session_id" in row and row["session_id"]: | |
| parts = str(row["session_id"]).split("_") | |
| if len(parts) > 1: | |
| try: | |
| session_num = int(parts[-1]) | |
| new["session_id"] = "_".join(parts[:-1]) + "_" + str(session_num + random.randint(-5, 5)) | |
| except: | |
| new["session_id"] = row["session_id"] | |
| else: | |
| new["session_id"] = row["session_id"] | |
| return new | |
| def augment_user_data(df: pd.DataFrame, target_count: int, new_user_id: str = None) -> pd.DataFrame: | |
| """ | |
| ์ฌ์ฉ์๋ณ ๋ฐ์ดํฐ๋ฅผ ์ฆํญํ์ฌ ๋ชฉํ ๊ฐ์๋งํผ ์์ฑ | |
| ์๋ก์ด ์ฌ์ฉ์์ธ ๊ฒฝ์ฐ ์๊ฐ์ ์ฐ์์ฑ์ ์ ์ง | |
| """ | |
| if len(df) >= target_count: | |
| return df.head(target_count) | |
| need = target_count - len(df) | |
| # ์๋ก์ด ์ฌ์ฉ์์ธ ๊ฒฝ์ฐ (๊ธฐ์กด ๋ฐ์ดํฐ๊ฐ ์๊ฑฐ๋ ์ ์ฌ์ฉ์ ID๊ฐ ์ ๊ณต๋ ๊ฒฝ์ฐ) | |
| is_new_user = new_user_id is not None or len(df) == 0 | |
| if is_new_user and len(df) > 0: | |
| # ์๋ก์ด ์ฌ์ฉ์๋ ํญ์ target_count๋งํผ ์์ฑ (์ฐธ์กฐ ๋ฐ์ดํฐ ๊ธธ์ด์ ๋ฌด๊ด) | |
| base_row = df.iloc[0].to_dict() | |
| new_rows = [] | |
| # ์๊ฐ ๊ธฐ๋ฐ ์ด๊ธฐ๊ฐ ์ค์ | |
| if "timestamp_utc" in base_row and base_row["timestamp_utc"]: | |
| try: | |
| base_time = datetime.fromisoformat(str(base_row["timestamp_utc"]).replace("Z", "+00:00")) | |
| except: | |
| base_time = datetime.now(timezone.utc) | |
| else: | |
| base_time = datetime.now(timezone.utc) | |
| base_window_id = 1 # ์ ์ฌ์ฉ์๋ window_id๋ฅผ 1๋ถํฐ ์์ | |
| base_window_start = 0 # ์ ์ฌ์ฉ์๋ window_start_ms๋ฅผ 0๋ถํฐ ์์ | |
| prev_fatigue = base_row.get("fatigue", 0.1) if base_row.get("fatigue") is not None else 0.1 | |
| # ์๋ก์ด ์ฌ์ฉ์๋ ํญ์ target_count๋งํผ ์์ฑ | |
| for i in range(target_count): | |
| # ์ํ ๋ ์ฝ๋ ์ ํ | |
| sample_idx = random.randint(0, len(df) - 1) | |
| sample = df.iloc[sample_idx].to_dict() | |
| # ์๋ก์ด ๋ ์ฝ๋ ์์ฑ | |
| new_row = augment_record_strict(sample) | |
| # ์๋ก์ด ์ฌ์ฉ์ ID ์ค์ | |
| if new_user_id: | |
| new_row["user_id"] = new_user_id | |
| # ์๊ฐ์ ์ฐ์์ฑ ์ ์ง | |
| window_interval = 2000 # window_size_ms | |
| new_row["window_id"] = base_window_id + i | |
| new_row["window_start_ms"] = base_window_start + i * window_interval | |
| new_row["window_end_ms"] = new_row["window_start_ms"] + window_interval | |
| # timestamp ์ฐ์์ฑ ์ ์ง | |
| new_row["timestamp_utc"] = (base_time + timedelta(milliseconds=i * window_interval)).isoformat() | |
| # ํผ๋ก๋ ์ฐ์์ฑ ์ ์ง (์ด์ ํผ๋ก๋๋ ์ง์ ๋ ์ฝ๋์ ํผ๋ก๋) | |
| if i > 0: | |
| new_row["fatigue_prev"] = prev_fatigue | |
| else: | |
| # ์ฒซ ๋ ์ฝ๋๋ ์ฐธ์กฐ ๋ฐ์ดํฐ์ ํผ๋ก๋์์ ์ฝ๊ฐ ๋ฎ๊ฒ ์์ | |
| new_row["fatigue_prev"] = max(0.05, prev_fatigue - random.uniform(0, 0.05)) | |
| # ํ์ฌ ํผ๋ก๋๋ ์ด์ ํผ๋ก๋ ๊ธฐ๋ฐ์ผ๋ก ์ฝ๊ฐ ์ฆ๊ฐํ๋ ๊ฒฝํฅ (์ค์ ์ธก์ ๊ณผ ์ ์ฌ) | |
| if "fatigue" in new_row and new_row["fatigue"] is not None: | |
| # ํผ๋ก๋๋ ์๊ฐ์ ๋ฐ๋ผ ์ ์ง์ ์ผ๋ก ์ฆ๊ฐํ๋ ๊ฒฝํฅ | |
| fatigue_base = new_row["fatigue_prev"] if "fatigue_prev" in new_row else prev_fatigue | |
| # ์ฝ๊ฐ์ ์ฆ๊ฐ + ๋ ธ์ด์ฆ | |
| fatigue_increase = random.uniform(0, 0.02) # ์๊ฐ์ ๋ฐ๋ฅธ ์ ์ง์ ์ฆ๊ฐ | |
| new_row["fatigue"] = min(0.95, max(0.05, fatigue_base + fatigue_increase + random.uniform(-0.01, 0.01))) | |
| new_row["fatigue_level"] = 0 if new_row["fatigue"] < 0.3 else 1 if new_row["fatigue"] < 0.6 else 2 | |
| prev_fatigue = new_row["fatigue"] | |
| # ์ธ์ ID ์์ฑ (์ ์ฌ์ฉ์์ด๋ฏ๋ก ์๋ก์ด ์ธ์ ) | |
| if "session_id" in new_row: | |
| new_row["session_id"] = f"session_{i // 10 + 1:03d}" # 10๊ฐ ๋ ์ฝ๋๋น ์ธ์ | |
| # measure_date๋ ๊ธฐ์กด ๋ฐ์ดํฐ์ ์๋ ๊ฒฝ์ฐ์๋ง ์ค์ | |
| if "measure_date" in sample: | |
| try: | |
| measure_time = datetime.fromisoformat(new_row["timestamp_utc"].replace("Z", "+00:00")) | |
| new_row["measure_date"] = measure_time.strftime("%Y-%m-%d") | |
| except: | |
| new_row["measure_date"] = base_time.strftime("%Y-%m-%d") | |
| new_rows.append(new_row) | |
| return pd.DataFrame(new_rows) | |
| else: | |
| # ๊ธฐ์กด ์ฌ์ฉ์ ๋ฐ์ดํฐ ์ฆํญ (์๊ฐ์ ์ฐ์์ฑ ์ ์ง) | |
| new_rows = [] | |
| last_row = df.iloc[-1].to_dict() | |
| # ๋ง์ง๋ง ๋ ์ฝ๋์ ์๊ฐ ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ | |
| if "timestamp_utc" in last_row and last_row["timestamp_utc"]: | |
| try: | |
| last_time = datetime.fromisoformat(str(last_row["timestamp_utc"]).replace("Z", "+00:00")) | |
| except: | |
| last_time = datetime.now(timezone.utc) | |
| else: | |
| last_time = datetime.now(timezone.utc) | |
| last_window_id = last_row.get("window_id", 0) if last_row.get("window_id") is not None else 0 | |
| last_window_start = last_row.get("window_end_ms", 0) if last_row.get("window_end_ms") is not None else 0 | |
| prev_fatigue = last_row.get("fatigue", 0.1) if last_row.get("fatigue") is not None else 0.1 | |
| for i in range(need): | |
| # ์ํ ๋ ์ฝ๋ ์ ํ | |
| sample_idx = random.randint(0, len(df) - 1) | |
| sample = df.iloc[sample_idx].to_dict() | |
| # ์๋ก์ด ๋ ์ฝ๋ ์์ฑ | |
| new_row = augment_record_strict(sample) | |
| # ์๊ฐ์ ์ฐ์์ฑ ์ ์ง | |
| window_interval = 2000 | |
| new_row["window_id"] = last_window_id + i + 1 | |
| new_row["window_start_ms"] = last_window_start + i * window_interval | |
| new_row["window_end_ms"] = new_row["window_start_ms"] + window_interval | |
| # timestamp ์ฐ์์ฑ ์ ์ง | |
| new_row["timestamp_utc"] = (last_time + timedelta(milliseconds=(i + 1) * window_interval)).isoformat() | |
| # ํผ๋ก๋ ์ฐ์์ฑ ์ ์ง | |
| new_row["fatigue_prev"] = prev_fatigue | |
| if "fatigue" in new_row and new_row["fatigue"] is not None: | |
| # ํผ๋ก๋๋ ์๊ฐ์ ๋ฐ๋ผ ์ ์ง์ ์ผ๋ก ์ฆ๊ฐํ๋ ๊ฒฝํฅ | |
| fatigue_increase = random.uniform(0, 0.02) # ์๊ฐ์ ๋ฐ๋ฅธ ์ ์ง์ ์ฆ๊ฐ | |
| new_row["fatigue"] = min(0.95, max(0.05, prev_fatigue + fatigue_increase + random.uniform(-0.01, 0.01))) | |
| new_row["fatigue_level"] = 0 if new_row["fatigue"] < 0.3 else 1 if new_row["fatigue"] < 0.6 else 2 | |
| prev_fatigue = new_row["fatigue"] | |
| # measure_date๋ ๊ธฐ์กด ๋ฐ์ดํฐ์ ์๋ ๊ฒฝ์ฐ์๋ง ์ค์ | |
| if "measure_date" in sample: | |
| try: | |
| measure_time = datetime.fromisoformat(new_row["timestamp_utc"].replace("Z", "+00:00")) | |
| new_row["measure_date"] = measure_time.strftime("%Y-%m-%d") | |
| except: | |
| new_row["measure_date"] = last_time.strftime("%Y-%m-%d") | |
| new_rows.append(new_row) | |
| return pd.concat([df, pd.DataFrame(new_rows)], ignore_index=True) | |
| def main(): | |
| load_dotenv() | |
| repo_id = require_env("HF_DATA_REPO_ID") | |
| token = require_env("HF_DATA_TOKEN") | |
| print(f"๐ ๊ธฐ์กด ๋ฐ์ดํฐ์ ๋ก๋ ์ค: {repo_id}") | |
| # ๊ฐ๋ณ parquet ํ์ผ์ ๋ชจ๋ ๋ก๋ (user๋ก ์์ํ์ง ์๋ ํ์ผ๋ ํฌํจ) | |
| api = HfApi() | |
| try: | |
| files = api.list_repo_files(repo_id=repo_id, repo_type="dataset", token=token) | |
| # ๋ชจ๋ parquet ํ์ผ ํํฐ๋ง (user๋ก ์์ํ์ง ์๋ ๊ฒ๋ ํฌํจ) | |
| parquet_files = [f for f in files if f.endswith(".parquet")] | |
| print(f"๐ Parquet ํ์ผ ์: {len(parquet_files)}") | |
| existing = DatasetDict() | |
| for file_path in parquet_files: | |
| try: | |
| # ํ์ผ๋ช ์์ ์ฌ์ฉ์ ID ์ถ์ถ | |
| # ํ์: data/user_xxx.parquet ๋๋ data/user_xxx-00000-of-00001.parquet | |
| filename = file_path.split("/")[-1] if "/" in file_path else file_path | |
| # .parquet ํ์ฅ์ ์ ๊ฑฐ | |
| filename_no_ext = filename.replace(".parquet", "") | |
| # -00000-of-00001 ๋ถ๋ถ์ด ์์ผ๋ฉด ์ ๊ฑฐ, ์์ผ๋ฉด ๊ทธ๋๋ก ์ฌ์ฉ | |
| if "-" in filename_no_ext: | |
| user_id = filename_no_ext.split("-")[0] | |
| else: | |
| user_id = filename_no_ext | |
| # local_user๋ก ์์ํ๋ ํ์ผ์ ์ ์ธ | |
| if user_id.startswith("local_user"): | |
| print(f"โญ๏ธ {user_id}: local_user๋ก ์์ํ๋ ํ์ผ์ ์ ์ธ") | |
| continue | |
| # ๊ฐ๋ณ ํ์ผ์ pandas๋ก ์ง์ ๋ก๋ | |
| from huggingface_hub import hf_hub_download | |
| import tempfile | |
| # ํ์ผ ๋ค์ด๋ก๋ | |
| local_path = hf_hub_download( | |
| repo_id=repo_id, | |
| filename=file_path, | |
| repo_type="dataset", | |
| token=token | |
| ) | |
| # pandas๋ก ์ง์ ์ฝ๊ธฐ | |
| df = pd.read_parquet(local_path) | |
| if len(df) > 0: | |
| existing[user_id] = Dataset.from_pandas(df, preserve_index=False) | |
| print(f"โ {user_id}: {len(df)} ๋ ์ฝ๋ ๋ก๋") | |
| else: | |
| print(f"โ ๏ธ {user_id}: ๋น ๋ฐ์ดํฐ์ , ๊ฑด๋๋") | |
| except Exception as e2: | |
| print(f"โ ๏ธ {file_path}: ๋ก๋ ์คํจ ({str(e2)[:100]}), ๊ฑด๋๋") | |
| continue | |
| except Exception as e3: | |
| print(f"โ ๋ฐ์ดํฐ์ ๋ก๋ ์์ ์คํจ: {e3}") | |
| return | |
| # ์ ํจํ ์ฌ์ฉ์๋ง ํํฐ๋ง (๋ฐ์ดํฐ๊ฐ ์๋ ์ฌ์ฉ์๋ง, local_user ์ ์ธ) | |
| valid_users = {} | |
| for user_id in existing.keys(): | |
| # local_user๋ก ์์ํ๋ ์ฌ์ฉ์๋ ์ ์ธ | |
| if user_id.startswith("local_user"): | |
| print(f"โญ๏ธ {user_id}: local_user๋ก ์์ํ๋ ์ฌ์ฉ์๋ ์ ์ธ") | |
| continue | |
| try: | |
| user_data = existing[user_id] | |
| if len(user_data) > 0: | |
| valid_users[user_id] = user_data | |
| else: | |
| print(f"โ ๏ธ {user_id}: ๋น ๋ฐ์ดํฐ์ , ๊ฑด๋๋") | |
| except Exception as e: | |
| print(f"โ ๏ธ {user_id}: ๋ฐ์ดํฐ ์ ๊ทผ ์คํจ ({e}), ๊ฑด๋๋") | |
| continue | |
| if len(valid_users) == 0: | |
| print("โ ์ ํจํ ์ฌ์ฉ์ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค.") | |
| return | |
| print(f"โ ์ ํจํ ์ฌ์ฉ์ ์: {len(valid_users)}๋ช ") | |
| # ํ์ฌ ์ด ๋ ์ฝ๋ ์ ๊ณ์ฐ | |
| current_total = sum(len(valid_users[user_id]) for user_id in valid_users) | |
| print(f"๐ ํ์ฌ ์ด ๋ ์ฝ๋ ์: {current_total}") | |
| # ๊ธฐ์กด ์ฌ์ฉ์ ๋ชฉ๋ก ๊ฐ์ ธ์ค๊ธฐ (์ํ๋ง์ฉ) | |
| all_users = list(valid_users.keys()) | |
| if len(all_users) == 0: | |
| print("โ ์ฆํญํ ์ฐธ์กฐ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค.") | |
| return | |
| # ์๋ก์ด ์ฌ์ฉ์ 20๋ช ์์ฑ (๊ธฐ์กด ์ฌ์ฉ์ ๋ฐ์ดํฐ๋ฅผ ์ฐธ์กฐํ์ฌ ์ฆํญ) | |
| print(f"๐ฏ ์๋ก์ด ์ฌ์ฉ์ {TARGET_USERS}๋ช ์์ฑ ์ค...") | |
| print(f"๐ ์ฐธ์กฐ ์ฌ์ฉ์: {len(all_users)}๋ช ") | |
| print(f"๐ฏ ์ฌ์ฉ์๋น ๋ชฉํ ๋ ์ฝ๋ ์: {RECORDS_PER_USER}") | |
| # ์๋ก์ด ์ฌ์ฉ์ ๋ฐ์ดํฐ์ ์์ฑ | |
| new_user_datasets = {} | |
| for i in range(1, TARGET_USERS + 1): | |
| # ์๋ก์ด ์ฌ์ฉ์ ID ์์ฑ | |
| new_user_id = f"augmented_user_{i:03d}" | |
| # ๊ธฐ์กด ์ฌ์ฉ์ ์ค ๋๋ค ์ ํ (์ฐธ์กฐ์ฉ) | |
| reference_user_id = random.choice(all_users) | |
| reference_df = valid_users[reference_user_id].to_pandas() | |
| if len(reference_df) == 0: | |
| print(f"โ ๏ธ ์ฐธ์กฐ ์ฌ์ฉ์ {reference_user_id}์ ๋ฐ์ดํฐ๊ฐ ๋น์ด์์ด ๊ฑด๋๋") | |
| continue | |
| try: | |
| # ์ฐธ์กฐ ๋ฐ์ดํฐ๋ฅผ ์ฆํญํ์ฌ ์๋ก์ด ์ฌ์ฉ์ ๋ฐ์ดํฐ ์์ฑ (์ ์ฌ์ฉ์ ID ์ ๋ฌ) | |
| new_user_df = augment_user_data(reference_df, RECORDS_PER_USER, new_user_id=new_user_id) | |
| # user_id ์ปฌ๋ผ์ด ์์ผ๋ฉด ์ถ๊ฐ | |
| if "user_id" not in new_user_df.columns: | |
| new_user_df["user_id"] = new_user_id | |
| else: | |
| new_user_df["user_id"] = new_user_id | |
| new_user_datasets[new_user_id] = Dataset.from_pandas(new_user_df, preserve_index=False) | |
| actual_count = len(new_user_df) | |
| print(f"๐ {new_user_id}: {actual_count} ๋ ์ฝ๋ ์์ฑ (์ฐธ์กฐ: {reference_user_id}, ๋ชฉํ: {RECORDS_PER_USER})") | |
| if actual_count != RECORDS_PER_USER: | |
| print(f" โ ๏ธ ๊ฒฝ๊ณ : ์์ฑ๋ ๋ ์ฝ๋ ์({actual_count})๊ฐ ๋ชฉํ({RECORDS_PER_USER})์ ๋ค๋ฆ ๋๋ค!") | |
| except Exception as e: | |
| print(f"โ {new_user_id}: ์์ฑ ์คํจ ({e}), ๊ฑด๋๋") | |
| continue | |
| if len(new_user_datasets) == 0: | |
| print("โ ์๋ก์ด ์ฌ์ฉ์ ๋ฐ์ดํฐ๊ฐ ์์ฑ๋์ง ์์์ต๋๋ค.") | |
| return | |
| # ๊ธฐ์กด ๋ฐ์ดํฐ์ ์คํค๋ง ํ์ธ (์ฒซ ๋ฒ์งธ ์ฌ์ฉ์ ๋ฐ์ดํฐ ๊ธฐ์ค) | |
| print("๐ง ๊ธฐ์กด ๋ฐ์ดํฐ ์คํค๋ง ํ์ธ ์ค...") | |
| reference_user_id = list(valid_users.keys())[0] | |
| reference_df = valid_users[reference_user_id].to_pandas() | |
| existing_columns = set(reference_df.columns) | |
| print(f" ๐ ๊ธฐ์กด ๋ฐ์ดํฐ ์ปฌ๋ผ ์: {len(existing_columns)}") | |
| print(f" ๐ ๊ธฐ์กด ๋ฐ์ดํฐ ์ปฌ๋ผ: {sorted(existing_columns)}") | |
| # ์๋ก์ด ์ฌ์ฉ์ ๋ฐ์ดํฐ๋ฅผ ๊ธฐ์กด ์คํค๋ง์ ๋ง์ถค | |
| print("๐ง ์๋ก์ด ์ฌ์ฉ์ ๋ฐ์ดํฐ๋ฅผ ๊ธฐ์กด ์คํค๋ง์ ๋ง์ถ๋ ์ค...") | |
| for user_id in new_user_datasets.keys(): | |
| df = new_user_datasets[user_id].to_pandas() | |
| # ๊ธฐ์กด์ ์๋ ์ปฌ๋ผ ์ ๊ฑฐ | |
| columns_to_remove = set(df.columns) - existing_columns | |
| if columns_to_remove: | |
| df = df.drop(columns=list(columns_to_remove)) | |
| print(f" โ ๏ธ {user_id}: ๋ถํ์ํ ์ปฌ๋ผ ์ ๊ฑฐ: {columns_to_remove}") | |
| # ๊ธฐ์กด์ ์๋๋ฐ ์๋ ์ปฌ๋ผ ์ถ๊ฐ (None์ผ๋ก) | |
| columns_to_add = existing_columns - set(df.columns) | |
| if columns_to_add: | |
| for col in columns_to_add: | |
| df[col] = None | |
| print(f" โ {user_id}: ๋๋ฝ๋ ์ปฌ๋ผ ์ถ๊ฐ: {columns_to_add}") | |
| # ์ปฌ๋ผ ์์๋ฅผ ๊ธฐ์กด ๋ฐ์ดํฐ์ ๋์ผํ๊ฒ ๋ง์ถค | |
| df = df[list(reference_df.columns)] | |
| new_user_datasets[user_id] = Dataset.from_pandas(df, preserve_index=False) | |
| print(f" โ {user_id}: ์คํค๋ง ์ ๊ทํ ์๋ฃ") | |
| # ๊ธฐ์กด ๋ฐ์ดํฐ์ ์ ์๋ก์ด ์ฌ์ฉ์ ๋ฐ์ดํฐ ์ถ๊ฐ | |
| final_datasets = {} | |
| # ๊ธฐ์กด ์ฌ์ฉ์ ๋ฐ์ดํฐ ์ ์ง | |
| for user_id in valid_users.keys(): | |
| final_datasets[user_id] = valid_users[user_id] | |
| # ์๋ก์ด ์ฌ์ฉ์ ๋ฐ์ดํฐ ์ถ๊ฐ | |
| for user_id in new_user_datasets.keys(): | |
| final_datasets[user_id] = new_user_datasets[user_id] | |
| final_dict = DatasetDict(final_datasets) | |
| new_users_total = sum(len(new_user_datasets[user_id]) for user_id in new_user_datasets) | |
| total_records = sum(len(final_dict[user_id]) for user_id in final_dict) | |
| print(f"๐ ์๋ก์ด ์ฌ์ฉ์๋ค์ ์ด ๋ ์ฝ๋ ์: {new_users_total}") | |
| print(f"๐ ์ ์ฒด ๋ฐ์ดํฐ์ ์ด ๋ ์ฝ๋ ์: {total_records}") | |
| print(f"๐ ์๋ก์ด parquet ํ์ผ ์: {len(new_user_datasets)}๊ฐ") | |
| # local_user๋ก ์์ํ๋ ํ์ผ ์ญ์ | |
| print("๐๏ธ local_user๋ก ์์ํ๋ ํ์ผ ์ญ์ ์ค...") | |
| try: | |
| files_to_delete = [] | |
| for file_path in parquet_files: | |
| filename = file_path.split("/")[-1] if "/" in file_path else file_path | |
| filename_no_ext = filename.replace(".parquet", "") | |
| # -00000-of-00001 ๋ถ๋ถ์ด ์์ผ๋ฉด ์ ๊ฑฐ | |
| if "-" in filename_no_ext: | |
| user_id = filename_no_ext.split("-")[0] | |
| else: | |
| user_id = filename_no_ext | |
| if user_id.startswith("local_user"): | |
| files_to_delete.append(file_path) | |
| for file_path in files_to_delete: | |
| try: | |
| api.delete_file(path_in_repo=file_path, repo_id=repo_id, repo_type="dataset", token=token) | |
| print(f" โ ์ญ์ : {file_path}") | |
| except Exception as e: | |
| print(f" โ ๏ธ ์ญ์ ์คํจ ({file_path}): {str(e)[:100]}") | |
| if files_to_delete: | |
| print(f"๐๏ธ {len(files_to_delete)}๊ฐ ํ์ผ ์ญ์ ์๋ฃ") | |
| else: | |
| print("โน๏ธ ์ญ์ ํ local_user ํ์ผ์ด ์์ต๋๋ค") | |
| except Exception as e: | |
| print(f"โ ๏ธ ํ์ผ ์ญ์ ์ค ์ค๋ฅ ๋ฐ์: {str(e)[:100]}") | |
| print(f"๐ค Hugging Face Hub์ ์ ๋ก๋ ์ค: {repo_id}") | |
| final_dict.push_to_hub(repo_id, token=token, private=True) | |
| print("โ ์ ๋ก๋ ์๋ฃ") | |
| if __name__ == "__main__": | |
| main() | |