67 lines
2.4 KiB
Python
67 lines
2.4 KiB
Python
"""Format conversion endpoints."""
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from fastapi.responses import Response
|
|
|
|
from app.core.dependencies import get_converter
|
|
from app.schemas.convert import MarkdownToDocxRequest, LatexToOmmlRequest, LatexToOmmlResponse
|
|
from app.services.converter import Converter
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/file")
|
|
async def convert_markdown_to_docx(
|
|
request: MarkdownToDocxRequest,
|
|
converter: Converter = Depends(get_converter),
|
|
) -> Response:
|
|
"""Convert markdown content to DOCX file.
|
|
|
|
Returns the generated DOCX file as a binary response.
|
|
"""
|
|
try:
|
|
docx_bytes = converter.export_to_file(request.markdown, export_type="docx")
|
|
return Response(
|
|
content=docx_bytes,
|
|
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
headers={"Content-Disposition": f'attachment; filename="{request.filename}.docx"'},
|
|
)
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=f"Conversion failed: {e}")
|
|
|
|
|
|
@router.post("/latex-to-omml", response_model=LatexToOmmlResponse)
|
|
async def convert_latex_to_omml(
|
|
request: LatexToOmmlRequest,
|
|
converter: Converter = Depends(get_converter),
|
|
) -> LatexToOmmlResponse:
|
|
"""Convert LaTeX formula to OMML (Office Math Markup Language).
|
|
|
|
OMML is the math format used by Microsoft Word and other Office applications.
|
|
This endpoint is separate from the main OCR endpoint due to the performance
|
|
overhead of OMML conversion (requires creating a temporary DOCX file).
|
|
|
|
Args:
|
|
request: Contains the LaTeX formula to convert (without $ or $$ delimiters).
|
|
|
|
Returns:
|
|
OMML representation of the formula.
|
|
|
|
Example:
|
|
```bash
|
|
curl -X POST "http://localhost:8000/api/v1/convert/latex-to-omml" \\
|
|
-H "Content-Type: application/json" \\
|
|
-d '{"latex": "\\\\frac{a}{b} + \\\\sqrt{c}"}'
|
|
```
|
|
"""
|
|
if not request.latex or not request.latex.strip():
|
|
raise HTTPException(status_code=400, detail="LaTeX formula cannot be empty")
|
|
|
|
try:
|
|
omml = converter.convert_to_omml(request.latex)
|
|
return LatexToOmmlResponse(omml=omml)
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
except RuntimeError as e:
|
|
raise HTTPException(status_code=503, detail=str(e))
|