Spaces:
Sleeping
Sleeping
File size: 4,084 Bytes
0832ae9 1e3cf08 aacdab1 1e3cf08 aacdab1 0832ae9 1e3cf08 aacdab1 1e3cf08 aacdab1 1e3cf08 aacdab1 1e3cf08 aacdab1 1e3cf08 aacdab1 1e3cf08 0832ae9 1e3cf08 aacdab1 7578bf5 1e3cf08 0832ae9 aacdab1 1e3cf08 7578bf5 4bc15ad aacdab1 80255bb f0ce083 4bc15ad aacdab1 1e3cf08 4bc15ad aacdab1 0832ae9 aacdab1 1e3cf08 0832ae9 1e3cf08 0832ae9 1e3cf08 aacdab1 1e3cf08 aacdab1 0832ae9 aacdab1 | 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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | import gradio as gr
import hashlib
import os
from dotenv import load_dotenv
load_dotenv()
from pipeline import run_course_builder
cache = {}
def get_cache_key(query: str, toc: str, archive_name: str = "") -> str:
key_string = f"{query.strip()}|{toc.strip()}|{archive_name}"
return hashlib.md5(key_string.encode('utf-8')).hexdigest()
def generate_course(query: str, toc: str, archive_file):
if archive_file is None:
return "❌ Пожалуйста, загрузите ZIP-архив с материалами", ""
try:
if hasattr(archive_file, 'read'):
file_content = archive_file.read()
else:
with open(str(archive_file), "rb") as f:
file_content = f.read()
archive_name = getattr(archive_file, 'name', 'unknown.zip')
cache_key = get_cache_key(query, toc, archive_name)
if cache_key in cache:
return "✅ Курс успешно сгенерирован!", cache[cache_key]
temp_path = "temp_materials.zip"
with open(temp_path, "wb") as f:
f.write(file_content)
result = run_course_builder(query, toc or "", temp_path)
markdown = result if isinstance(result, str) else result.get("markdown") or result.get("result") or str(result)
cache[cache_key] = markdown
return "✅ Курс успешно сгенерирован!", markdown
except Exception as e:
error_msg = f"❌ Ошибка: {str(e)}"
return error_msg, error_msg
def clear_cache():
cache.clear()
if os.path.exists("temp_materials.zip"):
try:
os.remove("temp_materials.zip")
except:
pass
return "🗑️ Кэш очищен", ""
def clear_cache():
cache.clear()
if os.path.exists("temp_materials.zip"):
try:
os.remove("temp_materials.zip")
except:
pass
return "🗑️ Кэш и временные файлы очищены", ""
# ====================== Gradio Interface ======================
with gr.Blocks(title="Генератор учебных курсов", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 📚 Генератор Учебных Курсов")
gr.Markdown("Загрузите оглавление и архив с материалами — получите готовый понедельный план")
with gr.Row():
with gr.Column(scale=2):
query_input = gr.Textbox(
label="Описание курса",
placeholder="Напишите, какой курс вам нужен (например: интенсивный курс на 9 недель по алгебре и геометрии)...",
lines=3
)
toc_input = gr.Textbox(
label="Оглавление",
placeholder="Вставьте оглавление предоставляемых материалов...",
lines=8
)
file_input = gr.File(
label="Архив с материалами (.zip)",
file_types=[".zip"],
type="filepath"
)
with gr.Column(scale=3):
status_output = gr.Textbox(label="Статус", interactive=False)
markdown_output = gr.Markdown(label="Сгенерированный курс", height=720)
with gr.Row():
generate_btn = gr.Button("🚀 Сгенерировать курс", variant="primary", size="large")
clear_btn = gr.Button("🗑️ Очистить кэш и файлы", variant="secondary")
# Обработка генерации
generate_btn.click(
fn=generate_course,
inputs=[query_input, toc_input, file_input],
outputs=[status_output, markdown_output]
)
# Очистка кэша
clear_btn.click(
fn=clear_cache,
inputs=[],
outputs=[status_output, markdown_output]
)
if __name__ == "__main__":
demo.launch() |