LesterCerioli commited on
Commit
5c3c18a
·
1 Parent(s): d9d7b41

Building Speed LLM

Browse files
Files changed (1) hide show
  1. README.md +1384 -0
README.md ADDED
@@ -0,0 +1,1384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLM Fiscal Brasileiro — SPED Fiscal System
2
+
3
+ > **PyTorch-powered LLM for Brazilian fiscal obligations (SPED)**
4
+ > Python 3.12 · PyTorch · Pydantic v2 · 117 tests
5
+
6
+ ---
7
+
8
+ ## Table of Contents / Índice
9
+
10
+ - [English](#english)
11
+ - [Overview](#overview)
12
+ - [Architecture](#architecture)
13
+ - [Project Structure](#project-structure)
14
+ - [Installation](#installation)
15
+ - [Quick Start](#quick-start)
16
+ - [LLM Model](#llm-model)
17
+ - [Tax Calculators](#tax-calculators)
18
+ - [SPED / DFe Generators](#sped--dfe-generators)
19
+ - [Annual Declarations](#annual-declarations)
20
+ - [SEFAZ Transmitter](#sefaz-transmitter)
21
+ - [Training the Model](#training-the-model)
22
+ - [Running Tests](#running-tests)
23
+ - [Fiscal Calendar](#fiscal-calendar)
24
+ - [Português Brasileiro](#português-brasileiro)
25
+ - [Visão Geral](#visão-geral)
26
+ - [Arquitetura](#arquitetura)
27
+ - [Estrutura do Projeto](#estrutura-do-projeto)
28
+ - [Instalação](#instalação)
29
+ - [Início Rápido](#início-rápido)
30
+ - [Modelo LLM](#modelo-llm)
31
+ - [Calculadoras Tributárias](#calculadoras-tributárias)
32
+ - [Geradores SPED / DFe](#geradores-sped--dfe)
33
+ - [Declarações Anuais](#declarações-anuais)
34
+ - [Transmissor SEFAZ](#transmissor-sefaz)
35
+ - [Treinamento do Modelo](#treinamento-do-modelo)
36
+ - [Execução dos Testes](#execução-dos-testes)
37
+ - [Calendário Fiscal](#calendário-fiscal)
38
+
39
+ ---
40
+
41
+ # English
42
+
43
+ ## Overview
44
+
45
+ The **Brazilian Fiscal LLM** is a Python 3.12 library that combines a custom **PyTorch Transformer** with a complete set of Brazilian tax compliance tools. It is designed to be consumed as a library by any application — there is no CLI or UI bundled in.
46
+
47
+ The system covers the full lifecycle of Brazilian fiscal obligations:
48
+
49
+ - **Intent classification** of natural-language fiscal queries (16 obligation classes)
50
+ - **RAG (Retrieval-Augmented Generation)** with 25 indexed fiscal knowledge documents
51
+ - **Tax calculators** for all major Brazilian taxes (ICMS, IPI, PIS/COFINS, IRPJ/CSLL, ISS, Simples Nacional)
52
+ - **SPED file generators** for all federal digital bookkeeping obligations
53
+ - **Electronic document generators** (NF-e, NFC-e, CT-e, MDF-e) with digital signatures
54
+ - **SEFAZ SOAP transmitter** for NF-e authorization
55
+
56
+ The single entry point is `PipelineFiscal`, which orchestrates all components.
57
+
58
+ ---
59
+
60
+ ## Architecture
61
+
62
+ ```
63
+ ┌──────────────────────────────────────────────────────────────────┐
64
+ │ PipelineFiscal │
65
+ │ (src/models/fiscal_llm.py) │
66
+ │ │
67
+ │ ┌─────────────────────┐ ┌──────────────────────────────────┐ │
68
+ │ │ TransformerFiscal │ │ BancoEmbeddingsFiscais (RAG) │ │
69
+ │ │ PyTorch 4-layer │ │ 25 knowledge documents │ │
70
+ │ │ encoder, d=256 │ │ cosine similarity search │ │
71
+ │ │ 8 heads, Pre-LN │ └──────────────────────────────────┘ │
72
+ │ └─────────────────────┘ │
73
+ │ ┌─────────────────────────────────────────────────────────────┐ │
74
+ │ │ Intent Classification (16 classes) │ │
75
+ │ └─────────────────────────────────────────────────────────────┘ │
76
+ │ │
77
+ │ ┌──────────────────┐ ┌──────────────────┐ ┌───────────────┐ │
78
+ │ │ Tax Calculators │ │ SPED Generators │ │ DFe / XML │ │
79
+ │ │ ICMS · IPI │ │ EFD ICMS/IPI │ │ NF-e · NFC-e │ │
80
+ │ │ PIS/COFINS │ │ EFD Contribu. │ │ CT-e · MDF-e │ │
81
+ │ │ IRPJ/CSLL · ISS │ │ ECD · ECF │ │ EFD-Reinf │ │
82
+ │ │ Simples Nac. │ │ DCTF · GIA │ │ e-Social │ │
83
+ │ └──────────────────┘ │ DIRF · DEFIS │ └───────────────┘ │
84
+ │ │ DeSTDA │ │
85
+ │ └──────────────────┘ │
86
+ └──────────────────────────────────────────────────────────────────┘
87
+ ```
88
+
89
+ **Key design decisions:**
90
+ - The LLM (`TransformerFiscal`) uses character-level tokenization — no external tokenizer dependency.
91
+ - RAG runs entirely in-memory using normalized cosine similarity on CLS embeddings.
92
+ - All monetary values use Python `Decimal` with `ROUND_HALF_UP` — no floating-point arithmetic.
93
+ - SPED files are pipe-delimited (`|REGISTRO|CAMPO1|`) UTF-8, matching the official Receita Federal spec.
94
+ - NF-e/CT-e/MDF-e use XML v4.00 with RSA-SHA1 XMLDSig digital signatures via the `cryptography` library.
95
+
96
+ ---
97
+
98
+ ## Project Structure
99
+
100
+ ```
101
+ llm-speed/
102
+ ├── src/
103
+ │ ├── __init__.py # Exports PipelineFiscal
104
+ │ ├── fiscal/
105
+ │ │ ├── entities.py # Pydantic v2 models (Empresa, NotaFiscal, …)
106
+ │ │ └── constants.py # Tax rates, CST tables, CFOP codes, deadlines
107
+ │ ├── calculators/
108
+ │ │ ├── icms.py # ICMS (own + ST + DIFAL + FCP)
109
+ │ │ ├── ipi.py # IPI (TIPI rates by NCM chapter)
110
+ │ │ ├── pis_cofins.py # PIS/COFINS (cumulative + non-cumulative + withholding)
111
+ │ │ ├── irpj_csll.py # IRPJ/CSLL (Lucro Real + Lucro Presumido + monthly estimates)
112
+ │ │ ├── iss.py # ISS (LC 116/2003 + Simples Nacional annexes)
113
+ │ │ └── simples_nacional.py # Simples Nacional (5 annexes, Fator R, PGDAS-D, MEI)
114
+ │ ├── generators/
115
+ │ │ ├── sped_writer.py # Base SPED pipe-delimited writer
116
+ │ │ ├── efd_icms_ipi.py # EFD ICMS/IPI (blocks 0,C,E,G,H,K,1,9)
117
+ │ │ ├── efd_contribuicoes.py # EFD Contribuições PIS/COFINS (blocks 0,C,M,1,9)
118
+ │ │ ├── ecd.py # ECD — Escrituração Contábil Digital
119
+ │ │ ├── ecf.py # ECF — Escrituração Contábil Fiscal (LALUR/LACS)
120
+ │ │ ├── nfe_xml.py # NF-e XML v4.00 (model 55) + digital signature
121
+ │ │ ├── nfce_xml.py # NFC-e XML v4.00 (model 65, consumer/POS)
122
+ │ │ ├── cte.py # CT-e XML v4.00 (model 57, freight)
123
+ │ │ ├── mdfe.py # MDF-e XML v3.00 (manifest, model 58)
124
+ │ │ ├── efd_reinf.py # EFD-Reinf XML events (R-1000…R-2099)
125
+ │ │ ├── esocial.py # e-Social XML events (S-1000…S-1299, S-2200, S-2299)
126
+ │ │ ├── dctf.py # DCTF XML (federal tax debit declaration)
127
+ │ │ ├── dirf.py # DIRF text file (annual IRRF withholding declaration)
128
+ │ │ ├── defis.py # DEFIS XML (Simples Nacional annual declaration)
129
+ │ │ ├── destda.py # DeSTDA XML (Simples Nacional monthly ICMS-ST/DIFAL)
130
+ │ │ └── gia.py # GIA/GIA-ST AIE file (São Paulo monthly ICMS)
131
+ │ ├── models/
132
+ │ │ ├── fiscal_llm.py # TransformerFiscal + RAG + PipelineFiscal
133
+ │ │ └── trainer.py # TrainerFiscal (173 examples, early stopping, class weights)
134
+ │ └── transmitters/
135
+ │ └── receita_federal.py # NF-e SEFAZ SOAP transmitter + SPED local validator
136
+ ├── tests/
137
+ │ ├── test_calculators.py # 43 tests for all tax calculators
138
+ │ └── test_generators.py # 74 tests for all generators
139
+ ├── pyproject.toml
140
+ └── requirements.txt
141
+ ```
142
+
143
+ ---
144
+
145
+ ## Installation
146
+
147
+ **Requirements:** Python 3.12+, pip
148
+
149
+ ```bash
150
+ # Clone the repository
151
+ git clone <repo-url>
152
+ cd llm-speed
153
+
154
+ # Create and activate virtual environment
155
+ python -m venv venv
156
+ source venv/bin/activate # Linux/macOS
157
+ # venv\Scripts\activate # Windows
158
+
159
+ # Install dependencies
160
+ pip install -r requirements.txt
161
+ ```
162
+
163
+ **Core dependencies:**
164
+
165
+ | Package | Purpose |
166
+ |---------|---------|
167
+ | `torch>=2.3.0` | TransformerFiscal model + training |
168
+ | `pydantic>=2.7.0` | Validated fiscal data models |
169
+ | `cryptography>=42.0.0` | NF-e/CT-e XML digital signatures (RSA-SHA1) |
170
+ | `lxml>=5.2.0` | C14N canonicalization for XMLDSig |
171
+ | `httpx>=0.27.0` | SEFAZ SOAP HTTP client |
172
+ | `zeep>=4.2.1` | SOAP envelope helpers |
173
+ | `python-dateutil>=2.9.0` | Brazilian fiscal calendar calculations |
174
+
175
+ ---
176
+
177
+ ## Quick Start
178
+
179
+ ```python
180
+ from src import PipelineFiscal
181
+
182
+ # Instantiate the LLM pipeline (uses random weights until trained)
183
+ pipeline = PipelineFiscal(diretorio_saida="./output")
184
+
185
+ # --- Natural language processing ---
186
+ resultado = pipeline.processar(
187
+ "calculate ICMS for a sale",
188
+ {"valor_mercadoria": 10000, "aliquota": 18, "uf_origem": "SP", "uf_destino": "RJ"}
189
+ )
190
+ print(resultado.resumo())
191
+ # [calcular_icms]
192
+ # base_calculo: R$ 10,000.00
193
+ # aliquota: R$ 18.00
194
+ # valor_icms: R$ 1,800.00
195
+ # valor_total_icms: R$ 1,800.00
196
+
197
+ # --- Direct tax calculation ---
198
+ r = pipeline.calcular_pis_cofins({
199
+ "valor": 100000,
200
+ "regime": "lucro_presumido",
201
+ })
202
+ print(r["pis_a_recolher"]) # 650.00
203
+ print(r["cofins_a_recolher"]) # 3000.00
204
+
205
+ # --- Generate SPED files for an entire period ---
206
+ from src.fiscal.entities import PeriodoApuracao, Empresa, ...
207
+ periodo = PeriodoApuracao(...)
208
+ arquivos = pipeline.gerar_obrigacoes(periodo)
209
+ # Returns: {"EFD_ICMS_IPI": ResultadoFiscal, "EFD_CONTRIBUICOES": ..., ...}
210
+
211
+ # --- SEFAZ status check ---
212
+ status = pipeline.verificar_sefaz(uf="SP")
213
+ print(status["mensagem"])
214
+ ```
215
+
216
+ ---
217
+
218
+ ## LLM Model
219
+
220
+ ### TransformerFiscal
221
+
222
+ A compact Transformer encoder trained for Brazilian fiscal intent classification.
223
+
224
+ | Parameter | Value |
225
+ |-----------|-------|
226
+ | Architecture | Transformer Encoder (Pre-LN) |
227
+ | Layers | 4 |
228
+ | d_model | 256 |
229
+ | Attention heads | 8 |
230
+ | FFN dimension | 1,024 |
231
+ | Tokenizer | Character-level (vocab ~200 chars) |
232
+ | Max sequence length | 1,024 tokens |
233
+ | Output classes | 16 fiscal obligation types |
234
+
235
+ **16 Intent Classes:**
236
+
237
+ | Class | Description |
238
+ |-------|-------------|
239
+ | `EFD_ICMS_IPI` | Generate EFD ICMS/IPI digital bookkeeping |
240
+ | `EFD_CONTRIBUICOES` | Generate EFD Contribuições (PIS/COFINS) |
241
+ | `ECD` | Generate Escrituração Contábil Digital |
242
+ | `ECF` | Generate Escrituração Contábil Fiscal |
243
+ | `NFe` | Emit / cancel NF-e or NFC-e |
244
+ | `NFSe` | Emit NFS-e (municipal service invoice) |
245
+ | `CTe` | Generate CT-e freight document |
246
+ | `eSocial` | Generate e-Social payroll events |
247
+ | `EFD_REINF` | Generate EFD-Reinf withholding events |
248
+ | `DCTF` | Generate DCTF federal tax declaration |
249
+ | `PGDAS` | Calculate Simples Nacional DAS / PGDAS-D |
250
+ | `calculo_icms` | Calculate ICMS for a transaction |
251
+ | `calculo_ipi` | Calculate IPI for industrial products |
252
+ | `calculo_pis_cofins` | Calculate PIS and COFINS on revenue |
253
+ | `calculo_irpj_csll` | Calculate IRPJ and CSLL (corporate taxes) |
254
+ | `calculo_iss` | Calculate ISS (municipal services tax) |
255
+
256
+ ### RAG Knowledge Base
257
+
258
+ `BancoEmbeddingsFiscais` indexes 25 fiscal knowledge documents covering all major obligations, rates, deadlines, and legislation. Retrieval uses cosine similarity on CLS token embeddings.
259
+
260
+ ```python
261
+ # Direct access to RAG
262
+ pipeline.rag.buscar("prazo EFD ICMS IPI", top_k=3)
263
+ # Returns: [(text, similarity_score), ...]
264
+ ```
265
+
266
+ ---
267
+
268
+ ## Tax Calculators
269
+
270
+ All calculators are available directly via `PipelineFiscal` or imported from `src.calculators.*`. All monetary values use `Decimal` with `ROUND_HALF_UP`.
271
+
272
+ ### ICMS (`src/calculators/icms.py`)
273
+
274
+ ```python
275
+ resultado = pipeline.calcular_icms({
276
+ "valor_mercadoria": 10000,
277
+ "aliquota": 18, # internal rate (%)
278
+ "uf_origem": "SP",
279
+ "uf_destino": "RJ",
280
+ "frete": 500,
281
+ "cst": "000", # CST: 000=taxed, 020=reduced, 040=exempt, 060=ST
282
+ "calcular_difal": False,
283
+ "consumidor_final": False,
284
+ # Optional ST parameters:
285
+ # "calcular_st": True, "mva": 40, "aliq_interna_destino": 18
286
+ })
287
+ ```
288
+
289
+ Supports: CST 000/010/020/030/040/041/050/051/060/070, ICMS-ST with MVA, FCP (Fundo de Combate à Pobreza), DIFAL (EC 87/2015).
290
+
291
+ ### IPI (`src/calculators/ipi.py`)
292
+
293
+ ```python
294
+ resultado = pipeline.calcular_ipi({
295
+ "valor_produtos": 5000,
296
+ "aliquota": 10,
297
+ "cst": "50", # 50=taxed, 52=exempt, 54=suspended
298
+ "frete": 200,
299
+ })
300
+ ```
301
+
302
+ Includes TIPI rates by NCM chapter (0% pharmaceuticals, 25% vehicles, 300% tobacco).
303
+
304
+ ### PIS/COFINS (`src/calculators/pis_cofins.py`)
305
+
306
+ ```python
307
+ resultado = pipeline.calcular_pis_cofins({
308
+ "valor": 100000,
309
+ "regime": "lucro_real", # or "lucro_presumido"
310
+ # Optional credits (non-cumulative regime only):
311
+ "receitas": [
312
+ {"descricao": "Vendas", "valor": 100000, "cst_pis": "01", "cst_cofins": "01"}
313
+ ],
314
+ })
315
+ ```
316
+
317
+ | Regime | PIS | COFINS |
318
+ |--------|-----|--------|
319
+ | Lucro Presumido (cumulative) | 0.65% | 3.00% |
320
+ | Lucro Real (non-cumulative) | 1.65% | 7.60% |
321
+
322
+ Supports credits on purchases, energy, rent, depreciation (Lei 10.637/2002 and 10.833/2003).
323
+
324
+ ### IRPJ / CSLL (`src/calculators/irpj_csll.py`)
325
+
326
+ ```python
327
+ resultado = pipeline.calcular_irpj_csll({
328
+ "valor": 500000, # Lucro Real: net profit / Lucro Presumido: gross revenue
329
+ "regime": "lucro_presumido", # or "lucro_real"
330
+ "atividade": "venda_mercadorias", # or "servicos_em_geral", "intermediacao"
331
+ })
332
+ ```
333
+
334
+ | Rule | Value |
335
+ |------|-------|
336
+ | IRPJ base rate | 15% |
337
+ | IRPJ surcharge | +10% on profit > R$ 20,000/month |
338
+ | CSLL rate | 9% (general) / 15% (financial institutions) |
339
+ | Lucro Presumido — commerce/industry | 8% of revenue |
340
+ | Lucro Presumido — services | 32% of revenue |
341
+ | Tax loss carryforward limit | 30% of taxable profit |
342
+
343
+ ### ISS (`src/calculators/iss.py`)
344
+
345
+ ```python
346
+ resultado = pipeline.calcular_iss({
347
+ "valor_servico": 10000,
348
+ "codigo_servico": "17", # LC 116/2003 service code
349
+ "aliquota": 3, # municipal rate (2%–5%)
350
+ "retencao_fonte": True,
351
+ })
352
+ ```
353
+
354
+ ### Simples Nacional (`src/calculators/simples_nacional.py`)
355
+
356
+ ```python
357
+ # Single activity DAS calculation
358
+ resultado = pipeline.calcular_simples({
359
+ "receita_mes": 50000,
360
+ "rbt12": 600000, # 12-month accumulated revenue
361
+ "anexo": "I", # I=commerce, II=industry, III-V=services
362
+ })
363
+
364
+ # Full PGDAS-D with multiple activities
365
+ resultado = pipeline.calcular_pgdas({
366
+ "periodo": "2024-01",
367
+ "rbt12": 600000,
368
+ "atividades": [
369
+ {"tipo": "comercio", "receita": 30000},
370
+ {"tipo": "servicos_advocacia", "receita": 20000},
371
+ ],
372
+ })
373
+ ```
374
+
375
+ Covers all 5 annexes (6 revenue brackets each), Fator R calculation for Annex III vs V, and MEI fixed amounts.
376
+
377
+ ---
378
+
379
+ ## SPED / DFe Generators
380
+
381
+ ### EFD ICMS/IPI (`src/generators/efd_icms_ipi.py`)
382
+
383
+ Layout version 017. Generates all mandatory blocks:
384
+
385
+ | Block | Contents |
386
+ |-------|----------|
387
+ | 0 | Establishment identification, participants (0150), products (0200) |
388
+ | C | NF-e records (C100, C110, C170, C190) |
389
+ | E | ICMS settlement (E110), IPI settlement (E520) |
390
+ | G | CIAP — ICMS credits on permanent assets (G001, G110) |
391
+ | H | Physical inventory (H005, H010) |
392
+ | K | Production and stock control (K100, K200) — industrial companies |
393
+ | 1 | Other information |
394
+ | 9 | File control and closing |
395
+
396
+ ```python
397
+ from src.generators.efd_icms_ipi import GeradorEFDICMSIPI
398
+ gerador = GeradorEFDICMSIPI(periodo)
399
+ caminho = gerador.gerar("./output")
400
+ ```
401
+
402
+ ### EFD Contribuições (`src/generators/efd_contribuicoes.py`)
403
+
404
+ Layout version 006. PIS/COFINS digital bookkeeping.
405
+
406
+ Blocks: 0, C (documents), M (PIS/COFINS settlement — M100, M200, M600), 1, 9.
407
+
408
+ ### ECD (`src/generators/ecd.py`)
409
+
410
+ Layout version 010. Digital accounting bookkeeping.
411
+
412
+ Includes default chart of accounts (50+ accounts), journal entries (I200/I250), balance sheet (J150).
413
+
414
+ ### ECF (`src/generators/ecf.py`)
415
+
416
+ Layout version 009. Replaces the old DIPJ declaration.
417
+
418
+ | Block | Contents |
419
+ |-------|----------|
420
+ | 0 | Tax parameters (0010), accountant (0930) |
421
+ | L | LALUR/LACS adjustments (Lucro Real) |
422
+ | N | IRPJ/CSLL calculation (N620, N630) |
423
+ | P | Lucro Presumido quarterly breakdown |
424
+ | Y | Partner information (Y600) |
425
+
426
+ ### NF-e (`src/generators/nfe_xml.py`)
427
+
428
+ NF-e XML v4.00, model 55. Full document with all fiscal groups:
429
+
430
+ - `ide` — identification with 44-digit access key (Módulo 11)
431
+ - `emit` / `dest` — emitter and recipient
432
+ - `det` — items with ICMS (CST 000–090), IPI, PIS, COFINS per item
433
+ - `total` / `transp` / `pag` — totals, transport, payment
434
+ - `AssinadorNFe` — RSA-SHA1 XMLDSig using PKCS#12 certificate
435
+
436
+ ```python
437
+ from src.generators.nfe_xml import GeradorNFeXML, AssinadorNFe
438
+ gerador = GeradorNFeXML(emitente, destinatario, itens)
439
+ xml = gerador.gerar_xml()
440
+ xml_assinado = AssinadorNFe(cert_path, cert_password).assinar(xml)
441
+ ```
442
+
443
+ ### NFC-e (`src/generators/nfce_xml.py`)
444
+
445
+ NFC-e XML v4.00, model 65. Consumer invoice for POS/retail. Optional CPF identification, QR Code URL.
446
+
447
+ ### CT-e (`src/generators/cte.py`)
448
+
449
+ CT-e XML v4.00, model 57. Freight transport fiscal document.
450
+
451
+ - Road modal (rodoviário) with RNTRC registration
452
+ - 44-digit access key (Módulo 11, model 57)
453
+ - ICMS calculation on freight service
454
+ - Referenced NF-e documents
455
+
456
+ ### MDF-e (`src/generators/mdfe.py`)
457
+
458
+ MDF-e XML v3.00, model 58. Groups CT-e and NF-e documents in transport routes.
459
+
460
+ - Unload municipalities with referenced documents
461
+ - Driver registration
462
+ - Cargo insurance data
463
+ - 44-digit access key (Módulo 11, model 58)
464
+
465
+ ### EFD-Reinf (`src/generators/efd_reinf.py`)
466
+
467
+ XML events for the EFD-Reinf (withholdings and social security information).
468
+
469
+ | Event | Description |
470
+ |-------|-------------|
471
+ | R-1000 | Employer registration |
472
+ | R-2010 | Services taken — INSS withholding |
473
+ | R-2020 | Services provided — INSS withholding |
474
+ | R-2060 | CPRB (payroll tax exemption) |
475
+ | R-2099 | Period closing |
476
+
477
+ ### e-Social (`src/generators/esocial.py`)
478
+
479
+ XML events for Brazil's digital labor bookkeeping system.
480
+
481
+ | Event | Description |
482
+ |-------|-------------|
483
+ | S-1000 | Employer data table |
484
+ | S-1010 | Payroll items (rubricas) table — 16 standard CLT items |
485
+ | S-1200 | Monthly payroll (remuneração) |
486
+ | S-1299 | Monthly payroll closing |
487
+ | S-2200 | Employee admission |
488
+ | S-2299 | Employment termination (rescisão) |
489
+
490
+ ### DCTF (`src/generators/dctf.py`)
491
+
492
+ XML for PGD DCTF Web. Monthly declaration of federal tax debits and credits.
493
+
494
+ ```python
495
+ from src.generators.dctf import montar_dctf_do_periodo
496
+ gerador = montar_dctf_do_periodo(
497
+ empresa=empresa,
498
+ periodo="2024-01",
499
+ valor_irpj=Decimal("5000"),
500
+ valor_csll=Decimal("1800"),
501
+ valor_pis=Decimal("650"),
502
+ valor_cofins=Decimal("3000"),
503
+ )
504
+ caminho = gerador.salvar("./output")
505
+ print(gerador.relatorio_resumo())
506
+ ```
507
+
508
+ ---
509
+
510
+ ## Annual Declarations
511
+
512
+ ### DIRF (`src/generators/dirf.py`)
513
+
514
+ Annual declaration of income tax withheld at source (IRRF). Text file format for PGD DIRF.
515
+
516
+ **Deadline:** Last business day of February.
517
+
518
+ ```python
519
+ from src.generators.dirf import GeradorDIRF, BeneficiarioDIRF, ResponsavelDIRF
520
+ gerador = GeradorDIRF(empresa, ano_calendario=2024, beneficiarios=[...], responsavel=...)
521
+ caminho = gerador.salvar("./output")
522
+ ```
523
+
524
+ ### DEFIS (`src/generators/defis.py`)
525
+
526
+ Annual fiscal information declaration for Simples Nacional companies. XML format for the Simples Nacional portal.
527
+
528
+ **Deadline:** March 31 of the following year.
529
+
530
+ ```python
531
+ from src.generators.defis import GeradorDEFIS, ReceitaMensalDEFIS, SocioDEFIS
532
+ gerador = GeradorDEFIS(empresa, ano_calendario=2024, receitas_mensais=[...], socios=[...])
533
+ xml = gerador.gerar_xml()
534
+ print(gerador.relatorio_resumo())
535
+ ```
536
+
537
+ ### DeSTDA (`src/generators/destda.py`)
538
+
539
+ Monthly declaration of ICMS-ST, DIFAL, and tax anticipation for Simples Nacional companies.
540
+
541
+ **Deadline:** 20th of the following month.
542
+
543
+ ```python
544
+ from src.generators.destda import GeradorDeSTDA, OperacaoSTDeSTDA
545
+ ops = [
546
+ OperacaoSTDeSTDA("SP", "RJ", "ST", base_calculo=Decimal("10000"),
547
+ aliquota=Decimal("18"), valor_imposto=Decimal("1800")),
548
+ OperacaoSTDeSTDA("SP", "MG", "DIFAL", base_calculo=Decimal("5000"),
549
+ aliquota=Decimal("6"), valor_imposto=Decimal("300")),
550
+ ]
551
+ gerador = GeradorDeSTDA(empresa, "2024-01", ops)
552
+ print(gerador.relatorio_resumo())
553
+ ```
554
+
555
+ ### GIA / GIA-ST — São Paulo (`src/generators/gia.py`)
556
+
557
+ Monthly ICMS information and settlement guide for São Paulo state. AIE pipe-delimited file format for SEFAZ-SP / SCANC.
558
+
559
+ **Deadline:** 20th of the following month (may vary by revenue tier).
560
+
561
+ ```python
562
+ from src.generators.gia import GeradorGIA, ApuracaoGIA, ApuracaoGIAST
563
+ apuracao = ApuracaoGIA(
564
+ debitos_operacoes_proprias=Decimal("50000"),
565
+ creditos_entradas=Decimal("30000"),
566
+ )
567
+ gerador = GeradorGIA(empresa, "2024-01", apuracao, apuracoes_st=[
568
+ ApuracaoGIAST("MG", Decimal("20000"), Decimal("12"), Decimal("2400")),
569
+ ])
570
+ caminho = gerador.salvar("./output") # → GIA_CNPJ_2024-01.aie
571
+ ```
572
+
573
+ ---
574
+
575
+ ## SEFAZ Transmitter
576
+
577
+ ### NF-e (`src/transmitters/receita_federal.py`)
578
+
579
+ ```python
580
+ from src.transmitters.receita_federal import TransmissorNFe
581
+
582
+ transmissor = TransmissorNFe(uf="SP", ambiente="2") # ambiente 2=homologação
583
+
584
+ # Check service availability
585
+ status = transmissor.verificar_status_servico()
586
+
587
+ # Submit NF-e for authorization
588
+ resultado = transmissor.autorizar_nfe(xml_assinado)
589
+ print(resultado.protocolo) # authorization protocol
590
+
591
+ # Cancel NF-e
592
+ resultado = transmissor.cancelar_nfe(chave, protocolo, justificativa)
593
+ ```
594
+
595
+ SOAP endpoints: SP (SEFAZ-SP), SVRS (other states), SVAN (national contingency).
596
+
597
+ ### SPED Local Validator
598
+
599
+ ```python
600
+ from src.transmitters.receita_federal import TransmissorSPEDLocal, ValidadorArquivoSPED
601
+
602
+ # Validates required records and line counts
603
+ valido, erros = ValidadorArquivoSPED().validar(caminho_arquivo)
604
+
605
+ # Prepares file for PGE (Java program) transmission
606
+ resultado = TransmissorSPEDLocal("./output").preparar_efd_icms_ipi(caminho)
607
+ ```
608
+
609
+ > **Note:** EFD ICMS/IPI, EFD Contribuições, and ECD files must be transmitted through the Receita Federal's local PGE/Validador program — direct HTTP upload is not supported for SPED. Only NF-e uses direct SEFAZ SOAP webservices.
610
+
611
+ ---
612
+
613
+ ## Training the Model
614
+
615
+ The `TransformerFiscal` ships with random weights. Use `TrainerFiscal` to train it on the built-in dataset (173 labeled examples) or your own data.
616
+
617
+ ```python
618
+ from src import PipelineFiscal
619
+
620
+ pipeline = PipelineFiscal()
621
+
622
+ # Train with built-in examples
623
+ history = pipeline.treinar(
624
+ epochs=50, # early stopping kicks in before if val_loss plateaus
625
+ caminho_saida="./checkpoints/fiscal_llm.pt",
626
+ )
627
+
628
+ # Load trained model
629
+ pipeline = PipelineFiscal(caminho_modelo="./checkpoints/fiscal_llm.pt")
630
+
631
+ # Evaluate per-class accuracy
632
+ from src.models.trainer import TrainerFiscal, EXEMPLOS_CLASSIFICACAO
633
+ from src.models.fiscal_llm import TokenizadorFiscal, TransformerFiscal, CLASSES_OBRIGACAO
634
+
635
+ tokenizador = TokenizadorFiscal()
636
+ trainer = TrainerFiscal(pipeline.modelo, tokenizador)
637
+ metricas = trainer.avaliar_por_classe(EXEMPLOS_CLASSIFICACAO)
638
+ print(f"Overall accuracy: {metricas['acuracia_geral']:.1%}")
639
+ ```
640
+
641
+ **Training configuration:**
642
+
643
+ | Parameter | Default |
644
+ |-----------|---------|
645
+ | Epochs | 50 |
646
+ | Optimizer | AdamW |
647
+ | Learning rate | 3e-4 (OneCycleLR) |
648
+ | Batch size | 16 |
649
+ | Gradient clipping | 1.0 |
650
+ | Val split | 15% |
651
+ | Early stopping patience | 8 epochs |
652
+ | Class weights | Enabled (inverse frequency) |
653
+
654
+ ---
655
+
656
+ ## Running Tests
657
+
658
+ ```bash
659
+ pip install pytest pytest-asyncio
660
+ python -m pytest tests/ -v
661
+ ```
662
+
663
+ **117 tests** covering all components:
664
+
665
+ | Module | Tests |
666
+ |--------|-------|
667
+ | ICMS calculator | 9 |
668
+ | IPI calculator | 6 |
669
+ | PIS/COFINS calculator | 6 |
670
+ | IRPJ/CSLL calculator | 7 |
671
+ | ISS calculator | 5 |
672
+ | Simples Nacional calculator | 9 |
673
+ | SPED writer | 3 |
674
+ | EFD ICMS/IPI (incl. Blocks G+K) | 10 |
675
+ | EFD Contribuições | 3 |
676
+ | ECD | 5 |
677
+ | ECF | 3 |
678
+ | NF-e | 6 |
679
+ | NFC-e | 4 |
680
+ | CT-e | 4 |
681
+ | MDF-e | 4 |
682
+ | EFD-Reinf | 3 |
683
+ | e-Social | 3 |
684
+ | DCTF | 5 |
685
+ | DIRF | 4 |
686
+ | DEFIS | 5 |
687
+ | DeSTDA | 5 |
688
+ | GIA | 5 |
689
+
690
+ ---
691
+
692
+ ## Fiscal Calendar
693
+
694
+ | Obligation | Frequency | Deadline |
695
+ |-----------|-----------|----------|
696
+ | DAS (Simples Nacional) | Monthly | Day 20 of following month |
697
+ | DeSTDA (ICMS-ST Simples) | Monthly | Day 20 of following month |
698
+ | GIA-SP | Monthly | Day 20 of following month |
699
+ | EFD ICMS/IPI | Monthly | 15th business day of following month |
700
+ | DCTF | Monthly | 15th business day of 2nd following month |
701
+ | EFD Contribuições | Monthly | 10th business day of 2nd following month |
702
+ | EFD-Reinf | Monthly | Day 15 of following month |
703
+ | e-Social (payroll) | Monthly | Day 7 of following month |
704
+ | ECD | Annual | Last business day of June |
705
+ | DEFIS (Simples Nacional) | Annual | March 31 |
706
+ | ECF | Annual | Last business day of July |
707
+ | DIRF | Annual | Last business day of February |
708
+
709
+ ---
710
+
711
+ ---
712
+
713
+ # Português Brasileiro
714
+
715
+ ## Visão Geral
716
+
717
+ O **LLM Fiscal Brasileiro** é uma biblioteca Python 3.12 que combina um **Transformer PyTorch** customizado com um conjunto completo de ferramentas de compliance tributário brasileiro. O sistema é projetado para ser consumido como biblioteca por qualquer aplicação — não há CLI ou interface gráfica embutida.
718
+
719
+ O sistema cobre o ciclo de vida completo das obrigações fiscais brasileiras:
720
+
721
+ - **Classificação de intenção** de consultas fiscais em linguagem natural (16 classes de obrigações)
722
+ - **RAG (Geração Aumentada por Recuperação)** com 25 documentos de conhecimento fiscal indexados
723
+ - **Calculadoras tributárias** para todos os principais tributos brasileiros (ICMS, IPI, PIS/COFINS, IRPJ/CSLL, ISS, Simples Nacional)
724
+ - **Geradores de arquivos SPED** para todas as obrigações de escrituração digital federal
725
+ - **Geradores de documentos eletrônicos** (NF-e, NFC-e, CT-e, MDF-e) com assinatura digital
726
+ - **Transmissor SOAP SEFAZ** para autorização de NF-e
727
+
728
+ O ponto de entrada único é o `PipelineFiscal`, que orquestra todos os componentes.
729
+
730
+ ---
731
+
732
+ ## Arquitetura
733
+
734
+ ```
735
+ ┌──────────────────────────────────────────────────────────────────┐
736
+ │ PipelineFiscal │
737
+ │ (src/models/fiscal_llm.py) │
738
+ │ │
739
+ │ ┌─────────────────────┐ ┌──────────────────────────────────┐ │
740
+ │ │ TransformerFiscal │ │ BancoEmbeddingsFiscais (RAG) │ │
741
+ │ │ PyTorch encoder │ │ 25 documentos de conhecimento │ │
742
+ │ │ 4 camadas, d=256 │ │ busca por similaridade cosseno │ │
743
+ │ │ 8 cabeças, Pre-LN │ └──────────────────────────────────┘ │
744
+ │ └─────────────────────┘ │
745
+ │ ┌─────────────────────────────────────────────────────────────┐ │
746
+ │ │ Classificação de Intenção (16 classes) │ │
747
+ │ └─────────────────────────────────────────────────────────────┘ │
748
+ │ │
749
+ │ ┌──────────────────┐ ┌──────────────────┐ ┌───────────────┐ │
750
+ │ │ Calculadoras │ │ Geradores SPED │ │ DFe / XML │ │
751
+ │ │ ICMS · IPI │ │ EFD ICMS/IPI │ │ NF-e · NFC-e │ │
752
+ │ │ PIS/COFINS │ │ EFD Contribu. │ │ CT-e · MDF-e │ │
753
+ │ │ IRPJ/CSLL · ISS │ │ ECD · ECF │ │ EFD-Reinf │ │
754
+ │ │ Simples Nac. │ │ DCTF · GIA │ │ e-Social │ │
755
+ │ └──────────────────┘ │ DIRF · DEFIS │ └───────────────┘ │
756
+ │ │ DeSTDA │ │
757
+ │ └──────────────────┘ │
758
+ └──────────────────────────────────────────────────────────────────┘
759
+ ```
760
+
761
+ **Decisões de design:**
762
+ - O LLM usa tokenização em nível de caractere — sem dependência de tokenizador externo.
763
+ - O RAG roda inteiramente em memória usando similaridade cosseno nos embeddings CLS.
764
+ - Todos os valores monetários usam `Decimal` Python com `ROUND_HALF_UP` — zero aritmética de ponto flutuante.
765
+ - Arquivos SPED são pipe-delimitados (`|REGISTRO|CAMPO1|`) em UTF-8, seguindo a especificação oficial da Receita Federal.
766
+ - NF-e/CT-e/MDF-e usam XML v4.00 com assinaturas digitais RSA-SHA1 XMLDSig via biblioteca `cryptography`.
767
+
768
+ ---
769
+
770
+ ## Estrutura do Projeto
771
+
772
+ ```
773
+ llm-speed/
774
+ ├── src/
775
+ │ ├── __init__.py # Exporta PipelineFiscal
776
+ │ ├── fiscal/
777
+ │ │ ├── entities.py # Modelos Pydantic v2 (Empresa, NotaFiscal, …)
778
+ │ │ └── constants.py # Alíquotas, tabelas CST, CFOPs, prazos
779
+ │ ├── calculators/
780
+ │ │ ├── icms.py # ICMS (próprio + ST + DIFAL + FCP)
781
+ │ │ ├── ipi.py # IPI (alíquotas TIPI por capítulo NCM)
782
+ │ │ ├── pis_cofins.py # PIS/COFINS (cumulativo + não cumulativo + retenção)
783
+ │ │ ├── irpj_csll.py # IRPJ/CSLL (Lucro Real + Lucro Presumido + estimativa)
784
+ │ │ ├── iss.py # ISS (LC 116/2003 + anexos Simples Nacional)
785
+ │ │ └── simples_nacional.py # Simples Nacional (5 anexos, Fator R, PGDAS-D, MEI)
786
+ │ ├── generators/
787
+ │ │ ├── sped_writer.py # Escritor base SPED pipe-delimitado
788
+ │ │ ├── efd_icms_ipi.py # EFD ICMS/IPI (blocos 0,C,E,G,H,K,1,9)
789
+ │ │ ├── efd_contribuicoes.py # EFD Contribuições PIS/COFINS (blocos 0,C,M,1,9)
790
+ │ │ ├── ecd.py # ECD — Escrituração Contábil Digital
791
+ │ │ ├── ecf.py # ECF — Escrituração Contábil Fiscal (LALUR/LACS)
792
+ │ │ ├── nfe_xml.py # NF-e XML v4.00 (modelo 55) + assinatura digital
793
+ │ │ ├── nfce_xml.py # NFC-e XML v4.00 (modelo 65, consumidor/PDV)
794
+ │ │ ├── cte.py # CT-e XML v4.00 (modelo 57, transporte)
795
+ │ │ ├── mdfe.py # MDF-e XML v3.00 (manifesto, modelo 58)
796
+ │ │ ├── efd_reinf.py # EFD-Reinf XML eventos (R-1000…R-2099)
797
+ │ │ ├── esocial.py # e-Social XML eventos (S-1000…S-1299, S-2200, S-2299)
798
+ │ │ ├── dctf.py # DCTF XML (declaração de débitos tributários federais)
799
+ │ │ ├── dirf.py # DIRF arquivo texto (declaração anual IRRF)
800
+ │ │ ├── defis.py # DEFIS XML (declaração anual Simples Nacional)
801
+ │ │ ├── destda.py # DeSTDA XML (ICMS-ST/DIFAL mensal Simples Nacional)
802
+ │ │ └── gia.py # GIA/GIA-ST arquivo AIE (ICMS mensal São Paulo)
803
+ │ ├── models/
804
+ │ │ ├── fiscal_llm.py # TransformerFiscal + RAG + PipelineFiscal
805
+ │ │ └── trainer.py # TrainerFiscal (173 exemplos, early stopping, pesos por classe)
806
+ │ └── transmitters/
807
+ │ └── receita_federal.py # Transmissor NF-e SOAP SEFAZ + validador SPED local
808
+ ├── tests/
809
+ │ ├── test_calculators.py # 43 testes das calculadoras tributárias
810
+ │ └── test_generators.py # 74 testes dos geradores
811
+ ├── pyproject.toml
812
+ └── requirements.txt
813
+ ```
814
+
815
+ ---
816
+
817
+ ## Instalação
818
+
819
+ **Requisitos:** Python 3.12+, pip
820
+
821
+ ```bash
822
+ # Clonar o repositório
823
+ git clone <repo-url>
824
+ cd llm-speed
825
+
826
+ # Criar e ativar ambiente virtual
827
+ python -m venv venv
828
+ source venv/bin/activate # Linux/macOS
829
+ # venv\Scripts\activate # Windows
830
+
831
+ # Instalar dependências
832
+ pip install -r requirements.txt
833
+ ```
834
+
835
+ **Dependências principais:**
836
+
837
+ | Pacote | Finalidade |
838
+ |--------|-----------|
839
+ | `torch>=2.3.0` | Modelo TransformerFiscal + treinamento |
840
+ | `pydantic>=2.7.0` | Modelos de dados fiscais validados |
841
+ | `cryptography>=42.0.0` | Assinatura digital NF-e/CT-e (RSA-SHA1) |
842
+ | `lxml>=5.2.0` | Canonicalização C14N para XMLDSig |
843
+ | `httpx>=0.27.0` | Cliente HTTP SOAP SEFAZ |
844
+ | `zeep>=4.2.1` | Auxiliares para envelope SOAP |
845
+ | `python-dateutil>=2.9.0` | Cálculos de calendário fiscal brasileiro |
846
+
847
+ ---
848
+
849
+ ## Início Rápido
850
+
851
+ ```python
852
+ from src import PipelineFiscal
853
+
854
+ # Instanciar o pipeline LLM (pesos aleatórios até ser treinado)
855
+ pipeline = PipelineFiscal(diretorio_saida="./output")
856
+
857
+ # --- Processamento em linguagem natural ---
858
+ resultado = pipeline.processar(
859
+ "calcule o ICMS de uma venda",
860
+ {"valor_mercadoria": 10000, "aliquota": 18, "uf_origem": "SP", "uf_destino": "RJ"}
861
+ )
862
+ print(resultado.resumo())
863
+ # [calcular_icms]
864
+ # base_calculo: R$ 10.000,00
865
+ # valor_icms: R$ 1.800,00
866
+ # valor_total_icms: R$ 1.800,00
867
+
868
+ # --- Cálculo direto de tributos ---
869
+ r = pipeline.calcular_pis_cofins({
870
+ "valor": 100000,
871
+ "regime": "lucro_presumido",
872
+ })
873
+ print(r["pis_a_recolher"]) # 650.00
874
+ print(r["cofins_a_recolher"]) # 3000.00
875
+
876
+ # --- Gerar obrigações SPED do período ---
877
+ from src.fiscal.entities import PeriodoApuracao, Empresa, ...
878
+ periodo = PeriodoApuracao(...)
879
+ arquivos = pipeline.gerar_obrigacoes(periodo)
880
+ # Retorna: {"EFD_ICMS_IPI": ResultadoFiscal, "EFD_CONTRIBUICOES": ..., ...}
881
+
882
+ # --- Verificar status SEFAZ ---
883
+ status = pipeline.verificar_sefaz(uf="SP")
884
+ print(status["mensagem"])
885
+ ```
886
+
887
+ ---
888
+
889
+ ## Modelo LLM
890
+
891
+ ### TransformerFiscal
892
+
893
+ Encoder Transformer compacto treinado para classificação de intenção fiscal brasileira.
894
+
895
+ | Parâmetro | Valor |
896
+ |-----------|-------|
897
+ | Arquitetura | Transformer Encoder (Pre-LN) |
898
+ | Camadas | 4 |
899
+ | d_model | 256 |
900
+ | Cabeças de atenção | 8 |
901
+ | Dimensão FFN | 1.024 |
902
+ | Tokenizador | Nível de caractere (vocab ~200 chars) |
903
+ | Comprimento máximo de sequência | 1.024 tokens |
904
+ | Classes de saída | 16 tipos de obrigação fiscal |
905
+
906
+ **16 Classes de Intenção:**
907
+
908
+ | Classe | Descrição |
909
+ |--------|-----------|
910
+ | `EFD_ICMS_IPI` | Gerar EFD ICMS/IPI |
911
+ | `EFD_CONTRIBUICOES` | Gerar EFD Contribuições (PIS/COFINS) |
912
+ | `ECD` | Gerar Escrituração Contábil Digital |
913
+ | `ECF` | Gerar Escrituração Contábil Fiscal |
914
+ | `NFe` | Emitir/cancelar NF-e ou NFC-e |
915
+ | `NFSe` | Emitir NFS-e (nota de serviço municipal) |
916
+ | `CTe` | Gerar CT-e (conhecimento de transporte) |
917
+ | `eSocial` | Gerar eventos e-Social (folha/admissão) |
918
+ | `EFD_REINF` | Gerar eventos EFD-Reinf (retenções) |
919
+ | `DCTF` | Gerar DCTF (débitos tributários federais) |
920
+ | `PGDAS` | Calcular DAS Simples Nacional / PGDAS-D |
921
+ | `calculo_icms` | Calcular ICMS de uma operação |
922
+ | `calculo_ipi` | Calcular IPI de produto industrializado |
923
+ | `calculo_pis_cofins` | Calcular PIS e COFINS sobre receitas |
924
+ | `calculo_irpj_csll` | Calcular IRPJ e CSLL (tributos corporativos) |
925
+ | `calculo_iss` | Calcular ISS (imposto municipal sobre serviços) |
926
+
927
+ ### Base de Conhecimento RAG
928
+
929
+ `BancoEmbeddingsFiscais` indexa 25 documentos de conhecimento fiscal cobrindo todas as principais obrigações, alíquotas, prazos e legislação. A recuperação usa similaridade cosseno nos embeddings do token CLS.
930
+
931
+ ```python
932
+ # Acesso direto ao RAG
933
+ pipeline.rag.buscar("prazo EFD ICMS IPI", top_k=3)
934
+ # Retorna: [(texto, score_similaridade), ...]
935
+ ```
936
+
937
+ ---
938
+
939
+ ## Calculadoras Tributárias
940
+
941
+ Todas as calculadoras estão disponíveis via `PipelineFiscal` ou importadas de `src.calculators.*`. Todos os valores monetários usam `Decimal` com `ROUND_HALF_UP`.
942
+
943
+ ### ICMS (`src/calculators/icms.py`)
944
+
945
+ ```python
946
+ resultado = pipeline.calcular_icms({
947
+ "valor_mercadoria": 10000,
948
+ "aliquota": 18, # alíquota interna (%)
949
+ "uf_origem": "SP",
950
+ "uf_destino": "RJ",
951
+ "frete": 500,
952
+ "cst": "000", # CST: 000=tributado, 020=redução, 040=isento, 060=ST
953
+ "calcular_difal": False,
954
+ "consumidor_final": False,
955
+ # Parâmetros opcionais ST:
956
+ # "calcular_st": True, "mva": 40, "aliq_interna_destino": 18
957
+ })
958
+ ```
959
+
960
+ Suporta: CST 000/010/020/030/040/041/050/051/060/070, ICMS-ST com MVA, FCP (Fundo de Combate à Pobreza), DIFAL (EC 87/2015).
961
+
962
+ ### IPI (`src/calculators/ipi.py`)
963
+
964
+ ```python
965
+ resultado = pipeline.calcular_ipi({
966
+ "valor_produtos": 5000,
967
+ "aliquota": 10,
968
+ "cst": "50", # 50=tributado, 52=isento, 54=suspenso
969
+ "frete": 200,
970
+ })
971
+ ```
972
+
973
+ Inclui alíquotas TIPI por capítulo NCM (0% farmacêuticos, 25% veículos, 300% cigarro).
974
+
975
+ ### PIS/COFINS (`src/calculators/pis_cofins.py`)
976
+
977
+ ```python
978
+ resultado = pipeline.calcular_pis_cofins({
979
+ "valor": 100000,
980
+ "regime": "lucro_real", # ou "lucro_presumido"
981
+ "receitas": [
982
+ {"descricao": "Vendas", "valor": 100000, "cst_pis": "01", "cst_cofins": "01"}
983
+ ],
984
+ })
985
+ ```
986
+
987
+ | Regime | PIS | COFINS |
988
+ |--------|-----|--------|
989
+ | Lucro Presumido (cumulativo) | 0,65% | 3,00% |
990
+ | Lucro Real (não cumulativo) | 1,65% | 7,60% |
991
+
992
+ Suporta créditos sobre compras, energia, aluguéis, depreciação (Leis 10.637/2002 e 10.833/2003).
993
+
994
+ ### IRPJ / CSLL (`src/calculators/irpj_csll.py`)
995
+
996
+ ```python
997
+ resultado = pipeline.calcular_irpj_csll({
998
+ "valor": 500000, # Lucro Real: lucro líquido / Lucro Presumido: receita bruta
999
+ "regime": "lucro_presumido", # ou "lucro_real"
1000
+ "atividade": "venda_mercadorias", # ou "servicos_em_geral", "intermediacao"
1001
+ })
1002
+ ```
1003
+
1004
+ | Regra | Valor |
1005
+ |-------|-------|
1006
+ | IRPJ alíquota base | 15% |
1007
+ | IRPJ adicional | +10% sobre lucro > R$ 20.000/mês |
1008
+ | CSLL alíquota | 9% (geral) / 15% (financeiras) |
1009
+ | Lucro Presumido — comércio/indústria | 8% da receita |
1010
+ | Lucro Presumido — serviços | 32% da receita |
1011
+ | Limite compensação prejuízos | 30% do lucro tributável |
1012
+
1013
+ ### ISS (`src/calculators/iss.py`)
1014
+
1015
+ ```python
1016
+ resultado = pipeline.calcular_iss({
1017
+ "valor_servico": 10000,
1018
+ "codigo_servico": "17", # código da LC 116/2003
1019
+ "aliquota": 3, # alíquota municipal (2%–5%)
1020
+ "retencao_fonte": True,
1021
+ })
1022
+ ```
1023
+
1024
+ ### Simples Nacional (`src/calculators/simples_nacional.py`)
1025
+
1026
+ ```python
1027
+ # Cálculo do DAS para uma atividade
1028
+ resultado = pipeline.calcular_simples({
1029
+ "receita_mes": 50000,
1030
+ "rbt12": 600000, # receita acumulada 12 meses
1031
+ "anexo": "I", # I=comércio, II=indústria, III-V=serviços
1032
+ })
1033
+
1034
+ # PGDAS-D completo com múltiplas atividades
1035
+ resultado = pipeline.calcular_pgdas({
1036
+ "periodo": "2024-01",
1037
+ "rbt12": 600000,
1038
+ "atividades": [
1039
+ {"tipo": "comercio", "receita": 30000},
1040
+ {"tipo": "servicos_advocacia", "receita": 20000},
1041
+ ],
1042
+ })
1043
+ ```
1044
+
1045
+ Cobre todos os 5 anexos (6 faixas cada), cálculo do Fator R para Anexo III vs V, e valores fixos do MEI.
1046
+
1047
+ ---
1048
+
1049
+ ## Geradores SPED / DFe
1050
+
1051
+ ### EFD ICMS/IPI (`src/generators/efd_icms_ipi.py`)
1052
+
1053
+ Layout versão 017. Gera todos os blocos obrigatórios:
1054
+
1055
+ | Bloco | Conteúdo |
1056
+ |-------|----------|
1057
+ | 0 | Identificação do estabelecimento, participantes (0150), produtos (0200) |
1058
+ | C | Registros NF-e (C100, C110, C170, C190) |
1059
+ | E | Apuração ICMS (E110), apuração IPI (E520) |
1060
+ | G | CIAP — crédito ICMS sobre ativo permanente (G001, G110) |
1061
+ | H | Inventário físico (H005, H010) |
1062
+ | K | Controle de produção e estoque (K100, K200) — indústrias |
1063
+ | 1 | Outras informações |
1064
+ | 9 | Controle e encerramento do arquivo |
1065
+
1066
+ ```python
1067
+ from src.generators.efd_icms_ipi import GeradorEFDICMSIPI
1068
+ gerador = GeradorEFDICMSIPI(periodo)
1069
+ caminho = gerador.gerar("./output")
1070
+ ```
1071
+
1072
+ ### EFD Contribuições (`src/generators/efd_contribuicoes.py`)
1073
+
1074
+ Layout versão 006. Escrituração digital de PIS/COFINS.
1075
+
1076
+ Blocos: 0, C (documentos), M (apuração PIS/COFINS — M100, M200, M600), 1, 9.
1077
+
1078
+ ### ECD (`src/generators/ecd.py`)
1079
+
1080
+ Layout versão 010. Escrituração contábil digital.
1081
+
1082
+ Inclui plano de contas padrão (50+ contas), lançamentos (I200/I250), balanço (J150).
1083
+
1084
+ ### ECF (`src/generators/ecf.py`)
1085
+
1086
+ Layout versão 009. Substitui a DIPJ.
1087
+
1088
+ | Bloco | Conteúdo |
1089
+ |-------|----------|
1090
+ | 0 | Parâmetros fiscais (0010), contador (0930) |
1091
+ | L | Ajustes LALUR/LACS (Lucro Real) |
1092
+ | N | Cálculo IRPJ/CSLL (N620, N630) |
1093
+ | P | Lucro Presumido por trimestre |
1094
+ | Y | Quadro societário (Y600) |
1095
+
1096
+ ### NF-e (`src/generators/nfe_xml.py`)
1097
+
1098
+ NF-e XML v4.00, modelo 55. Documento completo com todos os grupos fiscais:
1099
+
1100
+ - `ide` — identificação com chave de acesso 44 dígitos (Módulo 11)
1101
+ - `emit` / `dest` — emitente e destinatário
1102
+ - `det` — itens com ICMS (CST 000–090), IPI, PIS, COFINS por item
1103
+ - `total` / `transp` / `pag` — totais, transporte, pagamento
1104
+ - `AssinadorNFe` — assinatura RSA-SHA1 XMLDSig com certificado PKCS#12
1105
+
1106
+ ```python
1107
+ from src.generators.nfe_xml import GeradorNFeXML, AssinadorNFe
1108
+ gerador = GeradorNFeXML(emitente, destinatario, itens)
1109
+ xml = gerador.gerar_xml()
1110
+ xml_assinado = AssinadorNFe(cert_path, cert_password).assinar(xml)
1111
+ ```
1112
+
1113
+ ### NFC-e (`src/generators/nfce_xml.py`)
1114
+
1115
+ NFC-e XML v4.00, modelo 65. Nota do consumidor para PDV/varejo. Identificação do CPF opcional, URL QR Code.
1116
+
1117
+ ### CT-e (`src/generators/cte.py`)
1118
+
1119
+ CT-e XML v4.00, modelo 57. Documento fiscal para transporte de carga.
1120
+
1121
+ - Modal rodoviário com registro RNTRC
1122
+ - Chave de acesso 44 dígitos (Módulo 11, modelo 57)
1123
+ - Cálculo do ICMS sobre o serviço de transporte
1124
+ - Documentos NF-e referenciados
1125
+
1126
+ ### MDF-e (`src/generators/mdfe.py`)
1127
+
1128
+ MDF-e XML v3.00, modelo 58. Agrupa CT-e e NF-e em rotas de transporte.
1129
+
1130
+ - Municípios de descarga com documentos referenciados
1131
+ - Cadastro de condutores
1132
+ - Dados do seguro de carga
1133
+ - Chave de acesso 44 dígitos (Módulo 11, modelo 58)
1134
+
1135
+ ### EFD-Reinf (`src/generators/efd_reinf.py`)
1136
+
1137
+ Eventos XML para o EFD-Reinf (retenções e informações previdenciárias).
1138
+
1139
+ | Evento | Descrição |
1140
+ |--------|-----------|
1141
+ | R-1000 | Cadastro do empregador |
1142
+ | R-2010 | Serviços tomados — retenção INSS |
1143
+ | R-2020 | Serviços prestados — retenção INSS |
1144
+ | R-2060 | CPRB (contribuição previdenciária sobre receita bruta) |
1145
+ | R-2099 | Fechamento do período |
1146
+
1147
+ ### e-Social (`src/generators/esocial.py`)
1148
+
1149
+ Eventos XML para o sistema de escrituração digital trabalhista brasileiro.
1150
+
1151
+ | Evento | Descrição |
1152
+ |--------|-----------|
1153
+ | S-1000 | Dados do empregador |
1154
+ | S-1010 | Tabela de rubricas — 16 itens CLT padrão |
1155
+ | S-1200 | Remuneração mensal (folha de pagamento) |
1156
+ | S-1299 | Fechamento da folha mensal |
1157
+ | S-2200 | Admissão de empregado |
1158
+ | S-2299 | Desligamento (rescisão contratual) |
1159
+
1160
+ ### DCTF (`src/generators/dctf.py`)
1161
+
1162
+ XML para o PGD DCTF Web. Declaração mensal de débitos e créditos tributários federais.
1163
+
1164
+ ```python
1165
+ from src.generators.dctf import montar_dctf_do_periodo
1166
+ gerador = montar_dctf_do_periodo(
1167
+ empresa=empresa,
1168
+ periodo="2024-01",
1169
+ valor_irpj=Decimal("5000"),
1170
+ valor_csll=Decimal("1800"),
1171
+ valor_pis=Decimal("650"),
1172
+ valor_cofins=Decimal("3000"),
1173
+ )
1174
+ caminho = gerador.salvar("./output")
1175
+ print(gerador.relatorio_resumo())
1176
+ ```
1177
+
1178
+ ---
1179
+
1180
+ ## Declarações Anuais
1181
+
1182
+ ### DIRF (`src/generators/dirf.py`)
1183
+
1184
+ Declaração anual do imposto de renda retido na fonte. Arquivo texto para o PGD DIRF.
1185
+
1186
+ **Prazo:** Último dia útil de fevereiro.
1187
+
1188
+ ```python
1189
+ from src.generators.dirf import GeradorDIRF, BeneficiarioDIRF, ResponsavelDIRF
1190
+ gerador = GeradorDIRF(empresa, ano_calendario=2024, beneficiarios=[...], responsavel=...)
1191
+ caminho = gerador.salvar("./output")
1192
+ ```
1193
+
1194
+ ### DEFIS (`src/generators/defis.py`)
1195
+
1196
+ Declaração de informações socioeconômicas e fiscais para empresas do Simples Nacional. XML para o portal do Simples Nacional.
1197
+
1198
+ **Prazo:** 31 de março do ano seguinte.
1199
+
1200
+ ```python
1201
+ from src.generators.defis import GeradorDEFIS, ReceitaMensalDEFIS, SocioDEFIS
1202
+ gerador = GeradorDEFIS(empresa, ano_calendario=2024, receitas_mensais=[...], socios=[...])
1203
+ xml = gerador.gerar_xml()
1204
+ print(gerador.relatorio_resumo())
1205
+ ```
1206
+
1207
+ ### DeSTDA (`src/generators/destda.py`)
1208
+
1209
+ Declaração mensal de substituição tributária, diferencial de alíquota e antecipação para empresas do Simples Nacional.
1210
+
1211
+ **Prazo:** Dia 20 do mês seguinte.
1212
+
1213
+ ```python
1214
+ from src.generators.destda import GeradorDeSTDA, OperacaoSTDeSTDA
1215
+ ops = [
1216
+ OperacaoSTDeSTDA("SP", "RJ", "ST", base_calculo=Decimal("10000"),
1217
+ aliquota=Decimal("18"), valor_imposto=Decimal("1800")),
1218
+ OperacaoSTDeSTDA("SP", "MG", "DIFAL", base_calculo=Decimal("5000"),
1219
+ aliquota=Decimal("6"), valor_imposto=Decimal("300")),
1220
+ ]
1221
+ gerador = GeradorDeSTDA(empresa, "2024-01", ops)
1222
+ print(gerador.relatorio_resumo())
1223
+ ```
1224
+
1225
+ ### GIA / GIA-ST — São Paulo (`src/generators/gia.py`)
1226
+
1227
+ Guia de informação e apuração do ICMS mensal para o estado de São Paulo. Arquivo AIE pipe-delimitado para SEFAZ-SP / SCANC.
1228
+
1229
+ **Prazo:** Dia 20 do mês seguinte (pode variar por faixa de faturamento).
1230
+
1231
+ ```python
1232
+ from src.generators.gia import GeradorGIA, ApuracaoGIA, ApuracaoGIAST
1233
+ apuracao = ApuracaoGIA(
1234
+ debitos_operacoes_proprias=Decimal("50000"),
1235
+ creditos_entradas=Decimal("30000"),
1236
+ )
1237
+ gerador = GeradorGIA(empresa, "2024-01", apuracao, apuracoes_st=[
1238
+ ApuracaoGIAST("MG", Decimal("20000"), Decimal("12"), Decimal("2400")),
1239
+ ])
1240
+ caminho = gerador.salvar("./output") # → GIA_CNPJ_2024-01.aie
1241
+ ```
1242
+
1243
+ ---
1244
+
1245
+ ## Transmissor SEFAZ
1246
+
1247
+ ### NF-e (`src/transmitters/receita_federal.py`)
1248
+
1249
+ ```python
1250
+ from src.transmitters.receita_federal import TransmissorNFe
1251
+
1252
+ transmissor = TransmissorNFe(uf="SP", ambiente="2") # ambiente 2=homologação
1253
+
1254
+ # Verificar disponibilidade do serviço
1255
+ status = transmissor.verificar_status_servico()
1256
+
1257
+ # Transmitir NF-e para autorização
1258
+ resultado = transmissor.autorizar_nfe(xml_assinado)
1259
+ print(resultado.protocolo) # protocolo de autorização
1260
+
1261
+ # Cancelar NF-e
1262
+ resultado = transmissor.cancelar_nfe(chave, protocolo, justificativa)
1263
+ ```
1264
+
1265
+ Endpoints SOAP: SP (SEFAZ-SP), SVRS (demais estados), SVAN (contingência nacional).
1266
+
1267
+ ### Validador SPED Local
1268
+
1269
+ ```python
1270
+ from src.transmitters.receita_federal import TransmissorSPEDLocal, ValidadorArquivoSPED
1271
+
1272
+ # Valida presença de registros obrigatórios e contagem de linhas
1273
+ valido, erros = ValidadorArquivoSPED().validar(caminho_arquivo)
1274
+
1275
+ # Prepara arquivo para transmissão via PGE (programa Java)
1276
+ resultado = TransmissorSPEDLocal("./output").preparar_efd_icms_ipi(caminho)
1277
+ ```
1278
+
1279
+ > **Observação:** Os arquivos EFD ICMS/IPI, EFD Contribuições e ECD devem ser transmitidos pelo programa PGE/Validador da Receita Federal — não há upload HTTP direto para o SPED. Apenas a NF-e usa webservices SOAP diretos da SEFAZ.
1280
+
1281
+ ---
1282
+
1283
+ ## Treinamento do Modelo
1284
+
1285
+ O `TransformerFiscal` é iniciado com pesos aleatórios. Use o `TrainerFiscal` para treiná-lo com o dataset built-in (173 exemplos rotulados) ou seus próprios dados.
1286
+
1287
+ ```python
1288
+ from src import PipelineFiscal
1289
+
1290
+ pipeline = PipelineFiscal()
1291
+
1292
+ # Treinar com os exemplos built-in
1293
+ historico = pipeline.treinar(
1294
+ epochs=50, # early stopping pode parar antes se val_loss parar de melhorar
1295
+ caminho_saida="./checkpoints/fiscal_llm.pt",
1296
+ )
1297
+
1298
+ # Carregar modelo treinado
1299
+ pipeline = PipelineFiscal(caminho_modelo="./checkpoints/fiscal_llm.pt")
1300
+
1301
+ # Avaliar acurácia por classe
1302
+ from src.models.trainer import TrainerFiscal, EXEMPLOS_CLASSIFICACAO
1303
+ from src.models.fiscal_llm import TokenizadorFiscal
1304
+
1305
+ tokenizador = TokenizadorFiscal()
1306
+ trainer = TrainerFiscal(pipeline.modelo, tokenizador)
1307
+ metricas = trainer.avaliar_por_classe(EXEMPLOS_CLASSIFICACAO)
1308
+ print(f"Acurácia geral: {metricas['acuracia_geral']:.1%}")
1309
+ for classe, acc in metricas["acuracia_por_classe"].items():
1310
+ print(f" {classe}: {acc:.1%}")
1311
+ ```
1312
+
1313
+ **Configuração de treinamento:**
1314
+
1315
+ | Parâmetro | Padrão |
1316
+ |-----------|--------|
1317
+ | Épocas | 50 |
1318
+ | Otimizador | AdamW |
1319
+ | Learning rate | 3e-4 (OneCycleLR) |
1320
+ | Batch size | 16 |
1321
+ | Gradient clipping | 1,0 |
1322
+ | Divisão validação | 15% |
1323
+ | Paciência early stopping | 8 épocas |
1324
+ | Pesos por classe | Habilitado (frequência inversa) |
1325
+
1326
+ ---
1327
+
1328
+ ## Execução dos Testes
1329
+
1330
+ ```bash
1331
+ pip install pytest pytest-asyncio
1332
+ python -m pytest tests/ -v
1333
+ ```
1334
+
1335
+ **117 testes** cobrindo todos os componentes:
1336
+
1337
+ | Módulo | Testes |
1338
+ |--------|--------|
1339
+ | Calculadora ICMS | 9 |
1340
+ | Calculadora IPI | 6 |
1341
+ | Calculadora PIS/COFINS | 6 |
1342
+ | Calculadora IRPJ/CSLL | 7 |
1343
+ | Calculadora ISS | 5 |
1344
+ | Simples Nacional | 9 |
1345
+ | Escritor SPED | 3 |
1346
+ | EFD ICMS/IPI (incl. Blocos G+K) | 10 |
1347
+ | EFD Contribuições | 3 |
1348
+ | ECD | 5 |
1349
+ | ECF | 3 |
1350
+ | NF-e | 6 |
1351
+ | NFC-e | 4 |
1352
+ | CT-e | 4 |
1353
+ | MDF-e | 4 |
1354
+ | EFD-Reinf | 3 |
1355
+ | e-Social | 3 |
1356
+ | DCTF | 5 |
1357
+ | DIRF | 4 |
1358
+ | DEFIS | 5 |
1359
+ | DeSTDA | 5 |
1360
+ | GIA | 5 |
1361
+
1362
+ ---
1363
+
1364
+ ## Calendário Fiscal
1365
+
1366
+ | Obrigação | Periodicidade | Prazo |
1367
+ |-----------|--------------|-------|
1368
+ | DAS (Simples Nacional) | Mensal | Dia 20 do mês seguinte |
1369
+ | DeSTDA (ICMS-ST Simples) | Mensal | Dia 20 do mês seguinte |
1370
+ | GIA-SP | Mensal | Dia 20 do mês seguinte |
1371
+ | EFD ICMS/IPI | Mensal | 15º dia útil do mês seguinte |
1372
+ | DCTF | Mensal | 15º dia útil do 2º mês seguinte |
1373
+ | EFD Contribuições | Mensal | 10º dia útil do 2º mês seguinte |
1374
+ | EFD-Reinf | Mensal | Dia 15 do mês seguinte |
1375
+ | e-Social (folha) | Mensal | Dia 7 do mês seguinte |
1376
+ | ECD | Anual | Último dia útil de junho |
1377
+ | DEFIS (Simples Nacional) | Anual | 31 de março |
1378
+ | ECF | Anual | Último dia útil de julho |
1379
+ | DIRF | Anual | Último dia útil de fevereiro |
1380
+
1381
+ ---
1382
+
1383
+ *Sistema desenvolvido em Python 3.12 com PyTorch para o ecossistema fiscal brasileiro (SPED).*
1384
+ *117 testes · 20 obrigações cobertas · 6 tributos calculados*