Spaces:
Runtime error
Runtime error
Update app.py
Browse files6 unmodified lines78910111213143 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808 unmodified lines89909192939495969798996 unmodified linesvgg = tf.keras.applications.VGG19(include_top=False, weights="imagenet")vgg.trainable = FalseSTYLE_LAYERS = [...] # same layers as in your notebookCONTENT_LAYER = [...] # e.g. [('block5_conv4', 1)]def gram_matrix(A):3 unmodified linesA = tf.convert_to_tensor(A)if len(A.shape) == 4:# (batch, H, W, C)batch, H, W, C = A.shapeA = tf.reshape(A, (batch, H*W, C))gram = tf.matmul(A, A, transpose_a=True) / tf.cast(H*W, tf.float32)elif len(A.shape) == 3:# (batch, N, C) already flattenedbatch, N, C = A.shapegram = tf.matmul(A, A, transpose_a=True) / tf.cast(N, tf.float32)elif len(A.shape) == 2:# (N, C) no batchN, C = A.shapeA = tf.expand_dims(A, 0) # add batch dimgram = tf.matmul(A, A, transpose_a=True) / tf.cast(N, tf.float32)else:raise ValueError(f"Unexpected tensor rank for gram_matrix: {A.shape}")return gramdef compute_content_cost(a_C, a_G):"""Content cost between content and generated image features."""return tf.reduce_mean(tf.square(a_C - a_G))def compute_style_cost(a_S, a_G):"""Style cost using Gram matrices."""J_style = 0for s, g in zip(a_S, a_G):J_style += tf.reduce_mean(tf.square(gram_matrix(s) - gram_matrix(g)))return J_style / len(a_S)def total_cost(J_content, J_style, alpha=10, beta=40):"""Weighted sum of content + style."""return alpha * J_content + beta * J_styledef clip_0_1(img):"""Keep pixel values in [0,1]."""return tf.clip_by_value(img, 0.0, 1.0)def preprocess(img):img = Image.fromarray(img).resize((256, 256))arr = np.expand_dims(np.array(img) / 255.0, axis=0).astype(np.float32)return tf.convert_to_tensor(arr)def style_transfer(content, style, steps=1000):content_tensor = preprocess(content)style_tensor = preprocess(style)# Extract featuresa_C = vgg(content_tensor)a_S = vgg(style_tensor)# Init generated imagegenerated_image = tf.Variable(content_tensor)# Optimizeopt = tf.keras.optimizers.Adam(learning_rate=0.01)for i in range(steps):with tf.GradientTape() as tape:a_G = vgg(generated_image)8 unmodified linesout_img = (generated_image[0].numpy() * 255).astype("uint8")return Image.fromarray(out_img)demo = gr.Interface(fn=style_transfer,inputs=[gr.Image(type="numpy", label="Content Image"),gr.Image(type="numpy", label="Style Image")],outputs=gr.Image(type="pil", label="Stylized Image"),)demo.launch()6 unmodified lines78910111213143 unmodified lines181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768698 unmodified lines7879808182838485868788899091926 unmodified linesvgg = tf.keras.applications.VGG19(include_top=False, weights="imagenet")vgg.trainable = FalseSTYLE_LAYERS = [...] # your style layersCONTENT_LAYER = [...] # your content layer(s)def gram_matrix(A):3 unmodified linesA = tf.convert_to_tensor(A)if len(A.shape) == 4:batch, H, W, C = A.shapeA = tf.reshape(A, (batch, H * W, C))gram = tf.matmul(A, A, transpose_a=True) / tf.cast(H * W, tf.float32)elif len(A.shape) == 3:batch, N, C = A.shapegram = tf.matmul(A, A, transpose_a=True) / tf.cast(N, tf.float32)elif len(A.shape) == 2:N, C = A.shapeA = tf.expand_dims(A, 0)gram = tf.matmul(A, A, transpose_a=True) / tf.cast(N, tf.float32)else:raise ValueError(f"Unexpected tensor rank for gram_matrix: {A.shape}")return gramdef compute_content_cost(a_C, a_G):return tf.reduce_mean(tf.square(a_C - a_G))def compute_style_cost(a_S, a_G):J_style = 0for s, g in zip(a_S, a_G):J_style += tf.reduce_mean(tf.square(gram_matrix(s) - gram_matrix(g)))return J_style / len(a_S)def total_cost(J_content, J_style, alpha=10, beta=40):return alpha * J_content + beta * J_styledef preprocess(img):img = Image.fromarray(img).resize((256, 256))arr = np.expand_dims(np.array(img) / 255.0, axis=0).astype(np.float32)return tf.convert_to_tensor(arr)def style_transfer(content, style, steps):content_tensor = preprocess(content)style_tensor = preprocess(style)a_C = vgg(content_tensor)a_S = vgg(style_tensor)generated_image = tf.Variable(content_tensor)opt = tf.keras.optimizers.Adam(learning_rate=0.01)for i in range(steps):with tf.GradientTape() as tape:a_G = vgg(generated_image)8 unmodified linesout_img = (generated_image[0].numpy() * 255).astype("uint8")return Image.fromarray(out_img)demo = gr.Interface(fn=style_transfer,inputs=[gr.Image(type="numpy", label="Content Image"),gr.Image(type="numpy", label="Style Image"),gr.Slider(100, 2000, value=1000, step=100, label="Number of Iterations")],outputs=gr.Image(type="pil", label="Stylized Image"),)demo.launch()
app.py+19-26