查看原文
其他

两个Python脚本,快速构建妹子图片网站

码中人 码农真经 2023-12-25

引言

最近开始学习 AI 画图,用Stable Diffusion 画了不少图。于是用WordPress搭了个小网站,收集自己画的、网友画的图。

网站链接如下:

魔力美少女 – 你的 AI 女孩!AI画图 | AIGC[1]

魔力美少女

WordPress 写图片类文章需要先把图片上传到媒体库,然后再一张张图片插入成文,很烦人。于是写了两个Python脚本,一定程度上减轻这个痛苦。

mzhren/python2wordpress: a python script to uoload images to wordpress site.[2]

欢迎点选右上角的 Star 和 Fork

webp.py & batch_webp.py

这个 webp.py 脚本主要功能是将图片转换成webp格式,这样可以减少网站的图片大小,加快网站的加载速度。在转换之前,会对图片进行 resize 和 添加水印,以及图片 Prompt 信息的提取。

使用方法:

python webp.py -i <input_file>

默认情况下,会在当前目录下生成一个 output 目录,将转换后的图片放在这个目录下。

图片变换大小、转换格式、添加水印,都是使用 Pillow 库实现的。

代码如下:


from utils.resize import resize
from utils.add_watermark import add_watermark
from utils.get_prompt import get_prompt
import argparse
import glob
import os


def resize_and_addwatermark(inputFile, outputFile):
    image = resize(inputFile)
    result = add_watermark(image)
    result.save(outputFile, 'webp', quality=80)


def images_handler(inputFolder, outputFolder, image_name='girl'):
   # get png/jpg files and index them
    images = glob.glob(inputFolder + "/*.png")
    images.extend(glob.glob(inputFolder + "/*.jpg"))
    images.extend(glob.glob(inputFolder + "/*.jpeg"))

    name_index = 0
    has_prompt = False

    for image in images:
        if os.path.isfile(image):
            has_prompt = generate_prompt(image, has_prompt, outputFolder)
            print('doing', image)
            file_name = image_name + str(name_index) + ".webp"
            name_index += 1
            output_file = os.path.join(outputFolder, file_name)
            resize_and_addwatermark(image, output_file)
            print('done', image, 'to', output_file)
    print('done all')


def generate_prompt(image, has_prompt, outputFolder):
    if not has_prompt:
        prompt = get_prompt(image)
        if prompt:
            has_prompt = True
            prompt_file = os.path.join(outputFolder, 'prompt.txt')
            with open(prompt_file, 'w', encoding='utf8'as f:
                f.write(prompt)
                print('done', prompt_file)
    return has_prompt


def get_args():
    parser = argparse.ArgumentParser(
        description='Resize image and add watermark')
    parser.add_argument('-i''--input'help='input folder', required=True)
    parser.add_argument('-n''--name'help='name of images', default='girl_')
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    args = get_args()
    inputFolder = args.input
    outputFolder = inputFolder + "\output"
    name = args.name
    if not os.path.exists(outputFolder):
        os.makedirs(outputFolder)

    images_handler(inputFolder, outputFolder, name)

如果需要批量转换,可以使用 batch_webp.py 脚本,使用方法如下:

python batch_webp.py -i <input_dir>

py2wp.py

这个 py2wp.py 脚本主要功能是将图片上传到WordPress网站,并生成对应的文章。

使用方法:

python py2wp.py -f <input_images_folder> -tags <tags> -cat <categories> -t <title> -s <slug>

其中,-f-tags-t 参数是必须的,其他参数都是可选的。

Welcome to python-wordpress-xmlrpc’s documentation! — python-wordpress-xmlrpc 2.3 documentation[3]

该脚本使用 python-wordpress-xmlrpc 库实现,代码如下:

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost
from wordpress_xmlrpc.methods import media
from wordpress_xmlrpc.compat import xmlrpc_client

import argparse
import os

# replace with your own wordpress site url and credentials
wp = Client('http://your_wp_site.com/xmlrpc.php''admin''password')

def python_to_wp(folder, title, tags, category, slug=None):
    print('Creating post: ' + title)

    post = WordPressPost()
    post.title = title
    if slug:
        post.slug = slug
    post.content = ''
    prompt_txt_content = get_prompt_txt_content(folder)
    post.terms_names = {
        'post_tag': tags.split(','),
        'category': category.split(',')
    }

    post.excerpt = prompt_txt_content

    post.post_status = 'publish'

    images = get_folder_images(folder)

    has_cover = False

    for image in images:
        # upload image
        image_with_path = os.path.join(folder, image)
        image_uploaded = upload_image(image_with_path)
        image_url = image_uploaded['url']
        image_id = image_uploaded['id']
        image_name = image_uploaded['file']

        # add image to post content
        post.content += f'''<figure class="wp-block-image size-full"><img decoding="async" loading="lazy" src="{image_url}" alt="" ></figure>'''
        if not has_cover:
            post.thumbnail = image_id
            if image_name == 'cover.webp':
                has_cover = True

    wp.call(NewPost(post))
    print('Post created: ' + title)


def get_folder_images(folder):
    images = [f for f in os.listdir(
        folder) if os.path.isfile(os.path.join(folder, f))]
    images = [f for f in images if f.endswith('.webp')]
    return images


def upload_image(image):
    # get image name
    image_name = os.path.basename(image)

    # get image data
    data = {
        'name': image_name,
        'type''image/webp',
    }

    # open image
    with open(image, 'rb'as img:
        data['bits'] = xmlrpc_client.Binary(img.read())

    # upload image
    response = wp.call(media.UploadFile(data))

    return response


def get_prompt_txt_content(folder):
    prompt_file = os.path.join(folder, 'prompt.txt')
    if os.path.isfile(prompt_file):
        with open(prompt_file, 'r', encoding='utf8'as f:
            content = f.read()
            return content
    else:
        return ''


def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f''--folder'help='Choose Folder', required=True)
    parser.add_argument('-t''--title'help='Post Title', required=True)
    parser.add_argument('-s''--slug'help='Post Slug')
    parser.add_argument('-tags''--tags'help='Post Tags', required=True)
    parser.add_argument('-cat''--category',
                        default='妹子图'help='Post Category')
    args = parser.parse_args()
    return args


def main():
    args = get_args()
    python_to_wp(**vars(args))


if __name__ == '__main__':
    main()

python-wordpress-xmlrpc 使用简单,按照官方文档,只需要修改 wp = Client('http://your_wp_site.com/xmlrpc.php', 'admin', 'password') 中的 urlusernamepassword 即可。

往期推荐

关注 码中人

点赞、转发、广告,更多优质资源等你来...

(python数学)

欢迎关注我的公众号“码农真经”,原创技术文章第一时间推送。

引用链接

[1] 魔力美少女 – 你的 AI 女孩!AI画图 | AIGC: https://moligirls.com/
[2] mzhren/python2wordpress: a python script to uoload images to wordpress site.: https://github.com/mzhren/python2wordpress
[3] Welcome to python-wordpress-xmlrpc’s documentation! — python-wordpress-xmlrpc 2.3 documentation: https://python-wordpress-xmlrpc.readthedocs.io/en/latest/


继续滑动看下一个

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存