iespsurmreqmer commited on
Commit
6996c97
·
1 Parent(s): 80645ad
Files changed (7) hide show
  1. README.md +1 -1
  2. app.py +28 -20
  3. app2.py +38 -14
  4. app4.py +5 -9
  5. app5.py +4 -8
  6. app6.py +0 -35
  7. temp_image.jpg +0 -0
README.md CHANGED
@@ -5,7 +5,7 @@ colorFrom: gray
5
  colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.0.2
8
- app_file: app6.py
9
  pinned: false
10
  ---
11
 
 
5
  colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.0.2
8
+ app_file: app.py
9
  pinned: false
10
  ---
11
 
app.py CHANGED
@@ -1,29 +1,37 @@
1
  import gradio as gr
2
- from diffusers import DiffusionPipeline
3
  from PIL import Image
4
- import torch
5
 
6
- # Cargar pipeline (float32 para CPU)
7
- model_id = "stabilityai/stable-diffusion-x4-upscaler"
8
- pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-x4-upscaler", dtype=torch.bfloat16, device_map="cuda")
9
 
10
- # Función de Gradio
11
- def upscaler_gradio(imagen):
12
  if imagen is None:
13
- return None
14
 
15
- img = Image.fromarray(imagen) # convertir de NumPy a PIL
16
- prompt = "A high quality, detailed, and visually clear image"
17
- result = pipe(prompt=prompt, image=img).images[0]
18
  return result
19
 
20
- # Interfaz Gradio
21
- demo = gr.Interface(
22
- fn=upscaler_gradio,
23
- inputs=gr.Image(type="numpy"),
24
- outputs=gr.Image(),
25
- title="Upscaler Difusión",
26
- description="Sube una imagen y el modelo la mejorará y aumentará resolución 4×."
27
- )
28
 
29
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
2
  from PIL import Image
3
+ from transformers import pipeline
4
 
5
+ captioner = pipeline("image-to-text", model="Salesforce/blip-image-captioning-large")
 
 
6
 
7
+ def describir(imagen):
 
8
  if imagen is None:
9
+ return "Sube una imagen."
10
 
11
+ img = Image.fromarray(imagen)
12
+
13
+ result = captioner(img)[0]["generated_text"]
14
  return result
15
 
16
+ with gr.Blocks(title="Accesibilidad con Transformers") as demo:
17
+ gr.Markdown(
18
+ """
19
+ #Accesibilidad con Transformers
20
+ Sube una imagen y un modelo Transformer generará una descripción detallada
21
+ para mejorar la accesibilidad del contenido visual.
22
+ """
23
+ )
24
 
25
+ with gr.Row():
26
+ image_input = gr.Image(type="numpy", label="Sube una Imagen")
27
+
28
+ text_output = gr.Textbox(label="Descripción Generada")
29
+
30
+ run_button = gr.Button("Generar Descripción")
31
+ run_button.click(
32
+ fn=describir,
33
+ inputs=image_input,
34
+ outputs=text_output
35
+ )
36
+
37
+ demo.launch()
app2.py CHANGED
@@ -1,8 +1,6 @@
1
  from transformers import pipeline
2
  import gradio as gr
3
 
4
- #Recomendador trabajar o estudiar transformer
5
-
6
  generator = pipeline(
7
  "text2text-generation",
8
  model="google/flan-t5-small"
@@ -24,16 +22,42 @@ Explain the reasoning behind your recommendation.
24
  result = generator(prompt, max_length=200)
25
  return result[0]['generated_text']
26
 
27
- interface = gr.Interface(
28
- fn=career_advice,
29
- inputs=[
30
- gr.Number(label="Age"),
31
- gr.Textbox(label="Academic level"),
32
- gr.Textbox(label="Interests"),
33
- gr.Dropdown(choices=["Yes", "No"], label="Needs income")
34
- ],
35
- outputs=gr.Textbox(label="Recommendation"),
36
- title="Career Advisor for Students"
37
- )
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from transformers import pipeline
2
  import gradio as gr
3
 
 
 
4
  generator = pipeline(
5
  "text2text-generation",
6
  model="google/flan-t5-small"
 
22
  result = generator(prompt, max_length=200)
23
  return result[0]['generated_text']
24
 
25
+ with gr.Blocks(title="Asesor de Carrera Profesional") as demo:
26
+ gr.Markdown(
27
+ """
28
+ #Asesor de Carrera Profesional con IA
29
+ Bienvenido al asesor de carrera basado en el modelo **FLAN-T5**.
30
+ Introduce tus datos para recibir una recomendación personalizada sobre si deberías **continuar estudiando**,
31
+ hacer **Formación Profesional (FP)** o **comenzar a trabajar**.
32
+ """
33
+ )
34
+
35
+ with gr.Row():
36
+ with gr.Column(scale=1):
37
+ gr.Markdown("## 📝 Datos del Estudiante")
38
+ age_input = gr.Number(label="Edad", minimum=15, maximum=60, step=1)
39
+ academic_input = gr.Textbox(label="Nivel Académico (Ej: ESO, Bachillerato, Grado Universitario, etc.)", placeholder="Ej: Bachillerato de Ciencias")
40
+ interests_input = gr.Textbox(label="Intereses (Palabras clave)", placeholder="Ej: Tecnología, Diseño Gráfico, Cocina, Viajes")
41
+ income_input = gr.Dropdown(choices=["Sí", "No"], label="¿Necesitas generar ingresos inmediatamente?")
42
+
43
+ run_button = gr.Button("Obtener Recomendación ✨", variant="primary")
44
+
45
+ with gr.Column(scale=2):
46
+ gr.Markdown("## 💡 Recomendación Personalizada")
47
+ output_textbox = gr.Textbox(label="Recomendación del Experto", lines=10, interactive=False)
48
 
49
+ run_button.click(
50
+ fn=career_advice,
51
+ inputs=[age_input, academic_input, interests_input, income_input],
52
+ outputs=output_textbox
53
+ )
54
+
55
+ gr.Examples(
56
+ examples=[
57
+ [18, "High School Diploma", "Web design, programming", "No"],
58
+ [25, "University Degree (Incomplete)", "Project management, sales", "Yes"],
59
+ [16, "Compulsory Secondary Education (ESO)", "Mechanics, vehicle repair", "No"]
60
+ ],
61
+ inputs=[age_input, academic_input, interests_input, income_input]
62
+ )
63
+ demo.launch()
app4.py CHANGED
@@ -3,38 +3,34 @@ from huggingface_hub import InferenceClient
3
  import gradio as gr
4
  from dotenv import load_dotenv
5
 
6
- # Cargar variables del .env
7
  load_dotenv()
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
 
10
  if HF_TOKEN is None:
11
- raise ValueError("No se encontró la variable HF_TOKEN en el .env")
 
12
 
13
- # Inicializar cliente de inferencia HF
14
  client = InferenceClient(provider="hf-inference", api_key=HF_TOKEN)
15
 
16
  def clasificar_imagen(imagen):
17
  if imagen is None:
18
  return "Sube una imagen para clasificar."
19
 
20
- # Guardar temporalmente la imagen para enviarla al cliente
21
  temp_path = "temp_image.jpg"
22
  imagen.save(temp_path)
23
 
24
- # Llamada a la API
25
  output = client.image_classification(temp_path, model="google/vit-base-patch16-224")
26
 
27
- # Retornar la clasificación más probable
28
  if isinstance(output, list) and len(output) > 0:
29
  resultado = "\n".join([f"{item['label']}: {item['score']:.2f}" for item in output])
30
  else:
31
  resultado = "No se pudo clasificar la imagen."
32
  return resultado
33
 
34
- # Interfaz Gradio
35
  with gr.Blocks() as demo:
36
- gr.Markdown("# 🖼️ Clasificador de Imágenes con ViT")
37
- gr.Markdown("Sube una imagen y el modelo ViT-base de Google la clasificará usando HF Inference API gratuita.")
38
 
39
  img_input = gr.Image(type="pil", label="Sube tu imagen aquí")
40
  boton = gr.Button("Clasificar Imagen")
 
3
  import gradio as gr
4
  from dotenv import load_dotenv
5
 
6
+
7
  load_dotenv()
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
 
10
  if HF_TOKEN is None:
11
+ raise ValueError("No se encontró la variable HF_TOKEN en el .env")
12
+
13
 
 
14
  client = InferenceClient(provider="hf-inference", api_key=HF_TOKEN)
15
 
16
  def clasificar_imagen(imagen):
17
  if imagen is None:
18
  return "Sube una imagen para clasificar."
19
 
 
20
  temp_path = "temp_image.jpg"
21
  imagen.save(temp_path)
22
 
 
23
  output = client.image_classification(temp_path, model="google/vit-base-patch16-224")
24
 
 
25
  if isinstance(output, list) and len(output) > 0:
26
  resultado = "\n".join([f"{item['label']}: {item['score']:.2f}" for item in output])
27
  else:
28
  resultado = "No se pudo clasificar la imagen."
29
  return resultado
30
 
 
31
  with gr.Blocks() as demo:
32
+ gr.Markdown("# Clasificador de Imágenes con ViT")
33
+ gr.Markdown("Sube una imagen y se clasificará.")
34
 
35
  img_input = gr.Image(type="pil", label="Sube tu imagen aquí")
36
  boton = gr.Button("Clasificar Imagen")
app5.py CHANGED
@@ -3,29 +3,25 @@ from huggingface_hub import InferenceClient
3
  import gradio as gr
4
  from dotenv import load_dotenv
5
 
6
- # Cargar variables del .env
7
  load_dotenv()
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
 
10
  if HF_TOKEN is None:
11
- raise ValueError("No se encontró la variable HF_TOKEN en el .env")
12
 
13
- # Inicializar cliente de inferencia HF
14
  client = InferenceClient(provider="hf-inference", api_key=HF_TOKEN)
15
 
16
  def generar_imagen(prompt):
17
  if not prompt.strip():
18
  return None
19
 
20
- # Llamada a la API
21
  imagen = client.text_to_image(prompt, model="black-forest-labs/FLUX.1-schnell")
22
 
23
- return imagen # es un objeto PIL.Image
24
 
25
- # Interfaz Gradio
26
  with gr.Blocks() as demo:
27
- gr.Markdown("# 🎨 Generador de Imágenes con FLUX.1-schnell")
28
- gr.Markdown("Escribe un prompt y el modelo generará la imagen usando HF Inference API gratuita.")
29
 
30
  prompt_input = gr.Textbox(label="Escribe tu prompt aquí", lines=3)
31
  boton = gr.Button("Generar Imagen")
 
3
  import gradio as gr
4
  from dotenv import load_dotenv
5
 
 
6
  load_dotenv()
7
  HF_TOKEN = os.getenv("HF_TOKEN")
8
 
9
  if HF_TOKEN is None:
10
+ raise ValueError("No se encontró la variable HF_TOKEN en el .env")
11
 
 
12
  client = InferenceClient(provider="hf-inference", api_key=HF_TOKEN)
13
 
14
  def generar_imagen(prompt):
15
  if not prompt.strip():
16
  return None
17
 
 
18
  imagen = client.text_to_image(prompt, model="black-forest-labs/FLUX.1-schnell")
19
 
20
+ return imagen
21
 
 
22
  with gr.Blocks() as demo:
23
+ gr.Markdown("#Generador de Imágenes")
24
+ gr.Markdown("Escribe un prompt y el modelo generará la imagen usando Inference.")
25
 
26
  prompt_input = gr.Textbox(label="Escribe tu prompt aquí", lines=3)
27
  boton = gr.Button("Generar Imagen")
app6.py DELETED
@@ -1,35 +0,0 @@
1
- import gradio as gr
2
- from PIL import Image
3
- from diffusers import StableDiffusionImg2ImgPipeline
4
- import torch
5
-
6
- model_id = "runwayml/stable-diffusion-v1-5"
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
-
9
- pipe = StableDiffusionImg2ImgPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to(device)
10
-
11
- def convert_simple(input_image: Image.Image) -> Image.Image:
12
- prompt = "A high contrast, dramatic photo, black and white, monochrome, grayscale"
13
- strength = 0.95
14
-
15
- input_image = input_image.convert("RGB").resize((512, 512))
16
-
17
- output_image = pipe(
18
- prompt=prompt,
19
- image=input_image,
20
- strength=strength,
21
- guidance_scale=7.5
22
- ).images[0]
23
-
24
- final_bn_image = output_image.convert('L')
25
-
26
- return final_bn_image
27
-
28
- iface = gr.Interface(
29
- fn=convert_simple,
30
- inputs=[gr.Image(type="pil")],
31
- outputs="image",
32
- )
33
-
34
- if __name__ == "__main__":
35
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
temp_image.jpg DELETED
Binary file (31.7 kB)