tools.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. """
  2. @author: luojunhui
  3. """
  4. import re
  5. import oss2
  6. import random
  7. import string
  8. import hashlib
  9. import math
  10. import statistics
  11. from scipy.stats import t
  12. from odps import ODPS
  13. from datetime import datetime, timezone, date, timedelta
  14. from typing import List
  15. from requests import RequestException
  16. from urllib.parse import urlparse, parse_qs
  17. from tenacity import (
  18. stop_after_attempt,
  19. wait_exponential,
  20. retry_if_exception_type,
  21. )
  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: str) -> int:
  100. """
  101. 解析数值,支持:
  102. - 1.2万 / 3千 / 5亿
  103. - 158 / 3
  104. - 2.3万阅读 / 158reads(自动提取数字)
  105. """
  106. if not show_v:
  107. return 0
  108. show_v = show_v.strip().lower()
  109. # 提取数字(支持小数)
  110. match = re.search(r"\d+(\.\d+)?", show_v)
  111. if not match:
  112. return 0
  113. num = float(match.group())
  114. # 单位换算(中文)
  115. if "亿" in show_v:
  116. num *= 1e8
  117. elif "万" in show_v:
  118. num *= 1e4
  119. elif "千" in show_v:
  120. num *= 1e3
  121. return int(num)
  122. def decode_show_k(show_k: str) -> str:
  123. """
  124. 统一 key 映射(支持中英文)
  125. """
  126. if not show_k:
  127. return "show_unknown"
  128. show_k = show_k.strip().lower()
  129. this_dict = {
  130. # 中文
  131. "阅读": "show_view_count",
  132. "看过": "show_view_count",
  133. "观看": "show_view_count",
  134. "赞": "show_like_count",
  135. "付费": "show_pay_count",
  136. "赞赏": "show_zs_count",
  137. # 英文
  138. "reads": "show_view_count",
  139. "views": "show_view_count",
  140. "likes": "show_like_count",
  141. "payments": "show_pay_count",
  142. "paid": "show_pay_count",
  143. }
  144. return this_dict.get(show_k, "show_unknown")
  145. if not show_desc:
  146. return {
  147. "show_view_count": 0,
  148. "show_like_count": 0,
  149. "show_pay_count": 0,
  150. "show_zs_count": 0,
  151. }
  152. # 去掉 "+"
  153. show_desc = show_desc.replace("+", "")
  154. sta = {}
  155. # 按分组分隔符切分(兼容不同空白字符)
  156. for show_kv in re.split(r"[\u2004\u2005]+", show_desc):
  157. if not show_kv.strip():
  158. continue
  159. # 再按 key-value 分隔符切
  160. parts = show_kv.split("\u2006")
  161. if len(parts) != 2:
  162. continue
  163. a, b = parts
  164. # 自动判断谁是 value(数字)
  165. if re.search(r"\d", a):
  166. show_v, show_k = a, b
  167. else:
  168. show_k, show_v = a, b
  169. k = decode_show_k(show_k)
  170. v = decode_show_v(show_v)
  171. if k != "show_unknown":
  172. sta[k] = v
  173. return {
  174. "show_view_count": sta.get("show_view_count", 0),
  175. "show_like_count": sta.get("show_like_count", 0),
  176. "show_pay_count": sta.get("show_pay_count", 0),
  177. "show_zs_count": sta.get("show_zs_count", 0),
  178. }
  179. def generate_gzh_id(url):
  180. biz = url.split("biz=")[1].split("&")[0]
  181. idx = url.split("&idx=")[1].split("&")[0]
  182. sn = url.split("&sn=")[1].split("&")[0]
  183. url_bit = "{}-{}-{}".format(biz, idx, sn).encode()
  184. md5_hash = hashlib.md5()
  185. md5_hash.update(url_bit)
  186. md5_value = md5_hash.hexdigest()
  187. return md5_value
  188. def timestamp_to_str(timestamp, string_format="%Y-%m-%d %H:%M:%S") -> str:
  189. """
  190. :param string_format:
  191. :param timestamp:
  192. """
  193. dt_object = (
  194. datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone()
  195. )
  196. date_string = dt_object.strftime(string_format)
  197. return date_string
  198. def days_remaining_in_month():
  199. # 获取当前日期
  200. today = date.today()
  201. # 获取下个月的第一天
  202. if today.month == 12:
  203. next_month = today.replace(year=today.year + 1, month=1, day=1)
  204. else:
  205. next_month = today.replace(month=today.month + 1, day=1)
  206. # 计算本月最后一天(下个月第一天减去1天)
  207. last_day_of_month = next_month - timedelta(days=1)
  208. # 计算剩余天数
  209. remaining_days = (last_day_of_month - today).days
  210. return remaining_days
  211. def generate_task_trace_id():
  212. random_str = "".join(random.choices(string.ascii_lowercase + string.digits, k=16))
  213. return f"Task-{datetime.now().strftime('%Y%m%d%H%M%S')}-{random_str}"
  214. def ci_lower(data: List[int], conf: float = 0.95) -> float:
  215. """
  216. 计算data的置信区间下限
  217. """
  218. if len(data) < 2:
  219. raise ValueError("Sample length less than 2")
  220. n = len(data)
  221. mean = statistics.mean(data)
  222. std = statistics.stdev(data) / math.sqrt(n)
  223. # t 分位点(左侧):ppf 返回负值
  224. t_left = t.ppf((1 - conf) / 2, df=n - 1)
  225. return mean + t_left * std
  226. def fetch_from_odps(query):
  227. client = ODPS(
  228. access_id="LTAIWYUujJAm7CbH",
  229. secret_access_key="RfSjdiWwED1sGFlsjXv0DlfTnZTG1P",
  230. endpoint="http://service.cn.maxcompute.aliyun.com/api",
  231. project="loghubods",
  232. )
  233. with client.execute_sql(query).open_reader() as reader:
  234. if reader:
  235. return [item for item in reader]
  236. else:
  237. return []
  238. def init_odps_client():
  239. return ODPS(
  240. access_id="LTAIWYUujJAm7CbH",
  241. secret_access_key="RfSjdiWwED1sGFlsjXv0DlfTnZTG1P",
  242. endpoint="http://service.cn.maxcompute.aliyun.com/api",
  243. project="loghubods",
  244. )
  245. def upload_to_oss(local_video_path, oss_key):
  246. """
  247. 把视频上传到 oss
  248. :return:
  249. """
  250. access_key_id = "LTAIP6x1l3DXfSxm"
  251. access_key_secret = "KbTaM9ars4OX3PMS6Xm7rtxGr1FLon"
  252. endpoint = "oss-cn-hangzhou.aliyuncs.com"
  253. bucket_name = "art-pubbucket"
  254. bucket = oss2.Bucket(
  255. oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name
  256. )
  257. bucket.put_object_from_file(key=oss_key, filename=local_video_path)
  258. return oss_key