ai_time_task_creative_handler.py 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. import pandas as pd
  2. from utils.UrlConfig import *
  3. import json
  4. import logging
  5. import traceback
  6. import random
  7. import tornado.web
  8. from concurrent_log import ConcurrentTimedRotatingFileHandler
  9. from utils.ConstantConfig import *
  10. from utils.DataBaseConfig import *
  11. from utils.CommonFunction import get_history_video_info, get_new_video_info, get_missing_video_info, \
  12. get_top_video_info, get_campaign_and_group_name_rule, get_app_detail, get_request_data, \
  13. refresh_video, get_app_list
  14. from ai_strategy_request_func import ai_strategy_request_parse
  15. log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', '%m/%d/%Y %I:%M:%S %p')
  16. log_handler = ConcurrentTimedRotatingFileHandler("logs/ai_auto_create.log", when="midnight", backupCount=100)
  17. log_handler.setFormatter(log_formatter)
  18. logger = logging.getLogger('ai_time_task_creative_logger')
  19. logger.addHandler(log_handler)
  20. logger.setLevel(logging.DEBUG)
  21. print('id of ai_time_task_creative_logger %s' % id(logger))
  22. logger.info("ai_time_task_creative_server started!")
  23. class AiHistoricalMissingMaterial(tornado.web.RequestHandler):
  24. """
  25. 补充历史遗漏素材(关联创意个数为0个素材)
  26. """
  27. def post(self):
  28. data = self.request.body
  29. data = str(data, 'utf8')
  30. data = json.loads(data, encoding='utf8')
  31. logger.info("*************************************** NEW REQUEST ***************************************")
  32. account_id = data.get('account_id')
  33. campaign_id = data.get('campaign_id')
  34. logger.info("账户信息=%s, 当前进程=%s, 当前进程的主进程=%s, raw data from request is %s" %
  35. (account_id, os.getpid(), os.getppid(), data))
  36. try:
  37. sql = """
  38. select account_id, single_appid, app_id_array, general_track from ctop_ai_kuaishou_advertiser_strategy
  39. where account_id=%s order by create_time desc limit 1
  40. """ % account_id
  41. df = pd.read_sql(sql, engine)
  42. if df['general_track'].values[0] == 0:
  43. app_id_array = eval(df['app_id_array'].values[0])
  44. app_list = get_app_list(account_id=account_id, url=get_app_list_url)
  45. # app_dict key = ("appVersion": "ksjyrlyn-人类一脑涂地大败") , value = 完整的app_id信息
  46. app_dict = {}
  47. for app_info in app_list['data']:
  48. if app_info['appId'] in app_id_array:
  49. app_dict[app_info['appVersion']] = app_info
  50. video_list = get_missing_video_info(account_id=account_id,
  51. cnt=missing_video_cnt,
  52. url=get_missing_video_url,
  53. start_time=missing_video_start_time,
  54. end_time=missing_video_end_time)
  55. # 返回视频中有通用视频和特定视频,需要分开处理
  56. # "photo_name": "all",
  57. # "photo_name": "ksjytdrca-糖豆人冲啊",
  58. if video_list['code'] == 0:
  59. video_df = pd.DataFrame(video_list['data'])
  60. # 1-非通用视频的创建
  61. special_video_df = video_df[video_df.photo_name != 'all']
  62. for photo_name in special_video_df['photo_name'].unique():
  63. if photo_name in app_dict.keys():
  64. campaign_id = None
  65. app_id = app_dict[photo_name].get('appId', 'error')
  66. app_version = app_dict[photo_name].get('appVersion', 'error')
  67. track_url = app_dict[photo_name].get('trackUrl', 'error')
  68. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  69. campaign_df = pd.read_sql(sql, engine)
  70. for row in campaign_df.itertuples():
  71. if (app_version + '--优选广告位-' + '遗漏素材') == getattr(row, 'campaign_name'):
  72. campaign_id = getattr(row, 'campaign_id')
  73. break
  74. app_id_video_df = special_video_df[special_video_df.photo_name == photo_name]
  75. app_id_video_list = []
  76. for k, v in app_id_video_df.T.to_dict().items():
  77. app_id_video_list.append(v)
  78. request_data = get_request_data(account_id=account_id,
  79. campaign_id=campaign_id,
  80. video_info=app_id_video_list,
  81. campaign_name=app_version + '--优选广告位-' + '遗漏素材',
  82. group_name=app_version + '-优选广告位-不限-自定义-' + '遗漏素材',
  83. ai_strategy_remark="补充遗漏素材",
  84. unit_type=4,
  85. app_id=app_id,
  86. click_track_url=track_url)
  87. request = ai_strategy_request_parse(request_data)
  88. logger.info("account_id=%s, app_id=%s, 补充遗漏素材-特定视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  89. # 2-通用视频的创建,random.shuffle 选择 app_id
  90. general_video_df = video_df[video_df.photo_name == 'all']
  91. if not general_video_df.empty:
  92. general_video_cnt = len(general_video_df)
  93. app_version_list = list(app_dict)
  94. random.shuffle(app_version_list)
  95. video_cnt = 0
  96. for app_version in app_version_list[:general_video_cnt]:
  97. campaign_id = None
  98. app_id = app_dict[app_version].get('appId', 'error')
  99. track_url = app_dict[app_version].get('trackUrl', 'error')
  100. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  101. campaign_df = pd.read_sql(sql, engine)
  102. for row in campaign_df.itertuples():
  103. if (app_version + '--优选广告位-' + '遗漏素材') == getattr(row, 'campaign_name'):
  104. campaign_id = getattr(row, 'campaign_id')
  105. break
  106. single_video = [general_video_df.iloc[video_cnt, :].T.to_dict()]
  107. request_data = get_request_data(account_id=account_id,
  108. campaign_id=campaign_id,
  109. video_info=single_video,
  110. campaign_name=app_version + '--优选广告位-' + '遗漏素材',
  111. group_name=app_version + '-优选广告位-不限-自定义-' + '遗漏素材',
  112. ai_strategy_remark="补充遗漏素材",
  113. unit_type=4,
  114. app_id=app_id,
  115. click_track_url=track_url)
  116. request = ai_strategy_request_parse(request_data)
  117. video_cnt += 1
  118. logger.info("account_id=%s, app_id=%s, 补充遗漏素材-通用视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  119. else:
  120. logger.info("account_id=%s, 补充遗漏素材: 返回的视频中没有通用视频" % account_id)
  121. self.write(json.dumps({"message": "account_id=%s, 多应用的补充遗漏素材请求已走完!" % account_id}))
  122. self.flush()
  123. else:
  124. video_info = get_missing_video_info(account_id=account_id,
  125. cnt=missing_video_cnt,
  126. url=get_missing_video_url,
  127. start_time=missing_video_start_time,
  128. end_time=missing_video_end_time)
  129. if video_info['code'] != 0:
  130. logger.info("account_id = %s,补充历史遗漏素材,没有获取到视频,不发送ai策略请求!" % account_id)
  131. self.write(json.dumps({"account_id": account_id,
  132. "message": "补充历史遗漏素材,没有获取到视频,不发送ai策略请求!"}))
  133. self.flush()
  134. else:
  135. campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
  136. if (campaign_name is None) or (group_name is None):
  137. logger.info("没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!")
  138. self.write(json.dumps({"message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
  139. self.flush()
  140. else:
  141. request_data = get_request_data(account_id=account_id,
  142. campaign_id=campaign_id,
  143. video_info=video_info['data'],
  144. campaign_name=campaign_name,
  145. group_name=group_name,
  146. ai_strategy_remark="补充遗漏素材",
  147. name_replace="补充遗漏素材")
  148. request = ai_strategy_request_parse(request_data)
  149. logger.info("account_id = %s, 补充遗漏素材,ai策略的返回信息:%s" % (account_id, request))
  150. self.write(json.dumps(request))
  151. self.flush()
  152. except Exception:
  153. logger.error("account_id = %s, traceback is %s" % (account_id, traceback.format_exc()))
  154. self.write(json.dumps({"account_id": account_id, "message": traceback.format_exc(), "code": -1}))
  155. self.flush()
  156. class AiAutoCreative(tornado.web.RequestHandler):
  157. """
  158. 每5分钟,检查一次是否有上新素材,有的话,就自动创建
  159. """
  160. def post(self):
  161. data = self.request.body
  162. data = str(data, 'utf8')
  163. data = json.loads(data, encoding='utf8')
  164. logger.info("*************************************** NEW REQUEST ***************************************")
  165. account_id = data.get('account_id')
  166. campaign_id = data.get('campaign_id')
  167. logger.info("账户信息=%s, 当前进程=%s, 当前进程的主进程=%s, raw data from request is %s" %
  168. (account_id, os.getpid(), os.getppid(), data))
  169. try:
  170. # 刷新快手视频信息
  171. refresh_video(account_id=account_id, url=refresh_video_url)
  172. sql = """
  173. select account_id, single_appid, app_id_array, general_track from ctop_ai_kuaishou_advertiser_strategy
  174. where account_id=%s order by create_time desc limit 1
  175. """ % account_id
  176. df = pd.read_sql(sql, engine)
  177. if df['general_track'].values[0] == 0:
  178. app_id_array = eval(df['app_id_array'].values[0])
  179. app_list = get_app_list(account_id=account_id, url=get_app_list_url)
  180. # app_dict key = ("appVersion": "ksjyrlyn-人类一脑涂地大败") , value = 完整的app_id信息
  181. app_dict = {}
  182. for app_info in app_list['data']:
  183. if app_info['appId'] in app_id_array:
  184. app_dict[app_info['appVersion']] = app_info
  185. video_list = get_new_video_info(account_id=account_id,
  186. url=get_new_video_url)
  187. # 返回的视频中有通用视频和特定视频,需要分开处理
  188. # "photo_name": "all",
  189. # "photo_name": "ksjytdrca-糖豆人冲啊",
  190. if video_list['code'] == 0:
  191. video_df = pd.DataFrame(video_list['data'])
  192. # 1-特定视频的创建
  193. special_video_df = video_df[video_df.photo_name != 'all']
  194. for photo_name in special_video_df['photo_name'].unique():
  195. if photo_name in app_dict.keys():
  196. campaign_id = None
  197. app_id = app_dict[photo_name].get('appId', 'error')
  198. app_version = app_dict[photo_name].get('appVersion', 'error')
  199. track_url = app_dict[photo_name].get('trackUrl', 'error')
  200. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  201. campaign_df = pd.read_sql(sql, engine)
  202. for row in campaign_df.itertuples():
  203. if (app_version + '--优选广告位-' + '素材自动上新') == getattr(row, 'campaign_name'):
  204. campaign_id = getattr(row, 'campaign_id')
  205. break
  206. app_id_video_df = special_video_df[special_video_df.photo_name == photo_name]
  207. app_id_video_list = []
  208. for k, v in app_id_video_df.T.to_dict().items():
  209. app_id_video_list.append(v)
  210. request_data = get_request_data(account_id=account_id,
  211. campaign_id=campaign_id,
  212. video_info=app_id_video_list,
  213. campaign_name=app_version + '--优选广告位-' + '素材自动上新',
  214. group_name=app_version + '-优选广告位-不限-自定义-' + '素材自动上新',
  215. ai_strategy_remark="素材自动上新",
  216. unit_type=4,
  217. app_id=app_id,
  218. click_track_url=track_url)
  219. request = ai_strategy_request_parse(request_data)
  220. logger.info("account_id=%s, app_id=%s, 素材自动上新-特定视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  221. # 2-通用视频的创建,random.shuffle 选择 app_id
  222. general_video_df = video_df[video_df.photo_name == 'all']
  223. if not general_video_df.empty:
  224. general_video_cnt = len(general_video_df)
  225. app_version_list = list(app_dict)
  226. random.shuffle(app_version_list)
  227. video_cnt = 0
  228. for app_version in app_version_list[:general_video_cnt]:
  229. campaign_id = None
  230. app_id = app_dict[app_version].get('appId', 'error')
  231. track_url = app_dict[app_version].get('trackUrl', 'error')
  232. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  233. campaign_df = pd.read_sql(sql, engine)
  234. for row in campaign_df.itertuples():
  235. if (app_version + '--优选广告位-' + '素材自动上新') == getattr(row, 'campaign_name'):
  236. campaign_id = getattr(row, 'campaign_id')
  237. break
  238. single_video = [general_video_df.iloc[video_cnt, :].T.to_dict()]
  239. request_data = get_request_data(account_id=account_id,
  240. campaign_id=campaign_id,
  241. video_info=single_video,
  242. campaign_name=app_version + '--优选广告位-' + '素材自动上新',
  243. group_name=app_version + '-优选广告位-不限-自定义-' + '素材自动上新',
  244. ai_strategy_remark="素材自动上新",
  245. unit_type=4,
  246. app_id=app_id,
  247. click_track_url=track_url)
  248. request = ai_strategy_request_parse(request_data)
  249. video_cnt += 1
  250. logger.info("account_id=%s, app_id=%s, 素材自动上新-通用视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  251. else:
  252. logger.info("account_id=%s, 素材自动上新: 返回的视频中没有通用视频" % account_id)
  253. else:
  254. logger.info("account_id=%s, 素材自动上新: 没有获取到视频" % account_id)
  255. self.write(json.dumps({"message": "account_id=%s, 多应用的素材自动上新已走完!" % account_id}))
  256. self.flush()
  257. else:
  258. start_time = (datetime.date.today()).strftime('%Y-%m-%d %H:%M:%S')
  259. end_time = (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
  260. # 1-1 获取当天计划中包含“自动上新”计划的,计划id
  261. sql = """
  262. select campaign_id, campaign_name from ctop_kuaishou_campaign
  263. where account_id = %s
  264. and put_create_time >= '%s'
  265. and put_create_time <= '%s'
  266. """ % (account_id, start_time, end_time)
  267. df = pd.read_sql(sql, engine)
  268. for row in df.itertuples():
  269. if '素材自动上新' in getattr(row, 'campaign_name'):
  270. campaign_id = getattr(row, 'campaign_id')
  271. break
  272. video_info = get_new_video_info(account_id=account_id,
  273. url=get_new_video_url)
  274. if video_info['code'] != 0:
  275. self.write(json.dumps({"account_id": account_id, "message": "素材自动上新没有获取到视频,不发送ai策略请求!"}))
  276. self.flush()
  277. else:
  278. campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
  279. if (campaign_name is None) or (group_name is None):
  280. logger.info("account_id = %s, 素材自动上新 没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"
  281. % account_id)
  282. self.write(json.dumps({"account_id": account_id,
  283. "message": "素材自动上新 没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
  284. self.flush()
  285. else:
  286. request_data = get_request_data(account_id=account_id,
  287. campaign_id=campaign_id,
  288. video_info=video_info['data'],
  289. campaign_name=campaign_name,
  290. group_name=group_name,
  291. ai_strategy_remark="自动上新",
  292. name_replace="素材自动上新")
  293. request = ai_strategy_request_parse(request_data)
  294. logger.info("account_id = %s, 素材自动上新 ai策略的返回信息:%s" % (account_id, request))
  295. self.write(json.dumps(request))
  296. self.flush()
  297. except Exception:
  298. logger.error("account_id = %s, traceback is %s" % (account_id, traceback.format_exc()))
  299. self.write(json.dumps({"account_id": account_id, "message": traceback.format_exc(), "code": -1}))
  300. self.flush()
  301. class AiHighQualityMaterial(tornado.web.RequestHandler):
  302. """
  303. 补充历史高质量素材 -- 测试通过 在AD后台创建成功,检查AD信息和数据库表 没有问题
  304. """
  305. def post(self):
  306. data = self.request.body
  307. data = str(data, 'utf8')
  308. data = json.loads(data, encoding='utf8')
  309. logger.info("*************************************** NEW REQUEST ***************************************")
  310. account_id = data.get('account_id')
  311. campaign_id = data.get('campaign_id')
  312. logger.info("账户信息=%s, 当前进程=%s, 当前进程的主进程=%s, raw data from request is %s" %
  313. (account_id, os.getpid(), os.getppid(), data))
  314. try:
  315. sql = """select account_id, single_appid, app_id_array, general_track from ctop_ai_kuaishou_advertiser_strategy
  316. where account_id=%s order by create_time desc limit 1
  317. """ % account_id
  318. df = pd.read_sql(sql, engine)
  319. if df['general_track'].values[0] == 0:
  320. app_id_array = eval(df['app_id_array'].values[0])
  321. app_list = get_app_list(account_id=account_id, url=get_app_list_url)
  322. # app_dict key = ("appVersion": "ksjyrlyn-人类一脑涂地大败") , value = 完整的app_id信息
  323. app_dict = {}
  324. for app_info in app_list['data']:
  325. if app_info['appId'] in app_id_array:
  326. app_dict[app_info['appVersion']] = app_info
  327. video_list = get_top_video_info(account_id=account_id,
  328. cnt=high_quality_video_cnt,
  329. start_time=(datetime.datetime.now() +
  330. datetime.timedelta(days=-high_quality_video_days)).
  331. strftime("%Y-%m-%d %H:%M:%S"),
  332. end_time=(datetime.datetime.now() + datetime.timedelta(days=-1)).
  333. strftime("%Y-%m-%d %H:%M:%S"),
  334. url=get_high_quality_video_url)
  335. # 单独处理返回的时候中,有通用视频,需要单独处理
  336. # "photo_name": "all",
  337. # "photo_name": "ksjytdrca-糖豆人冲啊",
  338. if video_list['code'] == 0:
  339. video_df = pd.DataFrame(video_list['data'])
  340. # 1-特定视频的创建
  341. special_video_df = video_df[video_df.photo_name != 'all']
  342. for photo_name in special_video_df['photo_name'].unique():
  343. if photo_name in app_dict.keys():
  344. campaign_id = None
  345. app_id = app_dict[photo_name].get('appId', 'error')
  346. app_version = app_dict[photo_name].get('appVersion', 'error')
  347. track_url = app_dict[photo_name].get('trackUrl', 'error')
  348. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  349. campaign_df = pd.read_sql(sql, engine)
  350. for row in campaign_df.itertuples():
  351. if (app_version + '--优选广告位-' + '高质量素材') == getattr(row, 'campaign_name'):
  352. campaign_id = getattr(row, 'campaign_id')
  353. break
  354. app_id_video_df = special_video_df[special_video_df.photo_name == photo_name]
  355. app_id_video_list = []
  356. for k, v in app_id_video_df.T.to_dict().items():
  357. app_id_video_list.append(v)
  358. request_data = get_request_data(account_id=account_id,
  359. campaign_id=campaign_id,
  360. video_info=app_id_video_list,
  361. campaign_name=app_version + '--优选广告位-' + '高质量素材',
  362. group_name=app_version + '-优选广告位-不限-自定义-' + '高质量素材',
  363. ai_strategy_remark="高质量素材复建",
  364. unit_type=4,
  365. app_id=app_id,
  366. click_track_url=track_url)
  367. request = ai_strategy_request_parse(request_data)
  368. logger.info("account_id=%s, app_id=%s, 高质量素材复建-特定视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  369. # 2-通用视频的创建,random.shuffle 选择 app_id
  370. general_video_df = video_df[video_df.photo_name == 'all']
  371. if not general_video_df.empty:
  372. general_video_cnt = len(general_video_df)
  373. app_version_list = list(app_dict)
  374. random.shuffle(app_version_list)
  375. video_cnt = 0
  376. for app_version in app_version_list[:general_video_cnt]:
  377. campaign_id = None
  378. app_id = app_dict[app_version].get('appId', 'error')
  379. track_url = app_dict[app_version].get('trackUrl', 'error')
  380. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  381. campaign_df = pd.read_sql(sql, engine)
  382. for row in campaign_df.itertuples():
  383. if (app_version + '--优选广告位-' + '高质量素材') == getattr(row, 'campaign_name'):
  384. campaign_id = getattr(row, 'campaign_id')
  385. break
  386. single_video = [general_video_df.iloc[video_cnt, :].T.to_dict()]
  387. request_data = get_request_data(account_id=account_id,
  388. campaign_id=campaign_id,
  389. video_info=single_video,
  390. campaign_name=app_version + '--优选广告位-' + '高质量素材',
  391. group_name=app_version + '-优选广告位-不限-自定义-' + '高质量素材',
  392. ai_strategy_remark="高质量素材复建",
  393. unit_type=4,
  394. app_id=app_id,
  395. click_track_url=track_url)
  396. request = ai_strategy_request_parse(request_data)
  397. video_cnt += 1
  398. logger.info("account_id=%s, app_id=%s, 高质量素材复建-通用视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  399. else:
  400. logger.info("account_id=%s, 高质量素材复建: 返回的视频中没有通用视频" % account_id)
  401. else:
  402. logger.info("account_id=%s, 高质量素材复建: 没有获取到视频" % account_id)
  403. self.write(json.dumps({"message": "account_id=%s, 多应用的高质量素材复建请求已走完!" % account_id}))
  404. self.flush()
  405. else:
  406. video_info = get_top_video_info(account_id=account_id,
  407. cnt=high_quality_video_cnt,
  408. start_time=(datetime.datetime.now() +
  409. datetime.timedelta(days=-high_quality_video_days)).
  410. strftime("%Y-%m-%d %H:%M:%S"),
  411. end_time=(datetime.datetime.now() + datetime.timedelta(days=-1)).
  412. strftime("%Y-%m-%d %H:%M:%S"),
  413. url=get_high_quality_video_url)
  414. if video_info['code'] != 0:
  415. logger.info("account_id = %s, 高质量素材复建,没有获取到视频,不发送ai策略请求!" % account_id)
  416. self.write(json.dumps({"account_id": account_id,
  417. "message": "高质量素材复建,没有获取到视频,不发送ai策略请求!"}))
  418. self.flush()
  419. else:
  420. campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
  421. if (campaign_name is None) or (group_name is None):
  422. logger.error("account_id = %s, 没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!" % account_id)
  423. self.write(json.dumps({"account_id": account_id,
  424. "message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
  425. self.flush()
  426. else:
  427. request_data = get_request_data(account_id=account_id,
  428. campaign_id=campaign_id,
  429. video_info=video_info['data'],
  430. campaign_name=campaign_name,
  431. group_name=group_name,
  432. ai_strategy_remark="高质量素材复建",
  433. name_replace="高质量素材")
  434. request = ai_strategy_request_parse(request_data)
  435. logger.info("account_id = %s, 高质量素材复建,ai策略的返回信息:%s" % (account_id, request))
  436. self.write(json.dumps(request))
  437. self.flush()
  438. except Exception:
  439. logger.error("account_id = %s, traceback is %s" % (account_id, traceback.format_exc()))
  440. self.write(json.dumps({"account_id": account_id, "message": traceback.format_exc(), "code": -1}))
  441. self.flush()
  442. class AiUpCreativeByHour(tornado.web.RequestHandler):
  443. """
  444. 1点到20点,每小时执行一次,检查当前时点创意个数是否达到hour*100
  445. 没有达到则按照当前时点值,补充不同类型的视频
  446. """
  447. def post(self):
  448. data = self.request.body
  449. data = str(data, 'utf8')
  450. data = json.loads(data, encoding='utf8')
  451. account_id = data.get('account_id')
  452. campaign_id = data.get('campaign_id')
  453. logger.info("账户信息=%s, 当前进程=%s, 当前进程的主进程=%s, raw data from request is %s" %
  454. (account_id, os.getpid(), os.getppid(), data))
  455. try:
  456. # 1 从客户策略表中获取该账户下 每个素材搭配的封面个数, 来计算需要补充的素材个数
  457. sql = """select image_cnt from ctop_ai_kuaishou_advertiser_strategy
  458. where account_id = %s
  459. limit 1""" % account_id
  460. df = pd.read_sql(sql, engine)
  461. image_cnt = int(df['image_cnt'].values[0])
  462. # 2、获取从0点到now()为止,该账户下已有的创意个数 M
  463. sql = """select count(1) creative_cnt from ctop_kuaishou_creative
  464. where account_id = %s
  465. and creative_id is not NULL
  466. and creative_create_time <= '%s'
  467. and creative_create_time >= '%s'""" % (account_id,
  468. (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S'),
  469. (datetime.datetime.now()).strftime('%Y-%m-%d'))
  470. df = pd.read_sql(sql, engine)
  471. exist_creative_cnt = int(df['creative_cnt'].values[0])
  472. now_hour = datetime.datetime.now().hour
  473. now = datetime.datetime.now()
  474. should_creative_cnt = now_hour * 100
  475. # 3、计算需要补充的创意个数和视频个数,并按当前小时值,补充不同类似的视频
  476. if exist_creative_cnt < should_creative_cnt:
  477. need_video_cnt = (should_creative_cnt - exist_creative_cnt) // image_cnt
  478. logger.info("account_id = %s, 按小时需要补充的视频数量 = %s" % (account_id, need_video_cnt))
  479. if now_hour % 5 == 0:
  480. # campaign_group_name_place 用于广告计划和广告组名称的标识
  481. campaign_group_name_place = "高质量素材"
  482. video_list = get_top_video_info(account_id=account_id,
  483. url=get_high_quality_video_url,
  484. start_time=(now + datetime.timedelta(days=-high_quality_video_days)).
  485. strftime("%Y-%m-%d %H:%M:%S"),
  486. end_time=(now + datetime.timedelta(days=-1)).
  487. strftime("%Y-%m-%d %H:%M:%S"),
  488. cnt=need_video_cnt,
  489. app_version=None)
  490. elif (now_hour % 5 == 1) or (now_hour % 5 == 2):
  491. campaign_group_name_place = "历史素材打捞"
  492. video_list = get_history_video_info(account_id=account_id,
  493. url=get_history_video_url,
  494. start_time=history_video_start_time,
  495. end_time=history_video_end_time,
  496. video_cnt=need_video_cnt,
  497. related_creative_max_cnt=related_creative_max_cnt)
  498. else:
  499. campaign_group_name_place = "遗漏素材"
  500. video_list = get_missing_video_info(account_id=account_id,
  501. cnt=need_video_cnt,
  502. url=get_missing_video_url,
  503. start_time=missing_video_start_time,
  504. end_time=missing_video_end_time)
  505. if video_list['code'] == 0:
  506. # 根据获取到的视频进行创建
  507. sql = """select account_id, single_appid, app_id_array, general_track from ctop_ai_kuaishou_advertiser_strategy
  508. where account_id=%s order by create_time desc limit 1""" % account_id
  509. df = pd.read_sql(sql, engine)
  510. if df['general_track'].values[0] == 0:
  511. app_id_array = eval(df['app_id_array'].values[0])
  512. app_list = get_app_list(account_id=account_id, url=get_app_list_url)
  513. # app_dict key = ("appVersion": "ksjyrlyn-人类一脑涂地大败") , value = 完整的app_id信息
  514. app_dict = {}
  515. for app_info in app_list['data']:
  516. if app_info['appId'] in app_id_array:
  517. app_dict[app_info['appVersion']] = app_info
  518. # 单独处理返回的时候中,有通用视频,需要单独处理
  519. # "photo_name": "all",
  520. # "photo_name": "ksjytdrca-糖豆人冲啊",
  521. video_df = pd.DataFrame(video_list['data'])
  522. # 1-特定视频的创建
  523. special_video_df = video_df[video_df.photo_name != 'all']
  524. for photo_name in special_video_df['photo_name'].unique():
  525. if photo_name in app_dict.keys():
  526. campaign_id = None
  527. app_id = app_dict[photo_name].get('appId', 'error')
  528. app_version = app_dict[photo_name].get('appVersion', 'error')
  529. track_url = app_dict[photo_name].get('trackUrl', 'error')
  530. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  531. campaign_df = pd.read_sql(sql, engine)
  532. for row in campaign_df.itertuples():
  533. if (app_version + '--优选广告位-' + campaign_group_name_place) == getattr(row, 'campaign_name'):
  534. campaign_id = getattr(row, 'campaign_id')
  535. break
  536. app_id_video_df = special_video_df[special_video_df.photo_name == photo_name]
  537. app_id_video_list = []
  538. for k, v in app_id_video_df.T.to_dict().items():
  539. app_id_video_list.append(v)
  540. request_data = get_request_data(account_id=account_id,
  541. campaign_id=campaign_id,
  542. video_info=app_id_video_list,
  543. campaign_name=app_version+'--优选广告位-'+campaign_group_name_place,
  544. group_name=app_version+'-优选广告位-不限-自定义-'+campaign_group_name_place,
  545. ai_strategy_remark="按小时补充创意-"+campaign_group_name_place,
  546. unit_type=4,
  547. app_id=app_id,
  548. click_track_url=track_url)
  549. request = ai_strategy_request_parse(request_data)
  550. logger.info("account_id=%s, app_id=%s, %s补充创意-特定视频,ai策略的返回信息:%s" %
  551. (account_id, app_id, campaign_group_name_place, request))
  552. # 2-通用视频的创建,random.shuffle 选择 app_id
  553. general_video_df = video_df[video_df.photo_name == 'all']
  554. if not general_video_df.empty:
  555. # 每 batch_num 一组 随机选择一个app_id 进行创建
  556. batch_num = 10
  557. general_video_cnt = len(general_video_df)
  558. app_version_list = list(app_dict)
  559. random.shuffle(app_version_list)
  560. need_app_id_cnt = general_video_cnt // batch_num + 1
  561. video_cnt = 0
  562. for app_version in app_version_list[:need_app_id_cnt]:
  563. campaign_id = None
  564. app_id = app_dict[app_version].get('appId', 'error')
  565. track_url = app_dict[app_version].get('trackUrl', 'error')
  566. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  567. campaign_df = pd.read_sql(sql, engine)
  568. for row in campaign_df.itertuples():
  569. if (app_version + '--优选广告位-' + campaign_group_name_place) == getattr(row, 'campaign_name'):
  570. campaign_id = getattr(row, 'campaign_id')
  571. break
  572. batch_general_video_list = []
  573. for k, v in general_video_df.iloc[video_cnt: video_cnt+batch_num, :].T.to_dict().items():
  574. batch_general_video_list.append(v)
  575. request_data = get_request_data(account_id=account_id,
  576. campaign_id=campaign_id,
  577. video_info=batch_general_video_list,
  578. campaign_name=app_version + '--优选广告位-' + campaign_group_name_place,
  579. group_name=app_version + '-优选广告位-不限-自定义-' + campaign_group_name_place,
  580. ai_strategy_remark="按小时补充创意-"+campaign_group_name_place,
  581. unit_type=4,
  582. app_id=app_id,
  583. click_track_url=track_url)
  584. request = ai_strategy_request_parse(request_data)
  585. video_cnt += batch_num
  586. logger.info("account_id=%s, app_id=%s, %s补充创意-通用视频,ai策略的返回信息:%s" %
  587. (account_id, app_id, campaign_group_name_place, request))
  588. else:
  589. logger.info("account_id=%s, %s补充创意: 返回的视频中没有通用视频" % (account_id, campaign_group_name_place))
  590. self.write(json.dumps({"message": "account_id=%s, %s补充创意请求已走完!" % (account_id, campaign_group_name_place)}))
  591. self.flush()
  592. else:
  593. # 获取当天计划中包含“campaign_group_name_place”计划的,计划id
  594. sql = """select campaign_id, campaign_name from ctop_kuaishou_campaign
  595. where account_id = %s
  596. and put_create_time <= '%s'
  597. and put_create_time >= '%s' """ % (account_id,
  598. (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S'),
  599. (datetime.datetime.now()).strftime('%Y-%m-%d'))
  600. df = pd.read_sql(sql, engine)
  601. for row in df.itertuples():
  602. if campaign_group_name_place in getattr(row, 'campaign_name'):
  603. campaign_id = getattr(row, 'campaign_id')
  604. break
  605. campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
  606. if (campaign_name is None) or (group_name is None):
  607. logger.info("account_id = %s, 没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!" % account_id)
  608. self.write(json.dumps({"account_id": account_id,
  609. "message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
  610. self.flush()
  611. else:
  612. request_data = get_request_data(account_id=account_id,
  613. campaign_id=campaign_id,
  614. video_info=video_list['data'],
  615. campaign_name=campaign_name,
  616. group_name=group_name,
  617. ai_strategy_remark="按小时补充创意-"+campaign_group_name_place,
  618. name_replace=campaign_group_name_place)
  619. request = ai_strategy_request_parse(request_data)
  620. logger.info("account_id = %s, %s补充创意,ai策略的返回信息:%s" % (account_id, campaign_group_name_place, request))
  621. self.write(json.dumps(request))
  622. self.flush()
  623. else:
  624. logger.info("account_id=%s, 按小时补充创意: 没有成功获取到视频!" % account_id)
  625. self.write(json.dumps({"message": "account_id=%s, 按小时补充创意: 没有成功获取到视频!" % account_id}))
  626. self.flush()
  627. except Exception:
  628. logger.error("account_id = %s, traceback is %s" % (account_id, traceback.format_exc()))
  629. self.write(json.dumps({"account_id": account_id, "message": traceback.format_exc(), "code": -1}))
  630. self.flush()
  631. class AiProgramCreativeHighQualityMaterial(tornado.web.RequestHandler):
  632. """
  633. 使用历史跑量素材创建程序化创意
  634. 跑量素材150个(近14天的素材)
  635. 计划名称--跑量素材程序化
  636. timeTask: 每天上午10点执行 --(0 0 10 * * ?)
  637. ----------------------------------------
  638. 拼装参数和写入数据库时,需要修改名称(程序化与非程序化不一致):
  639. creative_name --> package_name(程序化创意名称)
  640. action_bar_text --> action_bar(行动号召按钮)
  641. description --> captions(作品广告语)
  642. click_track_url --> click_url
  643. 写入数据库时:
  644. image_md5s --> cover_image_tokens
  645. 程序化与非程序化的逻辑不一样:
  646. 需要5个视频4张封面一组,拼装程序化创意参数需要单独抽取一个方法出来
  647. 所有操作记录表中,添加status信息(已提交,成功,失败),和回调时的 message信息
  648. """
  649. def post(self):
  650. data = self.request.body
  651. data = str(data, 'utf8')
  652. data = json.loads(data, encoding='utf8')
  653. logger.info("*************************************** NEW REQUEST ***************************************")
  654. account_id = data.get('account_id')
  655. campaign_id = data.get('campaign_id')
  656. logger.info("账户信息=%s, 当前进程=%s, 当前进程的主进程=%s, raw data from request is %s" %
  657. (account_id, os.getpid(), os.getppid(), data))
  658. try:
  659. sql = """select account_id, single_appid, app_id_array, general_track from ctop_ai_kuaishou_advertiser_strategy
  660. where account_id=%s order by create_time desc limit 1
  661. """ % account_id
  662. df = pd.read_sql(sql, engine)
  663. if df['general_track'].values[0] == 0:
  664. app_id_array = eval(df['app_id_array'].values[0])
  665. app_list = get_app_list(account_id=account_id, url=get_app_list_url)
  666. # app_dict key = ("appVersion": "ksjyrlyn-人类一脑涂地大败") , value = 完整的app_id信息
  667. app_dict = {}
  668. for app_info in app_list['data']:
  669. if app_info['appId'] in app_id_array:
  670. app_dict[app_info['appVersion']] = app_info
  671. video_list = get_top_video_info(account_id=account_id,
  672. cnt=multi_app_id_programme_high_quality_video_cnt,
  673. start_time=(datetime.datetime.now() + datetime.timedelta(
  674. days=-high_quality_video_days)).strftime("%Y-%m-%d %H:%M:%S"),
  675. end_time=(datetime.datetime.now() + datetime.timedelta(days=-1)).
  676. strftime("%Y-%m-%d %H:%M:%S"),
  677. url=get_high_quality_video_url)
  678. # 单独处理返回的时候中,有通用视频,需要单独处理
  679. # "photo_name": "all",
  680. # "photo_name": "ksjytdrca-糖豆人冲啊",
  681. if video_list['code'] == 0:
  682. video_df = pd.DataFrame(video_list['data'])
  683. # 1-特定视频的创建
  684. special_video_df = video_df[video_df.photo_name != 'all']
  685. for photo_name in special_video_df['photo_name'].unique():
  686. if photo_name in app_dict.keys():
  687. campaign_id = None
  688. app_id = app_dict[photo_name].get('appId', 'error')
  689. app_version = app_dict[photo_name].get('appVersion', 'error')
  690. track_url = app_dict[photo_name].get('trackUrl', 'error')
  691. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  692. campaign_df = pd.read_sql(sql, engine)
  693. for row in campaign_df.itertuples():
  694. if (app_version + '--优选广告位-' + '程序化高质量素材') == getattr(row, 'campaign_name'):
  695. campaign_id = getattr(row, 'campaign_id')
  696. break
  697. app_id_video_df = special_video_df[special_video_df.photo_name == photo_name]
  698. app_id_video_list = []
  699. for k, v in app_id_video_df.T.to_dict().items():
  700. app_id_video_list.append(v)
  701. request_data = get_request_data(account_id=account_id,
  702. campaign_id=campaign_id,
  703. video_info=app_id_video_list,
  704. campaign_name=app_version + '--优选广告位-' + '程序化高质量素材',
  705. group_name=app_version + '-优选广告位-不限-程序化-' + '高质量素材',
  706. ai_strategy_remark="程序化高质量素材",
  707. unit_type=7,
  708. app_id=app_id,
  709. click_track_url=track_url)
  710. request = ai_strategy_request_parse(request_data)
  711. logger.info("account_id=%s, app_id=%s, 程序化高质量素材-特定视频,ai策略的返回信息:%s" %
  712. (account_id, app_id, request))
  713. # 2-通用视频的创建,random.shuffle 选择 app_id
  714. general_video_df = video_df[video_df.photo_name == 'all']
  715. general_video_list = []
  716. for k, v in general_video_df.T.to_dict().items():
  717. general_video_list.append(v)
  718. if general_video_list:
  719. app_version_list = list(app_dict)
  720. random.shuffle(app_version_list)
  721. # 每5个通用视频创建一个程序化广告组
  722. batch_num = 5
  723. app_id_cnt = 0
  724. for i in range(0, len(general_video_list), 5):
  725. if i + 5 < len(general_video_list):
  726. batch_general_video = general_video_list[i: i + batch_num]
  727. app_version = app_version_list[app_id_cnt]
  728. app_id = app_dict[app_version].get('appId', 'error')
  729. track_url = app_dict[app_version].get('trackUrl', 'error')
  730. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  731. campaign_df = pd.read_sql(sql, engine)
  732. for row in campaign_df.itertuples():
  733. if (app_version + '--优选广告位-' + '程序化高质量素材') == getattr(row, 'campaign_name'):
  734. campaign_id = getattr(row, 'campaign_id')
  735. break
  736. request_data = get_request_data(account_id=account_id,
  737. campaign_id=campaign_id,
  738. video_info=batch_general_video,
  739. campaign_name=app_version + '--优选广告位-' + '程序化高质量素材',
  740. group_name=app_version + '-优选广告位-不限-程序化-' + '高质量素材',
  741. ai_strategy_remark="程序化高质量素材",
  742. unit_type=7,
  743. app_id=app_id,
  744. click_track_url=track_url)
  745. request = ai_strategy_request_parse(request_data)
  746. app_id_cnt += 1
  747. logger.info("account_id=%s, app_id=%s, 程序化高质量素材-通用视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  748. else:
  749. batch_general_video = general_video_list[i: len(general_video_list)]
  750. app_version = app_version_list[app_id_cnt]
  751. app_id = app_dict[app_version].get('appId', 'error')
  752. track_url = app_dict[app_version].get('trackUrl', 'error')
  753. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  754. campaign_df = pd.read_sql(sql, engine)
  755. for row in campaign_df.itertuples():
  756. if (app_version + '--优选广告位-' + '程序化高质量素材') == getattr(row, 'campaign_name'):
  757. campaign_id = getattr(row, 'campaign_id')
  758. break
  759. request_data = get_request_data(account_id=account_id,
  760. campaign_id=campaign_id,
  761. video_info=batch_general_video,
  762. campaign_name=app_version + '--优选广告位-' + '程序化高质量素材',
  763. group_name=app_version + '-优选广告位-不限-程序化-' + '高质量素材',
  764. ai_strategy_remark="程序化高质量素材",
  765. unit_type=7,
  766. app_id=app_id,
  767. click_track_url=track_url)
  768. request = ai_strategy_request_parse(request_data)
  769. logger.info("account_id=%s, app_id=%s, 程序化高质量素材-通用视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  770. else:
  771. logger.info("account_id=%s, 程序化高质量素材: 返回的视频中没有通用视频" % account_id)
  772. self.write(json.dumps({"message": "account_id=%s, 程序化高质量素材请求已走完!" % account_id}))
  773. self.flush()
  774. else:
  775. video_info = get_top_video_info(account_id=account_id,
  776. cnt=programme_high_quality_video_cnt,
  777. start_time=(datetime.datetime.now() + datetime.timedelta(
  778. days=-high_quality_video_days)).strftime("%Y-%m-%d %H:%M:%S"),
  779. end_time=(datetime.datetime.now() + datetime.timedelta(days=-1)).
  780. strftime("%Y-%m-%d %H:%M:%S"),
  781. url=get_high_quality_video_url)
  782. if video_info['code'] != 0:
  783. logger.info("account_id = %s, 程序化高质量素材,没有获取到视频,不发送ai策略请求!" % account_id)
  784. self.write(json.dumps({"account_id": account_id,
  785. "message": "没有获取到视频,不发送ai策略请求!"}))
  786. self.flush()
  787. else:
  788. campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
  789. if (campaign_name is None) or (group_name is None):
  790. logger.info("account_id = %s, 没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!" % account_id)
  791. self.write(json.dumps({"account_id": account_id,
  792. "message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
  793. self.flush()
  794. else:
  795. request_data = get_request_data(account_id=account_id,
  796. campaign_id=campaign_id,
  797. video_info=video_info['data'],
  798. campaign_name=campaign_name,
  799. group_name=group_name,
  800. ai_strategy_remark="程序化高质量素材",
  801. name_replace="程序化高质量素材",
  802. unit_type=7)
  803. request = ai_strategy_request_parse(request_data)
  804. logger.info("account_id = %s, 程序化高质量素材, ai策略的返回信息:%s" % (account_id, request))
  805. self.write(json.dumps(request))
  806. self.flush()
  807. except Exception:
  808. logger.error("account_id = %s, traceback is %s" % (account_id, traceback.format_exc()))
  809. self.write(json.dumps({"account_id": account_id, "message": traceback.format_exc(), "code": -1}))
  810. self.flush()
  811. class AiProgramCreativeNewMaterial(tornado.web.RequestHandler):
  812. """
  813. 使用N天内 创意数关联小于M个(如当天创意关联数小于10的,150个素材)的素材创建程序化创意
  814. 计划名称--新素材程序化
  815. timeTask: 每天上午10点执行 --(0 0 10 * * ?)
  816. """
  817. def post(self):
  818. data = self.request.body
  819. data = str(data, 'utf8')
  820. data = json.loads(data, encoding='utf8')
  821. logger.info("*************************************** NEW REQUEST ***************************************")
  822. account_id = data.get('account_id')
  823. campaign_id = data.get('campaign_id')
  824. logger.info("账户信息=%s, 当前进程=%s, 当前进程的主进程=%s, raw data from request is %s" %
  825. (account_id, os.getpid(), os.getppid(), data))
  826. try:
  827. sql = """select account_id, single_appid, app_id_array, general_track from ctop_ai_kuaishou_advertiser_strategy
  828. where account_id=%s order by create_time desc limit 1
  829. """ % account_id
  830. df = pd.read_sql(sql, engine)
  831. if df['general_track'].values[0] == 0:
  832. app_id_array = eval(df['app_id_array'].values[0])
  833. app_list = get_app_list(account_id=account_id, url=get_app_list_url)
  834. # app_dict key = ("appVersion": "ksjyrlyn-人类一脑涂地大败") , value = 完整的app_id信息
  835. app_dict = {}
  836. for app_info in app_list['data']:
  837. if app_info['appId'] in app_id_array:
  838. app_dict[app_info['appVersion']] = app_info
  839. video_list = get_history_video_info(account_id=account_id,
  840. url=get_history_video_url,
  841. start_time=(datetime.datetime.now() + datetime.timedelta(days=-7)).
  842. strftime("%Y-%m-%d %H:%M:%S"),
  843. end_time=(datetime.datetime.now() + datetime.timedelta(days=-1)).
  844. strftime("%Y-%m-%d %H:%M:%S"),
  845. video_cnt=multi_app_id_programme_new_video_cnt,
  846. related_creative_max_cnt=related_creative_max_cnt)
  847. # 单独处理返回的时候中,有通用视频,需要单独处理
  848. # "photo_name": "all",
  849. # "photo_name": "ksjytdrca-糖豆人冲啊",
  850. if video_list['code'] == 0:
  851. video_df = pd.DataFrame(video_list['data'])
  852. # 1-特定视频的创建
  853. special_video_df = video_df[video_df.photo_name != 'all']
  854. for photo_name in special_video_df['photo_name'].unique():
  855. if photo_name in app_dict.keys():
  856. campaign_id = None
  857. app_id = app_dict[photo_name].get('appId', 'error')
  858. app_version = app_dict[photo_name].get('appVersion', 'error')
  859. track_url = app_dict[photo_name].get('trackUrl', 'error')
  860. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  861. campaign_df = pd.read_sql(sql, engine)
  862. for row in campaign_df.itertuples():
  863. if (app_version + '--优选广告位-' + '程序化上新素材') == getattr(row, 'campaign_name'):
  864. campaign_id = getattr(row, 'campaign_id')
  865. break
  866. app_id_video_df = special_video_df[special_video_df.photo_name == photo_name]
  867. app_id_video_list = []
  868. for k, v in app_id_video_df.T.to_dict().items():
  869. app_id_video_list.append(v)
  870. request_data = get_request_data(account_id=account_id,
  871. campaign_id=campaign_id,
  872. video_info=app_id_video_list,
  873. campaign_name=app_version + '--优选广告位-' + '程序化上新素材',
  874. group_name=app_version + '-优选广告位-不限-程序化-' + '上新素材',
  875. ai_strategy_remark="程序化上新素材",
  876. unit_type=7,
  877. app_id=app_id,
  878. click_track_url=track_url)
  879. request = ai_strategy_request_parse(request_data)
  880. logger.info("account_id=%s, app_id=%s, 程序化上新素材-特定视频,ai策略的返回信息:%s" %
  881. (account_id, app_id, request))
  882. # 2-通用视频的创建,random.shuffle 选择 app_id
  883. general_video_df = video_df[video_df.photo_name == 'all']
  884. general_video_list = []
  885. for k, v in general_video_df.T.to_dict().items():
  886. general_video_list.append(v)
  887. if general_video_list:
  888. app_version_list = list(app_dict)
  889. random.shuffle(app_version_list)
  890. # 每5个通用视频创建一个程序化广告组
  891. batch_num = 5
  892. app_id_cnt = 0
  893. for i in range(0, len(general_video_list), 5):
  894. if i + 5 < len(general_video_list):
  895. batch_general_video = general_video_list[i: i + batch_num]
  896. app_version = app_version_list[app_id_cnt]
  897. app_id = app_dict[app_version].get('appId', 'error')
  898. track_url = app_dict[app_version].get('trackUrl', 'error')
  899. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  900. campaign_df = pd.read_sql(sql, engine)
  901. for row in campaign_df.itertuples():
  902. if (app_version + '--优选广告位-' + '程序化上新素材') == getattr(row, 'campaign_name'):
  903. campaign_id = getattr(row, 'campaign_id')
  904. break
  905. request_data = get_request_data(account_id=account_id,
  906. campaign_id=campaign_id,
  907. video_info=batch_general_video,
  908. campaign_name=app_version + '--优选广告位-' + '程序化上新素材',
  909. group_name=app_version + '-优选广告位-不限-程序化-' + '上新素材',
  910. ai_strategy_remark="程序化上新素材",
  911. unit_type=7,
  912. app_id=app_id,
  913. click_track_url=track_url)
  914. request = ai_strategy_request_parse(request_data)
  915. app_id_cnt += 1
  916. logger.info("account_id=%s, app_id=%s, 程序化上新素材-通用视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  917. else:
  918. batch_general_video = general_video_list[i: len(general_video_list)]
  919. app_version = app_version_list[app_id_cnt]
  920. app_id = app_dict[app_version].get('appId', 'error')
  921. track_url = app_dict[app_version].get('trackUrl', 'error')
  922. sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign where account_id = %s """ % account_id
  923. campaign_df = pd.read_sql(sql, engine)
  924. for row in campaign_df.itertuples():
  925. if (app_version + '--优选广告位-' + '程序化上新素材') == getattr(row, 'campaign_name'):
  926. campaign_id = getattr(row, 'campaign_id')
  927. break
  928. request_data = get_request_data(account_id=account_id,
  929. campaign_id=campaign_id,
  930. video_info=batch_general_video,
  931. campaign_name=app_version + '--优选广告位-' + '程序化上新素材',
  932. group_name=app_version + '-优选广告位-不限-程序化-' + '上新素材',
  933. ai_strategy_remark="程序化上新素材",
  934. unit_type=7,
  935. app_id=app_id,
  936. click_track_url=track_url)
  937. request = ai_strategy_request_parse(request_data)
  938. logger.info("account_id=%s, app_id=%s, 程序化上新素材-通用视频,ai策略的返回信息:%s" % (account_id, app_id, request))
  939. else:
  940. logger.info("account_id=%s, 程序化上新素材: 返回的视频中没有通用视频" % account_id)
  941. self.write(json.dumps({"message": "account_id=%s, 程序化上新素材请求已走完!" % account_id}))
  942. self.flush()
  943. else:
  944. video_info = get_history_video_info(account_id=account_id,
  945. url=get_history_video_url,
  946. start_time=(datetime.datetime.now() + datetime.timedelta(days=-7)).
  947. strftime("%Y-%m-%d %H:%M:%S"),
  948. end_time=(datetime.datetime.now() + datetime.timedelta(days=-1)).
  949. strftime("%Y-%m-%d %H:%M:%S"),
  950. video_cnt=programme_new_video_cnt,
  951. related_creative_max_cnt=related_creative_max_cnt)
  952. if video_info['code'] != 0:
  953. self.write(json.dumps({"account_id": account_id,
  954. "message": "程序化上新素材,没有获取到视频,不发送ai策略请求!"}))
  955. self.flush()
  956. else:
  957. campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
  958. if (campaign_name is None) or (group_name is None):
  959. logger.info("没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!")
  960. self.write(json.dumps({"message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
  961. self.flush()
  962. else:
  963. request_data = get_request_data(account_id=account_id,
  964. campaign_id=campaign_id,
  965. video_info=video_info['data'],
  966. campaign_name=campaign_name,
  967. group_name=group_name,
  968. ai_strategy_remark="程序化上新素材",
  969. name_replace="程序化上新素材",
  970. unit_type=7)
  971. request = ai_strategy_request_parse(request_data)
  972. logger.info("account_id = %s, 程序化上新素材,ai策略的返回信息:%s" % (account_id, request))
  973. self.write(json.dumps(request))
  974. self.flush()
  975. except Exception:
  976. logger.error("account_id = %s, traceback is %s" % (account_id, traceback.format_exc()))
  977. self.write(json.dumps({"account_id": account_id, "message": traceback.format_exc(), "code": -1}))
  978. self.flush()