leovale14 commited on
Commit
1b1f622
1 Parent(s): 4750ac9

butterfly-gan

Browse files
Files changed (3) hide show
  1. app.py +56 -4
  2. requirements.txt +2 -0
  3. utils.py +78 -0
app.py CHANGED
@@ -1,7 +1,59 @@
1
  import streamlit as st
2
 
3
- st.title("Streamlit First Demo")
4
- st.markdown("This is a demo of streamlit")
5
 
6
- x = st.slider('Selecciona un valor')
7
- st.write(x, ' al cuadrado es', x * x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
 
3
+ from utils import carga_modelo, genera
 
4
 
5
+ ## P谩gina principal
6
+ st.title("Butterfly GAN (GAN de mariposas)")
7
+ st.write(
8
+ "Modelo Light-GAN entrenado con 1000 im谩genes de mariposas tomadas de la colecci贸n del Museo Smithsonian."
9
+ )
10
+
11
+ ## Barra lateral
12
+ st.sidebar.subheader("隆Esta mariposa no existe! Ni en Am茅rica Latina 馃く.")
13
+ st.sidebar.image("assets/logo.png", width=200)
14
+ st.sidebar.caption(
15
+ f"[Modelo](https://huggingface.co/ceyda/butterfly_cropped_uniq1K_512) y [Dataset](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset) usados."
16
+ )
17
+ st.sidebar.caption(f"*Disclaimers:*")
18
+ st.sidebar.caption(
19
+ "* Este demo es una versi贸n simplificada del creado por [Ceyda Cinarel](https://github.com/cceyda) y [Jonathan Whitaker](https://datasciencecastnet.home.blog/) ([link](https://huggingface.co/spaces/huggan/butterfly-gan)) durante el hackathon [HugGan](https://github.com/huggingface/community-events). Cualquier error se atribuye a [Omar Espejel](https://twitter.com/espejelomar)."
20
+ )
21
+ st.sidebar.caption(
22
+ "* Modelo basado en el [paper](https://openreview.net/forum?id=1Fqg133qRaI) *Towards Faster and Stabilized GAN Training for High-fidelity Few-shot Image Synthesis*."
23
+ )
24
+
25
+ ## Cargamos modelo
26
+ repo_id = "ceyda/butterfly_cropped_uniq1K_512"
27
+ version_modelo = "57d36a15546909557d9f967f47713236c8288838"
28
+ modelo_gan = carga_modelo(repo_id, version_modelo)
29
+
30
+ ## Generamos 4 mariposas
31
+ n_mariposas = 4
32
+
33
+ ## Funci贸n que genera mariposas y lo guarda como un estado de la sesi贸n
34
+ def corre():
35
+ with st.spinner("Generando, espera un poco..."):
36
+ ims = genera(modelo_gan, n_mariposas)
37
+ st.session_state["ims"] = ims
38
+
39
+
40
+ ## Si no hay una imagen generada entonces generala
41
+ if "ims" not in st.session_state:
42
+ st.session_state["ims"] = None
43
+ corre()
44
+
45
+ ## ims contiene las im谩genes generadas
46
+ ims = st.session_state["ims"]
47
+
48
+ ## Si la usuaria da click en el bot贸n entonces corremos la funci贸n genera()
49
+ corre_boton = st.button(
50
+ "Genera mariposas, porfa.",
51
+ on_click=corre,
52
+ help="Estamos en pleno vuelo, puede tardar.",
53
+ )
54
+
55
+ if ims is not None:
56
+ cols = st.columns(n_mariposas)
57
+ for j, im in enumerate(ims):
58
+ i = j % n_mariposas
59
+ cols[i].image(im, use_column_width=True)
requirements.txt CHANGED
@@ -1 +1,3 @@
 
 
1
  streamlit
 
1
+ git+https://github.com/huggingface/community-events.git@3fea10c5d5a50c69f509e34cd580fe9139905d04#egg=huggan
2
+ transformers
3
  streamlit
utils.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import numpy as np
4
+ import torch
5
+ from huggan.pytorch.lightweight_gan.lightweight_gan import LightweightGAN
6
+ from huggingface_hub import hf_hub_download
7
+
8
+ CONFIG_NAME = "config.json"
9
+ revision = None
10
+ cache_dir = None
11
+ force_download = False
12
+ proxies = None
13
+ resume_download = False
14
+ local_files_only = False
15
+ token = None
16
+
17
+
18
+ def carga_modelo(model_name="ceyda/butterfly_cropped_uniq1K_512"):
19
+ """
20
+ Loads a pre-trained LightweightGAN model from Hugging Face Model Hub.
21
+
22
+ Args:
23
+ model_name (str): The name of the pre-trained model to load. Defaults to "ceyda/butterfly_cropped_uniq1K_512".
24
+ model_version (str): The version of the pre-trained model to load. Defaults to None.
25
+
26
+ Returns:
27
+ LightweightGAN: The loaded pre-trained model.
28
+ """
29
+ # Load the config
30
+ config_file = hf_hub_download(
31
+ repo_id=str(model_name),
32
+ filename=CONFIG_NAME,
33
+ revision=revision,
34
+ cache_dir=cache_dir,
35
+ force_download=force_download,
36
+ proxies=proxies,
37
+ resume_download=resume_download,
38
+ token=token,
39
+ local_files_only=local_files_only,
40
+ )
41
+ with open(config_file, "r", encoding="utf-8") as f:
42
+ config = json.load(f)
43
+
44
+ # Call the _from_pretrained with all the needed arguments
45
+ gan = LightweightGAN(latent_dim=256, image_size=512)
46
+
47
+ gan = gan._from_pretrained(
48
+ model_id=str(model_name),
49
+ revision=revision,
50
+ cache_dir=cache_dir,
51
+ force_download=force_download,
52
+ proxies=proxies,
53
+ resume_download=resume_download,
54
+ local_files_only=local_files_only,
55
+ token=token,
56
+ use_auth_token=False,
57
+ config=config, # usually in **model_kwargs
58
+ )
59
+
60
+ gan.eval()
61
+ return gan
62
+
63
+
64
+ def genera(gan, batch_size=1):
65
+ """
66
+ Generates images using the given GAN model.
67
+
68
+ Args:
69
+ gan (nn.Module): The GAN model to use for generating images.
70
+ batch_size (int, optional): The number of images to generate in each batch. Defaults to 1.
71
+
72
+ Returns:
73
+ numpy.ndarray: A numpy array of generated images.
74
+ """
75
+ with torch.no_grad():
76
+ ims = gan.G(torch.randn(batch_size, gan.latent_dim)).clamp_(0.0, 1.0) * 255
77
+ ims = ims.permute(0, 2, 3, 1).detach().cpu().numpy().astype(np.uint8)
78
+ return ims