publish_single_video_pool_videos.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import json
  2. import datetime
  3. import traceback
  4. from pymysql.cursors import DictCursor
  5. from tqdm import tqdm
  6. from applications import aiditApi
  7. from applications.api import ApolloApi, FeishuBotApi
  8. from applications.const import SingleVideoPoolPublishTaskConst
  9. from applications.db import DatabaseConnector
  10. from config import long_articles_config
  11. # init
  12. apollo_api = ApolloApi(env="prod")
  13. feishu_bot_api = FeishuBotApi()
  14. const = SingleVideoPoolPublishTaskConst()
  15. # get config information from apollo
  16. video_pool_config = json.loads(
  17. apollo_api.get_config_value(key="video_pool_publish_config")
  18. )
  19. video_category_list = json.loads(apollo_api.get_config_value(key="category_list"))
  20. # platform_list = list(video_pool_config.keys())
  21. platform_list = ['hksp']
  22. experimental_account = json.loads(
  23. apollo_api.get_config_value(key="experimental_account")
  24. )
  25. experimental_account_set = set(experimental_account)
  26. class PublishSingleVideoPoolVideos:
  27. def __init__(self):
  28. self.db_client = DatabaseConnector(db_config=long_articles_config)
  29. self.db_client.connect()
  30. def get_task_list(self, platform: str) -> list[dict]:
  31. daily_limit = video_pool_config[platform]["process_num_each_day"]
  32. fetch_query = f"""
  33. select t1.id, t1.content_trace_id, t1.pq_vid, t1.score, t2.category, t2.out_account_id
  34. from single_video_transform_queue t1
  35. join publish_single_video_source t2 on t1.content_trace_id = t2.content_trace_id
  36. where
  37. t1.status = {const.TRANSFORM_INIT_STATUS}
  38. and t1.platform = '{platform}'
  39. and t2.category_status = {const.SUCCESS_STATUS}
  40. order by score desc
  41. limit {daily_limit};
  42. """
  43. fetch_response = self.db_client.fetch(query=fetch_query, cursor_type=DictCursor)
  44. return fetch_response
  45. def update_tasks_status(
  46. self, task_id_tuple: tuple, ori_status: int, new_status: int
  47. ) -> int:
  48. update_query = f"""
  49. update single_video_transform_queue
  50. set status = %s
  51. where id in %s and status = %s;
  52. """
  53. affected_rows = self.db_client.save(
  54. query=update_query, params=(new_status, task_id_tuple, ori_status)
  55. )
  56. return affected_rows
  57. def create_crawler_plan(
  58. self, vid_list: list, platform: str, task_id_tuple: tuple, category: str, experiment_tag: str = None
  59. ) -> None:
  60. try:
  61. # create video crawler plan
  62. date_info = datetime.datetime.today().strftime('%Y-%m-%d')
  63. if experiment_tag:
  64. plan_name = f"{video_pool_config[platform]['nick_name']}-{category}-{date_info}-视频数量: {len(vid_list): {experiment_tag}}"
  65. else:
  66. plan_name = f"{video_pool_config[platform]['nick_name']}-{category}-{date_info}-视频数量: {len(vid_list)}"
  67. crawler_plan_response = aiditApi.auto_create_single_video_crawler_task(
  68. plan_name=plan_name,
  69. plan_tag="单视频供给冷启动",
  70. video_id_list=vid_list,
  71. )
  72. crawler_plan_id = crawler_plan_response["data"]["id"]
  73. crawler_plan_name = crawler_plan_response["data"]["name"]
  74. # bind crawler plan to generate plan
  75. crawler_task_list = [
  76. {
  77. "contentType": 1,
  78. "inputSourceModal": 4,
  79. "inputSourceChannel": 10,
  80. "inputSourceType": 2,
  81. "inputSourceValue": crawler_plan_id,
  82. "inputSourceSubType": None,
  83. "fieldName": None,
  84. "inputSourceLabel": "原始帖子-视频-票圈小程序-内容添加计划-{}".format(
  85. crawler_plan_name
  86. ),
  87. }
  88. ]
  89. generate_plan_id = video_pool_config[platform]["generate_plan_id"]
  90. aiditApi.bind_crawler_task_to_generate_task(
  91. crawler_task_list=crawler_task_list,
  92. generate_task_id=generate_plan_id,
  93. )
  94. # update status
  95. self.update_tasks_status(
  96. task_id_tuple=task_id_tuple,
  97. ori_status=const.TRANSFORM_INIT_STATUS,
  98. new_status=const.TRANSFORM_SUCCESS_STATUS,
  99. )
  100. except Exception as e:
  101. feishu_bot_api.bot(
  102. title="视频内容池发布任务",
  103. detail={
  104. "platform": platform,
  105. "date": datetime.datetime.today().strftime("%Y-%m-%d"),
  106. "msg": "发布视频内容池失败,原因:{}".format(str(e)),
  107. "detail": traceback.format_exc(),
  108. },
  109. mention=False,
  110. )
  111. def deal(self):
  112. """
  113. entrance of this class
  114. """
  115. platform_map = [
  116. (key, video_pool_config[key]["nick_name"]) for key in video_pool_config
  117. ]
  118. columns = [
  119. feishu_bot_api.create_feishu_columns_sheet(
  120. sheet_type="plain_text", sheet_name="category", display_name="品类"
  121. ),
  122. feishu_bot_api.create_feishu_columns_sheet(
  123. sheet_type="number", sheet_name="total", display_name="品类视频总量"
  124. ),
  125. *[
  126. feishu_bot_api.create_feishu_columns_sheet(
  127. sheet_type="number", sheet_name=platform, display_name=display_name
  128. )
  129. for platform, display_name in platform_map
  130. ],
  131. ]
  132. publish_detail_table = {}
  133. for platform in tqdm(platform_list, desc="process each platform"):
  134. task_list = self.get_task_list(platform)
  135. if task_list:
  136. # split task list into each category
  137. for category in video_category_list:
  138. task_list_with_category = [
  139. task for task in task_list if task["category"] == category
  140. ]
  141. task_id_tuple = tuple(
  142. [task["id"] for task in task_list_with_category]
  143. )
  144. # 区分账号ID 是否属于实验账号
  145. experimental_vid_list = [task["pq_vid"] for task in task_list_with_category if task["out_account_id"] in experimental_account_set]
  146. normal_vid_list = [task["pq_vid"] for task in task_list_with_category if task["out_account_id"] not in experimental_account_set]
  147. if normal_vid_list:
  148. self.create_crawler_plan(
  149. normal_vid_list, platform, task_id_tuple, category
  150. )
  151. if publish_detail_table.get(platform):
  152. publish_detail_table[platform][category] = len(normal_vid_list)
  153. else:
  154. publish_detail_table[platform] = {category: len(normal_vid_list)}
  155. if experimental_vid_list:
  156. self.create_crawler_plan(
  157. experimental_vid_list, platform, task_id_tuple, category, "20250610-品类账号实验"
  158. )
  159. if publish_detail_table.get(platform):
  160. publish_detail_table[platform][category] += len(experimental_vid_list)
  161. else:
  162. publish_detail_table[platform] = {category: len(experimental_vid_list)}
  163. else:
  164. feishu_bot_api.bot(
  165. title="视频内容池发布任务",
  166. detail={
  167. "platform": platform,
  168. "date": datetime.datetime.today().strftime("%Y-%m-%d"),
  169. "msg": "该渠道今日无供给,注意关注供给详情",
  170. },
  171. mention=False,
  172. )
  173. detail_rows = []
  174. for category in video_category_list:
  175. platform_counts = {
  176. platform: publish_detail_table.get(platform, {}).get(category, 0)
  177. for platform in platform_list
  178. }
  179. total = sum(platform_counts.values())
  180. detail_rows.append(
  181. {"category": category, **platform_counts, "total": total}
  182. )
  183. feishu_bot_api.bot(
  184. title="视频内容池冷启动发布任务",
  185. detail={
  186. "columns": columns,
  187. "rows": detail_rows,
  188. },
  189. table=True,
  190. mention=False,
  191. )