Spaces:
Sleeping
Sleeping
import gradio as gr | |
from converter import MarkdownToDocxConverter | |
from datetime import datetime | |
import os | |
import requests | |
converter = MarkdownToDocxConverter() | |
def convert_markdown_to_docx(markdown_text: str, file_input: str, url_input: str): | |
# Приоритет: URL > Файл > Текст | |
if url_input: | |
try: | |
response = requests.get(url_input) | |
response.raise_for_status() | |
# Пытаемся получить "сырое" содержимое для таких сайтов, как GitHub Gist | |
if "gist.github.com" in url_input and not url_input.endswith("/raw"): | |
raw_url = url_input + "/raw" | |
response = requests.get(raw_url) | |
response.raise_for_status() | |
markdown_text = response.text | |
except requests.exceptions.RequestException as e: | |
raise gr.Error(f"Ошибка при скачивании файла по URL: {e}") | |
elif file_input: | |
with open(file_input.name, "r", encoding='utf-8') as file: | |
markdown_text = file.read() | |
if not markdown_text.strip(): | |
raise gr.Error("Нет входных данных для конвертации. Введите текст, загрузите файл или укажите URL.") | |
output_dir = "output" | |
os.makedirs(output_dir, exist_ok=True) | |
output_filename = f"output_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx" | |
output_path = os.path.join(output_dir, output_filename) | |
converter.convert(markdown_text, output_path) | |
return output_path | |
demo = gr.Blocks(title="Markdown to DOCX Converter") | |
with demo: | |
gr.Markdown("# Markdown to DOCX Converter") | |
with gr.Row(): | |
with gr.Column(): | |
with gr.Tab("Текст"): | |
markdown_input = gr.TextArea(label="Markdown Input", value="", lines=15) | |
with gr.Tab("Файл"): | |
file_input = gr.File(label="Загрузите Markdown файл") | |
with gr.Tab("URL"): | |
url_input = gr.Textbox(label="Введите URL Markdown файла", placeholder="https://gist.github.com/...") | |
with gr.Column(): | |
gr.Markdown("### Результат") | |
docx_output = gr.File(label="Скачать DOCX") | |
convert_button = gr.Button("Конвертировать", variant="primary") | |
convert_button.click( | |
convert_markdown_to_docx, | |
inputs=[markdown_input, file_input, url_input], | |
outputs=docx_output | |
) | |
if __name__ == "__main__": | |
demo.launch(server_name="0.0.0.0") |