JairoDanielMT commited on
Commit
f25faa7
1 Parent(s): 30fcc0b
Files changed (1) hide show
  1. app/main.py +84 -0
app/main.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ from typing import Any, Dict, Literal, Optional
5
+
6
+ from fastapi import FastAPI, HTTPException
7
+ from fastapi.responses import HTMLResponse, StreamingResponse
8
+ from pydantic import BaseModel, Field
9
+
10
+ from .renderer import render_html, render_pdf_bytes
11
+
12
+ app = FastAPI(
13
+ title="Doc Compiler Service",
14
+ version="1.0.0",
15
+ description=(
16
+ "Servicio de compilaci贸n que recibe JSON de documentaci贸n, "
17
+ "renderiza plantillas Jinja2 y devuelve HTML o PDF."
18
+ ),
19
+ )
20
+
21
+
22
+ class CompileRequest(BaseModel):
23
+ doc: Dict[str, Any] = Field(
24
+ ...,
25
+ description="JSON de documentaci贸n generado por la IA (incluyendo metadata.script_type).",
26
+ )
27
+ job_id: Optional[str] = Field(
28
+ None,
29
+ description="Identificador opcional para el archivo (por ejemplo, nombre del script o job).",
30
+ )
31
+ output: Literal["html", "pdf"] = Field(
32
+ "pdf",
33
+ description="Tipo de salida deseada. En estos endpoints se usa como referencia.",
34
+ )
35
+
36
+
37
+ @app.get("/health")
38
+ def health_check():
39
+ """
40
+ Endpoint simple de healthcheck para monitoreo.
41
+ """
42
+ return {"status": "ok"}
43
+
44
+
45
+ @app.post("/compile/html")
46
+ def compile_html(req: CompileRequest):
47
+ """
48
+ Recibe JSON y devuelve el HTML renderizado (煤til para depuraci贸n o previsualizaci贸n).
49
+ """
50
+ if not req.doc:
51
+ raise HTTPException(status_code=400, detail="Campo 'doc' es obligatorio")
52
+
53
+ try:
54
+ html = render_html(req.doc)
55
+ except Exception as exc:
56
+ raise HTTPException(status_code=500, detail=f"Error al renderizar HTML: {exc}")
57
+
58
+ return HTMLResponse(content=html)
59
+
60
+
61
+ @app.post("/compile/pdf")
62
+ def compile_pdf(req: CompileRequest):
63
+ """
64
+ Recibe JSON y devuelve el PDF compilado usando wkhtmltopdf.
65
+ """
66
+ if not req.doc:
67
+ raise HTTPException(status_code=400, detail="Campo 'doc' es obligatorio")
68
+
69
+ job_id = req.job_id or "document"
70
+
71
+ try:
72
+ pdf_bytes = render_pdf_bytes(req.doc)
73
+ except RuntimeError as exc:
74
+ raise HTTPException(status_code=500, detail=str(exc))
75
+ except Exception as exc:
76
+ raise HTTPException(status_code=500, detail=f"Error al generar PDF: {exc}")
77
+
78
+ filename = f"{job_id}.pdf"
79
+
80
+ return StreamingResponse(
81
+ io.BytesIO(pdf_bytes),
82
+ media_type="application/pdf",
83
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
84
+ )