Metadata-Version: 2.4
Name: infx
Version: 1.9.0
Summary: infx：会猜、会死、会留下记忆的推理力模块；内含 look 子模块（看图并指出下一个点）
Author: My AI Knowledge Library
License-Expression: MIT
Project-URL: Homepage, https://github.com/codersd-githubpythoncv/infx
Project-URL: Source, https://github.com/codersd-githubpythoncv/infx
Project-URL: Documentation, https://github.com/codersd-githubpythoncv/infx/tree/main/docs
Project-URL: Changelog, https://github.com/codersd-githubpythoncv/infx/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/codersd-githubpythoncv/infx/issues
Keywords: reasoning,evolutionary,death,vision,rnn,lmm,patterns,numpy,pandas
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=2.0
Provides-Extra: look
Requires-Dist: numpy>=1.24; extra == "look"
Requires-Dist: pandas>=2.0; extra == "look"
Requires-Dist: torch>=2.0; extra == "look"
Provides-Extra: vision
Requires-Dist: torch>=2.0; extra == "vision"
Provides-Extra: math
Requires-Dist: scipy>=1.10; extra == "math"
Requires-Dist: sympy>=1.12; extra == "math"
Requires-Dist: mpmath>=1.3; extra == "math"
Provides-Extra: net
Requires-Dist: requests>=2.28; extra == "net"
Provides-Extra: crawl
Requires-Dist: requests>=2.28; extra == "crawl"
Requires-Dist: scrapling>=0.5; extra == "crawl"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Provides-Extra: all
Requires-Dist: numpy>=1.24; extra == "all"
Requires-Dist: pandas>=2.0; extra == "all"
Requires-Dist: torch>=2.0; extra == "all"
Requires-Dist: scipy>=1.10; extra == "all"
Requires-Dist: sympy>=1.12; extra == "all"
Requires-Dist: mpmath>=1.3; extra == "all"
Requires-Dist: requests>=2.28; extra == "all"
Requires-Dist: scrapling>=0.5; extra == "all"
Dynamic: license-file

# infx

**Guess. Die. Remember. Look.**

`infx` (PyPI: `infx`) is an offline Python toolkit that does two things:

1. **Judges text** — is a sentence a *fact* or an *opinion*? Backed by an 808-rule
   grammar base, a negation-scope analyser, and optional hand-written or PyTorch
   models.
2. **Looks at data** — picks the next fixation point in a 2D image or a 3D volume,
   connects what it saw, and reports a residual that defines "approaching the truth".

The reasoning core needs only `numpy` + `pandas`. Torch is optional and used only
by the RNN eye and the torch model wrapper. No UI, no network calls, no GPU.

Docs: [quickstart](docs/quickstart.md) · [architecture](docs/architecture.md) · [contributing](CONTRIBUTING.md)

---

## Install

```bash
pip install infx               # core: numpy + pandas
pip install "infx[look]"       # adds torch (RNN eye + torch backend)
```

Python 3.11+.

## Two entry points

| Entry point | Import | Command | Needs |
|---|---|---|---|
| Reasoning | `import infx` | `infx "text"` / `python -m infx` | numpy, pandas |
| Vision | `import infx.look` | `infx-look --demo` / `python -m infx.look` | numpy, math, pandas, torch |

```bash
infx "据新华社报道，会议于 2024 年 3 月举行。"
infx-look --demo --saliency --eye
infx-look --3d
```

`look` is a subpackage of the library, not a separate project — but it has its own
API and CLI, and is allowed to depend only on the foundation layer.

## What it does not do

- It does **not** decide whether a sentence is *true*. It decides which *kind* of
  claim it is, and says what evidence would verify it.
- It does **not** ship a trained LLM. `look.lmm.load_lmm()` raises instead of
  pretending; the offline LMM is a statistical descriptor.
- It does **not** beat PyTorch. See the honest table below.

## Judge a sentence

```python
import infx

result = infx.assess("据新华社报道，温度达到 100 摄氏度。")
result.label.value, result.confidence        # ('fact', 0.83)
infx.speak(result)                           # human-readable verdict

infx.judge_claim(infx.Claim(text="The design is awful.")).label.value   # 'opinion'
```

`assess` splits text into claims and aggregates; `judge_claim` judges one claim.

## Look: where to look next

```python
from infx import look

sight = look.scan(image, steps=3, glimpse=8)
sight.next_point            # Point(row=4, col=4, saliency=1.0, reason="saliency 1.00")
look.explain(sight)         # "seen 3 spots: (4,4) -> (0,0) -> (2,1). Next: (2,2) ..."
```

Two explainable rules: **saliency** (`|block mean − global mean| + block std`) and
**novelty** (exponential decay with distance from already-seen points).

## Look at 3D until nothing is left

```python
sight = infx.scan_3d(volume, steps=8, glimpse=4)   # 3D array or (N,3) point cloud
sight.edges                                        # automatic connections (MST, n-1 edges)
sight.residual()                                   # share of saliency not yet seen

trace = infx.approach_truth(volume, steps=8, tol=0.02)
trace.converged, trace.residuals                   # True, [0.327, 0.0, 0.0]
```

"Approaching the truth" is defined, not asserted: the residual is the share of
saliency mass not yet covered. It falls monotonically; when the marginal gain
drops below `tol`, the eye has seen what there was to see.

Connections are automatic: `mst` (space skeleton, n-1 edges, no cycles) or
`saccade` (the path the eye actually took).

## Models: bring your own

```python
from infx.models import TorchModel, build_mlp, fit, judges_with_model
from infx.core.schema import Claim
from infx.core.pipeline import judge_claim

model = TorchModel(build_mlp(64, 32, 2, seed=2), name="mine")
report = fit(model, X, y, epochs=80)              # loss 0.706 -> 0.000
verdict = judge_claim(Claim(text="这个方案很糟糕"),
                      judges=judges_with_model(model, dim=64))
# opinion, cues include 'model'
```

Let a model decide where to look:

```python
from infx.models import TorchSaliency, set_saliency_provider

set_saliency_provider(TorchSaliency(vision_model))
look.scan(image, steps=2)          # saliency now comes from your model
```

Three deliberate choices: the cue weight is "how far from 0.5" (a hesitant model
contributes little); dimension mismatches raise instead of being swallowed as an
error cue; a broken model falls back to the built-in saliency formula.

### Hand-written model (no PyTorch)

```python
from infx.models import NumpyMLP, fit, numerical_grad_check

model = NumpyMLP(64, 32, 2, seed=0)     # forward and backward written by hand
fit(model, X, y, epochs=80)              # Adam, pure numpy
numerical_grad_check(model, X, y)        # gradients vs finite differences -> 5.4e-09
```

**"Stronger than PyTorch" is true in exactly three narrow ways:**

| Dimension | Hand-written numpy | PyTorch |
|---|---|---|
| Dependencies | **0** (numpy is already there) | ~2 GB |
| Gradient auditability | hand-derived + finite-difference checked (5.4e-09) | autograd, opaque |
| CPU determinism | fully deterministic | thread/kernel dependent at the last bit |
| **Speed and scale** | fine for small models | **wins outright** |

Benchmark, 160 samples × 8 dims × 40 epochs, on this CPU:

```
impl      framework    params    accuracy    train time
numpy     numpy           178        100%       12.8 ms
torch     torch           178        100%     3019.2 ms
```

⚠️ The 3 seconds is mostly torch's first-call initialisation, not its throughput.
**Do not advertise this as "faster than PyTorch"** — on speed and scale it loses.

Any object with `predict` / `predict_proba` can be plugged in, including a plain
function:

```python
from infx.models import register, build, wrap_predict

register("my-model", lambda: MyModel(path="..."))
model = build("my-model")
model = wrap_predict(lambda x: np.array([0.1, 0.9]), name="rule")
```

## Exact layer: symbolic and arbitrary precision

`pip install "infx[math]"` adds three libraries used for **verification**, not speed.

```python
from infx.exact import SymbolicNet, differentiate, high_precision

differentiate("x**3 + 2*x", "x")        # '3*x**2 + 2'  (exact, not a float)
differentiate("sin(x)", "x", order=2)   # '-sin(x)'

import mpmath
high_precision(mpmath.exp, 1, dps=50)[:16]   # '2.7182818284590'
```

**`SymbolicNet` produces gradients by symbolic differentiation.** The derivative is
derived exactly by sympy once, then evaluated numerically — so checking it against
finite differences is not "two floats agree" but "the float matches the true
derivative":

```python
net = SymbolicNet([2, 3, 2], activation="tanh", seed=0)
w, b = net.init_params()
loss, gw, gb = net.loss_and_grads(X, y, w, b)
net.check_gradients(X, y, w=w, b=b).describe()
# 符号梯度校验通过：17 个参数，最大绝对误差 1.07e-10
```

Measured agreement with central differences: **1e-10 to 1e-11** for tanh, sigmoid,
linear and relu.

⚠️ **This is not faster than PyTorch — it is slower, by a lot.** Symbolic
differentiation is expensive. Use `SymbolicNet` to prove that the fast path
(`NumpyMLP`, or your own model) has correct gradients, then train with the fast path.

Also available: `integrate`, `exact_value`, `compare_with_precision`,
`solve_ivp_reference`, `check_against_scipy`, `stats_reference`, `optimise`.

## Go and check: the network layer

`pip install "infx[net]"` — or `"infx[crawl]"` to add scrapling.

The rule this layer enforces: **a guess is labelled a guess; a fetched fact carries
its URL and its timestamp.**

```python
import infx

fetcher = infx.net.Fetcher()          # scrapling → requests → urllib, auto
result = fetcher.get("https://pypi.org/project/infx/")
result.status, result.elapsed_ms, result.backend
# (200, 412.3, 'requests')

report = infx.net.benchmark(["https://pypi.org/project/infx/"] * 3)
report.describe()      # '3/3 成功 · 均值 390 ms · 最快 307 ms · 最慢 454 ms'
```

**Verification, not vibes:**

```python
v = infx.net.verify("some claim", ["https://a.com/x", "https://b.com/y"])
v.describe()     # '取到 2 个来源 → 判定 fact（独立分组 2）'
```

Two pages on the **same host** count as one voice — that is what makes the verdict
mean something. And a failed fetch produces **no source, not a fake one**: if
everything fails, the claim stays unjudged.

**Politeness is a default, not an option**: 0.5 s minimum per host, an honest
User-Agent, optional `robots.txt` checking, and a retry cap. This is a verification
tool; deliberately not a bulk scraper.

**On "fast access"**: this module measures speed, it does not promise it. Every
number above came from a real request at that moment; your network and target will
differ.

## How judgment works

```
L0  foundation   core  judgment  grammar  patterns  death  knowledge  deps
L1  reasoning    colony  steps  truth  settle  syntax  similarity  models
L2  integration  table  spoken  look  batch  report  cli     <- dependencies only point down
```

- `core` splits claims, collects cues, combines weighted cues into a label.
- `judgment` holds hand-written, high-confidence detectors.
- `grammar` holds **808 rules as data**: Chinese 532 / English 276, 26 kinds,
  each with a stable id so a hit is traceable (`zh.src.900` = "据新华社报道").
- `syntax` adds what word lists cannot see: **negation scope** ("这并不重要" is
  negation applied to an evaluation), clauses, conditionals, reported speech.

```python
from infx import grammar
grammar.stats()          # {'total': 808, 'by_lang': {'zh': 532, 'en': 276}, ...}
grammar.match("据新华社报道，温度达到 100 摄氏度。")
# [RuleMatch(zh.src.900, '据新华社报道'), RuleMatch(zh.measure.001, '100 摄氏度')]
```

Rules are generated from word lists; adding a word adds a rule. The 808-rule base
is a coverage ceiling, not a usage count — on 59 sentences only 50 rules fire.

## How guessing works

`Colony` keeps hypotheses in fixed slots. Each round:

```
score   all hypotheses at once (stacked tensor W (size, d, k) + einsum)
rank    by (accuracy, confidence margin)
strike  the worst cull_ratio get one strike (the leader is protected)
death   a strike at the limit empties the slot and leaves a tombstone fingerprint
revive  the same slot is rebuilt: breed (copy an elite + additive mutation) or explore
anneal  shrink the step size when progress stalls, restore it when it returns
```

Slots never move. Only their contents die. Three hard-won insights:

1. Culling without breeding never learns (accuracy deadlocked at 0.61).
2. Multiplicative noise cannot rotate a weight vector — additive noise can.
3. Cull by rank, not by absolute score: "below average" moves the bar with the average.

## Quality: the honest numbers

| Set | Size | Accuracy | Macro F1 | What it really is |
|---|---|---|---|---|
| `quality.LABELED` | 49 | **100%** | 1.000 | written while tuning the rules — **not a blind test**, it is a regression guard |
| `quality.ADVERSARIAL` | 10 | **90%** | 0.859 | written against known weaknesses: sarcasm, double negation, conditionals |

```bash
python -c "from infx import quality; print(quality.report(quality.evaluate(quality.LABELED)))"
```

Evaluate on your own data — the function takes any `[(text, label)]`:

```python
from infx import quality
quality.evaluate([("温度为 100 摄氏度。", "fact"), ("这个方案很棒。", "opinion")])
```

Also measured: the grammar engine runs at **0.20 ms per sentence** (808 rules,
language-filtered), and only a fraction of rules fire on the 59-sentence probe corpus.

## Known limits

| Do not expect | Why |
|---|---|
| To beat a Transformer | This is a mechanism prototype, no pretraining |
| Guaranteed 100% accuracy | Rule-based; complex structures fail |
| Real image understanding | `Eye`'s GRU is untrained; `OfflineLMM` is a descriptor |
| Automatic web verification | `Resolver` needs you to inject a fetcher |
| A UI | Results are numpy arrays and pandas frames |

## Development

```bash
python -m unittest discover -s tests -t .      # 408 tests, ~6 s
```

Some tests are architecture tests: they parse the real import graph and fail on
upward dependencies, wrong dependency declarations, or name clashes.

```bash
python release.py status      # local version vs PyPI
python release.py bump patch  # bump version + CHANGELOG skeleton
python release.py check       # version + tests + build + twine check
python release.py publish     # upload + verify hash from PyPI
```

Hard gates: the version must agree in `pyproject.toml`, `infx/__init__.py` and the
top CHANGELOG section; a CHANGELOG section with an unfilled placeholder bullet is
refused.

## Repository layout

```
inference/                  # project (PyPI distribution name: infx)
├── infx/                   # the package (import infx)
│   ├── core/               # Claim, Cue, Verdict, scoring, text splitting
│   ├── judgment/           # hand-written fact/opinion detectors
│   ├── base/               # substrate: tensors, params, meters, budgets, checkpoints
│   ├── grammar/            # 808 rules: lexicon -> rules -> engine -> judge
│   ├── syntax/             # clauses, negation scope, syntax profile
│   ├── spoken/             # phrasing by confidence
│   ├── look/               # 2D fixation, RNN eye, LMM stub, 3D approach, tables
│   ├── models/             # torch wrapper, hand-written numpy MLP, registry, benchmark
│   ├── colony.py           # guess / die / revive
│   ├── death.py            # life state, tombstones, residue
│   ├── patterns.py         # six structure kinds + EvolvingPool
│   ├── steps.py            # arbitrary-length, nestable, learnable step sequences
│   ├── truth.py            # single source = opinion, independent sources = fact
│   ├── settle.py           # re-verify, re-pursue, re-learn
│   ├── knowledge.py        # fact graph
│   ├── table.py            # pandas result store
│   ├── batch.py            # JSONL batch judging
│   ├── similarity.py       # Jaccard / cosine / dedupe
│   ├── report.py           # Markdown and text reports
│   ├── quality.py          # labelled regression sets and metrics
│   └── deps.py             # dependency self-check
├── tests/                  # 408 tests
├── docs/                   # quickstart, architecture
├── examples/               # runnable demos
├── scripts/                # publish_github.py (git-less GitHub publishing)
├── release.py              # one-command release
└── pyproject.toml
```

## License

MIT.
