<jupyter_start><jupyter_text>Batch Tensorflow Hub Fast Style Transferby duskvirkusBased on: https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_arbitrary_image_stylization.ipynb  GPU check<jupyter_code>!nvidia-smi -L<jupyter_output>GPU 0: Tesla V100-SXM2-16GB (UUID: GPU-0403d88b-2170-bb4d-7f15-2859fe4be0ac)<jupyter_text>Connect Drive<jupyter_code>from google.colab import drive
drive.mount('/content/drive')<jupyter_output>Mounted at /content/drive<jupyter_text>Set to Tensorflow 2 and check version<jupyter_code>%tensorflow_version 2.x
import tensorflow
print(tensorflow.__version__)<jupyter_output>2.5.0<jupyter_text>Setup Code<jupyter_code>import functools
import os

from matplotlib import gridspec
import matplotlib.pylab as plt
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from PIL import Image

# Load TF-Hub module.

hub_handle = 'https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2'
hub_module = hub.load(hub_handle)

def crop_center(image):
  """Returns a cropped square image."""
  shape = image.shape
  new_shape = min(shape[1], shape[2])
  offset_y = max(shape[1] - shape[2], 0) // 2
  offset_x = max(shape[2] - shape[1], 0) // 2
  image = tf.image.crop_to_bounding_box(
      image, offset_y, offset_x, new_shape, new_shape)
  return image

@functools.lru_cache(maxsize=None)
def load_image_url(image_url, image_size=(256, 256), preserve_aspect_ratio=True):
  """Loads and preprocesses images."""
  # Cache image file locally.
  image_path = tf.keras.utils.get_file(os.path.basename(image_url)[-128:], image_url)
  return load_image(image_path, image_size, preserve_aspect_ratio)

def load_image(image_path, image_size=(256, 256), preserve_aspect_ratio=True):
  """Loads and preprocesses images."""
  # Load and convert to float32 numpy array, add batch dimension, and normalize to range [0, 1].
  img = tf.io.decode_image(
      tf.io.read_file(image_path),
      channels=3, dtype=tf.float32)[tf.newaxis, ...]
  img = crop_center(img)
  img = tf.image.resize(img, image_size, preserve_aspect_ratio=True)
  return img

def load_image_no_resize(image_path):
  img = tf.io.decode_image(
      tf.io.read_file(image_path),
      channels=3, dtype=tf.float32)[tf.newaxis, ...]
  return img<jupyter_output><empty_output><jupyter_text>Set Variables<jupyter_code>input_folder = '/content/drive/MyDrive/art/clip-vqgan-07-12-21' # path to folder of images to process
style_images = '/content/drive/MyDrive/art/misc/color-fringe.png' # one image path or array of image paths to use as the style image. example: 'path/to/image' or ['path/to/image1', 'path/to/image2']
output_folder = '/content/drive/MyDrive/art/style-transfer/test2' # where to save images (will create folders as needed, will overwrite existing files with the same name)
resize_style_image = True # can change to False and it will use the style image size may lead to worse results<jupyter_output><empty_output><jupyter_text>Run Batch<jupyter_code>style_image_resize_size = (256, 256)

# get image paths in input folder
input_images = []
for root, subdirs, files in os.walk(input_folder):
    for filename in files:
        input_images.append(os.path.join(root, filename))

# style images loop
if not isinstance(style_images, list):
  style_images = [style_images]

for style_im in style_images:
  # load style image
  style_image = None
  if resize_style_image:
    style_image = load_image(style_im, style_image_resize_size)
  else:
    style_image = load_image_no_resize(style_im)
  style_image = tf.nn.avg_pool(style_image, ksize=[3,3], strides=[1,1], padding='SAME')

  # create save folder
  style_output_dir = os.path.join(output_folder, style_im.split('/')[-1].split('.')[0])
  os.makedirs(style_output_dir, exist_ok=True)

  # process each image
  for input_im in input_images:

    content_image = load_image_no_resize(input_im)
    outputs = hub_module(tf.constant(content_image), tf.constant(style_image))
    tf.keras.preprocessing.image.save_img(os.path.join(style_output_dir, input_im.split('/')[-1].split('.')[0] + '.png'), outputs[0][0])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11814447934283644, 'fraction_numerical': 0.023677216719014255, 'mean_word_length': 5.438569206842923, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 22, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '617687', 'license': 'MIT', 'n_tokens_mistral': 1528, 'n_tokens_neox': 1465, 'n_words': 313, 'path': 'style_transfer/batch_fast_style_transfer.ipynb', 'repo_name': 'duskvirkus/colab-notebooks', 'size': '4139'}