isis-report-lib 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- isis_report_lib/__init__.py +40 -0
- isis_report_lib/api.py +106 -0
- isis_report_lib/formatting.py +28 -0
- isis_report_lib/layout.py +128 -0
- isis_report_lib/models.py +22 -0
- isis_report_lib/pdf.py +160 -0
- isis_report_lib/rendering.py +49 -0
- isis_report_lib/service.py +92 -0
- isis_report_lib/templates/relatorio_base.jinja +213 -0
- isis_report_lib/templates/relatorio_tabular.jinja +11 -0
- isis_report_lib/templates/relatorio_tabular_sections.jinja +68 -0
- isis_report_lib/toon.py +174 -0
- isis_report_lib-0.1.0.dist-info/METADATA +139 -0
- isis_report_lib-0.1.0.dist-info/RECORD +16 -0
- isis_report_lib-0.1.0.dist-info/WHEEL +4 -0
- isis_report_lib-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""isis_report_lib — gere PDFs tabulares a partir de dict ou texto `.toon`."""
|
|
2
|
+
|
|
3
|
+
from isis_report_lib.api import (
|
|
4
|
+
agenerate_pdf,
|
|
5
|
+
agenerate_pdf_from_toon,
|
|
6
|
+
arender_html,
|
|
7
|
+
generate_pdf,
|
|
8
|
+
generate_pdf_from_toon,
|
|
9
|
+
render_html,
|
|
10
|
+
render_html_from_toon,
|
|
11
|
+
)
|
|
12
|
+
from isis_report_lib.formatting import format_value
|
|
13
|
+
from isis_report_lib.layout import convert_data, convert_layout, infer_layout, is_template_format
|
|
14
|
+
from isis_report_lib.models import MetaInfo, ReportPayload
|
|
15
|
+
from isis_report_lib.service import BaseReportService, TabularReportService
|
|
16
|
+
from isis_report_lib.toon import ToonParser, parse_toon
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"MetaInfo",
|
|
22
|
+
"ReportPayload",
|
|
23
|
+
"ToonParser",
|
|
24
|
+
"parse_toon",
|
|
25
|
+
"format_value",
|
|
26
|
+
"convert_layout",
|
|
27
|
+
"convert_data",
|
|
28
|
+
"infer_layout",
|
|
29
|
+
"is_template_format",
|
|
30
|
+
"BaseReportService",
|
|
31
|
+
"TabularReportService",
|
|
32
|
+
"agenerate_pdf",
|
|
33
|
+
"generate_pdf",
|
|
34
|
+
"agenerate_pdf_from_toon",
|
|
35
|
+
"generate_pdf_from_toon",
|
|
36
|
+
"arender_html",
|
|
37
|
+
"render_html",
|
|
38
|
+
"render_html_from_toon",
|
|
39
|
+
"__version__",
|
|
40
|
+
]
|
isis_report_lib/api.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""API pública da lib (sync + async)."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from isis_report_lib.models import ReportPayload
|
|
7
|
+
from isis_report_lib.service import TabularReportService
|
|
8
|
+
from isis_report_lib.toon import parse_toon
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _normalize_payload(payload: dict[str, Any] | ReportPayload) -> dict[str, Any]:
|
|
12
|
+
if isinstance(payload, ReportPayload):
|
|
13
|
+
return payload.model_dump()
|
|
14
|
+
return dict(payload)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _run(coro):
|
|
18
|
+
"""Executa a coroutine e encerra o browser do loop efêmero (evita vazar Chromium).
|
|
19
|
+
|
|
20
|
+
A API async reutiliza o pool entre chamadas; a sync abre/fecha por chamada.
|
|
21
|
+
"""
|
|
22
|
+
from isis_report_lib.pdf import close_owned_browser
|
|
23
|
+
|
|
24
|
+
async def _scoped():
|
|
25
|
+
try:
|
|
26
|
+
return await coro
|
|
27
|
+
finally:
|
|
28
|
+
await close_owned_browser()
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
asyncio.get_running_loop()
|
|
32
|
+
except RuntimeError:
|
|
33
|
+
return asyncio.run(_scoped())
|
|
34
|
+
# Há um loop ativo (ex.: Jupyter): executa em thread separada p/ não travar.
|
|
35
|
+
import concurrent.futures
|
|
36
|
+
|
|
37
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
|
38
|
+
return pool.submit(lambda: asyncio.run(_scoped())).result()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def agenerate_pdf(
|
|
42
|
+
payload: dict[str, Any] | ReportPayload,
|
|
43
|
+
pdf_options: dict[str, Any] | None = None,
|
|
44
|
+
) -> bytes:
|
|
45
|
+
"""Gera PDF (async) a partir de payload dict/ReportPayload."""
|
|
46
|
+
service = TabularReportService(pdf_options=pdf_options)
|
|
47
|
+
return await service.execute(_normalize_payload(payload))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def generate_pdf(
|
|
51
|
+
payload: dict[str, Any] | ReportPayload,
|
|
52
|
+
pdf_options: dict[str, Any] | None = None,
|
|
53
|
+
) -> bytes:
|
|
54
|
+
"""Gera PDF (sync) a partir de payload dict/ReportPayload."""
|
|
55
|
+
return _run(agenerate_pdf(payload, pdf_options))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def agenerate_pdf_from_toon(
|
|
59
|
+
text: str,
|
|
60
|
+
pdf_options: dict[str, Any] | None = None,
|
|
61
|
+
) -> bytes:
|
|
62
|
+
"""Gera PDF (async) a partir de texto `.toon`."""
|
|
63
|
+
return await agenerate_pdf(parse_toon(text), pdf_options)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def generate_pdf_from_toon(
|
|
67
|
+
text: str,
|
|
68
|
+
pdf_options: dict[str, Any] | None = None,
|
|
69
|
+
) -> bytes:
|
|
70
|
+
"""Gera PDF (sync) a partir de texto `.toon`."""
|
|
71
|
+
return _run(agenerate_pdf_from_toon(text, pdf_options))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
async def arender_html(payload: dict[str, Any] | ReportPayload) -> str:
|
|
75
|
+
"""Renderiza só o HTML intermediário (async, sem Playwright)."""
|
|
76
|
+
from isis_report_lib.layout import convert_data, convert_layout, infer_layout
|
|
77
|
+
|
|
78
|
+
data = _normalize_payload(payload)
|
|
79
|
+
raw = data.get("data", [])
|
|
80
|
+
layout_raw = data.get("layout")
|
|
81
|
+
meta = data.get("meta", {})
|
|
82
|
+
if layout_raw:
|
|
83
|
+
layout = convert_layout(layout_raw)
|
|
84
|
+
ds_items = convert_data(raw, layout_raw)
|
|
85
|
+
else:
|
|
86
|
+
from isis_report_lib.layout import is_template_format
|
|
87
|
+
|
|
88
|
+
layout = infer_layout(raw)
|
|
89
|
+
if is_template_format(raw):
|
|
90
|
+
ds_items = {"groups": raw}
|
|
91
|
+
else:
|
|
92
|
+
ds_items = {"groups": [{"fields": r} if isinstance(r, dict) else {"fields": {"value": r}} for r in raw]}
|
|
93
|
+
|
|
94
|
+
from isis_report_lib.rendering import arender_report_html
|
|
95
|
+
|
|
96
|
+
return await arender_report_html(ds_items=ds_items, layout=layout, meta=meta)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def render_html(payload: dict[str, Any] | ReportPayload) -> str:
|
|
100
|
+
"""Renderiza só o HTML intermediário (sync, sem Playwright)."""
|
|
101
|
+
return _run(arender_html(payload))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def render_html_from_toon(text: str) -> str:
|
|
105
|
+
"""Renderiza HTML (sync) a partir de texto `.toon`."""
|
|
106
|
+
return render_html(parse_toon(text))
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Formatação de valores exibidos nos templates (máscaras int/float/date/str)."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def format_value(value: Any, format_mask: str) -> str:
|
|
7
|
+
"""Formata um valor conforme a máscara do layout.
|
|
8
|
+
|
|
9
|
+
- ``int``: milhar com ponto (``1234`` -> ``"1.234"``)
|
|
10
|
+
- ``float``: padrão pt-BR com 2 casas (``1234.5`` -> ``"1.234,50"``)
|
|
11
|
+
- ``date``: repassa como string
|
|
12
|
+
- demais: ``str(value)``; ``None`` -> ``""``
|
|
13
|
+
"""
|
|
14
|
+
if value is None:
|
|
15
|
+
return ""
|
|
16
|
+
if format_mask == "int":
|
|
17
|
+
try:
|
|
18
|
+
return f"{int(value):,}".replace(",", ".")
|
|
19
|
+
except (ValueError, TypeError):
|
|
20
|
+
return str(value)
|
|
21
|
+
if format_mask == "float":
|
|
22
|
+
try:
|
|
23
|
+
return f"{float(value):,.2f}".replace(",", "X").replace(".", ",").replace("X", ".")
|
|
24
|
+
except (ValueError, TypeError):
|
|
25
|
+
return str(value)
|
|
26
|
+
if format_mask == "date":
|
|
27
|
+
return str(value)
|
|
28
|
+
return str(value)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Conversão de layout hierárquico e de dados para o formato dos templates.
|
|
2
|
+
|
|
3
|
+
O layout de entrada é o formato "cru" do POC::
|
|
4
|
+
|
|
5
|
+
{
|
|
6
|
+
"empresa": {"label": "Empresa", "format_mask": "str", "alignment": "left"},
|
|
7
|
+
"pedidos": {
|
|
8
|
+
"pedido": {"label": "Código", "format_mask": "int", "alignment": "right"},
|
|
9
|
+
"cargas": {
|
|
10
|
+
"qtde": {"label": "Quantidade", "format_mask": "int", "alignment": "right"},
|
|
11
|
+
},
|
|
12
|
+
},
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
Chaves cujo valor é um dict **sem** ``label`` são tratadas como grupos aninhados.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def format_field(name: str, field_def: dict[str, Any]) -> dict[str, Any]:
|
|
22
|
+
"""Normaliza a definição de um campo com defaults (label=str, left)."""
|
|
23
|
+
return {
|
|
24
|
+
"name": name,
|
|
25
|
+
"label": field_def.get("label", name),
|
|
26
|
+
"format_mask": field_def.get("format_mask", "str"),
|
|
27
|
+
"alignment": field_def.get("alignment", "left"),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def convert_layout(layout_raw: dict[str, Any]) -> dict[str, Any]:
|
|
32
|
+
"""Converte o layout hierárquico para o formato pronto p/ renderização."""
|
|
33
|
+
header: list[dict[str, Any]] = []
|
|
34
|
+
groups: dict[str, Any] | None = None
|
|
35
|
+
|
|
36
|
+
for key, value in layout_raw.items():
|
|
37
|
+
if isinstance(value, dict) and "label" in value:
|
|
38
|
+
header.append(format_field(key, value))
|
|
39
|
+
elif isinstance(value, dict):
|
|
40
|
+
field_header: list[dict[str, Any]] = []
|
|
41
|
+
detail: list[dict[str, Any]] = []
|
|
42
|
+
for sub_key, sub_value in value.items():
|
|
43
|
+
if isinstance(sub_value, dict) and "label" in sub_value:
|
|
44
|
+
field_header.append(format_field(sub_key, sub_value))
|
|
45
|
+
elif isinstance(sub_value, dict):
|
|
46
|
+
for inner_key, inner_value in sub_value.items():
|
|
47
|
+
if isinstance(inner_value, dict) and "label" in inner_value:
|
|
48
|
+
detail.append(format_field(inner_key, inner_value))
|
|
49
|
+
if groups is None:
|
|
50
|
+
groups = {}
|
|
51
|
+
groups["header"] = field_header
|
|
52
|
+
if detail:
|
|
53
|
+
groups["detail"] = detail
|
|
54
|
+
|
|
55
|
+
result: dict[str, Any] = {"groups": {"header": header}}
|
|
56
|
+
if groups:
|
|
57
|
+
result["groups"]["groups"] = groups
|
|
58
|
+
return result
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def is_template_format(data: list[Any]) -> bool:
|
|
62
|
+
"""True se os dados já estão no formato do template (itens com ``fields``)."""
|
|
63
|
+
return bool(data and isinstance(data[0], dict) and "fields" in data[0])
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def convert_data(data_raw: list[dict[str, Any]], layout_raw: dict[str, Any]) -> dict[str, Any]:
|
|
67
|
+
"""Converte dados crus + layout cru para ``{"groups": [...]}`` do template."""
|
|
68
|
+
if is_template_format(data_raw):
|
|
69
|
+
return {"groups": data_raw}
|
|
70
|
+
|
|
71
|
+
group_keys: dict[str, Any] = {}
|
|
72
|
+
for k, v in layout_raw.items():
|
|
73
|
+
if isinstance(v, dict) and "label" not in v:
|
|
74
|
+
group_keys[k] = v
|
|
75
|
+
|
|
76
|
+
items: list[dict[str, Any]] = []
|
|
77
|
+
for record in data_raw:
|
|
78
|
+
fields: dict[str, Any] = {}
|
|
79
|
+
groups: list[dict[str, Any]] = []
|
|
80
|
+
|
|
81
|
+
for key, value in record.items():
|
|
82
|
+
if key in group_keys:
|
|
83
|
+
sub_layout = group_keys[key]
|
|
84
|
+
detail_key = next(
|
|
85
|
+
(sk for sk, sv in sub_layout.items() if isinstance(sv, dict) and "label" not in sv),
|
|
86
|
+
None,
|
|
87
|
+
)
|
|
88
|
+
for sub_item in value:
|
|
89
|
+
sub_fields = {sk: sub_item[sk] for sk in sub_layout if sk != detail_key and sk in sub_item}
|
|
90
|
+
detail = sub_item.get(detail_key, []) if detail_key else []
|
|
91
|
+
group_entry: dict[str, Any] = {"fields": sub_fields}
|
|
92
|
+
if detail:
|
|
93
|
+
group_entry["detail"] = detail
|
|
94
|
+
groups.append(group_entry)
|
|
95
|
+
else:
|
|
96
|
+
fields[key] = value
|
|
97
|
+
|
|
98
|
+
item: dict[str, Any] = {"fields": fields}
|
|
99
|
+
if groups:
|
|
100
|
+
item["groups"] = groups
|
|
101
|
+
items.append(item)
|
|
102
|
+
|
|
103
|
+
return {"groups": items}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def infer_layout(data: list[dict[str, Any]]) -> dict[str, Any]:
|
|
107
|
+
"""Infere um layout simples (só header) a partir da primeira linha de dados."""
|
|
108
|
+
if not data:
|
|
109
|
+
return {"groups": {"header": []}}
|
|
110
|
+
|
|
111
|
+
sample = data[0] if isinstance(data[0], dict) else {}
|
|
112
|
+
header: list[dict[str, Any]] = []
|
|
113
|
+
for key, value in sample.items():
|
|
114
|
+
if isinstance(value, list):
|
|
115
|
+
continue
|
|
116
|
+
dtype = "str"
|
|
117
|
+
alignment = "left"
|
|
118
|
+
if isinstance(value, bool):
|
|
119
|
+
dtype = "str"
|
|
120
|
+
elif isinstance(value, int):
|
|
121
|
+
dtype = "int"
|
|
122
|
+
alignment = "right"
|
|
123
|
+
elif isinstance(value, float):
|
|
124
|
+
dtype = "float"
|
|
125
|
+
alignment = "right"
|
|
126
|
+
header.append({"name": key, "label": key.replace("_", " ").title(), "format_mask": dtype, "alignment": alignment})
|
|
127
|
+
|
|
128
|
+
return {"groups": {"header": header}}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Modelos de dados da lib (extraídos do POC isis_report)."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MetaInfo(BaseModel):
|
|
9
|
+
"""Metadados do relatório."""
|
|
10
|
+
|
|
11
|
+
title: str
|
|
12
|
+
sub_title: str | None = None
|
|
13
|
+
company: str | None = None
|
|
14
|
+
mode: str = "exact"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ReportPayload(BaseModel):
|
|
18
|
+
"""Payload de relatório: metadados + layout hierárquico opcional + dados."""
|
|
19
|
+
|
|
20
|
+
meta: MetaInfo
|
|
21
|
+
layout: dict[str, Any] | None = None
|
|
22
|
+
data: list[Any] = Field(default_factory=list)
|
isis_report_lib/pdf.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Pool singleton de browser Playwright (extraído do POC isis_report).
|
|
2
|
+
|
|
3
|
+
Reuso do Chromium entre gerações; chame :func:`close_browser` ao encerrar
|
|
4
|
+
testes/scripts longos.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import logging
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from playwright.async_api import Browser, Playwright, async_playwright
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger("isis_report_lib")
|
|
14
|
+
|
|
15
|
+
_playwright_ctx = None
|
|
16
|
+
_playwright: Playwright | None = None
|
|
17
|
+
_browser: Browser | None = None
|
|
18
|
+
_owner_loop: asyncio.AbstractEventLoop | None = None
|
|
19
|
+
_lock = asyncio.Lock()
|
|
20
|
+
|
|
21
|
+
DEFAULT_FOOTER = (
|
|
22
|
+
'<div style="width:100%;text-align:center;font-size:10px;">'
|
|
23
|
+
"Página <span class='pageNumber'></span> de <span class='totalPages'></span></div>"
|
|
24
|
+
)
|
|
25
|
+
DEFAULT_MARGIN = {"top": ".2in", "bottom": ".5in", "left": ".2in", "right": ".2in"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _browser_usable() -> bool:
|
|
29
|
+
"""True se o browser existe, pertence ao loop atual e está conectado."""
|
|
30
|
+
if _browser is None:
|
|
31
|
+
return False
|
|
32
|
+
try:
|
|
33
|
+
running = asyncio.get_running_loop()
|
|
34
|
+
except RuntimeError:
|
|
35
|
+
return False
|
|
36
|
+
if _owner_loop is not running:
|
|
37
|
+
return False
|
|
38
|
+
try:
|
|
39
|
+
return _browser.is_connected()
|
|
40
|
+
except Exception:
|
|
41
|
+
return False
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def _reset_unlocked() -> None:
|
|
45
|
+
"""Fecha e limpa o browser/Playwright sem adquirir o lock (chamador já o detém).
|
|
46
|
+
|
|
47
|
+
Regra crítica: nunca se dá ``await`` em objetos de outro event loop (pode
|
|
48
|
+
bloquear para sempre no Linux, mesmo com ``wait_for``). Estado de loop
|
|
49
|
+
alheio/encerrado é apenas abandonado; o caso mesmo-loop fecha com timeout.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
async def _close_quietly(coro, label: str) -> None:
|
|
53
|
+
try:
|
|
54
|
+
await asyncio.wait_for(coro, timeout=10)
|
|
55
|
+
except Exception:
|
|
56
|
+
logger.warning("Falha ao fechar %s durante reset do pool; abandonando.", label)
|
|
57
|
+
|
|
58
|
+
global _playwright_ctx, _playwright, _browser, _owner_loop
|
|
59
|
+
try:
|
|
60
|
+
running = asyncio.get_running_loop()
|
|
61
|
+
except RuntimeError:
|
|
62
|
+
running = None
|
|
63
|
+
same_loop = running is not None and _owner_loop is running
|
|
64
|
+
|
|
65
|
+
if _browser is not None:
|
|
66
|
+
if same_loop:
|
|
67
|
+
await _close_quietly(_browser.close(), "browser")
|
|
68
|
+
else:
|
|
69
|
+
logger.warning("Abandonando browser de outro event loop sem fechar (evita deadlock).")
|
|
70
|
+
_browser = None
|
|
71
|
+
if _playwright_ctx is not None:
|
|
72
|
+
if same_loop:
|
|
73
|
+
await _close_quietly(_playwright_ctx.__aexit__(None, None, None), "playwright")
|
|
74
|
+
_playwright_ctx = None
|
|
75
|
+
_playwright = None
|
|
76
|
+
_owner_loop = None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
async def ensure_browser(headless: bool = True) -> None:
|
|
80
|
+
"""Garante o browser compartilhado iniciado (idempotente).
|
|
81
|
+
|
|
82
|
+
Se o browser pertence a um event loop diferente/encerrado (ex.: suítes
|
|
83
|
+
de teste que criam um loop por teste), ele é recriado no loop atual.
|
|
84
|
+
"""
|
|
85
|
+
global _playwright_ctx, _playwright, _browser, _owner_loop
|
|
86
|
+
async with _lock:
|
|
87
|
+
if _browser_usable():
|
|
88
|
+
return
|
|
89
|
+
await _reset_unlocked()
|
|
90
|
+
_playwright_ctx = async_playwright()
|
|
91
|
+
_playwright = await _playwright_ctx.__aenter__()
|
|
92
|
+
_browser = await _playwright.chromium.launch(headless=headless)
|
|
93
|
+
_owner_loop = asyncio.get_running_loop()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
_ensure_browser = ensure_browser # alias p/ compatibilidade com o POC
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def ensure_browser_sync(headless: bool = True) -> None:
|
|
100
|
+
"""Garante o browser de forma síncrona (agenda task se houver loop ativo)."""
|
|
101
|
+
if _browser is not None:
|
|
102
|
+
return
|
|
103
|
+
try:
|
|
104
|
+
loop = asyncio.get_event_loop()
|
|
105
|
+
if loop.is_running():
|
|
106
|
+
loop.create_task(ensure_browser(headless=headless))
|
|
107
|
+
else:
|
|
108
|
+
loop.run_until_complete(ensure_browser(headless=headless))
|
|
109
|
+
except RuntimeError:
|
|
110
|
+
asyncio.run(ensure_browser(headless=headless))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
async def new_page():
|
|
114
|
+
"""Retorna uma nova Page do browser compartilhado (feche com ``await page.close()``)."""
|
|
115
|
+
await _ensure_browser()
|
|
116
|
+
assert _browser is not None
|
|
117
|
+
return await _browser.new_page()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def get_pdf_from_html(html: str, **kwargs: Any) -> bytes:
|
|
121
|
+
"""Renderiza HTML em PDF via browser compartilhado.
|
|
122
|
+
|
|
123
|
+
kwargs aceitos: ``format`` (default ``"A4"``), ``display_header_footer``,
|
|
124
|
+
``header_template``, ``footer_template``, ``margin``.
|
|
125
|
+
"""
|
|
126
|
+
page = await new_page()
|
|
127
|
+
try:
|
|
128
|
+
await page.set_content(html)
|
|
129
|
+
return await page.pdf(
|
|
130
|
+
format=kwargs.get("format", "A4"),
|
|
131
|
+
display_header_footer=kwargs.get("display_header_footer", True),
|
|
132
|
+
header_template=kwargs.get("header_template", ""),
|
|
133
|
+
footer_template=kwargs.get("footer_template", DEFAULT_FOOTER),
|
|
134
|
+
margin=kwargs.get("margin", DEFAULT_MARGIN),
|
|
135
|
+
)
|
|
136
|
+
finally:
|
|
137
|
+
await page.close()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
async def close_browser() -> None:
|
|
141
|
+
"""Fecha o browser compartilhado e encerra o Playwright."""
|
|
142
|
+
global _playwright_ctx, _playwright, _browser, _owner_loop
|
|
143
|
+
async with _lock:
|
|
144
|
+
await _reset_unlocked()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
async def close_owned_browser() -> None:
|
|
148
|
+
"""Fecha o browser somente se pertencer ao loop atual.
|
|
149
|
+
|
|
150
|
+
Uso interno da API síncrona: cada ``generate_pdf`` roda em um loop
|
|
151
|
+
efêmero (``asyncio.run``), então o browser deve ser encerrado ao final
|
|
152
|
+
da chamada para não vazar processos Chromium. Nunca toca em browser
|
|
153
|
+
de outro loop (a API async mantém o pool reutilizável).
|
|
154
|
+
"""
|
|
155
|
+
try:
|
|
156
|
+
running = asyncio.get_running_loop()
|
|
157
|
+
except RuntimeError:
|
|
158
|
+
return
|
|
159
|
+
if _owner_loop is not None and _owner_loop is running:
|
|
160
|
+
await close_browser()
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Renderização Jinja2 com templates embutidos no pacote."""
|
|
2
|
+
|
|
3
|
+
from importlib import resources
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from jinja2 import Environment, FileSystemLoader
|
|
7
|
+
|
|
8
|
+
_env: Environment | None = None
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _templates_dir() -> str:
|
|
12
|
+
# importlib.resources.files funciona com pacote instalado (wheel/sdist)
|
|
13
|
+
return str(resources.files("isis_report_lib") / "templates")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def get_jinja_env() -> Environment:
|
|
17
|
+
"""Retorna (singleton) o Environment Jinja2 apontando p/ os templates do pacote."""
|
|
18
|
+
global _env
|
|
19
|
+
if _env is None:
|
|
20
|
+
_env = Environment(loader=FileSystemLoader(searchpath=_templates_dir()), autoescape=False)
|
|
21
|
+
return _env
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
async def arender_report_html(
|
|
25
|
+
ds_items: dict[str, Any],
|
|
26
|
+
layout: dict[str, Any],
|
|
27
|
+
meta: dict[str, Any],
|
|
28
|
+
template_name: str = "relatorio_tabular.jinja",
|
|
29
|
+
) -> str:
|
|
30
|
+
"""Renderiza o HTML do relatório (async p/ compatibilidade; Jinja é síncrono)."""
|
|
31
|
+
from isis_report_lib.formatting import format_value
|
|
32
|
+
|
|
33
|
+
env = get_jinja_env()
|
|
34
|
+
template = env.get_template(template_name)
|
|
35
|
+
return template.render(ds_items=ds_items, layout=layout, meta=meta, fmt=format_value, zip=zip)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def render_report_html(
|
|
39
|
+
ds_items: dict[str, Any],
|
|
40
|
+
layout: dict[str, Any],
|
|
41
|
+
meta: dict[str, Any],
|
|
42
|
+
template_name: str = "relatorio_tabular.jinja",
|
|
43
|
+
) -> str:
|
|
44
|
+
"""Versão síncrona da renderização do HTML."""
|
|
45
|
+
from isis_report_lib.formatting import format_value
|
|
46
|
+
|
|
47
|
+
env = get_jinja_env()
|
|
48
|
+
template = env.get_template(template_name)
|
|
49
|
+
return template.render(ds_items=ds_items, layout=layout, meta=meta, fmt=format_value, zip=zip)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Pipeline de geração de relatório: Obter -> Tratar -> HTML -> PDF.
|
|
2
|
+
|
|
3
|
+
Equivalente ao ``BaseReportService`` + ``SharedReportService`` do POC,
|
|
4
|
+
sem dependência do Robyn.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from abc import ABC, abstractmethod
|
|
9
|
+
from typing import Any, final
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger("isis_report_lib")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class BaseReportService(ABC):
|
|
15
|
+
"""Define o ciclo de vida de geração; ``execute`` garante a ordem."""
|
|
16
|
+
|
|
17
|
+
@final
|
|
18
|
+
async def execute(self, payload: dict[str, Any]) -> bytes:
|
|
19
|
+
service_name = self.__class__.__name__
|
|
20
|
+
try:
|
|
21
|
+
logger.info("Iniciando processamento do relatório: %s", service_name)
|
|
22
|
+
raw_data = await self._obter_dados(payload)
|
|
23
|
+
processed_data = await self._tratar_dados(raw_data, payload)
|
|
24
|
+
html_content = await self._gerar_html(processed_data, payload)
|
|
25
|
+
pdf_bytes = await self._gerar_pdf(html_content)
|
|
26
|
+
logger.info("Relatório %s gerado com sucesso.", service_name)
|
|
27
|
+
return pdf_bytes
|
|
28
|
+
except Exception:
|
|
29
|
+
logger.exception("Falha no pipeline do serviço %s", service_name)
|
|
30
|
+
raise
|
|
31
|
+
|
|
32
|
+
@abstractmethod
|
|
33
|
+
async def _obter_dados(self, payload: dict[str, Any]) -> Any:
|
|
34
|
+
"""Recupera dados brutos do payload."""
|
|
35
|
+
|
|
36
|
+
@abstractmethod
|
|
37
|
+
async def _tratar_dados(self, data: Any, payload: dict[str, Any]) -> Any:
|
|
38
|
+
"""Aplica layout/conversão de dados."""
|
|
39
|
+
|
|
40
|
+
@abstractmethod
|
|
41
|
+
async def _gerar_html(self, data: Any, payload: dict[str, Any]) -> str:
|
|
42
|
+
"""Renderiza o template Jinja2."""
|
|
43
|
+
|
|
44
|
+
@abstractmethod
|
|
45
|
+
async def _gerar_pdf(self, html: str) -> bytes:
|
|
46
|
+
"""Converte HTML em PDF."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class TabularReportService(BaseReportService):
|
|
50
|
+
"""Implementação tabular padrão (equivale ao SharedReportService do POC)."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, pdf_options: dict[str, Any] | None = None) -> None:
|
|
53
|
+
from isis_report_lib import pdf as _pdf
|
|
54
|
+
|
|
55
|
+
self._pdf_options = pdf_options or {}
|
|
56
|
+
self._pdf_module = _pdf
|
|
57
|
+
|
|
58
|
+
async def _obter_dados(self, payload: dict[str, Any]) -> Any:
|
|
59
|
+
return payload.get("data", [])
|
|
60
|
+
|
|
61
|
+
async def _tratar_dados(self, data: Any, payload: dict[str, Any]) -> dict[str, Any]:
|
|
62
|
+
from isis_report_lib.layout import convert_data, convert_layout, infer_layout, is_template_format
|
|
63
|
+
|
|
64
|
+
meta = payload.get("meta", {})
|
|
65
|
+
layout_raw = payload.get("layout")
|
|
66
|
+
|
|
67
|
+
if layout_raw:
|
|
68
|
+
layout = convert_layout(layout_raw)
|
|
69
|
+
ds_items = convert_data(data, layout_raw)
|
|
70
|
+
else:
|
|
71
|
+
layout = infer_layout(data)
|
|
72
|
+
# O template itera `data.fields`: embrulha registros crus.
|
|
73
|
+
if is_template_format(data):
|
|
74
|
+
ds_items = {"groups": data}
|
|
75
|
+
else:
|
|
76
|
+
ds_items = {"groups": [{"fields": r} if isinstance(r, dict) else {"fields": {"value": r}} for r in data]}
|
|
77
|
+
|
|
78
|
+
void = is_template_format # mantém referência p/ paridade com o POC
|
|
79
|
+
_ = void
|
|
80
|
+
return {"ds_items": ds_items, "layout": layout, "meta": meta}
|
|
81
|
+
|
|
82
|
+
async def _gerar_html(self, data: dict[str, Any], payload: dict[str, Any]) -> str:
|
|
83
|
+
from isis_report_lib.rendering import arender_report_html
|
|
84
|
+
|
|
85
|
+
return await arender_report_html(
|
|
86
|
+
ds_items=data["ds_items"],
|
|
87
|
+
layout=data["layout"],
|
|
88
|
+
meta=data["meta"],
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
async def _gerar_pdf(self, html: str) -> bytes:
|
|
92
|
+
return await self._pdf_module.get_pdf_from_html(html, **self._pdf_options)
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
|
|
5
|
+
<title>Isis Report</title>
|
|
6
|
+
<style>
|
|
7
|
+
:root {
|
|
8
|
+
--cor-client: #0A2F46;
|
|
9
|
+
--light-strips: #f2f2f2;
|
|
10
|
+
--light-white: #f1f1f1;
|
|
11
|
+
--contraste-cabecalho: #f1f1f1;
|
|
12
|
+
--font-customizada: sans-serif, Arial, Helvetica;
|
|
13
|
+
/* Orientação para impressão: auto || portrait || landscape */
|
|
14
|
+
--orientacao: portrait;
|
|
15
|
+
--margem-impressao: .25in .2in;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
* {
|
|
19
|
+
-webkit-print-color-adjust: {% block mode %} {% endblock %};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
body {
|
|
23
|
+
font-family: var(--font-customizada, sans-serif);
|
|
24
|
+
margin: 0;
|
|
25
|
+
padding: 0;
|
|
26
|
+
color: #3b4151;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
.container {
|
|
30
|
+
margin: 0 3rem 0;
|
|
31
|
+
padding: 1.2rem;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
h1 {
|
|
35
|
+
color: #333;
|
|
36
|
+
font-family: var(--font-customizada, sans-serif);
|
|
37
|
+
font-size: 1.8rem;
|
|
38
|
+
margin-bottom: 0;
|
|
39
|
+
margin-top: 0;
|
|
40
|
+
padding-inline: .5rem;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
h2 {
|
|
44
|
+
font-family: var(--font-customizada, sans-serif);
|
|
45
|
+
font-size: 1.3rem;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
h3 {
|
|
49
|
+
font-family: var(--font-customizada, sans-serif);
|
|
50
|
+
font-size: .9rem;
|
|
51
|
+
font-weight: 300;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
.icon-area {
|
|
55
|
+
display: flex;
|
|
56
|
+
align-items: center;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
.icon-area svg, .icon-area img{
|
|
60
|
+
width: 64px;
|
|
61
|
+
height: 64px;
|
|
62
|
+
padding-inline: .5rem;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
p, th, td {
|
|
66
|
+
font-family: var(--font-customizada, sans-serif);
|
|
67
|
+
font-size: 14px;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
p {
|
|
71
|
+
padding-inline: .45rem;
|
|
72
|
+
margin-block: .5em;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
.relatorio {
|
|
76
|
+
margin-block: .5rem;
|
|
77
|
+
border: 1px solid var(--light-white, #f1f1f1);
|
|
78
|
+
border-radius: 6px;
|
|
79
|
+
width: 100%;
|
|
80
|
+
border-spacing: 0;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
.header-table {
|
|
84
|
+
display: flex;
|
|
85
|
+
align-items: center;
|
|
86
|
+
justify-content: space-between;
|
|
87
|
+
margin-inline: .5rem;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
.header-table h2 {
|
|
91
|
+
font-weight: 600;
|
|
92
|
+
text-align: center;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
.periodo h3 {
|
|
96
|
+
text-align: center;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
.relatorio thead th:first-child {
|
|
100
|
+
border-radius: 4px 0 0 0;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
.relatorio thead th:last-child {
|
|
104
|
+
border-radius: 0 4px 0 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
.relatorio thead th {
|
|
108
|
+
background-color: var(--cor-client, #0A2F46);
|
|
109
|
+
padding: .9rem;
|
|
110
|
+
color: var(--contraste-cabecalho ,#f1f1f1);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
.relatorio tbody tr:nth-child(even) {
|
|
114
|
+
background-color: var(--light-strips, #f2f2f2);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
td {
|
|
118
|
+
border-bottom: 1px solid var(--light-white, #f1f1f1);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
.table-footer {
|
|
122
|
+
display: flex;
|
|
123
|
+
align-items: center;
|
|
124
|
+
justify-content: space-between;
|
|
125
|
+
padding: .5rem 1rem;
|
|
126
|
+
background-color: #fff;
|
|
127
|
+
margin-top: 1rem;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
.table-footer svg {
|
|
131
|
+
width: 7rem;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
.table-footer .data {
|
|
135
|
+
font-size: .8rem;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
.group-header-0, .group-footer-0,
|
|
139
|
+
.group-header-1, .group-footer-1, .summary {
|
|
140
|
+
padding: 0.5rem 1rem;
|
|
141
|
+
border-radius: 4px;
|
|
142
|
+
display: flex;
|
|
143
|
+
flex-wrap: wrap;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
.group-header-0, .group-footer-0, .summary {
|
|
147
|
+
background-color: var(--contraste-cabecalho, #f1f1f1);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
.summary {
|
|
151
|
+
border: 1px solid #d1d1d1;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
.group-header-1, .group-footer-1 {
|
|
155
|
+
border: 1px solid var(--contraste-cabecalho, #f1f1f1);
|
|
156
|
+
margin-block: .5rem;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
.group-header-1 .content, .group-footer-1 .content,
|
|
160
|
+
.group-header-0 .content, .group-footer-0 .content,
|
|
161
|
+
.summary .content {
|
|
162
|
+
padding-block: 0.2rem;
|
|
163
|
+
margin-inline-end: 1rem;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
.group-header-0 .content label, .group-footer-0 .content label,
|
|
167
|
+
.group-header-1 .content label, .group-footer-1 .content label,
|
|
168
|
+
.summary .content label {
|
|
169
|
+
font-weight: 300;
|
|
170
|
+
font-size: 0.9rem;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
.group-header-0 .content span, .group-footer-0 .content span,
|
|
175
|
+
.group-header-1 .content span, .group-footer-1 .content span,
|
|
176
|
+
.summary span {
|
|
177
|
+
font-weight: 600;
|
|
178
|
+
font-size: 1rem;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
.divisor-table {
|
|
182
|
+
margin-block-end: 1rem;
|
|
183
|
+
}
|
|
184
|
+
</style>
|
|
185
|
+
</head>
|
|
186
|
+
<body>
|
|
187
|
+
<main class="container">
|
|
188
|
+
<div class="icon-area">
|
|
189
|
+
<svg width="86" height="86" viewBox="0 0 86 86" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
190
|
+
<path d="M27.3331 25.9999C22.9331 27.8666 18.2665 29.3332 17.0665 29.3332C15.7332 29.3332 14.6665 30.2666 14.6665 31.4666C14.6665 33.9999 19.8665 33.0666 28.5331 29.1999C35.5998 25.9999 44.9331 25.9999 52.133 29.3332C55.733 30.9332 58.533 31.3332 59.1997 30.6666C60.7997 29.0666 60.7997 29.0666 52.3997 25.5999C43.4664 21.8666 37.1997 21.9999 27.3331 25.9999Z" fill="#0A2F46"/>
|
|
191
|
+
<path d="M64.7998 23.8666C62.9331 24.5333 62.6664 25.1999 63.7331 25.8666C64.9331 26.5332 62.9331 29.7332 57.3331 35.9999C50.3998 43.7332 48.7998 45.0665 46.7998 43.7332C44.9332 42.5332 43.1998 43.7332 36.2665 50.5332C28.7999 58.1331 27.5999 58.7998 23.0666 58.3998C18.7999 58.1331 17.8666 57.4665 17.5999 54.6665C17.1999 51.8665 17.3333 51.7332 19.1999 53.1998C21.3333 55.0665 25.3332 54.3998 25.3332 52.1331C25.3332 49.5998 21.3333 46.9332 18.5333 47.5998C15.0666 48.5332 13.3333 53.0665 14.9333 57.3331C16.5333 61.4664 18.2666 62.6664 23.4666 62.6664C27.7332 62.6664 35.3332 57.8665 41.1999 51.4665C44.1332 48.3998 44.6665 48.2665 46.6665 49.9998C48.6665 51.7331 49.7332 50.9332 58.1331 41.3332C63.1998 35.4665 68.2664 30.7999 69.3331 31.0666C70.6664 31.1999 71.4664 29.9999 71.7331 26.9332C72.1331 22.3999 70.3997 21.5999 64.7998 23.8666Z" fill="#0A2F46"/>
|
|
192
|
+
<path d="M27.9998 32.6666C23.9998 34.3999 19.3332 35.8666 17.7332 35.9999C13.7332 35.9999 13.5999 39.9999 17.4665 39.9999C19.0665 39.9999 23.8665 41.5999 28.1331 43.4665C33.0665 45.7332 36.7998 46.6665 38.2664 45.9999C40.2664 45.1999 40.2664 44.9332 38.6664 44.3999C37.5998 43.9999 33.9998 42.5332 30.6665 41.0665L24.6665 38.3999L29.9998 35.8666C35.3331 33.4666 35.3331 33.4666 35.9998 36.2666C37.0664 40.3999 40.6664 42.2665 43.1997 40.1332C44.3997 39.0665 45.3331 37.1999 45.3331 35.8666C45.3331 33.4666 45.5997 33.4666 49.8664 35.1999C54.133 36.9332 55.9997 36.7999 55.9997 34.5332C55.9997 32.7999 45.3331 29.3333 40.2664 29.3333C37.5998 29.4666 31.9998 30.9332 27.9998 32.6666ZM41.5998 36.2666C39.5998 38.2666 38.1331 36.7999 39.1998 33.8666C39.8664 32.1332 40.3998 31.8666 41.5998 33.0666C42.7997 34.2666 42.7997 35.0666 41.5998 36.2666ZM52.133 50.5332C49.3331 54.3998 48.2664 61.3331 50.3997 61.3331C51.5997 61.3331 60.533 50.6665 59.8663 50.2665C59.5997 49.9998 58.3997 49.1998 57.0664 48.2665C55.1997 46.7999 54.533 47.1999 52.133 50.5332Z" fill="#0A2F46"/>
|
|
193
|
+
</svg>
|
|
194
|
+
<h1>Isis Report</h1>
|
|
195
|
+
</div>
|
|
196
|
+
<hr class="divisor"/>
|
|
197
|
+
<div class="header-table">
|
|
198
|
+
<h2>{% block titulo %} {% endblock %}</h2>
|
|
199
|
+
<div class="periodo">
|
|
200
|
+
<h3>{% block filters %} {% endblock %}</h3>
|
|
201
|
+
</div>
|
|
202
|
+
</div>
|
|
203
|
+
{% block conteudo %} {% endblock %}
|
|
204
|
+
{% if type != "pdf" %}
|
|
205
|
+
<div class="table-footer">
|
|
206
|
+
<div class="data">
|
|
207
|
+
<span>{% block data_hora_impresssao %} {% endblock %}</span>
|
|
208
|
+
</div>
|
|
209
|
+
</div>
|
|
210
|
+
{% endif %}
|
|
211
|
+
</main>
|
|
212
|
+
</body>
|
|
213
|
+
</html>
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{% extends 'relatorio_base.jinja' %}
|
|
2
|
+
{% from 'relatorio_tabular_sections.jinja' import render_detail, render_group, render_divisor %}
|
|
3
|
+
{% block titulo %}{{meta.title}}{% endblock %}
|
|
4
|
+
{% block mode %}{{meta.mode}}{% endblock %}
|
|
5
|
+
{% block filters %}{{meta.sub_title}}{% endblock %}
|
|
6
|
+
{% block data_hora_impresssao %}{{meta.data_hora}}{% endblock %}
|
|
7
|
+
{% block conteudo %}
|
|
8
|
+
{% if ds_items.groups and layout.groups %}
|
|
9
|
+
{{render_group(ds_items.groups, layout.groups, zip, fmt, 0)}}
|
|
10
|
+
{% endif %}
|
|
11
|
+
{% endblock %}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
{% macro render_section_content(label, span) %}
|
|
2
|
+
<section class="content">
|
|
3
|
+
<label>{{label}}</label>
|
|
4
|
+
<span>{{span}}</span>
|
|
5
|
+
</section>
|
|
6
|
+
{% endmacro %}
|
|
7
|
+
{% macro render_section(section_class, ds, layout, zip, fmt) %}
|
|
8
|
+
<section class="{{section_class}}">
|
|
9
|
+
{% for data, field in zip(ds.items(), layout) %}
|
|
10
|
+
{{render_section_content(field.label, fmt(ds[field.name], field.format_mask))}}
|
|
11
|
+
{% endfor %}
|
|
12
|
+
</section>
|
|
13
|
+
{% endmacro %}
|
|
14
|
+
{% macro render_group_header(ds, layout, zip, fmt, nivel) %}
|
|
15
|
+
{{render_section("group-header-%i" % nivel, ds, layout, zip, fmt)}}
|
|
16
|
+
{% endmacro %}
|
|
17
|
+
{% macro render_group_footer(ds, layout, zip, fmt, nivel) %}
|
|
18
|
+
{{render_section("group-footer-%i" % nivel, ds, layout, zip, fmt)}}
|
|
19
|
+
{% endmacro %}
|
|
20
|
+
{% macro render_detail(ds, layout, zip, fmt) %}
|
|
21
|
+
<table class="relatorio">
|
|
22
|
+
<thead>
|
|
23
|
+
<tr>
|
|
24
|
+
{% for field in layout %}
|
|
25
|
+
<th style="text-align: {{field.alignment}}">{{field.label}}</th>
|
|
26
|
+
{% endfor %}
|
|
27
|
+
</tr>
|
|
28
|
+
</thead>
|
|
29
|
+
<tbody>
|
|
30
|
+
{% for dt_item in ds %}
|
|
31
|
+
<tr>
|
|
32
|
+
{% for field in layout %}
|
|
33
|
+
<td style="text-align: {{field.alignment}}"><p>{{fmt(dt_item[field.name], field.format_mask)}}</p></td>
|
|
34
|
+
{% endfor %}
|
|
35
|
+
</tr>
|
|
36
|
+
{% endfor %}
|
|
37
|
+
</tbody>
|
|
38
|
+
</table>
|
|
39
|
+
{% endmacro %}
|
|
40
|
+
{% macro render_group(ds, layout, zip, fmt, nivel) %}
|
|
41
|
+
{% for data in ds %}
|
|
42
|
+
{% if data.fields and layout.header %}
|
|
43
|
+
{{render_group_header(data.fields, layout.header, zip, fmt, nivel)}}
|
|
44
|
+
{% endif %}
|
|
45
|
+
{% if data.groups and layout.groups %}
|
|
46
|
+
{{render_group(data.groups, layout.groups, zip, fmt, nivel + 1)}}
|
|
47
|
+
{% endif %}
|
|
48
|
+
{% if data.detail and layout.detail %}
|
|
49
|
+
{{render_detail(data.detail, layout.detail, zip, fmt)}}
|
|
50
|
+
{% endif %}
|
|
51
|
+
{% if data.fields and layout.footer %}
|
|
52
|
+
{{render_group_footer(data.fields, layout.footer, zip, fmt, nivel)}}
|
|
53
|
+
{% endif %}
|
|
54
|
+
{% if not loop.last and nivel == 0 %}
|
|
55
|
+
{{render_divisor()}}
|
|
56
|
+
{% endif %}
|
|
57
|
+
{% endfor %}
|
|
58
|
+
{% endmacro %}
|
|
59
|
+
{% macro render_divisor() %}
|
|
60
|
+
<hr class="divisor-table"/>
|
|
61
|
+
{% endmacro %}
|
|
62
|
+
{% macro render_summary(ds, layout, zip, fmt) %}
|
|
63
|
+
<section class="summary">
|
|
64
|
+
{% for field in layout %}
|
|
65
|
+
{{render_section_content(field.label, fmt(ds[field.name], field.format_mask))}}
|
|
66
|
+
{% endfor %}
|
|
67
|
+
</section>
|
|
68
|
+
{% endmacro %}
|
isis_report_lib/toon.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Parser do formato textual `.toon` (cópia fiel do POC isis_report).
|
|
2
|
+
|
|
3
|
+
Sintaxe suportada:
|
|
4
|
+
|
|
5
|
+
- ``chave: valor`` — par simples
|
|
6
|
+
- ``chave:`` + linhas indentadas — objeto aninhado
|
|
7
|
+
- ``chave[n]:`` + itens ``- ...`` — array com n elementos
|
|
8
|
+
- ``chave[n]{a,b}:`` + linhas ``v1,v2`` — array de objetos
|
|
9
|
+
- ``dados[n]:`` — mapeado automaticamente para ``data``
|
|
10
|
+
- ``chave{Label,formato,align}`` — campo de layout inline
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ToonParser:
|
|
18
|
+
"""Converte texto `.toon` em dict estruturado."""
|
|
19
|
+
|
|
20
|
+
@staticmethod
|
|
21
|
+
def _convert_value(value: str) -> Any:
|
|
22
|
+
v = value.strip()
|
|
23
|
+
if v.lower() == "true":
|
|
24
|
+
return True
|
|
25
|
+
if v.lower() == "false":
|
|
26
|
+
return False
|
|
27
|
+
try:
|
|
28
|
+
return int(v)
|
|
29
|
+
except ValueError:
|
|
30
|
+
pass
|
|
31
|
+
try:
|
|
32
|
+
return float(v)
|
|
33
|
+
except ValueError:
|
|
34
|
+
pass
|
|
35
|
+
return v
|
|
36
|
+
|
|
37
|
+
def parse(self, text: str) -> dict:
|
|
38
|
+
"""Faz o parse do texto `.toon` para dict (com ``dados`` -> ``data``)."""
|
|
39
|
+
tokens = self._tokenize(text)
|
|
40
|
+
result, _ = self._parse_dict(tokens, 0, 0)
|
|
41
|
+
if "dados" in result:
|
|
42
|
+
result["data"] = result.pop("dados")
|
|
43
|
+
return result
|
|
44
|
+
|
|
45
|
+
def _tokenize(self, text: str) -> list[tuple[int, str]]:
|
|
46
|
+
tokens = []
|
|
47
|
+
for line in text.split("\n"):
|
|
48
|
+
stripped = line.rstrip()
|
|
49
|
+
content = stripped.strip()
|
|
50
|
+
if not content:
|
|
51
|
+
continue
|
|
52
|
+
indent = len(line) - len(line.lstrip())
|
|
53
|
+
level = indent // 2
|
|
54
|
+
tokens.append((level, content))
|
|
55
|
+
return tokens
|
|
56
|
+
|
|
57
|
+
def _parse_dict(self, tokens: list[tuple[int, str]], start: int, level: int) -> tuple[dict, int]:
|
|
58
|
+
result: dict[str, Any] = {}
|
|
59
|
+
i = start
|
|
60
|
+
while i < len(tokens):
|
|
61
|
+
tok_level, content = tokens[i]
|
|
62
|
+
if tok_level < level:
|
|
63
|
+
break
|
|
64
|
+
if tok_level > level:
|
|
65
|
+
i += 1
|
|
66
|
+
continue
|
|
67
|
+
|
|
68
|
+
if content.startswith("- "):
|
|
69
|
+
i += 1
|
|
70
|
+
continue
|
|
71
|
+
|
|
72
|
+
m = re.match(r"^(\w+)\[(\d+)\]\{([^}]+)\}:$", content)
|
|
73
|
+
if m:
|
|
74
|
+
key = m.group(1)
|
|
75
|
+
fields = [f.strip() for f in m.group(3).split(",")]
|
|
76
|
+
arr = []
|
|
77
|
+
i += 1
|
|
78
|
+
while i < len(tokens) and tokens[i][0] > tok_level:
|
|
79
|
+
_, val_line = tokens[i]
|
|
80
|
+
vals = [self._convert_value(v) for v in val_line.split(",")]
|
|
81
|
+
arr.append(dict(zip(fields, vals, strict=True)))
|
|
82
|
+
i += 1
|
|
83
|
+
result[key] = arr
|
|
84
|
+
continue
|
|
85
|
+
|
|
86
|
+
m = re.match(r"^(\w+)\[(\d+)\]:$", content)
|
|
87
|
+
if m:
|
|
88
|
+
key = m.group(1)
|
|
89
|
+
arr = []
|
|
90
|
+
i += 1
|
|
91
|
+
sub_arr, consumed = self._parse_array(tokens, i, tok_level + 1)
|
|
92
|
+
arr.extend(sub_arr)
|
|
93
|
+
i = consumed
|
|
94
|
+
result[key] = arr
|
|
95
|
+
continue
|
|
96
|
+
|
|
97
|
+
m = re.match(r"^(\w+)\{([^,]+),([^,]+),([^,]+)\}$", content)
|
|
98
|
+
if m:
|
|
99
|
+
result[m.group(1)] = {
|
|
100
|
+
"label": m.group(2).strip(),
|
|
101
|
+
"format_mask": m.group(3).strip(),
|
|
102
|
+
"alignment": m.group(4).strip(),
|
|
103
|
+
}
|
|
104
|
+
i += 1
|
|
105
|
+
continue
|
|
106
|
+
|
|
107
|
+
m = re.match(r"^([^:]+):\s*(.*)$", content)
|
|
108
|
+
if m:
|
|
109
|
+
key = m.group(1).strip()
|
|
110
|
+
value = m.group(2).strip()
|
|
111
|
+
if value:
|
|
112
|
+
result[key] = self._convert_value(value)
|
|
113
|
+
i += 1
|
|
114
|
+
else:
|
|
115
|
+
if i + 1 < len(tokens) and tokens[i + 1][0] > tok_level:
|
|
116
|
+
sub_dict, consumed = self._parse_dict(tokens, i + 1, tok_level + 1)
|
|
117
|
+
result[key] = sub_dict if sub_dict else {}
|
|
118
|
+
i = consumed
|
|
119
|
+
else:
|
|
120
|
+
result[key] = {}
|
|
121
|
+
i += 1
|
|
122
|
+
continue
|
|
123
|
+
|
|
124
|
+
i += 1
|
|
125
|
+
|
|
126
|
+
return result, i
|
|
127
|
+
|
|
128
|
+
def _parse_array(self, tokens: list[tuple[int, str]], start: int, level: int) -> tuple[list, int]:
|
|
129
|
+
result: list[Any] = []
|
|
130
|
+
i = start
|
|
131
|
+
while i < len(tokens):
|
|
132
|
+
tok_level, content = tokens[i]
|
|
133
|
+
if tok_level < level:
|
|
134
|
+
break
|
|
135
|
+
if tok_level > level:
|
|
136
|
+
i += 1
|
|
137
|
+
continue
|
|
138
|
+
|
|
139
|
+
if content.startswith("- "):
|
|
140
|
+
item: Any = {}
|
|
141
|
+
item_text = content[2:].strip()
|
|
142
|
+
m = re.match(r"^([^:]+):\s*(.*)$", item_text)
|
|
143
|
+
if m:
|
|
144
|
+
key = m.group(1).strip()
|
|
145
|
+
value = m.group(2).strip()
|
|
146
|
+
if value:
|
|
147
|
+
item[key] = self._convert_value(value)
|
|
148
|
+
else:
|
|
149
|
+
sub_dict: dict[str, Any] = {}
|
|
150
|
+
if i + 1 < len(tokens) and tokens[i + 1][0] > tok_level:
|
|
151
|
+
sub_dict, consumed = self._parse_dict(tokens, i + 1, tok_level + 1)
|
|
152
|
+
i = consumed
|
|
153
|
+
item[key] = sub_dict if sub_dict else {}
|
|
154
|
+
else:
|
|
155
|
+
item = self._convert_value(item_text)
|
|
156
|
+
i += 1
|
|
157
|
+
result.append(item)
|
|
158
|
+
continue
|
|
159
|
+
|
|
160
|
+
i += 1
|
|
161
|
+
if i < len(tokens) and tokens[i][0] == tok_level + 1:
|
|
162
|
+
extra_dict, consumed = self._parse_dict(tokens, i, tok_level + 1)
|
|
163
|
+
item.update(extra_dict)
|
|
164
|
+
i = consumed
|
|
165
|
+
result.append(item)
|
|
166
|
+
else:
|
|
167
|
+
i += 1
|
|
168
|
+
|
|
169
|
+
return result, i
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def parse_toon(text: str) -> dict[str, Any]:
|
|
173
|
+
"""Atalho funcional: ``ToonParser().parse(text)``."""
|
|
174
|
+
return ToonParser().parse(text)
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: isis-report-lib
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Biblioteca Python para geração de relatórios PDF tabulares com layouts hierárquicos (Jinja2 + Playwright). Extraída do POC isis_report.
|
|
5
|
+
Project-URL: Homepage, https://github.com/thepaneb/isis_report
|
|
6
|
+
Author: Gil Cleber Barboza
|
|
7
|
+
License: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: jinja2,pdf,playwright,report,toon
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Requires-Python: >=3.11
|
|
14
|
+
Requires-Dist: jinja2>=3.1
|
|
15
|
+
Requires-Dist: playwright>=1.40
|
|
16
|
+
Requires-Dist: pydantic>=2.0
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
19
|
+
Requires-Dist: pytest-timeout>=2; extra == 'dev'
|
|
20
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
21
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# isis-report-lib
|
|
25
|
+
|
|
26
|
+
Biblioteca Python para geração de relatórios **PDF tabulares** com layouts hierárquicos customizáveis — extraída do POC [isis_report](https://github.com/thepaneb/isis_report) (microserviço Robyn), sem o servidor.
|
|
27
|
+
|
|
28
|
+
- Entrada: `dict`/`ReportPayload` (`meta` + `layout` opcional + `data`) ou texto **`.toon`**
|
|
29
|
+
- Renderização: Jinja2 (templates embutidos no pacote)
|
|
30
|
+
- PDF: Playwright (Chromium)
|
|
31
|
+
- API: síncrona (`generate_pdf`) + assíncrona (`agenerate_pdf`)
|
|
32
|
+
|
|
33
|
+
## Instalação
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install isis-report-lib
|
|
37
|
+
playwright install chromium # necessário p/ gerar PDF
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Dev:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install -e ".[dev]"
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Uso rápido
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from isis_report_lib import generate_pdf, generate_pdf_from_toon, render_html
|
|
50
|
+
|
|
51
|
+
payload = {
|
|
52
|
+
"meta": {"title": "Pedido de Vendas", "sub_title": "2024", "mode": "exact"},
|
|
53
|
+
"layout": {
|
|
54
|
+
"empresa": {"label": "Empresa", "format_mask": "str", "alignment": "left"},
|
|
55
|
+
"pedidos": {
|
|
56
|
+
"pedido": {"label": "Código", "format_mask": "int", "alignment": "right"},
|
|
57
|
+
"valor_total": {"label": "Valor Total", "format_mask": "float", "alignment": "right"},
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
"data": [{"empresa": "CQ CONSULTORIA", "pedidos": [{"pedido": 750, "valor_total": 4000}]}],
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
pdf_bytes = generate_pdf(payload)
|
|
64
|
+
open("relatorio.pdf", "wb").write(pdf_bytes)
|
|
65
|
+
|
|
66
|
+
# Sem Playwright: só o HTML intermediário
|
|
67
|
+
html = render_html(payload)
|
|
68
|
+
|
|
69
|
+
# A partir de .toon
|
|
70
|
+
toon = open("examples/pedido.toon", encoding="utf-8").read()
|
|
71
|
+
open("relatorio_toon.pdf", "wb").write(generate_pdf_from_toon(toon))
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Async:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from isis_report_lib import agenerate_pdf, agenerate_pdf_from_toon
|
|
78
|
+
|
|
79
|
+
pdf = await agenerate_pdf(payload)
|
|
80
|
+
pdf = await agenerate_pdf_from_toon(toon_text)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Opções do PDF (repassadas ao `page.pdf` do Playwright):
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
generate_pdf(payload, pdf_options={"format": "A4", "margin": {"top": ".2in", "bottom": ".5in"}})
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Exemplo completo em `examples/`.
|
|
90
|
+
|
|
91
|
+
## Payload
|
|
92
|
+
|
|
93
|
+
| Campo | Tipo | Obrigatório | Descrição |
|
|
94
|
+
| --- | --- | --- | --- |
|
|
95
|
+
| `meta` | object | sim | `title`, `sub_title`, `mode` (`"exact"`/`"gray"`), `company` |
|
|
96
|
+
| `layout` | object | não | definição hierárquica; omitir = inferido dos dados |
|
|
97
|
+
| `data` | array | sim | registros crus ou formato template (`{"fields": ..., "groups": ...}`) |
|
|
98
|
+
|
|
99
|
+
Máscaras: `str` · `int` (milhar `1.234`) · `float` (pt-BR `1.234,50`) · `date`.
|
|
100
|
+
|
|
101
|
+
## Sintaxe `.toon`
|
|
102
|
+
|
|
103
|
+
```toon
|
|
104
|
+
meta:
|
|
105
|
+
title: Pedido de Vendas
|
|
106
|
+
mode: exact
|
|
107
|
+
layout:
|
|
108
|
+
produto{Produto,str,left}
|
|
109
|
+
valor{Valor,float,right}
|
|
110
|
+
dados[1]:
|
|
111
|
+
- produto: Caneta
|
|
112
|
+
valor: 5.50
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`dados[n]` é mapeado para `data`. Ver `examples/pedido.toon`.
|
|
116
|
+
|
|
117
|
+
## API
|
|
118
|
+
|
|
119
|
+
| Função | Descrição |
|
|
120
|
+
| --- | --- |
|
|
121
|
+
| `generate_pdf(payload, pdf_options?) -> bytes` | PDF sync a partir de dict/`ReportPayload` |
|
|
122
|
+
| `agenerate_pdf(...)` | idem, async |
|
|
123
|
+
| `generate_pdf_from_toon(text, ...)` / `agenerate_pdf_from_toon` | PDF a partir de `.toon` |
|
|
124
|
+
| `render_html(payload)` / `arender_html` / `render_html_from_toon` | HTML intermediário (sem browser) |
|
|
125
|
+
| `ToonParser().parse(text)` / `parse_toon(text)` | parse `.toon` -> dict |
|
|
126
|
+
| `TabularReportService(pdf_options?)` | pipeline `execute(payload)` (Obter→Tratar→HTML→PDF) |
|
|
127
|
+
|
|
128
|
+
## Testes
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
pytest -q
|
|
132
|
+
ruff check src tests
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Testes de PDF real exigem `playwright install chromium` e são pulados (`-m "not browser"`) se o browser não estiver disponível.
|
|
136
|
+
|
|
137
|
+
## Licença
|
|
138
|
+
|
|
139
|
+
MIT — ver `LICENSE`.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
isis_report_lib/__init__.py,sha256=5N-HxAFH1outs_TvWnm6YsYnezbr_wTYbYlhBkO08UA,1076
|
|
2
|
+
isis_report_lib/api.py,sha256=Ec9noh7arwA3TE-ybcbetVK06I46WxdkN9yL5UXRq0k,3427
|
|
3
|
+
isis_report_lib/formatting.py,sha256=3tTDfMr2a4ssSiC7CFjqOQ9bKDeo6qa0Ts14Nle71Hs,942
|
|
4
|
+
isis_report_lib/layout.py,sha256=eVxP-D23fnivs2FmQP_6FiFbjdTi7V95gJ_QQFcJlcQ,4854
|
|
5
|
+
isis_report_lib/models.py,sha256=jQfNb2LugeimGV4mgkWXYj-_anUMr-mGooGvKJUd9mQ,522
|
|
6
|
+
isis_report_lib/pdf.py,sha256=VpmldIUT8Odg-81Z7wtqu90ppJYFBQrvT-q9EcXyNrM,5492
|
|
7
|
+
isis_report_lib/rendering.py,sha256=HwIz8agw0181QL62-nFtkIDOmRsUiJm8Y9rdjVnGPVs,1605
|
|
8
|
+
isis_report_lib/service.py,sha256=xoI4rHkiaQD_gzsjFUBf2CXfV9k2gCfkLNo4KdpoPh4,3465
|
|
9
|
+
isis_report_lib/toon.py,sha256=5HLa8c-dTaahH6__oEwB0vvUPUt16j0rNSEO6hE9Uw4,5918
|
|
10
|
+
isis_report_lib/templates/relatorio_base.jinja,sha256=WybM5N_fklQlAmBHCJBOO2_fUDHyRiUph4Ypx8nCbiM,7764
|
|
11
|
+
isis_report_lib/templates/relatorio_tabular.jinja,sha256=0Nh83aWdt5v6yyRp_8veW9UlzvyWcV-nQA4fizJjla8,511
|
|
12
|
+
isis_report_lib/templates/relatorio_tabular_sections.jinja,sha256=dVoUdPskI1UgWLd8DJzuUtar2R0iDCfWYcGQlvMzXZY,2629
|
|
13
|
+
isis_report_lib-0.1.0.dist-info/METADATA,sha256=WUD61C4-9rWXCuqJF-KwlIlldod6FlNzdgArdTkonwQ,4312
|
|
14
|
+
isis_report_lib-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
15
|
+
isis_report_lib-0.1.0.dist-info/licenses/LICENSE,sha256=88qLEImKhDh_3bUVeY0JqcIj5P0O-ADyprP2zTO1iHY,1075
|
|
16
|
+
isis_report_lib-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Gil Cleber Barboza
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|