repository.py 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541
  1. """热点内容 MySQL 仓储。"""
  2. from __future__ import annotations
  3. import hashlib
  4. import json
  5. from datetime import date, datetime, timedelta
  6. from typing import Any
  7. try:
  8. import pymysql
  9. from pymysql.cursors import DictCursor
  10. except ImportError: # pragma: no cover - runtime dependency check
  11. pymysql = None
  12. DictCursor = None
  13. from app.hot_content.exceptions import HotContentFlowError
  14. from app.hot_content.status import ExecutionStatus, PostprocessStatus
  15. from app.hot_content.timezone import SHANGHAI_TZ
  16. from app.hot_content.types import MysqlConfig
  17. def _json_dumps(data: Any) -> str:
  18. return json.dumps(data, ensure_ascii=False, separators=(",", ":"))
  19. def _nullable_bool(value: Any) -> int | None:
  20. if value is None:
  21. return None
  22. return 1 if value else 0
  23. def _nullable_str(value: Any) -> str | None:
  24. if value is None:
  25. return None
  26. text = str(value).strip()
  27. return text if text else None
  28. def _nullable_json_dumps(value: Any) -> str | None:
  29. if value is None:
  30. return None
  31. return _json_dumps(value)
  32. def _wxindex_word_record_row(payload: dict[str, Any]) -> tuple[Any, ...]:
  33. name = str(payload.get("name") or "").strip()
  34. analyze_ymd = str(payload.get("analyze_ymd") or "").strip()
  35. if not name or not analyze_ymd:
  36. raise HotContentFlowError("invalid wxindex word record payload")
  37. return (
  38. name,
  39. payload.get("meta_id"),
  40. analyze_ymd,
  41. payload.get("fetch_start_ymd"),
  42. payload.get("fetch_end_ymd"),
  43. payload.get("data_start_ymd"),
  44. payload.get("data_end_ymd"),
  45. payload.get("data_days"),
  46. _nullable_bool(payload.get("is_sustained_high")),
  47. _nullable_bool(payload.get("is_rising")),
  48. _nullable_bool(payload.get("is_spike")),
  49. payload.get("retain_reason"),
  50. _nullable_bool(payload.get("is_internal_demand_matched")),
  51. _nullable_str(payload.get("matched_demand")),
  52. payload.get("demand_cache_run_id"),
  53. _nullable_json_dumps(payload.get("internal_demand_match_json")),
  54. payload.get("senior_fit_score"),
  55. _nullable_json_dumps(payload.get("demand_senior_fit_json")),
  56. _nullable_bool(payload.get("is_final_retained")),
  57. payload.get("min_score"),
  58. payload.get("max_score"),
  59. payload.get("avg_score"),
  60. _nullable_json_dumps(payload.get("detail_json")),
  61. )
  62. _WXINDEX_WORD_RECORD_UPSERT_SQL = """
  63. INSERT INTO hot_content_wxindex_word_records (
  64. name,
  65. meta_id,
  66. analyze_ymd,
  67. fetch_start_ymd,
  68. fetch_end_ymd,
  69. data_start_ymd,
  70. data_end_ymd,
  71. data_days,
  72. is_sustained_high,
  73. is_rising,
  74. is_spike,
  75. retain_reason,
  76. is_internal_demand_matched,
  77. matched_demand,
  78. demand_cache_run_id,
  79. internal_demand_match_json,
  80. senior_fit_score,
  81. demand_senior_fit_json,
  82. is_final_retained,
  83. min_score,
  84. max_score,
  85. avg_score,
  86. detail_json
  87. )
  88. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  89. ON DUPLICATE KEY UPDATE
  90. meta_id = VALUES(meta_id),
  91. fetch_start_ymd = VALUES(fetch_start_ymd),
  92. fetch_end_ymd = VALUES(fetch_end_ymd),
  93. data_start_ymd = VALUES(data_start_ymd),
  94. data_end_ymd = VALUES(data_end_ymd),
  95. data_days = VALUES(data_days),
  96. is_sustained_high = VALUES(is_sustained_high),
  97. is_rising = VALUES(is_rising),
  98. is_spike = VALUES(is_spike),
  99. retain_reason = VALUES(retain_reason),
  100. is_internal_demand_matched = VALUES(is_internal_demand_matched),
  101. matched_demand = VALUES(matched_demand),
  102. demand_cache_run_id = VALUES(demand_cache_run_id),
  103. internal_demand_match_json = VALUES(internal_demand_match_json),
  104. senior_fit_score = VALUES(senior_fit_score),
  105. demand_senior_fit_json = VALUES(demand_senior_fit_json),
  106. is_final_retained = VALUES(is_final_retained),
  107. min_score = VALUES(min_score),
  108. max_score = VALUES(max_score),
  109. avg_score = VALUES(avg_score),
  110. detail_json = VALUES(detail_json)
  111. """
  112. _WXINDEX_WORD_RECORD_INIT_UPSERT_SQL = """
  113. INSERT INTO hot_content_wxindex_word_records (
  114. name,
  115. meta_id,
  116. analyze_ymd,
  117. fetch_start_ymd,
  118. fetch_end_ymd,
  119. data_start_ymd,
  120. data_end_ymd,
  121. data_days,
  122. is_sustained_high,
  123. is_rising,
  124. is_spike,
  125. retain_reason,
  126. is_internal_demand_matched,
  127. matched_demand,
  128. demand_cache_run_id,
  129. internal_demand_match_json,
  130. senior_fit_score,
  131. demand_senior_fit_json,
  132. is_final_retained,
  133. min_score,
  134. max_score,
  135. avg_score,
  136. detail_json
  137. )
  138. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  139. ON DUPLICATE KEY UPDATE
  140. meta_id = VALUES(meta_id),
  141. fetch_start_ymd = VALUES(fetch_start_ymd),
  142. fetch_end_ymd = VALUES(fetch_end_ymd),
  143. demand_cache_run_id = VALUES(demand_cache_run_id)
  144. """
  145. def _wxindex_word_stats_row(payload: dict[str, Any]) -> tuple[Any, ...]:
  146. name = str(payload.get("name") or "").strip()
  147. analyze_ymd = str(payload.get("analyze_ymd") or "").strip()
  148. if not name or not analyze_ymd:
  149. raise HotContentFlowError("invalid wxindex word stats payload")
  150. return (
  151. name,
  152. payload.get("meta_id"),
  153. analyze_ymd,
  154. payload.get("wxindex_word_record_id"),
  155. payload.get("retain_reason"),
  156. payload.get("senior_fit_score"),
  157. payload.get("data_start_ymd"),
  158. payload.get("data_end_ymd"),
  159. payload.get("data_days"),
  160. payload.get("min_score"),
  161. payload.get("max_score"),
  162. payload.get("avg_score"),
  163. _nullable_json_dumps(payload.get("detail_json")),
  164. )
  165. _WXINDEX_WORD_STATS_UPSERT_SQL = """
  166. INSERT INTO hot_content_wxindex_word_stats (
  167. name,
  168. meta_id,
  169. analyze_ymd,
  170. wxindex_word_record_id,
  171. retain_reason,
  172. senior_fit_score,
  173. data_start_ymd,
  174. data_end_ymd,
  175. data_days,
  176. min_score,
  177. max_score,
  178. avg_score,
  179. detail_json
  180. )
  181. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  182. ON DUPLICATE KEY UPDATE
  183. meta_id = VALUES(meta_id),
  184. wxindex_word_record_id = VALUES(wxindex_word_record_id),
  185. retain_reason = VALUES(retain_reason),
  186. senior_fit_score = VALUES(senior_fit_score),
  187. data_start_ymd = VALUES(data_start_ymd),
  188. data_end_ymd = VALUES(data_end_ymd),
  189. data_days = VALUES(data_days),
  190. min_score = VALUES(min_score),
  191. max_score = VALUES(max_score),
  192. avg_score = VALUES(avg_score),
  193. detail_json = VALUES(detail_json)
  194. """
  195. def _json_loads(value: Any) -> Any:
  196. if value is None:
  197. return None
  198. if isinstance(value, (dict, list)):
  199. return value
  200. if isinstance(value, (bytes, bytearray)):
  201. value = value.decode("utf-8")
  202. if isinstance(value, str):
  203. return json.loads(value)
  204. return value
  205. def _normalize_demand_names(demand_name_set: list[str]) -> list[str]:
  206. names: list[str] = []
  207. seen: set[str] = set()
  208. for item in demand_name_set:
  209. name = str(item).strip()
  210. if not name or name in seen:
  211. continue
  212. seen.add(name)
  213. names.append(name)
  214. return names
  215. def unique_title_key(source: str, title: str) -> str:
  216. return hashlib.sha256(f"{source}\n{title}".encode("utf-8")).hexdigest()
  217. class HotContentRepository:
  218. def __init__(self, config: MysqlConfig):
  219. if pymysql is None or DictCursor is None:
  220. raise HotContentFlowError("missing dependency: pip install pymysql")
  221. self.conn = pymysql.connect(
  222. host=config.host,
  223. port=config.port,
  224. user=config.user,
  225. password=config.password,
  226. database=config.database,
  227. charset=config.charset,
  228. autocommit=True,
  229. cursorclass=DictCursor,
  230. )
  231. def close(self) -> None:
  232. self.conn.close()
  233. def upsert_record(self, *, source: str, title: str, rank: int | None) -> dict[str, Any]:
  234. key = unique_title_key(source, title)
  235. sql = """
  236. INSERT INTO hot_content_records (
  237. unique_key, source, title, hot_rank, execution_status, created_at, updated_at
  238. )
  239. VALUES (%s, %s, %s, %s, %s, NOW(), NOW())
  240. ON DUPLICATE KEY UPDATE
  241. id=LAST_INSERT_ID(id),
  242. hot_rank=VALUES(hot_rank),
  243. updated_at=NOW()
  244. """
  245. with self.conn.cursor() as cursor:
  246. cursor.execute(
  247. sql,
  248. (
  249. key,
  250. source,
  251. title,
  252. rank,
  253. ExecutionStatus.HOT_SAVED,
  254. ),
  255. )
  256. record_id = int(cursor.lastrowid)
  257. cursor.execute(
  258. """
  259. SELECT
  260. id,
  261. unique_key,
  262. execution_status,
  263. article_title,
  264. article_body,
  265. article_url,
  266. decode_request_result IS NOT NULL AS has_decode_request,
  267. contribution_points_json IS NOT NULL AS has_contribution_points
  268. FROM hot_content_records
  269. WHERE id = %s
  270. """,
  271. (record_id,),
  272. )
  273. row = cursor.fetchone()
  274. if not row:
  275. raise HotContentFlowError(f"missing hot_content_records id={record_id}")
  276. return {
  277. "id": int(row["id"]),
  278. "unique_key": str(row["unique_key"]),
  279. "execution_status": int(row["execution_status"]),
  280. "article_title": row.get("article_title"),
  281. "article_body": row.get("article_body"),
  282. "article_url": row.get("article_url"),
  283. "has_decode_request": bool(row.get("has_decode_request")),
  284. "has_contribution_points": bool(row.get("has_contribution_points")),
  285. }
  286. def update_status(
  287. self,
  288. *,
  289. record_id: int,
  290. status: int,
  291. error_message: str | None = None,
  292. ) -> None:
  293. sql = """
  294. UPDATE hot_content_records
  295. SET execution_status=%s, error_reason=%s, updated_at=NOW()
  296. WHERE id=%s
  297. """
  298. with self.conn.cursor() as cursor:
  299. cursor.execute(sql, (status, error_message, record_id))
  300. def update_article(
  301. self,
  302. *,
  303. record_id: int,
  304. article_title: str,
  305. article_body: str,
  306. url: str,
  307. ) -> None:
  308. sql = """
  309. UPDATE hot_content_records
  310. SET article_title=%s,
  311. article_body=%s,
  312. article_url=%s,
  313. execution_status=%s,
  314. error_reason=NULL,
  315. updated_at=NOW()
  316. WHERE id=%s
  317. """
  318. with self.conn.cursor() as cursor:
  319. cursor.execute(
  320. sql,
  321. (
  322. article_title,
  323. article_body,
  324. url,
  325. ExecutionStatus.CONTENT_OK,
  326. record_id,
  327. ),
  328. )
  329. def mark_no_valid_content(
  330. self,
  331. *,
  332. record_id: int,
  333. reason: str,
  334. ) -> None:
  335. """搜不到文章或缺标题/正文:仅更新 execution_status + error_reason,不动分类字段。"""
  336. sql = """
  337. UPDATE hot_content_records
  338. SET execution_status=%s,
  339. error_reason=%s,
  340. updated_at=NOW()
  341. WHERE id=%s
  342. """
  343. with self.conn.cursor() as cursor:
  344. cursor.execute(
  345. sql,
  346. (
  347. ExecutionStatus.NO_VALID_CONTENT,
  348. str(reason or "no valid content").strip(),
  349. record_id,
  350. ),
  351. )
  352. def update_category_filter_result(
  353. self,
  354. *,
  355. record_id: int,
  356. passed: bool,
  357. result_json: dict[str, Any],
  358. ) -> None:
  359. self._ensure_category_filter_columns()
  360. status = (
  361. ExecutionStatus.CATEGORY_FILTER_PASSED
  362. if passed
  363. else ExecutionStatus.CATEGORY_FILTER_REJECTED
  364. )
  365. reason = str(result_json.get("reason") or "").strip()
  366. error_message = None if passed else (reason or "category filter rejected")
  367. sql = """
  368. UPDATE hot_content_records
  369. SET execution_status=%s,
  370. category_filter_passed=%s,
  371. category_filter_reason=%s,
  372. category_filter_json=%s,
  373. error_reason=%s,
  374. updated_at=NOW()
  375. WHERE id=%s
  376. """
  377. with self.conn.cursor() as cursor:
  378. cursor.execute(
  379. sql,
  380. (
  381. status,
  382. 1 if passed else 0,
  383. reason or None,
  384. _json_dumps(result_json),
  385. error_message,
  386. record_id,
  387. ),
  388. )
  389. def get_record_for_category_filter(self, record_id: int) -> dict[str, Any] | None:
  390. self._ensure_category_filter_columns()
  391. sql = """
  392. SELECT
  393. id,
  394. source,
  395. title,
  396. article_title,
  397. article_body,
  398. article_url,
  399. execution_status,
  400. category_filter_passed,
  401. category_filter_reason,
  402. category_filter_json
  403. FROM hot_content_records
  404. WHERE id = %s
  405. LIMIT 1
  406. """
  407. with self.conn.cursor() as cursor:
  408. cursor.execute(sql, (record_id,))
  409. row = cursor.fetchone()
  410. if not row:
  411. return None
  412. category_filter_json = _json_loads(row.get("category_filter_json"))
  413. passed_raw = row.get("category_filter_passed")
  414. passed: bool | None
  415. if passed_raw is None:
  416. passed = None
  417. else:
  418. passed = bool(int(passed_raw))
  419. return {
  420. "id": int(row["id"]),
  421. "source": str(row.get("source") or ""),
  422. "title": str(row.get("title") or ""),
  423. "article_title": str(row.get("article_title") or ""),
  424. "article_body": str(row.get("article_body") or ""),
  425. "article_url": str(row.get("article_url") or ""),
  426. "execution_status": int(row.get("execution_status") or 0),
  427. "category_filter_passed": passed,
  428. "category_filter_reason": str(row.get("category_filter_reason") or ""),
  429. "category_filter_json": (
  430. category_filter_json if isinstance(category_filter_json, dict) else {}
  431. ),
  432. }
  433. def get_category_filter_status(self, record_id: int) -> dict[str, Any] | None:
  434. record = self.get_record_for_category_filter(record_id)
  435. if not record:
  436. return None
  437. matched_category = None
  438. category_filter_json = record.get("category_filter_json") or {}
  439. if isinstance(category_filter_json, dict):
  440. matched_category = category_filter_json.get("matched_category")
  441. return {
  442. "id": record["id"],
  443. "passed": record["category_filter_passed"],
  444. "reason": record["category_filter_reason"],
  445. "matched_category": matched_category,
  446. "execution_status": record["execution_status"],
  447. }
  448. def update_decode_result(
  449. self,
  450. *,
  451. record_id: int,
  452. status: int,
  453. request_json: dict[str, Any],
  454. response_json: dict[str, Any] | None,
  455. error_message: str | None = None,
  456. ) -> None:
  457. decode_request_result = {
  458. "request": request_json,
  459. "response": response_json,
  460. }
  461. sql = """
  462. UPDATE hot_content_records
  463. SET decode_request_result=%s,
  464. execution_status=%s,
  465. error_reason=%s,
  466. updated_at=NOW()
  467. WHERE id=%s
  468. """
  469. with self.conn.cursor() as cursor:
  470. cursor.execute(
  471. sql,
  472. (
  473. _json_dumps(decode_request_result),
  474. status,
  475. error_message,
  476. record_id,
  477. ),
  478. )
  479. def list_decode_result_candidates(self, *, limit: int) -> list[dict[str, Any]]:
  480. sql = """
  481. SELECT id, unique_key
  482. FROM hot_content_records
  483. WHERE execution_status IN (%s, %s, %s)
  484. AND contribution_points_json IS NULL
  485. ORDER BY updated_at ASC, id ASC
  486. LIMIT %s
  487. """
  488. with self.conn.cursor() as cursor:
  489. cursor.execute(
  490. sql,
  491. (
  492. ExecutionStatus.DECODE_SUBMITTED,
  493. ExecutionStatus.DECODE_SUCCESS,
  494. ExecutionStatus.DECODE_PENDING,
  495. limit,
  496. ),
  497. )
  498. rows = cursor.fetchall()
  499. return [
  500. {
  501. "id": int(row["id"]),
  502. "unique_key": str(row["unique_key"]),
  503. }
  504. for row in rows
  505. ]
  506. def save_decode_result_export(
  507. self,
  508. *,
  509. record_id: int,
  510. decode_result_json: dict[str, Any],
  511. contribution_points_json: dict[str, Any],
  512. ) -> None:
  513. sql = """
  514. UPDATE hot_content_records
  515. SET decode_result_json=%s,
  516. contribution_points_json=%s,
  517. execution_status=%s,
  518. error_reason=NULL,
  519. updated_at=NOW()
  520. WHERE id=%s
  521. """
  522. with self.conn.cursor() as cursor:
  523. cursor.execute(
  524. sql,
  525. (
  526. _json_dumps(decode_result_json),
  527. _json_dumps(contribution_points_json),
  528. ExecutionStatus.CONTRIBUTION_EXTRACTED,
  529. record_id,
  530. ),
  531. )
  532. def get_demand_cache_by_hour(self, *, cache_hour: datetime) -> dict[str, Any] | None:
  533. sql = """
  534. SELECT
  535. id,
  536. cache_hour,
  537. source_table,
  538. partition_dt,
  539. demand_name_set_json,
  540. item_count,
  541. updated_at
  542. FROM demand_pool_hourly_cache
  543. WHERE cache_hour=%s
  544. LIMIT 1
  545. """
  546. with self.conn.cursor() as cursor:
  547. cursor.execute(sql, (cache_hour,))
  548. row = cursor.fetchone()
  549. if not row:
  550. return None
  551. demand_name_set = _json_loads(row.get("demand_name_set_json")) or []
  552. if not isinstance(demand_name_set, list):
  553. demand_name_set = []
  554. return {
  555. "id": int(row["id"]),
  556. "cache_hour": row.get("cache_hour"),
  557. "source_table": str(row["source_table"]),
  558. "partition_dt": row.get("partition_dt"),
  559. "demand_name_set": [
  560. str(name).strip()
  561. for name in demand_name_set
  562. if str(name).strip()
  563. ],
  564. "item_count": int(row.get("item_count") or 0),
  565. "updated_at": row.get("updated_at"),
  566. }
  567. def save_demand_cache_set(
  568. self,
  569. *,
  570. cache_hour: datetime,
  571. source_table: str,
  572. partition_dt: str | None,
  573. excluded_strategy: str,
  574. top_n: int,
  575. demand_name_set: list[str],
  576. ) -> int:
  577. sql = """
  578. INSERT INTO demand_pool_hourly_cache (
  579. cache_hour,
  580. source_table,
  581. partition_dt,
  582. excluded_strategy,
  583. top_n,
  584. demand_name_set_json,
  585. item_count,
  586. created_at,
  587. updated_at
  588. )
  589. VALUES (%s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
  590. ON DUPLICATE KEY UPDATE
  591. id=LAST_INSERT_ID(id),
  592. source_table=VALUES(source_table),
  593. partition_dt=VALUES(partition_dt),
  594. excluded_strategy=VALUES(excluded_strategy),
  595. top_n=VALUES(top_n),
  596. demand_name_set_json=VALUES(demand_name_set_json),
  597. item_count=VALUES(item_count),
  598. updated_at=NOW()
  599. """
  600. normalized_names = _normalize_demand_names(demand_name_set)
  601. with self.conn.cursor() as cursor:
  602. cursor.execute(
  603. sql,
  604. (
  605. cache_hour,
  606. source_table,
  607. partition_dt,
  608. excluded_strategy,
  609. top_n,
  610. _json_dumps(normalized_names),
  611. len(normalized_names),
  612. ),
  613. )
  614. return int(cursor.lastrowid)
  615. def list_postprocess_candidates(self, *, limit: int) -> list[dict[str, Any]]:
  616. sql = """
  617. SELECT
  618. id,
  619. unique_key,
  620. source,
  621. title,
  622. created_at,
  623. article_title,
  624. article_body,
  625. demand_cache_run_id,
  626. postprocess_status,
  627. decode_result_json,
  628. contribution_points_json,
  629. contribution_demand_match_json,
  630. wxindex_trend_json,
  631. demand_event_sense_json,
  632. demand_senior_fit_json
  633. FROM hot_content_records
  634. WHERE contribution_points_json IS NOT NULL
  635. AND postprocess_status IN (%s, %s, %s, %s)
  636. ORDER BY updated_at ASC, id ASC
  637. LIMIT %s
  638. """
  639. with self.conn.cursor() as cursor:
  640. cursor.execute(
  641. sql,
  642. (
  643. PostprocessStatus.PENDING,
  644. PostprocessStatus.DEMAND_MATCHED,
  645. PostprocessStatus.WXINDEX_DONE,
  646. PostprocessStatus.FAILED,
  647. limit,
  648. ),
  649. )
  650. rows = cursor.fetchall()
  651. return [
  652. {
  653. "id": int(row["id"]),
  654. "unique_key": str(row["unique_key"]),
  655. "source": str(row.get("source") or ""),
  656. "title": str(row.get("title") or ""),
  657. "created_at": row.get("created_at"),
  658. "article_title": row.get("article_title"),
  659. "article_body": row.get("article_body"),
  660. "demand_cache_run_id": row.get("demand_cache_run_id"),
  661. "postprocess_status": int(row.get("postprocess_status") or 0),
  662. "decode_result_json": _json_loads(row.get("decode_result_json")),
  663. "contribution_points_json": _json_loads(row.get("contribution_points_json")),
  664. "contribution_demand_match_json": _json_loads(
  665. row.get("contribution_demand_match_json")
  666. ),
  667. "wxindex_trend_json": _json_loads(row.get("wxindex_trend_json")),
  668. "demand_event_sense_json": _json_loads(
  669. row.get("demand_event_sense_json")
  670. ),
  671. "demand_senior_fit_json": _json_loads(row.get("demand_senior_fit_json")),
  672. }
  673. for row in rows
  674. ]
  675. def save_contribution_demand_match(
  676. self,
  677. *,
  678. record_id: int,
  679. demand_cache_run_id: int,
  680. match_json: dict[str, Any],
  681. ) -> None:
  682. sql = """
  683. UPDATE hot_content_records
  684. SET demand_cache_run_id=%s,
  685. contribution_demand_match_json=%s,
  686. postprocess_status=%s,
  687. postprocess_error_reason=NULL,
  688. updated_at=NOW()
  689. WHERE id=%s
  690. """
  691. with self.conn.cursor() as cursor:
  692. cursor.execute(
  693. sql,
  694. (
  695. demand_cache_run_id,
  696. _json_dumps(match_json),
  697. PostprocessStatus.DEMAND_MATCHED,
  698. record_id,
  699. ),
  700. )
  701. def save_wxindex_trend(
  702. self,
  703. *,
  704. record_id: int,
  705. trend_json: dict[str, Any],
  706. ) -> None:
  707. sql = """
  708. UPDATE hot_content_records
  709. SET wxindex_trend_json=%s,
  710. postprocess_status=%s,
  711. postprocess_error_reason=NULL,
  712. updated_at=NOW()
  713. WHERE id=%s
  714. """
  715. with self.conn.cursor() as cursor:
  716. cursor.execute(
  717. sql,
  718. (
  719. _json_dumps(trend_json),
  720. PostprocessStatus.WXINDEX_DONE,
  721. record_id,
  722. ),
  723. )
  724. def save_demand_quality(
  725. self,
  726. *,
  727. record_id: int,
  728. event_sense_json: dict[str, Any],
  729. senior_fit_json: dict[str, Any],
  730. update_status: bool = True,
  731. ) -> None:
  732. self._ensure_record_quality_columns()
  733. if update_status:
  734. sql = """
  735. UPDATE hot_content_records
  736. SET demand_event_sense_json=%s,
  737. demand_senior_fit_json=%s,
  738. postprocess_status=%s,
  739. postprocess_error_reason=NULL,
  740. updated_at=NOW()
  741. WHERE id=%s
  742. """
  743. params = (
  744. _json_dumps(event_sense_json),
  745. _json_dumps(senior_fit_json),
  746. PostprocessStatus.QUALITY_DONE,
  747. record_id,
  748. )
  749. else:
  750. sql = """
  751. UPDATE hot_content_records
  752. SET demand_event_sense_json=%s,
  753. demand_senior_fit_json=%s,
  754. updated_at=NOW()
  755. WHERE id=%s
  756. """
  757. params = (
  758. _json_dumps(event_sense_json),
  759. _json_dumps(senior_fit_json),
  760. record_id,
  761. )
  762. with self.conn.cursor() as cursor:
  763. cursor.execute(sql, params)
  764. def update_postprocess_status(
  765. self,
  766. *,
  767. record_id: int,
  768. status: int,
  769. error_message: str | None = None,
  770. ) -> None:
  771. sql = """
  772. UPDATE hot_content_records
  773. SET postprocess_status=%s,
  774. postprocess_error_reason=%s,
  775. updated_at=NOW()
  776. WHERE id=%s
  777. """
  778. with self.conn.cursor() as cursor:
  779. cursor.execute(sql, (status, error_message, record_id))
  780. def replace_demand_export_rows(
  781. self,
  782. *,
  783. record_id: int,
  784. source: str,
  785. hot_title: str,
  786. article_title: str,
  787. rows: list[dict[str, Any]],
  788. ) -> None:
  789. self._ensure_demand_export_table()
  790. delete_sql = "DELETE FROM hot_content_demand_exports WHERE record_id=%s"
  791. insert_sql = """
  792. INSERT INTO hot_content_demand_exports (
  793. record_id,
  794. source,
  795. hot_title,
  796. article_title,
  797. item_type,
  798. item_text,
  799. point_category,
  800. matched_demand,
  801. contribution_score,
  802. wxindex_keyword,
  803. all_hot_keywords,
  804. wxindex_latest_score,
  805. wxindex_trend,
  806. is_as_demand,
  807. event_sense_score,
  808. senior_fit_score,
  809. created_at,
  810. updated_at
  811. )
  812. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
  813. """
  814. with self.conn.cursor() as cursor:
  815. cursor.execute(delete_sql, (record_id,))
  816. insert_rows = [
  817. (
  818. record_id,
  819. source,
  820. hot_title,
  821. article_title,
  822. str(item.get("item_type") or ""),
  823. str(item.get("item_text") or ""),
  824. str(item.get("point_category") or ""),
  825. str(item.get("matched_demand") or ""),
  826. item.get("contribution_score"),
  827. str(item.get("wxindex_keyword") or ""),
  828. str(item.get("all_hot_keywords") or ""),
  829. float(item.get("wxindex_latest_score") or 0),
  830. str(item.get("wxindex_trend") or ""),
  831. int(item.get("is_as_demand") or 0),
  832. item.get("event_sense_score"),
  833. item.get("senior_fit_score"),
  834. )
  835. for item in rows
  836. if str(item.get("item_type") or "").strip()
  837. and str(item.get("item_text") or "").strip()
  838. ]
  839. if insert_rows:
  840. cursor.executemany(insert_sql, insert_rows)
  841. def list_odps_sync_records(self) -> list[dict[str, Any]]:
  842. """读取当天完成 postprocess 且质量判断完成的记录,供 ODPS 同步。"""
  843. self._ensure_record_quality_columns()
  844. today_start = datetime.now(SHANGHAI_TZ).replace(
  845. hour=0,
  846. minute=0,
  847. second=0,
  848. microsecond=0,
  849. tzinfo=None,
  850. )
  851. today_end = today_start + timedelta(days=1)
  852. sql = """
  853. SELECT
  854. id,
  855. contribution_points_json,
  856. contribution_demand_match_json,
  857. wxindex_trend_json,
  858. demand_event_sense_json,
  859. demand_senior_fit_json
  860. FROM hot_content_records
  861. WHERE updated_at >= %s
  862. AND updated_at < %s
  863. AND postprocess_status = %s
  864. AND contribution_demand_match_json IS NOT NULL
  865. AND TRIM(CAST(contribution_demand_match_json AS CHAR)) <> ''
  866. ORDER BY id ASC
  867. """
  868. with self.conn.cursor() as cursor:
  869. cursor.execute(
  870. sql,
  871. (today_start, today_end, PostprocessStatus.QUALITY_DONE),
  872. )
  873. rows = cursor.fetchall()
  874. records: list[dict[str, Any]] = []
  875. for row in rows:
  876. records.append(
  877. {
  878. "id": int(row["id"]),
  879. "contribution_points_json": _json_loads(
  880. row.get("contribution_points_json")
  881. ),
  882. "contribution_demand_match_json": _json_loads(
  883. row.get("contribution_demand_match_json")
  884. ),
  885. "wxindex_trend_json": _json_loads(row.get("wxindex_trend_json")),
  886. "demand_event_sense_json": _json_loads(
  887. row.get("demand_event_sense_json")
  888. ),
  889. "demand_senior_fit_json": _json_loads(
  890. row.get("demand_senior_fit_json")
  891. ),
  892. }
  893. )
  894. return records
  895. def list_demand_export_groups(self) -> list[dict[str, Any]]:
  896. """读取主表当天创建的 record 对应导出分组,仅供 ODPS 当天分区同步(不跨天)。"""
  897. self._ensure_demand_export_table()
  898. today_start = datetime.now(SHANGHAI_TZ).replace(
  899. hour=0,
  900. minute=0,
  901. second=0,
  902. microsecond=0,
  903. tzinfo=None,
  904. )
  905. today_end = today_start + timedelta(days=1)
  906. sql = """
  907. SELECT
  908. e.record_id,
  909. e.item_type,
  910. e.item_text,
  911. e.point_category,
  912. e.matched_demand,
  913. e.wxindex_latest_score
  914. FROM hot_content_demand_exports e
  915. INNER JOIN hot_content_records r ON r.id = e.record_id
  916. WHERE r.created_at >= %s
  917. AND r.created_at < %s
  918. ORDER BY e.record_id ASC, e.id ASC
  919. """
  920. with self.conn.cursor() as cursor:
  921. cursor.execute(sql, (today_start, today_end))
  922. rows = cursor.fetchall()
  923. grouped: dict[int, list[dict[str, Any]]] = {}
  924. for row in rows:
  925. record_id = int(row["record_id"])
  926. grouped.setdefault(record_id, []).append(
  927. {
  928. "item_type": str(row.get("item_type") or ""),
  929. "item_text": str(row.get("item_text") or ""),
  930. "point_category": str(row.get("point_category") or ""),
  931. "matched_demand": str(row.get("matched_demand") or ""),
  932. "wxindex_latest_score": float(row.get("wxindex_latest_score") or 0),
  933. }
  934. )
  935. return [
  936. {"record_id": record_id, "export_rows": export_rows}
  937. for record_id, export_rows in grouped.items()
  938. ]
  939. def _ensure_demand_export_table(self) -> None:
  940. sql = """
  941. CREATE TABLE IF NOT EXISTS hot_content_demand_exports (
  942. id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  943. record_id BIGINT UNSIGNED NOT NULL,
  944. source VARCHAR(64) NOT NULL DEFAULT '',
  945. hot_title VARCHAR(1024) NOT NULL DEFAULT '',
  946. article_title VARCHAR(1024) NOT NULL DEFAULT '',
  947. item_type VARCHAR(32) NOT NULL COMMENT '元素/短语',
  948. item_text VARCHAR(1024) NOT NULL,
  949. point_category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '点类型:灵感点/目的点/关键点',
  950. matched_demand VARCHAR(1024) NOT NULL DEFAULT '' COMMENT '匹配到的需求',
  951. contribution_score DOUBLE NULL COMMENT '贡献分,仅元素有值',
  952. wxindex_keyword VARCHAR(1024) NOT NULL DEFAULT '' COMMENT '获取微信指数的元素',
  953. all_hot_keywords VARCHAR(1024) NOT NULL DEFAULT '' COMMENT '全部热点词',
  954. wxindex_latest_score DOUBLE NOT NULL DEFAULT 0,
  955. wxindex_trend VARCHAR(32) NOT NULL DEFAULT '' COMMENT '微信指数趋势',
  956. is_as_demand TINYINT NOT NULL DEFAULT 0 COMMENT '是否作为需求:0否 1是',
  957. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  958. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  959. PRIMARY KEY (id),
  960. KEY idx_record_id (record_id),
  961. KEY idx_source_type (source, item_type)
  962. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  963. """
  964. with self.conn.cursor() as cursor:
  965. cursor.execute(sql)
  966. self._ensure_demand_export_column(
  967. cursor,
  968. "matched_demand",
  969. """
  970. ALTER TABLE hot_content_demand_exports
  971. ADD COLUMN matched_demand VARCHAR(1024) NOT NULL DEFAULT ''
  972. COMMENT '匹配到的需求'
  973. AFTER item_text
  974. """,
  975. )
  976. self._ensure_demand_export_column(
  977. cursor,
  978. "point_category",
  979. """
  980. ALTER TABLE hot_content_demand_exports
  981. ADD COLUMN point_category VARCHAR(32) NOT NULL DEFAULT ''
  982. COMMENT '点类型:灵感点/目的点/关键点'
  983. AFTER item_text
  984. """,
  985. )
  986. self._ensure_demand_export_column(
  987. cursor,
  988. "contribution_score",
  989. """
  990. ALTER TABLE hot_content_demand_exports
  991. ADD COLUMN contribution_score DOUBLE NULL
  992. COMMENT '贡献分,仅词有值'
  993. AFTER matched_demand
  994. """,
  995. )
  996. self._ensure_demand_export_column(
  997. cursor,
  998. "wxindex_trend",
  999. """
  1000. ALTER TABLE hot_content_demand_exports
  1001. ADD COLUMN wxindex_trend VARCHAR(32) NOT NULL DEFAULT ''
  1002. COMMENT '微信指数趋势'
  1003. AFTER wxindex_latest_score
  1004. """,
  1005. )
  1006. self._ensure_demand_export_column(
  1007. cursor,
  1008. "wxindex_keyword",
  1009. """
  1010. ALTER TABLE hot_content_demand_exports
  1011. ADD COLUMN wxindex_keyword VARCHAR(1024) NOT NULL DEFAULT ''
  1012. COMMENT '获取微信指数的词'
  1013. AFTER contribution_score
  1014. """,
  1015. )
  1016. self._ensure_demand_export_column(
  1017. cursor,
  1018. "all_hot_keywords",
  1019. """
  1020. ALTER TABLE hot_content_demand_exports
  1021. ADD COLUMN all_hot_keywords VARCHAR(1024) NOT NULL DEFAULT ''
  1022. COMMENT '全部热点词'
  1023. AFTER wxindex_keyword
  1024. """,
  1025. )
  1026. self._ensure_demand_export_column(
  1027. cursor,
  1028. "is_as_demand",
  1029. """
  1030. ALTER TABLE hot_content_demand_exports
  1031. ADD COLUMN is_as_demand TINYINT NOT NULL DEFAULT 0
  1032. COMMENT '是否作为需求:0否 1是'
  1033. AFTER wxindex_trend
  1034. """,
  1035. )
  1036. self._ensure_demand_export_column(
  1037. cursor,
  1038. "event_sense_score",
  1039. """
  1040. ALTER TABLE hot_content_demand_exports
  1041. ADD COLUMN event_sense_score DOUBLE NULL
  1042. COMMENT '事件性得分 0-10'
  1043. AFTER is_as_demand
  1044. """,
  1045. )
  1046. self._ensure_demand_export_column(
  1047. cursor,
  1048. "senior_fit_score",
  1049. """
  1050. ALTER TABLE hot_content_demand_exports
  1051. ADD COLUMN senior_fit_score DOUBLE NULL
  1052. COMMENT '老年性得分 0-10'
  1053. AFTER event_sense_score
  1054. """,
  1055. )
  1056. def _ensure_record_quality_columns(self) -> None:
  1057. with self.conn.cursor() as cursor:
  1058. for column_name, alter_sql in (
  1059. (
  1060. "demand_event_sense_json",
  1061. """
  1062. ALTER TABLE hot_content_records
  1063. ADD COLUMN demand_event_sense_json JSON NULL
  1064. COMMENT '需求事件性 LLM 评分结果'
  1065. AFTER wxindex_trend_json
  1066. """,
  1067. ),
  1068. (
  1069. "demand_senior_fit_json",
  1070. """
  1071. ALTER TABLE hot_content_records
  1072. ADD COLUMN demand_senior_fit_json JSON NULL
  1073. COMMENT '需求老年性 LLM 评分结果'
  1074. AFTER demand_event_sense_json
  1075. """,
  1076. ),
  1077. ):
  1078. cursor.execute(
  1079. """
  1080. SELECT COUNT(*) AS cnt
  1081. FROM information_schema.COLUMNS
  1082. WHERE TABLE_SCHEMA = DATABASE()
  1083. AND TABLE_NAME = 'hot_content_records'
  1084. AND COLUMN_NAME = %s
  1085. """,
  1086. (column_name,),
  1087. )
  1088. if int((cursor.fetchone() or {}).get("cnt") or 0) == 0:
  1089. cursor.execute(alter_sql)
  1090. def _ensure_category_filter_columns(self) -> None:
  1091. with self.conn.cursor() as cursor:
  1092. for column_name, alter_sql in (
  1093. (
  1094. "category_filter_json",
  1095. """
  1096. ALTER TABLE hot_content_records
  1097. ADD COLUMN category_filter_json JSON NULL
  1098. COMMENT '老年人兴趣分类筛选 LLM 结果'
  1099. AFTER article_url
  1100. """,
  1101. ),
  1102. (
  1103. "category_filter_passed",
  1104. """
  1105. ALTER TABLE hot_content_records
  1106. ADD COLUMN category_filter_passed TINYINT NULL
  1107. COMMENT '分类筛选是否通过:1通过 0不通过 NULL未筛选'
  1108. AFTER category_filter_json
  1109. """,
  1110. ),
  1111. (
  1112. "category_filter_reason",
  1113. """
  1114. ALTER TABLE hot_content_records
  1115. ADD COLUMN category_filter_reason TEXT NULL
  1116. COMMENT '分类筛选原因'
  1117. AFTER category_filter_passed
  1118. """,
  1119. ),
  1120. ):
  1121. cursor.execute(
  1122. """
  1123. SELECT COUNT(*) AS cnt
  1124. FROM information_schema.COLUMNS
  1125. WHERE TABLE_SCHEMA = DATABASE()
  1126. AND TABLE_NAME = 'hot_content_records'
  1127. AND COLUMN_NAME = %s
  1128. """,
  1129. (column_name,),
  1130. )
  1131. if int((cursor.fetchone() or {}).get("cnt") or 0) == 0:
  1132. cursor.execute(alter_sql)
  1133. def _ensure_demand_export_column(
  1134. self,
  1135. cursor: Any,
  1136. column_name: str,
  1137. alter_sql: str,
  1138. ) -> None:
  1139. cursor.execute(
  1140. """
  1141. SELECT COUNT(*) AS cnt
  1142. FROM information_schema.COLUMNS
  1143. WHERE TABLE_SCHEMA = DATABASE()
  1144. AND TABLE_NAME = 'hot_content_demand_exports'
  1145. AND COLUMN_NAME = %s
  1146. """,
  1147. (column_name,),
  1148. )
  1149. if int((cursor.fetchone() or {}).get("cnt") or 0) == 0:
  1150. cursor.execute(alter_sql)
  1151. def list_synced_odps_demand_ids(
  1152. self,
  1153. *,
  1154. partition_dt: str,
  1155. ) -> set[str]:
  1156. """返回 hot_content_odps_sync_log 中指定分区日已有的 demand_id(跨流程去重用)。"""
  1157. normalized_partition_dt = str(partition_dt or "").strip()
  1158. if not normalized_partition_dt:
  1159. return set()
  1160. self._ensure_odps_sync_log_table()
  1161. sql = """
  1162. SELECT demand_id
  1163. FROM hot_content_odps_sync_log
  1164. WHERE partition_dt = %s
  1165. """
  1166. with self.conn.cursor() as cursor:
  1167. cursor.execute(sql, (normalized_partition_dt,))
  1168. rows = cursor.fetchall()
  1169. return {
  1170. str(row.get("demand_id") or "").strip()
  1171. for row in rows
  1172. if str(row.get("demand_id") or "").strip()
  1173. }
  1174. def count_odps_sync_log_rows(self, *, partition_dt: str) -> int:
  1175. """统计 hot_content_odps_sync_log 指定分区日已写入条数(供日限额计算)。"""
  1176. normalized_partition_dt = str(partition_dt or "").strip()
  1177. if not normalized_partition_dt:
  1178. return 0
  1179. self._ensure_odps_sync_log_table()
  1180. sql = """
  1181. SELECT COUNT(*) AS cnt
  1182. FROM hot_content_odps_sync_log
  1183. WHERE partition_dt = %s
  1184. """
  1185. with self.conn.cursor() as cursor:
  1186. cursor.execute(sql, (normalized_partition_dt,))
  1187. row = cursor.fetchone() or {}
  1188. return int(row.get("cnt") or 0)
  1189. def save_odps_sync_logs(self, rows: list[dict[str, Any]]) -> int:
  1190. if not rows:
  1191. return 0
  1192. self._ensure_odps_sync_log_table()
  1193. sql = """
  1194. INSERT INTO hot_content_odps_sync_log (
  1195. partition_dt,
  1196. strategy,
  1197. demand_id,
  1198. demand_name,
  1199. demand_type,
  1200. record_id,
  1201. weight
  1202. )
  1203. VALUES (%s, %s, %s, %s, %s, %s, %s)
  1204. ON DUPLICATE KEY UPDATE
  1205. demand_name = VALUES(demand_name),
  1206. demand_type = VALUES(demand_type),
  1207. record_id = VALUES(record_id),
  1208. weight = VALUES(weight),
  1209. synced_at = CURRENT_TIMESTAMP
  1210. """
  1211. insert_rows = [
  1212. (
  1213. str(item.get("partition_dt") or ""),
  1214. str(item.get("strategy") or ""),
  1215. str(item.get("demand_id") or ""),
  1216. str(item.get("demand_name") or ""),
  1217. str(item.get("demand_type") or ""),
  1218. int(item.get("record_id") or 0),
  1219. float(item["weight"]) if item.get("weight") is not None else None,
  1220. )
  1221. for item in rows
  1222. if str(item.get("demand_id") or "").strip()
  1223. ]
  1224. with self.conn.cursor() as cursor:
  1225. cursor.executemany(sql, insert_rows)
  1226. return len(insert_rows)
  1227. def _ensure_odps_sync_log_weight_column(self, cursor: Any) -> None:
  1228. cursor.execute(
  1229. """
  1230. SELECT COUNT(*) AS cnt
  1231. FROM information_schema.COLUMNS
  1232. WHERE TABLE_SCHEMA = DATABASE()
  1233. AND TABLE_NAME = 'hot_content_odps_sync_log'
  1234. AND COLUMN_NAME = 'weight'
  1235. """,
  1236. )
  1237. if int((cursor.fetchone() or {}).get("cnt") or 0) == 0:
  1238. cursor.execute(
  1239. """
  1240. ALTER TABLE hot_content_odps_sync_log
  1241. ADD COLUMN weight DOUBLE NULL DEFAULT NULL
  1242. COMMENT 'ODPS 需求权重(记录 wxindex 最高分 / 1000000)'
  1243. AFTER record_id
  1244. """
  1245. )
  1246. def list_wxindex_word_scores(self, name: str) -> list[dict[str, Any]]:
  1247. word = str(name or "").strip()
  1248. if not word:
  1249. return []
  1250. self._ensure_wxindex_words_table()
  1251. sql = """
  1252. SELECT dt, total_score
  1253. FROM hot_content_wxindex_words
  1254. WHERE name = %s
  1255. ORDER BY dt ASC
  1256. """
  1257. with self.conn.cursor() as cursor:
  1258. cursor.execute(sql, (word,))
  1259. rows = cursor.fetchall()
  1260. scores: list[dict[str, Any]] = []
  1261. for row in rows:
  1262. dt = str(row.get("dt") or "").strip()
  1263. if not dt:
  1264. continue
  1265. try:
  1266. total_score = float(row["total_score"])
  1267. except (TypeError, ValueError, KeyError):
  1268. continue
  1269. scores.append({"ymd": dt, "total_score": total_score})
  1270. return scores
  1271. def list_wxindex_word_scores_in_range(
  1272. self,
  1273. name: str,
  1274. *,
  1275. start_ymd: str,
  1276. end_ymd: str,
  1277. ) -> list[dict[str, Any]]:
  1278. word = str(name or "").strip()
  1279. start = str(start_ymd or "").strip()
  1280. end = str(end_ymd or "").strip()
  1281. if not word or not start or not end:
  1282. return []
  1283. self._ensure_wxindex_words_table()
  1284. sql = """
  1285. SELECT dt, total_score
  1286. FROM hot_content_wxindex_words
  1287. WHERE name = %s
  1288. AND dt >= %s
  1289. AND dt <= %s
  1290. ORDER BY dt ASC
  1291. """
  1292. with self.conn.cursor() as cursor:
  1293. cursor.execute(sql, (word, start, end))
  1294. rows = cursor.fetchall()
  1295. scores: list[dict[str, Any]] = []
  1296. for row in rows:
  1297. dt = str(row.get("dt") or "").strip()
  1298. if not dt:
  1299. continue
  1300. try:
  1301. total_score = float(row["total_score"])
  1302. except (TypeError, ValueError, KeyError):
  1303. continue
  1304. scores.append({"ymd": dt, "total_score": total_score})
  1305. return scores
  1306. def list_active_wxindex_word_meta(
  1307. self,
  1308. *,
  1309. today: date | None = None,
  1310. ) -> list[dict[str, Any]]:
  1311. """返回当天仍在抓取窗口内的 meta(today < fetch_end_ymd)。"""
  1312. current = today or datetime.now(SHANGHAI_TZ).date()
  1313. today_ymd = current.strftime("%Y%m%d")
  1314. self._ensure_wxindex_word_meta_table()
  1315. sql = """
  1316. SELECT id, name, event_created_at, fetch_start_ymd, fetch_end_ymd
  1317. FROM hot_content_wxindex_word_meta
  1318. WHERE fetch_end_ymd > %s
  1319. ORDER BY id ASC
  1320. """
  1321. with self.conn.cursor() as cursor:
  1322. cursor.execute(sql, (today_ymd,))
  1323. rows = cursor.fetchall()
  1324. result: list[dict[str, Any]] = []
  1325. for row in rows:
  1326. meta = self._normalize_wxindex_word_meta_row(row)
  1327. if meta is not None:
  1328. result.append(meta)
  1329. return result
  1330. def save_wxindex_word_record(self, payload: dict[str, Any]) -> int:
  1331. row = _wxindex_word_record_row(payload)
  1332. name = str(row[0])
  1333. analyze_ymd = str(row[2])
  1334. self._ensure_wxindex_word_records_table()
  1335. with self.conn.cursor() as cursor:
  1336. cursor.execute(_WXINDEX_WORD_RECORD_UPSERT_SQL, row)
  1337. cursor.execute(
  1338. """
  1339. SELECT id
  1340. FROM hot_content_wxindex_word_records
  1341. WHERE name = %s
  1342. AND analyze_ymd = %s
  1343. """,
  1344. (name, analyze_ymd),
  1345. )
  1346. record_row = cursor.fetchone() or {}
  1347. return int(record_row.get("id") or 0)
  1348. def init_wxindex_word_records(
  1349. self,
  1350. payloads: list[dict[str, Any]],
  1351. ) -> dict[str, int]:
  1352. """批量 init 追溯记录:一次 executemany,重复跑只更新 meta/抓取窗口。"""
  1353. if not payloads:
  1354. return {}
  1355. rows: list[tuple[Any, ...]] = []
  1356. analyze_ymd = ""
  1357. names: list[str] = []
  1358. for payload in payloads:
  1359. row = _wxindex_word_record_row(payload)
  1360. rows.append(row)
  1361. analyze_ymd = str(row[2])
  1362. names.append(str(row[0]))
  1363. self._ensure_wxindex_word_records_table()
  1364. with self.conn.cursor() as cursor:
  1365. cursor.executemany(_WXINDEX_WORD_RECORD_INIT_UPSERT_SQL, rows)
  1366. return self.map_wxindex_word_record_ids(analyze_ymd=analyze_ymd, names=names)
  1367. def map_wxindex_word_record_ids(
  1368. self,
  1369. *,
  1370. analyze_ymd: str,
  1371. names: list[str],
  1372. ) -> dict[str, int]:
  1373. normalized_analyze_ymd = str(analyze_ymd or "").strip()
  1374. normalized_names = [
  1375. str(name or "").strip() for name in names if str(name or "").strip()
  1376. ]
  1377. if not normalized_analyze_ymd or not normalized_names:
  1378. return {}
  1379. placeholders = ", ".join(["%s"] * len(normalized_names))
  1380. sql = f"""
  1381. SELECT id, name
  1382. FROM hot_content_wxindex_word_records
  1383. WHERE analyze_ymd = %s
  1384. AND name IN ({placeholders})
  1385. """
  1386. with self.conn.cursor() as cursor:
  1387. cursor.execute(sql, [normalized_analyze_ymd, *normalized_names])
  1388. rows = cursor.fetchall()
  1389. return {
  1390. str(row.get("name") or "").strip(): int(row.get("id") or 0)
  1391. for row in rows
  1392. if str(row.get("name") or "").strip()
  1393. }
  1394. def list_wxindex_word_records_by_analyze_ymd(
  1395. self,
  1396. *,
  1397. analyze_ymd: str,
  1398. names: list[str] | None = None,
  1399. ) -> dict[str, dict[str, Any]]:
  1400. """按 analyze_ymd 批量读取追溯记录,供同日重跑跳过已完成阶段。"""
  1401. normalized_analyze_ymd = str(analyze_ymd or "").strip()
  1402. if not normalized_analyze_ymd:
  1403. return {}
  1404. normalized_names = [
  1405. str(name or "").strip() for name in (names or []) if str(name or "").strip()
  1406. ]
  1407. self._ensure_wxindex_word_records_table()
  1408. params: list[Any] = [normalized_analyze_ymd]
  1409. name_filter = ""
  1410. if normalized_names:
  1411. placeholders = ", ".join(["%s"] * len(normalized_names))
  1412. name_filter = f" AND name IN ({placeholders})"
  1413. params.extend(normalized_names)
  1414. sql = f"""
  1415. SELECT
  1416. id,
  1417. name,
  1418. meta_id,
  1419. analyze_ymd,
  1420. fetch_start_ymd,
  1421. fetch_end_ymd,
  1422. data_start_ymd,
  1423. data_end_ymd,
  1424. data_days,
  1425. is_sustained_high,
  1426. is_rising,
  1427. is_spike,
  1428. retain_reason,
  1429. is_internal_demand_matched,
  1430. matched_demand,
  1431. demand_cache_run_id,
  1432. internal_demand_match_json,
  1433. senior_fit_score,
  1434. demand_senior_fit_json,
  1435. is_final_retained,
  1436. min_score,
  1437. max_score,
  1438. avg_score,
  1439. detail_json
  1440. FROM hot_content_wxindex_word_records
  1441. WHERE analyze_ymd = %s{name_filter}
  1442. """
  1443. with self.conn.cursor() as cursor:
  1444. cursor.execute(sql, params)
  1445. rows = cursor.fetchall()
  1446. result: dict[str, dict[str, Any]] = {}
  1447. for row in rows or []:
  1448. name = str(row.get("name") or "").strip()
  1449. if not name:
  1450. continue
  1451. record = dict(row)
  1452. record["internal_demand_match_json"] = _json_loads(
  1453. record.get("internal_demand_match_json")
  1454. )
  1455. record["demand_senior_fit_json"] = _json_loads(
  1456. record.get("demand_senior_fit_json")
  1457. )
  1458. record["detail_json"] = _json_loads(record.get("detail_json"))
  1459. result[name] = record
  1460. return result
  1461. def list_wxindex_word_stats_names(
  1462. self,
  1463. *,
  1464. analyze_ymd: str,
  1465. names: list[str] | None = None,
  1466. ) -> set[str]:
  1467. """返回指定 analyze_ymd 下已写入 stats 表的词名集合。"""
  1468. normalized_analyze_ymd = str(analyze_ymd or "").strip()
  1469. if not normalized_analyze_ymd:
  1470. return set()
  1471. normalized_names = [
  1472. str(name or "").strip() for name in (names or []) if str(name or "").strip()
  1473. ]
  1474. self._ensure_wxindex_word_stats_table()
  1475. params: list[Any] = [normalized_analyze_ymd]
  1476. name_filter = ""
  1477. if normalized_names:
  1478. placeholders = ", ".join(["%s"] * len(normalized_names))
  1479. name_filter = f" AND name IN ({placeholders})"
  1480. params.extend(normalized_names)
  1481. sql = f"""
  1482. SELECT name
  1483. FROM hot_content_wxindex_word_stats
  1484. WHERE analyze_ymd = %s{name_filter}
  1485. """
  1486. with self.conn.cursor() as cursor:
  1487. cursor.execute(sql, params)
  1488. rows = cursor.fetchall()
  1489. return {
  1490. str(row.get("name") or "").strip()
  1491. for row in rows or []
  1492. if str(row.get("name") or "").strip()
  1493. }
  1494. def save_wxindex_word_stats_batch(
  1495. self,
  1496. payloads: list[dict[str, Any]],
  1497. ) -> int:
  1498. """批量写入通过热度+老年性筛选的词统计。"""
  1499. if not payloads:
  1500. return 0
  1501. rows = [_wxindex_word_stats_row(payload) for payload in payloads]
  1502. self._ensure_wxindex_word_stats_table()
  1503. with self.conn.cursor() as cursor:
  1504. cursor.executemany(_WXINDEX_WORD_STATS_UPSERT_SQL, rows)
  1505. return len(rows)
  1506. def _ensure_wxindex_word_stats_table(self) -> None:
  1507. sql = """
  1508. CREATE TABLE IF NOT EXISTS hot_content_wxindex_word_stats (
  1509. id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
  1510. name VARCHAR(256) NOT NULL COMMENT '词',
  1511. meta_id BIGINT UNSIGNED NULL COMMENT '关联 meta.id',
  1512. analyze_ymd VARCHAR(8) NOT NULL COMMENT '分析日期 yyyymmdd',
  1513. wxindex_word_record_id BIGINT UNSIGNED NULL COMMENT '关联 records.id',
  1514. retain_reason VARCHAR(64) NULL COMMENT '热度保留原因',
  1515. senior_fit_score DOUBLE NULL COMMENT '老年性得分 0-10',
  1516. data_start_ymd VARCHAR(8) NULL COMMENT '分析数据起始日',
  1517. data_end_ymd VARCHAR(8) NULL COMMENT '分析数据结束日',
  1518. data_days INT NULL COMMENT '分析天数',
  1519. min_score DOUBLE NULL COMMENT '区间最低热度',
  1520. max_score DOUBLE NULL COMMENT '区间最高热度',
  1521. avg_score DOUBLE NULL COMMENT '区间平均热度',
  1522. detail_json JSON NULL COMMENT '扩展详情',
  1523. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  1524. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1525. ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  1526. PRIMARY KEY (id),
  1527. UNIQUE KEY uk_name_analyze_ymd (name, analyze_ymd),
  1528. KEY idx_analyze_ymd (analyze_ymd),
  1529. KEY idx_retain_reason (retain_reason)
  1530. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  1531. """
  1532. with self.conn.cursor() as cursor:
  1533. cursor.execute(sql)
  1534. def _ensure_wxindex_word_records_table(self) -> None:
  1535. sql = """
  1536. CREATE TABLE IF NOT EXISTS hot_content_wxindex_word_records (
  1537. id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
  1538. name VARCHAR(256) NOT NULL COMMENT '词',
  1539. meta_id BIGINT UNSIGNED NULL COMMENT '关联 meta.id',
  1540. analyze_ymd VARCHAR(8) NOT NULL COMMENT '分析日期 yyyymmdd',
  1541. fetch_start_ymd VARCHAR(8) NULL COMMENT 'meta 抓取起始日',
  1542. fetch_end_ymd VARCHAR(8) NULL COMMENT 'meta 抓取结束日',
  1543. data_start_ymd VARCHAR(8) NULL COMMENT '实际分析数据起始日',
  1544. data_end_ymd VARCHAR(8) NULL COMMENT '实际分析数据结束日',
  1545. data_days INT NULL COMMENT '实际分析天数',
  1546. is_sustained_high TINYINT(1) NULL COMMENT '持续热度>1000万',
  1547. is_rising TINYINT(1) NULL COMMENT '热度持续上涨',
  1548. is_spike TINYINT(1) NULL COMMENT '最近3天突然暴涨',
  1549. retain_reason VARCHAR(64) NULL COMMENT '保留原因(按2->3->1优先级)',
  1550. is_internal_demand_matched TINYINT(1) NULL COMMENT '是否匹配票圈内部需求',
  1551. matched_demand VARCHAR(1024) NULL COMMENT '匹配到的内部需求',
  1552. demand_cache_run_id BIGINT UNSIGNED NULL COMMENT '需求池缓存ID',
  1553. internal_demand_match_json JSON NULL COMMENT '内部需求匹配详情',
  1554. senior_fit_score DOUBLE NULL COMMENT '老年性得分 0-10',
  1555. demand_senior_fit_json JSON NULL COMMENT '老年性 LLM 评分结果',
  1556. is_final_retained TINYINT(1) NULL COMMENT '老年性达标且最终保留',
  1557. min_score DOUBLE NULL COMMENT '区间最低热度',
  1558. max_score DOUBLE NULL COMMENT '区间最高热度',
  1559. avg_score DOUBLE NULL COMMENT '区间平均热度',
  1560. detail_json JSON NULL COMMENT '分析详情',
  1561. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  1562. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1563. ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  1564. PRIMARY KEY (id),
  1565. UNIQUE KEY uk_name_analyze_ymd (name, analyze_ymd),
  1566. KEY idx_analyze_ymd (analyze_ymd),
  1567. KEY idx_patterns (is_sustained_high, is_rising, is_spike),
  1568. KEY idx_retain_reason (retain_reason)
  1569. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  1570. """
  1571. with self.conn.cursor() as cursor:
  1572. cursor.execute(sql)
  1573. self._ensure_wxindex_word_records_retain_columns(cursor)
  1574. self._ensure_wxindex_word_records_senior_columns(cursor)
  1575. self._ensure_wxindex_word_records_nullable_columns(cursor)
  1576. def _ensure_wxindex_word_records_nullable_columns(self, cursor: Any) -> None:
  1577. nullable_specs = {
  1578. "fetch_start_ymd": (
  1579. "MODIFY COLUMN fetch_start_ymd VARCHAR(8) NULL "
  1580. "COMMENT 'meta 抓取起始日'"
  1581. ),
  1582. "fetch_end_ymd": (
  1583. "MODIFY COLUMN fetch_end_ymd VARCHAR(8) NULL "
  1584. "COMMENT 'meta 抓取结束日'"
  1585. ),
  1586. "data_start_ymd": (
  1587. "MODIFY COLUMN data_start_ymd VARCHAR(8) NULL "
  1588. "COMMENT '实际分析数据起始日'"
  1589. ),
  1590. "data_end_ymd": (
  1591. "MODIFY COLUMN data_end_ymd VARCHAR(8) NULL "
  1592. "COMMENT '实际分析数据结束日'"
  1593. ),
  1594. "data_days": (
  1595. "MODIFY COLUMN data_days INT NULL COMMENT '实际分析天数'"
  1596. ),
  1597. "is_sustained_high": (
  1598. "MODIFY COLUMN is_sustained_high TINYINT(1) NULL "
  1599. "COMMENT '持续热度>1000万'"
  1600. ),
  1601. "is_rising": (
  1602. "MODIFY COLUMN is_rising TINYINT(1) NULL "
  1603. "COMMENT '热度持续上涨'"
  1604. ),
  1605. "is_spike": (
  1606. "MODIFY COLUMN is_spike TINYINT(1) NULL "
  1607. "COMMENT '最近3天突然暴涨'"
  1608. ),
  1609. "matched_demand": (
  1610. "MODIFY COLUMN matched_demand VARCHAR(1024) NULL "
  1611. "COMMENT '匹配到的内部需求'"
  1612. ),
  1613. "is_final_retained": (
  1614. "MODIFY COLUMN is_final_retained TINYINT(1) NULL "
  1615. "COMMENT '老年性达标且最终保留'"
  1616. ),
  1617. }
  1618. column_names = list(nullable_specs.keys())
  1619. placeholders = ", ".join(["%s"] * len(column_names))
  1620. cursor.execute(
  1621. f"""
  1622. SELECT COLUMN_NAME, IS_NULLABLE
  1623. FROM information_schema.COLUMNS
  1624. WHERE TABLE_SCHEMA = DATABASE()
  1625. AND TABLE_NAME = 'hot_content_wxindex_word_records'
  1626. AND COLUMN_NAME IN ({placeholders})
  1627. """,
  1628. column_names,
  1629. )
  1630. nullable_map = {
  1631. str(row.get("COLUMN_NAME") or ""): str(row.get("IS_NULLABLE") or "").upper()
  1632. for row in (cursor.fetchall() or [])
  1633. }
  1634. alters = [
  1635. sql
  1636. for column_name, sql in nullable_specs.items()
  1637. if nullable_map.get(column_name) == "NO"
  1638. ]
  1639. if alters:
  1640. cursor.execute(
  1641. "ALTER TABLE hot_content_wxindex_word_records " + ", ".join(alters)
  1642. )
  1643. def _ensure_wxindex_word_records_senior_columns(self, cursor: Any) -> None:
  1644. columns = {
  1645. "senior_fit_score": (
  1646. "ALTER TABLE hot_content_wxindex_word_records "
  1647. "ADD COLUMN senior_fit_score DOUBLE NULL "
  1648. "COMMENT '老年性得分 0-10' "
  1649. "AFTER internal_demand_match_json"
  1650. ),
  1651. "demand_senior_fit_json": (
  1652. "ALTER TABLE hot_content_wxindex_word_records "
  1653. "ADD COLUMN demand_senior_fit_json JSON NULL "
  1654. "COMMENT '老年性 LLM 评分结果' "
  1655. "AFTER senior_fit_score"
  1656. ),
  1657. "is_final_retained": (
  1658. "ALTER TABLE hot_content_wxindex_word_records "
  1659. "ADD COLUMN is_final_retained TINYINT(1) NULL "
  1660. "COMMENT '老年性达标且最终保留' "
  1661. "AFTER demand_senior_fit_json"
  1662. ),
  1663. }
  1664. for column_name, alter_sql in columns.items():
  1665. cursor.execute(
  1666. """
  1667. SELECT COUNT(*) AS cnt
  1668. FROM information_schema.COLUMNS
  1669. WHERE TABLE_SCHEMA = DATABASE()
  1670. AND TABLE_NAME = 'hot_content_wxindex_word_records'
  1671. AND COLUMN_NAME = %s
  1672. """,
  1673. (column_name,),
  1674. )
  1675. if int((cursor.fetchone() or {}).get("cnt") or 0) == 0:
  1676. cursor.execute(alter_sql)
  1677. def _ensure_wxindex_word_records_retain_columns(self, cursor: Any) -> None:
  1678. columns = {
  1679. "retain_reason": (
  1680. "ALTER TABLE hot_content_wxindex_word_records "
  1681. "ADD COLUMN retain_reason VARCHAR(64) NULL "
  1682. "COMMENT '保留原因(按2->3->1优先级)' "
  1683. "AFTER is_spike"
  1684. ),
  1685. "is_internal_demand_matched": (
  1686. "ALTER TABLE hot_content_wxindex_word_records "
  1687. "ADD COLUMN is_internal_demand_matched TINYINT(1) NULL "
  1688. "COMMENT '是否匹配票圈内部需求' "
  1689. "AFTER retain_reason"
  1690. ),
  1691. "matched_demand": (
  1692. "ALTER TABLE hot_content_wxindex_word_records "
  1693. "ADD COLUMN matched_demand VARCHAR(1024) NULL "
  1694. "COMMENT '匹配到的内部需求' "
  1695. "AFTER is_internal_demand_matched"
  1696. ),
  1697. "demand_cache_run_id": (
  1698. "ALTER TABLE hot_content_wxindex_word_records "
  1699. "ADD COLUMN demand_cache_run_id BIGINT UNSIGNED NULL "
  1700. "COMMENT '需求池缓存ID' "
  1701. "AFTER matched_demand"
  1702. ),
  1703. "internal_demand_match_json": (
  1704. "ALTER TABLE hot_content_wxindex_word_records "
  1705. "ADD COLUMN internal_demand_match_json JSON NULL "
  1706. "COMMENT '内部需求匹配详情' "
  1707. "AFTER demand_cache_run_id"
  1708. ),
  1709. }
  1710. for column_name, alter_sql in columns.items():
  1711. cursor.execute(
  1712. """
  1713. SELECT COUNT(*) AS cnt
  1714. FROM information_schema.COLUMNS
  1715. WHERE TABLE_SCHEMA = DATABASE()
  1716. AND TABLE_NAME = 'hot_content_wxindex_word_records'
  1717. AND COLUMN_NAME = %s
  1718. """,
  1719. (column_name,),
  1720. )
  1721. if int((cursor.fetchone() or {}).get("cnt") or 0) == 0:
  1722. cursor.execute(alter_sql)
  1723. def list_stale_wxindex_words(
  1724. self,
  1725. *,
  1726. end_ymd: str,
  1727. update_window_days: int = 7,
  1728. today: date | None = None,
  1729. ) -> list[dict[str, Any]]:
  1730. """返回更新窗口内、仍缺近 7 日区间数据的词。"""
  1731. target_end = str(end_ymd or "").strip()
  1732. if not target_end:
  1733. return []
  1734. current = today or datetime.now(SHANGHAI_TZ).date()
  1735. active_since = current - timedelta(days=max(update_window_days, 0))
  1736. self._ensure_wxindex_word_meta_table()
  1737. self._ensure_wxindex_words_table()
  1738. sql = """
  1739. SELECT
  1740. m.name,
  1741. m.event_created_at,
  1742. m.fetch_start_ymd,
  1743. MIN(w.dt) AS earliest_dt,
  1744. MAX(w.dt) AS latest_dt
  1745. FROM hot_content_wxindex_word_meta m
  1746. INNER JOIN hot_content_wxindex_words w ON w.name = m.name
  1747. WHERE DATE(m.event_created_at) >= %s
  1748. GROUP BY m.name, m.event_created_at, m.fetch_start_ymd
  1749. HAVING MAX(w.dt) < %s OR MIN(w.dt) > m.fetch_start_ymd
  1750. ORDER BY m.name ASC
  1751. """
  1752. with self.conn.cursor() as cursor:
  1753. cursor.execute(sql, (active_since, target_end))
  1754. rows = cursor.fetchall()
  1755. stale_words: list[dict[str, Any]] = []
  1756. for row in rows:
  1757. name = str(row.get("name") or "").strip()
  1758. fetch_start_ymd = str(row.get("fetch_start_ymd") or "").strip()
  1759. earliest_dt = str(row.get("earliest_dt") or "").strip()
  1760. latest_dt = str(row.get("latest_dt") or "").strip()
  1761. event_created_at = row.get("event_created_at")
  1762. if name and fetch_start_ymd and earliest_dt and latest_dt and event_created_at:
  1763. stale_words.append(
  1764. {
  1765. "name": name,
  1766. "event_created_at": event_created_at,
  1767. "fetch_start_ymd": fetch_start_ymd,
  1768. "earliest_dt": earliest_dt,
  1769. "latest_dt": latest_dt,
  1770. }
  1771. )
  1772. return stale_words
  1773. def list_word_earliest_event_times(
  1774. self,
  1775. *,
  1776. since_dt: datetime,
  1777. ) -> dict[str, datetime]:
  1778. """从 wxindex_trend_json 汇总近期间每个检索词的最早事件时间。"""
  1779. self._ensure_record_quality_columns()
  1780. sql = """
  1781. SELECT
  1782. word_name,
  1783. MIN(event_created_at) AS event_created_at
  1784. FROM (
  1785. SELECT
  1786. TRIM(searches.keyword) AS word_name,
  1787. r.created_at AS event_created_at
  1788. FROM hot_content_records r
  1789. JOIN JSON_TABLE(
  1790. r.wxindex_trend_json,
  1791. '$.wxindex_searches[*]' COLUMNS (
  1792. keyword VARCHAR(256) PATH '$.keyword'
  1793. )
  1794. ) AS searches
  1795. WHERE r.created_at >= %s
  1796. AND r.wxindex_trend_json IS NOT NULL
  1797. AND TRIM(searches.keyword) <> ''
  1798. UNION ALL
  1799. SELECT
  1800. TRIM(JSON_UNQUOTE(JSON_EXTRACT(r.wxindex_trend_json, '$.llm_selected_word'))) AS word_name,
  1801. r.created_at AS event_created_at
  1802. FROM hot_content_records r
  1803. WHERE r.created_at >= %s
  1804. AND r.wxindex_trend_json IS NOT NULL
  1805. AND TRIM(JSON_UNQUOTE(JSON_EXTRACT(r.wxindex_trend_json, '$.llm_selected_word'))) <> ''
  1806. ) AS word_events
  1807. WHERE word_name IS NOT NULL
  1808. AND word_name <> ''
  1809. GROUP BY word_name
  1810. """
  1811. with self.conn.cursor() as cursor:
  1812. cursor.execute(sql, (since_dt, since_dt))
  1813. rows = cursor.fetchall()
  1814. event_map: dict[str, datetime] = {}
  1815. for row in rows:
  1816. name = str(row.get("word_name") or "").strip()
  1817. event_created_at = row.get("event_created_at")
  1818. if name and isinstance(event_created_at, datetime):
  1819. event_map[name] = event_created_at
  1820. return event_map
  1821. def list_wxindex_word_bounds_without_meta(self) -> list[dict[str, Any]]:
  1822. self._ensure_wxindex_word_meta_table()
  1823. self._ensure_wxindex_words_table()
  1824. sql = """
  1825. SELECT
  1826. w.name,
  1827. MIN(w.dt) AS earliest_dt,
  1828. MIN(w.created_at) AS first_created_at
  1829. FROM hot_content_wxindex_words w
  1830. LEFT JOIN hot_content_wxindex_word_meta m ON m.name = w.name
  1831. WHERE m.name IS NULL
  1832. GROUP BY w.name
  1833. ORDER BY w.name ASC
  1834. """
  1835. with self.conn.cursor() as cursor:
  1836. cursor.execute(sql)
  1837. rows = cursor.fetchall()
  1838. bounds: list[dict[str, Any]] = []
  1839. for row in rows:
  1840. name = str(row.get("name") or "").strip()
  1841. earliest_dt = str(row.get("earliest_dt") or "").strip()
  1842. first_created_at = row.get("first_created_at")
  1843. if name and earliest_dt:
  1844. bounds.append(
  1845. {
  1846. "name": name,
  1847. "earliest_dt": earliest_dt,
  1848. "first_created_at": first_created_at,
  1849. }
  1850. )
  1851. return bounds
  1852. def list_wxindex_word_names_without_meta(self) -> list[str]:
  1853. self._ensure_wxindex_word_meta_table()
  1854. self._ensure_wxindex_words_table()
  1855. sql = """
  1856. SELECT DISTINCT w.name
  1857. FROM hot_content_wxindex_words w
  1858. LEFT JOIN hot_content_wxindex_word_meta m ON m.name = w.name
  1859. WHERE m.name IS NULL
  1860. ORDER BY w.name ASC
  1861. """
  1862. with self.conn.cursor() as cursor:
  1863. cursor.execute(sql)
  1864. rows = cursor.fetchall()
  1865. return [
  1866. str(row.get("name") or "").strip()
  1867. for row in rows
  1868. if str(row.get("name") or "").strip()
  1869. ]
  1870. def get_wxindex_word_first_row_created_at(self, name: str) -> datetime | None:
  1871. word = str(name or "").strip()
  1872. if not word:
  1873. return None
  1874. self._ensure_wxindex_words_table()
  1875. sql = """
  1876. SELECT MIN(created_at) AS first_created_at
  1877. FROM hot_content_wxindex_words
  1878. WHERE name = %s
  1879. """
  1880. with self.conn.cursor() as cursor:
  1881. cursor.execute(sql, (word,))
  1882. row = cursor.fetchone() or {}
  1883. first_created_at = row.get("first_created_at")
  1884. return first_created_at if isinstance(first_created_at, datetime) else None
  1885. def list_all_wxindex_word_meta(self) -> list[dict[str, Any]]:
  1886. self._ensure_wxindex_word_meta_table()
  1887. sql = """
  1888. SELECT id, name, event_created_at, fetch_start_ymd, fetch_end_ymd
  1889. FROM hot_content_wxindex_word_meta
  1890. ORDER BY id ASC
  1891. """
  1892. with self.conn.cursor() as cursor:
  1893. cursor.execute(sql)
  1894. rows = cursor.fetchall()
  1895. result: list[dict[str, Any]] = []
  1896. for row in rows:
  1897. meta = self._normalize_wxindex_word_meta_row(row)
  1898. if meta is not None:
  1899. result.append(meta)
  1900. return result
  1901. def update_wxindex_word_meta_fetch_start(
  1902. self,
  1903. *,
  1904. name: str,
  1905. fetch_start_ymd: str,
  1906. ) -> None:
  1907. word = str(name or "").strip()
  1908. target_start = str(fetch_start_ymd or "").strip()
  1909. if not word or not target_start:
  1910. raise HotContentFlowError("invalid wxindex word meta fetch_start_ymd payload")
  1911. self._ensure_wxindex_word_meta_table()
  1912. sql = """
  1913. UPDATE hot_content_wxindex_word_meta
  1914. SET fetch_start_ymd = %s
  1915. WHERE name = %s
  1916. """
  1917. with self.conn.cursor() as cursor:
  1918. cursor.execute(sql, (target_start, word))
  1919. def update_wxindex_word_meta(
  1920. self,
  1921. *,
  1922. name: str,
  1923. event_created_at: datetime,
  1924. fetch_start_ymd: str,
  1925. fetch_end_ymd: str,
  1926. ) -> None:
  1927. word = str(name or "").strip()
  1928. target_start = str(fetch_start_ymd or "").strip()
  1929. target_end = str(fetch_end_ymd or "").strip()
  1930. if not word or not target_start or not target_end:
  1931. raise HotContentFlowError("invalid wxindex word meta payload")
  1932. self._ensure_wxindex_word_meta_table()
  1933. event_at = event_created_at
  1934. if event_at.tzinfo is not None:
  1935. event_at = event_at.astimezone(SHANGHAI_TZ).replace(tzinfo=None)
  1936. sql = """
  1937. UPDATE hot_content_wxindex_word_meta
  1938. SET event_created_at = %s,
  1939. fetch_start_ymd = %s,
  1940. fetch_end_ymd = %s
  1941. WHERE name = %s
  1942. """
  1943. with self.conn.cursor() as cursor:
  1944. cursor.execute(sql, (event_at, target_start, target_end, word))
  1945. def get_wxindex_word_meta(self, name: str) -> dict[str, Any] | None:
  1946. word = str(name or "").strip()
  1947. if not word:
  1948. return None
  1949. self._ensure_wxindex_word_meta_table()
  1950. sql = """
  1951. SELECT id, name, event_created_at, fetch_start_ymd, fetch_end_ymd
  1952. FROM hot_content_wxindex_word_meta
  1953. WHERE name = %s
  1954. """
  1955. with self.conn.cursor() as cursor:
  1956. cursor.execute(sql, (word,))
  1957. row = cursor.fetchone()
  1958. if not row:
  1959. return None
  1960. return self._normalize_wxindex_word_meta_row(row)
  1961. def ensure_wxindex_word_meta(
  1962. self,
  1963. *,
  1964. name: str,
  1965. event_created_at: datetime,
  1966. fetch_start_ymd: str,
  1967. fetch_end_ymd: str,
  1968. ) -> dict[str, Any]:
  1969. word = str(name or "").strip()
  1970. target_start = str(fetch_start_ymd or "").strip()
  1971. target_end = str(fetch_end_ymd or "").strip()
  1972. if not word or not target_start or not target_end:
  1973. raise HotContentFlowError("invalid wxindex word meta payload")
  1974. self._ensure_wxindex_word_meta_table()
  1975. event_at = event_created_at
  1976. if event_at.tzinfo is not None:
  1977. event_at = event_at.astimezone(SHANGHAI_TZ).replace(tzinfo=None)
  1978. sql = """
  1979. INSERT INTO hot_content_wxindex_word_meta (
  1980. name,
  1981. event_created_at,
  1982. fetch_start_ymd,
  1983. fetch_end_ymd
  1984. )
  1985. VALUES (%s, %s, %s, %s)
  1986. ON DUPLICATE KEY UPDATE
  1987. event_created_at = VALUES(event_created_at),
  1988. fetch_start_ymd = VALUES(fetch_start_ymd),
  1989. fetch_end_ymd = VALUES(fetch_end_ymd)
  1990. """
  1991. with self.conn.cursor() as cursor:
  1992. cursor.execute(sql, (word, event_at, target_start, target_end))
  1993. meta = self.get_wxindex_word_meta(word)
  1994. if meta is None:
  1995. raise HotContentFlowError(f"failed to persist wxindex word meta: {word}")
  1996. return meta
  1997. def delete_wxindex_word_meta_by_names(self, names: list[str]) -> int:
  1998. words = [str(name or "").strip() for name in names]
  1999. words = [name for name in words if name]
  2000. if not words:
  2001. return 0
  2002. self._ensure_wxindex_word_meta_table()
  2003. placeholders = ", ".join(["%s"] * len(words))
  2004. sql = f"DELETE FROM hot_content_wxindex_word_meta WHERE name IN ({placeholders})"
  2005. with self.conn.cursor() as cursor:
  2006. cursor.execute(sql, tuple(words))
  2007. return int(cursor.rowcount or 0)
  2008. def list_low_max_wxindex_words(
  2009. self,
  2010. *,
  2011. min_max_score: float,
  2012. ) -> list[dict[str, Any]]:
  2013. """按 name 聚合,返回最大值低于阈值的词。"""
  2014. self._ensure_wxindex_words_table()
  2015. sql = """
  2016. SELECT
  2017. name,
  2018. MAX(total_score) AS max_score,
  2019. COUNT(*) AS row_count
  2020. FROM hot_content_wxindex_words
  2021. GROUP BY name
  2022. HAVING MAX(total_score) < %s
  2023. ORDER BY name ASC
  2024. """
  2025. with self.conn.cursor() as cursor:
  2026. cursor.execute(sql, (min_max_score,))
  2027. rows = cursor.fetchall()
  2028. low_words: list[dict[str, Any]] = []
  2029. for row in rows:
  2030. name = str(row.get("name") or "").strip()
  2031. if not name:
  2032. continue
  2033. try:
  2034. max_score = float(row["max_score"])
  2035. row_count = int(row["row_count"])
  2036. except (TypeError, ValueError, KeyError):
  2037. continue
  2038. low_words.append(
  2039. {
  2040. "name": name,
  2041. "max_score": max_score,
  2042. "row_count": row_count,
  2043. }
  2044. )
  2045. return low_words
  2046. def count_wxindex_words_outside_event_window(
  2047. self,
  2048. *,
  2049. window_days: int = 7,
  2050. ) -> int:
  2051. self._ensure_wxindex_word_meta_table()
  2052. self._ensure_wxindex_words_table()
  2053. sql = """
  2054. SELECT COUNT(*) AS row_count
  2055. FROM hot_content_wxindex_words w
  2056. INNER JOIN hot_content_wxindex_word_meta m ON m.name = w.name
  2057. WHERE w.dt < m.fetch_start_ymd
  2058. OR w.dt > m.fetch_end_ymd
  2059. """
  2060. with self.conn.cursor() as cursor:
  2061. cursor.execute(sql)
  2062. row = cursor.fetchone() or {}
  2063. return int(row.get("row_count") or 0)
  2064. def list_wxindex_words_outside_event_window_samples(
  2065. self,
  2066. *,
  2067. window_days: int = 7,
  2068. limit: int = 20,
  2069. ) -> list[dict[str, Any]]:
  2070. self._ensure_wxindex_word_meta_table()
  2071. self._ensure_wxindex_words_table()
  2072. sql = """
  2073. SELECT
  2074. w.name,
  2075. w.dt,
  2076. m.event_created_at,
  2077. m.fetch_start_ymd AS start_ymd,
  2078. m.fetch_end_ymd AS end_ymd
  2079. FROM hot_content_wxindex_words w
  2080. INNER JOIN hot_content_wxindex_word_meta m ON m.name = w.name
  2081. WHERE w.dt < m.fetch_start_ymd
  2082. OR w.dt > m.fetch_end_ymd
  2083. ORDER BY w.name ASC, w.dt ASC
  2084. LIMIT %s
  2085. """
  2086. with self.conn.cursor() as cursor:
  2087. cursor.execute(sql, (limit,))
  2088. rows = cursor.fetchall()
  2089. samples: list[dict[str, Any]] = []
  2090. for row in rows:
  2091. name = str(row.get("name") or "").strip()
  2092. dt = str(row.get("dt") or "").strip()
  2093. if name and dt:
  2094. samples.append(
  2095. {
  2096. "name": name,
  2097. "dt": dt,
  2098. "event_created_at": row.get("event_created_at"),
  2099. "start_ymd": str(row.get("start_ymd") or "").strip(),
  2100. "end_ymd": str(row.get("end_ymd") or "").strip(),
  2101. }
  2102. )
  2103. return samples
  2104. def delete_wxindex_words_outside_event_window(
  2105. self,
  2106. *,
  2107. window_days: int = 7,
  2108. ) -> int:
  2109. self._ensure_wxindex_word_meta_table()
  2110. self._ensure_wxindex_words_table()
  2111. sql = """
  2112. DELETE w
  2113. FROM hot_content_wxindex_words w
  2114. INNER JOIN hot_content_wxindex_word_meta m ON m.name = w.name
  2115. WHERE w.dt < m.fetch_start_ymd
  2116. OR w.dt > m.fetch_end_ymd
  2117. """
  2118. with self.conn.cursor() as cursor:
  2119. cursor.execute(sql)
  2120. return int(cursor.rowcount or 0)
  2121. def delete_wxindex_words_without_meta(self) -> int:
  2122. self._ensure_wxindex_word_meta_table()
  2123. self._ensure_wxindex_words_table()
  2124. sql = """
  2125. DELETE w
  2126. FROM hot_content_wxindex_words w
  2127. LEFT JOIN hot_content_wxindex_word_meta m ON m.name = w.name
  2128. WHERE m.name IS NULL
  2129. """
  2130. with self.conn.cursor() as cursor:
  2131. cursor.execute(sql)
  2132. return int(cursor.rowcount or 0)
  2133. def count_wxindex_words_without_meta(self) -> int:
  2134. self._ensure_wxindex_word_meta_table()
  2135. self._ensure_wxindex_words_table()
  2136. sql = """
  2137. SELECT COUNT(*) AS row_count
  2138. FROM hot_content_wxindex_words w
  2139. LEFT JOIN hot_content_wxindex_word_meta m ON m.name = w.name
  2140. WHERE m.name IS NULL
  2141. """
  2142. with self.conn.cursor() as cursor:
  2143. cursor.execute(sql)
  2144. row = cursor.fetchone() or {}
  2145. return int(row.get("row_count") or 0)
  2146. def delete_wxindex_words_by_names(self, names: list[str]) -> int:
  2147. cleaned = [str(name or "").strip() for name in names if str(name or "").strip()]
  2148. if not cleaned:
  2149. return 0
  2150. self._ensure_wxindex_words_table()
  2151. placeholders = ", ".join(["%s"] * len(cleaned))
  2152. sql = f"""
  2153. DELETE FROM hot_content_wxindex_words
  2154. WHERE name IN ({placeholders})
  2155. """
  2156. with self.conn.cursor() as cursor:
  2157. cursor.execute(sql, tuple(cleaned))
  2158. return int(cursor.rowcount or 0)
  2159. def list_wxindex_word_names_with_dt(
  2160. self,
  2161. names: list[str],
  2162. *,
  2163. dt: str,
  2164. ) -> set[str]:
  2165. """返回在 hot_content_wxindex_words 中存在指定日期数据的词名集合。"""
  2166. target_dt = str(dt or "").strip()
  2167. normalized_names = [
  2168. str(name or "").strip() for name in names if str(name or "").strip()
  2169. ]
  2170. if not target_dt or not normalized_names:
  2171. return set()
  2172. self._ensure_wxindex_words_table()
  2173. placeholders = ", ".join(["%s"] * len(normalized_names))
  2174. sql = f"""
  2175. SELECT DISTINCT name
  2176. FROM hot_content_wxindex_words
  2177. WHERE dt = %s
  2178. AND name IN ({placeholders})
  2179. """
  2180. with self.conn.cursor() as cursor:
  2181. cursor.execute(sql, [target_dt, *normalized_names])
  2182. rows = cursor.fetchall()
  2183. return {
  2184. str(row.get("name") or "").strip()
  2185. for row in rows or []
  2186. if str(row.get("name") or "").strip()
  2187. }
  2188. def has_wxindex_word(self, name: str) -> bool:
  2189. return self.get_wxindex_word_latest_dt(name) is not None
  2190. def get_wxindex_word_latest_dt(self, name: str) -> str | None:
  2191. word = str(name or "").strip()
  2192. if not word:
  2193. return None
  2194. self._ensure_wxindex_words_table()
  2195. sql = """
  2196. SELECT MAX(dt) AS latest_dt
  2197. FROM hot_content_wxindex_words
  2198. WHERE name = %s
  2199. """
  2200. with self.conn.cursor() as cursor:
  2201. cursor.execute(sql, (word,))
  2202. row = cursor.fetchone() or {}
  2203. latest_dt = str(row.get("latest_dt") or "").strip()
  2204. return latest_dt or None
  2205. def save_wxindex_daily_scores(
  2206. self,
  2207. *,
  2208. name: str,
  2209. scores: list[dict[str, Any]],
  2210. ) -> tuple[int, int]:
  2211. """按词+日期写入每日指数,重复行跳过。返回 (inserted, skipped)。"""
  2212. word = str(name or "").strip()
  2213. if not word or not scores:
  2214. return 0, 0
  2215. self._ensure_wxindex_words_table()
  2216. sql = """
  2217. INSERT IGNORE INTO hot_content_wxindex_words (
  2218. name,
  2219. dt,
  2220. total_score
  2221. )
  2222. VALUES (%s, %s, %s)
  2223. """
  2224. rows: list[tuple[str, str, float]] = []
  2225. seen: set[tuple[str, str]] = set()
  2226. for item in scores:
  2227. if not isinstance(item, dict):
  2228. continue
  2229. dt = str(item.get("ymd") or item.get("dt") or "").strip()
  2230. if not dt:
  2231. continue
  2232. try:
  2233. total_score = float(item["total_score"])
  2234. except (TypeError, ValueError, KeyError):
  2235. continue
  2236. key = (word, dt)
  2237. if key in seen:
  2238. continue
  2239. seen.add(key)
  2240. rows.append((word, dt, total_score))
  2241. if not rows:
  2242. return 0, 0
  2243. inserted = 0
  2244. with self.conn.cursor() as cursor:
  2245. for row in rows:
  2246. cursor.execute(sql, row)
  2247. inserted += int(cursor.rowcount or 0)
  2248. skipped = len(rows) - inserted
  2249. return inserted, skipped
  2250. def list_records_with_wxindex_trend_after(
  2251. self,
  2252. *,
  2253. after_created_at: datetime,
  2254. ) -> list[dict[str, Any]]:
  2255. sql = """
  2256. SELECT id, created_at, wxindex_trend_json
  2257. FROM hot_content_records
  2258. WHERE created_at > %s
  2259. AND wxindex_trend_json IS NOT NULL
  2260. AND TRIM(CAST(wxindex_trend_json AS CHAR)) <> ''
  2261. ORDER BY id ASC
  2262. """
  2263. with self.conn.cursor() as cursor:
  2264. cursor.execute(sql, (after_created_at,))
  2265. rows = cursor.fetchall()
  2266. records: list[dict[str, Any]] = []
  2267. for row in rows:
  2268. records.append(
  2269. {
  2270. "id": int(row["id"]),
  2271. "created_at": row.get("created_at"),
  2272. "wxindex_trend_json": _json_loads(row.get("wxindex_trend_json")),
  2273. }
  2274. )
  2275. return records
  2276. def list_records_with_wxindex_trend(
  2277. self,
  2278. *,
  2279. since_dt: datetime,
  2280. ) -> list[dict[str, Any]]:
  2281. sql = """
  2282. SELECT id, created_at, wxindex_trend_json
  2283. FROM hot_content_records
  2284. WHERE created_at >= %s
  2285. AND wxindex_trend_json IS NOT NULL
  2286. AND TRIM(CAST(wxindex_trend_json AS CHAR)) <> ''
  2287. ORDER BY id ASC
  2288. """
  2289. with self.conn.cursor() as cursor:
  2290. cursor.execute(sql, (since_dt,))
  2291. rows = cursor.fetchall()
  2292. records: list[dict[str, Any]] = []
  2293. for row in rows:
  2294. records.append(
  2295. {
  2296. "id": int(row["id"]),
  2297. "created_at": row.get("created_at"),
  2298. "wxindex_trend_json": _json_loads(row.get("wxindex_trend_json")),
  2299. }
  2300. )
  2301. return records
  2302. def _ensure_wxindex_word_meta_table(self) -> None:
  2303. sql = """
  2304. CREATE TABLE IF NOT EXISTS hot_content_wxindex_word_meta (
  2305. id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
  2306. name VARCHAR(256) NOT NULL COMMENT '词',
  2307. event_created_at DATETIME NOT NULL COMMENT '首次关联热点事件创建时间',
  2308. fetch_start_ymd VARCHAR(8) NOT NULL COMMENT '数据窗口左边界:事件创建日往前7天',
  2309. fetch_end_ymd VARCHAR(8) NOT NULL DEFAULT '' COMMENT '数据窗口右边界:事件创建日后7天',
  2310. meta_created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '元数据创建时间',
  2311. PRIMARY KEY (id),
  2312. UNIQUE KEY uk_name (name),
  2313. KEY idx_event_created_at (event_created_at)
  2314. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  2315. """
  2316. with self.conn.cursor() as cursor:
  2317. cursor.execute(sql)
  2318. self._ensure_wxindex_word_meta_id_column(cursor)
  2319. self._ensure_wxindex_word_meta_fetch_end_column(cursor)
  2320. def _ensure_wxindex_word_meta_fetch_end_column(self, cursor: Any) -> None:
  2321. cursor.execute(
  2322. """
  2323. SELECT COUNT(*) AS cnt
  2324. FROM information_schema.COLUMNS
  2325. WHERE TABLE_SCHEMA = DATABASE()
  2326. AND TABLE_NAME = 'hot_content_wxindex_word_meta'
  2327. AND COLUMN_NAME = 'fetch_end_ymd'
  2328. """
  2329. )
  2330. if int((cursor.fetchone() or {}).get("cnt") or 0) == 0:
  2331. cursor.execute(
  2332. """
  2333. ALTER TABLE hot_content_wxindex_word_meta
  2334. ADD COLUMN fetch_end_ymd VARCHAR(8) NOT NULL DEFAULT ''
  2335. COMMENT '数据窗口右边界:事件创建日后7天'
  2336. AFTER fetch_start_ymd
  2337. """
  2338. )
  2339. cursor.execute(
  2340. """
  2341. UPDATE hot_content_wxindex_word_meta
  2342. SET fetch_end_ymd = DATE_FORMAT(
  2343. DATE_ADD(DATE(event_created_at), INTERVAL 7 DAY),
  2344. '%Y%m%d'
  2345. )
  2346. WHERE fetch_end_ymd IS NULL
  2347. OR TRIM(fetch_end_ymd) = ''
  2348. """
  2349. )
  2350. def _ensure_wxindex_word_meta_id_column(self, cursor: Any) -> None:
  2351. cursor.execute(
  2352. """
  2353. SELECT COUNT(*) AS cnt
  2354. FROM information_schema.COLUMNS
  2355. WHERE TABLE_SCHEMA = DATABASE()
  2356. AND TABLE_NAME = 'hot_content_wxindex_word_meta'
  2357. AND COLUMN_NAME = 'id'
  2358. """
  2359. )
  2360. if int((cursor.fetchone() or {}).get("cnt") or 0) > 0:
  2361. return
  2362. cursor.execute(
  2363. """
  2364. ALTER TABLE hot_content_wxindex_word_meta
  2365. DROP PRIMARY KEY,
  2366. ADD COLUMN id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST,
  2367. ADD UNIQUE KEY uk_name (name)
  2368. """
  2369. )
  2370. @staticmethod
  2371. def _normalize_wxindex_word_meta_row(row: dict[str, Any]) -> dict[str, Any] | None:
  2372. name = str(row.get("name") or "").strip()
  2373. fetch_start_ymd = str(row.get("fetch_start_ymd") or "").strip()
  2374. fetch_end_ymd = str(row.get("fetch_end_ymd") or "").strip()
  2375. event_created_at = row.get("event_created_at")
  2376. if not name or not fetch_start_ymd or event_created_at is None:
  2377. return None
  2378. if not fetch_end_ymd and isinstance(event_created_at, datetime):
  2379. event_date = event_created_at.date()
  2380. fetch_end_ymd = (event_date + timedelta(days=7)).strftime("%Y%m%d")
  2381. if not fetch_end_ymd:
  2382. return None
  2383. try:
  2384. meta_id = int(row.get("id"))
  2385. except (TypeError, ValueError):
  2386. return None
  2387. return {
  2388. "id": meta_id,
  2389. "name": name,
  2390. "event_created_at": event_created_at,
  2391. "fetch_start_ymd": fetch_start_ymd,
  2392. "fetch_end_ymd": fetch_end_ymd,
  2393. }
  2394. def _ensure_wxindex_words_table(self) -> None:
  2395. sql = """
  2396. CREATE TABLE IF NOT EXISTS hot_content_wxindex_words (
  2397. id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  2398. name VARCHAR(256) NOT NULL COMMENT '词',
  2399. dt VARCHAR(8) NOT NULL COMMENT '日期 yyyymmdd',
  2400. total_score DOUBLE NOT NULL COMMENT '微信指数',
  2401. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  2402. PRIMARY KEY (id),
  2403. UNIQUE KEY uk_name_dt (name, dt),
  2404. KEY idx_name (name),
  2405. KEY idx_dt (dt)
  2406. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  2407. """
  2408. with self.conn.cursor() as cursor:
  2409. cursor.execute(sql)
  2410. def _ensure_odps_sync_log_table(self) -> None:
  2411. sql = """
  2412. CREATE TABLE IF NOT EXISTS hot_content_odps_sync_log (
  2413. id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  2414. partition_dt VARCHAR(8) NOT NULL COMMENT 'ODPS 分区 dt',
  2415. strategy VARCHAR(128) NOT NULL COMMENT '需求 strategy',
  2416. demand_id CHAR(32) NOT NULL COMMENT 'ODPS demand_id',
  2417. demand_name VARCHAR(1024) NOT NULL DEFAULT '' COMMENT '需求名',
  2418. demand_type VARCHAR(32) NOT NULL DEFAULT '' COMMENT '特征点/短语',
  2419. record_id BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '来源 hot_content_records.id',
  2420. weight DOUBLE NULL DEFAULT NULL COMMENT 'ODPS 需求权重(记录 wxindex 最高分 / 1000000)',
  2421. synced_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '写入 ODPS 时间',
  2422. PRIMARY KEY (id),
  2423. UNIQUE KEY uk_odps_sync (partition_dt, strategy, demand_id),
  2424. KEY idx_record_partition (record_id, partition_dt),
  2425. KEY idx_partition_strategy (partition_dt, strategy)
  2426. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  2427. """
  2428. with self.conn.cursor() as cursor:
  2429. cursor.execute(sql)
  2430. self._ensure_odps_sync_log_weight_column(cursor)