process_data.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """
  2. process the data to satisfy the lightgbm
  3. """
  4. import sys
  5. import os
  6. import json
  7. import asyncio
  8. import argparse
  9. import time
  10. from tqdm import tqdm
  11. import jieba.analyse
  12. from concurrent.futures.thread import ThreadPoolExecutor
  13. sys.path.append(os.getcwd())
  14. from functions import generate_label_date, generate_daily_strings, MysqlClient, MySQLClientSpider
  15. class DataProcessor(object):
  16. """
  17. Insert some information to lightgbm_data
  18. """
  19. def __init__(self, ):
  20. self.client = MysqlClient()
  21. self.client_spider = MySQLClientSpider()
  22. self.label_data = {}
  23. def generate_train_label(self, item, y_ori_data, cate):
  24. """
  25. 生成训练数据,用 np.array矩阵的方式返回,
  26. :return: x_train, 训练数据, y_train, 训练 label
  27. """
  28. video_id = item["video_id"]
  29. dt = item["dt"]
  30. useful_features = [
  31. "uid",
  32. "type",
  33. "channel",
  34. "fans",
  35. "view_count_user_30days",
  36. "share_count_user_30days",
  37. "return_count_user_30days",
  38. "rov_user",
  39. "str_user",
  40. "out_user_id",
  41. "mode",
  42. "out_play_cnt",
  43. "out_like_cnt",
  44. "out_share_cnt",
  45. "out_collection_cnt",
  46. ]
  47. spider_features = [
  48. "channel",
  49. "out_user_id",
  50. "mode",
  51. "out_play_cnt",
  52. "out_like_cnt",
  53. "out_share_cnt"
  54. ]
  55. user_features = [
  56. "uid",
  57. "channel",
  58. "fans",
  59. "view_count_user_30days",
  60. "share_count_user_30days",
  61. "return_count_user_30days",
  62. "rov_user",
  63. "str_user"
  64. ]
  65. match self.ll:
  66. case "all":
  67. item_features = [item[i] for i in useful_features]
  68. case "user":
  69. if item['type'] == "userupload":
  70. item_features = [item[i] for i in user_features]
  71. else:
  72. return None, None
  73. case "spider":
  74. if item['type'] == "spider":
  75. item_features = [item[i] for i in spider_features]
  76. lop, duration = self.cal_lop(video_id)
  77. item_features.append(lop)
  78. item_features.append(duration)
  79. else:
  80. return None, None
  81. keywords_textrank = self.title_processor(video_id)
  82. if keywords_textrank:
  83. for i in range(3):
  84. try:
  85. item_features.append(keywords_textrank[i])
  86. except:
  87. item_features.append(None)
  88. else:
  89. item_features.append(None)
  90. item_features.append(None)
  91. item_features.append(None)
  92. label_dt = generate_label_date(dt)
  93. label_obj = y_ori_data.get(label_dt, {}).get(video_id)
  94. if label_obj:
  95. label = int(label_obj[cate]) if label_obj[cate] else 0
  96. else:
  97. label = 0
  98. return label, item_features
  99. def producer(self):
  100. """
  101. 生成数据
  102. :return:none
  103. """
  104. # 把 label, video_title, daily_dt_str, 存储到 mysql 数据库中去
  105. label_path = "data/train_data/daily-label-20240101-20240325.json"
  106. with open(label_path, encoding="utf-8") as f:
  107. self.label_data = json.loads(f.read())
  108. def read_title(client, video_id):
  109. """
  110. read_title_from mysql
  111. """
  112. sql = f"""SELECT title from wx_video where id = {video_id};"""
  113. # print("title", sql)
  114. try:
  115. title = client.select(sql)[0][0]
  116. return title
  117. except Exception as e:
  118. print(video_id, "\t", e)
  119. return ""
  120. def generate_label(video_id, hourly_dt_str, label_info):
  121. """
  122. generate label daily_dt_str for mysql
  123. :param label_info:
  124. :param video_id:
  125. :param hourly_dt_str:
  126. :return: label, daily_dt_str
  127. """
  128. label_dt = generate_label_date(hourly_dt_str)
  129. label_obj = label_info.get(label_dt, {}).get(video_id)
  130. if label_obj:
  131. label = int(label_obj["total_return"]) if label_obj["total_return"] else 0
  132. print(label)
  133. else:
  134. label = 0
  135. return label, label_dt
  136. def process_info(item_):
  137. """
  138. Insert data into MySql
  139. :param item_:
  140. """
  141. video_id, hour_dt = item_
  142. label_info = self.label_data
  143. title = read_title(client=self.client, video_id=video_id)
  144. label, dt_daily = generate_label(video_id, hour_dt, label_info)
  145. insert_sql = f"""UPDATE lightgbm_data set video_title = '{title}', label = '{label}', daily_dt_str = '{dt_daily}' where video_id = '{video_id}';"""
  146. print(insert_sql)
  147. self.client_spider.update(insert_sql)
  148. select_sql = "SELECT video_id, hour_dt_str FROM lightgbm_data where label = 0 and hour_dt_str < '20240327';"
  149. init_data_tuple = self.client_spider.select(select_sql)
  150. init_list = list(init_data_tuple)
  151. for item in tqdm(init_list[:100]):
  152. # print(item)
  153. process_info(item)
  154. time.sleep(0.5)
  155. # with ThreadPoolExecutor(max_workers=10) as Pool:
  156. # Pool.map(process_info, init_list)
  157. class SpiderProcess(object):
  158. """
  159. Spider Data Process and Process data for lightgbm training
  160. """
  161. def __init__(self):
  162. self.client_spider = MySQLClientSpider()
  163. def spider_lop(self, video_id):
  164. """
  165. Spider lop = like / play
  166. :param video_id:
  167. :return:
  168. """
  169. sql = f"""SELECT like_cnt, play_cnt, duration from crawler_video where video_id = '{video_id}';"""
  170. try:
  171. like_cnt, play_cnt, duration = self.client_spider.select(sql)[0]
  172. lop = (like_cnt + 700) / (play_cnt + 18000)
  173. return lop, duration
  174. except Exception as e:
  175. print(video_id, "\t", e)
  176. return 0, 0
  177. def spider_data_produce(self):
  178. """
  179. 把 spider_duration 存储到数据库中
  180. :return:
  181. """
  182. return
  183. class UserProcess(object):
  184. """
  185. User Data Process
  186. """
  187. def __init__(self):
  188. self.client = MysqlClient()
  189. self.user_features = [
  190. "uid",
  191. "channel",
  192. "user_fans",
  193. "user_view_30",
  194. "user_share_30",
  195. "user_return_30",
  196. "user_rov",
  197. "user_str",
  198. "user_return_videos_30",
  199. "user_return_videos_3",
  200. "user_return_3",
  201. "user_view_3",
  202. "user_share_3",
  203. "address"
  204. ]
  205. def title_processor(self, video_id):
  206. """
  207. 通过 video_id 去获取title, 然后通过 title 再分词,把关键词作为 feature
  208. :param video_id: the video id
  209. :return: tag_list [tag, tag, tag, tag......]
  210. """
  211. sql = f"""SELECT title from wx_video where id = {video_id};"""
  212. try:
  213. title = self.client.select(sql)[0][0]
  214. keywords_textrank = jieba.analyse.textrank(title, topK=3)
  215. return list(keywords_textrank)
  216. except Exception as e:
  217. print(video_id, "\t", e)
  218. return []
  219. def user_data_process(self):
  220. """
  221. 把 user_return_3, user_view_3, user_share_3
  222. user_return_videos_3, user_return_videos_30
  223. address 存储到 mysql 数据库中
  224. :return:
  225. """
  226. user_path = '/data'
  227. if __name__ == "__main__":
  228. # D = DataProcessor()
  229. # D.producer()
  230. # parser = argparse.ArgumentParser() # 新建参数解释器对象
  231. # parser.add_argument("--mode")
  232. # parser.add_argument("--category")
  233. # parser.add_argument("--dtype", default="whole")
  234. # args = parser.parse_args()
  235. # mode = args.mode
  236. # category = args.category
  237. # dtype = args.dtype
  238. D = DataProcessor()
  239. D.producer()
  240. # if mode == "train":
  241. # print("Loading data and process for training.....")
  242. # D = DataProcessor(flag="train", ll=category)
  243. # D.producer("whole")
  244. # elif mode == "predict":
  245. # print("Loading data and process for prediction for each day......")
  246. # D = DataProcessor(flag="predict", ll=category)
  247. # if dtype == "single":
  248. # date_str = str(input("Please enter the date of the prediction"))
  249. # D.producer(date_str)
  250. # elif dtype == "days":
  251. # start_date_str = str(input("Please enter the start date of the prediction"))
  252. # end_date_str = str(input("Please enter the end date of the prediction"))
  253. # dt_list = generate_daily_strings(start_date=start_date_str, end_date=end_date_str)
  254. # for d in dt_list:
  255. # D.producer()