def create_versioned_spell_icons(championfull, summoners):
    if not os.path.exists(os.path.join(ver_path, "spell")):
        os.makedirs(os.path.join(ver_path, "spell"))
    # Champion Spells
    champion_summary = download.download_versioned_cdragon_champion_summary()
    for x in champion_summary:
        champion = download.download_versioned_cdragon_champion(
            "default", x['id'])
        for i, spell in enumerate(champion['spells']):
            image = download.download_image(
                get_cdragon_url(spell['abilityIconPath']))
            name = championfull['data'][x['alias']]['spells'][i]['id']
            with open(os.path.join(ver_path, f"spell/{name}.png"), "wb") as f:
                f.write(image)
    # Summoner Spells
    cdragon_summoners = download.download_versioned_cdragon_summoner_spells(
        "default")
    for summoner, value in summoners['data'].items():
        for x in cdragon_summoners:
            if str(x['id']) == value['key']:
                url = get_cdragon_url(x['iconPath'])
                image = download.download_image(url)
                with open(os.path.join(ver_path, f"spell/{summoner}.png"),
                          "wb") as f:
                    f.write(image)

    return
def spacex(number_of_launches, path):
    spacex_api_url = 'https://api.spacexdata.com/v3/launches'
    all_launches = get_all_launches(spacex_api_url)
    complete_launches = find_all_complete_launches(all_launches)
    last_complete_launches = find_last_launches(complete_launches,
                                                number_of_launches)
    launches_images = get_launch_image_url(last_complete_launches)
    random_images = get_random_flickr_image(launches_images)
    for url in random_images:
        download_image(url, path)
Beispiel #3
0
def _download(image_id, image_root):

    print("image {} is downloading...".format(image_id))
    image_root = os.path.join(image_root, "append")
    download_image(image_id=image_id, image_root=image_root)
    image_filepath = os.path.join(image_root, image_id)
    image = imread(fname=image_filepath + "_.jpg")
    image = resize_image(
        image=image, large_side=self._image_large_side
    )
    imsave(fname=image_filepath + ".jpg", arr=image)
Beispiel #4
0
def rank(bot, update):
    """
    处理 /rank 命令的函数
    工作流程:
        1. 从日榜中随机获取一张图片的信息
        2. 检查对应头像是否在文件缓存中,有转7
        3. 下载图片,尝试截取头像,失败转5
        4. 把新头像加入文件缓存,转7
        5. 拉黑失败的图片信息,从文件缓存中随机获取一张头像,成功转7
        6. 回复失败,退出
        7. 回复图片,退出
    """
    illust = get_illust_from_ranking()
    url = illust.image_urls.large
    filename = (str(illust.id) + "." + url.split(".")[-1]).encode("ascii")
    # 否则redis缓存时有编码问题
    filepath = os.path.join(CACHE_DIR, filename)
    avatar_filepath = os.path.join(CACHE_DIR, "avatar_" + filename)

    success = False
    # 是否回复图片

    if not find_cache(avatar_filepath):  # cache中没有该头像文件
        success = download_image(url, CACHE_DIR, filename) and generate_avatar(
            CACHE_DIR, filename)
        if os.path.exists(filepath): os.remove(filepath)

        # 下载文件和提取头像都成功
        if success:
            add_cache(avatar_filepath)
            # 把新头像加入缓存

        # 从缓存中随机取头像
        else:
            blacklist_illust_in_ranking(illust.id)
            # 把失败的尝试拉入黑名单
            avatar_filepath = get_random_from_cache()

            # 没有缓存头像,才会真正失败
            success = (avatar_filepath is not None)
    else:
        success = True

    if success:
        with open(avatar_filepath, "rb") as f:
            update.message.reply_photo(f)
            pid = filter(str.isdigit, avatar_filepath)
            # 从文件名提取pixiv id
            update.message.reply_text("pixiv id = %s" % str(pid))
    else:
        update.message.reply_text(NO_AVATAR_TEXT)
Beispiel #5
0
def search_impl(bot, update):
    """
    处理 /search 命令的函数,关键词搜索的实现
    工作流程:
        1. 根据关键词随机获取一张图片的信息
        2. 检查对应头像是否在文件缓存中,有转6
        3. 下载图片,尝试截取头像,失败转5
        4. 把新头像加入文件缓存,转6
        5. 回复失败,退出
        6. 回复图片,退出
    """
    keywords = update.message.text + " 100"
    # 通过人气保证图片质量
    illust = get_illust_from_keywords(keywords)

    # 关键词错误等原因,没有符合条件的图片
    if illust is None:
        update.message.reply_text(ERROR_KEYWORD_TEXT)
        return ConversationHandler.END

    url = illust.image_urls.large
    filename = (str(illust.id) + "." + url.split(".")[-1]).encode("ascii")
    # 否则redis缓存时有编码问题
    filepath = os.path.join(CACHE_DIR, filename)
    avatar_filepath = os.path.join(CACHE_DIR, "avatar_" + filename)

    success = False
    # 是否回复图片

    if not find_cache(avatar_filepath):  # cache中没有该头像文件
        success = download_image(url, CACHE_DIR, filename) and generate_avatar(
            CACHE_DIR, filename)
        if os.path.exists(filepath): os.remove(filepath)

        # 下载文件和提取头像都成功
        if success:
            add_cache(avatar_filepath)
            # 把新头像加入缓存
    else:
        success = True

    if success:
        with open(avatar_filepath, "rb") as f:
            update.message.reply_photo(f)
            pid = filter(str.isdigit, avatar_filepath)
            # 从文件名提取pixiv id
            update.message.reply_text("pixiv id = %s" % str(pid))
    else:
        update.message.reply_text(NO_AVATAR_TEXT)
    return ConversationHandler.END
def create_versioned_champion_passives():
    if not os.path.exists(os.path.join(ver_path, "passive")):
        os.makedirs(os.path.join(ver_path, "passive"))
    cdragon_champions = download.download_versioned_cdragon_champion_summary()
    for champion in cdragon_champions:
        cdragon_champion = download.download_versioned_cdragon_champion(
            "default", champion['id'])
        url = get_cdragon_url(cdragon_champion['passive']['abilityIconPath'])
        image = download.download_image(url)
        with open(
                os.path.join(
                    ver_path,
                    f"passive/{get_image_name_from_path(cdragon_champion['passive']['abilityIconPath'])}"
                ), "wb") as f:
            f.write(image)
    return
Beispiel #7
0
def show_pictures(urls):
    # Picture display's GUI settings
    root = tk.Tk()
    root.resizable(width=False, height=False)
    rows = 0
    columns = 0
    MAX_NUMBER_OF_COLUMNS = 4

    for url in urls:
        # Browser settings
        user_agent = 'Mozilla/5.0 (compatible; MSIE 5.5; Windows NT)'
        req = Request(url, headers={'User-Agent': user_agent})
        req.add_header(
            'Accept',
            'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        )
        context = ssl._create_unverified_context()

        # Attempt to open url to check if valid
        try:
            u = urlopen(req, context=context)
        except Exception as e:
            print(e)
            continue

        # Grab data from url
        raw_data = u.read()
        u.close()
        image_file = Image.open(BytesIO(raw_data))
        image_file = image_file.resize((400, 400), Image.ANTIALIAS)
        photo_image = ImageTk.PhotoImage(image_file)

        # Set labels to have images, and attach event to download image when clicked
        label = tk.Label(image=photo_image)
        label.image = photo_image
        label.grid(row=rows, column=columns)
        label.bind(
            "<Button-1>",
            lambda event, image_link=url: download_image(event, image_link))

        # Increase columns until max columns are reached, and then columns are reset and a new row is added
        columns += 1
        if columns == MAX_NUMBER_OF_COLUMNS:
            rows += 1
            columns = 0

    root.mainloop()
Beispiel #8
0
def convert():
    # POSTリクエストの場合はreCAPTCHAの検証を行う
    # https://developers.google.com/recaptcha/docs/verify
    if request.method == 'POST':
        recaptchaToken = request.get_json().get('recaptchaToken', None)
        if not verify_recaptcha_v3(recaptchaToken):
            return 'Invalid request.\n', 400

    image_url = request.args.get("url", "")
    if not validators.url(image_url):
        return 'Invalid URL: %s\n' % image_url, 400
    size = parse_thumbnail_size(request)
    auto = parse_histogram_equalization(request)
    save_format = parse_output_format(request)
    threshold = parse_binarization_threshold(request)
    base_image_mode = parse_base_image_mode(request)

    # 画像をダウンロード
    input_file_name = ''
    try:
        input_file_name = download_image(image_url)
    except Exception as e:
        return 'Invalid request: %s\n' % e, 400

    if not input_file_name:
        return 'Error: input_file_name is empty.\n', 500

    # 画像を点描画に変換
    output_file_path = ''
    try:
        print(size, auto)
        output_file_path = main(input_file_name,
                                thumbnail_size=size,
                                histogram_equalization=auto,
                                save_format=save_format,
                                binarization_threshold=threshold,
                                base_image_mode=base_image_mode)
    except Exception as e:
        print(e)
        return 'Error: %s' % e, 500

    if output_file_path == '':
        return 'Error: output_file_path is empty.\n', 500

    return send_file(output_file_path,
                     as_attachment=False,
                     mimetype='image/' + save_format)
def create_unversioned_champion_tile(championfull):
    if not os.path.exists(os.path.join(unv_path, "champion/tiles")):
        os.makedirs(os.path.join(unv_path, "champion/tiles"))
    for champion in championfull['data']:
        champion_key = championfull['data'][champion]['key']
        cdragon_champion = download.download_versioned_cdragon_champion(
            "default", champion_key)
        for i in range(len(cdragon_champion['skins'])):
            url = get_cdragon_url(cdragon_champion['skins'][i]['tilePath'])

            image = download.download_image(url)
            print(
                f"{champion}_{championfull['data'][champion]['skins'][i]['num']}"
            )
            with open(
                    os.path.join(
                        unv_path,
                        f"champion/tiles/{champion}_{championfull['data'][champion]['skins'][i]['num']}.jpg"
                    ), "wb") as f:
                f.write(image)
    return
Beispiel #10
0
def handle_user_msg(text, msgObj):
    if text == "表情包":
        image_url = webcrawl.get_image_url()
    elif text.startswith("表情包:") or text.startswith("表情包:"):
        #特地匹配了中文冒号和英文冒号
        query = text.replace("表情包:", "").replace("表情包:", "").strip()
        if query in blackword_list:
            log.debug("触发黑名单词:" + query)
            image_url = "warning"
        else:
            image_url = webcrawl.get_image_url_with_content(query)
    else:
        return
    if image_url == "warning":
        image_path = warning_image_path
    elif image_url is not None:
        image_path = download.download_image(image_url)
    else:
        log.debug("未找到相关图片")
        image_path = no_image_result_path
    msgObj.user.send_image(image_path)
    log.debug("Send image success")