Exemplo n.º 1
0
def startAppWithConfig(params):
    MLog.debug(u"程序启动...")
    os.system("python -m uiautomator2 init")
    time.sleep(10)
    # 取序列号
    start_time = datetime.datetime.now()
    serial = getDevices()
    MLog.info(u"读取到的序列号 = " + str(serial))
    devices = []
    pool = Pool(len(serial) + 1)  # 取电脑核数
    for index in range(len(serial)):
        serial_number = serial[index]
        MLog.info(u"启动一个新进程 : index = " + str(index) + u" serial_number = " +
                  serial_number)
        deviceInfo = DeviceInfo(serial_number)
        devices.append(deviceInfo.getDeviceInfo())
        # pool.apply_async(test_main, args=(serial_number,))
        # 下面方法注释开会导致进程阻塞,debug时可以打开,运行时注释掉!!!
        result = pool.apply_async(test_main, args=(
            serial_number,
            1,
            params,
        ))
        result.get()
    pool.close()
    pool.join()
    # 生成图表
    create_lines(devices, getApkName())

    # sendEmailWithDefaultConfig()  # 发邮件
    end_time = datetime.datetime.now()
    MLog.info("all time = {}".format(end_time - start_time))
    MLog.info(u"end main...")
def match_img(img, target_img, values, match_path):
    # print img
    # print target_img
    # print match_path
    # 加载原始RGB
    img_rgb = cv2.imread(img)
    # 创建一个原始图像的灰度版本,所有操作在灰度版本中处理,然后在RGB图像中使用相同坐标还原
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    # 加载将要搜索的图像模板
    template = cv2.imread(target_img, 0)
    # 记录图像模板的尺寸,失败原因可能这个图片太大了
    w, h = template.shape[::-1]
    # 使用matchTemplate对原始灰度图像和图像模板进行匹配(调接口,这个值可以打印一下,不知道是个什么值)
    res = cv2.matchTemplate(img_gray, template,
                            cv2.TM_CCOEFF_NORMED)  # 最后这个参数可以试一下调一下
    # print "what! there is a result = {}".format(res)
    # 根据外部传参设置阈值
    threshold = values
    # print res >= threshold
    loc = np.where(res >= threshold)

    x = 0
    y = 0
    # 匹配完成后在原始图像中使用灰度图像的坐标对原始图像进行标记。
    mflag = False
    for pt in zip(*loc[::-1]):
        x = pt[0]
        y = pt[1]
        if x != 0 and y != 0 and not mflag:
            mflag = True
            feature = img_rgb[y:y + h, x:x + w]
            # 首帧多了很多遍操作。减少到1次
            cv2.imwrite(match_path, feature)
            MLog.debug("match_img: clip picture success path = " + img)
Exemplo n.º 3
0
def sendEmailWithDefaultConfig():
    user = u"*****@*****.**"
    password = u"lcqctgdcbvklghde"
    to_users = u"[email protected], [email protected],[email protected]"
    conf = Config("default.ini")
    apk_name = conf.getconf("default").apk_name
    conf = Config("default.ini")
    event = conf.getconf("serial").serial_number
    serial = event.split(',')
    deviceInfo = DeviceInfo(serial[0])
    subject = deviceInfo.getDeviceInfo() + apk_name + u"启动时间数据分析"
    content = u"数据分析详见附件:"
    contentType = u"application/octet-stream"
    try:

        log_file = make_log_patch()

        patchFile = []
        MLog.debug(u"sendmail sendEmailWithDefaultConfig: 收集邮件附件:")
        for files in os.walk(chart_data_path):
            for f in files[2]:
                new_file_path = files[0] + f
                patchFile.append(new_file_path)

        patchFile.append(log_file)

        MLog.debug(u"sendmail sendEmailWithDefaultConfig: " + str(patchFile))

    except Exception, e:
        MLog.error(u"sendmail sendEmailWithDefaultConfig: 收集附件失败! e = " +
                   repr(e))
        patchFile = None
Exemplo n.º 4
0
def write_data_to_file(type, device, apk, json_data):
    suffix = u".json"
    src = file_path + type + os.sep + device + os.sep
    checkSrcVialdAndAutoCreate(src)
    json_file = src + apk + suffix
    MLog.debug(u"data_center write_data_to_file:" + json_file)
    write_json(json_data, json_file)
Exemplo n.º 5
0
def multi_huya_calculate_parts(params):
    device_name = params["device"]  # 设备名称
    name_with_suffix = device_name + "_first"
    dir_index = params["dir_index"]  # 当前算的第几组数据
    # rgb_folder = calculate_homepage_rgb()  # 计算样本库的rgb均值
    conf = Config("apk.ini")
    conf_default = Config("default.ini")
    app_key = conf_default.getconf("default").app
    feature_dir = conf.getconf(app_key).feature  # 特征图的文件夹名字
    file_count = count_file("./screenrecord/" + name_with_suffix + "/" +
                            name_with_suffix + "_" + str(dir_index))
    real_path = "./screenrecord/" + name_with_suffix + "/" + name_with_suffix + "_" + str(
        dir_index) + "/"
    real_first_feature_path = path + "/picrepos/feature/" + feature_dir + "/" + device_name + "_launch_feature.jpg"
    if not exists(real_first_feature_path):
        MLog.debug(
            "calculate: first, there is no adapted feature pic for current Phone"
        )
        real_first_feature_path = path + "/picrepos/feature/" + feature_dir + "/common_launch_feature.jpg"
    # 中间launching判断
    real_launching_feature_path = path + "/picrepos/feature/" + feature_dir + "/" + device_name + "_launching_feature.jpg"
    real_last_feature_path = path + "/picrepos/feature/" + feature_dir + "/" + device_name + "_homepage_feature.jpg"
    first = first_frame_find(file_count, real_path,
                             real_first_feature_path)  # 取图片这些步骤好繁琐啊,想想有没办法改进下
    launching_index, last = huya_first_find_frame(
        file_count, first, real_path, real_launching_feature_path,
        real_last_feature_path, rgb_folder)  # 虎牙的计算也就只有这句不一样吊
    # frame_value = settings.get_value("ffmpeg")
    frame_value = 50
    total_time = int((last - first + 1) * (1000 / float(frame_value)))
    launching_time = int(
        (launching_index - first + 1) * (1000 / float(frame_value)))
    return dir_index, first, launching_index, last, total_time, launching_time, total_time - launching_time
Exemplo n.º 6
0
def clip_generate_flag(path1, path2):
    MLog.debug("clip_specific_pic(): the path = {}".format(path1))
    img = Image.open(path1)
    width = img.size[0]
    height = img.size[1]
    img = img.crop((0, 300, width, height - 200))
    img.save(path2)
Exemplo n.º 7
0
    def enterLiveRoom(self):
        # 启动APP
        self.start()
        time.sleep(15)
        if self.getEnterLiveRoom() > 0:
            if self.machineName == "PACM00":
                self.fileOperation.removeDirs("/sdcard/DCIM/Screenshots")
                MLog.info(u"删除 screenshot")
                path = os.path.dirname(__file__) + "\\"
                MLog.debug(u"screen_record_main enterLiveRoom: path = " + path)
                os.chdir(path)
                if os.path.exists("Screenshots"):
                    shutil.rmtree("Screenshots")

            enter_dir = self.tempDir + "_enterliveroom"
            self.fileOperation.mkdir(enter_dir)
            for index in range(int(self.getEnterLiveRoom())):
                self.startApp.enter(self.d, 10, enter_dir + '/' + str(index) + ".mp4", self.serNum)
                time.sleep(5)
                if self.machineName == "PACM00":
                    os.system('adb -s ' + self.serNum + ' shell service call statusbar 1')
                    self.d(text="停止录屏").click()
            time.sleep(5)
            if self.machineName == "PACM00":
                self.videoOperation.pullRecord("/sdcard/DCIM/Screenshots")
            else:
                self.videoOperation.pullRecord(enter_dir)
            path = os.path.abspath('.')
            folder = path + '/' + enter_dir
            MLog.debug(u"screen_record_main enterLiveRoom: path2 = " + path)
            os.chdir(folder)
            self.appOperation.killProcess()
            for index in range(int(self.getEnterLiveRoom())):
                self.videoOperation.videoToPhoto(str(enter_dir + "_" + str(index)), str(index))
            os.chdir(path)
Exemplo n.º 8
0
    def notFirstLaunch(self):
        if self.getNormalStartTime() > 0:
            if self.machineName == "PACM00":
                self.fileOperation.removeDirs("/sdcard/DCIM/Screenshots")
                MLog.info(u"删除 screenshot")
                path = os.path.dirname(__file__) + "\\"
                print path
                os.chdir(path)
                if os.path.exists("Screenshots"):
                    shutil.rmtree("Screenshots")

            notfirst_dir = self.tempDir + "_notfirst"
            self.fileOperation.mkdir(notfirst_dir)
            for index in range(int(self.getNormalStartTime())):

                self.appOperation.killProcess()
                self.startApp.startAPP(self.d, 15, notfirst_dir + '/' + str(index) + ".mp4")
                time.sleep(15)
                if self.machineName == "PACM00":
                    os.system('adb -s ' + self.serNum + ' shell service call statusbar 1')
                    self.d(text="停止录屏").click()
            time.sleep(10)
            if self.machineName == "PACM00":
                self.videoOperation.pullRecord("/sdcard/DCIM/Screenshots")
            else:
                self.videoOperation.pullRecord(notfirst_dir)
            path = os.path.abspath('.')
            folder = path + '/' + notfirst_dir
            MLog.debug(u"screen_record_main notFirstLaunch: path = " + path)
            os.chdir(folder)
            self.appOperation.killProcess()
            for index in range(int(self.getNormalStartTime())):
                self.videoOperation.videoToPhoto(str(notfirst_dir + "_" + str(index)), str(index))
            os.chdir(path)
Exemplo n.º 9
0
 def startAPP(self, d, times, name):
     try:
         MLog.debug(u"尝试启动app")
         self.startAppBySwipe(d, times, name)
     except Exception, e:
         MLog.debug(u"startAPP:" + u"启动app失败! e = " + repr(e) + "  " +
                    self.machineName)
         sysExit(u"程序退出,原因:启动app失败!")
Exemplo n.º 10
0
def checkSrcVialdAndAutoCreate(file_path):
    try:
        if not os.path.exists(file_path):
            MLog.debug(u"fileUtil checkSrcVialdAndAutoCreate: 文件路径不存在,现在创建一个...")
            os.makedirs(file_path)
            MLog.debug(u"fileUtil checkSrcVialdAndAutoCreate: 路径为:" + file_path)
    except IOError, e:
        MLog.error(u"fileUtil checkSrcVialdAndAutoCreate: 创建文件失败!,异常如下:")
        MLog.error(u"fileUtil checkSrcVialdAndAutoCreate:: e = " + repr(e))
Exemplo n.º 11
0
def last_and_launching_frame_find_rgb(length, from_index, real_path, real_launching_feature_path,
                                      real_last_feature_path, rgb_folder):
    launching_homepage_flag = True
    launching_index = -1
    homepage_index = -1
    for i in range(from_index+2, length+1):
        src_file_path = real_path + base_utils.adapter_num(i) + ".jpg"
        feature_name = base_utils.adapter_num(i) + "_feature.jpg"

        if launching_homepage_flag:
            # 进入启动页匹配
            flag = isLaunchingPage(src_file_path, real_launching_feature_path)
            if flag:
                MLog.debug("find_lanching_end_frame: " + src_file_path + " is launching frame")
                continue
            else:
                # 没匹配到,则先记录为启动结束帧,记得往前取一帧
                launching_index = i - 1
                clip_generate_flag(real_path + base_utils.adapter_num(i - 1) + ".jpg",
                                   real_path + base_utils.adapter_num(i - 1) + "_feature.jpg")
                MLog.debug("find_lanching_end_frame: " + src_file_path + " is not launching frame!!!!")
                launching_homepage_flag = False
        else:
            # 首页匹配
            # 取巧操作,取右下角的点,看他是不是纯白,来过滤掉还有蒙层的帧
            if not isHomepageFinish(src_file_path):
                MLog.info("index = {} is not at homepage".format(i))
                continue
            match_img(src_file_path, real_last_feature_path, threshold, real_path + feature_name)
            if base_utils.os.path.exists(real_path + feature_name):
                # 如果识别到了,拿来图片和图库对比,如果当前图片rgb值远大于图库的平均rgb
                # 认为这一帧还在加载中;反之,则认为当前为加载完成帧

                degree = calculate_by_hists(real_last_feature_path, real_path + feature_name)
                print "degree = {}    -----------------------------".format(degree)
                # 这个值是否还可以再调一下?这个值太难取了,有些手机的帧很模糊,有些手机又特别清楚
                if degree < 0.65:
                    continue

                dst_path = real_path + base_utils.adapter_num(i) + "_clip.jpg"
                clip_specific_pic(src_file_path, dst_path)
                if compare_rgb(dst_path, rgb_folder):
                    MLog.debug("the rgb test is passed")
                    if isHomePageLoadFinish(src_file_path, src_file_path[0: len(src_file_path) - 4] + "_loaded.jpg"):
                        MLog.debug("the loading test is passed")
                        homepage_index = i
                        return launching_index, homepage_index
            else:
                # 没找到首页特征图时,去找启动页的特征图
                tmp_flag = isLaunchingPage(src_file_path, real_launching_feature_path)
                if tmp_flag:
                    launching_homepage_flag = True
                    MLog.info("we find launching  pic agagin, the index = {}".format(i))
                    continue
        MLog.debug("last_frame_find_rgb: " + src_file_path + " is not last frame")
    return launching_index, homepage_index
Exemplo n.º 12
0
def clip(path, count):
    for i in range(1, count + 1):
        complete_path = path + base_utils.adapter_num(i) + ".jpg"
        MLog.debug("clip(): the complete path = {}".format(complete_path))
        img = Image.open(complete_path)
        width = img.size[0]
        height = img.size[1]
        img = img.crop((0, 300, width, height - 200))
        # os.remove(path)
        img.save(base_utils.rename_path(path, i))
Exemplo n.º 13
0
def rename_files():
    i = 1
    path = "../homepage"
    for file1 in os.listdir(path):
        if os.path.isfile(os.path.join(path, file1)) == True:
            new_name = rename(i)
            i += 1
            MLog.debug("其实这个方法我是拿来懒得手动改名字的, newname = {}".format(new_name))
            os.rename(os.path.join(path, file1), os.path.join(path, new_name))
            print "ok"
Exemplo n.º 14
0
def find_lanching_end_frame(start_index, length, feature_path, folder_path):
    for i in range(start_index, length+1):
        src_file_path = folder_path + base_utils.adapter_num(i) + ".jpg"
        if isLaunchingPage(src_file_path, feature_path):
            MLog.debug("find_lanching_end_frame: " + src_file_path + " is launching frame")
            continue
        else:
            MLog.debug("find_lanching_end_frame: " + src_file_path + " is not launching frame!!!!")
            clip_generate_flag(folder_path + base_utils.adapter_num(i-1) + ".jpg",
                               folder_path + base_utils.adapter_num(i - 1) + "_feature.jpg")
            return i - 1
    return -1
Exemplo n.º 15
0
 def installAPK(self, name):
     feature_path = self.getFeaturePath()
     path = os.path.dirname(__file__) + "\\"
     os.chdir(path)
     print path
     apk_path = feature_path + os.sep + "apk" + os.sep + name
     if not fileExist(apk_path):
         MLog.error(u"installAPK:" + u"请检查下你的apk安装包 " + name + u" 是否放置在:" +
                    feature_path + u"中的apk分类的路径下!")
         sysExit(u"应用退出,原因:安装失败!")
     MLog.debug(u"installAPK: 执行安装操作,包路径apk_path = " + apk_path)
     os.system("adb -s " + self.serNum + " install " + apk_path)
     MLog.info(u"app_operation installAPK: 安装成功! sermun = " + self.serNum)
Exemplo n.º 16
0
    def firstLaunch(self):
        if self.getFirstStartTime() > 0:
            if self.machineName == "PACM00":
                self.fileOperation.removeDirs("/sdcard/DCIM/Screenshots")
                MLog.info(u"删除 screenshot")
                path = os.path.dirname(__file__) + "\\"
                MLog.debug(u"screen_record_main firstLaunch: path = " + path)
                os.chdir(path)
                if os.path.exists("Screenshots"):
                    shutil.rmtree("Screenshots")
            self.appOperation.uninstallAPK()

            # firstTimes = firstLaunchTimes * 20
            first_dir = self.tempDir + "_first"
            self.fileOperation.mkdir(first_dir)
            if self.machineName != "PACM00":
                self.appOperation.installAPK(self.getApkName())
                time.sleep(20)  # 后续改成轮询是否有安装包的包名,有再录屏
            # screenRecord(firstTimes, first_dir + '/' + 'first.mp4')
            # startTime = time.time()
            for index in range(int(self.getFirstStartTime())):
                if self.machineName == "PACM00":
                    self.appOperation.uninstallAPK()
                    time.sleep(2)
                    self.appOperation.installAPK(self.getApkName())
                    time.sleep(15)
                    doInThread(self.registerEvent.inputListener, self.d, 0, self.serNum)
                else:
                    self.appOperation.clearData()
                    time.sleep(3)
                self.startApp.startAPP(self.d, 15, first_dir + '/' + str(index) + '.mp4')
                time.sleep(15)
                MLog.info(u"等待清除缓存...")
                if self.machineName == "PACM00":
                    os.system('adb -s ' + self.serNum + ' shell service call statusbar 1')
                    self.d(text="停止录屏").click()
            time.sleep(10)
            if self.machineName == "PACM00":
                self.videoOperation.pullRecord("/sdcard/DCIM/Screenshots")
            else:
                self.videoOperation.pullRecord(first_dir)
            path = os.path.abspath('.')
            folder = path + '/' + first_dir
            MLog.debug(u"screen_record_main firstLaunch: folder = " + folder)
            os.chdir(folder)
            self.appOperation.killProcess()
            for index in range(int(self.getFirstStartTime())):
                self.videoOperation.videoToPhoto(str(first_dir + "_" + str(index)), str(index))
            os.chdir(path)
def new_first_frame_find(start_index, length, real_path, real_feature_path):
    for i in range(start_index, length + 1):
        src_file_path = real_path + base_utils.adapter_num(i) + ".jpg"
        feature_name = real_path + base_utils.adapter_num(i) + "_feature.jpg"
        # print src_file_path
        # print real_feature_path
        match_img(src_file_path, real_feature_path, threshold, feature_name)
        if base_utils.os.path.exists(feature_name):
            # 首帧思路,如果识别到了,取出截取部分与特征图做个彩色直方图对比,确定
            degree = calculate_by_hists(real_feature_path, feature_name)
            # print degree
            if degree > 0.6:
                return i
        MLog.debug("new_first_frame_find: " + src_file_path +
                   " is not first frame")
    return -1
Exemplo n.º 18
0
def json_file_to_charts(type, device, apks):
    MLog.info(u"json_file_to_charts: type = " + type + u", device = " +
              device + u", apks =" + str(apks))
    # MLog.debug(u"json_file_to_charts: 开始生成折线图...")
    lines = []
    for apk in apks:
        file = get_json_file(type, device, apk)
        try:
            MLog.debug(u"尝试打开文件生成折线图,file = " + file)
            if not fileExist(file):
                continue
            lines.append(read_json(file))
        except Exception, e:
            MLog.error(u"打开文件失败" + file)
            MLog.error(u"e = " + repr(e))
            print lines
Exemplo n.º 19
0
def clip_specific_pic(path, dst_path):
    if path.find(".png") != -1:
        img = cv2.imread(path)
        # 防png
        path = path.replace(".png", ".jpg")
        cv2.imwrite(path, img)
    MLog.debug("clip_specific_pic(): the path = {}".format(path))
    img = Image.open(path)
    # img.convert("RGB")
    # img.save("F:\\cao.jpg")
    width = img.size[0]
    height = img.size[1]
    # 上面部分裁剪 12%, 下面部分裁剪0%
    top_margin = int(height * 0.12)
    bottom_margin = int(height * 0)
    img = img.crop((0, top_margin, width, height - bottom_margin))
    img.save(dst_path)
    return height
Exemplo n.º 20
0
def calculate_repos_rgb():
    conf = Config("apk.ini")
    conf_default = Config("default.ini")
    app_key = conf_default.getconf("default").app
    real_homepage = conf.getconf(app_key).homepage
    # homepage_dir = conf.getconf(real_homepage).feature
    path = feature_path + "/picrepos/homepage/" + real_homepage + "/"
    mean_r = 0
    mean_g = 0
    mean_b = 0
    length_file = base_utils.count_file(feature_path + "/picrepos/homepage/" + real_homepage)
    for i in range(1, length_file + 1):
        rgb = calculate_pic_rgb(path + base_utils.adapter_num(i) + ".jpg")
        mean_r += rgb[0]
        mean_g += rgb[1]
        mean_b += rgb[2]
    mean_r /= length_file
    mean_g /= length_file
    mean_b /= length_file
    MLog.debug("calculate_repos_rgb: the folder mean rgb: r = {}, g = {}, b = {}".format(mean_r, mean_g, mean_b))
    return mean_r, mean_g, mean_b
Exemplo n.º 21
0
def calcule_specific_area_rgb(path, x1, y1, x2, y2):
    x1 = int(x1)
    y1 = int(y1)
    x2 = int(x2)
    y2 = int(y2)
    im = Image.open(path)
    pix = im.load()
    mean_r = 0
    mean_g = 0
    mean_b = 0
    for i in range(x1, x2):
        for j in range(y1, y2):
            mean_r += pix[i, j][0]
            mean_g += pix[i, j][1]
            mean_b += pix[i, j][2]
    pixles = (x2 - x1) * (y2 - y1)
    mean_r /= pixles
    mean_g /= pixles
    mean_b /= pixles
    MLog.debug("mean: r = {}, g = {}, b = {}".format(mean_r, mean_g, mean_b))
    return mean_r, mean_g, mean_b
Exemplo n.º 22
0
def new_last_frame_find_rgb(start_index, length, real_path, real_feature_path, rgb_folder):
    for i in range(start_index, length+1):
        src_file_path = real_path + base_utils.adapter_num(i) + ".jpg"
        feature_name = base_utils.adapter_num(i) + "_feature.jpg"
        match_img(src_file_path, real_feature_path, threshold, real_path + feature_name)
        if base_utils.os.path.exists(real_path + feature_name):
            # 如果识别到了,拿来图片和图库对比,如果当前图片rgb值远大于图库的平均rgb
            # 认为这一帧还在加载中;反之,则认为当前为加载完成帧

            degree = calculate_by_hists(last_frame_feature, real_path + feature_name)
            # 这个值是否还可以再调一下?
            MLog.debug(u"new_last_frame_find_rgb: color degreee = {}".format(str(degree)))
            if degree < 0.41:
                continue

            # 识别到才裁剪
            clip_specific_pic(src_file_path)
            if compare_rgb(src_file_path, rgb_folder):
                return i
        MLog.debug("new_last_frame_find_rgb: " + src_file_path + " is not last frame")
    return -1
Exemplo n.º 23
0
def create_detail_sheet_by_json(sheet_name, file_name, title, json_data):
    if json_data is None or json_data is [] or len(json_data) == 0:
        MLog.error(u"json == None or json_data == [], return !")
        raise Exception(u"创建Excel时,传入的json数据是空的,所以抛出这个错误!")

    # 创建一个工作簿
    w = Workbook()
    # 创建一个工作表
    ws = w.add_sheet(sheet_name)
    style = init_normal_style()

    # 调整单元格宽度,先调20个够用
    content_size = 6000
    for i in range(0, 20):
        ws.col(i).width = content_size

    # 表格偏移量
    x_offset = 0
    y_offset = 0

    ws.write_merge(y_offset, y_offset, x_offset,
                   x_offset + len(json_data[0]) - 1,
                   unicode(str(title), 'utf-8'), style)

    for index in range(0, len(json_data)):
        cur = 0
        for key, value in json_data[index].items():
            if index == 0:
                # 写标题
                ws.write(y_offset + 1, x_offset + cur, key, style)
            # 写内容
            ws.write(index + y_offset + 2, x_offset + cur, value, style)
            cur += 1

    file_name = file_path + file_name

    checkSrcVialdAndAutoCreate(file_path)
    w.save(file_name + '.xls')
    MLog.debug(u"handledata create_detail_sheet_by_json: Excel文件生成路径:" +
               os.path.abspath(file_name) + ".xls")
Exemplo n.º 24
0
def write_data_local(device_name, enter_liveroom_datas, first_launch_all_datas,
                     first_lunch_splash_datas, normal_launch_all_datas,
                     normal_launch_splash_datas):
    # write log data
    MLog.info(
        u"--------------------------开始写入json数据到本地--------------------------")
    MLog.debug(u"首次启动总耗时->")
    MLog.info(
        json.dumps(first_launch_all_datas, ensure_ascii=False).decode('utf8'))
    MLog.debug(u"非首次启动总耗时>")
    MLog.info(
        json.dumps(normal_launch_all_datas, ensure_ascii=False).decode('utf8'))
    MLog.debug(u"首次启动闪屏页耗时->")
    MLog.info(
        json.dumps(first_lunch_splash_datas,
                   ensure_ascii=False).decode('utf8'))
    MLog.debug(u"非首次启动闪屏页耗时->")
    MLog.info(
        json.dumps(normal_launch_splash_datas,
                   ensure_ascii=False).decode('utf8'))
    MLog.debug(u"进直播间耗时->")
    MLog.info(
        json.dumps(enter_liveroom_datas, ensure_ascii=False).decode('utf8'))
    # 写 JSON 数据
    write_data_to_file(u"首次启动总耗时", device_name,
                       getApkName().split(".apk")[0], first_launch_all_datas)
    write_data_to_file(u"非首次启动总耗时", device_name,
                       getApkName().split(".apk")[0], normal_launch_all_datas)
    write_data_to_file(u"首次启动闪屏页耗时", device_name,
                       getApkName().split(".apk")[0], first_lunch_splash_datas)
    write_data_to_file(u"非首次启动闪屏页耗时", device_name,
                       getApkName().split(".apk")[0],
                       normal_launch_splash_datas)
    write_data_to_file(u"进直播间耗时", device_name,
                       getApkName().split(".apk")[0], enter_liveroom_datas)
    MLog.info(
        u"--------------------------写入json数据到本地结束--------------------------")
Exemplo n.º 25
0
 def mkdir(self, name):
     os.system('adb -s ' + self.serNum + ' shell rm -rf ' + self.saveDir +
               name)
     os.system('adb -s ' + self.serNum + ' shell mkdir -p ' + self.saveDir +
               name)
     MLog.debug(u"file_operation mkdir: SD卡文件夹创建成功")
     path = os.path.dirname(__file__) + "\\"
     os.chdir(path)
     MLog.debug(u"file_operation mkdir:" + u'创建文件夹' + path)
     if os.path.exists(name):
         shutil.rmtree(name)
     print name
     os.makedirs(name)
     MLog.debug(u"file_operation mkdir: 'PC文件夹创建成功")
Exemplo n.º 26
0
def huya_first_find_frame(length, from_index, real_path, real_launching_feature_path,
                          real_last_feature_path, rgb_folder):
    launching_homepage_flag = True
    launching_index = -1
    homepage_index = -1
    for i in range(from_index+2, length+1):
        src_file_path = real_path + base_utils.adapter_num(i) + ".jpg"
        feature_name = base_utils.adapter_num(i) + "_feature.jpg"

        if launching_homepage_flag:
            # 进入启动页匹配
            flag = isLaunchingPage(src_file_path, real_launching_feature_path)
            if flag:
                MLog.debug("find_lanching_end_frame: " + src_file_path + " is launching frame")
                continue
            else:
                # 没匹配到,则先记录为启动结束帧,记得往前取一帧
                launching_index = i - 1
                clip_generate_flag(real_path + base_utils.adapter_num(i - 1) + ".jpg",
                                   real_path + base_utils.adapter_num(i - 1) + "_feature.jpg")
                MLog.debug("find_lanching_end_frame: " + src_file_path + " is not launching frame!!!!")
                launching_homepage_flag = False
        else:
            match_img(src_file_path, real_last_feature_path, threshold, real_path + feature_name)
            if base_utils.os.path.exists(real_path + feature_name):
                # 如果识别到了,拿来图片和图库对比,如果当前图片rgb值远大于图库的平均rgb
                # 认为这一帧还在加载中;反之,则认为当前为加载完成帧

                degree = calculate_by_hists(real_last_feature_path, real_path + feature_name)
                print "degree = {}    -----------------------------".format(degree)
                # 这个值是否还可以再调一下?这个值太难取了,有些手机的帧很模糊,有些手机又特别清楚
                if degree < 0.735:
                    continue

                # 识别到才裁剪
                homepage_index = i
                return launching_index, homepage_index
            else:
                # 没找到首页特征图时,去找启动页的特征图
                tmp_flag = isLaunchingPage(src_file_path, real_launching_feature_path)
                if tmp_flag:
                    launching_homepage_flag = True
                    MLog.info("we find launching  pic agagin, the index = {}".format(i))
                    continue
        MLog.debug("last_frame_find_rgb: " + src_file_path + " is not last frame")
    return launching_index, homepage_index
Exemplo n.º 27
0
def create_from_file_per(src, title, show_avg):
    MLog.debug(u"data_transform create_from_file_per: 通过读取json文件生成图表数据")

    # 子目录或文件
    lst = []
    for item in os.listdir(src):
        item = item.decode('GB2312')
        path = os.path.join(src, item)
        if os.path.splitext(path)[1] == '.json':
            lst.append(path)
            MLog.debug(u"create_from_file_per: add path " + path)

    lines = []
    chart_items = []
    result_name = "chart"
    for file in lst:
        MLog.debug(u"create_from_file_per: file = " + file)
        lines.append(read_json(file))
    print lines

    file_name = title
    chart = ChartItem(file_name, lines, show_avg)
    chart_items.append(chart)
    create_charts(result_name, chart_items)
Exemplo n.º 28
0
def test_main(serial_num, method, params):
    deviceInfo = DeviceInfo(serial_num)
    settings._init()
    firstLaunchTimes, notFirstLaunchTimes, enterLiveTimes, apkName, package = get_start_params(
    )
    MLog.info("current Device = {}".format(serial_num))
    start_time = datetime.datetime.now()
    if params.install_method == Constants.autoInstall:  # 自动安装
        MLog.info(u"main test_main: 自动安装!")
        start_python(serial_num, params)
    else:  # 手动安装,判断有么有安装,没有安装提示,return,安装之后走
        if apkIsInstall(package):
            start_python(serial_num, params)
        else:
            print u"应用没有安装,请先安装应用"
            sys.exit()

    end_video_2_frame_time = datetime.datetime.now()
    MLog.info(u"录屏及切帧时间 time = {}".format(end_video_2_frame_time - start_time))

    path = os.path.dirname(__file__) + "\\"
    os.chdir(path)
    print path
    device_name = deviceInfo.getDeviceInfo()
    first_launch_result, normal_launch_result, enter_ent = start_calculate(
        device_name)
    MLog.debug("first_launch_result ==========")
    MLog.debug(first_launch_result)
    MLog.debug("normal_launch_result ==========")
    MLog.debug(normal_launch_result)
    MLog.debug("enter ent ==========")
    MLog.debug(enter_ent)

    first_launch_all_datas, normal_launch_all_datas, detail_data, avg_detail_data, first_lunch_splash_datas, normal_launch_splash_datas, enter_liveroom_datas = format_data(
        first_launch_result, normal_launch_result, enter_ent, apkName)
    end_calculate_time = datetime.datetime.now()
    MLog.info(u"计算时间 time ={}".format(end_calculate_time -
                                      end_video_2_frame_time))

    # ---------------------------- UI Part ------------------------------#
    # 创建表格
    create_sheet(detail_data, avg_detail_data, device_name)
    # 写入json数据到本地
    write_data_local(device_name, enter_liveroom_datas, first_launch_all_datas,
                     first_lunch_splash_datas, normal_launch_all_datas,
                     normal_launch_splash_datas)

    end_time = datetime.datetime.now()
    MLog.info(
        "all time = {}, video_frame time = {}, calculate time = {}, datacharts time = {}"
        .format(end_time - start_time, end_video_2_frame_time - start_time,
                end_calculate_time - end_video_2_frame_time,
                end_time - end_calculate_time))
Exemplo n.º 29
0
    params.sdk_path = ""  # 暂不生效,所以不传
    params.video_path = ""
    params.app_path = ""
    params.install_method = 1

    params.first_start_times = config.getFirstStartTime()
    params.normal_start_times = config.getNormalStartTime()
    params.enter_liveroom_times = config.getEnterLiveRoom()
    params.app_name = config.getAppName()
    params.package_name = config.getPackage()
    params.features = config.getFeaturePath()
    return params


if __name__ == '__main__':
    MLog.debug(u"程序启动...")
    config = BaseConfig()
    params = configToParams(config)
    os.system("python -m uiautomator2 init")
    time.sleep(10)
    # 取序列号
    start_time = datetime.datetime.now()
    serial = getDevices()
    MLog.info(u"读取到的序列号 = " + str(serial))
    devices = []
    pool = Pool(len(serial) + 1)  # 取电脑核数
    for index in range(len(serial)):
        serial_number = serial[index]
        MLog.info(u"启动一个新进程 : index = " + str(index) + u" serial_number = " +
                  serial_number)
        deviceInfo = DeviceInfo(serial_number)
Exemplo n.º 30
0
def sendEmail(authInfo,
              fromAdd,
              toAdd,
              subject,
              content,
              contentType='plain',
              patchFileList=None):
    def _format_addr(s):
        name, addr = parseaddr(
            s
        )  # 将email地址根据'< '符合分为两部分,如jack <[email protected],>会变成(jack,[email protected]
        return formataddr(( \
            Header(name, 'utf-8').encode(), \
            addr.encode('utf-8') if isinstance(addr, unicode) else addr))

    strFrom = fromAdd
    strTo = toAdd
    # 多个邮箱地址分割成list
    toAddList = toAdd.split(",")
    server = authInfo.get('server')
    smtpPort = 25
    sslPort = 465
    user = authInfo.get('user')
    passwd = authInfo.get('password')

    if not (server and user and passwd):
        MLog.debug(u"sendmail sendEmail: incomplete login info, exit now!")
        return

    # 设定root信息
    msgRoot = MIMEMultipart('alternative')
    msgRoot['Subject'] = Header(subject, 'utf-8').encode()
    msgRoot['From'] = _format_addr(u'%s<%s>' %
                                   (strFrom.split('@')[0], strFrom))
    msgRoot['To'] = strTo

    # 邮件正文内容
    if contentType == 'html':
        msgHtml = MIMEText(content, 'html', 'utf-8')
        msgRoot.attach(msgHtml)
    else:
        msgText = MIMEText(content, 'plain', 'utf-8')
        msgRoot.attach(msgText)

    # 设定附件信息
    if not patchFileList is None:
        MLog.debug(u"sendmail sendEmail: 打包附件:")
        for patchFile in patchFileList:
            # print patchFile
            with codecs.open(patchFile, 'rb') as f:
                patchFileName = patchFile.split("/")[-1]
                # 设置附件的MIME和文件名,这里是txt类型:
                msgPatch = MIMEBase('text', 'txt', filename=patchFileName)
                # 加上必要的头信息:
                msgPatch.add_header('Content-Disposition',
                                    'attachment',
                                    filename=patchFileName)
                msgPatch.add_header('Content-ID', '<0>')
                msgPatch.add_header('X-Attachment-Id', '0')
                # 把附件的内容读进来:
                msgPatch.set_payload(f.read())
                # 用Base64编码:
                encoders.encode_base64(msgPatch)
                # 添加到MIMEMultipart:
                msgRoot.attach(msgPatch)

    try:
        # 发送邮件
        smtp = smtplib.SMTP()
        # smtp.connect(server, smtpPort)
        # ssl加密方式,通信过程加密,邮件数据安全
        smtp = smtplib.SMTP_SSL()
        smtp.connect(server, sslPort)

        # 设定调试级别,依情况而定
        # smtp.set_debuglevel(1)
        smtp.login(user, passwd)
        smtp.sendmail(strFrom, toAddList, msgRoot.as_string())
        smtp.quit()
        MLog.debug(u"sendmail sendEmail: 邮件发送成功!")
    except Exception, e:
        MLog.error(u"sendmail sendEmail: 邮件发送失败! e = " + repr(e))