tools.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 decode_show_v(show_v: str) -> int:
  99. if not show_v:
  100. return 0
  101. show_v = show_v.strip().lower()
  102. # 统一小数点(防 1,3k 这种)
  103. show_v = show_v.replace(",", ".")
  104. # 👇 核心:提取“数字 + 单位”
  105. match = re.search(r"(\d+(?:\.\d+)?)([a-z\u4e00-\u9fa5]*)", show_v)
  106. if not match:
  107. return 0
  108. num = float(match.group(1))
  109. unit = match.group(2)
  110. # 中文单位
  111. if "亿" in unit:
  112. num *= 1e8
  113. elif "万" in unit:
  114. num *= 1e4
  115. elif "千" in unit:
  116. num *= 1e3
  117. # 英文单位(重点)
  118. elif unit.startswith("k"):
  119. num *= 1e3
  120. elif unit.startswith("m"):
  121. num *= 1e6
  122. elif unit.startswith("b"):
  123. num *= 1e9
  124. return int(num)
  125. def generate_gzh_id(url):
  126. biz = url.split("biz=")[1].split("&")[0]
  127. idx = url.split("&idx=")[1].split("&")[0]
  128. sn = url.split("&sn=")[1].split("&")[0]
  129. url_bit = "{}-{}-{}".format(biz, idx, sn).encode()
  130. md5_hash = hashlib.md5()
  131. md5_hash.update(url_bit)
  132. md5_value = md5_hash.hexdigest()
  133. return md5_value
  134. def timestamp_to_str(timestamp, string_format="%Y-%m-%d %H:%M:%S") -> str:
  135. """
  136. :param string_format:
  137. :param timestamp:
  138. """
  139. dt_object = (
  140. datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone()
  141. )
  142. date_string = dt_object.strftime(string_format)
  143. return date_string
  144. def days_remaining_in_month():
  145. # 获取当前日期
  146. today = date.today()
  147. # 获取下个月的第一天
  148. if today.month == 12:
  149. next_month = today.replace(year=today.year + 1, month=1, day=1)
  150. else:
  151. next_month = today.replace(month=today.month + 1, day=1)
  152. # 计算本月最后一天(下个月第一天减去1天)
  153. last_day_of_month = next_month - timedelta(days=1)
  154. # 计算剩余天数
  155. remaining_days = (last_day_of_month - today).days
  156. return remaining_days
  157. def generate_task_trace_id():
  158. random_str = "".join(random.choices(string.ascii_lowercase + string.digits, k=16))
  159. return f"Task-{datetime.now().strftime('%Y%m%d%H%M%S')}-{random_str}"
  160. def ci_lower(data: List[int], conf: float = 0.95) -> float:
  161. """
  162. 计算data的置信区间下限
  163. """
  164. if len(data) < 2:
  165. raise ValueError("Sample length less than 2")
  166. n = len(data)
  167. mean = statistics.mean(data)
  168. std = statistics.stdev(data) / math.sqrt(n)
  169. # t 分位点(左侧):ppf 返回负值
  170. t_left = t.ppf((1 - conf) / 2, df=n - 1)
  171. return mean + t_left * std
  172. def fetch_from_odps(query):
  173. client = ODPS(
  174. access_id="LTAIWYUujJAm7CbH",
  175. secret_access_key="RfSjdiWwED1sGFlsjXv0DlfTnZTG1P",
  176. endpoint="http://service.cn.maxcompute.aliyun.com/api",
  177. project="loghubods",
  178. )
  179. with client.execute_sql(query).open_reader() as reader:
  180. if reader:
  181. return [item for item in reader]
  182. else:
  183. return []
  184. def init_odps_client():
  185. return ODPS(
  186. access_id="LTAIWYUujJAm7CbH",
  187. secret_access_key="RfSjdiWwED1sGFlsjXv0DlfTnZTG1P",
  188. endpoint="http://service.cn.maxcompute.aliyun.com/api",
  189. project="loghubods",
  190. )
  191. def upload_to_oss(local_video_path, oss_key):
  192. """
  193. 把视频上传到 oss
  194. :return:
  195. """
  196. access_key_id = "LTAIP6x1l3DXfSxm"
  197. access_key_secret = "KbTaM9ars4OX3PMS6Xm7rtxGr1FLon"
  198. endpoint = "oss-cn-hangzhou.aliyuncs.com"
  199. bucket_name = "art-pubbucket"
  200. bucket = oss2.Bucket(
  201. oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name
  202. )
  203. bucket.put_object_from_file(key=oss_key, filename=local_video_path)
  204. return oss_key