process_data.py 8.7 KB

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