process_data.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. """
  2. process the data to satisfy the lightgbm
  3. """
  4. import datetime
  5. import sys
  6. import os
  7. import json
  8. import asyncio
  9. import argparse
  10. import time
  11. from tqdm import tqdm
  12. import jieba.analyse
  13. import pandas as pd
  14. sys.path.append(os.getcwd())
  15. from functions import generate_label_date, generate_daily_strings, MysqlClient, MySQLClientSpider
  16. class DataProcessor(object):
  17. """
  18. Insert some information to lightgbm_data
  19. """
  20. def __init__(self, ):
  21. self.client = MysqlClient()
  22. self.client_spider = MySQLClientSpider()
  23. self.label_data = {}
  24. def producer(self):
  25. """
  26. 生成数据
  27. :return:none
  28. """
  29. # 把 label, video_title, daily_dt_str, 存储到 mysql 数据库中去
  30. label_path = "data/train_data/daily-label-20240326-20240331.json"
  31. with open(label_path, encoding="utf-8") as f:
  32. self.label_data = json.loads(f.read())
  33. def read_title(client, video_id):
  34. """
  35. read_title_from mysql
  36. """
  37. sql = f"""SELECT title from wx_video where id = {video_id};"""
  38. # print("title", sql)
  39. try:
  40. title = client.select(sql)[0][0]
  41. return title.strip()
  42. except Exception as e:
  43. print(video_id, "\t", e)
  44. return ""
  45. def generate_label(video_id, hourly_dt_str, label_info):
  46. """
  47. generate label daily_dt_str for mysql
  48. :param label_info:
  49. :param video_id:
  50. :param hourly_dt_str:
  51. :return: label, daily_dt_str
  52. """
  53. label_dt = generate_label_date(hourly_dt_str)
  54. label_obj = label_info.get(label_dt, {}).get(video_id)
  55. if label_obj:
  56. label = int(label_obj["total_return"]) if label_obj["total_return"] else 0
  57. # print(label)
  58. else:
  59. label = 0
  60. return label, label_dt
  61. def process_info(item_):
  62. """
  63. Insert data into MySql
  64. :param item_:
  65. """
  66. video_id, hour_dt = item_
  67. # print(type(video_id))
  68. label_info = self.label_data
  69. title = read_title(client=self.client, video_id=video_id)
  70. label, dt_daily = generate_label(str(video_id), hour_dt, label_info)
  71. insert_sql = f"""UPDATE lightgbm_data set video_title = '{title}', label = '{label}', daily_dt_str = '{dt_daily}' where video_id = '{video_id}';"""
  72. # print(insert_sql)
  73. self.client_spider.update(insert_sql)
  74. select_sql = "SELECT video_id, hour_dt_str FROM lightgbm_data where label is NULL and hour_dt_str >= '2024032700';"
  75. init_data_tuple = self.client_spider.select(select_sql)
  76. init_list = list(init_data_tuple)
  77. for item in tqdm(init_list):
  78. try:
  79. process_info(item)
  80. except Exception as e:
  81. print("操作失败", e)
  82. class SpiderProcess(object):
  83. """
  84. Spider Data Process and Process data for lightgbm training
  85. """
  86. def __init__(self):
  87. self.client_spider = MySQLClientSpider()
  88. self.spider_features = [
  89. "channel",
  90. "out_user_id",
  91. "mode",
  92. "out_play_cnt",
  93. "out_like_cnt",
  94. "out_share_cnt"
  95. ]
  96. def spider_lop(self, video_id):
  97. """
  98. Spider lop = like / play
  99. :param video_id:
  100. :return:
  101. """
  102. sql = f"""SELECT like_cnt, play_cnt, duration from crawler_video where video_id = '{video_id}';"""
  103. try:
  104. like_cnt, play_cnt, duration = self.client_spider.select(sql)[0]
  105. lop = (like_cnt + 700) / (play_cnt + 18000)
  106. return lop, duration
  107. except Exception as e:
  108. print(video_id, "\t", e)
  109. return 0, 0
  110. def spider_data_produce(self, flag, dt_time=None):
  111. """
  112. 把 spider_duration 存储到数据库中
  113. :return:
  114. """
  115. if flag == "train":
  116. select_sql = "SELECT video_id, video_title, label, channel, out_user_id, spider_mode, out_play_cnt, out_like_cnt, out_share_cnt FROM lightgbm_data WHERE type = 'spider' order by daily_dt_str;"
  117. des_path = "data/train_data/spider_train_{}".format(datetime.datetime.today().strftime("%Y%m%d"))
  118. elif flag == "predict":
  119. dt_time = datetime.datetime.strptime(dt_time, "%Y%m%d")
  120. three_date_before = dt_time + datetime.timedelta(days=4)
  121. temp_time = three_date_before.strftime("%Y%m%d")
  122. select_sql = f"""SELECT video_id, video_title, label, channel, out_user_id, spider_mode, out_play_cnt, out_like_cnt, out_share_cnt FROM lightgbm_data WHERE type = 'spider' and daily_dt_str = '{temp_time}';"""
  123. print(select_sql)
  124. des_path = "data/predict_data/predict_{}.json".format(dt_time.strftime("%Y%m%d"))
  125. else:
  126. return
  127. data_list = self.client_spider.select(select_sql)
  128. df = []
  129. for line in tqdm(data_list):
  130. try:
  131. temp = list(line)
  132. video_id = line[0]
  133. title = line[1]
  134. lop, duration = self.spider_lop(video_id)
  135. title_tags = list(jieba.analyse.textrank(title, topK=3))
  136. temp.append(lop)
  137. temp.append(duration)
  138. if title_tags:
  139. for i in range(3):
  140. try:
  141. temp.append(title_tags[i])
  142. except:
  143. temp.append(None)
  144. else:
  145. temp.append(None)
  146. temp.append(None)
  147. temp.append(None)
  148. df.append(temp[2:])
  149. except:
  150. continue
  151. df = pd.DataFrame(df, columns=['label', 'channel', 'out_user_id', 'mode', 'out_play_cnt', 'out_like_cnt',
  152. 'out_share_cnt', 'lop', 'duration', 'tag1', 'tag2', 'tag3'])
  153. df.to_json(des_path, orient='records')
  154. class UserProcess(object):
  155. """
  156. User Data Process
  157. """
  158. def __init__(self):
  159. self.client_spider = MySQLClientSpider()
  160. self.user_features = [
  161. "label",
  162. "uid",
  163. "channel",
  164. "user_fans",
  165. "user_view_30",
  166. "user_share_30",
  167. "user_return_30",
  168. "user_rov",
  169. "user_str",
  170. "user_return_videos_30",
  171. "user_return_videos_3",
  172. "user_return_3",
  173. "user_view_3",
  174. "user_share_3",
  175. "address",
  176. "tag1",
  177. "tag2",
  178. "tag3"
  179. ]
  180. def userinfo_to_mysql(self, start_date, end_date):
  181. """
  182. 把 user_return_3, user_view_3, user_share_3
  183. user_return_videos_3, user_return_videos_30
  184. address 存储到 mysql 数据库中
  185. :return:
  186. """
  187. user_path = 'data/train_data/daily-user-info-{}-{}.json'.format(start_date, end_date)
  188. with open(user_path) as f:
  189. data = json.loads(f.read())
  190. sql = "select video_id, hour_dt_str from lightgbm_data where type = 'userupload' and address is NULL;"
  191. dt_list = self.client_spider.select(sql)
  192. for item in tqdm(dt_list):
  193. video_id, dt = item
  194. dt = dt[:8]
  195. user_info_obj = data.get(dt, {}).get(str(video_id))
  196. if user_info_obj:
  197. try:
  198. video_id = user_info_obj['video_id']
  199. address = user_info_obj['address']
  200. return_3 = user_info_obj['return_3days']
  201. view_3 = user_info_obj['view_3days']
  202. share_3 = user_info_obj['share_3days']
  203. return_videos_3 = user_info_obj['3day_return_500_videos']
  204. return_videos_30 = user_info_obj['30day_return_2000_videos']
  205. update_sql = f"""UPDATE lightgbm_data set address='{address}', user_return_3={return_3}, user_view_3={view_3}, user_share_3={share_3}, user_return_videos_3={return_videos_3}, user_return_videos_30={return_videos_30} where video_id = '{video_id}';"""
  206. self.client_spider.update(update_sql)
  207. except Exception as e:
  208. print(e)
  209. pass
  210. else:
  211. print("No user info")
  212. def generate_user_data(self, flag, dt_time=None):
  213. """
  214. 生成user训练数据
  215. :return:
  216. """
  217. dt_time = datetime.datetime.strptime(dt_time, "%Y%m%d")
  218. three_date_before = dt_time + datetime.timedelta(days=4)
  219. temp_time = three_date_before.strftime("%Y%m%d")
  220. if flag == "train":
  221. sql = "select video_title, label, user_id, channel, user_fans, user_view_30, user_share_30, user_return_30, user_rov, user_str, user_return_videos_30, user_return_videos_3, user_return_3, user_view_3, user_share_3, address from lightgbm_data where type = 'userupload' and daily_dt_str >= '20240305';"
  222. des_path = "data/train_data/user_train_{}.json".format(datetime.datetime.today().strftime("%Y%m%d"))
  223. elif flag == "predict":
  224. sql = f"""select video_title, label, user_id, channel, user_fans, user_view_30, user_share_30, user_return_30, user_rov, user_str, user_return_videos_30, user_return_videos_3, user_return_3, user_view_3, user_share_3, address from lightgbm_data where type = 'userupload' and daily_dt_str = '{temp_time}';"""
  225. des_path = "data/predict_data/user_predict_{}.json".format(dt_time.strftime("%Y%m%d"))
  226. else:
  227. return
  228. dt_list = self.client_spider.select(sql)
  229. df = []
  230. for line in tqdm(dt_list):
  231. title = line[0]
  232. temp = list(line)
  233. title_tags = list(jieba.analyse.textrank(title, topK=3))
  234. if title_tags:
  235. for i in range(3):
  236. try:
  237. temp.append(title_tags[i])
  238. except:
  239. temp.append(None)
  240. else:
  241. temp.append(None)
  242. temp.append(None)
  243. temp.append(None)
  244. df.append(temp[1:])
  245. df = pd.DataFrame(df, columns=self.user_features)
  246. df.to_json(des_path, orient='records')
  247. if __name__ == "__main__":
  248. parser = argparse.ArgumentParser() # 新建参数解释器对象
  249. parser.add_argument("--mode")
  250. parser.add_argument("--de")
  251. parser.add_argument("--dt")
  252. args = parser.parse_args()
  253. mode = args.mode
  254. D = args.de
  255. dt = args.dt
  256. match D:
  257. case "spider":
  258. S = SpiderProcess()
  259. S.spider_data_produce(flag=mode, dt_time=dt)
  260. case "user":
  261. U = UserProcess()
  262. if mode == "generate":
  263. sd = str(input("输入开始日期,格式为 YYYYmmdd"))
  264. ed = str(input("输入结束日期,格式为 YYYYmmdd"))
  265. U.userinfo_to_mysql(start_date=sd, end_date=ed)
  266. else:
  267. U.generate_user_data(flag=mode, dt_time=dt)
  268. # else:
  269. # print("Error")
  270. case "Data":
  271. D = DataProcessor()
  272. D.producer()
  273. # if mode == "train":
  274. # print("Loading data and process for training.....")
  275. # D = DataProcessor(flag="train", ll=category)
  276. # D.producer("whole")
  277. # elif mode == "predict":
  278. # print("Loading data and process for prediction for each day......")
  279. # D = DataProcessor(flag="predict", ll=category)
  280. # if dtype == "single":
  281. # date_str = str(input("Please enter the date of the prediction"))
  282. # D.producer(date_str)
  283. # elif dtype == "days":
  284. # start_date_str = str(input("Please enter the start date of the prediction"))
  285. # end_date_str = str(input("Please enter the end date of the prediction"))
  286. # dt_list = generate_daily_strings(start_date=start_date_str, end_date=end_date_str)
  287. # for d in dt_list:
  288. # D.producer()