소스 검색

多应用功能完成60%

liyuyi@c-top.com.cn 4 년 전
부모
커밋
3f5dd28870
4개의 변경된 파일397개의 추가작업 그리고 100개의 파일을 삭제
  1. 9 6
      ai_strategy_request_func.py
  2. 341 91
      ai_time_task_creative_handler.py
  3. 43 3
      utils/CommonFunction.py
  4. 4 0
      utils/UrlConfig.py

+ 9 - 6
ai_strategy_request_func.py

@@ -72,7 +72,7 @@ class ParseAddCampaignOrAddGroupRequest(object):
     def __init__(self, request_data):
         self.ai_strategy_uuid = str(uuid.uuid4())
         self.request_data = request_data
-        self.video = self.request_data['video']['data']
+        self.video = self.request_data['video']
         self.account_id = self.request_data['account_id']
         self.campaign_info = self.request_data['campaign_info']
         self.campaign_id = self.request_data['campaign_info'].get('campaign_id', None)
@@ -208,16 +208,17 @@ class ParseAddCampaignOrAddGroupRequest(object):
                      'sticker_title', 'overlay_type', 'expose_tag', 'new_expose_tag', 'site_id',
                      'click_track_url', 'impression_url', 'ad_photo_played_t3s_url', 'actionbar_click_url',
                      'creative_category', 'creative_tag', 'image_cnt',
-                     'create_time', 'effective_time', 'expiry_time', 'timer_task_status']
+                     'create_time', 'effective_time', 'expiry_time', 'timer_task_status',
+                     'single_appid', 'app_id_array']
         for col in drop_cols:
             if col in group_params.keys():
                 del group_params[col]
 
-
         # 2 从请求的信息中更新组层级信息, 如组的名称、测试定向、测试出价等, update客户策略信息
         if (self.group_info is not None) and (len(self.group_info) > 0):
             for key, value in self.group_info.items():
-                group_params.update({key: value})
+                if value:
+                    group_params.update({key: value})
 
         # 3 smart_cover 和 asset_mining 需要将0/1 转化为 False/True
         group_params['smart_cover'] = True if group_params.get('smart_cover', 0) == 1 else False
@@ -259,7 +260,8 @@ class ParseAddCampaignOrAddGroupRequest(object):
         # 2 从请求的信息中更新创意层级的信息,如广告语
         if (self.creative_info is not None) and (len(self.creative_info) > 0):
             for key, value in self.creative_info.items():
-                creative_params.update({key: value})
+                if value:
+                    creative_params.update({key: value})
 
         # 3 拼装json的 创意参数
         creative_params_to_request = creative_params.copy()
@@ -292,7 +294,8 @@ class ParseAddCampaignOrAddGroupRequest(object):
         # 2 从请求的信息中更新创意层级的信息,如广告语,创意名称等
         if (self.creative_info is not None) and (len(self.creative_info) > 0):
             for key, value in self.creative_info.items():
-                creative_params.update({key: value})
+                if value:
+                    creative_params.update({key: value})
 
         # 3 程序化创意部分字段发生改变,需要重命名
         #   creative_name  --> package_name(程序化创意名称)

+ 341 - 91
ai_time_task_creative_handler.py

@@ -5,9 +5,8 @@ import logging
 import traceback
 import tornado.web
 from concurrent_log import ConcurrentTimedRotatingFileHandler
-# from logging.handlers import TimedRotatingFileHandler
 from utils.CommonFunction import get_history_video_info, get_new_video_info, get_missing_video_info, \
-                                 get_top_video_info, get_campaign_and_group_name_rule
+                                 get_top_video_info, get_campaign_and_group_name_rule,get_app_detail
 from utils.ConstantConfig import *
 from ai_strategy_request_func import ai_strategy_request_parse
 from utils.DataBaseConfig import *
@@ -36,34 +35,118 @@ class AiHistoricalMissingMaterial(tornado.web.RequestHandler):
         logger.info("账户信息=%s, 当前进程=%s, 当前进程的主进程=%s,  raw data from request is %s" %
                     (account_id, os.getpid(), os.getppid(), data))
         try:
-            video_info = get_missing_video_info(account_id,
-                                                missing_video_cnt,
-                                                get_missing_video_url,
-                                                missing_video_start_time,
-                                                missing_video_end_time)
-            if video_info['code'] != 0:
-                logger.info("the res of video is %s" % video_info['message'])
-                logger.info("没有获取到视频,不发送ai策略请求!")
-                self.write(json.dumps({"message": "没有获取到视频,不发送ai策略请求!"}))
+            sql = """
+            select account_id, single_appid, app_id_array, general_track from ctop_ai_kuaishou_advertiser_strategy
+            where account_id=%s and status=1 order by create_time desc limit 1
+            """ % account_id
+            df = pd.read_sql(sql, engine)
+            if df['general_track'].values[0] == 0:
+                for app_id in df['app_id_array'].values[0]:
+                    # 1、获取该 app_id 的应该详情
+                    app_id_info = get_app_detail(account_id=account_id,
+                                                 url=get_app_detail_url,
+                                                 app_id=app_id)
+                    if app_id_info['code'] != 0:
+                        logger.info('account_id=%s, app_id=%s,the res of get_app_detail is %s' %
+                                    (account_id, app_id, app_id_info['message']))
+                        continue
+
+                    # 2、依据 appVersion 的值,来判断当天是否已经有对应的计划,如果有则获取 campaign_id,没有则设置 campaign_name
+                    app_version = app_id_info['data'].get('appVersion', 'error')
+                    track_url = app_id_info['data'].get('trackUrl','error')
+
+                    start_time = (datetime.date.today()).strftime('%Y-%m-%d %H:%M:%S')
+                    end_time = (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
+                    sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign 
+                              where account_id = %s
+                              and put_create_time >= '%s'
+                              and put_create_time <= '%s'
+                                        """ % (account_id, start_time, end_time)
+                    campaign_df = pd.read_sql(sql, engine)
+                    for row in campaign_df.itertuples():
+                        if ('遗漏素材' in getattr(row, 'campaign_name')) and (app_version in getattr(row, 'campaign_name')):
+                            campaign_id = getattr(row, 'campaign_id')
+                            break
+
+                    # 3、获取通用视频5个
+                    general_video_info = get_missing_video_info(account_id=account_id,
+                                                                cnt=5,
+                                                                url=get_missing_video_url,
+                                                                start_time=missing_video_start_time,
+                                                                end_time=missing_video_end_time,
+                                                                app_version='all')
+                    if general_video_info['code'] != 0:
+                        logger.info('account_id=%s, app_id=%s, the res of general_video_info is %s' %
+                                    (account_id, app_id, general_video_info['message']))
+
+                    # 4、获取app_id对应的视频50个
+                    special_video_info = get_missing_video_info(account_id=account_id,
+                                                                cnt=50,
+                                                                url=get_missing_video_url,
+                                                                start_time=missing_video_start_time,
+                                                                end_time=missing_video_end_time,
+                                                                app_version=app_version)
+                    if special_video_info['code'] != 0:
+                        logger.info('account_id=%s, app_id=%s, the res of special_video_info is %s' %
+                                    (account_id, app_id, special_video_info['message']))
+
+                    # 5、video_info 合并
+                    full_video_info = []
+                    if general_video_info['code'] == 0:
+                        full_video_info.extend(general_video_info['data'])
+                    if special_video_info['code'] == 0:
+                        full_video_info.extend(special_video_info['data'])
+
+                    # 6、拼装request_data,调用ai_strategy_request_parse方法
+                    # 广告计划名称:渠道包 - 游戏名称 - 版位 - 日期
+                    # 广告组名称:渠道包 - 游戏名称 - 优选 - 不限(定向)-自定义 / 程序化 - 日期
+                    if full_video_info:
+                        request_data = get_request_data(account_id=account_id,
+                                                        campaign_id=campaign_id,
+                                                        video_info=full_video_info,
+                                                        campaign_name=app_version + '-优选广告位-' + '遗漏素材',
+                                                        group_name=app_version + '-优选广告位-不限-自定义-' + '遗漏素材',
+                                                        ai_strategy_remark="补充遗漏素材",
+                                                        unit_type=4,
+                                                        app_id=app_id,
+                                                        click_track_url=track_url)
+                        request = ai_strategy_request_parse(request_data)
+                        logger.info("account_id=%s, app_id=%s, ai策略的返回信息:%s" % (account_id, app_id, request))
+                    else:
+                        logger.info("account_id=%s, app_id=%s, 没有获取到视频,不发送ai策略请求!" % (account_id, app_id))
+
+                # TODO 返回信息如何组织内容
+                self.write(json.dumps({"account_id=%s, 多应用的补充遗漏素材请求已走完!" % account_id}))
                 self.flush()
             else:
-                campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
-                if (campaign_name is None) or (group_name is None):
-                    logger.info("没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!")
-                    self.write(json.dumps({"message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
+                video_info = get_missing_video_info(account_id,
+                                                    missing_video_cnt,
+                                                    get_missing_video_url,
+                                                    missing_video_start_time,
+                                                    missing_video_end_time)
+                if video_info['code'] != 0:
+                    logger.info("the res of video is %s" % video_info['message'])
+                    logger.info("没有获取到视频,不发送ai策略请求!")
+                    self.write(json.dumps({"message": "没有获取到视频,不发送ai策略请求!"}))
                     self.flush()
                 else:
-                    request_data = get_request_data(account_id=account_id,
-                                                    campaign_id=campaign_id,
-                                                    video_info=video_info,
-                                                    campaign_name=campaign_name,
-                                                    group_name=group_name,
-                                                    ai_strategy_remark="补充遗漏素材",
-                                                    name_replace="补充遗漏素材")
-                    request = ai_strategy_request_parse(request_data)
-                    logger.info("ai策略的返回信息:%s" % request)
-                    self.write(json.dumps(request))
-                    self.flush()
+                    campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
+                    if (campaign_name is None) or (group_name is None):
+                        logger.info("没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!")
+                        self.write(json.dumps({"message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
+                        self.flush()
+                    else:
+                        request_data = get_request_data(account_id=account_id,
+                                                        campaign_id=campaign_id,
+                                                        video_info=video_info['data'],
+                                                        campaign_name=campaign_name,
+                                                        group_name=group_name,
+                                                        ai_strategy_remark="补充遗漏素材",
+                                                        name_replace="补充遗漏素材")
+                        request = ai_strategy_request_parse(request_data)
+                        logger.info("ai策略的返回信息:%s" % request)
+                        self.write(json.dumps(request))
+                        self.flush()
         except Exception:
             logger.error(traceback.format_exc())
             self.write(json.dumps(traceback.format_exc()))
@@ -83,47 +166,125 @@ class AiAutoCreative(tornado.web.RequestHandler):
         campaign_id = data.get('campaign_id')
         logger.info("账户信息=%s, 当前进程=%s, 当前进程的主进程=%s,  raw data from request is %s" %
                     (account_id, os.getpid(), os.getppid(), data))
-        try:
-            start_time = (datetime.date.today()).strftime('%Y-%m-%d %H:%M:%S')
-            end_time = (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
 
-            # 1-1 获取当天计划中包含“自动上新”计划的,计划id
+        try:
             sql = """
-                                select campaign_id, campaign_name from ctop_kuaishou_campaign 
-                                where account_id = %s
-                                and put_create_time >= '%s'
-                                and put_create_time <= '%s'
-                                """ % (account_id, start_time, end_time)
+                        select account_id, single_appid, app_id_array, general_track from ctop_ai_kuaishou_advertiser_strategy
+                        where account_id=%s and status=1 order by create_time desc limit 1
+                        """ % account_id
             df = pd.read_sql(sql, engine)
-            for row in df.itertuples():
-                if '素材自动上新' in getattr(row, 'campaign_name'):
-                    campaign_id = getattr(row, 'campaign_id')
-                    break
+            if df['general_track'].values[0] == 0:
+                for app_id in df['app_id_array'].values[0]:
+                    # 1、获取该 app_id 的应该详情
+                    app_id_info = get_app_detail(account_id=account_id,
+                                                 url=get_app_detail_url,
+                                                 app_id=app_id)
+                    if app_id_info['code'] != 0:
+                        logger.info('account_id=%s, app_id=%s,the res of get_app_detail is %s' %
+                                    (account_id, app_id, app_id_info['message']))
+                        continue
 
-            video_info = get_new_video_info(account_id, get_new_video_url)
-            if video_info['code'] != 0:
-                logger.info("the res of video is %s" % video_info['message'])
-                logger.info("没有获取到视频,不发送ai策略请求!")
-                self.write(json.dumps({"message": "没有获取到视频,不发送ai策略请求!"}))
+                    # 2、依据 appVersion 的值,来判断当天是否已经有对应的计划,如果有则获取 campaign_id,没有则设置 campaign_name
+                    app_version = app_id_info['data'].get('appVersion', 'error')
+                    track_url = app_id_info['data'].get('trackUrl', 'error')
+
+                    start_time = (datetime.date.today()).strftime('%Y-%m-%d %H:%M:%S')
+                    end_time = (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
+                    sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign 
+                                          where account_id = %s
+                                          and put_create_time >= '%s'
+                                          and put_create_time <= '%s'
+                                                    """ % (account_id, start_time, end_time)
+                    campaign_df = pd.read_sql(sql, engine)
+                    for row in campaign_df.itertuples():
+                        if ('素材自动上新' in getattr(row, 'campaign_name')) and (app_version in getattr(row, 'campaign_name')):
+                            campaign_id = getattr(row, 'campaign_id')
+                            break
+
+                    # 3、获取通用视频
+                    general_video_info = get_new_video_info(account_id=account_id,
+                                                            url=get_new_video_url,
+                                                            app_version='all')
+                    if general_video_info['code'] != 0:
+                        logger.info('account_id=%s, app_id=%s, the res of general_video_info is %s' %
+                                    (account_id, app_id, general_video_info['message']))
+
+                    # 4、获取app_id对应的视频
+                    special_video_info = get_new_video_info(account_id=account_id,
+                                                            url=get_new_video_url,
+                                                            app_version=app_version)
+                    if special_video_info['code'] != 0:
+                        logger.info('account_id=%s, app_id=%s, the res of special_video_info is %s' %
+                                    (account_id, app_id, special_video_info['message']))
+
+                    # 5、video_info 合并
+                    full_video_info = []
+                    if general_video_info['code'] == 0:
+                        full_video_info.extend(general_video_info['data'])
+                    if special_video_info['code'] == 0:
+                        full_video_info.extend(special_video_info['data'])
+
+                    # 6、拼装request_data,调用ai_strategy_request_parse方法
+                    # 广告计划名称:渠道包 - 游戏名称 - 版位 - 日期
+                    # 广告组名称:渠道包 - 游戏名称 - 优选 - 不限(定向)-自定义 / 程序化 - 日期
+                    if full_video_info:
+                        request_data = get_request_data(account_id=account_id,
+                                                        campaign_id=campaign_id,
+                                                        video_info=full_video_info,
+                                                        campaign_name=app_version + '-优选广告位-' + '素材自动上新',
+                                                        group_name=app_version + '-优选广告位-不限-自定义-' + '素材自动上新',
+                                                        ai_strategy_remark="素材自动上新",
+                                                        unit_type=4,
+                                                        app_id=app_id,
+                                                        click_track_url=track_url)
+                        request = ai_strategy_request_parse(request_data)
+                        logger.info("account_id=%s, app_id=%s, ai策略的返回信息:%s" % (account_id, app_id, request))
+                    else:
+                        logger.info("account_id=%s, app_id=%s, 没有获取到视频,不发送ai策略请求!" % (account_id, app_id))
+
+                self.write(json.dumps({"account_id=%s, 多应用的素材自动上新请求已走完!" % account_id}))
                 self.flush()
             else:
-                campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
-                if (campaign_name is None) or (group_name is None):
-                    logger.info("没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!")
-                    self.write(json.dumps({"message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
+                start_time = (datetime.date.today()).strftime('%Y-%m-%d %H:%M:%S')
+                end_time = (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
+
+                # 1-1 获取当天计划中包含“自动上新”计划的,计划id
+                sql = """
+                                    select campaign_id, campaign_name from ctop_kuaishou_campaign 
+                                    where account_id = %s
+                                    and put_create_time >= '%s'
+                                    and put_create_time <= '%s'
+                                    """ % (account_id, start_time, end_time)
+                df = pd.read_sql(sql, engine)
+                for row in df.itertuples():
+                    if '素材自动上新' in getattr(row, 'campaign_name'):
+                        campaign_id = getattr(row, 'campaign_id')
+                        break
+
+                video_info = get_new_video_info(account_id, get_new_video_url)
+                if video_info['code'] != 0:
+                    logger.info("the res of video is %s" % video_info['message'])
+                    logger.info("没有获取到视频,不发送ai策略请求!")
+                    self.write(json.dumps({"message": "没有获取到视频,不发送ai策略请求!"}))
                     self.flush()
                 else:
-                    request_data = get_request_data(account_id=account_id,
-                                                    campaign_id=campaign_id,
-                                                    video_info=video_info,
-                                                    campaign_name=campaign_name,
-                                                    group_name=group_name,
-                                                    ai_strategy_remark="自动上新",
-                                                    name_replace="素材自动上新")
-                    request = ai_strategy_request_parse(request_data)
-                    logger.info("ai策略的返回信息:%s" % request)
-                    self.write(json.dumps(request))
-                    self.flush()
+                    campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
+                    if (campaign_name is None) or (group_name is None):
+                        logger.info("没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!")
+                        self.write(json.dumps({"message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
+                        self.flush()
+                    else:
+                        request_data = get_request_data(account_id=account_id,
+                                                        campaign_id=campaign_id,
+                                                        video_info=video_info['data'],
+                                                        campaign_name=campaign_name,
+                                                        group_name=group_name,
+                                                        ai_strategy_remark="自动上新",
+                                                        name_replace="素材自动上新")
+                        request = ai_strategy_request_parse(request_data)
+                        logger.info("ai策略的返回信息:%s" % request)
+                        self.write(json.dumps(request))
+                        self.flush()
         except Exception:
             logger.error(traceback.format_exc())
             self.write(json.dumps(traceback.format_exc()))
@@ -144,32 +305,117 @@ class AiHighQualityMaterial(tornado.web.RequestHandler):
         logger.info("账户信息=%s, 当前进程=%s, 当前进程的主进程=%s,  raw data from request is %s" %
                     (account_id, os.getpid(), os.getppid(), data))
         try:
-            video_info = get_top_video_info(account_id, high_quality_video_cnt,
-                                            (datetime.datetime.now() + datetime.timedelta(days=-high_quality_video_days)).strftime("%Y-%m-%d"),
-                                             str(datetime.date.today()), get_high_quality_video_url)
-            if video_info['code'] != 0:
-                logger.info("the res of video is %s" % video_info['message'])
-                logger.info("没有获取到视频,不发送ai策略请求!")
-                self.write(json.dumps({"message": "没有获取到视频,不发送ai策略请求!"}))
+            sql = """select account_id, single_appid, app_id_array, general_track from ctop_ai_kuaishou_advertiser_strategy
+                     where account_id=%s and status=1 order by create_time desc limit 1
+                     """ % account_id
+            df = pd.read_sql(sql, engine)
+            if df['general_track'].values[0] == 0:
+                for app_id in df['app_id_array'].values[0]:
+                    # 1、获取该 app_id 的应该详情
+                    app_id_info = get_app_detail(account_id=account_id,
+                                                 url=get_app_detail_url,
+                                                 app_id=app_id)
+                    if app_id_info['code'] != 0:
+                        logger.info('account_id=%s, app_id=%s,the res of get_app_detail is %s' %
+                                    (account_id, app_id, app_id_info['message']))
+                        continue
+
+                    # 2、依据 appVersion 的值,来判断当天是否已经有对应的计划,如果有则获取 campaign_id,没有则设置 campaign_name
+                    app_version = app_id_info['data'].get('appVersion', 'error')
+                    track_url = app_id_info['data'].get('trackUrl', 'error')
+
+                    start_time = (datetime.date.today()).strftime('%Y-%m-%d %H:%M:%S')
+                    end_time = (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
+                    sql = """ select campaign_id, campaign_name from ctop_kuaishou_campaign 
+                              where account_id = %s
+                              and put_create_time >= '%s'
+                              and put_create_time <= '%s'
+                              """ % (account_id, start_time, end_time)
+                    campaign_df = pd.read_sql(sql, engine)
+                    for row in campaign_df.itertuples():
+                        if ('高质量素材' in getattr(row, 'campaign_name')) and (app_version in getattr(row, 'campaign_name')):
+                            campaign_id = getattr(row, 'campaign_id')
+                            break
+
+                    # 3、获取通用视频
+                    general_video_info = get_top_video_info(account_id=account_id,
+                                                            url=get_high_quality_video_url,
+                                                            start_time=(datetime.datetime.now() +
+                                                                        datetime.timedelta(days=-high_quality_video_days)).
+                                                            strftime("%Y-%m-%d"),
+                                                            end_time=str(datetime.date.today()),
+                                                            app_version='all')
+                    if general_video_info['code'] != 0:
+                        logger.info('account_id=%s, app_id=%s, the res of general_video_info is %s' %
+                                    (account_id, app_id, general_video_info['message']))
+
+                    # 4、获取app_id对应的视频
+                    special_video_info = get_top_video_info(account_id=account_id,
+                                                            url=get_high_quality_video_url,
+                                                            start_time=(datetime.datetime.now() +
+                                                                        datetime.timedelta(days=-high_quality_video_days)).
+                                                            strftime("%Y-%m-%d"),
+                                                            end_time=str(datetime.date.today()),
+                                                            app_version=app_version)
+                    if special_video_info['code'] != 0:
+                        logger.info('account_id=%s, app_id=%s, the res of special_video_info is %s' %
+                                    (account_id, app_id, special_video_info['message']))
+
+                    # 5、video_info 合并
+                    full_video_info = []
+                    if general_video_info['code'] == 0:
+                        full_video_info.extend(general_video_info['data'])
+                    if special_video_info['code'] == 0:
+                        full_video_info.extend(special_video_info['data'])
+
+                    # 6、拼装request_data,调用ai_strategy_request_parse方法
+                    # 广告计划名称:渠道包 - 游戏名称 - 版位 - 日期
+                    # 广告组名称:渠道包 - 游戏名称 - 优选 - 不限(定向)-自定义 / 程序化 - 日期
+                    if full_video_info:
+                        request_data = get_request_data(account_id=account_id,
+                                                        campaign_id=campaign_id,
+                                                        video_info=full_video_info,
+                                                        campaign_name=app_version + '-优选广告位-' + '高质量素材',
+                                                        group_name=app_version + '-优选广告位-不限-自定义-' + '高质量素材',
+                                                        ai_strategy_remark="高质量素材复建",
+                                                        unit_type=4,
+                                                        app_id=app_id,
+                                                        click_track_url=track_url)
+                        request = ai_strategy_request_parse(request_data)
+                        logger.info("account_id=%s, app_id=%s, ai策略的返回信息:%s" % (account_id, app_id, request))
+                    else:
+                        logger.info("account_id=%s, app_id=%s, 没有获取到视频,不发送ai策略请求!" % (account_id, app_id))
+
+                self.write(json.dumps({"account_id=%s, 多应用的高质量素材复建请求已走完!" % account_id}))
                 self.flush()
             else:
-                campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
-                if (campaign_name is None) or (group_name is None):
-                    logger.info("没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!")
-                    self.write(json.dumps({"message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
+                video_info = get_top_video_info(account_id, high_quality_video_cnt,
+                                                (datetime.datetime.now() + datetime.timedelta(
+                                                    days=-high_quality_video_days)).strftime("%Y-%m-%d"),
+                                                str(datetime.date.today()), get_high_quality_video_url)
+                if video_info['code'] != 0:
+                    logger.info("the res of video is %s" % video_info['message'])
+                    logger.info("没有获取到视频,不发送ai策略请求!")
+                    self.write(json.dumps({"message": "没有获取到视频,不发送ai策略请求!"}))
                     self.flush()
                 else:
-                    request_data = get_request_data(account_id=account_id,
-                                                    campaign_id=campaign_id,
-                                                    video_info=video_info,
-                                                    campaign_name=campaign_name,
-                                                    group_name=group_name,
-                                                    ai_strategy_remark="高质量素材复建",
-                                                    name_replace="高质量素材")
-                    request = ai_strategy_request_parse(request_data)
-                    logger.info("ai策略的返回信息:%s" % request)
-                    self.write(json.dumps(request))
-                    self.flush()
+                    campaign_name, group_name = get_campaign_and_group_name_rule(account_id)
+                    if (campaign_name is None) or (group_name is None):
+                        logger.info("没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!")
+                        self.write(json.dumps({"message": "没有获取到广告计划命名规则 或 广告组命名规则,不发送ai策略请求!"}))
+                        self.flush()
+                    else:
+                        request_data = get_request_data(account_id=account_id,
+                                                        campaign_id=campaign_id,
+                                                        video_info=video_info['data'],
+                                                        campaign_name=campaign_name,
+                                                        group_name=group_name,
+                                                        ai_strategy_remark="高质量素材复建",
+                                                        name_replace="高质量素材")
+                        request = ai_strategy_request_parse(request_data)
+                        logger.info("ai策略的返回信息:%s" % request)
+                        self.write(json.dumps(request))
+                        self.flush()
         except Exception:
             logger.error(traceback.format_exc())
             self.write(json.dumps(traceback.format_exc()))
@@ -263,7 +509,7 @@ class AiCheckAndUpTOFullCreative(tornado.web.RequestHandler):
                     else:
                         request_data = get_request_data(account_id=account_id,
                                                         campaign_id=campaign_id,
-                                                        video_info=video_info,
+                                                        video_info=video_info['data'],
                                                         campaign_name=campaign_name,
                                                         group_name=group_name,
                                                         ai_strategy_remark="用高质量素材补满创意",
@@ -329,7 +575,7 @@ class AiProgramCreativeHighQualityMaterial(tornado.web.RequestHandler):
                 else:
                     request_data = get_request_data(account_id=account_id,
                                                     campaign_id=campaign_id,
-                                                    video_info=video_info,
+                                                    video_info=video_info['data'],
                                                     campaign_name=campaign_name,
                                                     group_name=group_name,
                                                     ai_strategy_remark="程序化高质量素材",
@@ -383,7 +629,7 @@ class AiProgramCreativeNewMaterial(tornado.web.RequestHandler):
                 else:
                     request_data = get_request_data(account_id=account_id,
                                                     campaign_id=campaign_id,
-                                                    video_info=video_info,
+                                                    video_info=video_info['data'],
                                                     campaign_name=campaign_name,
                                                     group_name=group_name,
                                                     ai_strategy_remark="程序化上新素材",
@@ -399,9 +645,9 @@ class AiProgramCreativeNewMaterial(tornado.web.RequestHandler):
             self.flush()
 
 
-def get_request_data(account_id, campaign_id, video_info,
-                     campaign_name, group_name, ai_strategy_remark,
-                     name_replace, unit_type=4):
+def get_request_data(account_id, campaign_id, video_info, campaign_name, group_name,
+                     ai_strategy_remark, name_replace='',
+                     unit_type=4, click_track_url=None, app_id=None):
     res = {
         "video": video_info,
         "operation_type": 1,
@@ -409,11 +655,15 @@ def get_request_data(account_id, campaign_id, video_info,
         "ai_strategy_remark": ai_strategy_remark,
         "campaign_info":
             {"campaign_id": campaign_id,
-             "campaign_name": campaign_name.replace('自定义', name_replace) + str(datetime.datetime.now())},
+             "campaign_name": (campaign_name.replace('自定义', name_replace) + str(datetime.datetime.now()))
+             if not name_replace else (campaign_name + str(datetime.datetime.now()))},
         'group_info':
-            {'group_name': group_name.replace('自定义', name_replace) + str(datetime.datetime.now()),
+            {'group_name': (group_name.replace('自定义', name_replace) + str(datetime.datetime.now()))
+                if not name_replace else (group_name + str(datetime.datetime.now())),
              'begin_time': str(datetime.date.today()),
-             'unit_type': unit_type},
-        'creative_info': {'is_sticky': 0}
+             'unit_type': unit_type,
+             'app_id': app_id},
+        'creative_info': {'is_sticky': 0,
+                          'click_track_url': click_track_url}
     }
     return res

+ 43 - 3
utils/CommonFunction.py

@@ -14,6 +14,43 @@ def get_lower_case_name(name):
     return "".join(lst).lower()
 
 
+def get_app_detail(account_id, url, app_id):
+    """
+    获取应用详情
+    url:http://localhost:8080/jeecg-boot/ai/aiKuaiShouAppInfo/getAppDetail
+    请求方式:post
+    入参:accountId 账户id
+         appId     应用id
+    返回参数:
+     {
+        "code": 0,
+        "data": {
+        "id": 413,
+        "accountId": 9864909,
+        "appVersion": "ksjyrlyn-人类一脑涂地大败",
+        "appName": "233乐园",
+        "packageName": "com.meta.box",
+        "platform": 1,
+        "url": "https://www.233leyuan.com/apiserv/api/deliveryTest/ABTest?id=ksjyrlyn",
+        "useSdk": 0,
+        "appPrivacyUrl": "https://webcdn.233leyuan.com/app/useragreement/metax/privacyagreement.html",
+        "trackUrl": "https://lnk0.com/kYZxds?chn=451&imei_md5=__IMEI2__&androidid_md5_1=__ANDROIDID2__&oaid=__OAID__&adcampaign=__DNAME__&adcreative=__CID__&adgroup=__AID__&did=__DID__&accountid=__ACCOUNTID__&platform=__OS__&clicktime=__TS__&ip=__IP__&useragent=__UA__&channelapp=__CSITE__&callback_url=__CALLBACK__&action=none",
+        "appMd5": "0b2314c738956dc159ed38dc584ef214",
+        "imageToken": "marketb3e98f5f68a74870b8d8d814499d6189.jpg",
+        "status": 2,
+        "remark": "创建应用成功",
+        "appId": 3543665,
+        "createTime": "2021-02-03 16:40:53",
+        "updateTime": "2021-02-03 16:42:52"},
+    "message": "success"
+    }
+    """
+    request_data = {"accountId": account_id, "appId": app_id}
+    request = requests.post(url=url, headers=headers, data=json.JSONEncoder().encode(request_data)).text
+    request = json.loads(request)
+    return request
+
+
 def get_history_video_info(account_id, url, start_time, end_time, video_cnt, related_creative_max_cnt):
     """
     url:http://192.168.1.8:8080/jeecg-boot/kuaishou/material/getHistoryVideoList
@@ -35,7 +72,6 @@ def get_history_video_info(account_id, url, start_time, end_time, video_cnt, rel
     return request
 
 
-
 def get_new_video_info(account_id, url):
     """
     url:http://192.168.1.8:8080/jeecg-boot/kuaishou/material/getNewVideoList
@@ -49,7 +85,7 @@ def get_new_video_info(account_id, url):
     return request
 
 
-def get_missing_video_info(account_id, cnt, url, start_time, end_time):
+def get_missing_video_info(account_id, cnt, url, start_time, end_time, app_version=None):
     """
     url:"http://192.168.1.8:8080/jeecg-boot/kuaishou/material/getCreateZeroVideoList"
     请求方式:POST
@@ -60,8 +96,12 @@ def get_missing_video_info(account_id, cnt, url, start_time, end_time):
         startTime: 开始时间
         endTime:   结束时间
     """
+    if not app_version:
+        request_data = {"accountId": account_id, "videoCnt": cnt, "startTime": start_time, "endTime": end_time}
+    else:
+        request_data = {"accountId": account_id, "videoCnt": cnt, "startTime": start_time, "endTime": end_time,
+                        'appVersion': app_version}
 
-    request_data = {"accountId": account_id, "videoCnt": cnt, "startTime": start_time, "endTime": end_time}
     request = requests.post(url, headers=headers, data=json.JSONEncoder().encode(request_data)).text
     request = json.loads(request)
     return request

+ 4 - 0
utils/UrlConfig.py

@@ -16,6 +16,8 @@ if os_env_code_status == 'dev':
     get_missing_video_url = "http://192.168.1.8:8080/jeecg-boot/kuaishou/material/getCreateZeroVideoList"
     # 获取历史高质量视频url
     get_high_quality_video_url = "http://192.168.1.8:8080/jeecg-boot/kuaishou/material/getHistoryTopVideoList"
+    # 获取应用详情
+    get_app_detail_url = "http://localhost:8080/jeecg-boot/ai/aiKuaiShouAppInfo/getAppDetail"
 else:
     print("生产环境--url!")
     # 创建计划url
@@ -30,3 +32,5 @@ else:
     get_missing_video_url = "http://api.tjyourong.com.cn/jeecg-boot/kuaishou/material/getCreateZeroVideoList"
     # 获取历史高质量视频url
     get_high_quality_video_url = "http://api.tjyourong.com.cn/jeecg-boot/kuaishou/material/getHistoryTopVideoList"
+    # 获取应用详情
+    get_app_detail_url = "http://api.tjyourong.com.cn/jeecg-boot/ai/aiKuaiShouAppInfo/getAppDetail"