serigy 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. serigy-0.2.0/LICENSE +21 -0
  2. serigy-0.2.0/PKG-INFO +131 -0
  3. serigy-0.2.0/README.md +108 -0
  4. serigy-0.2.0/pyproject.toml +77 -0
  5. serigy-0.2.0/setup.cfg +4 -0
  6. serigy-0.2.0/src/serigy/__init__.py +44 -0
  7. serigy-0.2.0/src/serigy/__main__.py +112 -0
  8. serigy-0.2.0/src/serigy/api/__init__.py +46 -0
  9. serigy-0.2.0/src/serigy/api/inferencia.py +484 -0
  10. serigy-0.2.0/src/serigy/api/predizer.py +233 -0
  11. serigy-0.2.0/src/serigy/api/schemas.py +217 -0
  12. serigy-0.2.0/src/serigy/checkpoint.py +195 -0
  13. serigy-0.2.0/src/serigy/cliente.py +349 -0
  14. serigy-0.2.0/src/serigy/components/__init__.py +41 -0
  15. serigy-0.2.0/src/serigy/components/asemantico.py +264 -0
  16. serigy-0.2.0/src/serigy/components/confianca.py +228 -0
  17. serigy-0.2.0/src/serigy/components/convergencia.py +180 -0
  18. serigy-0.2.0/src/serigy/components/sistema.py +210 -0
  19. serigy-0.2.0/src/serigy/config.py +210 -0
  20. serigy-0.2.0/src/serigy/dados/__init__.py +8 -0
  21. serigy-0.2.0/src/serigy/dados/extrator.py +283 -0
  22. serigy-0.2.0/src/serigy/primitivos/__init__.py +74 -0
  23. serigy-0.2.0/src/serigy/primitivos/adapters.py +164 -0
  24. serigy-0.2.0/src/serigy/primitivos/confianca.py +46 -0
  25. serigy-0.2.0/src/serigy/primitivos/encode.py +211 -0
  26. serigy-0.2.0/src/serigy/primitivos/heads.py +396 -0
  27. serigy-0.2.0/src/serigy/primitivos/persist.py +167 -0
  28. serigy-0.2.0/src/serigy/primitivos/prioridade_util.py +36 -0
  29. serigy-0.2.0/src/serigy/primitivos/schemas.py +388 -0
  30. serigy-0.2.0/src/serigy/primitivos/system_one.py +82 -0
  31. serigy-0.2.0/src/serigy/utils/__init__.py +27 -0
  32. serigy-0.2.0/src/serigy/utils/calibracao_h3.py +61 -0
  33. serigy-0.2.0/src/serigy/utils/metricas.py +137 -0
  34. serigy-0.2.0/src/serigy/utils/ordinal.py +129 -0
  35. serigy-0.2.0/src/serigy.egg-info/PKG-INFO +131 -0
  36. serigy-0.2.0/src/serigy.egg-info/SOURCES.txt +76 -0
  37. serigy-0.2.0/src/serigy.egg-info/dependency_links.txt +1 -0
  38. serigy-0.2.0/src/serigy.egg-info/entry_points.txt +2 -0
  39. serigy-0.2.0/src/serigy.egg-info/requires.txt +8 -0
  40. serigy-0.2.0/src/serigy.egg-info/top_level.txt +1 -0
  41. serigy-0.2.0/tests/test_arena_live.py +126 -0
  42. serigy-0.2.0/tests/test_asemantico.py +48 -0
  43. serigy-0.2.0/tests/test_bench_typesafe.py +80 -0
  44. serigy-0.2.0/tests/test_cache_dataset.py +73 -0
  45. serigy-0.2.0/tests/test_cache_fakebr.py +83 -0
  46. serigy-0.2.0/tests/test_calibracao_heads.py +102 -0
  47. serigy-0.2.0/tests/test_calibracao_ternaria.py +23 -0
  48. serigy-0.2.0/tests/test_cliente_publico.py +201 -0
  49. serigy-0.2.0/tests/test_contrato_api.py +224 -0
  50. serigy-0.2.0/tests/test_csv_para_treino.py +29 -0
  51. serigy-0.2.0/tests/test_dados.py +124 -0
  52. serigy-0.2.0/tests/test_eval_honesto.py +89 -0
  53. serigy-0.2.0/tests/test_gerar_dataset_trex.py +149 -0
  54. serigy-0.2.0/tests/test_golpes_ref.py +76 -0
  55. serigy-0.2.0/tests/test_inferencia.py +179 -0
  56. serigy-0.2.0/tests/test_primitivos_adapters.py +139 -0
  57. serigy-0.2.0/tests/test_primitivos_contrato.py +230 -0
  58. serigy-0.2.0/tests/test_primitivos_heads.py +193 -0
  59. serigy-0.2.0/tests/test_primitivos_invariantes.py +146 -0
  60. serigy-0.2.0/tests/test_primitivos_persist_embed.py +111 -0
  61. serigy-0.2.0/tests/test_primitivos_prioridade.py +30 -0
  62. serigy-0.2.0/tests/test_primitivos_prioridade_s4.py +223 -0
  63. serigy-0.2.0/tests/test_primitivos_sdk.py +169 -0
  64. serigy-0.2.0/tests/test_primitivos_treino.py +71 -0
  65. serigy-0.2.0/tests/test_sdk_primitivos_publico.py +262 -0
  66. serigy-0.2.0/tests/test_sintetico_golpes.py +65 -0
  67. serigy-0.2.0/tests/test_sistema.py +30 -0
  68. serigy-0.2.0/tests/test_smoke_pre_publish.py +97 -0
  69. serigy-0.2.0/tests/test_treinamento.py +106 -0
  70. serigy-0.2.0/tests/test_trex_cinematica.py +121 -0
  71. serigy-0.2.0/tests/test_trex_cost_panel.py +74 -0
  72. serigy-0.2.0/tests/test_trex_curso_dense.py +117 -0
  73. serigy-0.2.0/tests/test_trex_duck_hold.py +58 -0
  74. serigy-0.2.0/tests/test_trex_engine.py +170 -0
  75. serigy-0.2.0/tests/test_trex_kinematic_arena.py +67 -0
  76. serigy-0.2.0/tests/test_trex_prompts_raw.py +173 -0
  77. serigy-0.2.0/tests/test_trex_serigy_mapping.py +17 -0
  78. serigy-0.2.0/tests/test_trex_timing.py +20 -0
serigy-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wendell Barreto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
serigy-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: serigy
3
+ Version: 0.2.0
4
+ Summary: Inference-only PT-BR typed predictors (load Hub weights + predict / system_one)
5
+ Author-email: Wendell Barreto <wendellbarreto@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/wendellbigato/serigy-jev
8
+ Project-URL: Hugging Face, https://huggingface.co/wendellperbar/serigy-jev
9
+ Project-URL: Hugging Face Golpes BR, https://huggingface.co/wendellperbar/serigy-golpes-br
10
+ Project-URL: Hugging Face T-Rex, https://huggingface.co/wendellperbar/serigy-trex
11
+ Requires-Python: >=3.14
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy>=1.26.0
15
+ Requires-Dist: pydantic>=2.5.0
16
+ Requires-Dist: torch
17
+ Requires-Dist: transformers>=4.40.0
18
+ Requires-Dist: sentence-transformers>=3.0.0
19
+ Requires-Dist: safetensors>=0.4.0
20
+ Requires-Dist: huggingface_hub>=0.24.0
21
+ Requires-Dist: python-dotenv>=1.0.0
22
+ Dynamic: license-file
23
+
24
+ <p align="center">
25
+ <img src="assets/brand/simbolo_transparente.png" alt="Serigy" width="140"/>
26
+ </p>
27
+
28
+ # Serigy
29
+
30
+ Classificador local de fake news em PT-BR. Carrega pesos do Hub e faz `predict`.
31
+ Também expõe primitivos System One: **Escolha**, **Indice**, **Verdadeiro**, **Prioridade**.
32
+
33
+ Marca: [`assets/brand/`](assets/brand/) · [spec](.cursor/specs/marca/spec.md).
34
+
35
+ ```bash
36
+ pip install serigy
37
+ ```
38
+
39
+ ```python
40
+ from serigy import SerigyModel
41
+
42
+ model = SerigyModel("wendellperbar/serigy-jev")
43
+ out = model.predict(
44
+ "Senado aprova lei que PROÍBE jogo de videogame para menores de 18 anos."
45
+ )
46
+ print(out["predicao"], out["score_final"], out["confianca_calibrada"])
47
+ ```
48
+
49
+ ```bash
50
+ serigy --texto "texto da notícia..."
51
+ ```
52
+
53
+ Se o sensor for gated, configure `HF_TOKEN`.
54
+
55
+ ### Saída (`predict` = Prioridade)
56
+
57
+ | Campo | Significado |
58
+ |-------|-------------|
59
+ | `predicao` | `Claramente Falso` / `Incerto/Misto` / `Claramente Verdadeiro` |
60
+ | `classe_ordinal` | `0`, `1` ou `2` |
61
+ | `score_final` | veracidade `0.0`…`1.0` |
62
+ | `confianca_calibrada` | perto de `1` = mais concentrado |
63
+ | `probabilidades` | massa em cada classe |
64
+
65
+ Critérios usam `type: "prioridade"` (alias de input: `ordinal_score`).
66
+
67
+ ### System One (`system_one`)
68
+
69
+ ```python
70
+ from serigy import SerigyModel, Escolha, Indice, Verdadeiro, Prioridade
71
+
72
+ model = SerigyModel("wendellperbar/serigy-jev")
73
+ result = model.system_one(
74
+ "texto a avaliar…",
75
+ {
76
+ "rota": Escolha(
77
+ instructions="Qual ação?",
78
+ criteria={"abaixar": None, "fazer_nada": None, "pular": None},
79
+ ),
80
+ "nivel": Indice(
81
+ instructions="Quão grave?",
82
+ criteria=["Baixa", "Média", "Alta"],
83
+ ),
84
+ "eh_fato": Verdadeiro(instructions="É verdadeira?"),
85
+ },
86
+ )
87
+ print(result.answers["rota"].escolha, result.answers["eh_fato"].verdadeiro)
88
+ # JSON público: result.as_public_dict()
89
+ ```
90
+
91
+ | Jev | Serigy | O que responde |
92
+ |-----|--------|----------------|
93
+ | Choice | `escolha` | Qual opção (conjunto fechado)? |
94
+ | Score | `indice` | Em que ponto do espectro (K∈[2,10])? |
95
+ | Noul | `verdadeiro` | A proposição é verdadeira? (P(sim)) |
96
+ | — | `prioridade` | Em qual de 3 patamares? (`predict` é atalho) |
97
+
98
+ CLI System One: `serigy --json '{"state":"…","questions":{…}}'`.
99
+
100
+ Spec pública: [`.cursor/specs/sdk-primitivos/spec.md`](.cursor/specs/sdk-primitivos/spec.md).
101
+
102
+ Pesos FakeNews: [huggingface.co/wendellperbar/serigy-jev](https://huggingface.co/wendellperbar/serigy-jev)
103
+
104
+ ### Golpes BR (System One)
105
+
106
+ Heads multi-task para mensagens de golpe/legítimas em PT-BR (staging `hf/golpes/` → Hub `wendellperbar/serigy-golpes-br`):
107
+
108
+ ```python
109
+ from serigy import SerigyModel, Escolha, Verdadeiro
110
+
111
+ model = SerigyModel("wendellperbar/serigy-golpes-br")
112
+ result = model.system_one(
113
+ "Confirme seu CPF neste link para liberar o PIX…",
114
+ {
115
+ "acao": Escolha(
116
+ instructions="Como tratar?",
117
+ criteria={"bloquear": None, "revisar": None, "entregar": None},
118
+ ),
119
+ "eh_golpe": Verdadeiro(instructions="É golpe?"),
120
+ },
121
+ )
122
+ ```
123
+
124
+ Sync / upload: [`hf/README.md`](hf/README.md) · card [`hf/golpes/README.md`](hf/golpes/README.md).
125
+
126
+ ### Extra: benchmark T-Rex (monorepo)
127
+
128
+ Comparativo Serigy × Jev × Laya no Chrome T-Rex Runner (`serigy_trex`):
129
+ [src/serigy_trex/README.md](src/serigy_trex/README.md) · [docs/RELATORIO_TREX.md](docs/RELATORIO_TREX.md) · [spec](.cursor/specs/trex-benchmark/spec.md).
130
+
131
+ MIT — Copyright © 2026 Wendell Barreto.
serigy-0.2.0/README.md ADDED
@@ -0,0 +1,108 @@
1
+ <p align="center">
2
+ <img src="assets/brand/simbolo_transparente.png" alt="Serigy" width="140"/>
3
+ </p>
4
+
5
+ # Serigy
6
+
7
+ Classificador local de fake news em PT-BR. Carrega pesos do Hub e faz `predict`.
8
+ Também expõe primitivos System One: **Escolha**, **Indice**, **Verdadeiro**, **Prioridade**.
9
+
10
+ Marca: [`assets/brand/`](assets/brand/) · [spec](.cursor/specs/marca/spec.md).
11
+
12
+ ```bash
13
+ pip install serigy
14
+ ```
15
+
16
+ ```python
17
+ from serigy import SerigyModel
18
+
19
+ model = SerigyModel("wendellperbar/serigy-jev")
20
+ out = model.predict(
21
+ "Senado aprova lei que PROÍBE jogo de videogame para menores de 18 anos."
22
+ )
23
+ print(out["predicao"], out["score_final"], out["confianca_calibrada"])
24
+ ```
25
+
26
+ ```bash
27
+ serigy --texto "texto da notícia..."
28
+ ```
29
+
30
+ Se o sensor for gated, configure `HF_TOKEN`.
31
+
32
+ ### Saída (`predict` = Prioridade)
33
+
34
+ | Campo | Significado |
35
+ |-------|-------------|
36
+ | `predicao` | `Claramente Falso` / `Incerto/Misto` / `Claramente Verdadeiro` |
37
+ | `classe_ordinal` | `0`, `1` ou `2` |
38
+ | `score_final` | veracidade `0.0`…`1.0` |
39
+ | `confianca_calibrada` | perto de `1` = mais concentrado |
40
+ | `probabilidades` | massa em cada classe |
41
+
42
+ Critérios usam `type: "prioridade"` (alias de input: `ordinal_score`).
43
+
44
+ ### System One (`system_one`)
45
+
46
+ ```python
47
+ from serigy import SerigyModel, Escolha, Indice, Verdadeiro, Prioridade
48
+
49
+ model = SerigyModel("wendellperbar/serigy-jev")
50
+ result = model.system_one(
51
+ "texto a avaliar…",
52
+ {
53
+ "rota": Escolha(
54
+ instructions="Qual ação?",
55
+ criteria={"abaixar": None, "fazer_nada": None, "pular": None},
56
+ ),
57
+ "nivel": Indice(
58
+ instructions="Quão grave?",
59
+ criteria=["Baixa", "Média", "Alta"],
60
+ ),
61
+ "eh_fato": Verdadeiro(instructions="É verdadeira?"),
62
+ },
63
+ )
64
+ print(result.answers["rota"].escolha, result.answers["eh_fato"].verdadeiro)
65
+ # JSON público: result.as_public_dict()
66
+ ```
67
+
68
+ | Jev | Serigy | O que responde |
69
+ |-----|--------|----------------|
70
+ | Choice | `escolha` | Qual opção (conjunto fechado)? |
71
+ | Score | `indice` | Em que ponto do espectro (K∈[2,10])? |
72
+ | Noul | `verdadeiro` | A proposição é verdadeira? (P(sim)) |
73
+ | — | `prioridade` | Em qual de 3 patamares? (`predict` é atalho) |
74
+
75
+ CLI System One: `serigy --json '{"state":"…","questions":{…}}'`.
76
+
77
+ Spec pública: [`.cursor/specs/sdk-primitivos/spec.md`](.cursor/specs/sdk-primitivos/spec.md).
78
+
79
+ Pesos FakeNews: [huggingface.co/wendellperbar/serigy-jev](https://huggingface.co/wendellperbar/serigy-jev)
80
+
81
+ ### Golpes BR (System One)
82
+
83
+ Heads multi-task para mensagens de golpe/legítimas em PT-BR (staging `hf/golpes/` → Hub `wendellperbar/serigy-golpes-br`):
84
+
85
+ ```python
86
+ from serigy import SerigyModel, Escolha, Verdadeiro
87
+
88
+ model = SerigyModel("wendellperbar/serigy-golpes-br")
89
+ result = model.system_one(
90
+ "Confirme seu CPF neste link para liberar o PIX…",
91
+ {
92
+ "acao": Escolha(
93
+ instructions="Como tratar?",
94
+ criteria={"bloquear": None, "revisar": None, "entregar": None},
95
+ ),
96
+ "eh_golpe": Verdadeiro(instructions="É golpe?"),
97
+ },
98
+ )
99
+ ```
100
+
101
+ Sync / upload: [`hf/README.md`](hf/README.md) · card [`hf/golpes/README.md`](hf/golpes/README.md).
102
+
103
+ ### Extra: benchmark T-Rex (monorepo)
104
+
105
+ Comparativo Serigy × Jev × Laya no Chrome T-Rex Runner (`serigy_trex`):
106
+ [src/serigy_trex/README.md](src/serigy_trex/README.md) · [docs/RELATORIO_TREX.md](docs/RELATORIO_TREX.md) · [spec](.cursor/specs/trex-benchmark/spec.md).
107
+
108
+ MIT — Copyright © 2026 Wendell Barreto.
@@ -0,0 +1,77 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "serigy"
7
+ version = "0.2.0"
8
+ description = "Inference-only PT-BR typed predictors (load Hub weights + predict / system_one)"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ authors = [{ name = "Wendell Barreto", email = "wendellbarreto@gmail.com" }]
12
+ requires-python = ">=3.14"
13
+ dependencies = [
14
+ "numpy>=1.26.0",
15
+ "pydantic>=2.5.0",
16
+ "torch",
17
+ "transformers>=4.40.0",
18
+ "sentence-transformers>=3.0.0",
19
+ "safetensors>=0.4.0",
20
+ "huggingface_hub>=0.24.0",
21
+ "python-dotenv>=1.0.0",
22
+ ]
23
+
24
+ [project.scripts]
25
+ serigy = "serigy.__main__:main"
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/wendellbigato/serigy-jev"
29
+ "Hugging Face" = "https://huggingface.co/wendellperbar/serigy-jev"
30
+ "Hugging Face Golpes BR" = "https://huggingface.co/wendellperbar/serigy-golpes-br"
31
+ "Hugging Face T-Rex" = "https://huggingface.co/wendellperbar/serigy-trex"
32
+
33
+ # Wheel/sdist = apenas inferência. serigy_train / serigy_trex ficam no git
34
+ # (pythonpath) e são removidos de novo no publish.yml por segurança.
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+ include = ["serigy", "serigy.*"]
38
+ exclude = ["serigy_train", "serigy_train.*", "serigy_trex", "serigy_trex.*"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+ pythonpath = ["src"]
43
+ markers = [
44
+ "smoke: integração real (checkpoint + sensor); requer RUN_SMOKE=1",
45
+ ]
46
+
47
+ [dependency-groups]
48
+ dev = [
49
+ "ipykernel>=7.3.0",
50
+ "pytest>=8.0.0",
51
+ ]
52
+ # Monorepo only (não vai no METADATA do PyPI):
53
+ train = [
54
+ "mlx>=0.31.2",
55
+ "mlx-lm>=0.31.0",
56
+ "datasets>=3.6,<4",
57
+ "scikit-learn>=1.4.0",
58
+ "tqdm>=4.66.0",
59
+ ]
60
+ bench = [
61
+ "typesafe-sdk>=0.1.0",
62
+ "pandas>=2.0.0",
63
+ "matplotlib>=3.8.0",
64
+ "seaborn>=0.13.0",
65
+ "ipywidgets>=8.0.0",
66
+ "jupyter>=1.0.0",
67
+ "laya>=0.3.3",
68
+ ]
69
+ # T-Rex arena / dataset / vídeo (spec trex-benchmark; fora do wheel PyPI)
70
+ trex = [
71
+ "pillow>=10.0.0",
72
+ "imageio>=2.34.0",
73
+ "imageio-ffmpeg>=0.5.0",
74
+ "tqdm>=4.66.0",
75
+ "typesafe-sdk>=0.1.0",
76
+ "laya>=0.3.3",
77
+ ]
serigy-0.2.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,44 @@
1
+ """Serigy — inferência pública (pip).
2
+
3
+ Uso:
4
+ from serigy import SerigyModel, Escolha, Verdadeiro
5
+ model = SerigyModel("wendellperbar/serigy-jev")
6
+ out = model.predict("texto da notícia...")
7
+ result = model.system_one(state, {"q": Verdadeiro(instructions="…?")})
8
+
9
+ Após cada upload no Hub, atualize DEFAULT_HUB_REVISION em cliente.py
10
+ (pin atual: 785ef7e842fb82409af027b4f9ee217a4e72f9d7).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from serigy.cliente import DEFAULT_REPO, SerigyModel
16
+ from serigy.primitivos.schemas import (
17
+ Escolha,
18
+ Indice,
19
+ Prioridade,
20
+ SystemOneRequest,
21
+ SystemOneResult,
22
+ Verdadeiro,
23
+ )
24
+
25
+ __all__ = [
26
+ "SerigyModel",
27
+ "DEFAULT_REPO",
28
+ "Escolha",
29
+ "Indice",
30
+ "Verdadeiro",
31
+ "Prioridade",
32
+ "SystemOneRequest",
33
+ "SystemOneResult",
34
+ ]
35
+
36
+ try:
37
+ from importlib.metadata import PackageNotFoundError, version
38
+
39
+ try:
40
+ __version__ = version("serigy")
41
+ except PackageNotFoundError:
42
+ __version__ = "0.2.0"
43
+ except ImportError: # pragma: no cover
44
+ __version__ = "0.2.0"
@@ -0,0 +1,112 @@
1
+ """CLI: python -m serigy --texto "..." | --json '{...}' | --stdin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from serigy.cliente import DEFAULT_REPO, SerigyModel, _saida_publica_system_one
12
+ from serigy.primitivos.schemas import SystemOneRequest
13
+
14
+
15
+ def _carregar_json(args: argparse.Namespace) -> dict[str, Any]:
16
+ if args.stdin:
17
+ return json.load(sys.stdin)
18
+ assert args.json is not None
19
+ raw = args.json
20
+ caminho = Path(raw)
21
+ if caminho.is_file():
22
+ return json.loads(caminho.read_text(encoding="utf-8"))
23
+ return json.loads(raw)
24
+
25
+
26
+ def main(argv: list[str] | None = None) -> int:
27
+ parser = argparse.ArgumentParser(
28
+ prog="serigy",
29
+ description="Inferência Serigy (schema público I/O)",
30
+ )
31
+ parser.add_argument(
32
+ "texto_posicional",
33
+ nargs="?",
34
+ default=None,
35
+ help="Texto da notícia (alternativa a --texto)",
36
+ )
37
+ parser.add_argument("--texto", default=None, help="Texto da notícia (predict)")
38
+ parser.add_argument("--fonte", default=None, help="Fonte opcional (predict)")
39
+ parser.add_argument(
40
+ "--json",
41
+ default=None,
42
+ help="System One: JSON (arquivo ou string) com state + questions",
43
+ )
44
+ parser.add_argument(
45
+ "--stdin",
46
+ action="store_true",
47
+ help="System One: ler envelope JSON de stdin",
48
+ )
49
+ parser.add_argument(
50
+ "--model",
51
+ default=DEFAULT_REPO,
52
+ help=f"Hub id ou pasta local (default: {DEFAULT_REPO})",
53
+ )
54
+ parser.add_argument(
55
+ "--revision",
56
+ default=None,
57
+ help="Revision Hub (commit/tag); default: SERIGY_HUB_REVISION / pin do pacote",
58
+ )
59
+ parser.add_argument(
60
+ "--allow-custom-models",
61
+ action="store_true",
62
+ help="Permite model_id/embedding fora da allowlist (só se confiar no checkpoint)",
63
+ )
64
+ parser.add_argument(
65
+ "--hf-token",
66
+ default=None,
67
+ help="Token HF (ou env HF_TOKEN)",
68
+ )
69
+ parser.add_argument(
70
+ "--warm",
71
+ action="store_true",
72
+ help="Pré-carrega o sensor antes da predição",
73
+ )
74
+ args = parser.parse_args(argv)
75
+
76
+ modo_system_one = bool(args.json or args.stdin)
77
+ texto = args.texto or args.texto_posicional
78
+ if modo_system_one and texto:
79
+ parser.error("use --texto OU --json/--stdin, não ambos")
80
+ if not modo_system_one and not texto:
81
+ parser.error("informe --texto, argumento posicional, --json ou --stdin")
82
+
83
+ print(f"carregando {args.model}…", file=sys.stderr)
84
+ model = SerigyModel(
85
+ args.model,
86
+ token=args.hf_token,
87
+ warm=args.warm,
88
+ revision=args.revision,
89
+ allow_custom_models=args.allow_custom_models,
90
+ )
91
+
92
+ if modo_system_one:
93
+ payload = _carregar_json(args)
94
+ req = SystemOneRequest.model_validate(payload)
95
+ result = model.system_one(req.state, req.questions)
96
+ out = _saida_publica_system_one(result)
97
+ print(json.dumps(out, ensure_ascii=False, indent=2))
98
+ return 0
99
+
100
+ out = model.predict(texto, fonte=args.fonte)
101
+ print(
102
+ f"→ {out['predicao']} | classe={out['classe_ordinal']} "
103
+ f"| score={out['score_final']:.3f} "
104
+ f"| confiança={out['confianca_calibrada']:.3f}",
105
+ file=sys.stderr,
106
+ )
107
+ print(json.dumps(out, ensure_ascii=False, indent=2))
108
+ return 0
109
+
110
+
111
+ if __name__ == "__main__":
112
+ raise SystemExit(main())
@@ -0,0 +1,46 @@
1
+ """Schemas + motor de inferência (uso interno; API pública = SerigyModel)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from serigy.api.schemas import (
8
+ ComponentesConfianca,
9
+ CriteriosAvaliacao,
10
+ InputEco,
11
+ MetricasInferencia,
12
+ NivelOrdinal,
13
+ Noticia,
14
+ NoticiaRequest,
15
+ OutputPredicao,
16
+ PesosComponentes,
17
+ PredicaoResponse,
18
+ ProbabilidadesOrdinais,
19
+ )
20
+
21
+ if TYPE_CHECKING:
22
+ from serigy.api.inferencia import MotorInferencia, predizer
23
+
24
+ __all__ = [
25
+ "Noticia",
26
+ "NivelOrdinal",
27
+ "CriteriosAvaliacao",
28
+ "NoticiaRequest",
29
+ "InputEco",
30
+ "ComponentesConfianca",
31
+ "PesosComponentes",
32
+ "ProbabilidadesOrdinais",
33
+ "OutputPredicao",
34
+ "MetricasInferencia",
35
+ "PredicaoResponse",
36
+ "MotorInferencia",
37
+ "predizer",
38
+ ]
39
+
40
+
41
+ def __getattr__(name: str) -> Any:
42
+ if name in ("MotorInferencia", "predizer"):
43
+ from serigy.api import inferencia as _inf
44
+
45
+ return getattr(_inf, name)
46
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")