research_tasks.py 17.7 KB
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
from __future__ import annotations

import json
import threading
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from uuid import uuid4

from loguru import logger
from utils.runtime_paths import LOGS_DIR

_UNSET = object()

PROJECT_ROOT = Path(__file__).resolve().parent.parent
RESEARCH_TASKS_PATH = LOGS_DIR / "venue_research_tasks.json"

RESEARCH_VENUE_TYPE_OPTIONS = [
    {"value": "museum", "label": "博物馆"},
    {"value": "art_gallery", "label": "艺术馆"},
    {"value": "digital_art_center", "label": "数字艺术中心"},
    {"value": "science_center", "label": "科技馆"},
    {"value": "memorial_hall", "label": "纪念馆"},
    {"value": "cultural_complex", "label": "综合文化场馆"},
]

RESEARCH_FOCUS_OPTIONS = [
    {"value": "strengths_improvements", "label": "识别优点与待改进点"},
    {"value": "operations_diagnosis", "label": "运营诊断与服务优化"},
    {"value": "experience_feedback", "label": "用户体验反馈研究"},
    {"value": "campaign_review", "label": "活动 / 特展复盘"},
    {"value": "benchmark_compare", "label": "竞品 / 标杆对比"},
]

RESEARCH_TIME_RANGE_OPTIONS = [
    {"value": "recent_30_days", "label": "近 30 天"},
    {"value": "recent_90_days", "label": "近 90 天"},
    {"value": "recent_180_days", "label": "近 180 天"},
    {"value": "recent_365_days", "label": "近 1 年"},
    {"value": "custom_window", "label": "自定义时间窗口"},
]

RESEARCH_STATUS_LABELS = {
    "draft": "草稿",
    "ready": "已就绪",
    "researching": "研究中",
    "reported": "已生成报告",
    "archived": "已归档",
}

UNIFIED_RESEARCH_STATUS_LABELS = {
    "draft": "草稿",
    "ready": "已就绪",
    "queued": "待采集",
    "crawling": "采集中",
    "analyzing": "分析中",
    "reporting": "报告生成中",
    "completed": "已完成",
    "failed": "失败",
    "cancelled": "已取消",
    "archived": "已归档",
}

LEGACY_STATUS_FROM_UNIFIED = {
    "draft": "draft",
    "ready": "ready",
    "queued": "researching",
    "crawling": "researching",
    "analyzing": "researching",
    "reporting": "researching",
    "completed": "reported",
    "failed": "researching",
    "cancelled": "archived",
    "archived": "archived",
}

UNIFIED_STATUS_FROM_LEGACY = {
    "draft": "draft",
    "ready": "ready",
    "researching": "analyzing",
    "reported": "completed",
    "archived": "archived",
}


class ResearchTaskStore:
    """JSON-backed store for the venue research task workflow."""

    def __init__(self, path: Path):
        self._path = path
        self._lock = threading.Lock()
        self._store: Optional[Dict[str, Any]] = None

    def _default_store(self) -> Dict[str, Any]:
        return {"active_task_id": None, "tasks": []}

    def _load_locked(self) -> Dict[str, Any]:
        if self._store is not None:
            return self._store

        if not self._path.exists():
            self._store = self._default_store()
            return self._store

        try:
            data = json.loads(self._path.read_text(encoding="utf-8"))
            if not isinstance(data, dict):
                raise ValueError("Research task store must be an object")
            tasks = data.get("tasks") or []
            if not isinstance(tasks, list):
                tasks = []
            self._store = {
                "active_task_id": data.get("active_task_id"),
                "tasks": tasks,
            }
        except Exception as exc:
            logger.warning(f"Failed to load research task store, resetting it: {exc}")
            self._store = self._default_store()
        return self._store

    def _save_locked(self) -> None:
        if self._store is None:
            return
        self._path.parent.mkdir(parents=True, exist_ok=True)
        self._path.write_text(
            json.dumps(self._store, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )

    @staticmethod
    def _list_to_display_text(values: List[str]) -> str:
        return "\n".join([item for item in values if item]) if values else ""

    @staticmethod
    def _normalize_multiline_values(raw_value: Any) -> List[str]:
        if raw_value is None:
            return []
        if isinstance(raw_value, list):
            raw_parts = raw_value
        else:
            raw_parts = (
                str(raw_value)
                .replace(",", ",")
                .replace(";", "\n")
                .replace(";", "\n")
                .splitlines()
            )

        results: List[str] = []
        seen = set()
        for part in raw_parts:
            for piece in str(part).split(","):
                value = piece.strip()
                if not value or value in seen:
                    continue
                seen.add(value)
                results.append(value)
        return results

    @staticmethod
    def _get_option_label(options: List[Dict[str, str]], value: str, default_label: str = "") -> str:
        for option in options:
            if option.get("value") == value:
                return option.get("label", default_label)
        return default_label or value

    def _compose_research_query(self, task: Dict[str, Any]) -> str:
        venue_name = task.get("venue_name", "").strip()
        city = task.get("city", "").strip()
        venue_type_label = task.get("venue_type_label") or self._get_option_label(
            RESEARCH_VENUE_TYPE_OPTIONS,
            task.get("venue_type"),
            "场馆",
        )
        focus_label = task.get("research_focus_label") or self._get_option_label(
            RESEARCH_FOCUS_OPTIONS,
            task.get("research_focus"),
            "运营反馈调研",
        )
        time_range_label = task.get("time_range_label") or self._get_option_label(
            RESEARCH_TIME_RANGE_OPTIONS,
            task.get("time_range"),
            "近 90 天",
        )
        benchmark_list = task.get("benchmark_venues") or []
        benchmark_text = f";竞品或标杆参考:{'、'.join(benchmark_list)}" if benchmark_list else ""
        notes = task.get("notes", "").strip()
        notes_text = f";补充要求:{notes}" if notes else ""

        base_subject = f"{city}{venue_name}" if city else venue_name
        return (
            f"请围绕 {base_subject} 这家 {venue_type_label} 开展 {focus_label},"
            f"重点收集 {time_range_label} 内的用户反馈、公开资料与社交平台内容,"
            f"输出优点、待改进点、改进建议与可借鉴做法{benchmark_text}{notes_text}。"
        )

    def _compose_crawler_keywords(self, task: Dict[str, Any]) -> List[str]:
        venue_name = task.get("venue_name", "").strip()
        city = task.get("city", "").strip()
        benchmark_list = task.get("benchmark_venues") or []

        base_keywords = [
            venue_name,
            f"{venue_name} {city}" if city else "",
            f"{venue_name} 评价",
            f"{venue_name} 值不值得去",
            f"{venue_name} 排队",
            f"{venue_name} 服务",
            f"{venue_name} 展览",
            f"{venue_name} 拍照",
        ]
        if benchmark_list:
            base_keywords.append(f"{venue_name} 对比 {' '.join(benchmark_list[:2])}")
        return [item for item in self._normalize_multiline_values(base_keywords) if item]

    @staticmethod
    def _sanitize_status(value: str) -> str:
        return value if value in RESEARCH_STATUS_LABELS else "draft"

    @staticmethod
    def _normalize_unified_status(value: Any) -> str:
        raw_value = str(value or "").strip().lower()
        if raw_value in UNIFIED_RESEARCH_STATUS_LABELS:
            return raw_value
        return UNIFIED_STATUS_FROM_LEGACY.get(raw_value, "draft")

    def _legacy_status_from_unified(self, value: Any) -> str:
        return LEGACY_STATUS_FROM_UNIFIED[self._normalize_unified_status(value)]

    def _resolve_status_label(self, *, legacy_status: Any, unified_status: Any) -> str:
        normalized_unified = self._normalize_unified_status(unified_status)
        return UNIFIED_RESEARCH_STATUS_LABELS.get(
            normalized_unified,
            RESEARCH_STATUS_LABELS.get(str(legacy_status or "").lower(), "草稿"),
        )

    def _find_task_locked(self, task_id: str) -> Optional[Dict[str, Any]]:
        store = self._load_locked()
        for task in store["tasks"]:
            if task.get("task_id") == task_id:
                return task
        return None

    def _serialize_task(self, task: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
        if not task:
            return None

        serialized = dict(task)
        serialized["unified_status"] = self._normalize_unified_status(
            serialized.get("unified_status") or serialized.get("status")
        )
        serialized["status_label"] = self._resolve_status_label(
            legacy_status=serialized.get("status"),
            unified_status=serialized.get("unified_status"),
        )
        serialized["summary_text"] = (
            f"{serialized.get('venue_name', '')}"
            f"{(' 路 ' + serialized.get('city', '')) if serialized.get('city') else ''}"
            f"{(' 路 ' + serialized.get('research_focus_label', '')) if serialized.get('research_focus_label') else ''}"
        )
        serialized["benchmark_venues_text"] = self._list_to_display_text(serialized.get("benchmark_venues") or [])
        serialized["crawler_keywords_text"] = self._list_to_display_text(serialized.get("crawler_keywords") or [])
        return serialized

    def _snapshot_locked(self, limit: int = 12) -> Dict[str, Any]:
        store = self._load_locked()
        tasks = sorted(
            store["tasks"],
            key=lambda item: item.get("updated_at") or item.get("created_at") or "",
            reverse=True,
        )
        active_task_id = store.get("active_task_id")
        active_task = self._find_task_locked(active_task_id) if active_task_id else None
        return {
            "active_task": self._serialize_task(active_task),
            "tasks": [self._serialize_task(task) for task in tasks[:limit]],
        }

    def _build_task_record(self, payload: Dict[str, Any], existing_task: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        now = datetime.now().isoformat()
        task = dict(existing_task or {})

        venue_name = str(payload.get("venue_name", "")).strip()
        if not venue_name:
            raise ValueError("请填写场馆名称")

        venue_type = str(payload.get("venue_type") or "museum").strip()
        research_focus = str(payload.get("research_focus") or "strengths_improvements").strip()
        time_range = str(payload.get("time_range") or "recent_90_days").strip()

        venue_type_values = {item["value"] for item in RESEARCH_VENUE_TYPE_OPTIONS}
        focus_values = {item["value"] for item in RESEARCH_FOCUS_OPTIONS}
        time_range_values = {item["value"] for item in RESEARCH_TIME_RANGE_OPTIONS}

        if venue_type not in venue_type_values:
            venue_type = "museum"
        if research_focus not in focus_values:
            research_focus = "strengths_improvements"
        if time_range not in time_range_values:
            time_range = "recent_90_days"

        task["task_id"] = task.get("task_id") or f"venue-{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid4().hex[:6]}"
        task["venue_name"] = venue_name
        task["city"] = str(payload.get("city", "")).strip()
        task["venue_type"] = venue_type
        task["venue_type_label"] = self._get_option_label(RESEARCH_VENUE_TYPE_OPTIONS, venue_type, "场馆")
        task["research_focus"] = research_focus
        task["research_focus_label"] = self._get_option_label(RESEARCH_FOCUS_OPTIONS, research_focus, "运营反馈调研")
        task["time_range"] = time_range
        task["time_range_label"] = self._get_option_label(RESEARCH_TIME_RANGE_OPTIONS, time_range, "近 90 天")
        task["benchmark_venues"] = self._normalize_multiline_values(payload.get("benchmark_venues"))
        task["notes"] = str(payload.get("notes", "")).strip()
        task["unified_status"] = self._normalize_unified_status(
            payload.get("unified_status")
            or task.get("unified_status")
            or payload.get("status")
            or task.get("status")
        )
        incoming_status = str(payload.get("status") or task.get("status") or "").strip().lower()
        if incoming_status in RESEARCH_STATUS_LABELS:
            task["status"] = self._sanitize_status(incoming_status)
        else:
            task["status"] = self._legacy_status_from_unified(task["unified_status"])
        task["created_at"] = task.get("created_at") or now
        task["updated_at"] = now
        task["generated_query"] = self._compose_research_query(task)
        task["crawler_keywords"] = self._compose_crawler_keywords(task)
        task["crawler_defaults"] = {
            "keywords": task["crawler_keywords"],
            "max_notes": 20,
            "max_comments": 20,
            "start_page": 1,
            "crawler_type": "search",
            "login_type": "qrcode",
        }
        task["last_action"] = str(payload.get("last_action", "")).strip()
        if "crawler_job_id" in payload:
            raw_crawler_job_id = payload.get("crawler_job_id")
            normalized_crawler_job_id = str(raw_crawler_job_id).strip() if raw_crawler_job_id is not None else ""
            task["crawler_job_id"] = normalized_crawler_job_id or None
        if "analysis_run_id" in payload:
            raw_analysis_run_id = payload.get("analysis_run_id")
            normalized_analysis_run_id = str(raw_analysis_run_id).strip() if raw_analysis_run_id is not None else ""
            task["analysis_run_id"] = normalized_analysis_run_id or None
        if "report_job_id" in payload:
            raw_report_job_id = payload.get("report_job_id")
            normalized_report_job_id = str(raw_report_job_id).strip() if raw_report_job_id is not None else ""
            task["report_job_id"] = normalized_report_job_id or None
        return task

    def snapshot(self, limit: int = 12) -> Dict[str, Any]:
        with self._lock:
            return self._snapshot_locked(limit=limit)

    def upsert(self, payload: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
        with self._lock:
            store = self._load_locked()
            task_id = str(payload.get("task_id", "")).strip()
            existing_task = self._find_task_locked(task_id) if task_id else None
            task = self._build_task_record(payload, existing_task=existing_task)

            if existing_task is None:
                store["tasks"].append(task)
            else:
                existing_task.clear()
                existing_task.update(task)
                task = existing_task

            store["active_task_id"] = task["task_id"]
            store["tasks"] = sorted(
                store["tasks"],
                key=lambda item: item.get("updated_at") or item.get("created_at") or "",
                reverse=True,
            )[:30]
            self._save_locked()
            return self._serialize_task(task), self._snapshot_locked()

    def activate(self, task_id: str) -> Optional[Dict[str, Any]]:
        with self._lock:
            store = self._load_locked()
            task = self._find_task_locked(task_id)
            if not task:
                return None
            task["updated_at"] = datetime.now().isoformat()
            store["active_task_id"] = task_id
            self._save_locked()
            return self._snapshot_locked()

    def update_status(
        self,
        task_id: str,
        *,
        status: Optional[str] = None,
        unified_status: Optional[str] = None,
        last_action: Optional[str] = None,
        query: Optional[str] = None,
        crawler_job_id: Any = _UNSET,
        analysis_run_id: Any = _UNSET,
        report_job_id: Any = _UNSET,
    ) -> Optional[Dict[str, Any]]:
        with self._lock:
            task = self._find_task_locked(task_id)
            if not task:
                return None
            if status:
                raw_status = str(status).strip().lower()
                if raw_status in RESEARCH_STATUS_LABELS:
                    task["status"] = self._sanitize_status(raw_status)
                else:
                    task["status"] = self._legacy_status_from_unified(raw_status)
            if unified_status:
                task["unified_status"] = self._normalize_unified_status(unified_status)
            elif not task.get("unified_status"):
                task["unified_status"] = self._normalize_unified_status(status or task.get("status"))
            if last_action:
                task["last_action"] = str(last_action).strip()
            if query:
                task["generated_query"] = str(query).strip()
            if crawler_job_id is not _UNSET:
                normalized_crawler_job_id = str(crawler_job_id).strip() if crawler_job_id is not None else ""
                task["crawler_job_id"] = normalized_crawler_job_id or None
            if analysis_run_id is not _UNSET:
                normalized_analysis_run_id = str(analysis_run_id).strip() if analysis_run_id is not None else ""
                task["analysis_run_id"] = normalized_analysis_run_id or None
            if report_job_id is not _UNSET:
                normalized_report_job_id = str(report_job_id).strip() if report_job_id is not None else ""
                task["report_job_id"] = normalized_report_job_id or None
            task["updated_at"] = datetime.now().isoformat()
            self._save_locked()
            return self._serialize_task(task)

    def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:
        with self._lock:
            task = self._find_task_locked(task_id)
            return dict(task) if task else None


research_task_service = ResearchTaskStore(RESEARCH_TASKS_PATH)