init xiaoxiang project
This commit is contained in:
+978
@@ -0,0 +1,978 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import datetime
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from difflib import SequenceMatcher
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
import urllib3
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
if str(BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(BASE_DIR))
|
||||
|
||||
WORK_ID_ENV = "ELEPHANT_WORKID"
|
||||
MISSING_FILE_ENV = "ELEPHANT_MISSING_FILE"
|
||||
CHECKPOINT_FILE_ENV = "ELEPHANT_MISSING_CHECKPOINT"
|
||||
SLEEP_SECONDS_ENV = "ELEPHANT_MISSING_SLEEP"
|
||||
MAX_WORKERS_ENV = "ELEPHANT_MISSING_MAX_WORKERS"
|
||||
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
DB_CONF = {
|
||||
"host": "183.6.7.91",
|
||||
"port": 33016,
|
||||
"user": "root",
|
||||
"password": "Aliyun@7646!",
|
||||
"db": "tk_test",
|
||||
"charset": "utf8mb4",
|
||||
}
|
||||
|
||||
DEFAULT_TOKEN = "d7e0759c-8f52-4c82-8102-774da69416d5"
|
||||
|
||||
MAPPING_DICT = {
|
||||
"非及时达标签 1": ["预售", "厂家直发", "云超特卖", "xxH 发货"],
|
||||
"非及时达标签 2": ["预约", "商家直发", "云卖场", "xxH 内发货"],
|
||||
"非及时达标签 3": ["明日达", "厂商直发", "云超商城", "xx 小时内发快递"],
|
||||
"非及时达标签 4": ["明日送达", "快递发货", "云仓特卖", "XX 陆续发货"],
|
||||
"非及时达标签 5": ["次日达", "产地寻鲜", "甄选商城", "xx 月 xx 日发货"],
|
||||
"非及时达标签 6": ["多日达", "地产量贩", "社区团购", "xx.xx 送达"],
|
||||
"非及时达标签 7": ["即将开售", "跨境购", "xx 月 xx 日送达"],
|
||||
}
|
||||
|
||||
TAG_MAPPING = {
|
||||
312: "冷藏",
|
||||
319: "冷冻",
|
||||
378: "明日达",
|
||||
274: "严选",
|
||||
320: "新品",
|
||||
399: "地标",
|
||||
430: "元宵节",
|
||||
318: "冷鲜",
|
||||
377: "无抗",
|
||||
297: "秒杀价",
|
||||
365: "新鲜快手菜",
|
||||
198: "辣度2星",
|
||||
199: "辣度1星",
|
||||
163: "省心价",
|
||||
263: "省心价",
|
||||
379: "中国有机产品",
|
||||
293: "日日鲜",
|
||||
359: "黑金系列",
|
||||
366: "手工鲜切",
|
||||
148: "预定",
|
||||
}
|
||||
|
||||
ID_DICT = {
|
||||
10000439: 238,
|
||||
10000900: 2101,
|
||||
10000880: 26,
|
||||
10000665: 825,
|
||||
10000839: 2048,
|
||||
10000519: 646,
|
||||
10001060: 2150,
|
||||
10000163: 1971,
|
||||
10000952: 2123,
|
||||
10000956: 2127,
|
||||
10001084: 2155,
|
||||
10001075: 2151,
|
||||
10001107: 2158,
|
||||
10001195: 2161,
|
||||
10001222: 2162,
|
||||
10001400: 2177,
|
||||
10001506: 2188,
|
||||
10001575: 2187,
|
||||
}
|
||||
|
||||
DATA_COMPLETED_INSERT_SQL = """
|
||||
INSERT INTO data_completed
|
||||
(
|
||||
work_id, goods_id, s_id, station_id, `desc`, f_id, f_name, goods_tag, image,
|
||||
is_immediate, original_price, price, price_tag, s_name, shop_id, t_id, t_name,
|
||||
title, token, vip_price
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
|
||||
|
||||
def load_detail_module():
|
||||
module_path = BASE_DIR / "小象超市详情列表请求部分.py"
|
||||
spec = importlib.util.spec_from_file_location("elephant_detail_module", module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
module.print = lambda *args, **kwargs: None
|
||||
return module
|
||||
|
||||
|
||||
DETAIL_MODULE = load_detail_module()
|
||||
|
||||
|
||||
def log(message):
|
||||
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
print(f"[{now}] {message}", flush=True)
|
||||
|
||||
|
||||
def now_iso():
|
||||
return datetime.datetime.now().replace(microsecond=0).isoformat()
|
||||
|
||||
|
||||
def get_workid():
|
||||
format_today = str(datetime.date.today()).replace("-", "")
|
||||
return os.environ.get(WORK_ID_ENV, format_today)
|
||||
|
||||
|
||||
def get_missing_file_path():
|
||||
return BASE_DIR / os.environ.get(MISSING_FILE_ENV, "缺漏数据")
|
||||
|
||||
|
||||
def get_checkpoint_file_path():
|
||||
return BASE_DIR / os.environ.get(
|
||||
CHECKPOINT_FILE_ENV, "elephant_missing_pages_checkpoint.json"
|
||||
)
|
||||
|
||||
|
||||
def get_sleep_seconds():
|
||||
value = os.environ.get(SLEEP_SECONDS_ENV, "0")
|
||||
try:
|
||||
return max(0.0, float(value))
|
||||
except ValueError:
|
||||
return 0.0
|
||||
|
||||
|
||||
def get_max_workers(total_headers):
|
||||
value = os.environ.get(MAX_WORKERS_ENV, "10")
|
||||
try:
|
||||
requested = int(value)
|
||||
except ValueError:
|
||||
requested = 10
|
||||
return max(1, min(total_headers, requested))
|
||||
|
||||
|
||||
def get_db_connection(dict_cursor=False):
|
||||
kwargs = dict(DB_CONF)
|
||||
if dict_cursor:
|
||||
kwargs["cursorclass"] = pymysql.cursors.DictCursor
|
||||
return pymysql.connect(**kwargs)
|
||||
|
||||
|
||||
def load_checkpoint(checkpoint_path):
|
||||
if not checkpoint_path.exists():
|
||||
return {}
|
||||
try:
|
||||
with checkpoint_path.open("r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
except Exception as exc:
|
||||
log(f"checkpoint 读取失败,忽略旧文件: {exc}")
|
||||
return {}
|
||||
|
||||
|
||||
def save_checkpoint(checkpoint_path, state):
|
||||
state["updated_at"] = now_iso()
|
||||
checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp_path = checkpoint_path.with_suffix(checkpoint_path.suffix + ".tmp")
|
||||
with temp_path.open("w", encoding="utf-8") as f:
|
||||
json.dump(state, f, ensure_ascii=False, indent=2, sort_keys=True)
|
||||
temp_path.replace(checkpoint_path)
|
||||
|
||||
|
||||
def normalize_tag_text(text):
|
||||
text = str(text or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
return text.removesuffix("_折").removesuffix("_赠")
|
||||
|
||||
|
||||
def append_unique_tag(tags, seen, text):
|
||||
text = normalize_tag_text(text)
|
||||
if not text or text in {"折", "赠"}:
|
||||
return
|
||||
if text not in seen:
|
||||
seen.add(text)
|
||||
tags.append(text)
|
||||
|
||||
|
||||
def extract_group_tag_texts(group_data):
|
||||
texts = []
|
||||
for part in group_data or []:
|
||||
text = part.get("singleDataInfo", {}).get("text", "")
|
||||
text = normalize_tag_text(text)
|
||||
if text:
|
||||
texts.append(text)
|
||||
if len(texts) > 1:
|
||||
texts = [text for text in texts if text not in {"折", "赠"}]
|
||||
return texts
|
||||
|
||||
|
||||
def build_goods_tag(item, image_tags):
|
||||
tags = []
|
||||
seen = set()
|
||||
|
||||
for tag in image_tags:
|
||||
append_unique_tag(tags, seen, tag)
|
||||
|
||||
show_contents = item.get("showContents", {})
|
||||
|
||||
for node in show_contents.get("9", []):
|
||||
element_info = node.get("elementInfo", {})
|
||||
if element_info.get("constructionType") == "Text":
|
||||
text = element_info.get("singleDataInfo", {}).get("text", "")
|
||||
append_unique_tag(tags, seen, text)
|
||||
|
||||
for node in show_contents.get("10", []):
|
||||
element_info = node.get("elementInfo", {})
|
||||
if element_info.get("constructionType") != "Tag":
|
||||
continue
|
||||
for text in extract_group_tag_texts(element_info.get("groupDataInfo", [])):
|
||||
append_unique_tag(tags, seen, text)
|
||||
|
||||
for node in show_contents.get("14", []):
|
||||
element_info = node.get("elementInfo", {})
|
||||
if element_info.get("constructionType") != "Tag":
|
||||
continue
|
||||
for part in element_info.get("groupDataInfo", []):
|
||||
text = part.get("singleDataInfo", {}).get("text", "")
|
||||
append_unique_tag(tags, seen, text)
|
||||
|
||||
for node in show_contents.get("11", []):
|
||||
element_info = node.get("elementInfo", {})
|
||||
if element_info.get("constructionType") == "Text":
|
||||
text = element_info.get("singleDataInfo", {}).get("text", "")
|
||||
if text == "出清价":
|
||||
append_unique_tag(tags, seen, text)
|
||||
elif element_info.get("constructionType") == "Tag":
|
||||
for text in extract_group_tag_texts(element_info.get("groupDataInfo", [])):
|
||||
append_unique_tag(tags, seen, text)
|
||||
|
||||
label = item.get("lxInfo", {}).get("label", "")
|
||||
for part in str(label).split(","):
|
||||
part = normalize_tag_text(part)
|
||||
if part == "出清价" or "折" in part:
|
||||
append_unique_tag(tags, seen, part)
|
||||
|
||||
return "--".join(tags)
|
||||
|
||||
|
||||
def find_all_values_by_key(data, target_key):
|
||||
results = []
|
||||
if isinstance(data, dict):
|
||||
for key, value in data.items():
|
||||
if key == target_key:
|
||||
results.append(value)
|
||||
if isinstance(value, (dict, list)):
|
||||
results.extend(find_all_values_by_key(value, target_key))
|
||||
elif isinstance(data, list):
|
||||
for item in data:
|
||||
results.extend(find_all_values_by_key(item, target_key))
|
||||
return results
|
||||
|
||||
|
||||
def clean_price(price_str):
|
||||
if price_str is None or price_str == "":
|
||||
return 0.0
|
||||
clean_str = "".join(ch for ch in str(price_str) if ch.isdigit() or ch == ".")
|
||||
try:
|
||||
return float(clean_str)
|
||||
except ValueError:
|
||||
return 0.0
|
||||
|
||||
|
||||
def ensure_json_dict(value):
|
||||
if isinstance(value, dict):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
return json.loads(value)
|
||||
raise ValueError(f"无法解析 JSON: {type(value)}")
|
||||
|
||||
|
||||
def task_key(task):
|
||||
return "|".join(
|
||||
[
|
||||
task["work_id"],
|
||||
str(task["shop_id"]),
|
||||
str(task["one_id"]),
|
||||
str(task["two_id"]),
|
||||
str(task["page_no"]),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def category_key_from_task(task):
|
||||
return "|".join(
|
||||
[
|
||||
task["work_id"],
|
||||
str(task["shop_id"]),
|
||||
str(task["one_id"]),
|
||||
str(task["two_id"]),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def format_task(task):
|
||||
return (
|
||||
f"店铺={task['shop_id']} 分类={task['one_name']}/{task['two_name']} "
|
||||
f"页={task['page_no']}"
|
||||
)
|
||||
|
||||
|
||||
def read_missing_entries(missing_file_path):
|
||||
entries = []
|
||||
with missing_file_path.open("r", encoding="utf-8") as f:
|
||||
for line_no, raw_line in enumerate(f, start=1):
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
try:
|
||||
head, page_text = line.rsplit("-", 1)
|
||||
shop_text, names_text = head.split("-", 1)
|
||||
entry = {
|
||||
"line_no": line_no,
|
||||
"source_line": line,
|
||||
"shop_id": int(shop_text),
|
||||
"names_text": names_text,
|
||||
"page_no": int(page_text),
|
||||
}
|
||||
except Exception as exc:
|
||||
raise ValueError(f"缺漏数据第 {line_no} 行格式不对: {line} ({exc})")
|
||||
entries.append(entry)
|
||||
return entries
|
||||
|
||||
|
||||
def compact_name(text):
|
||||
return "".join(
|
||||
ch for ch in str(text or "").strip() if ch not in {"/", "/", " ", "-", "_"}
|
||||
)
|
||||
|
||||
|
||||
def score_category_name(source_full, candidate_full):
|
||||
if source_full == candidate_full:
|
||||
return 1000
|
||||
source_compact = compact_name(source_full)
|
||||
candidate_compact = compact_name(candidate_full)
|
||||
if source_compact == candidate_compact:
|
||||
return 950
|
||||
|
||||
score = 0
|
||||
if source_full in candidate_full or candidate_full in source_full:
|
||||
score = max(score, 850)
|
||||
if source_compact in candidate_compact or candidate_compact in source_compact:
|
||||
score = max(score, 800)
|
||||
score = max(
|
||||
score, int(SequenceMatcher(None, source_full, candidate_full).ratio() * 700)
|
||||
)
|
||||
score = max(
|
||||
score,
|
||||
int(SequenceMatcher(None, source_compact, candidate_compact).ratio() * 750),
|
||||
)
|
||||
return score
|
||||
|
||||
|
||||
def load_category_lookup(work_id, shop_ids):
|
||||
if not shop_ids:
|
||||
return {}
|
||||
placeholders = ",".join(["%s"] * len(shop_ids))
|
||||
sql = f"""
|
||||
SELECT id, shop_id, one_id, one_name, two_id, two_name, one_all_num
|
||||
FROM category_detail
|
||||
WHERE work_id = %s AND shop_id IN ({placeholders})
|
||||
"""
|
||||
params = [work_id, *shop_ids]
|
||||
conn = get_db_connection(dict_cursor=True)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql, params)
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
lookup = defaultdict(list)
|
||||
for row in rows:
|
||||
lookup[int(row["shop_id"])].append(row)
|
||||
return lookup
|
||||
|
||||
|
||||
def resolve_task(entry, category_lookup, work_id):
|
||||
rows = category_lookup.get(entry["shop_id"], [])
|
||||
if not rows:
|
||||
raise ValueError(
|
||||
f"当前 work_id={work_id} 下找不到店铺 {entry['shop_id']} 的分类数据"
|
||||
)
|
||||
|
||||
source_full = entry["names_text"]
|
||||
exact_matches = [
|
||||
row for row in rows if f"{row['one_name']}-{row['two_name']}" == source_full
|
||||
]
|
||||
if len(exact_matches) > 1:
|
||||
raise ValueError(
|
||||
f"无法唯一匹配分类: 第 {entry['line_no']} 行 {entry['source_line']},精确命中 {len(exact_matches)} 条"
|
||||
)
|
||||
|
||||
mapped = False
|
||||
if exact_matches:
|
||||
row = exact_matches[0]
|
||||
else:
|
||||
scored = []
|
||||
for row in rows:
|
||||
candidate_full = f"{row['one_name']}-{row['two_name']}"
|
||||
score = score_category_name(source_full, candidate_full)
|
||||
scored.append((score, candidate_full, row))
|
||||
scored.sort(key=lambda item: item[0], reverse=True)
|
||||
best_score, _, row = scored[0]
|
||||
second_score = scored[1][0] if len(scored) > 1 else -1
|
||||
if best_score < 650 or best_score == second_score:
|
||||
raise ValueError(
|
||||
f"无法唯一匹配分类: 第 {entry['line_no']} 行 {entry['source_line']},最佳分数 {best_score}"
|
||||
)
|
||||
mapped = True
|
||||
|
||||
one_name = row["one_name"]
|
||||
two_name = row["two_name"]
|
||||
task = {
|
||||
"line_no": entry["line_no"],
|
||||
"source_line": entry["source_line"],
|
||||
"work_id": work_id,
|
||||
"shop_id": int(row["shop_id"]),
|
||||
"category_row_id": int(row["id"]),
|
||||
"one_id": int(row["one_id"]),
|
||||
"one_name": one_name,
|
||||
"two_id": int(row["two_id"]),
|
||||
"two_name": two_name,
|
||||
"one_all_num": int(row["one_all_num"] or 0),
|
||||
"page_no": entry["page_no"],
|
||||
"status": "pending",
|
||||
"attempts": 0,
|
||||
"rebuild_attempts": 0,
|
||||
"last_error": "",
|
||||
"rebuild_last_error": "",
|
||||
"last_header_id": None,
|
||||
"page_replaced_at": None,
|
||||
"category_rebuilt_at": None,
|
||||
"updated_at": None,
|
||||
}
|
||||
task["category_key"] = category_key_from_task(task)
|
||||
task["task_key"] = task_key(task)
|
||||
if mapped:
|
||||
log(
|
||||
"分类名自动映射: "
|
||||
f"第 {entry['line_no']} 行 {entry['names_text']} -> {one_name}-{two_name}"
|
||||
)
|
||||
return task
|
||||
|
||||
|
||||
def build_state(work_id, missing_file_path, checkpoint_path):
|
||||
raw_entries = read_missing_entries(missing_file_path)
|
||||
if not raw_entries:
|
||||
raise ValueError("缺漏数据文件为空")
|
||||
|
||||
shop_ids = sorted({entry["shop_id"] for entry in raw_entries})
|
||||
category_lookup = load_category_lookup(work_id, shop_ids)
|
||||
old_state = load_checkpoint(checkpoint_path)
|
||||
old_tasks = old_state.get("tasks", {}) if isinstance(old_state, dict) else {}
|
||||
|
||||
state = {
|
||||
"version": 1,
|
||||
"mode": "missing_page_repair",
|
||||
"work_id": work_id,
|
||||
"source_file": str(missing_file_path),
|
||||
"updated_at": now_iso(),
|
||||
"tasks": {},
|
||||
}
|
||||
|
||||
for entry in raw_entries:
|
||||
task = resolve_task(entry, category_lookup, work_id)
|
||||
old_task = old_tasks.get(task["task_key"], {})
|
||||
for field in [
|
||||
"status",
|
||||
"attempts",
|
||||
"rebuild_attempts",
|
||||
"last_error",
|
||||
"rebuild_last_error",
|
||||
"last_header_id",
|
||||
"page_replaced_at",
|
||||
"category_rebuilt_at",
|
||||
"updated_at",
|
||||
]:
|
||||
if field in old_task:
|
||||
task[field] = old_task[field]
|
||||
if task["task_key"] in state["tasks"]:
|
||||
log(f"缺漏文件里有重复任务,已自动去重: {task['source_line']}")
|
||||
continue
|
||||
state["tasks"][task["task_key"]] = task
|
||||
return state
|
||||
|
||||
|
||||
def summarize_tasks(tasks):
|
||||
summary = defaultdict(int)
|
||||
for task in tasks.values():
|
||||
summary[task["status"]] += 1
|
||||
return dict(summary)
|
||||
|
||||
|
||||
class BadHeaderError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def fetch_missing_page(task, hd):
|
||||
hd_id = hd[0]
|
||||
log(f"开始请求 {format_task(task)},使用 header_id={hd_id}")
|
||||
try:
|
||||
response, _ = DETAIL_MODULE.one_(
|
||||
task["one_id"],
|
||||
task["two_id"],
|
||||
task["page_no"],
|
||||
task["shop_id"],
|
||||
hd,
|
||||
task["one_all_num"],
|
||||
)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"header_id={hd_id} 请求异常: {exc}") from exc
|
||||
|
||||
if "您的网络好像不太给力" in response.text:
|
||||
DETAIL_MODULE.update_headers(418, hd_id)
|
||||
raise BadHeaderError(f"header_id={hd_id} 您的网络好像不太给力")
|
||||
|
||||
try:
|
||||
req_json = response.json()
|
||||
except Exception as exc:
|
||||
if "Expecting value: line 1 column 1 (char 0)" in str(exc):
|
||||
DETAIL_MODULE.update_headers(403, hd_id)
|
||||
raise BadHeaderError(f"header_id={hd_id} JSON 解析失败: {exc}") from exc
|
||||
raise RuntimeError(f"header_id={hd_id} JSON 解析失败: {exc}") from exc
|
||||
|
||||
if req_json.get("data") == {}:
|
||||
raise RuntimeError(f"header_id={hd_id} 返回 data 为空")
|
||||
|
||||
try:
|
||||
one_price = req_json["data"]["contents"][0]["subModule"]["contents"][0][
|
||||
"lxInfo"
|
||||
]["sale_price"]
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"header_id={hd_id} 首商品价格读取失败: {exc}") from exc
|
||||
|
||||
if one_price == "?":
|
||||
DETAIL_MODULE.update_headers(406, hd_id)
|
||||
raise BadHeaderError(f"header_id={hd_id} 首商品价格仍为 ?")
|
||||
|
||||
DETAIL_MODULE.update_headers(1, hd_id)
|
||||
return req_json, hd_id
|
||||
|
||||
|
||||
def page_repair_worker(worker_no, hd, task_queue, state, checkpoint_path, state_lock):
|
||||
worker_name = f"worker-{worker_no}"
|
||||
hd_id = hd[0]
|
||||
sleep_seconds = get_sleep_seconds()
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
requeue_count = 0
|
||||
log(f"[{worker_name}] 启动,header_id={hd_id}")
|
||||
|
||||
while True:
|
||||
try:
|
||||
task_key = task_queue.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
with state_lock:
|
||||
task = state["tasks"].get(task_key)
|
||||
if task is None or task["status"] in {"page_replaced", "done"}:
|
||||
current_task = None
|
||||
else:
|
||||
current_task = dict(task)
|
||||
|
||||
if current_task is None:
|
||||
task_queue.task_done()
|
||||
continue
|
||||
|
||||
try:
|
||||
req_json, used_hd_id = fetch_missing_page(current_task, hd)
|
||||
deleted_count = replace_page_log(current_task, req_json)
|
||||
except BadHeaderError as exc:
|
||||
with state_lock:
|
||||
task = state["tasks"][task_key]
|
||||
task["attempts"] += 1
|
||||
task["status"] = "pending"
|
||||
task["last_error"] = str(exc)
|
||||
task["last_header_id"] = hd_id
|
||||
task["updated_at"] = now_iso()
|
||||
save_checkpoint(checkpoint_path, state)
|
||||
requeue_count += 1
|
||||
task_queue.put(task_key)
|
||||
task_queue.task_done()
|
||||
log(
|
||||
f"[{worker_name}] header_id={hd_id} 已废弃,任务回队: "
|
||||
f"{format_task(current_task)},原因: {exc}"
|
||||
)
|
||||
break
|
||||
except Exception as exc:
|
||||
with state_lock:
|
||||
task = state["tasks"][task_key]
|
||||
task["attempts"] += 1
|
||||
task["status"] = "failed"
|
||||
task["last_error"] = str(exc)
|
||||
task["last_header_id"] = hd_id
|
||||
task["updated_at"] = now_iso()
|
||||
save_checkpoint(checkpoint_path, state)
|
||||
failed_count += 1
|
||||
task_queue.task_done()
|
||||
log(f"补页失败: {format_task(current_task)},原因: {exc}")
|
||||
else:
|
||||
with state_lock:
|
||||
task = state["tasks"][task_key]
|
||||
task["attempts"] += 1
|
||||
task["status"] = "page_replaced"
|
||||
task["last_error"] = ""
|
||||
task["last_header_id"] = used_hd_id
|
||||
task["page_replaced_at"] = now_iso()
|
||||
task["updated_at"] = now_iso()
|
||||
save_checkpoint(checkpoint_path, state)
|
||||
success_count += 1
|
||||
task_queue.task_done()
|
||||
log(
|
||||
f"补页成功: {format_task(current_task)},header_id={used_hd_id},"
|
||||
f"替换旧日志 {deleted_count} 条"
|
||||
)
|
||||
|
||||
if sleep_seconds > 0:
|
||||
time.sleep(sleep_seconds)
|
||||
|
||||
log(
|
||||
f"[{worker_name}] 退出,header_id={hd_id},"
|
||||
f"成功 {success_count} 条,失败 {failed_count} 条,回队 {requeue_count} 条"
|
||||
)
|
||||
|
||||
|
||||
def replace_page_log(task, req_json):
|
||||
delete_sql = """
|
||||
DELETE FROM category_detail_log
|
||||
WHERE work_id = %s AND shop_id = %s AND one_id = %s AND two_id = %s AND category_detail_id = %s
|
||||
"""
|
||||
insert_sql = """
|
||||
INSERT INTO category_detail_log
|
||||
(shop_id, category_detail_id, one_id, two_id, req_json, work_id)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
req_text = json.dumps(req_json, ensure_ascii=False)
|
||||
conn = get_db_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
delete_sql,
|
||||
(
|
||||
task["work_id"],
|
||||
task["shop_id"],
|
||||
task["one_id"],
|
||||
task["two_id"],
|
||||
task["page_no"],
|
||||
),
|
||||
)
|
||||
deleted_count = cur.rowcount
|
||||
cur.execute(
|
||||
insert_sql,
|
||||
(
|
||||
task["shop_id"],
|
||||
task["page_no"],
|
||||
task["one_id"],
|
||||
task["two_id"],
|
||||
req_text,
|
||||
task["work_id"],
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return deleted_count
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def build_data_completed_rows(task, req_json):
|
||||
station_id = ID_DICT.get(task["shop_id"])
|
||||
if station_id is None:
|
||||
raise ValueError(f"店铺 {task['shop_id']} 没有 station_id 映射")
|
||||
|
||||
payload = ensure_json_dict(req_json)
|
||||
contents = payload["data"]["contents"][0]["subModule"]["contents"]
|
||||
rows = []
|
||||
for item in contents:
|
||||
all_image_urls = find_all_values_by_key(item, "elementId")
|
||||
all_mapping = find_all_values_by_key(item, "text")
|
||||
ocr_results = []
|
||||
ocr_mapping = 1
|
||||
|
||||
for value in all_image_urls:
|
||||
if value in TAG_MAPPING:
|
||||
ocr_results.append(TAG_MAPPING[value])
|
||||
|
||||
for text in all_mapping:
|
||||
if any(text in values for values in MAPPING_DICT.values()):
|
||||
ocr_mapping = 0
|
||||
|
||||
title = item.get("lxInfo", {}).get("content_name", "")
|
||||
goods_id = item.get("logicContents", {}).get("skuId", "")
|
||||
desc = item.get("lxInfo", {}).get("label", "")
|
||||
price = item.get("lxInfo", {}).get("sale_price", 0.0)
|
||||
original_price = item.get("lxInfo", {}).get("origin_price", 0.0)
|
||||
vip_price = item.get("lxInfo", {}).get("member_price", 0.0)
|
||||
goods_tag = build_goods_tag(item, ocr_results)
|
||||
show_contents = item.get("showContents", {})
|
||||
image_list = show_contents.get("6", [])
|
||||
if isinstance(image_list, list) and image_list:
|
||||
image = (
|
||||
image_list[0]
|
||||
.get("elementInfo", {})
|
||||
.get("singleDataInfo", {})
|
||||
.get("image", {})
|
||||
.get("url", "")
|
||||
)
|
||||
else:
|
||||
image = ""
|
||||
|
||||
rows.append(
|
||||
(
|
||||
task["work_id"],
|
||||
goods_id,
|
||||
task["two_id"],
|
||||
station_id,
|
||||
desc,
|
||||
task["one_id"],
|
||||
task["one_name"],
|
||||
goods_tag,
|
||||
image,
|
||||
1 if ocr_mapping else 0,
|
||||
clean_price(original_price),
|
||||
clean_price(price),
|
||||
goods_tag,
|
||||
task["two_name"],
|
||||
task["shop_id"],
|
||||
None,
|
||||
None,
|
||||
title,
|
||||
DEFAULT_TOKEN,
|
||||
clean_price(vip_price),
|
||||
)
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def load_latest_page_logs_for_category(task):
|
||||
sql = """
|
||||
SELECT id, category_detail_id, req_json
|
||||
FROM category_detail_log
|
||||
WHERE work_id = %s AND shop_id = %s AND one_id = %s AND two_id = %s
|
||||
ORDER BY category_detail_id ASC, id DESC
|
||||
"""
|
||||
conn = get_db_connection(dict_cursor=True)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
sql,
|
||||
(task["work_id"], task["shop_id"], task["one_id"], task["two_id"]),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
latest_by_page = {}
|
||||
for row in rows:
|
||||
page_no = int(row["category_detail_id"])
|
||||
if page_no not in latest_by_page:
|
||||
latest_by_page[page_no] = row
|
||||
return latest_by_page
|
||||
|
||||
|
||||
def rebuild_category_data(task):
|
||||
latest_by_page = load_latest_page_logs_for_category(task)
|
||||
if not latest_by_page:
|
||||
raise ValueError(f"{format_task(task)} 没查到任何页日志,无法重清洗")
|
||||
|
||||
all_rows = []
|
||||
for page_no in sorted(latest_by_page):
|
||||
page_log = latest_by_page[page_no]
|
||||
try:
|
||||
page_rows = build_data_completed_rows(task, page_log["req_json"])
|
||||
except Exception as exc:
|
||||
raise ValueError(f"第 {page_no} 页重清洗失败: {exc}") from exc
|
||||
all_rows.extend(page_rows)
|
||||
|
||||
if not all_rows:
|
||||
raise ValueError(f"{format_task(task)} 页日志存在,但没有解析出任何商品")
|
||||
|
||||
delete_sql = """
|
||||
DELETE FROM data_completed
|
||||
WHERE work_id = %s AND shop_id = %s AND f_id = %s AND s_id = %s
|
||||
"""
|
||||
conn = get_db_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
delete_sql,
|
||||
(
|
||||
task["work_id"],
|
||||
str(task["shop_id"]),
|
||||
str(task["one_id"]),
|
||||
str(task["two_id"]),
|
||||
),
|
||||
)
|
||||
deleted_count = cur.rowcount
|
||||
cur.executemany(DATA_COMPLETED_INSERT_SQL, all_rows)
|
||||
inserted_count = cur.rowcount
|
||||
conn.commit()
|
||||
return len(latest_by_page), deleted_count, inserted_count
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_page_tasks_to_run(tasks):
|
||||
return [
|
||||
task
|
||||
for task in tasks.values()
|
||||
if task["status"] not in {"page_replaced", "done"}
|
||||
]
|
||||
|
||||
|
||||
def get_categories_ready_to_rebuild(tasks):
|
||||
grouped = defaultdict(list)
|
||||
for task in tasks.values():
|
||||
grouped[task["category_key"]].append(task)
|
||||
|
||||
ready = []
|
||||
for group_tasks in grouped.values():
|
||||
statuses = {task["status"] for task in group_tasks}
|
||||
has_page_replaced = any(
|
||||
task["status"] == "page_replaced" for task in group_tasks
|
||||
)
|
||||
if has_page_replaced and statuses.issubset({"page_replaced", "done"}):
|
||||
ready.append(sorted(group_tasks, key=lambda item: item["page_no"]))
|
||||
ready.sort(
|
||||
key=lambda group: (group[0]["shop_id"], group[0]["one_id"], group[0]["two_id"])
|
||||
)
|
||||
return ready
|
||||
|
||||
|
||||
def run_page_repair_phase(state, checkpoint_path):
|
||||
page_tasks = get_page_tasks_to_run(state["tasks"])
|
||||
if not page_tasks:
|
||||
log("补页阶段: 没有待处理页")
|
||||
return
|
||||
|
||||
headers = list(DETAIL_MODULE.get_hds())
|
||||
if not headers:
|
||||
raise RuntimeError("没有可用详情 headers")
|
||||
|
||||
worker_count = get_max_workers(len(headers))
|
||||
state_lock = threading.Lock()
|
||||
task_queue = queue.Queue()
|
||||
for task in page_tasks:
|
||||
task_queue.put(task["task_key"])
|
||||
|
||||
log(
|
||||
f"补页阶段启动: 待处理 {len(page_tasks)} 条,"
|
||||
f"可用 headers {len(headers)} 个,并发 {worker_count}"
|
||||
)
|
||||
with ThreadPoolExecutor(max_workers=worker_count) as pool:
|
||||
futures = []
|
||||
for worker_no, hd in enumerate(headers, start=1):
|
||||
futures.append(
|
||||
pool.submit(
|
||||
page_repair_worker,
|
||||
worker_no,
|
||||
hd,
|
||||
task_queue,
|
||||
state,
|
||||
checkpoint_path,
|
||||
state_lock,
|
||||
)
|
||||
)
|
||||
for future in futures:
|
||||
future.result()
|
||||
|
||||
remaining = task_queue.qsize()
|
||||
summary = summarize_tasks(state["tasks"])
|
||||
log(f"补页阶段结束: 队列剩余 {remaining} 条,状态分布 {summary}")
|
||||
|
||||
|
||||
def run_category_rebuild_phase(state, checkpoint_path):
|
||||
ready_groups = get_categories_ready_to_rebuild(state["tasks"])
|
||||
if not ready_groups:
|
||||
log("重清洗阶段: 没有待重建分类")
|
||||
return
|
||||
|
||||
for index, group_tasks in enumerate(ready_groups, start=1):
|
||||
task = group_tasks[0]
|
||||
title = (
|
||||
f"店铺={task['shop_id']} 分类={task['one_name']}/{task['two_name']} "
|
||||
f"缺漏页数={len(group_tasks)}"
|
||||
)
|
||||
log(f"[重清洗 {index}/{len(ready_groups)}] {title}")
|
||||
for item in group_tasks:
|
||||
item["rebuild_attempts"] += 1
|
||||
try:
|
||||
page_count, deleted_count, inserted_count = rebuild_category_data(task)
|
||||
rebuilt_at = now_iso()
|
||||
for item in group_tasks:
|
||||
item["status"] = "done"
|
||||
item["rebuild_last_error"] = ""
|
||||
item["category_rebuilt_at"] = rebuilt_at
|
||||
item["updated_at"] = rebuilt_at
|
||||
save_checkpoint(checkpoint_path, state)
|
||||
log(
|
||||
f"重清洗成功: 店铺={task['shop_id']} 分类={task['one_name']}/{task['two_name']},"
|
||||
f"采用 {page_count} 页最新日志,删除旧成品 {deleted_count} 条,插入新成品 {inserted_count} 条"
|
||||
)
|
||||
except Exception as exc:
|
||||
for item in group_tasks:
|
||||
item["rebuild_last_error"] = str(exc)
|
||||
item["updated_at"] = now_iso()
|
||||
save_checkpoint(checkpoint_path, state)
|
||||
log(f"重清洗失败: {title},原因: {exc}")
|
||||
|
||||
|
||||
def main():
|
||||
work_id = get_workid()
|
||||
missing_file_path = get_missing_file_path()
|
||||
checkpoint_path = get_checkpoint_file_path()
|
||||
log(f"本次 work_id: {work_id}")
|
||||
log(f"缺漏文件: {missing_file_path}")
|
||||
log(f"checkpoint: {checkpoint_path}")
|
||||
|
||||
if not missing_file_path.exists():
|
||||
raise FileNotFoundError(f"缺漏文件不存在: {missing_file_path}")
|
||||
|
||||
state = build_state(work_id, missing_file_path, checkpoint_path)
|
||||
save_checkpoint(checkpoint_path, state)
|
||||
summary = summarize_tasks(state["tasks"])
|
||||
log(f"任务装载完成: 总计 {len(state['tasks'])} 条,状态分布 {summary}")
|
||||
|
||||
try:
|
||||
run_page_repair_phase(state, checkpoint_path)
|
||||
run_category_rebuild_phase(state, checkpoint_path)
|
||||
except KeyboardInterrupt:
|
||||
save_checkpoint(checkpoint_path, state)
|
||||
log("收到中断信号,已保存 checkpoint;下次直接重跑脚本即可续跑")
|
||||
raise
|
||||
|
||||
summary = summarize_tasks(state["tasks"])
|
||||
log(f"执行结束,状态分布 {summary}")
|
||||
failed_tasks = [
|
||||
task for task in state["tasks"].values() if task["status"] == "failed"
|
||||
]
|
||||
if failed_tasks:
|
||||
log(f"仍有 {len(failed_tasks)} 条补页失败,重跑脚本会自动继续尝试")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user