File size: 1,878 Bytes
e230f23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b65e8c0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import gradio as gr
import tensorflow as tf
from tensorflow import keras
from math import sqrt, ceil

from huggingface_hub import from_pretrained_keras

import numpy as np


model = from_pretrained_keras("keras-io/conditional-gan")

latent_dim = 128

def generate_latent_points(digit, latent_dim, n_samples, n_classes=10):
	# generate points in the latent space
	random_latent_vectors = tf.random.normal(shape=(n_samples, latent_dim))
	labels = tf.keras.utils.to_categorical([digit for _ in range(n_samples)], n_classes)
	return tf.concat([random_latent_vectors, labels], 1)

def create_digit_samples(digit, n_samples):
    if digit in range(10):
        latent_dim = 128
        random_vector_labels = generate_latent_points(int(digit), latent_dim, int(n_samples))
        examples = model.predict(random_vector_labels)
        examples = examples * 255.0
        size = ceil(sqrt(n_samples))
        digit_images = np.zeros((28*size, 28*size), dtype=float)
        n = 0
        for i in range(size):
            for j in range(size):
                if n == n_samples:
                    break
                digit_images[i* 28 : (i+1)*28, j*28 : (j+1)*28] = examples[n, :, :, 0]
                n += 1
        digit_images = (digit_images/127.5) -1
        return digit_images

description = "Keras implementation for Conditional GAN to generate samples for specific digit of MNIST"
article = "Author:<a href=\"https://huggingface.co/rajrathi\"> Rajeshwar Rathi</a>; Based on the keras example by <a href=\"https://keras.io/examples/generative/conditional_gan/\">Sayak Paul</a>"
title = "cGAN MNIST"

examples = [[1, 10], [3, 5], [5, 15]]


iface = gr.Interface(
    fn = create_digit_samples,
    inputs = ["number", "number"],
    outputs = ["image"],
    examples = examples,
    description = description,
    title = title,
    article = article
    )

iface.launch()