Spaces:
Sleeping
Sleeping
File size: 3,226 Bytes
9c62954 a364276 9c62954 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
import gradio as gr
import subprocess
import tempfile
import os
import uuid
def convert_to_epub(uploaded_file, title, author):
"""
Convierte un archivo de entrada (docx, pdf, md, etc.) a EPUB utilizando Pandoc.
Permite incluir opcionalmente metadatos (t铆tulo y autor).
"""
# Verificar que se haya subido un archivo
if uploaded_file is None:
return "No se ha subido ning煤n archivo."
# Obtener la extensi贸n del archivo mediante su nombre original
filename = uploaded_file.name if hasattr(uploaded_file, "name") else "input_file"
ext = os.path.splitext(filename)[1].lower()
if ext == "":
return "El archivo subido no tiene extensi贸n reconocible."
# Crear un directorio temporal para manejar archivos de entrada y salida
with tempfile.TemporaryDirectory() as tmpdir:
input_filename = f"input_{uuid.uuid4().hex}{ext}"
input_path = os.path.join(tmpdir, input_filename)
output_path = os.path.join(tmpdir, "output.epub")
# Escribir el archivo subido en disco
with open(input_path, "wb") as f:
with open(uploaded_file, "rb") as uploaded:
f.write(uploaded.read())
# Construir el comando para Pandoc
cmd = ["pandoc", input_path, "-o", output_path, "--toc"]
# Incluir metadatos opcionales (si el usuario los provee)
if title.strip():
cmd.extend(["--metadata", f"title={title.strip()}"])
if author.strip():
cmd.extend(["--metadata", f"author={author.strip()}"])
# Ejecutar Pandoc y capturar errores, si los hubiera
try:
result = subprocess.run(
cmd,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
except subprocess.CalledProcessError as e:
error_message = e.stderr if e.stderr else str(e)
return f"Error en la conversi贸n: {error_message}"
# Verificar que el archivo EPUB se gener贸
if not os.path.exists(output_path):
return "Error: El archivo EPUB no se gener贸 correctamente."
# Leer el archivo EPUB generado
with open(output_path, "rb") as f:
epub_data = f.read()
# Para que Gradio ofrezca el archivo para descarga, lo salvamos temporalmente
output_filename = "output.epub"
with open(output_filename, "wb") as f:
f.write(epub_data)
return output_filename
# Configuraci贸n de la interfaz de Gradio
iface = gr.Interface(
fn=convert_to_epub,
inputs=[
gr.File(label="Sube un archivo (docx, pdf, md, etc.)"),
gr.Textbox(label="T铆tulo (opcional)", placeholder="T铆tulo del documento"),
gr.Textbox(label="Autor (opcional)", placeholder="Autor del documento")
],
outputs=gr.File(label="Archivo EPUB"),
title="Conversor a EPUB con Pandoc",
description=(
"Sube un documento en uno de los formatos soportados (docx, pdf, md, etc.) y convi茅rtelo a EPUB utilizando Pandoc.\n\n"
),
allow_flagging="never",
)
if __name__ == "__main__":
iface.launch() |