LesterCerioli/Speed
0
1---2license: mit3language:4- pt5tags:6- pytorch7- transformer8- text-classification9- fiscal10- sped11- brazil12- tax13- nlp14- llm15- brazilian-fiscal16pipeline_tag: text-classification17library_name: pytorch18base_model: []19datasets: []20metrics:21- accuracy22model-index:23- name: LLM Fiscal Brasileiro — SPED24 results:25 - task:26 type: text-classification27 name: Brazilian Fiscal Obligation Classification28 metrics:29 - type: accuracy30 value: 0.9531 name: Accuracy (intent classification, 16 classes)32---33 34# LLM Fiscal Brasileiro — SPED Fiscal System35 36> **PyTorch-powered LLM for Brazilian fiscal obligations (SPED)**37> Python 3.12 · PyTorch · Pydantic v2 · 117 tests38 39---40 41## Table of Contents / Índice42 43- [English](#english)44 - [Overview](#overview)45 - [Architecture](#architecture)46 - [Project Structure](#project-structure)47 - [Installation](#installation)48 - [Quick Start](#quick-start)49 - [LLM Model](#llm-model)50 - [Tax Calculators](#tax-calculators)51 - [SPED / DFe Generators](#sped--dfe-generators)52 - [Annual Declarations](#annual-declarations)53 - [SEFAZ Transmitter](#sefaz-transmitter)54 - [Training the Model](#training-the-model)55 - [Running Tests](#running-tests)56 - [Fiscal Calendar](#fiscal-calendar)57- [Português Brasileiro](#português-brasileiro)58 - [Visão Geral](#visão-geral)59 - [Arquitetura](#arquitetura)60 - [Estrutura do Projeto](#estrutura-do-projeto)61 - [Instalação](#instalação)62 - [Início Rápido](#início-rápido)63 - [Modelo LLM](#modelo-llm)64 - [Calculadoras Tributárias](#calculadoras-tributárias)65 - [Geradores SPED / DFe](#geradores-sped--dfe)66 - [Declarações Anuais](#declarações-anuais)67 - [Transmissor SEFAZ](#transmissor-sefaz)68 - [Treinamento do Modelo](#treinamento-do-modelo)69 - [Execução dos Testes](#execução-dos-testes)70 - [Calendário Fiscal](#calendário-fiscal)71 72---73 74# English75 76## Overview77 78The **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.79 80The system covers the full lifecycle of Brazilian fiscal obligations:81 82- **Intent classification** of natural-language fiscal queries (16 obligation classes)83- **RAG (Retrieval-Augmented Generation)** with 25 indexed fiscal knowledge documents84- **Tax calculators** for all major Brazilian taxes (ICMS, IPI, PIS/COFINS, IRPJ/CSLL, ISS, Simples Nacional)85- **SPED file generators** for all federal digital bookkeeping obligations86- **Electronic document generators** (NF-e, NFC-e, CT-e, MDF-e) with digital signatures87- **SEFAZ SOAP transmitter** for NF-e authorization88 89The single entry point is `PipelineFiscal`, which orchestrates all components.90 91---92 93## Architecture94 95```96┌──────────────────────────────────────────────────────────────────┐97│ PipelineFiscal │98│ (src/models/fiscal_llm.py) │99│ │100│ ┌─────────────────────┐ ┌──────────────────────────────────┐ │101│ │ TransformerFiscal │ │ BancoEmbeddingsFiscais (RAG) │ │102│ │ PyTorch 4-layer │ │ 25 knowledge documents │ │103│ │ encoder, d=256 │ │ cosine similarity search │ │104│ │ 8 heads, Pre-LN │ └──────────────────────────────────┘ │105│ └─────────────────────┘ │106│ ┌─────────────────────────────────────────────────────────────┐ │107│ │ Intent Classification (16 classes) │ │108│ └─────────────────────────────────────────────────────────────┘ │109│ │110│ ┌──────────────────┐ ┌──────────────────┐ ┌───────────────┐ │111│ │ Tax Calculators │ │ SPED Generators │ │ DFe / XML │ │112│ │ ICMS · IPI │ │ EFD ICMS/IPI │ │ NF-e · NFC-e │ │113│ │ PIS/COFINS │ │ EFD Contribu. │ │ CT-e · MDF-e │ │114│ │ IRPJ/CSLL · ISS │ │ ECD · ECF │ │ EFD-Reinf │ │115│ │ Simples Nac. │ │ DCTF · GIA │ │ e-Social │ │116│ └──────────────────┘ │ DIRF · DEFIS │ └───────────────┘ │117│ │ DeSTDA │ │118│ └──────────────────┘ │119└──────────────────────────────────────────────────────────────────┘120```121 122**Key design decisions:**123- The LLM (`TransformerFiscal`) uses character-level tokenization — no external tokenizer dependency.124- RAG runs entirely in-memory using normalized cosine similarity on CLS embeddings.125- All monetary values use Python `Decimal` with `ROUND_HALF_UP` — no floating-point arithmetic.126- SPED files are pipe-delimited (`|REGISTRO|CAMPO1|`) UTF-8, matching the official Receita Federal spec.127- NF-e/CT-e/MDF-e use XML v4.00 with RSA-SHA1 XMLDSig digital signatures via the `cryptography` library.128 129---130 131## Project Structure132 133```134llm-speed/135├── src/136│ ├── __init__.py # Exports PipelineFiscal137│ ├── fiscal/138│ │ ├── entities.py # Pydantic v2 models (Empresa, NotaFiscal, …)139│ │ └── constants.py # Tax rates, CST tables, CFOP codes, deadlines140│ ├── calculators/141│ │ ├── icms.py # ICMS (own + ST + DIFAL + FCP)142│ │ ├── ipi.py # IPI (TIPI rates by NCM chapter)143│ │ ├── pis_cofins.py # PIS/COFINS (cumulative + non-cumulative + withholding)144│ │ ├── irpj_csll.py # IRPJ/CSLL (Lucro Real + Lucro Presumido + monthly estimates)145│ │ ├── iss.py # ISS (LC 116/2003 + Simples Nacional annexes)146│ │ └── simples_nacional.py # Simples Nacional (5 annexes, Fator R, PGDAS-D, MEI)147│ ├── generators/148│ │ ├── sped_writer.py # Base SPED pipe-delimited writer149│ │ ├── efd_icms_ipi.py # EFD ICMS/IPI (blocks 0,C,E,G,H,K,1,9)150│ │ ├── efd_contribuicoes.py # EFD Contribuições PIS/COFINS (blocks 0,C,M,1,9)151│ │ ├── ecd.py # ECD — Escrituração Contábil Digital152│ │ ├── ecf.py # ECF — Escrituração Contábil Fiscal (LALUR/LACS)153│ │ ├── nfe_xml.py # NF-e XML v4.00 (model 55) + digital signature154│ │ ├── nfce_xml.py # NFC-e XML v4.00 (model 65, consumer/POS)155│ │ ├── cte.py # CT-e XML v4.00 (model 57, freight)156│ │ ├── mdfe.py # MDF-e XML v3.00 (manifest, model 58)157│ │ ├── efd_reinf.py # EFD-Reinf XML events (R-1000…R-2099)158│ │ ├── esocial.py # e-Social XML events (S-1000…S-1299, S-2200, S-2299)159│ │ ├── dctf.py # DCTF XML (federal tax debit declaration)160│ │ ├── dirf.py # DIRF text file (annual IRRF withholding declaration)161│ │ ├── defis.py # DEFIS XML (Simples Nacional annual declaration)162│ │ ├── destda.py # DeSTDA XML (Simples Nacional monthly ICMS-ST/DIFAL)163│ │ └── gia.py # GIA/GIA-ST AIE file (São Paulo monthly ICMS)164│ ├── models/165│ │ ├── fiscal_llm.py # TransformerFiscal + RAG + PipelineFiscal166│ │ └── trainer.py # TrainerFiscal (173 examples, early stopping, class weights)167│ └── transmitters/168│ └── receita_federal.py # NF-e SEFAZ SOAP transmitter + SPED local validator169├── tests/170│ ├── test_calculators.py # 43 tests for all tax calculators171│ └── test_generators.py # 74 tests for all generators172├── pyproject.toml173└── requirements.txt174```175 176---177 178## Installation179 180**Requirements:** Python 3.12+, pip181 182```bash183# Clone the repository184git clone <repo-url>185cd llm-speed186 187# Create and activate virtual environment188python -m venv venv189source venv/bin/activate # Linux/macOS190# venv\Scripts\activate # Windows191 192# Install dependencies193pip install -r requirements.txt194```195 196**Core dependencies:**197 198| Package | Purpose |199|---------|---------|200| `torch>=2.3.0` | TransformerFiscal model + training |201| `pydantic>=2.7.0` | Validated fiscal data models |202| `cryptography>=42.0.0` | NF-e/CT-e XML digital signatures (RSA-SHA1) |203| `lxml>=5.2.0` | C14N canonicalization for XMLDSig |204| `httpx>=0.27.0` | SEFAZ SOAP HTTP client |205| `zeep>=4.2.1` | SOAP envelope helpers |206| `python-dateutil>=2.9.0` | Brazilian fiscal calendar calculations |207 208---209 210## Quick Start211 212```python213from src import PipelineFiscal214 215# Instantiate the LLM pipeline (uses random weights until trained)216pipeline = PipelineFiscal(diretorio_saida="./output")217 218# --- Natural language processing ---219resultado = pipeline.processar(220 "calculate ICMS for a sale",221 {"valor_mercadoria": 10000, "aliquota": 18, "uf_origem": "SP", "uf_destino": "RJ"}222)223print(resultado.resumo())224# [calcular_icms]225# base_calculo: R$ 10,000.00226# aliquota: R$ 18.00227# valor_icms: R$ 1,800.00228# valor_total_icms: R$ 1,800.00229 230# --- Direct tax calculation ---231r = pipeline.calcular_pis_cofins({232 "valor": 100000,233 "regime": "lucro_presumido",234})235print(r["pis_a_recolher"]) # 650.00236print(r["cofins_a_recolher"]) # 3000.00237 238# --- Generate SPED files for an entire period ---239from src.fiscal.entities import PeriodoApuracao, Empresa, ...240periodo = PeriodoApuracao(...)241arquivos = pipeline.gerar_obrigacoes(periodo)242# Returns: {"EFD_ICMS_IPI": ResultadoFiscal, "EFD_CONTRIBUICOES": ..., ...}243 244# --- SEFAZ status check ---245status = pipeline.verificar_sefaz(uf="SP")246print(status["mensagem"])247```248 249---250 251## LLM Model252 253### TransformerFiscal254 255A compact Transformer encoder trained for Brazilian fiscal intent classification.256 257| Parameter | Value |258|-----------|-------|259| Architecture | Transformer Encoder (Pre-LN) |260| Layers | 4 |261| d_model | 256 |262| Attention heads | 8 |263| FFN dimension | 1,024 |264| Tokenizer | Character-level (vocab ~200 chars) |265| Max sequence length | 1,024 tokens |266| Output classes | 16 fiscal obligation types |267 268**16 Intent Classes:**269 270| Class | Description |271|-------|-------------|272| `EFD_ICMS_IPI` | Generate EFD ICMS/IPI digital bookkeeping |273| `EFD_CONTRIBUICOES` | Generate EFD Contribuições (PIS/COFINS) |274| `ECD` | Generate Escrituração Contábil Digital |275| `ECF` | Generate Escrituração Contábil Fiscal |276| `NFe` | Emit / cancel NF-e or NFC-e |277| `NFSe` | Emit NFS-e (municipal service invoice) |278| `CTe` | Generate CT-e freight document |279| `eSocial` | Generate e-Social payroll events |280| `EFD_REINF` | Generate EFD-Reinf withholding events |281| `DCTF` | Generate DCTF federal tax declaration |282| `PGDAS` | Calculate Simples Nacional DAS / PGDAS-D |283| `calculo_icms` | Calculate ICMS for a transaction |284| `calculo_ipi` | Calculate IPI for industrial products |285| `calculo_pis_cofins` | Calculate PIS and COFINS on revenue |286| `calculo_irpj_csll` | Calculate IRPJ and CSLL (corporate taxes) |287| `calculo_iss` | Calculate ISS (municipal services tax) |288 289### RAG Knowledge Base290 291`BancoEmbeddingsFiscais` indexes 25 fiscal knowledge documents covering all major obligations, rates, deadlines, and legislation. Retrieval uses cosine similarity on CLS token embeddings.292 293```python294# Direct access to RAG295pipeline.rag.buscar("prazo EFD ICMS IPI", top_k=3)296# Returns: [(text, similarity_score), ...]297```298 299---300 301## Tax Calculators302 303All calculators are available directly via `PipelineFiscal` or imported from `src.calculators.*`. All monetary values use `Decimal` with `ROUND_HALF_UP`.304 305### ICMS (`src/calculators/icms.py`)306 307```python308resultado = pipeline.calcular_icms({309 "valor_mercadoria": 10000,310 "aliquota": 18, # internal rate (%)311 "uf_origem": "SP",312 "uf_destino": "RJ",313 "frete": 500,314 "cst": "000", # CST: 000=taxed, 020=reduced, 040=exempt, 060=ST315 "calcular_difal": False,316 "consumidor_final": False,317 # Optional ST parameters:318 # "calcular_st": True, "mva": 40, "aliq_interna_destino": 18319})320```321 322Supports: CST 000/010/020/030/040/041/050/051/060/070, ICMS-ST with MVA, FCP (Fundo de Combate à Pobreza), DIFAL (EC 87/2015).323 324### IPI (`src/calculators/ipi.py`)325 326```python327resultado = pipeline.calcular_ipi({328 "valor_produtos": 5000,329 "aliquota": 10,330 "cst": "50", # 50=taxed, 52=exempt, 54=suspended331 "frete": 200,332})333```334 335Includes TIPI rates by NCM chapter (0% pharmaceuticals, 25% vehicles, 300% tobacco).336 337### PIS/COFINS (`src/calculators/pis_cofins.py`)338 339```python340resultado = pipeline.calcular_pis_cofins({341 "valor": 100000,342 "regime": "lucro_real", # or "lucro_presumido"343 # Optional credits (non-cumulative regime only):344 "receitas": [345 {"descricao": "Vendas", "valor": 100000, "cst_pis": "01", "cst_cofins": "01"}346 ],347})348```349 350| Regime | PIS | COFINS |351|--------|-----|--------|352| Lucro Presumido (cumulative) | 0.65% | 3.00% |353| Lucro Real (non-cumulative) | 1.65% | 7.60% |354 355Supports credits on purchases, energy, rent, depreciation (Lei 10.637/2002 and 10.833/2003).356 357### IRPJ / CSLL (`src/calculators/irpj_csll.py`)358 359```python360resultado = pipeline.calcular_irpj_csll({361 "valor": 500000, # Lucro Real: net profit / Lucro Presumido: gross revenue362 "regime": "lucro_presumido", # or "lucro_real"363 "atividade": "venda_mercadorias", # or "servicos_em_geral", "intermediacao"364})365```366 367| Rule | Value |368|------|-------|369| IRPJ base rate | 15% |370| IRPJ surcharge | +10% on profit > R$ 20,000/month |371| CSLL rate | 9% (general) / 15% (financial institutions) |372| Lucro Presumido — commerce/industry | 8% of revenue |373| Lucro Presumido — services | 32% of revenue |374| Tax loss carryforward limit | 30% of taxable profit |375 376### ISS (`src/calculators/iss.py`)377 378```python379resultado = pipeline.calcular_iss({380 "valor_servico": 10000,381 "codigo_servico": "17", # LC 116/2003 service code382 "aliquota": 3, # municipal rate (2%–5%)383 "retencao_fonte": True,384})385```386 387### Simples Nacional (`src/calculators/simples_nacional.py`)388 389```python390# Single activity DAS calculation391resultado = pipeline.calcular_simples({392 "receita_mes": 50000,393 "rbt12": 600000, # 12-month accumulated revenue394 "anexo": "I", # I=commerce, II=industry, III-V=services395})396 397# Full PGDAS-D with multiple activities398resultado = pipeline.calcular_pgdas({399 "periodo": "2024-01",400 "rbt12": 600000,401 "atividades": [402 {"tipo": "comercio", "receita": 30000},403 {"tipo": "servicos_advocacia", "receita": 20000},404 ],405})406```407 408Covers all 5 annexes (6 revenue brackets each), Fator R calculation for Annex III vs V, and MEI fixed amounts.409 410---411 412## SPED / DFe Generators413 414### EFD ICMS/IPI (`src/generators/efd_icms_ipi.py`)415 416Layout version 017. Generates all mandatory blocks:417 418| Block | Contents |419|-------|----------|420| 0 | Establishment identification, participants (0150), products (0200) |421| C | NF-e records (C100, C110, C170, C190) |422| E | ICMS settlement (E110), IPI settlement (E520) |423| G | CIAP — ICMS credits on permanent assets (G001, G110) |424| H | Physical inventory (H005, H010) |425| K | Production and stock control (K100, K200) — industrial companies |426| 1 | Other information |427| 9 | File control and closing |428 429```python430from src.generators.efd_icms_ipi import GeradorEFDICMSIPI431gerador = GeradorEFDICMSIPI(periodo)432caminho = gerador.gerar("./output")433```434 435### EFD Contribuições (`src/generators/efd_contribuicoes.py`)436 437Layout version 006. PIS/COFINS digital bookkeeping.438 439Blocks: 0, C (documents), M (PIS/COFINS settlement — M100, M200, M600), 1, 9.440 441### ECD (`src/generators/ecd.py`)442 443Layout version 010. Digital accounting bookkeeping.444 445Includes default chart of accounts (50+ accounts), journal entries (I200/I250), balance sheet (J150).446 447### ECF (`src/generators/ecf.py`)448 449Layout version 009. Replaces the old DIPJ declaration.450 451| Block | Contents |452|-------|----------|453| 0 | Tax parameters (0010), accountant (0930) |454| L | LALUR/LACS adjustments (Lucro Real) |455| N | IRPJ/CSLL calculation (N620, N630) |456| P | Lucro Presumido quarterly breakdown |457| Y | Partner information (Y600) |458 459### NF-e (`src/generators/nfe_xml.py`)460 461NF-e XML v4.00, model 55. Full document with all fiscal groups:462 463- `ide` — identification with 44-digit access key (Módulo 11)464- `emit` / `dest` — emitter and recipient465- `det` — items with ICMS (CST 000–090), IPI, PIS, COFINS per item466- `total` / `transp` / `pag` — totals, transport, payment467- `AssinadorNFe` — RSA-SHA1 XMLDSig using PKCS#12 certificate468 469```python470from src.generators.nfe_xml import GeradorNFeXML, AssinadorNFe471gerador = GeradorNFeXML(emitente, destinatario, itens)472xml = gerador.gerar_xml()473xml_assinado = AssinadorNFe(cert_path, cert_password).assinar(xml)474```475 476### NFC-e (`src/generators/nfce_xml.py`)477 478NFC-e XML v4.00, model 65. Consumer invoice for POS/retail. Optional CPF identification, QR Code URL.479 480### CT-e (`src/generators/cte.py`)481 482CT-e XML v4.00, model 57. Freight transport fiscal document.483 484- Road modal (rodoviário) with RNTRC registration485- 44-digit access key (Módulo 11, model 57)486- ICMS calculation on freight service487- Referenced NF-e documents488 489### MDF-e (`src/generators/mdfe.py`)490 491MDF-e XML v3.00, model 58. Groups CT-e and NF-e documents in transport routes.492 493- Unload municipalities with referenced documents494- Driver registration495- Cargo insurance data496- 44-digit access key (Módulo 11, model 58)497 498### EFD-Reinf (`src/generators/efd_reinf.py`)499 500XML events for the EFD-Reinf (withholdings and social security information).501 502| Event | Description |503|-------|-------------|504| R-1000 | Employer registration |505| R-2010 | Services taken — INSS withholding |506| R-2020 | Services provided — INSS withholding |507| R-2060 | CPRB (payroll tax exemption) |508| R-2099 | Period closing |509 510### e-Social (`src/generators/esocial.py`)511 512XML events for Brazil's digital labor bookkeeping system.513 514| Event | Description |515|-------|-------------|516| S-1000 | Employer data table |517| S-1010 | Payroll items (rubricas) table — 16 standard CLT items |518| S-1200 | Monthly payroll (remuneração) |519| S-1299 | Monthly payroll closing |520| S-2200 | Employee admission |521| S-2299 | Employment termination (rescisão) |522 523### DCTF (`src/generators/dctf.py`)524 525XML for PGD DCTF Web. Monthly declaration of federal tax debits and credits.526 527```python528from src.generators.dctf import montar_dctf_do_periodo529gerador = montar_dctf_do_periodo(530 empresa=empresa,531 periodo="2024-01",532 valor_irpj=Decimal("5000"),533 valor_csll=Decimal("1800"),534 valor_pis=Decimal("650"),535 valor_cofins=Decimal("3000"),536)537caminho = gerador.salvar("./output")538print(gerador.relatorio_resumo())539```540 541---542 543## Annual Declarations544 545### DIRF (`src/generators/dirf.py`)546 547Annual declaration of income tax withheld at source (IRRF). Text file format for PGD DIRF.548 549**Deadline:** Last business day of February.550 551```python552from src.generators.dirf import GeradorDIRF, BeneficiarioDIRF, ResponsavelDIRF553gerador = GeradorDIRF(empresa, ano_calendario=2024, beneficiarios=[...], responsavel=...)554caminho = gerador.salvar("./output")555```556 557### DEFIS (`src/generators/defis.py`)558 559Annual fiscal information declaration for Simples Nacional companies. XML format for the Simples Nacional portal.560 561**Deadline:** March 31 of the following year.562 563```python564from src.generators.defis import GeradorDEFIS, ReceitaMensalDEFIS, SocioDEFIS565gerador = GeradorDEFIS(empresa, ano_calendario=2024, receitas_mensais=[...], socios=[...])566xml = gerador.gerar_xml()567print(gerador.relatorio_resumo())568```569 570### DeSTDA (`src/generators/destda.py`)571 572Monthly declaration of ICMS-ST, DIFAL, and tax anticipation for Simples Nacional companies.573 574**Deadline:** 20th of the following month.575 576```python577from src.generators.destda import GeradorDeSTDA, OperacaoSTDeSTDA578ops = [579 OperacaoSTDeSTDA("SP", "RJ", "ST", base_calculo=Decimal("10000"),580 aliquota=Decimal("18"), valor_imposto=Decimal("1800")),581 OperacaoSTDeSTDA("SP", "MG", "DIFAL", base_calculo=Decimal("5000"),582 aliquota=Decimal("6"), valor_imposto=Decimal("300")),583]584gerador = GeradorDeSTDA(empresa, "2024-01", ops)585print(gerador.relatorio_resumo())586```587 588### GIA / GIA-ST — São Paulo (`src/generators/gia.py`)589 590Monthly ICMS information and settlement guide for São Paulo state. AIE pipe-delimited file format for SEFAZ-SP / SCANC.591 592**Deadline:** 20th of the following month (may vary by revenue tier).593 594```python595from src.generators.gia import GeradorGIA, ApuracaoGIA, ApuracaoGIAST596apuracao = ApuracaoGIA(597 debitos_operacoes_proprias=Decimal("50000"),598 creditos_entradas=Decimal("30000"),599)600gerador = GeradorGIA(empresa, "2024-01", apuracao, apuracoes_st=[601 ApuracaoGIAST("MG", Decimal("20000"), Decimal("12"), Decimal("2400")),602])603caminho = gerador.salvar("./output") # → GIA_CNPJ_2024-01.aie604```605 606---607 608## SEFAZ Transmitter609 610### NF-e (`src/transmitters/receita_federal.py`)611 612```python613from src.transmitters.receita_federal import TransmissorNFe614 615transmissor = TransmissorNFe(uf="SP", ambiente="2") # ambiente 2=homologação616 617# Check service availability618status = transmissor.verificar_status_servico()619 620# Submit NF-e for authorization621resultado = transmissor.autorizar_nfe(xml_assinado)622print(resultado.protocolo) # authorization protocol623 624# Cancel NF-e625resultado = transmissor.cancelar_nfe(chave, protocolo, justificativa)626```627 628SOAP endpoints: SP (SEFAZ-SP), SVRS (other states), SVAN (national contingency).629 630### SPED Local Validator631 632```python633from src.transmitters.receita_federal import TransmissorSPEDLocal, ValidadorArquivoSPED634 635# Validates required records and line counts636valido, erros = ValidadorArquivoSPED().validar(caminho_arquivo)637 638# Prepares file for PGE (Java program) transmission639resultado = TransmissorSPEDLocal("./output").preparar_efd_icms_ipi(caminho)640```641 642> **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.643 644---645 646## Training the Model647 648The `TransformerFiscal` ships with random weights. Use `TrainerFiscal` to train it on the built-in dataset (173 labeled examples) or your own data.649 650```python651from src import PipelineFiscal652 653pipeline = PipelineFiscal()654 655# Train with built-in examples656history = pipeline.treinar(657 epochs=50, # early stopping kicks in before if val_loss plateaus658 caminho_saida="./checkpoints/fiscal_llm.pt",659)660 661# Load trained model662pipeline = PipelineFiscal(caminho_modelo="./checkpoints/fiscal_llm.pt")663 664# Evaluate per-class accuracy665from src.models.trainer import TrainerFiscal, EXEMPLOS_CLASSIFICACAO666from src.models.fiscal_llm import TokenizadorFiscal, TransformerFiscal, CLASSES_OBRIGACAO667 668tokenizador = TokenizadorFiscal()669trainer = TrainerFiscal(pipeline.modelo, tokenizador)670metricas = trainer.avaliar_por_classe(EXEMPLOS_CLASSIFICACAO)671print(f"Overall accuracy: {metricas['acuracia_geral']:.1%}")672```673 674**Training configuration:**675 676| Parameter | Default |677|-----------|---------|678| Epochs | 50 |679| Optimizer | AdamW |680| Learning rate | 3e-4 (OneCycleLR) |681| Batch size | 16 |682| Gradient clipping | 1.0 |683| Val split | 15% |684| Early stopping patience | 8 epochs |685| Class weights | Enabled (inverse frequency) |686 687---688 689## Running Tests690 691```bash692pip install pytest pytest-asyncio693python -m pytest tests/ -v694```695 696**117 tests** covering all components:697 698| Module | Tests |699|--------|-------|700| ICMS calculator | 9 |701| IPI calculator | 6 |702| PIS/COFINS calculator | 6 |703| IRPJ/CSLL calculator | 7 |704| ISS calculator | 5 |705| Simples Nacional calculator | 9 |706| SPED writer | 3 |707| EFD ICMS/IPI (incl. Blocks G+K) | 10 |708| EFD Contribuições | 3 |709| ECD | 5 |710| ECF | 3 |711| NF-e | 6 |712| NFC-e | 4 |713| CT-e | 4 |714| MDF-e | 4 |715| EFD-Reinf | 3 |716| e-Social | 3 |717| DCTF | 5 |718| DIRF | 4 |719| DEFIS | 5 |720| DeSTDA | 5 |721| GIA | 5 |722 723---724 725## Fiscal Calendar726 727| Obligation | Frequency | Deadline |728|-----------|-----------|----------|729| DAS (Simples Nacional) | Monthly | Day 20 of following month |730| DeSTDA (ICMS-ST Simples) | Monthly | Day 20 of following month |731| GIA-SP | Monthly | Day 20 of following month |732| EFD ICMS/IPI | Monthly | 15th business day of following month |733| DCTF | Monthly | 15th business day of 2nd following month |734| EFD Contribuições | Monthly | 10th business day of 2nd following month |735| EFD-Reinf | Monthly | Day 15 of following month |736| e-Social (payroll) | Monthly | Day 7 of following month |737| ECD | Annual | Last business day of June |738| DEFIS (Simples Nacional) | Annual | March 31 |739| ECF | Annual | Last business day of July |740| DIRF | Annual | Last business day of February |741 742---743 744---745 746# Português Brasileiro747 748## Visão Geral749 750O **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.751 752O sistema cobre o ciclo de vida completo das obrigações fiscais brasileiras:753 754- **Classificação de intenção** de consultas fiscais em linguagem natural (16 classes de obrigações)755- **RAG (Geração Aumentada por Recuperação)** com 25 documentos de conhecimento fiscal indexados756- **Calculadoras tributárias** para todos os principais tributos brasileiros (ICMS, IPI, PIS/COFINS, IRPJ/CSLL, ISS, Simples Nacional)757- **Geradores de arquivos SPED** para todas as obrigações de escrituração digital federal758- **Geradores de documentos eletrônicos** (NF-e, NFC-e, CT-e, MDF-e) com assinatura digital759- **Transmissor SOAP SEFAZ** para autorização de NF-e760 761O ponto de entrada único é o `PipelineFiscal`, que orquestra todos os componentes.762 763---764 765## Arquitetura766 767```768┌──────────────────────────────────────────────────────────────────┐769│ PipelineFiscal │770│ (src/models/fiscal_llm.py) │771│ │772│ ┌─────────────────────┐ ┌──────────────────────────────────┐ │773│ │ TransformerFiscal │ │ BancoEmbeddingsFiscais (RAG) │ │774│ │ PyTorch encoder │ │ 25 documentos de conhecimento │ │775│ │ 4 camadas, d=256 │ │ busca por similaridade cosseno │ │776│ │ 8 cabeças, Pre-LN │ └──────────────────────────────────┘ │777│ └─────────────────────┘ │778│ ┌─────────────────────────────────────────────────────────────┐ │779│ │ Classificação de Intenção (16 classes) │ │780│ └─────────────────────────────────────────────────────────────┘ │781│ │782│ ┌──────────────────┐ ┌──────────────────┐ ┌───────────────┐ │783│ │ Calculadoras │ │ Geradores SPED │ │ DFe / XML │ │784│ │ ICMS · IPI │ │ EFD ICMS/IPI │ │ NF-e · NFC-e │ │785│ │ PIS/COFINS │ │ EFD Contribu. │ │ CT-e · MDF-e │ │786│ │ IRPJ/CSLL · ISS │ │ ECD · ECF │ │ EFD-Reinf │ │787│ │ Simples Nac. │ │ DCTF · GIA │ │ e-Social │ │788│ └──────────────────┘ │ DIRF · DEFIS │ └───────────────┘ │789│ │ DeSTDA │ │790│ └──────────────────┘ │791└──────────────────────────────────────────────────────────────────┘792```793 794**Decisões de design:**795- O LLM usa tokenização em nível de caractere — sem dependência de tokenizador externo.796- O RAG roda inteiramente em memória usando similaridade cosseno nos embeddings CLS.797- Todos os valores monetários usam `Decimal` Python com `ROUND_HALF_UP` — zero aritmética de ponto flutuante.798- Arquivos SPED são pipe-delimitados (`|REGISTRO|CAMPO1|`) em UTF-8, seguindo a especificação oficial da Receita Federal.799- NF-e/CT-e/MDF-e usam XML v4.00 com assinaturas digitais RSA-SHA1 XMLDSig via biblioteca `cryptography`.800 801---802 803## Estrutura do Projeto804 805```806llm-speed/807├── src/808│ ├── __init__.py # Exporta PipelineFiscal809│ ├── fiscal/810│ │ ├── entities.py # Modelos Pydantic v2 (Empresa, NotaFiscal, …)811│ │ └── constants.py # Alíquotas, tabelas CST, CFOPs, prazos812│ ├── calculators/813│ │ ├── icms.py # ICMS (próprio + ST + DIFAL + FCP)814│ │ ├── ipi.py # IPI (alíquotas TIPI por capítulo NCM)815│ │ ├── pis_cofins.py # PIS/COFINS (cumulativo + não cumulativo + retenção)816│ │ ├── irpj_csll.py # IRPJ/CSLL (Lucro Real + Lucro Presumido + estimativa)817│ │ ├── iss.py # ISS (LC 116/2003 + anexos Simples Nacional)818│ │ └── simples_nacional.py # Simples Nacional (5 anexos, Fator R, PGDAS-D, MEI)819│ ├── generators/820│ │ ├── sped_writer.py # Escritor base SPED pipe-delimitado821│ │ ├── efd_icms_ipi.py # EFD ICMS/IPI (blocos 0,C,E,G,H,K,1,9)822│ │ ├── efd_contribuicoes.py # EFD Contribuições PIS/COFINS (blocos 0,C,M,1,9)823│ │ ├── ecd.py # ECD — Escrituração Contábil Digital824│ │ ├── ecf.py # ECF — Escrituração Contábil Fiscal (LALUR/LACS)825│ │ ├── nfe_xml.py # NF-e XML v4.00 (modelo 55) + assinatura digital826│ │ ├── nfce_xml.py # NFC-e XML v4.00 (modelo 65, consumidor/PDV)827│ │ ├── cte.py # CT-e XML v4.00 (modelo 57, transporte)828│ │ ├── mdfe.py # MDF-e XML v3.00 (manifesto, modelo 58)829│ │ ├── efd_reinf.py # EFD-Reinf XML eventos (R-1000…R-2099)830│ │ ├── esocial.py # e-Social XML eventos (S-1000…S-1299, S-2200, S-2299)831│ │ ├── dctf.py # DCTF XML (declaração de débitos tributários federais)832│ │ ├── dirf.py # DIRF arquivo texto (declaração anual IRRF)833│ │ ├── defis.py # DEFIS XML (declaração anual Simples Nacional)834│ │ ├── destda.py # DeSTDA XML (ICMS-ST/DIFAL mensal Simples Nacional)835│ │ └── gia.py # GIA/GIA-ST arquivo AIE (ICMS mensal São Paulo)836│ ├── models/837│ │ ├── fiscal_llm.py # TransformerFiscal + RAG + PipelineFiscal838│ │ └── trainer.py # TrainerFiscal (173 exemplos, early stopping, pesos por classe)839│ └── transmitters/840│ └── receita_federal.py # Transmissor NF-e SOAP SEFAZ + validador SPED local841├── tests/842│ ├── test_calculators.py # 43 testes das calculadoras tributárias843│ └── test_generators.py # 74 testes dos geradores844├── pyproject.toml845└── requirements.txt846```847 848---849 850## Instalação851 852**Requisitos:** Python 3.12+, pip853 854```bash855# Clonar o repositório856git clone <repo-url>857cd llm-speed858 859# Criar e ativar ambiente virtual860python -m venv venv861source venv/bin/activate # Linux/macOS862# venv\Scripts\activate # Windows863 864# Instalar dependências865pip install -r requirements.txt866```867 868**Dependências principais:**869 870| Pacote | Finalidade |871|--------|-----------|872| `torch>=2.3.0` | Modelo TransformerFiscal + treinamento |873| `pydantic>=2.7.0` | Modelos de dados fiscais validados |874| `cryptography>=42.0.0` | Assinatura digital NF-e/CT-e (RSA-SHA1) |875| `lxml>=5.2.0` | Canonicalização C14N para XMLDSig |876| `httpx>=0.27.0` | Cliente HTTP SOAP SEFAZ |877| `zeep>=4.2.1` | Auxiliares para envelope SOAP |878| `python-dateutil>=2.9.0` | Cálculos de calendário fiscal brasileiro |879 880---881 882## Início Rápido883 884```python885from src import PipelineFiscal886 887# Instanciar o pipeline LLM (pesos aleatórios até ser treinado)888pipeline = PipelineFiscal(diretorio_saida="./output")889 890# --- Processamento em linguagem natural ---891resultado = pipeline.processar(892 "calcule o ICMS de uma venda",893 {"valor_mercadoria": 10000, "aliquota": 18, "uf_origem": "SP", "uf_destino": "RJ"}894)895print(resultado.resumo())896# [calcular_icms]897# base_calculo: R$ 10.000,00898# valor_icms: R$ 1.800,00899# valor_total_icms: R$ 1.800,00900 901# --- Cálculo direto de tributos ---902r = pipeline.calcular_pis_cofins({903 "valor": 100000,904 "regime": "lucro_presumido",905})906print(r["pis_a_recolher"]) # 650.00907print(r["cofins_a_recolher"]) # 3000.00908 909# --- Gerar obrigações SPED do período ---910from src.fiscal.entities import PeriodoApuracao, Empresa, ...911periodo = PeriodoApuracao(...)912arquivos = pipeline.gerar_obrigacoes(periodo)913# Retorna: {"EFD_ICMS_IPI": ResultadoFiscal, "EFD_CONTRIBUICOES": ..., ...}914 915# --- Verificar status SEFAZ ---916status = pipeline.verificar_sefaz(uf="SP")917print(status["mensagem"])918```919 920---921 922## Modelo LLM923 924### TransformerFiscal925 926Encoder Transformer compacto treinado para classificação de intenção fiscal brasileira.927 928| Parâmetro | Valor |929|-----------|-------|930| Arquitetura | Transformer Encoder (Pre-LN) |931| Camadas | 4 |932| d_model | 256 |933| Cabeças de atenção | 8 |934| Dimensão FFN | 1.024 |935| Tokenizador | Nível de caractere (vocab ~200 chars) |936| Comprimento máximo de sequência | 1.024 tokens |937| Classes de saída | 16 tipos de obrigação fiscal |938 939**16 Classes de Intenção:**940 941| Classe | Descrição |942|--------|-----------|943| `EFD_ICMS_IPI` | Gerar EFD ICMS/IPI |944| `EFD_CONTRIBUICOES` | Gerar EFD Contribuições (PIS/COFINS) |945| `ECD` | Gerar Escrituração Contábil Digital |946| `ECF` | Gerar Escrituração Contábil Fiscal |947| `NFe` | Emitir/cancelar NF-e ou NFC-e |948| `NFSe` | Emitir NFS-e (nota de serviço municipal) |949| `CTe` | Gerar CT-e (conhecimento de transporte) |950| `eSocial` | Gerar eventos e-Social (folha/admissão) |951| `EFD_REINF` | Gerar eventos EFD-Reinf (retenções) |952| `DCTF` | Gerar DCTF (débitos tributários federais) |953| `PGDAS` | Calcular DAS Simples Nacional / PGDAS-D |954| `calculo_icms` | Calcular ICMS de uma operação |955| `calculo_ipi` | Calcular IPI de produto industrializado |956| `calculo_pis_cofins` | Calcular PIS e COFINS sobre receitas |957| `calculo_irpj_csll` | Calcular IRPJ e CSLL (tributos corporativos) |958| `calculo_iss` | Calcular ISS (imposto municipal sobre serviços) |959 960### Base de Conhecimento RAG961 962`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.963 964```python965# Acesso direto ao RAG966pipeline.rag.buscar("prazo EFD ICMS IPI", top_k=3)967# Retorna: [(texto, score_similaridade), ...]968```969 970---971 972## Calculadoras Tributárias973 974Todas as calculadoras estão disponíveis via `PipelineFiscal` ou importadas de `src.calculators.*`. Todos os valores monetários usam `Decimal` com `ROUND_HALF_UP`.975 976### ICMS (`src/calculators/icms.py`)977 978```python979resultado = pipeline.calcular_icms({980 "valor_mercadoria": 10000,981 "aliquota": 18, # alíquota interna (%)982 "uf_origem": "SP",983 "uf_destino": "RJ",984 "frete": 500,985 "cst": "000", # CST: 000=tributado, 020=redução, 040=isento, 060=ST986 "calcular_difal": False,987 "consumidor_final": False,988 # Parâmetros opcionais ST:989 # "calcular_st": True, "mva": 40, "aliq_interna_destino": 18990})991```992 993Suporta: CST 000/010/020/030/040/041/050/051/060/070, ICMS-ST com MVA, FCP (Fundo de Combate à Pobreza), DIFAL (EC 87/2015).994 995### IPI (`src/calculators/ipi.py`)996 997```python998resultado = pipeline.calcular_ipi({999 "valor_produtos": 5000,1000 "aliquota": 10,1001 "cst": "50", # 50=tributado, 52=isento, 54=suspenso1002 "frete": 200,1003})1004```1005 1006Inclui alíquotas TIPI por capítulo NCM (0% farmacêuticos, 25% veículos, 300% cigarro).1007 1008### PIS/COFINS (`src/calculators/pis_cofins.py`)1009 1010```python1011resultado = pipeline.calcular_pis_cofins({1012 "valor": 100000,1013 "regime": "lucro_real", # ou "lucro_presumido"1014 "receitas": [1015 {"descricao": "Vendas", "valor": 100000, "cst_pis": "01", "cst_cofins": "01"}1016 ],1017})1018```1019 1020| Regime | PIS | COFINS |1021|--------|-----|--------|1022| Lucro Presumido (cumulativo) | 0,65% | 3,00% |1023| Lucro Real (não cumulativo) | 1,65% | 7,60% |1024 1025Suporta créditos sobre compras, energia, aluguéis, depreciação (Leis 10.637/2002 e 10.833/2003).1026 1027### IRPJ / CSLL (`src/calculators/irpj_csll.py`)1028 1029```python1030resultado = pipeline.calcular_irpj_csll({1031 "valor": 500000, # Lucro Real: lucro líquido / Lucro Presumido: receita bruta1032 "regime": "lucro_presumido", # ou "lucro_real"1033 "atividade": "venda_mercadorias", # ou "servicos_em_geral", "intermediacao"1034})1035```1036 1037| Regra | Valor |1038|-------|-------|1039| IRPJ alíquota base | 15% |1040| IRPJ adicional | +10% sobre lucro > R$ 20.000/mês |1041| CSLL alíquota | 9% (geral) / 15% (financeiras) |1042| Lucro Presumido — comércio/indústria | 8% da receita |1043| Lucro Presumido — serviços | 32% da receita |1044| Limite compensação prejuízos | 30% do lucro tributável |1045 1046### ISS (`src/calculators/iss.py`)1047 1048```python1049resultado = pipeline.calcular_iss({1050 "valor_servico": 10000,1051 "codigo_servico": "17", # código da LC 116/20031052 "aliquota": 3, # alíquota municipal (2%–5%)1053 "retencao_fonte": True,1054})1055```1056 1057### Simples Nacional (`src/calculators/simples_nacional.py`)1058 1059```python1060# Cálculo do DAS para uma atividade1061resultado = pipeline.calcular_simples({1062 "receita_mes": 50000,1063 "rbt12": 600000, # receita acumulada 12 meses1064 "anexo": "I", # I=comércio, II=indústria, III-V=serviços1065})1066 1067# PGDAS-D completo com múltiplas atividades1068resultado = pipeline.calcular_pgdas({1069 "periodo": "2024-01",1070 "rbt12": 600000,1071 "atividades": [1072 {"tipo": "comercio", "receita": 30000},1073 {"tipo": "servicos_advocacia", "receita": 20000},1074 ],1075})1076```1077 1078Cobre todos os 5 anexos (6 faixas cada), cálculo do Fator R para Anexo III vs V, e valores fixos do MEI.1079 1080---1081 1082## Geradores SPED / DFe1083 1084### EFD ICMS/IPI (`src/generators/efd_icms_ipi.py`)1085 1086Layout versão 017. Gera todos os blocos obrigatórios:1087 1088| Bloco | Conteúdo |1089|-------|----------|1090| 0 | Identificação do estabelecimento, participantes (0150), produtos (0200) |1091| C | Registros NF-e (C100, C110, C170, C190) |1092| E | Apuração ICMS (E110), apuração IPI (E520) |1093| G | CIAP — crédito ICMS sobre ativo permanente (G001, G110) |1094| H | Inventário físico (H005, H010) |1095| K | Controle de produção e estoque (K100, K200) — indústrias |1096| 1 | Outras informações |1097| 9 | Controle e encerramento do arquivo |1098 1099```python1100from src.generators.efd_icms_ipi import GeradorEFDICMSIPI1101gerador = GeradorEFDICMSIPI(periodo)1102caminho = gerador.gerar("./output")1103```1104 1105### EFD Contribuições (`src/generators/efd_contribuicoes.py`)1106 1107Layout versão 006. Escrituração digital de PIS/COFINS.1108 1109Blocos: 0, C (documentos), M (apuração PIS/COFINS — M100, M200, M600), 1, 9.1110 1111### ECD (`src/generators/ecd.py`)1112 1113Layout versão 010. Escrituração contábil digital.1114 1115Inclui plano de contas padrão (50+ contas), lançamentos (I200/I250), balanço (J150).1116 1117### ECF (`src/generators/ecf.py`)1118 1119Layout versão 009. Substitui a DIPJ.1120 1121| Bloco | Conteúdo |1122|-------|----------|1123| 0 | Parâmetros fiscais (0010), contador (0930) |1124| L | Ajustes LALUR/LACS (Lucro Real) |1125| N | Cálculo IRPJ/CSLL (N620, N630) |1126| P | Lucro Presumido por trimestre |1127| Y | Quadro societário (Y600) |1128 1129### NF-e (`src/generators/nfe_xml.py`)1130 1131NF-e XML v4.00, modelo 55. Documento completo com todos os grupos fiscais:1132 1133- `ide` — identificação com chave de acesso 44 dígitos (Módulo 11)1134- `emit` / `dest` — emitente e destinatário1135- `det` — itens com ICMS (CST 000–090), IPI, PIS, COFINS por item1136- `total` / `transp` / `pag` — totais, transporte, pagamento1137- `AssinadorNFe` — assinatura RSA-SHA1 XMLDSig com certificado PKCS#121138 1139```python1140from src.generators.nfe_xml import GeradorNFeXML, AssinadorNFe1141gerador = GeradorNFeXML(emitente, destinatario, itens)1142xml = gerador.gerar_xml()1143xml_assinado = AssinadorNFe(cert_path, cert_password).assinar(xml)1144```1145 1146### NFC-e (`src/generators/nfce_xml.py`)1147 1148NFC-e XML v4.00, modelo 65. Nota do consumidor para PDV/varejo. Identificação do CPF opcional, URL QR Code.1149 1150### CT-e (`src/generators/cte.py`)1151 1152CT-e XML v4.00, modelo 57. Documento fiscal para transporte de carga.1153 1154- Modal rodoviário com registro RNTRC1155- Chave de acesso 44 dígitos (Módulo 11, modelo 57)1156- Cálculo do ICMS sobre o serviço de transporte1157- Documentos NF-e referenciados1158 1159### MDF-e (`src/generators/mdfe.py`)1160 1161MDF-e XML v3.00, modelo 58. Agrupa CT-e e NF-e em rotas de transporte.1162 1163- Municípios de descarga com documentos referenciados1164- Cadastro de condutores1165- Dados do seguro de carga1166- Chave de acesso 44 dígitos (Módulo 11, modelo 58)1167 1168### EFD-Reinf (`src/generators/efd_reinf.py`)1169 1170Eventos XML para o EFD-Reinf (retenções e informações previdenciárias).1171 1172| Evento | Descrição |1173|--------|-----------|1174| R-1000 | Cadastro do empregador |1175| R-2010 | Serviços tomados — retenção INSS |1176| R-2020 | Serviços prestados — retenção INSS |1177| R-2060 | CPRB (contribuição previdenciária sobre receita bruta) |1178| R-2099 | Fechamento do período |1179 1180### e-Social (`src/generators/esocial.py`)1181 1182Eventos XML para o sistema de escrituração digital trabalhista brasileiro.1183 1184| Evento | Descrição |1185|--------|-----------|1186| S-1000 | Dados do empregador |1187| S-1010 | Tabela de rubricas — 16 itens CLT padrão |1188| S-1200 | Remuneração mensal (folha de pagamento) |1189| S-1299 | Fechamento da folha mensal |1190| S-2200 | Admissão de empregado |1191| S-2299 | Desligamento (rescisão contratual) |1192 1193### DCTF (`src/generators/dctf.py`)1194 1195XML para o PGD DCTF Web. Declaração mensal de débitos e créditos tributários federais.1196 1197```python1198from src.generators.dctf import montar_dctf_do_periodo1199gerador = montar_dctf_do_periodo(1200 empresa=empresa,