Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import os | |
| import google.generativeai as genai | |
| from PyPDF2 import PdfReader | |
| from fpdf import FPDF | |
| # Inyecta CSS para utilizar la fuente "Poppins" de Google Fonts | |
| st.markdown(""" | |
| <style> | |
| @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap'); | |
| html, body, [class*="css"] { | |
| font-family: 'Poppins', sans-serif; | |
| } | |
| h1, h2, h3, h4, h5, h6 { | |
| font-weight: 600; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| api_key = os.environ.get("GEMINI_API_KEY") | |
| if not api_key: | |
| st.error("La clave API no está configurada. Por favor, configúrala en las variables de entorno.") | |
| else: | |
| genai.configure(api_key=api_key) | |
| configuracion_generacion = { | |
| "temperature": 2, | |
| "top_p": 0.95, | |
| "top_k": 64, | |
| "max_output_tokens": 65536, | |
| "response_mime_type": "text/plain", | |
| } | |
| modelo = genai.GenerativeModel( | |
| model_name="gemini-2.0-flash-thinking-exp-01-21", | |
| generation_config=configuracion_generacion, | |
| ) | |
| def extraer_texto_de_pdf(archivo): | |
| """Extrae el texto de un archivo PDF subido.""" | |
| lector = PdfReader(archivo) | |
| texto = "" | |
| for pagina in lector.pages: | |
| texto += pagina.extract_text() + "\n" | |
| return texto | |
| def respuesta_stream(prompt): | |
| """Envía el prompt al modelo generativo y transmite la respuesta en tiempo real.""" | |
| sesion_chat = modelo.start_chat( | |
| history=[{"role": "user", "parts": [prompt]}] | |
| ) | |
| for fragmento in sesion_chat.send_message("Procesando entrada...", stream=True): | |
| if fragmento.text: | |
| yield fragmento.text | |
| def crear_pdf(contenido): | |
| """Crea un archivo PDF bien formateado a partir del contenido dado.""" | |
| pdf = FPDF() | |
| pdf.add_page() | |
| pdf.set_font("Arial", size=12) | |
| lineas = contenido.split("\n") | |
| for linea in lineas: | |
| # Elimina el formato de negrita estilo markdown (**) | |
| linea_formateada = linea.replace("**", "") | |
| pdf.multi_cell(0, 10, linea_formateada) | |
| return pdf | |
| # Interfaz de usuario con Streamlit | |
| st.title("Resumen de Texto y Extracción de Ideas Clave") | |
| # Estado de sesión para almacenar el texto generado | |
| if "texto_generado" not in st.session_state: | |
| st.session_state.texto_generado = "" | |
| archivo_subido = st.file_uploader("Sube un documento (PDF) o pega el texto a continuación:", type=["pdf"]) | |
| texto_entrada = st.text_area("O pega tu artículo aquí:", placeholder="Pega tu artículo o texto aquí...") | |
| if st.button("Generar Resumen e Ideas Clave"): | |
| if archivo_subido: | |
| texto_entrada = extraer_texto_de_pdf(archivo_subido) | |
| if texto_entrada.strip(): | |
| st.markdown("### Generando resultados...") | |
| contenedor_respuesta = st.empty() | |
| st.session_state.texto_generado = "" # Limpiar el texto previo | |
| for fragmento in respuesta_stream(f"Resume el siguiente texto y extrae las ideas clave:\n{texto_entrada}"): | |
| st.session_state.texto_generado += fragmento | |
| contenedor_respuesta.markdown(st.session_state.texto_generado) | |
| else: | |
| st.warning("Por favor, sube un archivo o ingresa texto para procesar.") | |
| if st.session_state.texto_generado: | |
| st.markdown("### Resumen e Ideas Clave") | |
| st.text_area("Resultados:", st.session_state.texto_generado, height=300) | |
| # Generar PDF para descarga | |
| pdf = crear_pdf(st.session_state.texto_generado) | |
| archivo_pdf = "resumen_ideas.pdf" | |
| pdf.output(archivo_pdf) | |
| with open(archivo_pdf, "rb") as f: | |
| st.download_button( | |
| label="Descargar PDF", | |
| data=f, | |
| file_name="resumen_ideas.pdf", | |
| mime="application/pdf" | |
| ) | |