common.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. """
  2. @author: luojunhui
  3. """
  4. import random
  5. import string
  6. import hashlib
  7. import math
  8. import statistics
  9. from scipy.stats import t
  10. from datetime import datetime, timezone, date, timedelta
  11. from typing import List
  12. from requests import RequestException
  13. from urllib.parse import urlparse, parse_qs
  14. from tenacity import (
  15. stop_after_attempt,
  16. wait_exponential,
  17. retry_if_exception_type,
  18. )
  19. from applications.config import name_map
  20. def str_to_md5(strings):
  21. """
  22. 字符串转化为 md5 值
  23. :param strings:
  24. :return:
  25. """
  26. # 将字符串转换为字节
  27. original_bytes = strings.encode("utf-8")
  28. # 创建一个md5 hash对象
  29. md5_hash = hashlib.md5()
  30. # 更新hash对象,传入原始字节
  31. md5_hash.update(original_bytes)
  32. # 获取16进制形式的MD5哈希值
  33. md5_value = md5_hash.hexdigest()
  34. return md5_value
  35. def proxy():
  36. """
  37. 快代理
  38. """
  39. # 隧道域名:端口号
  40. tunnel = "j685.kdltps.com:15818"
  41. # 用户名密码方式
  42. username = "t14070979713487"
  43. password = "hqwanfvy"
  44. proxies = {
  45. "http": "http://%(user)s:%(pwd)s@%(proxy)s/"
  46. % {"user": username, "pwd": password, "proxy": tunnel},
  47. "https": "http://%(user)s:%(pwd)s@%(proxy)s/"
  48. % {"user": username, "pwd": password, "proxy": tunnel},
  49. }
  50. return proxies
  51. def async_proxy():
  52. return {
  53. "url": "http://j685.kdltps.com:15818",
  54. "username": "t14070979713487",
  55. "password": "hqwanfvy",
  56. }
  57. def request_retry(retry_times, min_retry_delay, max_retry_delay):
  58. """
  59. :param retry_times:
  60. :param min_retry_delay:
  61. :param max_retry_delay:
  62. """
  63. common_retry = dict(
  64. stop=stop_after_attempt(retry_times),
  65. wait=wait_exponential(min=min_retry_delay, max=max_retry_delay),
  66. retry=retry_if_exception_type((RequestException, TimeoutError)),
  67. reraise=True, # 重试耗尽后重新抛出异常
  68. )
  69. return common_retry
  70. def yield_batch(data, batch_size):
  71. """
  72. 生成批次数据
  73. :param data:
  74. :param batch_size:
  75. :return:
  76. """
  77. for i in range(0, len(data), batch_size):
  78. yield data[i : i + batch_size]
  79. def extract_root_source_id(path: str) -> dict:
  80. """
  81. 提取path参数
  82. :param path:
  83. :return:
  84. """
  85. params = parse_qs(urlparse(path).query)
  86. jump_page = params.get("jumpPage", [None])[0]
  87. if jump_page:
  88. params2 = parse_qs(jump_page)
  89. res = {
  90. "video_id": params2["pages/user-videos?id"][0],
  91. "root_source_id": params2["rootSourceId"][0],
  92. }
  93. return res
  94. else:
  95. return {}
  96. def show_desc_to_sta(show_desc):
  97. def decode_show_v(show_v):
  98. """
  99. :param show_v:
  100. :return:
  101. """
  102. foo = show_v.replace("千", "e3").replace("万", "e4").replace("亿", "e8")
  103. foo = eval(foo)
  104. return int(foo)
  105. def decode_show_k(show_k):
  106. """
  107. :param show_k:
  108. :return:
  109. """
  110. this_dict = {
  111. "阅读": "show_view_count", # 文章
  112. "看过": "show_view_count", # 图文
  113. "观看": "show_view_count", # 视频
  114. "赞": "show_like_count",
  115. "付费": "show_pay_count",
  116. "赞赏": "show_zs_count",
  117. }
  118. if show_k not in this_dict:
  119. print(f"error from decode_show_k, show_k not found: {show_k}")
  120. return this_dict.get(show_k, "show_unknown")
  121. show_desc = show_desc.replace("+", "")
  122. sta = {}
  123. for show_kv in show_desc.split("\u2004\u2005"):
  124. if not show_kv:
  125. continue
  126. show_k, show_v = show_kv.split("\u2006")
  127. k = decode_show_k(show_k)
  128. v = decode_show_v(show_v)
  129. sta[k] = v
  130. res = {
  131. "show_view_count": sta.get("show_view_count", 0),
  132. "show_like_count": sta.get("show_like_count", 0),
  133. "show_pay_count": sta.get("show_pay_count", 0),
  134. "show_zs_count": sta.get("show_zs_count", 0),
  135. }
  136. return res
  137. def generate_gzh_id(url):
  138. biz = url.split("biz=")[1].split("&")[0]
  139. idx = url.split("&idx=")[1].split("&")[0]
  140. sn = url.split("&sn=")[1].split("&")[0]
  141. url_bit = "{}-{}-{}".format(biz, idx, sn).encode()
  142. md5_hash = hashlib.md5()
  143. md5_hash.update(url_bit)
  144. md5_value = md5_hash.hexdigest()
  145. return md5_value
  146. def timestamp_to_str(timestamp, string_format="%Y-%m-%d %H:%M:%S") -> str:
  147. """
  148. :param string_format:
  149. :param timestamp:
  150. """
  151. dt_object = (
  152. datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone()
  153. )
  154. date_string = dt_object.strftime(string_format)
  155. return date_string
  156. def days_remaining_in_month():
  157. # 获取当前日期
  158. today = date.today()
  159. # 获取下个月的第一天
  160. if today.month == 12:
  161. next_month = today.replace(year=today.year + 1, month=1, day=1)
  162. else:
  163. next_month = today.replace(month=today.month + 1, day=1)
  164. # 计算本月最后一天(下个月第一天减去1天)
  165. last_day_of_month = next_month - timedelta(days=1)
  166. # 计算剩余天数
  167. remaining_days = (last_day_of_month - today).days
  168. return remaining_days
  169. def generate_task_trace_id():
  170. random_str = "".join(random.choices(string.ascii_lowercase + string.digits, k=16))
  171. return f"Task-{datetime.now().strftime('%Y%m%d%H%M%S')}-{random_str}"
  172. def ci_lower(data: List[int], conf: float = 0.95) -> float:
  173. """
  174. 计算data的置信区间下限
  175. """
  176. if len(data) < 2:
  177. raise ValueError("Sample length less than 2")
  178. n = len(data)
  179. mean = statistics.mean(data)
  180. std = statistics.stdev(data) / math.sqrt(n)
  181. # t 分位点(左侧):ppf 返回负值
  182. t_left = t.ppf((1 - conf) / 2, df=n - 1)
  183. return mean + t_left * std
  184. def get_task_chinese_name(data):
  185. """
  186. 通过输入任务详情信息获取任务名称
  187. """
  188. task_name = data['task_name']
  189. task_name_chinese = name_map.get(task_name, task_name)
  190. # account_method
  191. if task_name == 'crawler_gzh_articles':
  192. account_method = data.get('account_method', '')
  193. account_method = account_method.replace("account_association", "账号联想").replace("search", "")
  194. crawl_mode = data.get('crawl_mode', '')
  195. crawl_mode = crawl_mode.replace("search", "搜索").replace("account", "抓账号")
  196. strategy = data.get('strategy', '')
  197. return f"{task_name_chinese}\t{crawl_mode}\t{account_method}\t{strategy}"
  198. elif task_name == 'article_pool_cold_start':
  199. platform = data.get('platform')
  200. platform = platform.replace('toutiao', '今日头条').replace("weixin", "微信")
  201. strategy = data.get('strategy')
  202. strategy = strategy.replace("strategy", "策略")
  203. category_list = data.get('category_list', [])
  204. category_list = "、".join(category_list)
  205. crawler_methods = data.get('crawler_methods', [])
  206. crawler_methods = "、".join(crawler_methods)
  207. return f"{task_name_chinese}\t{platform}\t{crawler_methods}\t{category_list}\t{strategy}"
  208. else:
  209. return task_name_chinese