Ntdeseb commited on
Commit
e0c4be3
·
1 Parent(s): 9e11962

Actualizando con modelos IA personalizados

Browse files
Files changed (3) hide show
  1. README.md +115 -7
  2. app.py +257 -137
  3. requirements.txt +8 -6
README.md CHANGED
@@ -1,14 +1,122 @@
1
  ---
2
- title: Ntia
3
- emoji: 🖼
4
- colorFrom: purple
5
  colorTo: red
6
  sdk: gradio
7
- sdk_version: 5.25.2
8
  app_file: app.py
9
  pinned: false
10
- license: apache-2.0
11
- short_description: ntdesweb
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Modelos Ia Simple
3
+ emoji: 🦀
4
+ colorFrom: indigo
5
  colorTo: red
6
  sdk: gradio
7
+ sdk_version: 5.38.2
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
11
+ short_description: Modelos libres de IA
12
  ---
13
 
14
+ # 🤖 Modelos Libres de IA
15
+
16
+ Un Space de Hugging Face que proporciona acceso gratuito a modelos de IA para generación de texto e imágenes sin límites de cuota.
17
+
18
+ ## 🚀 Características
19
+
20
+ - **Generación de Texto**: Múltiples modelos de lenguaje como DialoGPT, GPT-2, y GPT-Neo
21
+ - **Chat Conversacional**: Interfaz de chat con DialoGPT
22
+ - **Generación de Imágenes**: Stable Diffusion v1.4 y v1.5
23
+ - **Sin Límites**: Uso ilimitado sin costos
24
+ - **Interfaz Intuitiva**: Gradio con diseño moderno
25
+
26
+ ## 📋 Modelos Disponibles
27
+
28
+ ### Texto
29
+ - `microsoft/DialoGPT-medium` - Chat conversacional
30
+ - `gpt2` - Generación de texto
31
+ - `distilgpt2` - GPT-2 optimizado
32
+ - `EleutherAI/gpt-neo-125M` - GPT-Neo pequeño
33
+
34
+ ### Imágenes
35
+ - `runwayml/stable-diffusion-v1-5` - Stable Diffusion v1.5
36
+ - `CompVis/stable-diffusion-v1-4` - Stable Diffusion v1.4
37
+
38
+ ## 🛠️ Instalación Local
39
+
40
+ Si quieres ejecutar esto localmente:
41
+
42
+ ```bash
43
+ # Clonar el repositorio
44
+ git clone <tu-repositorio>
45
+ cd huggingface-space
46
+
47
+ # Instalar dependencias
48
+ pip install -r requirements.txt
49
+
50
+ # Ejecutar la aplicación
51
+ python app.py
52
+ ```
53
+
54
+ ## 🌐 Uso en Hugging Face Spaces
55
+
56
+ 1. Ve a [Hugging Face Spaces](https://huggingface.co/spaces)
57
+ 2. Haz clic en "Create new Space"
58
+ 3. Selecciona "Gradio" como SDK
59
+ 4. Sube estos archivos a tu Space
60
+ 5. ¡Listo! Tu aplicación estará disponible en `https://huggingface.co/spaces/tu-usuario/tu-space`
61
+
62
+ ## 💡 Consejos de Uso
63
+
64
+ ### Para Texto
65
+ - Usa prompts claros y específicos
66
+ - Ajusta la longitud máxima según tus necesidades
67
+ - DialoGPT es mejor para conversaciones
68
+
69
+ ### Para Imágenes
70
+ - Describe detalladamente lo que quieres ver
71
+ - Ajusta los pasos de inferencia (más pasos = mejor calidad pero más lento)
72
+ - Usa palabras descriptivas y específicas
73
+
74
+ ## 🔧 Configuración Avanzada
75
+
76
+ ### Agregar Nuevos Modelos
77
+
78
+ Para agregar más modelos, edita el diccionario `MODELS` en `app.py`:
79
+
80
+ ```python
81
+ MODELS = {
82
+ "text": {
83
+ "nuevo-modelo/texto": "Descripción",
84
+ # ... más modelos
85
+ },
86
+ "image": {
87
+ "nuevo-modelo/imagen": "Descripción",
88
+ # ... más modelos
89
+ }
90
+ }
91
+ ```
92
+
93
+ ### Optimización de Rendimiento
94
+
95
+ - Los modelos se cargan en caché para reutilización
96
+ - Usa GPU si está disponible para mejor rendimiento
97
+ - Ajusta los parámetros de generación según tus necesidades
98
+
99
+ ## 📝 Licencia
100
+
101
+ Este proyecto está bajo la licencia MIT. Los modelos individuales tienen sus propias licencias.
102
+
103
+ ## 🤝 Contribuciones
104
+
105
+ ¡Las contribuciones son bienvenidas! Puedes:
106
+ - Agregar nuevos modelos
107
+ - Mejorar la interfaz
108
+ - Optimizar el rendimiento
109
+ - Reportar bugs
110
+
111
+ ## 📞 Soporte
112
+
113
+ Si tienes problemas o preguntas:
114
+ 1. Revisa los logs del Space
115
+ 2. Verifica que todos los archivos estén subidos correctamente
116
+ 3. Asegúrate de que las dependencias estén actualizadas
117
+
118
+ ---
119
+
120
+ **¡Disfruta usando modelos de IA sin límites! 🎉**
121
+
122
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,154 +1,274 @@
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
-
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
  import torch
 
 
 
 
 
 
8
 
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
 
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
 
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
 
 
 
 
 
 
 
 
 
 
 
 
78
  )
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
-
82
- result = gr.Image(label="Result", show_label=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  )
 
 
 
 
 
 
 
 
 
 
91
 
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
  with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
-
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
-
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
-
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
- )
152
 
 
153
  if __name__ == "__main__":
154
- demo.launch()
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
2
  import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
4
+ from diffusers import StableDiffusionPipeline, DiffusionPipeline
5
+ import requests
6
+ from PIL import Image
7
+ import io
8
+ import base64
9
 
10
+ # Configuración de modelos libres
11
+ MODELS = {
12
+ "text": {
13
+ "microsoft/DialoGPT-medium": "Chat conversacional",
14
+ "gpt2": "Generación de texto",
15
+ "distilgpt2": "GPT-2 optimizado",
16
+ "EleutherAI/gpt-neo-125M": "GPT-Neo pequeño"
17
+ },
18
+ "image": {
19
+ "runwayml/stable-diffusion-v1-5": "Stable Diffusion v1.5",
20
+ "CompVis/stable-diffusion-v1-4": "Stable Diffusion v1.4"
21
+ }
22
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ # Cache para los modelos
25
+ model_cache = {}
 
 
 
26
 
27
+ def load_text_model(model_name):
28
+ """Cargar modelo de texto"""
29
+ if model_name not in model_cache:
30
+ print(f"Cargando modelo de texto: {model_name}")
31
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
32
+ model = AutoModelForCausalLM.from_pretrained(model_name)
33
+
34
+ # Configurar para chat si es DialoGPT
35
+ if "dialogpt" in model_name.lower():
36
+ tokenizer.pad_token = tokenizer.eos_token
37
+ model.config.pad_token_id = model.config.eos_token_id
38
+
39
+ model_cache[model_name] = {
40
+ "tokenizer": tokenizer,
41
+ "model": model,
42
+ "type": "text"
43
+ }
44
+
45
+ return model_cache[model_name]
46
 
47
+ def load_image_model(model_name):
48
+ """Cargar modelo de imagen"""
49
+ if model_name not in model_cache:
50
+ print(f"Cargando modelo de imagen: {model_name}")
51
+ pipe = StableDiffusionPipeline.from_pretrained(
52
+ model_name,
53
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
54
+ )
55
+
56
+ if torch.cuda.is_available():
57
+ pipe = pipe.to("cuda")
58
+
59
+ model_cache[model_name] = {
60
+ "pipeline": pipe,
61
+ "type": "image"
62
+ }
63
+
64
+ return model_cache[model_name]
65
 
66
+ def generate_text(prompt, model_name, max_length=100):
67
+ """Generar texto con el modelo seleccionado"""
68
+ try:
69
+ model_data = load_text_model(model_name)
70
+ tokenizer = model_data["tokenizer"]
71
+ model = model_data["model"]
72
+
73
+ # Preparar input
74
+ inputs = tokenizer.encode(prompt, return_tensors="pt")
75
+
76
+ # Generar
77
+ with torch.no_grad():
78
+ outputs = model.generate(
79
+ inputs,
80
+ max_length=max_length,
81
+ num_return_sequences=1,
82
+ temperature=0.7,
83
+ do_sample=True,
84
+ pad_token_id=tokenizer.eos_token_id
85
  )
86
+
87
+ # Decodificar respuesta
88
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
89
+
90
+ # Para DialoGPT, extraer solo la respuesta del asistente
91
+ if "dialogpt" in model_name.lower():
92
+ response = response.replace(prompt, "").strip()
93
+
94
+ return response
95
+
96
+ except Exception as e:
97
+ return f"Error generando texto: {str(e)}"
98
 
99
+ def generate_image(prompt, model_name, num_inference_steps=20):
100
+ """Generar imagen con el modelo seleccionado"""
101
+ try:
102
+ model_data = load_image_model(model_name)
103
+ pipeline = model_data["pipeline"]
104
+
105
+ # Generar imagen
106
+ image = pipeline(
107
+ prompt,
108
+ num_inference_steps=num_inference_steps,
109
+ guidance_scale=7.5
110
+ ).images[0]
111
+
112
+ return image
113
+
114
+ except Exception as e:
115
+ return f"Error generando imagen: {str(e)}"
116
 
117
+ def chat_with_model(message, history, model_name):
118
+ """Función de chat para DialoGPT"""
119
+ try:
120
+ model_data = load_text_model(model_name)
121
+ tokenizer = model_data["tokenizer"]
122
+ model = model_data["model"]
123
+
124
+ # Construir historial de conversación
125
+ conversation = ""
126
+ for user_msg, bot_msg in history:
127
+ conversation += f"User: {user_msg}\n"
128
+ if bot_msg:
129
+ conversation += f"Assistant: {bot_msg}\n"
130
+
131
+ conversation += f"User: {message}\nAssistant:"
132
+
133
+ # Generar respuesta
134
+ inputs = tokenizer.encode(conversation, return_tensors="pt", truncation=True, max_length=512)
135
+
136
+ with torch.no_grad():
137
+ outputs = model.generate(
138
+ inputs,
139
+ max_length=inputs.shape[1] + 50,
140
+ temperature=0.7,
141
+ do_sample=True,
142
+ pad_token_id=tokenizer.eos_token_id
143
  )
144
+
145
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
146
+
147
+ # Extraer solo la respuesta del asistente
148
+ response = response.split("Assistant:")[-1].strip()
149
+
150
+ return response
151
+
152
+ except Exception as e:
153
+ return f"Error en el chat: {str(e)}"
154
 
155
+ # Interfaz de Gradio
156
+ with gr.Blocks(title="Modelos Libres de IA", theme=gr.themes.Soft()) as demo:
157
+ gr.Markdown("# 🤖 Modelos Libres de IA")
158
+ gr.Markdown("### Genera texto e imágenes sin límites de cuota")
159
+
160
+ with gr.Tabs():
161
+ # Tab de Generación de Texto
162
+ with gr.TabItem("📝 Generación de Texto"):
163
+ with gr.Row():
164
+ with gr.Column():
165
+ text_model = gr.Dropdown(
166
+ choices=list(MODELS["text"].keys()),
167
+ value="microsoft/DialoGPT-medium",
168
+ label="Modelo de Texto"
169
+ )
170
+ text_prompt = gr.Textbox(
171
+ label="Prompt",
172
+ placeholder="Escribe tu prompt aquí...",
173
+ lines=3
174
+ )
175
+ max_length = gr.Slider(
176
+ minimum=50,
177
+ maximum=200,
178
+ value=100,
179
+ step=10,
180
+ label="Longitud máxima"
181
+ )
182
+ text_btn = gr.Button("Generar Texto", variant="primary")
183
+
184
+ with gr.Column():
185
+ text_output = gr.Textbox(
186
+ label="Resultado",
187
+ lines=10,
188
+ interactive=False
189
+ )
190
+
191
+ text_btn.click(
192
+ generate_text,
193
+ inputs=[text_prompt, text_model, max_length],
194
+ outputs=text_output
195
  )
196
+
197
+ # Tab de Chat
198
+ with gr.TabItem("💬 Chat"):
199
  with gr.Row():
200
+ with gr.Column():
201
+ chat_model = gr.Dropdown(
202
+ choices=["microsoft/DialoGPT-medium"],
203
+ value="microsoft/DialoGPT-medium",
204
+ label="Modelo de Chat"
205
+ )
206
+
207
+ with gr.Column():
208
+ chatbot = gr.Chatbot(
209
+ label="Chat",
210
+ height=400
211
+ )
212
+ chat_input = gr.Textbox(
213
+ label="Mensaje",
214
+ placeholder="Escribe tu mensaje...",
215
+ lines=2
216
+ )
217
+ chat_btn = gr.Button("Enviar", variant="primary")
218
+
219
+ chat_btn.click(
220
+ chat_with_model,
221
+ inputs=[chat_input, chatbot, chat_model],
222
+ outputs=[chatbot],
223
+ clear_input=True
224
+ )
225
+
226
+ chat_input.submit(
227
+ chat_with_model,
228
+ inputs=[chat_input, chatbot, chat_model],
229
+ outputs=[chatbot],
230
+ clear_input=True
231
+ )
232
+
233
+ # Tab de Generación de Imágenes
234
+ with gr.TabItem("🎨 Generación de Imágenes"):
235
  with gr.Row():
236
+ with gr.Column():
237
+ image_model = gr.Dropdown(
238
+ choices=list(MODELS["image"].keys()),
239
+ value="runwayml/stable-diffusion-v1-5",
240
+ label="Modelo de Imagen"
241
+ )
242
+ image_prompt = gr.Textbox(
243
+ label="Prompt de Imagen",
244
+ placeholder="Describe la imagen que quieres generar...",
245
+ lines=3
246
+ )
247
+ steps = gr.Slider(
248
+ minimum=10,
249
+ maximum=50,
250
+ value=20,
251
+ step=5,
252
+ label="Pasos de inferencia"
253
+ )
254
+ image_btn = gr.Button("Generar Imagen", variant="primary")
255
+
256
+ with gr.Column():
257
+ image_output = gr.Image(
258
+ label="Imagen Generada",
259
+ type="pil"
260
+ )
261
+
262
+ image_btn.click(
263
+ generate_image,
264
+ inputs=[image_prompt, image_model, steps],
265
+ outputs=image_output
266
+ )
 
267
 
268
+ # Configuración para Hugging Face Spaces
269
  if __name__ == "__main__":
270
+ demo.launch(
271
+ server_name="0.0.0.0",
272
+ server_port=7860,
273
+ share=False
274
+ )
requirements.txt CHANGED
@@ -1,6 +1,8 @@
1
- accelerate
2
- diffusers
3
- invisible_watermark
4
- torch
5
- transformers
6
- xformers
 
 
 
1
+ gradio>=4.0.0
2
+ torch>=2.0.0
3
+ transformers>=4.30.0
4
+ diffusers>=0.20.0
5
+ accelerate>=0.20.0
6
+ Pillow>=9.0.0
7
+ numpy>=1.21.0
8
+ requests>=2.28.0