zhongqingkandian_author.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import os
  2. import sys
  3. import json
  4. import random
  5. import uuid
  6. import time
  7. import traceback
  8. from datetime import datetime
  9. import requests
  10. sys.path.append(os.getcwd())
  11. from application.common.feishu import FsData
  12. from application.common.feishu.feishu_utils import FeishuUtils
  13. from application.common.gpt import GPT4oMini
  14. from application.common.messageQueue import MQ
  15. from application.common.log import AliyunLogger
  16. from application.functions.zqkd_db_redis import DatabaseOperations, RedisOperations
  17. from application.items import VideoItem
  18. from application.pipeline import PiaoQuanPipeline
  19. from application.common.log import Local
  20. class ZhongQingKanDianAuthor:
  21. API_BASE_URL = "http://8.217.192.46:8889"
  22. COMMON_HEADERS = {
  23. "Content-Type": "application/json"
  24. }
  25. # 最大重试次数
  26. MAX_RETRIES = 3
  27. # 最大等待时长
  28. TIMEOUT = 30
  29. def __init__(self, platform, mode, rule_dict, user_list, env="prod"):
  30. """
  31. 初始化
  32. :param platform: 平台名称 zhongqingkandian
  33. :param mode: 运行模式 recommend
  34. :param rule_dict: 规则字典,包含视频数量限制、时长限制等规则 [{"videos_cnt":{"min":100,"max":0}},{"duration":{"min":30,"max":1200}}]
  35. :param user_list: 用户列表
  36. :param env: 运行环境,默认为 "prod"
  37. """
  38. self.limit_flag = True
  39. self.platform = platform
  40. self.mode = mode
  41. self.rule_dict = rule_dict
  42. self.user_list = user_list
  43. self.env = env
  44. self.download_cnt = 0
  45. self.mq = MQ(topic_name="topic_crawler_etl_" + self.env)
  46. self.expire_flag = False
  47. self.aliyun_log = AliyunLogger(mode=self.mode, platform=self.platform)
  48. self.db_ops = DatabaseOperations(mode=mode, platform=platform)
  49. self.redis_ops = RedisOperations(mode=mode, platform=platform)
  50. data_rule = FsData()
  51. self.title_rule = data_rule.get_title_rule()
  52. self.LocalLog = Local.logger(self.platform, self.mode)
  53. self.curses = 1
  54. result = self.redis_ops.get_last_scanned_id()
  55. self.last_scanned_id = 0 if result is None else int(result)
  56. self.zqkd_user_list = self.db_ops.select_user(self.last_scanned_id)
  57. self.LocalLog.info(f"获取到的用户列表:{self.zqkd_user_list} \n 昨天最后扫描的用户ID{self.last_scanned_id}")
  58. self.session = requests.session()
  59. def send_request(self, path, data):
  60. """
  61. 同步发送 POST 请求到指定路径,带有重试机制。
  62. :param path: 请求的 API 路径
  63. :param data: 请求的数据
  64. :return: 响应的 JSON 数据,如果请求失败则返回 None
  65. """
  66. full_url = f"{self.API_BASE_URL}{path}"
  67. for retry in range(self.MAX_RETRIES):
  68. try:
  69. response = self.session.post(full_url, data=data, timeout=self.TIMEOUT, headers=self.COMMON_HEADERS)
  70. response.raise_for_status()
  71. self.LocalLog.info(f"{path}响应数据:{response.json()}")
  72. return response.json()
  73. except Exception as e:
  74. tb_info = traceback.format_exc()
  75. self.LocalLog.info(f"{path}请求失败:{e} \n{tb_info}")
  76. self.aliyun_log.logging(
  77. code="3000",
  78. message=f"请求 {path} 失败,错误信息: {str(e)}",
  79. data={"path": path}
  80. )
  81. time.sleep(5)
  82. return None
  83. def is_response_valid(self, resp, url):
  84. """
  85. 检查响应是否有效(状态码为 0 表示有效)。
  86. :param resp: 响应数据
  87. :param url: 请求的 URL
  88. :return: 如果响应有效则返回响应数据,否则返回 None
  89. """
  90. try:
  91. if resp and resp.get('code') != 0:
  92. self.aliyun_log.logging(
  93. code="3000",
  94. message=f"抓取{url}失败,请求失败,响应:{resp}"
  95. )
  96. self.LocalLog.info(f"{url}请求失败,响应:{resp}")
  97. return None
  98. return resp
  99. except Exception as e:
  100. tb_info = traceback.format_exc()
  101. self.aliyun_log.logging(
  102. code="3000",
  103. message=f"检查响应有效性时出错,错误信息: {str(e)}",
  104. data={"url": url, "resp": resp}
  105. )
  106. self.LocalLog.info(f"检查 {url} 响应有效性时出错:{e} \n{tb_info}")
  107. return None
  108. def req_user_list(self, account_id):
  109. """
  110. 请求与指定内容 ID 相关的推荐列表。
  111. :param
  112. :return: 相关推荐视频列表的有效响应数据,如果请求失败则返回 None
  113. """
  114. try:
  115. url = '/crawler/zhong_qing_kan_dian/blogger'
  116. body = json.dumps({
  117. "account_id": f"{account_id}",
  118. "content_type": "全部",
  119. "cursor": f"{self.curses}"
  120. })
  121. self.LocalLog.info(f"开始请求用户视频列表{body}")
  122. resp = self.send_request(url, body)
  123. return self.is_response_valid(resp, url)
  124. except Exception as e:
  125. tb_info = traceback.format_exc()
  126. self.aliyun_log.logging(
  127. code="1004",
  128. message=f"请求相关推荐视频列表时发生异常,错误信息: {str(e)}",
  129. data={"url": url}
  130. )
  131. self.LocalLog.info(f"请求相关推荐视频列表 {url} 时发生异常:{e} \n{tb_info}")
  132. return None
  133. def req_detail(self, content_link, **kwargs):
  134. """
  135. 请求视频详情。
  136. :param content_link: 视频内容链接
  137. :param kwargs: 额外的视频信息
  138. :return: 无返回值,处理视频详情信息
  139. """
  140. try:
  141. self.LocalLog.info(f"开始请求视频详情,链接: {content_link}")
  142. url = '/crawler/zhong_qing_kan_dian/detail'
  143. body = json.dumps({
  144. "content_link": content_link
  145. })
  146. resp = self.send_request(url, body)
  147. if not self.is_response_valid(resp, url):
  148. return
  149. data = resp.get("data", {}).get("data", {})
  150. if data.get("content_type") != "video":
  151. self.aliyun_log.logging(
  152. code="3003",
  153. message=f"跳过非视频内容",
  154. data={"content_link": content_link}
  155. )
  156. self.LocalLog.info(f"跳过非视频内容,链接: {content_link}")
  157. return
  158. self.LocalLog.info(f"{content_link} 是视频")
  159. data.update(kwargs)
  160. self.process_video_obj(data)
  161. time.sleep(10)
  162. except Exception as e:
  163. tb_info = traceback.format_exc()
  164. self.aliyun_log.logging(
  165. code="1005",
  166. message=f"请求视频详情时发生异常,错误信息: {str(e)}",
  167. data={"content_link": content_link}
  168. )
  169. self.LocalLog.error(f"请求视频详情,链接 {content_link} 时发生异常:{e} \n{tb_info}")
  170. def control_request_author(self):
  171. """
  172. 控制相关推荐视频列表的请求和处理流程。
  173. :return: 无返回值,根据下载数量限制控制流程
  174. """
  175. while self.limit_flag:
  176. try:
  177. self.download_cnt = self.db_ops.get_today_videos()
  178. if self.download_cnt >= self.rule_dict.get("videos_cnt", {}).get("min", 100):
  179. self.aliyun_log.logging(
  180. code="2010",
  181. message=f"今日已经达到最大量",
  182. data=self.download_cnt
  183. )
  184. self.LocalLog.info(f"当日视频已达到最大爬取量{self.download_cnt}")
  185. return
  186. self.LocalLog.info(f"开始用户视频列表的请求和处理流程,今日已爬 {self.download_cnt} 个视频")
  187. if not self.zqkd_user_list:
  188. self.LocalLog.info("没有用户数据")
  189. time.sleep(10)
  190. continue
  191. for user_info in self.zqkd_user_list:
  192. # if not self.limit_flag:
  193. # return
  194. current_id, user_id = user_info
  195. author_resp = self.req_user_list(user_id)
  196. if current_id > self.last_scanned_id:
  197. self.redis_ops.set_last_scanned_id(current_id)
  198. if not author_resp:
  199. continue
  200. author_data = author_resp.get("data", {})
  201. # 判断是否有下一页
  202. if not author_data["next_cursor"]:
  203. continue
  204. video_data = author_data.get("data", [])
  205. self.LocalLog.info(f"用户{user_id}第{self.curses}页数据长度{len(video_data)}")
  206. for video_obj in video_data:
  207. # if not self.limit_flag:
  208. # return
  209. video_content_link = video_obj.get("share_url")
  210. if video_content_link:
  211. self.req_detail(video_content_link, **video_obj)
  212. except Exception as e:
  213. tb_info = traceback.format_exc()
  214. self.aliyun_log.logging(
  215. code="3009",
  216. message=f"控制相关推荐视频请求和处理时发生异常,错误信息: {str(e)}",
  217. data={}
  218. )
  219. self.LocalLog.info(f"控制相关推荐视频请求和处理时发生异常:\n{tb_info}")
  220. def process_video_obj(self, video_obj):
  221. """
  222. 处理视频对象,包括检查视频时长、用户信息、保存数据等操作。
  223. :param video_obj: 视频对象,包含视频的各种信息
  224. :return: 无返回值,完成视频对象的处理
  225. """
  226. try:
  227. video_duration = video_obj["video_url_list"][0]['video_duration']
  228. video_id = video_obj['channel_content_id']
  229. # 检查视频ID是否存在
  230. if self.redis_ops.check_video_id_exists(video_id):
  231. self.aliyun_log.logging(
  232. code="3004",
  233. message=f"重复视频ID:{video_id}"
  234. )
  235. self.LocalLog.info(f"重复视频ID: {video_id}")
  236. return
  237. our_user = random.choice(self.user_list)
  238. trace_id = self.platform + str(uuid.uuid1())
  239. item = VideoItem()
  240. # account_id = video_obj["channel_account_id"]
  241. # account_name = video_obj["channel_account_name"]
  242. # account_avatar = video_obj["avatar"]
  243. # # 检查用户ID是否存在
  244. # """
  245. # 需要改为判断redis
  246. # """
  247. # is_repeat_user = self.db_ops.check_user_id(account_id)
  248. # if is_repeat_user:
  249. # # 更新用户信息,使用异步方法并等待结果
  250. # self.LocalLog.info(f"用户{account_id}已经存在数据库中")
  251. # self.db_ops.update_user(account_id, account_name, account_avatar)
  252. # else:
  253. # self.LocalLog.info(f"用户{account_id}没在数据库中")
  254. # # 插入用户信息,使用异步方法并等待结果
  255. # self.db_ops.insert_user(account_id, account_name, account_avatar)
  256. # self.redis_ops.add_user_data("task:zqkd_user_id", json.dumps({"uid": account_id}))
  257. # self.aliyun_log.logging(code="1007", message=f"用户数据写入成功,用户ID:{account_id}")
  258. # self.LocalLog.info(f"用户数据写入成功,用户ID: {account_id}")
  259. if video_duration > self.rule_dict.get("duration", {}).get("max",
  260. 1200) or video_duration < self.rule_dict.get(
  261. "duration", {}).get("min", 30):
  262. self.aliyun_log.logging(
  263. code="3005",
  264. message=f"视频时长不满足条件[>=30s&<=1200s]视频ID:{video_obj['channel_content_id']},视频时长:{video_duration}"
  265. )
  266. self.LocalLog.info(
  267. f"视频时长不满足条件,视频ID: {video_obj['channel_content_id']}, 视频时长: {video_duration}")
  268. return
  269. item.add_video_info("video_id", video_obj['channel_content_id'])
  270. item.add_video_info("video_title", video_obj["title"])
  271. item.add_video_info("play_cnt", self.convert_number(video_obj["read_num"]))
  272. item.add_video_info("publish_time_stamp", int(int(video_obj["publish_timestamp"]) / 1000))
  273. item.add_video_info("out_user_id", video_obj["channel_account_id"])
  274. item.add_video_info("cover_url", video_obj["image_url_list"][0]['image_url'])
  275. item.add_video_info("like_cnt", 0)
  276. item.add_video_info("collection_cnt", 0)
  277. item.add_video_info("share_cnt", 0)
  278. item.add_video_info("comment_cnt", 0)
  279. item.add_video_info("video_url", video_obj["video_url_list"][0]['video_url'])
  280. item.add_video_info("out_video_id", int(video_obj["channel_content_id"]))
  281. item.add_video_info("duration", video_obj["video_url_list"][0]['video_duration'])
  282. item.add_video_info("platform", self.platform)
  283. item.add_video_info("strategy", self.mode)
  284. item.add_video_info("session", f"{self.platform}-{int(time.time())}")
  285. item.add_video_info("user_id", our_user["uid"])
  286. item.add_video_info("user_name", our_user["nick_name"])
  287. mq_obj = item.produce_item()
  288. pipeline = PiaoQuanPipeline(
  289. platform=self.platform,
  290. mode=self.mode,
  291. rule_dict=self.rule_dict,
  292. env=self.env,
  293. item=mq_obj,
  294. trace_id=trace_id
  295. )
  296. if pipeline.process_item():
  297. title_list = self.title_rule.split(",")
  298. title = video_obj["title"]
  299. contains_keyword = any(keyword in title for keyword in title_list)
  300. if contains_keyword:
  301. new_title = GPT4oMini.get_ai_mini_title(title)
  302. if new_title:
  303. item.add_video_info("video_title", new_title)
  304. current_time = datetime.now()
  305. formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
  306. values = [
  307. [
  308. video_obj["video_url_list"][0]['video_url'],
  309. video_obj["image_url_list"][0]['image_url'],
  310. title,
  311. new_title,
  312. formatted_time,
  313. ]
  314. ]
  315. FeishuUtils.insert_columns("U5dXsSlPOhiNNCtEfgqcm1iYnpf", "v8S6nL", "ROWS", 1, 2)
  316. time.sleep(0.5)
  317. FeishuUtils.update_values("U5dXsSlPOhiNNCtEfgqcm1iYnpf", "v8S6nL", "A2:Z2", values)
  318. self.download_cnt += 1
  319. self.mq.send_msg(mq_obj)
  320. # 保存视频ID
  321. self.redis_ops.save_video_id(video_obj['channel_content_id'])
  322. if self.download_cnt >= self.rule_dict.get("videos_cnt", {}).get("min", 300) and self.zqkd_user_list:
  323. self.LocalLog.info("视频数量已达到预期")
  324. # 判断视频数量达到预期且用户列表没有轮训完
  325. # self.redis_ops.set_last_scanned_id(self.last_scanned_id)
  326. self.limit_flag = False
  327. elif not self.zqkd_user_list:
  328. # 如果数据没达到预期数量,则重新开始扫用户数据,扫所有用户下一页的数据,直到数量达到预期
  329. self.LocalLog.info("扫描到最后一个用户")
  330. self.redis_ops.set_last_scanned_id(0)
  331. self.curses += 1
  332. except Exception as e:
  333. tb_info = traceback.format_exc()
  334. self.aliyun_log.logging(
  335. code="1005",
  336. message=f"处理视频对象时发生异常,错误信息: {str(e)}",
  337. data={"video_obj": video_obj}
  338. )
  339. self.LocalLog.error(f"处理视频对象时发生异常: {e}\n{tb_info}")
  340. def convert_number(self,s):
  341. """解析数字字符串,处理包含'万'的情况"""
  342. if isinstance(s, int): # 如果已经是int,直接返回
  343. return s
  344. elif isinstance(s, str): # 如果是字符串,处理'万'
  345. if '万' in s:
  346. try:
  347. num = float(s.strip('万')) * 10000
  348. return int(num) if num.is_integer() else num # 整数返回int,小数返回float
  349. except ValueError:
  350. print(f"无法将 '{s}' 转换为有效的数字。")
  351. return 0 # 默认返回0或其他默认值
  352. else:
  353. try:
  354. return int(s) # 尝试转换为int
  355. except ValueError:
  356. try:
  357. return float(s) # 尝试转换为float
  358. except ValueError:
  359. print(f"'{s}' 不是有效的数字格式。")
  360. return 0 # 默认返回0或其他默认值
  361. else:
  362. print(f"不支持的类型: {type(s).__name__}")
  363. return 0 # 非int/str类型返回默认值
  364. def run(self):
  365. """
  366. 运行主流程,执行推荐视频和相关推荐视频的请求,直到达到下载数量限制。
  367. :return: 无返回值,程序运行的主逻辑
  368. """
  369. self.LocalLog.info("开始执行中青看点用户视频抓取...")
  370. self.control_request_author()
  371. if __name__ == '__main__':
  372. ZhongQingKanDianAuthor(
  373. platform="zhongqingkandian",
  374. mode="author",
  375. rule_dict={'videos_cnt': {'min': 2, 'max': 0}, 'duration': {'min': 30, 'max': 1200}},
  376. user_list=[{"uid": 81525568, "link": "中青看点推荐", "nick_name": "芸芸众生"}]
  377. ).run()