Metadata-Version: 2.4
Name: sieve-lens
Version: 0.23.0
Summary: Invisible Prompt Observation Engine (Zero-Dependency, Deterministic)
Author: Kai IWASAKI
License: MIT
Project-URL: Homepage, https://github.com/neguseatama/sieve-lens
Project-URL: Repository, https://github.com/neguseatama/sieve-lens.git
Project-URL: Bug Tracker, https://github.com/neguseatama/sieve-lens/issues
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Text Processing :: Filters
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: pdf
Requires-Dist: pypdf>=4.0; extra == "pdf"
Provides-Extra: pdf-images
Requires-Dist: pypdf>=4.0; extra == "pdf-images"
Requires-Dist: Pillow>=10.0; extra == "pdf-images"
Requires-Dist: pytesseract>=0.3.10; extra == "pdf-images"
Provides-Extra: ocr
Requires-Dist: Pillow>=10.0; extra == "ocr"
Requires-Dist: pytesseract>=0.3.10; extra == "ocr"
Provides-Extra: html-css
Requires-Dist: tinycss2>=1.1; extra == "html-css"
Provides-Extra: html-css-full
Requires-Dist: tinycss2>=1.1; extra == "html-css-full"
Requires-Dist: cssselect2>=0.7; extra == "html-css-full"
Provides-Extra: dashboard
Requires-Dist: Jinja2>=3.0; extra == "dashboard"
Requires-Dist: Plotly>=5.0; extra == "dashboard"
Provides-Extra: pdf-report
Requires-Dist: weasyprint>=60.0; extra == "pdf-report"
Requires-Dist: Jinja2>=3.0; extra == "pdf-report"
Requires-Dist: Plotly>=5.0; extra == "pdf-report"
Requires-Dist: kaleido>=0.2; extra == "pdf-report"
Provides-Extra: all
Requires-Dist: pypdf>=4.0; extra == "all"
Requires-Dist: Pillow>=10.0; extra == "all"
Requires-Dist: pytesseract>=0.3.10; extra == "all"
Requires-Dist: tinycss2>=1.1; extra == "all"
Requires-Dist: cssselect2>=0.7; extra == "all"
Requires-Dist: Jinja2>=3.0; extra == "all"
Requires-Dist: Plotly>=5.0; extra == "all"
Requires-Dist: weasyprint>=60.0; extra == "all"
Requires-Dist: kaleido>=0.2; extra == "all"
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: setuptools>=61; extra == "test"
Requires-Dist: wheel; extra == "test"
Dynamic: license-file

# Sieve Lens v0.23.0

**Invisible Prompt Observation Engine**

*Sieve Lens is not a tool that distrusts AI.*  
*It is a tool that helps AI receive trustworthy input.*

> Zero-dependency, deterministic, explainable observation of invisible content
> in documents (resumes, submissions, reports) that may be intended to
> influence AI-based evaluation systems.

Extends the [Sieve](https://github.com/neguseatama/sieve-core) series to the
domain of **machine-readable vs. human-visible divergence**.

[![CI](https://github.com/neguseatama/sieve-lens/actions/workflows/tests.yml/badge.svg)](https://github.com/neguseatama/sieve-lens/actions/workflows/tests.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python Version](https://img.shields.io/badge/python-3.9%20%7C%203.10%20%7C%203.11%20%7C%203.12-blue)](https://www.python.org/)

**English** | [日本語](README.ja.md)

## What is Sieve Lens?

Sieve Lens finds text that an AI can read as a prompt.

Some documents contain text that a person can't see but an AI can read.
Lens compares **the path an AI reads** (the text inside the document) with
**the path a person sees** (what is drawn on screen), and reports **text
the AI can read but a person can't see**.

- The same document always gives the same result (deterministic).
- Lens doesn't judge intent. It reports what it found.
- It can also extract only the visible text (hidden text is not included).

---

## 🧩 The Sieve Series

Sieve is a family of deterministic, zero-dependency engines that share
the same design principles (deterministic output, no telemetry, fully
local) — each engine observes or masks one specific risk, and they
compose:

| Package | Role | Connects to |
|---------|------|-------------|
| [sieve-core-engine](https://github.com/neguseatama/sieve-core) | Foundational engine for deterministic structure aggregation and confidence scoring | — |
| [sieve-referee](https://github.com/neguseatama/sieve-referee) | Observes text structure, reuse, and paraphrase | — |
| [sieve-scope](https://github.com/neguseatama/sieve-scope) | Observes structural similarity of source code | — |
| [sieve-lens](https://github.com/neguseatama/sieve-lens) | Observes invisible content and concealment elements | → redact via `--from-lens` |
| [sieve-redact](https://github.com/neguseatama/sieve-redact) | Deterministic masking of designated regions with completeness verification | ← lens, → tray |
| [sieve-order](https://github.com/neguseatama/sieve-order) | Observes the surface structure of prompts in a 6-bit observation space | — |
| [sieve-crowd](https://github.com/neguseatama/sieve-crowd) | Table-data anonymization and privacy-protection engine | — |
| [sieve-tray](https://github.com/neguseatama/sieve-tray) | Local front-end that integrates the engines | ← all engines |

Observation → masking in one pass: Lens finds what a human can't see,
Redact removes it with a receipt that proves nothing else changed.

## 📐 7-bit Observation Space

| Bit | Name | What it observes |
|-----|------|------------------|
| H1 | Parseability | The file can be read and parsed |
| H2 | Zero-Width Density | Density of zero-width chars exceeds threshold |
| H3 | Bidi Controls | Bidi control characters present |
| H4 | Format Concealment | CSS hiding rules (`display:none`, etc.); DOCX concealment (hidden-text formatting / near-invisible colour / tiny font / tracked deletions) |
| H5 | Out-of-Band Channel | Meaningful content in comments / metadata / headers / footers / footnotes |
| H6 | Script Mixing | Latin+Cyrillic or Latin+Greek mixed within a token |
| H7 | Contiguous Payload | A run of ≥ N contiguous invisible chars exists |

Mask format: `H1H2H3H4-H5H6H7` (e.g., `1000-100`).

---

## 📦 Supported Formats

| Format | Coverage | Dependencies |
|--------|----------|--------------|
| `.txt`, `.md` | Plain text, full character-level scanning | none (core) |
| `.html`, `.htm` | HTML with inline-style and `<style>` block concealment detection; optional external CSS resolution | none (core); `tinycss2` (optional) |
| `.docx` | Body, comments, core properties, headers, footers, footnotes, endnotes; concealment observation (hidden-text formatting, near-invisible colour, tiny font, tracked deletions) | none (core) |
| `.pdf` | Body text, metadata, annotations, invisible text (Tr 3), Form XObject text (Tr 3 / raw stream) | `pypdf` (optional) |
| `.png`, `.jpg`, `.jpeg`, `.gif`, `.bmp`, `.tif`, `.tiff`, `.webp` | Metadata (EXIF / PNG text / XMP) + OCR text | `Pillow`, `pytesseract` + tesseract binary + language packs (optional) |

**Not supported**: audio, video.

---

## 🔥 Key Features

- **7-bit observation space (H1–H7)**  
  Independent, deterministic detection of each class of invisible content.
- **Zero dependencies**  
  Python standard library only. Runs offline, no telemetry, no network.
- **Deterministic**  
  Same input always yields the same observation, on any platform.
- **Explainable**  
  Every observation carries location and decoded content, so a human can verify.
- **Observation, not judgment**  
  The engine reports evidence. It never declares "this is an attack".
- **Self-contained HTML report** (since v0.1)  
- **PDF support** via `pypdf` (since v0.2)  
- **Image OCR support** via `Pillow` + `pytesseract` (since v0.3)  
  OCR language is configurable: `install(engine, ocr_lang="eng+jpn")`
- **Interactive HTML dashboard** (since v0.5)  
  Batch-analyze a directory and produce a single self-contained dashboard
  with summary cards, mask distribution, hypothesis activation charts,
  and a sortable file table. Requires `Jinja2` + `Plotly`.
- **Printable PDF report** (since v0.6)  
  Generate an A4 PDF report from a directory of documents. Includes
  summary, hypothesis table, mask distribution, and a color-coded file
  list. Requires `weasyprint` (and optionally `kaleido` for charts).
- **Image layer analysis** (since v0.7)  
  Detects pixel-level concealment in images: transparent RGBA layers
  carrying non-zero RGB values, and low-contrast text with a WCAG ratio
  below 2:1. Requires `Pillow`.
- **Full CSS selector resolution** (since v0.8)  
  Extends the HTML extractor with full CSS selector matching via
  `cssselect2`: descendant, child, sibling, attribute, and pseudo-class
  selectors. Hidden rules are only reported when they match an element.
- **Report internationalization (i18n)** (since v0.9)  
  Dashboard and PDF reports are available in English and Japanese.
  Auto-detection selects the language based on input document content.
- **PDF embedded image analysis** (since v0.10)  
  Extracts images embedded in PDF pages and applies OCR, transparent
  layer detection, low-contrast detection, and metadata analysis to
  each image. Requires `pypdf` + `Pillow`.
- **PDF Form XObject text scanning** (since v0.15)  
  Text inside Form XObject content streams, including invisible (Tr 3)
  text, is scanned with the same semantics as page content streams;
  nested forms are walked with cycle protection (depth cap of 8).
- **Control-syntax audit lane** (since v0.17)  
  Observes documents for LLM prompt-boundary patterns: chat-template
  special tokens (`<|im_start|>`, `[INST]`, `<<SYS>>`), override phrases
  in English and Japanese, and pseudo structural tags. Occurrences in
  declared system zones (document metadata) are counted and passed
  through; unbacked occurrences become receipt findings with pattern,
  location, and offset. The lane records surface facts only and never
  declares intent. The vocabulary is an external JSON
  (`control_vocab_v1.json` ships as a reference copy; the embedded
  default applies unless a file override is given).
- **Geometry concealment lane** (since v0.17, H8 html; PDF subscan v0.18)  
  Observes geometric concealment styles that keep text parseable while
  rendering it invisible to human readers: sub-pixel `font-size`,
  near-zero `opacity`, collapsed `transform: scale(...)`, and zero
  `line-height`. Inline style attributes are scanned with the standard
  library; `<style>` blocks and local `<link>` stylesheets are parsed
  when tinycss2 is installed. The PDF subscan walks page content
  streams and Form XObjects and observes tiny `Tf` font sizes and
  `Tm` placements outside the page MediaBox (Tr 3 stays with the PDF
  extension's H4 coverage). The threshold set is an external JSON
  (`geometry_thresholds_v2.json` ships as a reference copy; embedded
  defaults apply unless a file override is given). The receipt records
  rule, raw value, measured number, threshold, and position - facts
  only, no intent judgment.
- **Bounded document reading (L1: safe reading)** (v0.19+)
  Every input is checked before it is parsed. Oversized, encrypted or broken files are refused with one of 13 clear reason codes — and nothing else travels out: no content, no file names.

- **DOCX concealment observation (L2)** (v0.20+)
  Finds the invisible text a `.docx` can carry: hidden-text marks, tiny fonts, letters painted into the background, and leftovers of tracked deletions — reported as separate `hidden` segments next to the body text. Background colour is resolved through Word's highlight, shading and theme settings. Documents with broken style/theme/settings parts are refused instead of ignored.

- **Pinned character table** (v0.21+)
  Lens ships the character table the Sieve tools share (`chartable_v1.json`, fixed by sha256): the invisible characters, the look-alike twins, and the fullwidth/space/dash folding rules in one file. The loader verifies the pin on every load — a missing, tampered or malformed table is a hard error, never a silent fallback. See `docs/CHARTABLE.md`.

- **Visible text extraction** (since v0.22.0)  
  `visible_text(observation)` returns just what a human reader sees:
  the visible segments in order, joined by a single newline; empty
  segments are dropped and nothing is re-extracted. An optional
  `strip` set removes the five invisible-character kinds
  (zero-width spaces, word joiners, mid-text BOMs, bidi controls, tag
  characters) with per-kind counts, while emoji joins (ZWJ), Japanese
  IVS (variation selectors) and flag emoji sequences survive.

- **Series-wide character codes for text and HTML** (since v0.22.0)  
  Plain text and HTML inputs decode with the series-wide policy: UTF-8
  BOM, then strict UTF-8, then strict CP932, refused otherwise;
  UTF-16/UTF-32 BOMs are refused outright and `errors="replace"` is
  never used. A CP932 detection adds one `encoding_name` diagnostics
  item; UTF-8 inputs observe exactly as before.

## 📦 Installation

```bash
# Core (zero-dependency)
pip install sieve-lens

# From PyPI (for released versions)
pip install "sieve-lens[pdf]"
pip install "sieve-lens[ocr]"

# Or the latest from GitHub
pip install "sieve-lens[pdf] @ git+https://github.com/neguseatama/sieve-lens.git"
pip install "sieve-lens[ocr] @ git+https://github.com/neguseatama/sieve-lens.git"
```

PDF report charts require Chrome/Chromium when generated with kaleido 1.x.

---

## 💻 Quick Start

```python
from sieve_lens import SieveLensEngine, format_report, format_report_html

engine = SieveLensEngine()
obs = engine.observe("resume.docx")

print(obs.mask)                    # e.g. "1000-100"
print(obs.h_states)                # {'H1': 1, 'H2': 0, ..., 'H7': 0}
print(format_report(obs))          # human-readable text report

html = format_report_html(obs)     # self-contained HTML report
```

To write the HTML report to a file:

```python
from sieve_lens import write_report_html
write_report_html(obs, "report.html")
```

### PDF (requires the `pdf` extra)

```python
from sieve_lens import SieveLensEngine
from sieve_lens_ext.pdf import install

engine = SieveLensEngine()
install(engine)                    # attach .pdf support
obs = engine.observe("resume.pdf")
print(obs.mask)
```

### Image OCR (requires the `ocr` extra)

```python
from sieve_lens import SieveLensEngine
from sieve_lens_ext.ocr import install

engine = SieveLensEngine()
install(engine, ocr_lang="eng+jpn")    # tesseract language packs
obs = engine.observe("screenshot.png")
print(obs.mask)
```

---

## 🔬 Testing

```bash
# Full suite (pytest; missing optional deps are skipped)
python -m pytest tests/ -q

# Per-suite (unittest discover)
# v0 test suite
python -m unittest discover -s tests -p "test_sieve_lens.py" -v

# v0.1 test suite
python -m unittest discover -s tests -p "test_sieve_lens_v0_1.py" -v

# v0.2 PDF extension (requires pypdf)
python -m unittest discover -s tests -p "test_sieve_lens_pdf.py" -v
```

---

## 📋 Sieve Schema Contract v1 (v0.18.0)

Vocabulary and threshold JSON files follow one strict contract shared by the
Sieve tools (details in `docs/SCHEMA_CONTRACT_v1.md`):

- **Strict** — duplicate keys, `NaN`/`Infinity` and inputs over 1 MiB are refused; the built-in defaults apply instead
- **Refuse, don't ignore** — keys outside the contract are rejected
- **Conformance corpus** — the contract is verified by 44 accept/reject cases

---

## 🔗 Redact Bridge (v0.12.0)

Exports an observation catalog (JSON) that
[Sieve Redact](https://github.com/neguseatama/sieve-redact) consumes directly:

    python -m sieve_lens_ext.redact_bridge input.txt catalog.json
    python -m sieve_redact input.txt -o clean.txt --from-lens catalog.json

- The catalog carries the kind, codepoint, count and positions (first-seen
  order) of each observation.
- Look-alike characters (Cyrillic/Greek -> Latin, full-width digits and
  letters -> ASCII, 102 entries) carry a `twin` field, which Redact converts
  into a replacement rule; invisible characters become deletions.
- Lens and Redact share the same definition of what counts as invisible.

---

## Good to know

1. **Observation, not judgment.** Lens reports surface facts — the final confirmation is human. Visible text tricks such as paraphrasing are outside the scan.
2. **OCR needs language packs.** Without the pack for a language, OCR text is simply 0 — no error is raised.
3. **DOCX means the standard Transitional format.** Strict-OOXML documents are refused (`unsupported_namespace`) — re-save them in the standard format and their content becomes observable.
4. **Kanji are shared between Japanese and Chinese.** A Chinese-language document may be detected as Japanese.

---

## 📄 License

MIT License. See [LICENSE](LICENSE) for details.

---

## 👤 Author

* **Kai IWASAKI**
