process_data.py 8.8 KB

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