Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,49 +1,80 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
-
import torch
|
| 4 |
from pptx import Presentation
|
| 5 |
from pptx.util import Inches, Pt
|
| 6 |
-
import os
|
| 7 |
import io
|
| 8 |
from huggingface_hub import InferenceClient
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
| 12 |
|
| 13 |
@st.cache_resource
|
| 14 |
-
def
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
def generate_presentation_content(topic,
|
| 21 |
-
prompt = f"Crea una presentación de PowerPoint sobre el tema: {topic}.
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
def create_powerpoint(slides):
|
| 31 |
prs = Presentation()
|
| 32 |
|
| 33 |
-
for
|
| 34 |
slide = prs.slides.add_slide(prs.slide_layouts[1])
|
| 35 |
|
| 36 |
-
lines = slide_content.split("\n")
|
| 37 |
-
title = lines[0]
|
| 38 |
-
content = "\n".join(lines[1:])
|
| 39 |
-
|
| 40 |
title_shape = slide.shapes.title
|
| 41 |
content_shape = slide.placeholders[1]
|
| 42 |
|
| 43 |
-
title_shape.text = title
|
| 44 |
-
content_shape.text = content
|
| 45 |
|
| 46 |
-
# Guardar la presentación en un buffer de bytes
|
| 47 |
pptx_buffer = io.BytesIO()
|
| 48 |
prs.save(pptx_buffer)
|
| 49 |
pptx_buffer.seek(0)
|
|
@@ -53,28 +84,30 @@ def create_powerpoint(slides):
|
|
| 53 |
def main():
|
| 54 |
st.title("Generador de presentaciones PowerPoint con IA")
|
| 55 |
|
|
|
|
|
|
|
| 56 |
topic = st.text_input("Por favor, ingrese el tema de la presentación:")
|
| 57 |
|
| 58 |
if st.button("Generar Presentación"):
|
| 59 |
if topic:
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
else:
|
| 79 |
st.warning("Por favor, ingrese un tema para la presentación.")
|
| 80 |
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
|
|
|
| 2 |
from pptx import Presentation
|
| 3 |
from pptx.util import Inches, Pt
|
|
|
|
| 4 |
import io
|
| 5 |
from huggingface_hub import InferenceClient
|
| 6 |
+
import json
|
| 7 |
+
import re
|
|
|
|
| 8 |
|
| 9 |
@st.cache_resource
|
| 10 |
+
def get_inference_client():
|
| 11 |
+
return InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
| 12 |
+
|
| 13 |
+
def extract_and_clean_json(text):
|
| 14 |
+
# Intenta encontrar un JSON válido en el texto
|
| 15 |
+
json_match = re.search(r'\{.*\}', text, re.DOTALL)
|
| 16 |
+
if json_match:
|
| 17 |
+
json_str = json_match.group()
|
| 18 |
+
# Limpia el JSON de caracteres no válidos
|
| 19 |
+
json_str = re.sub(r'[\n\t\r]', '', json_str)
|
| 20 |
+
# Intenta corregir problemas comunes de formato
|
| 21 |
+
json_str = re.sub(r',\s*}', '}', json_str) # Elimina comas finales extras
|
| 22 |
+
json_str = re.sub(r',\s*]', ']', json_str) # Elimina comas finales extras en arrays
|
| 23 |
+
return json_str
|
| 24 |
+
return None
|
| 25 |
|
| 26 |
+
def generate_presentation_content(topic, client):
|
| 27 |
+
prompt = f"""Crea una presentación de PowerPoint sobre el tema: {topic}.
|
| 28 |
+
Genera exactamente 5 diapositivas. Cada diapositiva debe tener un título y contenido.
|
| 29 |
+
Formatea la salida como un JSON con la siguiente estructura:
|
| 30 |
+
{{
|
| 31 |
+
"slides": [
|
| 32 |
+
{{"title": "Título de la diapositiva 1", "content": "Contenido de la diapositiva 1"}},
|
| 33 |
+
{{"title": "Título de la diapositiva 2", "content": "Contenido de la diapositiva 2"}},
|
| 34 |
+
...
|
| 35 |
+
]
|
| 36 |
+
}}
|
| 37 |
+
Asegúrate de que la salida sea un JSON válido sin ningún texto adicional antes o después.
|
| 38 |
+
No incluyas saltos de línea o caracteres especiales dentro del JSON.
|
| 39 |
+
"""
|
| 40 |
|
| 41 |
+
response = client.text_generation(prompt, max_new_tokens=1500, temperature=0.7)
|
|
|
|
| 42 |
|
| 43 |
+
try:
|
| 44 |
+
json_str = extract_and_clean_json(response)
|
| 45 |
+
if json_str:
|
| 46 |
+
slides_data = json.loads(json_str)
|
| 47 |
+
if 'slides' in slides_data and len(slides_data['slides']) == 5:
|
| 48 |
+
return slides_data['slides']
|
| 49 |
+
else:
|
| 50 |
+
raise ValueError("El JSON no contiene exactamente 5 diapositivas")
|
| 51 |
+
else:
|
| 52 |
+
raise ValueError("No se encontró un JSON válido en la respuesta")
|
| 53 |
+
except json.JSONDecodeError as e:
|
| 54 |
+
st.error(f"Error al decodificar JSON: {str(e)}")
|
| 55 |
+
st.text("JSON procesado (después de limpieza):")
|
| 56 |
+
st.code(json_str)
|
| 57 |
+
st.text("Respuesta original del modelo:")
|
| 58 |
+
st.code(response)
|
| 59 |
+
return None
|
| 60 |
+
except ValueError as e:
|
| 61 |
+
st.error(str(e))
|
| 62 |
+
st.text("Respuesta del modelo:")
|
| 63 |
+
st.code(response)
|
| 64 |
+
return None
|
| 65 |
|
| 66 |
def create_powerpoint(slides):
|
| 67 |
prs = Presentation()
|
| 68 |
|
| 69 |
+
for slide_data in slides:
|
| 70 |
slide = prs.slides.add_slide(prs.slide_layouts[1])
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
title_shape = slide.shapes.title
|
| 73 |
content_shape = slide.placeholders[1]
|
| 74 |
|
| 75 |
+
title_shape.text = slide_data['title']
|
| 76 |
+
content_shape.text = slide_data['content']
|
| 77 |
|
|
|
|
| 78 |
pptx_buffer = io.BytesIO()
|
| 79 |
prs.save(pptx_buffer)
|
| 80 |
pptx_buffer.seek(0)
|
|
|
|
| 84 |
def main():
|
| 85 |
st.title("Generador de presentaciones PowerPoint con IA")
|
| 86 |
|
| 87 |
+
client = get_inference_client()
|
| 88 |
+
|
| 89 |
topic = st.text_input("Por favor, ingrese el tema de la presentación:")
|
| 90 |
|
| 91 |
if st.button("Generar Presentación"):
|
| 92 |
if topic:
|
| 93 |
+
try:
|
| 94 |
+
with st.spinner("Generando contenido de la presentación..."):
|
| 95 |
+
slides = generate_presentation_content(topic, client)
|
| 96 |
+
|
| 97 |
+
if slides:
|
| 98 |
+
with st.spinner("Creando archivo PowerPoint..."):
|
| 99 |
+
pptx_buffer = create_powerpoint(slides)
|
| 100 |
+
|
| 101 |
+
st.success("Presentación generada con éxito!")
|
| 102 |
+
|
| 103 |
+
st.download_button(
|
| 104 |
+
label="Descargar Presentación",
|
| 105 |
+
data=pptx_buffer,
|
| 106 |
+
file_name=f"{topic.replace(' ', '_')}_presentacion.pptx",
|
| 107 |
+
mime="application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
| 108 |
+
)
|
| 109 |
+
except Exception as e:
|
| 110 |
+
st.error(f"Ocurrió un error al generar la presentación: {str(e)}")
|
| 111 |
else:
|
| 112 |
st.warning("Por favor, ingrese un tema para la presentación.")
|
| 113 |
|