xiaoniangaotuijianliu.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import os
  2. import random
  3. import sys
  4. import time
  5. import uuid
  6. import json
  7. from datetime import datetime
  8. import cv2
  9. import requests
  10. from application.common.feishu import FsData
  11. from application.common.feishu.feishu_utils import FeishuUtils
  12. from application.common.gpt import GPT4oMini
  13. from application.common.mysql.sql import Sql
  14. from application.common.redis.xng_redis import xng_in_video_data
  15. from application.config.config import xiaoniangao_view_api,xiaoniangao_history_api
  16. sys.path.append(os.getcwd())
  17. from application.items import VideoItem
  18. from application.pipeline import PiaoQuanPipeline
  19. from application.common.messageQueue import MQ
  20. from application.common.log import AliyunLogger
  21. from application.common.mysql import MysqlHelper
  22. def video_view(content_id, account_id):
  23. headers = {
  24. "Content-Type": "application/json"
  25. }
  26. payload = {
  27. "content_id": str(content_id),
  28. "account_id": str(account_id)
  29. }
  30. try:
  31. # 发送 POST 请求
  32. response = requests.post(
  33. xiaoniangao_view_api,
  34. headers=headers,
  35. json=payload # 自动将字典转换为 JSON
  36. )
  37. # 检查 HTTP 状态码
  38. if response.status_code == 200:
  39. # 解析 JSON 响应
  40. result = response.json()
  41. # 提取关键字段
  42. code = result.get("code")
  43. msg = result.get("msg")
  44. # 业务逻辑处理(示例)
  45. if code == 0:
  46. print("请求成功")
  47. video_history(content_id)
  48. else:
  49. print(f"{xiaoniangao_view_api}请求失败,错误码: {code}, 消息: {msg}")
  50. else:
  51. print(f"{xiaoniangao_view_api}HTTP 请求失败,状态码: {response.status_code}")
  52. except requests.exceptions.RequestException as e:
  53. print(f"{xiaoniangao_view_api}请求异常: {e}")
  54. except json.JSONDecodeError:
  55. print(f"{xiaoniangao_view_api}响应不是有效的 JSON 格式")
  56. def video_history(video_view_lists):
  57. headers = {
  58. "Content-Type": "application/json"
  59. }
  60. payload = {
  61. "content_ids": video_view_lists
  62. }
  63. try:
  64. # 发送 POST 请求
  65. response = requests.post(
  66. xiaoniangao_history_api,
  67. headers=headers,
  68. json=payload # 自动将字典转换为 JSON
  69. )
  70. # 检查 HTTP 状态码
  71. if response.status_code == 200:
  72. # 解析 JSON 响应
  73. result = response.json()
  74. # 提取关键字段
  75. code = result.get("code")
  76. msg = result.get("msg")
  77. # 业务逻辑处理(示例)
  78. if code == 0:
  79. print("请求成功")
  80. else:
  81. print(f"{xiaoniangao_history_api}请求失败,错误码: {code}, 消息: {msg}")
  82. else:
  83. print(f"{xiaoniangao_history_api}HTTP 请求失败,状态码: {response.status_code}")
  84. except requests.exceptions.RequestException as e:
  85. print(f"{xiaoniangao_history_api}请求异常: {e}")
  86. except json.JSONDecodeError:
  87. print(f"{xiaoniangao_history_api}响应不是有效的 JSON 格式")
  88. class XNGTJLRecommend(object):
  89. """
  90. 小年糕推荐流
  91. """
  92. def __init__(self, platform, mode, rule_dict, user_list, env="prod"):
  93. self.limit_flag = False
  94. self.platform = platform
  95. self.mode = mode
  96. self.rule_dict = rule_dict
  97. self.user_list = user_list
  98. self.env = env
  99. self.download_cnt = 0
  100. self.mq = MQ(topic_name="topic_crawler_etl_" + self.env)
  101. self.expire_flag = False
  102. self.aliyun_log = AliyunLogger(mode=self.mode, platform=self.platform)
  103. self.mysql = MysqlHelper(mode=self.mode, platform=self)
  104. def get_video_duration(self, video_link: str) -> int:
  105. cap = cv2.VideoCapture(video_link)
  106. if cap.isOpened():
  107. rate = cap.get(5)
  108. frame_num = cap.get(7)
  109. duration = int(frame_num / rate)
  110. return duration
  111. return 0
  112. def get_recommend_list(self):
  113. print("小年糕推荐流开始")
  114. """
  115. 获取推荐页视频
  116. """
  117. headers = {
  118. 'Content-Type': 'application/json'
  119. }
  120. data_rule = FsData()
  121. title_rule = data_rule.get_title_rule()
  122. # for i in range(3):
  123. for i in range(6):
  124. url = "http://8.217.192.46:8889/crawler/xiao_nian_gao_plus/recommend"
  125. payload = json.dumps({})
  126. response = requests.request("POST", url, headers=headers, data=payload)
  127. response = response.json()
  128. if response['code'] != 0:
  129. self.aliyun_log.logging(
  130. code="3000",
  131. message="抓取单条视频失败,请求失败"
  132. ),
  133. return
  134. video_view_lists = []
  135. for index, video_obj in enumerate(response['data']['data'], 1):
  136. try:
  137. self.aliyun_log.logging(
  138. code="1001", message="扫描到一条视频", data=video_obj
  139. )
  140. vid = video_obj['id']
  141. video_view_lists.append(str(vid))
  142. self.process_video_obj(video_obj, title_rule)
  143. except Exception as e:
  144. self.aliyun_log.logging(
  145. code="3000",
  146. message="抓取单条视频失败, 该视频位于第{}页第{}条报错原因是{}".format(
  147. 1, index, e
  148. ),
  149. )
  150. if self.limit_flag:
  151. return
  152. video_history(video_view_lists)
  153. time.sleep(random.randint(5, 10))
  154. def process_video_obj(self, video_obj, title_rule):
  155. """
  156. 处理视频
  157. :param video_obj:
  158. """
  159. time.sleep(random.randint(3, 8))
  160. trace_id = self.platform + str(uuid.uuid1())
  161. our_user = random.choice(self.user_list)
  162. item = VideoItem()
  163. vid = video_obj['id']
  164. mid = int(video_obj['user']['mid'])
  165. print(f"vid={vid},mid={mid}")
  166. try:
  167. mid = int(video_obj['user']['mid'])
  168. print(f"id:{mid}")
  169. user_name = video_obj['user']['nick']
  170. avatar_url = video_obj['user']['hurl']
  171. sql = Sql()
  172. max_id = sql.select_id(mid)
  173. if max_id:
  174. sql.update_name_url(mid, avatar_url, user_name)
  175. else:
  176. time.sleep(1)
  177. link = sql.select_id_status(mid)
  178. if link:
  179. sql.insert_name_url(mid, avatar_url, user_name)
  180. print(f"开始写入{mid}")
  181. xng_in_video_data(json.dumps({"mid": mid}))
  182. except Exception as e:
  183. print(f"写入异常{e}")
  184. pass
  185. url = video_obj["v_url"]
  186. duration = self.get_video_duration(url)
  187. item.add_video_info("video_id", video_obj["id"])
  188. item.add_video_info("video_title", video_obj["title"])
  189. item.add_video_info("play_cnt", int(video_obj["play_pv"]))
  190. item.add_video_info("publish_time_stamp", int(int(video_obj["t"]) / 1000))
  191. item.add_video_info("out_user_id", video_obj["id"])
  192. item.add_video_info("cover_url", video_obj["url"])
  193. item.add_video_info("like_cnt", 0)
  194. item.add_video_info("share_cnt", int(video_obj["share"]))
  195. item.add_video_info("comment_cnt", int(video_obj["comment_count"]))
  196. item.add_video_info("video_url", video_obj["v_url"])
  197. item.add_video_info("out_video_id", video_obj["id"])
  198. item.add_video_info("duration", int(duration))
  199. item.add_video_info("platform", self.platform)
  200. item.add_video_info("strategy", self.mode)
  201. item.add_video_info("session", "{}-{}".format(self.platform, int(time.time())))
  202. item.add_video_info("user_id", our_user["uid"])
  203. item.add_video_info("user_name", our_user["nick_name"])
  204. mq_obj = item.produce_item()
  205. pipeline = PiaoQuanPipeline(
  206. platform=self.platform,
  207. mode=self.mode,
  208. rule_dict=self.rule_dict,
  209. env=self.env,
  210. item=mq_obj,
  211. trace_id=trace_id,
  212. )
  213. if pipeline.process_item():
  214. title_list = title_rule.split(",")
  215. title = video_obj["title"]
  216. contains_keyword = any(keyword in title for keyword in title_list)
  217. if contains_keyword:
  218. new_title = GPT4oMini.get_ai_mini_title(title)
  219. if new_title:
  220. item.add_video_info("video_title", new_title)
  221. current_time = datetime.now()
  222. formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
  223. values = [
  224. [
  225. video_obj["v_url"],
  226. video_obj["url"],
  227. title,
  228. new_title,
  229. formatted_time,
  230. ]
  231. ]
  232. FeishuUtils.insert_columns("U5dXsSlPOhiNNCtEfgqcm1iYnpf", "D1nVxQ", "ROWS", 1, 2)
  233. time.sleep(0.5)
  234. FeishuUtils.update_values("U5dXsSlPOhiNNCtEfgqcm1iYnpf", "D1nVxQ", "A2:Z2", values)
  235. self.mq.send_msg(mq_obj)
  236. video_view(vid, mid)
  237. self.aliyun_log.logging(code="1002", message="成功发送至 ETL", data=mq_obj)
  238. if self.download_cnt >= int(
  239. self.rule_dict.get("videos_cnt", {}).get("min", 200)
  240. ):
  241. self.limit_flag = True
  242. """
  243. 查询用户id是否存在
  244. """
  245. def select_id(self, uid):
  246. sql = f""" select uid from xng_uid where uid = "{uid}"; """
  247. db = MysqlHelper()
  248. repeat_video = db.select(sql=sql)
  249. if repeat_video:
  250. return True
  251. return False
  252. """
  253. 查询用户id是否之前已添加过
  254. """
  255. def select_id_status(self, uid):
  256. sql = f""" select uid from crawler_user_v3 where link = "{uid}"; """
  257. db = MysqlHelper()
  258. repeat_video = db.select(sql=sql)
  259. if repeat_video:
  260. return False
  261. return True
  262. def run(self):
  263. self.get_recommend_list()
  264. if __name__ == '__main__':
  265. J = XNGTJLRecommend(
  266. platform="xiaonianggaotuijianliu",
  267. mode="recommend",
  268. rule_dict={},
  269. user_list=[{'uid': "123456", 'nick_name': "xiaoxiao"}],
  270. )
  271. J.get_recommend_list()
  272. # J.logic()