Spaces:
Runtime error
Runtime error
| """ | |
| Utility functions for generating Word documents (DOCX) from course outlines. | |
| This module provides a helper to convert a course outline into a .docx file. | |
| It uses the python-docx library to construct a simple document with a title, | |
| outline sections, optional bullet points, and a references section. The | |
| generated file is saved to a temporary location and the path is returned. | |
| Dependencies: | |
| python-docx >= 1.1.0 | |
| """ | |
| from datetime import datetime | |
| from typing import List, Dict, Optional | |
| from docx import Document | |
| from docx.shared import Pt | |
| def outline_to_docx( | |
| title: str, | |
| outline_text: str, | |
| references: Optional[List[Dict[str, str]]] = None, | |
| path: str = "/tmp/course_outline.docx", | |
| ) -> str: | |
| """Create a Word document from a course outline. | |
| Args: | |
| title: Title for the course or outline. | |
| outline_text: Plain text of the outline. Each line will be written as a | |
| separate paragraph. If you need more structured output, consider | |
| extending this function to parse the text. | |
| references: Optional list of dictionaries with 'title' and 'url' keys. | |
| These will be included in a references section at the end. | |
| path: File system path where the document will be written. Defaults | |
| to '/tmp/course_outline.docx'. | |
| Returns: | |
| The file path to the generated document. | |
| """ | |
| # Create a new document | |
| doc = Document() | |
| # Title heading | |
| title_heading = doc.add_heading(level=1) | |
| run = title_heading.add_run(title or "Course Outline") | |
| run.bold = True | |
| run.font.size = Pt(20) | |
| # Write each line of the outline as a paragraph | |
| for line in (outline_text or "").splitlines(): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| # Use list bullet style if the line looks like a bullet (starts with '-' or '*') | |
| if line.lstrip().startswith(("-", "*")): | |
| # Remove leading bullet characters | |
| content = line.lstrip("-* ") | |
| p = doc.add_paragraph(content, style="List Bullet") | |
| else: | |
| p = doc.add_paragraph(line) | |
| # Standard font size | |
| for r in p.runs: | |
| r.font.size = Pt(12) | |
| # References | |
| if references: | |
| doc.add_heading("References", level=2) | |
| for ref in references: | |
| ref_title = ref.get("title", "") | |
| ref_url = ref.get("url", "") | |
| para = doc.add_paragraph() | |
| if ref_title: | |
| para.add_run(ref_title).bold = True | |
| para.add_run(" β ") | |
| para.add_run(ref_url) | |
| for r in para.runs: | |
| r.font.size = Pt(11) | |
| # Timestamp | |
| doc.add_paragraph() | |
| timestamp = datetime.now().strftime("Generated %Y-%m-%d %H:%M:%S") | |
| footer = doc.add_paragraph(timestamp) | |
| for r in footer.runs: | |
| r.font.size = Pt(8) | |
| # Save document | |
| doc.save(path) | |
| return path |