litmus-cli 0.3.0__py3-none-any.whl
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.
- litmus/__init__.py +27 -0
- litmus/artifact.py +179 -0
- litmus/cli.py +342 -0
- litmus/detectors/__init__.py +3 -0
- litmus/detectors/base.py +56 -0
- litmus/exif.py +158 -0
- litmus/inspectors/__init__.py +32 -0
- litmus/inspectors/base.py +36 -0
- litmus/inspectors/c2pa.py +159 -0
- litmus/inspectors/file_metadata.py +210 -0
- litmus/inspectors/office_metadata.py +54 -0
- litmus/inspectors/text_markers.py +75 -0
- litmus/inspectors/unicode_scan.py +308 -0
- litmus/io.py +54 -0
- litmus/model.py +173 -0
- litmus/office.py +198 -0
- litmus/pipeline.py +464 -0
- litmus/providers/__init__.py +17 -0
- litmus/providers/registry.py +239 -0
- litmus/reporting.py +150 -0
- litmus/server.py +176 -0
- litmus/transform/__init__.py +12 -0
- litmus/transform/base.py +30 -0
- litmus/transform/code_structural.py +119 -0
- litmus/transform/file_strip.py +148 -0
- litmus/transform/text_normalize.py +257 -0
- litmus/validate/__init__.py +3 -0
- litmus/validate/binary.py +75 -0
- litmus/validate/code.py +165 -0
- litmus/validate/office.py +73 -0
- litmus/validate/structural.py +136 -0
- litmus/validate/text.py +158 -0
- litmus/validate/treesitter_code.py +129 -0
- litmus/web_ui.py +728 -0
- litmus_cli-0.3.0.dist-info/METADATA +108 -0
- litmus_cli-0.3.0.dist-info/RECORD +39 -0
- litmus_cli-0.3.0.dist-info/WHEEL +4 -0
- litmus_cli-0.3.0.dist-info/entry_points.txt +2 -0
- litmus_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Provider capability matrix.
|
|
2
|
+
|
|
3
|
+
Knowledge about what each provider marks, and whether anyone outside the
|
|
4
|
+
provider can verify it, is **data with citations**. Updating a claim is a data
|
|
5
|
+
edit plus a source URL, not a code change.
|
|
6
|
+
|
|
7
|
+
Every row carries an ``EvidenceLabel``. A row must never assert
|
|
8
|
+
``CONFIRMED`` without an official provider URL in ``source``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from enum import StrEnum
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel, Field
|
|
16
|
+
|
|
17
|
+
from ..model import ArtifactKind, EvidenceClass, EvidenceLabel
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Detectability(StrEnum):
|
|
21
|
+
#: A public, usable detector exists today.
|
|
22
|
+
PUBLIC_DETECTOR = "public_detector"
|
|
23
|
+
#: The signal is structurally readable without a provider service.
|
|
24
|
+
LOCALLY_READABLE = "locally_readable"
|
|
25
|
+
#: The provider states the signal exists but publishes no detector.
|
|
26
|
+
NO_PUBLIC_DETECTOR = "no_public_detector"
|
|
27
|
+
#: A detector is announced but not yet available.
|
|
28
|
+
ANNOUNCED_NOT_AVAILABLE = "announced_not_available"
|
|
29
|
+
#: No evidence either way.
|
|
30
|
+
UNKNOWN = "unknown"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Capability(BaseModel):
|
|
34
|
+
provider: str
|
|
35
|
+
surface: str
|
|
36
|
+
artifact_kind: ArtifactKind
|
|
37
|
+
evidence_class: EvidenceClass
|
|
38
|
+
signal: str
|
|
39
|
+
marked: bool | None = Field(description="Does the provider mark this? None = unknown.")
|
|
40
|
+
detectability: Detectability
|
|
41
|
+
label: EvidenceLabel
|
|
42
|
+
source: str | None = None
|
|
43
|
+
notes: str = ""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
ANTHROPIC_SURFACES = (
|
|
47
|
+
"claude.ai",
|
|
48
|
+
"api",
|
|
49
|
+
"claude_code",
|
|
50
|
+
"claude_cowork",
|
|
51
|
+
"claude_tag",
|
|
52
|
+
"aws_bedrock",
|
|
53
|
+
"google_cloud",
|
|
54
|
+
"microsoft_foundry",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
_NEWS = "https://www.anthropic.com/news/claude-text-watermark"
|
|
58
|
+
_HELP = "https://support.claude.com/en/articles/16266773-how-claude-marks-ai-generated-content"
|
|
59
|
+
_OPENAI_PROVENANCE = "https://openai.com/index/advancing-content-provenance/"
|
|
60
|
+
_OPENAI_C2PA_HELP = "https://help.openai.com/en/articles/8912793-c2pa-in-chatgpt-images"
|
|
61
|
+
|
|
62
|
+
CAPABILITIES: list[Capability] = [
|
|
63
|
+
*(
|
|
64
|
+
Capability(
|
|
65
|
+
provider="anthropic",
|
|
66
|
+
surface=surface,
|
|
67
|
+
artifact_kind=ArtifactKind.TEXT,
|
|
68
|
+
evidence_class=EvidenceClass.STATISTICAL_WATERMARK,
|
|
69
|
+
signal="claude_text_watermark",
|
|
70
|
+
marked=True,
|
|
71
|
+
detectability=Detectability.ANNOUNCED_NOT_AVAILABLE,
|
|
72
|
+
label=EvidenceLabel.CONFIRMED,
|
|
73
|
+
source=_HELP,
|
|
74
|
+
notes=(
|
|
75
|
+
"Applies to Claude models launched on or after 2026-08-02, worldwide. "
|
|
76
|
+
"Applied at token-selection time during generation. No public detector "
|
|
77
|
+
"or published algorithm as of 2026-08-16; a detection API is announced "
|
|
78
|
+
"as forthcoming. This tool therefore cannot detect or measure it."
|
|
79
|
+
),
|
|
80
|
+
)
|
|
81
|
+
for surface in ANTHROPIC_SURFACES
|
|
82
|
+
),
|
|
83
|
+
Capability(
|
|
84
|
+
provider="anthropic",
|
|
85
|
+
surface="all",
|
|
86
|
+
artifact_kind=ArtifactKind.SOURCE_CODE,
|
|
87
|
+
evidence_class=EvidenceClass.STATISTICAL_WATERMARK,
|
|
88
|
+
signal="claude_text_watermark",
|
|
89
|
+
marked=True,
|
|
90
|
+
detectability=Detectability.ANNOUNCED_NOT_AVAILABLE,
|
|
91
|
+
label=EvidenceLabel.CONFIRMED,
|
|
92
|
+
source=_NEWS,
|
|
93
|
+
notes=(
|
|
94
|
+
"Anthropic states watermarking of code is sparse because code 'has to be "
|
|
95
|
+
"exact', leaving fewer free token choices. No published threshold."
|
|
96
|
+
),
|
|
97
|
+
),
|
|
98
|
+
Capability(
|
|
99
|
+
provider="anthropic",
|
|
100
|
+
surface="all",
|
|
101
|
+
artifact_kind=ArtifactKind.BINARY,
|
|
102
|
+
evidence_class=EvidenceClass.SIGNED_PROVENANCE,
|
|
103
|
+
signal="c2pa_content_credential",
|
|
104
|
+
marked=True,
|
|
105
|
+
detectability=Detectability.LOCALLY_READABLE,
|
|
106
|
+
label=EvidenceLabel.CONFIRMED,
|
|
107
|
+
source=_HELP,
|
|
108
|
+
notes=(
|
|
109
|
+
"Attached to generated .svg, .png and .jpg files. Metadata only - nothing "
|
|
110
|
+
"is embedded in the pixels. Contains no identifying user information. "
|
|
111
|
+
"Readable by any C2PA-aware tool."
|
|
112
|
+
),
|
|
113
|
+
),
|
|
114
|
+
Capability(
|
|
115
|
+
provider="anthropic",
|
|
116
|
+
surface="api",
|
|
117
|
+
artifact_kind=ArtifactKind.TEXT,
|
|
118
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
119
|
+
signal="response_headers_or_fields",
|
|
120
|
+
marked=None,
|
|
121
|
+
detectability=Detectability.UNKNOWN,
|
|
122
|
+
label=EvidenceLabel.UNKNOWN,
|
|
123
|
+
source=None,
|
|
124
|
+
notes=(
|
|
125
|
+
"No documentation found describing provenance in HTTP headers, JSON "
|
|
126
|
+
"fields or token metadata. Not probed; undocumented fields are not invented."
|
|
127
|
+
),
|
|
128
|
+
),
|
|
129
|
+
Capability(
|
|
130
|
+
provider="openai",
|
|
131
|
+
surface="all",
|
|
132
|
+
artifact_kind=ArtifactKind.TEXT,
|
|
133
|
+
evidence_class=EvidenceClass.STATISTICAL_WATERMARK,
|
|
134
|
+
signal="text_watermark",
|
|
135
|
+
marked=None,
|
|
136
|
+
detectability=Detectability.UNKNOWN,
|
|
137
|
+
label=EvidenceLabel.UNVERIFIED,
|
|
138
|
+
source=None,
|
|
139
|
+
notes=(
|
|
140
|
+
"Press reporting describes a built-but-unshipped prototype. OpenAI does "
|
|
141
|
+
"not document a deployed text watermark; absence of documentation is weak "
|
|
142
|
+
"evidence of absence."
|
|
143
|
+
),
|
|
144
|
+
),
|
|
145
|
+
Capability(
|
|
146
|
+
provider="openai",
|
|
147
|
+
surface="all",
|
|
148
|
+
artifact_kind=ArtifactKind.BINARY,
|
|
149
|
+
evidence_class=EvidenceClass.SIGNED_PROVENANCE,
|
|
150
|
+
signal="c2pa_content_credential",
|
|
151
|
+
marked=True,
|
|
152
|
+
detectability=Detectability.LOCALLY_READABLE,
|
|
153
|
+
label=EvidenceLabel.CONFIRMED,
|
|
154
|
+
source=_OPENAI_C2PA_HELP,
|
|
155
|
+
notes="C2PA Content Credentials on DALL-E 3 and Sora output.",
|
|
156
|
+
),
|
|
157
|
+
Capability(
|
|
158
|
+
provider="openai",
|
|
159
|
+
surface="all",
|
|
160
|
+
artifact_kind=ArtifactKind.BINARY,
|
|
161
|
+
evidence_class=EvidenceClass.STATISTICAL_WATERMARK,
|
|
162
|
+
signal="synthid_image_watermark",
|
|
163
|
+
marked=True,
|
|
164
|
+
detectability=Detectability.NO_PUBLIC_DETECTOR,
|
|
165
|
+
label=EvidenceLabel.CONFIRMED,
|
|
166
|
+
source=_OPENAI_PROVENANCE,
|
|
167
|
+
notes=(
|
|
168
|
+
"Durable SynthID image watermarking added via partnership with Google. "
|
|
169
|
+
"OpenAI operates a verification tool; no unrestricted third-party detector."
|
|
170
|
+
),
|
|
171
|
+
),
|
|
172
|
+
Capability(
|
|
173
|
+
provider="openai",
|
|
174
|
+
surface="codex",
|
|
175
|
+
artifact_kind=ArtifactKind.SOURCE_CODE,
|
|
176
|
+
evidence_class=EvidenceClass.STATISTICAL_WATERMARK,
|
|
177
|
+
signal="code_watermark",
|
|
178
|
+
marked=None,
|
|
179
|
+
detectability=Detectability.UNKNOWN,
|
|
180
|
+
label=EvidenceLabel.UNKNOWN,
|
|
181
|
+
source=None,
|
|
182
|
+
notes="No evidence found either way.",
|
|
183
|
+
),
|
|
184
|
+
Capability(
|
|
185
|
+
provider="generic",
|
|
186
|
+
surface="all",
|
|
187
|
+
artifact_kind=ArtifactKind.TEXT,
|
|
188
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
189
|
+
signal="invisible_unicode",
|
|
190
|
+
marked=None,
|
|
191
|
+
detectability=Detectability.LOCALLY_READABLE,
|
|
192
|
+
label=EvidenceLabel.CONFIRMED,
|
|
193
|
+
source=None,
|
|
194
|
+
notes=(
|
|
195
|
+
"Invisible-character anomalies are detectable locally but are NOT a "
|
|
196
|
+
"provider watermark and do not imply AI generation."
|
|
197
|
+
),
|
|
198
|
+
),
|
|
199
|
+
]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def capabilities(
|
|
203
|
+
provider: str | None = None, artifact_kind: ArtifactKind | None = None
|
|
204
|
+
) -> list[Capability]:
|
|
205
|
+
rows = CAPABILITIES
|
|
206
|
+
if provider:
|
|
207
|
+
rows = [r for r in rows if r.provider == provider.lower()]
|
|
208
|
+
if artifact_kind:
|
|
209
|
+
rows = [r for r in rows if r.artifact_kind is artifact_kind]
|
|
210
|
+
return rows
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def providers() -> list[str]:
|
|
214
|
+
return sorted({row.provider for row in CAPABILITIES})
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def undetectable_signals(artifact_kind: ArtifactKind) -> list[Capability]:
|
|
218
|
+
"""Signals that may be present for this artifact kind but cannot be checked.
|
|
219
|
+
|
|
220
|
+
These become the ``unknown_signals`` list in the report, which is how the
|
|
221
|
+
system stays honest about the difference between "not found" and
|
|
222
|
+
"not checkable".
|
|
223
|
+
"""
|
|
224
|
+
blocked = {
|
|
225
|
+
Detectability.NO_PUBLIC_DETECTOR,
|
|
226
|
+
Detectability.ANNOUNCED_NOT_AVAILABLE,
|
|
227
|
+
Detectability.UNKNOWN,
|
|
228
|
+
}
|
|
229
|
+
seen: set[tuple[str, str]] = set()
|
|
230
|
+
rows: list[Capability] = []
|
|
231
|
+
for row in CAPABILITIES:
|
|
232
|
+
if row.artifact_kind is not artifact_kind or row.detectability not in blocked:
|
|
233
|
+
continue
|
|
234
|
+
key = (row.provider, row.signal)
|
|
235
|
+
if key in seen:
|
|
236
|
+
continue
|
|
237
|
+
seen.add(key)
|
|
238
|
+
rows.append(row)
|
|
239
|
+
return rows
|
litmus/reporting.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Human-readable rendering of reports.
|
|
2
|
+
|
|
3
|
+
Plain text on purpose: no colour libraries, no terminal detection, so piped
|
|
4
|
+
output and terminal output are identical and diffable.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from .model import BatchReport, Report, Severity
|
|
10
|
+
from .providers import Capability
|
|
11
|
+
|
|
12
|
+
_SEVERITY_MARK = {Severity.INFO: " ", Severity.NOTICE: " *", Severity.WARNING: " !"}
|
|
13
|
+
|
|
14
|
+
DISCLAIMER = (
|
|
15
|
+
"No finding in this report establishes authorship, and the absence of a finding "
|
|
16
|
+
"does not establish human authorship. Signals that no public detector can check "
|
|
17
|
+
"are listed under 'unknown signals'."
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def render_report(report: Report, *, verbose: bool = False, include_disclaimer: bool = True) -> str:
|
|
22
|
+
a = report.artifact
|
|
23
|
+
lines: list[str] = []
|
|
24
|
+
lines.append(f"artifact {a.path or '<stdin>'}")
|
|
25
|
+
lines.append(
|
|
26
|
+
f" kind={a.kind.value}"
|
|
27
|
+
+ (f" language={a.language}" if a.language else "")
|
|
28
|
+
+ (f" media_type={a.media_type}" if a.media_type else "")
|
|
29
|
+
)
|
|
30
|
+
lines.append(f" sha256={a.sha256} size={a.size_bytes}B")
|
|
31
|
+
|
|
32
|
+
lines.append("")
|
|
33
|
+
if report.inspection.findings:
|
|
34
|
+
lines.append(f"findings ({len(report.inspection.findings)})")
|
|
35
|
+
for f in report.inspection.findings:
|
|
36
|
+
mark = _SEVERITY_MARK[f.severity]
|
|
37
|
+
lines.append(f"{mark} [{f.evidence_class.value}] {f.category}: {f.summary}")
|
|
38
|
+
if f.locations and verbose:
|
|
39
|
+
for loc in f.locations[:10]:
|
|
40
|
+
where = f"{loc.line}:{loc.column}" if loc.line else f"@{loc.offset}"
|
|
41
|
+
lines.append(f" {where} {loc.excerpt or ''}".rstrip())
|
|
42
|
+
if len(f.locations) > 10:
|
|
43
|
+
lines.append(f" ... {len(f.locations) - 10} more")
|
|
44
|
+
if f.details and verbose:
|
|
45
|
+
for key, value in f.details.items():
|
|
46
|
+
lines.append(f" {key}: {value}")
|
|
47
|
+
if f.removable_by:
|
|
48
|
+
lines.append(f" removable by: {', '.join(f.removable_by)}")
|
|
49
|
+
else:
|
|
50
|
+
lines.append("findings none")
|
|
51
|
+
|
|
52
|
+
if verbose:
|
|
53
|
+
skipped = [i for i in report.inspection.inspectors if not i.ran]
|
|
54
|
+
if skipped:
|
|
55
|
+
lines.append("")
|
|
56
|
+
lines.append("inspectors not run")
|
|
57
|
+
for status in skipped:
|
|
58
|
+
lines.append(f" {status.name}: {status.reason}")
|
|
59
|
+
|
|
60
|
+
prov = report.inspection.provenance
|
|
61
|
+
lines.append("")
|
|
62
|
+
lines.append(f"provenance confidence={prov.confidence.value}")
|
|
63
|
+
for signal in prov.unknown_signals:
|
|
64
|
+
lines.append(f" unknown signal: {signal}")
|
|
65
|
+
for note in prov.notes:
|
|
66
|
+
lines.append(f" note: {note}")
|
|
67
|
+
|
|
68
|
+
tr = report.transformation
|
|
69
|
+
if tr.performed or tr.rejected_reason:
|
|
70
|
+
lines.append("")
|
|
71
|
+
applied = [op for op in tr.operations if op.applied]
|
|
72
|
+
lines.append(f"transform performed={tr.performed} accepted={tr.accepted}")
|
|
73
|
+
if tr.rejected_reason:
|
|
74
|
+
lines.append(f" rejected: {tr.rejected_reason}")
|
|
75
|
+
for op in applied:
|
|
76
|
+
lines.append(f" applied {op.operation} ({op.changes} char(s)): {op.description}")
|
|
77
|
+
if op_note := op.details.get("note"):
|
|
78
|
+
lines.append(f" note: {op_note!s}")
|
|
79
|
+
if tr.performed and not applied:
|
|
80
|
+
lines.append(" no operation changed the content")
|
|
81
|
+
if tr.output_sha256:
|
|
82
|
+
lines.append(f" output sha256={tr.output_sha256} size={tr.output_size_bytes}B")
|
|
83
|
+
|
|
84
|
+
vr = report.validation
|
|
85
|
+
if vr.performed:
|
|
86
|
+
lines.append("")
|
|
87
|
+
lines.append(f"validation all_passed={vr.all_passed}")
|
|
88
|
+
for check in vr.checks:
|
|
89
|
+
state = {True: "pass", False: "FAIL", None: "n/a "}[check.passed]
|
|
90
|
+
lines.append(f" [{state}] {check.name}: {check.detail}")
|
|
91
|
+
|
|
92
|
+
if include_disclaimer:
|
|
93
|
+
lines.append("")
|
|
94
|
+
lines.append(DISCLAIMER)
|
|
95
|
+
return "\n".join(lines)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def render_batch(batch: BatchReport, *, verbose: bool = False) -> str:
|
|
99
|
+
"""Render a batch.
|
|
100
|
+
|
|
101
|
+
For a multi-artifact scan, clean artifacts are summarised rather than
|
|
102
|
+
printed in full: a per-file repetition of the same provenance caveats
|
|
103
|
+
buries the artifacts that actually have findings. ``--verbose`` prints
|
|
104
|
+
everything. Single-artifact output is always shown in full.
|
|
105
|
+
"""
|
|
106
|
+
single = len(batch.reports) == 1 and not batch.errors
|
|
107
|
+
shown = (
|
|
108
|
+
batch.reports
|
|
109
|
+
if single or verbose
|
|
110
|
+
else [r for r in batch.reports if r.has_findings or r.transformation.performed]
|
|
111
|
+
)
|
|
112
|
+
hidden = len(batch.reports) - len(shown)
|
|
113
|
+
|
|
114
|
+
blocks = [render_report(r, verbose=verbose, include_disclaimer=single) for r in shown]
|
|
115
|
+
for err in batch.errors:
|
|
116
|
+
blocks.append(f"error {err.get('path', '?')}: {err.get('error', '')}")
|
|
117
|
+
|
|
118
|
+
with_findings = sum(1 for r in batch.reports if r.has_findings)
|
|
119
|
+
summary = [
|
|
120
|
+
f"summary {len(batch.reports)} artifact(s), {with_findings} with findings, "
|
|
121
|
+
f"{len(batch.errors)} error(s)"
|
|
122
|
+
]
|
|
123
|
+
if hidden:
|
|
124
|
+
summary.append(f" {hidden} clean artifact(s) not shown; use --verbose")
|
|
125
|
+
if not single:
|
|
126
|
+
summary.append("")
|
|
127
|
+
summary.append(DISCLAIMER)
|
|
128
|
+
blocks.append("\n".join(summary))
|
|
129
|
+
return "\n\n".join(blocks)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def render_capabilities(rows: list[Capability]) -> str:
|
|
133
|
+
lines = [
|
|
134
|
+
"Provider capability matrix. Every row states whether the signal can actually",
|
|
135
|
+
"be checked by anyone outside the provider. Source URLs back CONFIRMED rows.",
|
|
136
|
+
"",
|
|
137
|
+
]
|
|
138
|
+
for row in rows:
|
|
139
|
+
lines.append(f"{row.provider}/{row.surface} [{row.artifact_kind.value}] {row.signal}")
|
|
140
|
+
marked = {True: "yes", False: "no", None: "unknown"}[row.marked]
|
|
141
|
+
lines.append(
|
|
142
|
+
f" class={row.evidence_class.value} marked={marked} "
|
|
143
|
+
f"detectability={row.detectability.value} evidence={row.label.value}"
|
|
144
|
+
)
|
|
145
|
+
if row.notes:
|
|
146
|
+
lines.append(f" {row.notes}")
|
|
147
|
+
if row.source:
|
|
148
|
+
lines.append(f" source: {row.source}")
|
|
149
|
+
lines.append("")
|
|
150
|
+
return "\n".join(lines).rstrip() + "\n"
|
litmus/server.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""A fully-local web UI for drag-and-drop inspection and cleaning.
|
|
2
|
+
|
|
3
|
+
Design constraints that follow from the project's privacy stance (brief §14):
|
|
4
|
+
|
|
5
|
+
* **Standard library only.** No web framework, so the base install stays
|
|
6
|
+
dependency-light and has nothing network-capable beyond this opt-in server.
|
|
7
|
+
* **Loopback by default.** Binds ``127.0.0.1``; a non-loopback host must be
|
|
8
|
+
requested explicitly and prints a warning.
|
|
9
|
+
* **In-memory only.** Uploaded bytes are analysed in RAM and never written to
|
|
10
|
+
disk by the server. The browser downloads the cleaned result itself.
|
|
11
|
+
|
|
12
|
+
The request logic lives in ``build_result`` as a pure function so it can be
|
|
13
|
+
unit-tested without sockets; the HTTP handler is a thin shell over it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import base64
|
|
19
|
+
import contextlib
|
|
20
|
+
import errno
|
|
21
|
+
import json
|
|
22
|
+
import logging
|
|
23
|
+
import webbrowser
|
|
24
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from .artifact import load_bytes
|
|
29
|
+
from .model import Report
|
|
30
|
+
from .pipeline import TransformOptions, analyze, inspect
|
|
31
|
+
from .web_ui import INDEX_HTML
|
|
32
|
+
|
|
33
|
+
log = logging.getLogger("litmus.server")
|
|
34
|
+
|
|
35
|
+
#: Upload ceiling for the browser path. Smaller than the CLI's file cap because
|
|
36
|
+
#: base64 in a JSON body is memory-heavy and a browser tool is interactive.
|
|
37
|
+
MAX_UPLOAD_BYTES = 16 * 1024 * 1024
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_result(
|
|
41
|
+
name: str,
|
|
42
|
+
data: bytes,
|
|
43
|
+
*,
|
|
44
|
+
mode: str,
|
|
45
|
+
profile: str = "standard",
|
|
46
|
+
force: bool = False,
|
|
47
|
+
) -> dict[str, Any]:
|
|
48
|
+
"""Analyse an uploaded artifact. Pure function; no I/O, no globals.
|
|
49
|
+
|
|
50
|
+
``mode`` is ``"inspect"`` (report only) or ``"clean"`` (transform too).
|
|
51
|
+
"""
|
|
52
|
+
artifact = load_bytes(data, path=Path(name) if name else None)
|
|
53
|
+
|
|
54
|
+
if mode == "clean":
|
|
55
|
+
options = TransformOptions(profile=profile, force_code=force)
|
|
56
|
+
report, output = analyze(artifact, options=options)
|
|
57
|
+
result: dict[str, Any] = {"report": report.model_dump(mode="json")}
|
|
58
|
+
if report.transformation.accepted and output != data:
|
|
59
|
+
result["output_base64"] = base64.b64encode(output).decode("ascii")
|
|
60
|
+
result["output_name"] = name or "cleaned"
|
|
61
|
+
return result
|
|
62
|
+
|
|
63
|
+
report = Report(artifact=artifact.ref, inspection=inspect(artifact))
|
|
64
|
+
return {"report": report.model_dump(mode="json")}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
68
|
+
# Keep response headers quiet: no tool version, no Python version.
|
|
69
|
+
server_version = "litmus"
|
|
70
|
+
sys_version = ""
|
|
71
|
+
|
|
72
|
+
def _send(self, code: int, body: bytes, content_type: str) -> None:
|
|
73
|
+
self.send_response(code)
|
|
74
|
+
self.send_header("Content-Type", content_type)
|
|
75
|
+
self.send_header("Content-Length", str(len(body)))
|
|
76
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
77
|
+
self.send_header(
|
|
78
|
+
"Content-Security-Policy",
|
|
79
|
+
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
|
|
80
|
+
"img-src data:; connect-src 'self'; form-action 'none'",
|
|
81
|
+
)
|
|
82
|
+
self.end_headers()
|
|
83
|
+
self.wfile.write(body)
|
|
84
|
+
|
|
85
|
+
def _send_json(self, code: int, payload: dict[str, Any]) -> None:
|
|
86
|
+
self._send(code, json.dumps(payload).encode("utf-8"), "application/json")
|
|
87
|
+
|
|
88
|
+
def log_message(self, fmt: str, *args: Any) -> None: # quieter, to our logger
|
|
89
|
+
log.debug("%s - %s", self.address_string(), fmt % args)
|
|
90
|
+
|
|
91
|
+
def do_GET(self) -> None: # noqa: N802 - http.server API
|
|
92
|
+
if self.path in ("/", "/index.html"):
|
|
93
|
+
self._send(200, INDEX_HTML.encode("utf-8"), "text/html; charset=utf-8")
|
|
94
|
+
elif self.path == "/health":
|
|
95
|
+
self._send_json(200, {"status": "ok"})
|
|
96
|
+
else:
|
|
97
|
+
self._send_json(404, {"error": "not found"})
|
|
98
|
+
|
|
99
|
+
def do_POST(self) -> None: # noqa: N802 - http.server API
|
|
100
|
+
if self.path != "/api/analyze":
|
|
101
|
+
self._send_json(404, {"error": "not found"})
|
|
102
|
+
return
|
|
103
|
+
length = int(self.headers.get("Content-Length", "0") or "0")
|
|
104
|
+
if length > MAX_UPLOAD_BYTES:
|
|
105
|
+
self._send_json(413, {"error": f"file exceeds {MAX_UPLOAD_BYTES} byte limit"})
|
|
106
|
+
return
|
|
107
|
+
try:
|
|
108
|
+
payload = json.loads(self.rfile.read(length) or b"{}")
|
|
109
|
+
data = base64.b64decode(payload["data_base64"])
|
|
110
|
+
if len(data) > MAX_UPLOAD_BYTES:
|
|
111
|
+
self._send_json(413, {"error": "file too large"})
|
|
112
|
+
return
|
|
113
|
+
result = build_result(
|
|
114
|
+
str(payload.get("name", "")),
|
|
115
|
+
data,
|
|
116
|
+
mode=str(payload.get("mode", "inspect")),
|
|
117
|
+
profile=str(payload.get("profile", "standard")),
|
|
118
|
+
force=bool(payload.get("force", False)),
|
|
119
|
+
)
|
|
120
|
+
except (KeyError, ValueError, TypeError) as exc:
|
|
121
|
+
self._send_json(400, {"error": f"{type(exc).__name__}: {exc}"})
|
|
122
|
+
return
|
|
123
|
+
except Exception as exc: # noqa: BLE001 - a bad upload must not kill the server
|
|
124
|
+
log.exception("analyze failed")
|
|
125
|
+
self._send_json(500, {"error": f"{type(exc).__name__}: {exc}"})
|
|
126
|
+
return
|
|
127
|
+
self._send_json(200, result)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
#: How many consecutive ports to try before giving up, starting at the one
|
|
131
|
+
#: requested. Keeps auto-selection bounded and deterministic.
|
|
132
|
+
_PORT_PROBE_LIMIT = 20
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _bind_free_port(host: str, port: int) -> tuple[ThreadingHTTPServer, int]:
|
|
136
|
+
"""Bind to ``port``, or the next free port after it, and return the server.
|
|
137
|
+
|
|
138
|
+
A busy port is a normal situation (another copy is already running, or an
|
|
139
|
+
unrelated service holds it), so litmus steps to the next free port instead
|
|
140
|
+
of crashing. Raises ``SystemExit`` with a friendly message if a whole band
|
|
141
|
+
of ports is occupied.
|
|
142
|
+
"""
|
|
143
|
+
for candidate in range(port, port + _PORT_PROBE_LIMIT):
|
|
144
|
+
try:
|
|
145
|
+
return ThreadingHTTPServer((host, candidate), _Handler), candidate
|
|
146
|
+
except OSError as exc:
|
|
147
|
+
if exc.errno == errno.EADDRINUSE:
|
|
148
|
+
continue # try the next port
|
|
149
|
+
raise SystemExit(f"litmus :: could not start the web UI: {exc}") from exc
|
|
150
|
+
raise SystemExit(
|
|
151
|
+
f"litmus :: ports {port}-{port + _PORT_PROBE_LIMIT - 1} are all in use. "
|
|
152
|
+
f"Free one up, or choose another with --port."
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def serve(host: str = "127.0.0.1", port: int = 8765, *, open_browser: bool = True) -> None:
|
|
157
|
+
"""Start the local server. Blocks until interrupted."""
|
|
158
|
+
if host not in ("127.0.0.1", "localhost", "::1"):
|
|
159
|
+
log.warning(
|
|
160
|
+
"binding to %s exposes this tool beyond your machine; it processes files "
|
|
161
|
+
"locally but has no authentication",
|
|
162
|
+
host,
|
|
163
|
+
)
|
|
164
|
+
httpd, port = _bind_free_port(host, port)
|
|
165
|
+
url = f"http://{host}:{port}/"
|
|
166
|
+
print(f"litmus web UI at {url} (Ctrl-C to stop; nothing is uploaded off this machine)")
|
|
167
|
+
if open_browser:
|
|
168
|
+
# A headless box has no browser; failing to open one is not fatal.
|
|
169
|
+
with contextlib.suppress(Exception):
|
|
170
|
+
webbrowser.open(url)
|
|
171
|
+
try:
|
|
172
|
+
httpd.serve_forever()
|
|
173
|
+
except KeyboardInterrupt:
|
|
174
|
+
print("\nstopping")
|
|
175
|
+
finally:
|
|
176
|
+
httpd.server_close()
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from .base import AppliedOperation, Transform
|
|
2
|
+
from .code_structural import STRUCTURAL_CODE_OPS
|
|
3
|
+
from .text_normalize import PROFILES, TRANSFORMS, resolve_operations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"PROFILES",
|
|
7
|
+
"STRUCTURAL_CODE_OPS",
|
|
8
|
+
"TRANSFORMS",
|
|
9
|
+
"AppliedOperation",
|
|
10
|
+
"Transform",
|
|
11
|
+
"resolve_operations",
|
|
12
|
+
]
|
litmus/transform/base.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Transform protocol.
|
|
2
|
+
|
|
3
|
+
A transform is a pure, deterministic ``str -> str`` function with an id, a
|
|
4
|
+
description, and an honest declaration of whether it preserves meaning. No
|
|
5
|
+
model calls, no randomness, no clock reads: the same input always produces
|
|
6
|
+
byte-identical output.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Transform:
|
|
17
|
+
id: str
|
|
18
|
+
description: str
|
|
19
|
+
#: True when the operation cannot change what the text means to a reader.
|
|
20
|
+
semantics_preserving: bool
|
|
21
|
+
apply: Callable[[str], str]
|
|
22
|
+
#: Caveats that a user needs in order to judge the operation, e.g. that
|
|
23
|
+
#: replacing NO-BREAK SPACE changes line-breaking behaviour.
|
|
24
|
+
note: str = ""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class AppliedOperation:
|
|
29
|
+
transform: Transform
|
|
30
|
+
changes: int
|