Autogenerate images for articles

I need to create pictures for my website in automatical way.

auto creation of picture with django and Web design|lower


IMAGE GENERATOR

1. I will create some basic background images for each category.

1.2. I'll create backgrounds with LibreOffice Draw. Export settings from LibreOffice Draw: .png, width: 555, compress:9, resolution:555, checkboxes: unchecked/

1.3. Try to use OfficeLibre Draw API with Python if it is possible. Unnable to do that.

1.4. Take images from LibreOffice draw gallery /usr/lib/libreoffice/share/gallery // I have to combine 3 random images then change the image randomly. And decrease size of an image.

OPEN CV & PIL

1.5. addWeighted function just blends images. It doesn't suit well for my purposes. I need insert one image into an another. // But it is possible to make two copies of one image -> add watermark into second copy -> then blend with original image with addWeighted // It works well

cv2.addWeighted(ov 0.5, ou, 0.5, 0, ou) // ov is a copy of ou but with inserted image.

1.5.1. There is an easy way to insert one cv2 image into another (so called alpha blending): img[50:150,30:90]=img2[0:100,0:60] // But I've faced the problem it doesn't take into an account the image's transparency.

1.5.2. Try to save png with interlaced mode enabled. // Doesn't help

1.5.3. While save png uncheck interlaced and save transparency options. // Doesn't help

1.5.4. Save as tif. // Doesn't help

1.5.5. Save as png without compression. // Doesn't help

1.5.6. I will use PIL library for this purpose. It works without any problems.

from PIL import Image

b = Image.open(r'/home/.../static/image/Blockchain/background.jpg')

a = Image.open(r'/home/.../static/image/Blockchain/Bitcoin/1.png')

b.paste(a, (0,0), mask=a)

b.show()

1.5.7. My gallery files are .svg I have to convert them into .png

1.5.7.1. I will try to use cairosvg package. To install $ pip3 install cairosvg

import cairosvg

cairosvg.svg2png(url='/home/.../_gallery/arrows/A01-Arrow-Gray-Left.svg', write_to='/home/.../Blockchain/Bitcoin/2.png')

1.5.7.2. Now I need a script to convert hundreds of files from svg to png.

import os

import cairosvg

d='/directory/myimages/'

for f in os.listdir(d):

    if os.path.isfile(d+'/'+f) and f.endswith(".svg"):

        n = f.split('.svg')[0]

        cairosvg.svg2png(url=d+'/'+n+'.svg',write_to=d+'/'+n+'.png')

1.5.8. I need random generator to set random position for inserted images. // import random -> random.random() It doesn't need any seeds.

SCRIPT

1.6. Final script:

import os

from PIL import Image

from PIL import ImageFilter

from PIL import ImageEnhance

from PIL import ImageOps

import random

import pexpect  # To use linux command from python

#1.Take user input. Which subcategory new article belongs.

subcategory = "joomla"                          # TODO Integrate with database

nm = "Petya2"                                         # TODO Take name from database. Article name. Get from database

#2.Then I have to get category which subcategory belongs.

category = ""                                           # Is a main category name which we are looking for.

local_dir = "/home/.../eclipse-workspace/django001/outleys/static/image/"  #Set the Base loca directory with images

for ctg in os.listdir(local_dir) :                    # Get list of categories ,ctg is the top level category

if os.path.isdir(local_dir+ctg) and category=='':

               for k in os.listdir(local_dir+ctg):          # k is subactegory

                            if os.path.isdir(local_dir+ctg+"/"+k) and k==subcategory:  # Iterate over all subcategories until match

                                       category = ctg                    # We find top level categoty which correspond subcategory

break

else:

break

#3.Get first two images 

p1 = Image.open(local_dir+category+"/background.png")

p2 = Image.open(local_dir+category+"/"+subcategory+"/1.png")

#3.1.Get random third image

folder_list = os.listdir(local_dir+"_gallery_png/")   # Get list of folders

file_dir = local_dir+"_gallery_png/"+folder_list[int((len(folder_list)*random.random()))] # Get random folder

files = os.listdir(file_dir)                          # Get list of files inside of random folder

# Choose random file image from a random folder

p3 = Image.open(file_dir+"/"+files[int((len(files)*random.random()))])   # Choose random image from gallery

#3.1.1 Increase or decrease p3 if it is too small or too big

if p3.size[0]<200 and p3.size[1]<200:

krat = 300//p3.size[0]                            # How much times it should be enlarged

  w2 = p3.size[0]*krat

  h2 = p3.size[1]*krat

p3=p3.resize((w2,h2), Image.Resampling.NEAREST)   # Increase image

if p3.size[0]>400 or p3.size[1]>400:

krat1 = p3.size[0]//300                           # How much times it should be decreased

krat2 = p3.size[1]//300  

krat = max(krat2, krat1)

w3=p3.size[0]//krat

h3=p3.size[1]//krat

p3=p3.resize((w3,h3), Image.Resampling.LANCZOS)   # Decreas size

#3.2. Construct composite image

w = int(0.7*p1.size[0]*random.random()-p1.size[0]//2) # Generate random position to insert p2

h = int(0.7*p1.size[1]*random.random()-p1.size[1]//2)

p1.paste(p2, (w,h), mask=p2)

w1 = int((p1.size[0]-p3.size[0])*random.random())     # Generate random position to insert p3

h1 = int((p1.size[1]-p3.size[1])*random.random())

p1.paste(p3, (w1,h1), mask=p3)

#3.3. Apply random effects

imdir = local_dir+category+"/"+subcategory+"/"+nm+".png"

rullet = int(150*random.random())                     # Random number from 0 to 150

if 0<= rullet <= 5:                                   # 5% probability

p1 = p1.convert("L")                              # Made black&white

if 5< rullet <= 10:                                   # 5% probability

p1 = p1.convert("1")                              # Made crop

if 10< rullet <= 15:                                  # 5% from PIL import ImageOpsprobability

p1 = p1.filter(ImageFilter.CONTOUR)               # contour

if 15< rullet <= 20:                                  # 5% probability

p1 = p1.transpose(Image.FLIP_LEFT_RIGHT)          # Mirror

if 20< rullet <= 25:                                  

p1 = p1.filter(ImageFilter.GaussianBlur(radius = 2*random.random()+1 )) # blur

if 25< rullet <= 30:                               

p1 = p1.filter(ImageFilter.SHARPEN)               # Sharpen

if 30< rullet <= 35:                                  

p1 = ImageOps.expand(p1, border = 10, fill = 100) # border

if 35< rullet <= 40:                                

p1 = ImageEnhance.Color(p1).enhance(5.0*random.random()+1.0)   # more colors

if 40< rullet <= 45:                               

p1 = ImageEnhance.Contrast(p1).enhance(5.0*random.random()+1.0)   # more contrast

if 45< rullet <= 50:                                 

p1 = ImageEnhance.Brightness(p1).enhance(5.0*random.random()+1.0)   # more bright

if 50< rullet <= 55:                                  

p1 = p1.filter(ImageFilter.MaxFilter(size=int(3*random.random()+1)))  # fancy

p1.save(imdir,"PNG")                              #Save generated image

#4.   Upload image to the remote server /www/outleys.site/mydiary/how_to/static/image/

c1 = pexpect.spawn('scp '+imdir+' u0224243@37.140.192.232:/var/www/u0224243/data/www/outleys.site/mydiary/how_to/static/image/'+category+'/')   # Write an image to the server

c1.expect('(?i)password:')                            # Wait for password prompt

c1.sendline('UWP_5lyy')                               # send password

#5.   Write image to database

sql = "UPDATE `how_to_article2` SET `im3` = %s WHERE `how_to_article2`.`id` = '"+str(r1)+"';"  # Write into database

w = [ "image/"+category+"/"+nm+".png",]

m.execute(sql,w) 

db.commit()

1.7. I unable to connect to database from python's mysql.connector.connect. Got an error mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user '<user name>'@'xxx.xxx.137.192' (using password: YES) // Strange that ip addres doesn't correspond which one I specified in host parameter.

1.7.1. In hosting's admin panel I have to add new user and set checkbow to allow remote access.

1.8. pexpect.spawn('scp ..') doesn't move file from local machine to the server  // Filename should be without spaces and exclamation points. Strip it out filename.strip("!").replace(" ","-")

1.9. I've faced problem with python. I have a dictionary with list. When I assign one dictionary element to another element of the same dictionary. When I after change secon element, first also change its value.