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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
sys.path.append("../..")
|
| 3 |
+
import json
|
| 4 |
+
from typing import Dict, List, Optional
|
| 5 |
+
import sys
|
| 6 |
+
from sqlalchemy import text
|
| 7 |
+
from sqlalchemy.engine import Result
|
| 8 |
+
from app.db import engine
|
| 9 |
+
from app.config import settings
|
| 10 |
+
from app.cleaning.prompts import CLEAN_PROMPT
|
| 11 |
+
from app.cleaning.llm import LLM
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
"""
|
| 15 |
+
IN-PLACE CLEANING PIPELINE (Original Logic, No Mirroring)
|
| 16 |
+
|
| 17 |
+
- Reads from SAME TABLE
|
| 18 |
+
- Writes back into SAME TABLE
|
| 19 |
+
- Adds <col>_clean columns if missing
|
| 20 |
+
- Cleans only up to clean_cap rows (default 20)
|
| 21 |
+
- Preserves original data completely
|
| 22 |
+
- No target schema, no cloned tables, no mirroring
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
MAX_ROWS_PER_TABLE = 20
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# ----------------------------------------------------
|
| 29 |
+
# ADD <col>_clean columns into SAME TABLE
|
| 30 |
+
# ----------------------------------------------------
|
| 31 |
+
def ensure_clean_columns(schema: str, table: str, culprit_columns: List[str]):
|
| 32 |
+
if not culprit_columns:
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
with engine.begin() as cx:
|
| 36 |
+
for col in culprit_columns:
|
| 37 |
+
col_clean = f"{col}_clean"
|
| 38 |
+
sql = (
|
| 39 |
+
f'ALTER TABLE "{schema}"."{table}" '
|
| 40 |
+
f'ADD COLUMN IF NOT EXISTS "{col_clean}" TEXT'
|
| 41 |
+
)
|
| 42 |
+
cx.execute(text(sql))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ----------------------------------------------------
|
| 46 |
+
# Count rows
|
| 47 |
+
# ----------------------------------------------------
|
| 48 |
+
def _count_source_rows(schema: str, table: str) -> int:
|
| 49 |
+
try:
|
| 50 |
+
with engine.begin() as cx:
|
| 51 |
+
row = cx.execute(
|
| 52 |
+
text(f'SELECT COUNT(*) FROM "{schema}"."{table}"')
|
| 53 |
+
).first()
|
| 54 |
+
return int(row[0])
|
| 55 |
+
except Exception:
|
| 56 |
+
return -1
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# ----------------------------------------------------
|
| 60 |
+
# Stream rows from SAME TABLE
|
| 61 |
+
# ----------------------------------------------------
|
| 62 |
+
def stream_rows(schema: str, table: str, batch_size=1000, max_rows=None):
|
| 63 |
+
limit = ""
|
| 64 |
+
if max_rows:
|
| 65 |
+
limit = f" LIMIT {int(max_rows)}"
|
| 66 |
+
|
| 67 |
+
sql = f'SELECT * FROM "{schema}"."{table}"{limit}'
|
| 68 |
+
|
| 69 |
+
with engine.begin() as cx:
|
| 70 |
+
result: Result = (
|
| 71 |
+
cx.execution_options(stream_results=True)
|
| 72 |
+
.execute(text(sql))
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
batch = []
|
| 76 |
+
yielded = 0
|
| 77 |
+
|
| 78 |
+
for row in result.mappings():
|
| 79 |
+
batch.append(dict(row))
|
| 80 |
+
yielded += 1
|
| 81 |
+
|
| 82 |
+
if len(batch) >= batch_size:
|
| 83 |
+
yield batch
|
| 84 |
+
batch = []
|
| 85 |
+
|
| 86 |
+
if max_rows and yielded >= max_rows:
|
| 87 |
+
break
|
| 88 |
+
|
| 89 |
+
if batch:
|
| 90 |
+
yield batch
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# ----------------------------------------------------
|
| 94 |
+
# Write back INTO SAME TABLE
|
| 95 |
+
# ----------------------------------------------------
|
| 96 |
+
def write_batch(schema: str, table: str, rows: List[Dict], pk_col: str):
|
| 97 |
+
if not rows:
|
| 98 |
+
return
|
| 99 |
+
|
| 100 |
+
for r in rows:
|
| 101 |
+
# json encode dict/list so SQL can accept it
|
| 102 |
+
for k, v in list(r.items()):
|
| 103 |
+
if isinstance(v, (dict, list)):
|
| 104 |
+
r[k] = json.dumps(v)
|
| 105 |
+
|
| 106 |
+
with engine.begin() as cx:
|
| 107 |
+
for r in rows:
|
| 108 |
+
pk_val = r[pk_col]
|
| 109 |
+
|
| 110 |
+
set_list = ", ".join(
|
| 111 |
+
f'"{c}" = :{c}' for c in r.keys() if c != pk_col
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
sql = (
|
| 115 |
+
f'UPDATE "{schema}"."{table}" '
|
| 116 |
+
f'SET {set_list} '
|
| 117 |
+
f'WHERE "{pk_col}" = :{pk_col}'
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
cx.execute(text(sql), r)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# ----------------------------------------------------
|
| 124 |
+
# LLM clean
|
| 125 |
+
# ----------------------------------------------------
|
| 126 |
+
def clean_value(llm: LLM, value: str) -> str:
|
| 127 |
+
if not llm.enabled():
|
| 128 |
+
return value
|
| 129 |
+
|
| 130 |
+
out = llm.clean_text(
|
| 131 |
+
value,
|
| 132 |
+
system=CLEAN_PROMPT,
|
| 133 |
+
instruction="Clean the following product text."
|
| 134 |
+
)
|
| 135 |
+
return out.strip() or value
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# ----------------------------------------------------
|
| 139 |
+
# MAIN FUNCTION — identical logic to old pipeline
|
| 140 |
+
# ----------------------------------------------------
|
| 141 |
+
def run_clean_table(
|
| 142 |
+
schema: str,
|
| 143 |
+
table: str,
|
| 144 |
+
culprit_columns: List[str],
|
| 145 |
+
batch_size: int = 1000,
|
| 146 |
+
clean_cap: Optional[int] = None,
|
| 147 |
+
primary_key: Optional[str] = None,
|
| 148 |
+
clean_all: bool = False,
|
| 149 |
+
):
|
| 150 |
+
if not primary_key:
|
| 151 |
+
raise ValueError("primary_key required")
|
| 152 |
+
|
| 153 |
+
llm = LLM()
|
| 154 |
+
|
| 155 |
+
# Ensure <col>_clean exists
|
| 156 |
+
ensure_clean_columns(schema, table, culprit_columns)
|
| 157 |
+
|
| 158 |
+
# Determine cleaning cap
|
| 159 |
+
total_rows = _count_source_rows(schema, table)
|
| 160 |
+
cap = None if clean_all else (clean_cap or MAX_ROWS_PER_TABLE)
|
| 161 |
+
|
| 162 |
+
print(f"\n→ In-place cleaning {schema}.{table} (rows={total_rows}, cap={cap})")
|
| 163 |
+
sys.stdout.flush()
|
| 164 |
+
|
| 165 |
+
# Skip rows already cleaned
|
| 166 |
+
skip_pks = set()
|
| 167 |
+
if culprit_columns:
|
| 168 |
+
cond = " AND ".join([f'"{c}_clean" IS NOT NULL' for c in culprit_columns])
|
| 169 |
+
sql = (
|
| 170 |
+
f'SELECT "{primary_key}" FROM "{schema}"."{table}" '
|
| 171 |
+
f'WHERE {cond}'
|
| 172 |
+
)
|
| 173 |
+
try:
|
| 174 |
+
with engine.begin() as cx:
|
| 175 |
+
rows = cx.execute(text(sql)).fetchall()
|
| 176 |
+
skip_pks = {r[0] for r in rows}
|
| 177 |
+
except:
|
| 178 |
+
skip_pks = set()
|
| 179 |
+
|
| 180 |
+
rows_cleaned = 0
|
| 181 |
+
rows_processed = 0
|
| 182 |
+
skipped_existing = 0
|
| 183 |
+
|
| 184 |
+
# STREAM + CLEAN + UPDATE SAME TABLE
|
| 185 |
+
for rows in stream_rows(schema, table, batch_size=batch_size):
|
| 186 |
+
out_rows = []
|
| 187 |
+
|
| 188 |
+
for r in rows:
|
| 189 |
+
pk = r.get(primary_key)
|
| 190 |
+
|
| 191 |
+
# Skip already cleaned rows
|
| 192 |
+
if pk in skip_pks:
|
| 193 |
+
skipped_existing += 1
|
| 194 |
+
continue
|
| 195 |
+
|
| 196 |
+
will_clean = (cap is None) or (rows_cleaned < cap)
|
| 197 |
+
|
| 198 |
+
# Clean selected columns
|
| 199 |
+
for col in culprit_columns:
|
| 200 |
+
original = r.get(col)
|
| 201 |
+
original_s = None if original is None else str(original)
|
| 202 |
+
|
| 203 |
+
if will_clean:
|
| 204 |
+
cleaned = clean_value(llm, original_s) if original_s else None
|
| 205 |
+
r[f"{col}_clean"] = cleaned
|
| 206 |
+
rows_cleaned += 1
|
| 207 |
+
else:
|
| 208 |
+
# out-of-cap rows → NULL clean column (old behavior)
|
| 209 |
+
r[f"{col}_clean"] = None
|
| 210 |
+
|
| 211 |
+
out_rows.append(r)
|
| 212 |
+
|
| 213 |
+
# Write back to same table
|
| 214 |
+
write_batch(schema, table, out_rows, pk_col=primary_key)
|
| 215 |
+
rows_processed += len(out_rows)
|
| 216 |
+
|
| 217 |
+
# progress
|
| 218 |
+
target = cap or total_rows
|
| 219 |
+
pct = int(min(rows_cleaned, target) * 100 / target)
|
| 220 |
+
|
| 221 |
+
print(
|
| 222 |
+
f" {table}: cleaned {rows_cleaned}/{target} ({pct}%) "
|
| 223 |
+
f"| updated rows: {rows_processed} | skipped: {skipped_existing}"
|
| 224 |
+
)
|
| 225 |
+
sys.stdout.flush()
|
| 226 |
+
|
| 227 |
+
print(
|
| 228 |
+
f"✓ DONE: {schema}.{table} in-place cleaned "
|
| 229 |
+
f"(cleaned={rows_cleaned}, skipped={skipped_existing})\n"
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# ----------------------------------------------------
|
| 234 |
+
# YAML Loader
|
| 235 |
+
# ----------------------------------------------------
|
| 236 |
+
def run_cleaning_from_yaml(
|
| 237 |
+
yaml_path: str,
|
| 238 |
+
batch_size: int = 1000,
|
| 239 |
+
clean_cap: Optional[int] = None,
|
| 240 |
+
clean_all: bool = False,
|
| 241 |
+
):
|
| 242 |
+
import yaml
|
| 243 |
+
|
| 244 |
+
with open(yaml_path, "r") as f:
|
| 245 |
+
cfg = yaml.safe_load(f)
|
| 246 |
+
|
| 247 |
+
for t in cfg.get("tables", []):
|
| 248 |
+
run_clean_table(
|
| 249 |
+
schema=t["schema"],
|
| 250 |
+
table=t["name"],
|
| 251 |
+
culprit_columns=t["culprit_columns"],
|
| 252 |
+
batch_size=batch_size,
|
| 253 |
+
primary_key=t["primary_key"],
|
| 254 |
+
clean_cap=clean_cap,
|
| 255 |
+
clean_all=clean_all,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
|