johnometalman commited on
Commit
6f9e1b3
1 Parent(s): 4d9ef05

fork del proyecto original

Browse files
Files changed (2) hide show
  1. app.py +37 -34
  2. utils.py +15 -12
app.py CHANGED
@@ -1,55 +1,58 @@
1
  import streamlit as st
2
  from utils import carga_modelo, genera
3
- import os
4
 
5
  ## P谩gina principal
6
- st.title('Generador de Mariposas')
7
- st.write('Este es un modelo light GAN entrenado para generaci贸n de mariposas')
8
-
9
- ## Barra Lateral
10
- st.sidebar.subheader('Esta mariposa no existe, 驴Puedes creerlo?')
11
- logo_path = 'assets/logo.png'
12
-
13
- if os.path.exists(logo_path):
14
- st.sidebar.image(logo_path, width=200)
15
- else:
16
- st.sidebar.write("鈿狅笍 Logo not found.")
17
-
18
- st.sidebar.caption('Demo creado en vivo')
19
-
20
- # Define the repo_id for the model on Hugging Face (this is the identifier for the model repository)
21
- repo_id = 'ceyda/butterfly_cropped_uniq1K_512'
22
 
23
- # Access the Hugging Face token and API key from environment variables set in Hugging Face Spaces
24
- hf_token = os.getenv("HF_AUTH_TOKEN")
25
- api_key = os.getenv("API_KEY")
 
 
 
 
 
 
 
 
 
 
26
 
27
- # Load the model using the repo_id and Hugging Face token for authentication
28
- modelo_gan = carga_modelo(repo_id, hf_token)
 
 
29
 
30
- # Number of butterflies to generate
31
  n_mariposas = 4
32
 
33
- ## Core de la app
34
  def corre():
35
- with st.spinner('Generando espera un poco....'):
36
  ims = genera(modelo_gan, n_mariposas)
37
- st.session_state['ims'] = ims # Corrected line
 
38
 
39
- if 'ims' not in st.session_state:
40
- st.session_state['ims'] = None
 
41
  corre()
42
 
43
- ims = st.session_state['ims']
 
44
 
 
45
  corre_boton = st.button(
46
- 'Genera mariposa por favor',
47
- on_click=corre,
48
- help='Estamos en vuelo, abrocha tu cintur贸n'
49
  )
50
 
51
- if ims is not None:
52
  cols = st.columns(n_mariposas)
53
  for j, im in enumerate(ims):
54
  i = j % n_mariposas
55
- cols[i].image(im, use_column_width=True)
 
1
  import streamlit as st
2
  from utils import carga_modelo, genera
 
3
 
4
  ## P谩gina principal
5
+ st.title("Butterfly GAN (GAN de mariposas)")
6
+ st.write(
7
+ "Modelo Light-GAN entrenado con 1000 im谩genes de mariposas tomadas de la colecci贸n del Museo Smithsonian."
8
+ )
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ ## Barra lateral
11
+ st.sidebar.subheader("隆Esta mariposa no existe! Ni en Am茅rica Latina 馃く.")
12
+ st.sidebar.image("assets/logo.png", width=200)
13
+ st.sidebar.caption(
14
+ f"[Modelo](https://huggingface.co/ceyda/butterfly_cropped_uniq1K_512) y [Dataset](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset) usados."
15
+ )
16
+ st.sidebar.caption(f"*Disclaimers:*")
17
+ st.sidebar.caption(
18
+ "* 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)."
19
+ )
20
+ st.sidebar.caption(
21
+ "* Modelo basado en el [paper](https://openreview.net/forum?id=1Fqg133qRaI) *Towards Faster and Stabilized GAN Training for High-fidelity Few-shot Image Synthesis*."
22
+ )
23
 
24
+ ## Cargamos modelo
25
+ repo_id = "ceyda/butterfly_cropped_uniq1K_512"
26
+ version_modelo = "57d36a15546909557d9f967f47713236c8288838"
27
+ modelo_gan = carga_modelo(repo_id, version_modelo)
28
 
29
+ ## Generamos 4 mariposas
30
  n_mariposas = 4
31
 
32
+ ## Funci贸n que genera mariposas y lo guarda como un estado de la sesi贸n
33
  def corre():
34
+ with st.spinner("Generando, espera un poco..."):
35
  ims = genera(modelo_gan, n_mariposas)
36
+ st.session_state["ims"] = ims
37
+
38
 
39
+ ## Si no hay una imagen generada entonces generala
40
+ if "ims" not in st.session_state:
41
+ st.session_state["ims"] = None
42
  corre()
43
 
44
+ ## ims contiene las im谩genes generadas
45
+ ims = st.session_state["ims"]
46
 
47
+ ## Si la usuaria da click en el bot贸n entonces corremos la funci贸n genera()
48
  corre_boton = st.button(
49
+ "Genera mariposas, porfa.",
50
+ on_click=corre,
51
+ help="Estamos en pleno vuelo, puede tardar.",
52
  )
53
 
54
+ if ims is not None:
55
  cols = st.columns(n_mariposas)
56
  for j, im in enumerate(ims):
57
  i = j % n_mariposas
58
+ cols[i].image(im, use_column_width=True)
utils.py CHANGED
@@ -1,15 +1,18 @@
1
- from transformers import AutoFeatureExtractor
 
 
2
 
3
- def carga_modelo(repo_id, token):
4
- try:
5
- # Try loading the model as a feature extractor
6
- model = AutoFeatureExtractor.from_pretrained(repo_id, use_auth_token=token)
7
- return model
8
- except Exception as e:
9
- raise ValueError(f"Error loading model: {str(e)}")
10
 
 
 
 
 
 
11
 
12
- def genera(modelo_gan, n_mariposas):
13
- # Your generation logic here (for example, generating images)
14
- # This is just a placeholder
15
- return ["image1.png", "image2.png", "image3.png", "image4.png"] # Example generated images
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from huggan.pytorch.lightweight_gan.lightweight_gan import LightweightGAN
4
 
 
 
 
 
 
 
 
5
 
6
+ ## Cargamos el modelo desde el Hub de Hugging Face
7
+ def carga_modelo(model_name="ceyda/butterfly_cropped_uniq1K_512", model_version=None):
8
+ gan = LightweightGAN.from_pretrained(model_name, version=model_version)
9
+ gan.eval()
10
+ return gan
11
 
12
+
13
+ ## Usamos el modelo GAN para generar im谩genes
14
+ def genera(gan, batch_size=1):
15
+ with torch.no_grad():
16
+ ims = gan.G(torch.randn(batch_size, gan.latent_dim)).clamp_(0.0, 1.0) * 255
17
+ ims = ims.permute(0, 2, 3, 1).detach().cpu().numpy().astype(np.uint8)
18
+ return ims