Files
hsa/Html/apps/services/markdown_service.py
2025-12-11 20:46:22 +08:00

65 lines
2.3 KiB
Python

import os, shutil, markdown
from flask import current_app
from ..services.course_service import load_material
from ..services.cos_service import get_text_file
def load_full_markdown_file(course_id, chapter_name, lesson_name):
material = load_material(course_id)
for chapter in material.chapters:
if chapter.chapter_name == chapter_name:
for lesson in chapter.lessons:
if lesson.lesson_name == lesson_name:
return get_text_file(lesson.markdown_lesson_file_link), get_text_file(lesson.markdown_prompt_file_name), get_text_file(lesson.markdown_score_prompt_file_link)
return None, None, None
def load_markdown_file(course_id, chapter_name, lesson_name):
material = load_material(course_id)
file_link = None
for chapter in material.chapters:
if chapter.chapter_name == chapter_name:
for lesson in chapter.lessons:
if lesson.lesson_name == lesson_name:
file_link = lesson.markdown_lesson_file_link
break
break
if file_link is None:
return None
return get_text_file(file_link)
def convert_markdown_to_html(md_file: str) -> str:
"""将 markdown 文件转成 HTML 片段"""
return markdown.markdown(md_file)
def wrap_with_styles(html_content: str) -> str:
"""加上 CSS 样式和外层 HTML"""
return f"""
<html>
<head>
<style>
img {{
max-width: 100%;
height: auto;
}}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css">
</head>
<body class="markdown-body">
{html_content}
</body>
</html>
"""
def save_html(html_str: str, output_path: str) -> None:
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
f.write(html_str)
def copy_images(source_dir: str, target_dir: str) -> None:
if not os.path.exists(source_dir):
return
os.makedirs(target_dir, exist_ok=True)
for filename in os.listdir(source_dir):
src = os.path.join(source_dir, filename)
if os.path.isfile(src):
shutil.copy(src, target_dir)