Spaces:
Paused
Paused
File size: 7,331 Bytes
342973b |
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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
"""
Markdown Generator - Generate .md files
"""
from typing import Dict, List, Optional
from datetime import datetime
class MarkdownGenerator:
"""
Generate Markdown (.md) files with proper formatting.
"""
def __init__(self):
"""Initialize Markdown generator."""
pass
def generate_markdown(
self,
title: str,
content: Dict[str, str],
author: str = "AI Academic Suite",
include_toc: bool = True,
include_citations: bool = False,
citations: List[str] = None,
) -> str:
"""
Generate Markdown content.
Args:
title: Document title
content: Dictionary of section titles and content
author: Document author
include_toc: Include table of contents
include_citations: Include bibliography
citations: List of citations
Returns:
Markdown string
"""
md_content = []
# Add title
md_content.append(f"# {title}\n")
# Add metadata
md_content.append(f"**Author:** {author}\n")
md_content.append(f"**Date:** {datetime.now().strftime('%B %d, %Y')}\n\n")
md_content.append("---\n\n")
# Add table of contents
if include_toc:
md_content.append("## Table of Contents\n\n")
for i, section in enumerate(content.keys(), 1):
# Create anchor link
anchor = section.lower().replace(" ", "-")
md_content.append(f"{i}. [{section}](#{anchor})\n")
md_content.append("\n---\n\n")
# Add sections
for section_title, section_content in content.items():
md_content.append(f"## {section_title}\n\n")
md_content.append(section_content)
md_content.append("\n\n")
# Add bibliography
if include_citations and citations:
md_content.append("---\n\n")
md_content.append("## References\n\n")
for i, citation in enumerate(citations, 1):
md_content.append(f"{i}. {citation}\n\n")
return "".join(md_content)
def generate_markdown_bytes(
self,
title: str,
content: Dict[str, str],
author: str = "AI Academic Suite",
include_toc: bool = True,
include_citations: bool = False,
citations: List[str] = None,
) -> bytes:
"""
Generate Markdown content as bytes.
Args:
title: Document title
content: Dictionary of section titles and content
author: Document author
include_toc: Include table of contents
include_citations: Include bibliography
citations: List of citations
Returns:
Markdown bytes
"""
md_text = self.generate_markdown(
title, content, author, include_toc, include_citations, citations
)
return md_text.encode("utf-8")
def add_formatting(self, text: str, formatting_type: str = "emphasis") -> str:
"""
Add Markdown formatting to text.
Args:
text: Text to format
formatting_type: Type of formatting (bold, italic, code, etc.)
Returns:
Formatted text
"""
if formatting_type == "bold":
return f"**{text}**"
elif formatting_type == "italic":
return f"*{text}*"
elif formatting_type == "code":
return f"`{text}`"
elif formatting_type == "code_block":
return f"```\n{text}\n```"
elif formatting_type == "quote":
return f"> {text}"
elif formatting_type == "link":
# Assumes text format: "label|url"
if "|" in text:
label, url = text.split("|", 1)
return f"[{label}]({url})"
return text
else:
return text
def convert_html_to_markdown(self, html_content: str) -> str:
"""
Convert HTML to Markdown.
Args:
html_content: HTML string
Returns:
Markdown string
"""
try:
from html2text import HTML2Text
h = HTML2Text()
h.ignore_links = False
return h.handle(html_content)
except ImportError:
# Fallback basic conversion
import re
md_content = html_content
# Basic HTML to Markdown conversions
md_content = re.sub(r"<h1>(.*?)</h1>", r"# \1", md_content, flags=re.IGNORECASE)
md_content = re.sub(r"<h2>(.*?)</h2>", r"## \1", md_content, flags=re.IGNORECASE)
md_content = re.sub(r"<h3>(.*?)</h3>", r"### \1", md_content, flags=re.IGNORECASE)
md_content = re.sub(r"<b>(.*?)</b>", r"**\1**", md_content, flags=re.IGNORECASE)
md_content = re.sub(r"<i>(.*?)</i>", r"*\1*", md_content, flags=re.IGNORECASE)
md_content = re.sub(r"<code>(.*?)</code>", r"`\1`", md_content, flags=re.IGNORECASE)
md_content = re.sub(r"<p>(.*?)</p>", r"\1\n\n", md_content, flags=re.IGNORECASE)
md_content = re.sub(r"<a href=['\"]([^'\"]+)['\"]>(.*?)</a>", r"[\2](\1)", md_content, flags=re.IGNORECASE)
md_content = re.sub(r"<br\s*/?>", r"\n", md_content, flags=re.IGNORECASE)
md_content = re.sub(r"<[^>]+>", "", md_content) # Remove remaining tags
return md_content
def create_table(self, headers: List[str], rows: List[List[str]]) -> str:
"""
Create Markdown table.
Args:
headers: Table column headers
rows: List of rows (each row is list of cell values)
Returns:
Markdown table string
"""
md_table = "| " + " | ".join(headers) + " |\n"
md_table += "|" + "|".join(["---" for _ in headers]) + "|\n"
for row in rows:
md_table += "| " + " | ".join(str(cell) for cell in row) + " |\n"
return md_table
def create_code_block(self, code: str, language: str = "") -> str:
"""
Create Markdown code block.
Args:
code: Code content
language: Programming language for syntax highlighting
Returns:
Markdown code block
"""
return f"```{language}\n{code}\n```"
def create_list(self, items: List[str], ordered: bool = False) -> str:
"""
Create Markdown list.
Args:
items: List items
ordered: Whether to create ordered (numbered) list
Returns:
Markdown list
"""
if ordered:
return "\n".join(f"{i+1}. {item}" for i, item in enumerate(items))
else:
return "\n".join(f"- {item}" for item in items)
def create_task_list(self, tasks: Dict[str, bool]) -> str:
"""
Create Markdown task list.
Args:
tasks: Dictionary of task descriptions and completion status
Returns:
Markdown task list
"""
task_list = ""
for task, completed in tasks.items():
checkbox = "[x]" if completed else "[ ]"
task_list += f"{checkbox} {task}\n"
return task_list
|