common.py 7.4 KB

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