process_data.py 11 KB

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