JairoCesar commited on
Commit
18522a9
·
verified ·
1 Parent(s): 659187e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -24
app.py CHANGED
@@ -4,14 +4,14 @@ from pptx.util import Inches
4
  import requests
5
  from PIL import Image
6
  from io import BytesIO
 
7
  import os
8
  import json
9
  import re
10
  import google.generativeai as genai
11
 
12
-
13
  # Configurar Gemini
14
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") # Asegúrate de que esté bien escrito
15
  genai.configure(api_key=GEMINI_API_KEY)
16
 
17
  # Obtener la clave API de Pixabay desde los secretos de Streamlit
@@ -19,7 +19,7 @@ PIXABAY_API_KEY = st.secrets["pixabay"]
19
 
20
  @st.cache_resource
21
  def get_gemini_model():
22
- return genai.GenerativeModel("gemini-1.5-flash") # Puedes cambiar al modelo que d
23
 
24
  def extract_and_clean_json(text):
25
  json_match = re.search(r'\{.*\}', text, re.DOTALL)
@@ -54,27 +54,22 @@ def generate_presentation_content(topic, client, max_retries=3):
54
  """
55
 
56
  for attempt in range(max_retries):
57
- response = client.text_generation(prompt, max_new_tokens=2000, temperature=0.7)
58
-
59
  try:
 
60
  json_str = extract_and_clean_json(response)
61
  if json_str:
62
  slides_data = json.loads(json_str)
63
  if 'slides' in slides_data and len(slides_data['slides']) == 9:
64
  return slides_data['slides']
65
-
66
- # Si llegamos aquí, el JSON no era válido o no tenía la estructura correcta
67
  raise ValueError("JSON inválido o estructura incorrecta")
68
-
69
  except (json.JSONDecodeError, ValueError) as e:
70
- if attempt == max_retries - 1: # Último intento
71
  st.error(f"Error al generar el contenido después de {max_retries} intentos: {str(e)}")
72
  st.text("Última respuesta del modelo:")
73
  st.code(response)
74
  return None
75
  else:
76
  st.warning(f"Intento {attempt + 1} fallido. Reintentando...")
77
-
78
  return None
79
 
80
  def buscar_imagen_pixabay(query):
@@ -107,7 +102,7 @@ def create_powerpoint(slides, template_path):
107
 
108
  # Buscar e insertar imagen
109
  try:
110
- img = buscar_imagen_pixabay(slide_data['title']) # usar el título como consulta
111
  if img:
112
  img_path = "/tmp/temp_img.jpg"
113
  img.save(img_path)
@@ -125,38 +120,37 @@ def create_powerpoint(slides, template_path):
125
  return pptx_buffer
126
 
127
  def main():
128
- st.title("PowerPoint Mágico con el Buho")
129
-
130
- client = get_inference_client()
131
-
132
  topic = st.text_input("Por favor, ingrese el tema de la presentación:")
133
-
134
- # Opciones de plantillas
135
  template_options = {
136
  "Simple": "PLANTILLAS/Simple.pptx",
137
  "Corporativo": "PLANTILLAS/Corporativo.pptx",
138
  "Moderno": "PLANTILLAS/Moderno.pptx"
139
  }
140
-
141
  selected_template = st.selectbox("Seleccione una plantilla", list(template_options.keys()))
142
-
143
  if st.button("Generar Presentación"):
144
  if topic:
145
  try:
146
  with st.spinner("Generando contenido de la presentación..."):
147
  slides = generate_presentation_content(topic, client)
148
-
149
  if slides:
150
  template_path = template_options[selected_template]
151
  if not os.path.exists(template_path):
152
  st.error(f"No se encontró la plantilla: {template_path}")
153
  return
154
-
155
  with st.spinner("Creando archivo PowerPoint..."):
156
  pptx_buffer = create_powerpoint(slides, template_path)
157
-
158
- st.success("Presentación generada con éxito!")
159
-
160
  st.download_button(
161
  label="Descargar Presentación",
162
  data=pptx_buffer,
 
4
  import requests
5
  from PIL import Image
6
  from io import BytesIO
7
+ import io
8
  import os
9
  import json
10
  import re
11
  import google.generativeai as genai
12
 
 
13
  # Configurar Gemini
14
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
15
  genai.configure(api_key=GEMINI_API_KEY)
16
 
17
  # Obtener la clave API de Pixabay desde los secretos de Streamlit
 
19
 
20
  @st.cache_resource
21
  def get_gemini_model():
22
+ return genai.GenerativeModel("gemini-1.5-flash")
23
 
24
  def extract_and_clean_json(text):
25
  json_match = re.search(r'\{.*\}', text, re.DOTALL)
 
54
  """
55
 
56
  for attempt in range(max_retries):
 
 
57
  try:
58
+ response = client.generate_content(prompt).text
59
  json_str = extract_and_clean_json(response)
60
  if json_str:
61
  slides_data = json.loads(json_str)
62
  if 'slides' in slides_data and len(slides_data['slides']) == 9:
63
  return slides_data['slides']
 
 
64
  raise ValueError("JSON inválido o estructura incorrecta")
 
65
  except (json.JSONDecodeError, ValueError) as e:
66
+ if attempt == max_retries - 1:
67
  st.error(f"Error al generar el contenido después de {max_retries} intentos: {str(e)}")
68
  st.text("Última respuesta del modelo:")
69
  st.code(response)
70
  return None
71
  else:
72
  st.warning(f"Intento {attempt + 1} fallido. Reintentando...")
 
73
  return None
74
 
75
  def buscar_imagen_pixabay(query):
 
102
 
103
  # Buscar e insertar imagen
104
  try:
105
+ img = buscar_imagen_pixabay(slide_data['title'])
106
  if img:
107
  img_path = "/tmp/temp_img.jpg"
108
  img.save(img_path)
 
120
  return pptx_buffer
121
 
122
  def main():
123
+ st.title("PowerPoint Mágico con el Búho")
124
+
125
+ client = get_gemini_model()
126
+
127
  topic = st.text_input("Por favor, ingrese el tema de la presentación:")
128
+
 
129
  template_options = {
130
  "Simple": "PLANTILLAS/Simple.pptx",
131
  "Corporativo": "PLANTILLAS/Corporativo.pptx",
132
  "Moderno": "PLANTILLAS/Moderno.pptx"
133
  }
134
+
135
  selected_template = st.selectbox("Seleccione una plantilla", list(template_options.keys()))
136
+
137
  if st.button("Generar Presentación"):
138
  if topic:
139
  try:
140
  with st.spinner("Generando contenido de la presentación..."):
141
  slides = generate_presentation_content(topic, client)
142
+
143
  if slides:
144
  template_path = template_options[selected_template]
145
  if not os.path.exists(template_path):
146
  st.error(f"No se encontró la plantilla: {template_path}")
147
  return
148
+
149
  with st.spinner("Creando archivo PowerPoint..."):
150
  pptx_buffer = create_powerpoint(slides, template_path)
151
+
152
+ st.success("¡Presentación generada con éxito!")
153
+
154
  st.download_button(
155
  label="Descargar Presentación",
156
  data=pptx_buffer,