common.py 7.9 KB

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