lens-eval 0.1.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 (38) hide show
  1. lens_eval-0.1.0/LICENSE +202 -0
  2. lens_eval-0.1.0/PKG-INFO +44 -0
  3. lens_eval-0.1.0/README.md +0 -0
  4. lens_eval-0.1.0/lens_eval/__init__.py +55 -0
  5. lens_eval-0.1.0/lens_eval/_validate.py +85 -0
  6. lens_eval-0.1.0/lens_eval/cli.py +215 -0
  7. lens_eval-0.1.0/lens_eval/combiners/__init__.py +93 -0
  8. lens_eval-0.1.0/lens_eval/combiners/base.py +93 -0
  9. lens_eval-0.1.0/lens_eval/combiners/ebm.py +141 -0
  10. lens_eval-0.1.0/lens_eval/combiners/gbm.py +134 -0
  11. lens_eval-0.1.0/lens_eval/combiners/glm.py +187 -0
  12. lens_eval-0.1.0/lens_eval/combiners/glm_interactions.py +109 -0
  13. lens_eval-0.1.0/lens_eval/configs/__init__.py +6 -0
  14. lens_eval-0.1.0/lens_eval/configs/naturalness_centroid_natureencoder.json +9 -0
  15. lens_eval-0.1.0/lens_eval/diagnostics.py +169 -0
  16. lens_eval-0.1.0/lens_eval/encoders.py +378 -0
  17. lens_eval-0.1.0/lens_eval/errors.py +33 -0
  18. lens_eval-0.1.0/lens_eval/lens.py +638 -0
  19. lens_eval-0.1.0/lens_eval/persistence.py +142 -0
  20. lens_eval-0.1.0/lens_eval/report.py +388 -0
  21. lens_eval-0.1.0/lens_eval/selection.py +280 -0
  22. lens_eval-0.1.0/lens_eval.egg-info/PKG-INFO +44 -0
  23. lens_eval-0.1.0/lens_eval.egg-info/SOURCES.txt +36 -0
  24. lens_eval-0.1.0/lens_eval.egg-info/dependency_links.txt +1 -0
  25. lens_eval-0.1.0/lens_eval.egg-info/entry_points.txt +2 -0
  26. lens_eval-0.1.0/lens_eval.egg-info/requires.txt +35 -0
  27. lens_eval-0.1.0/lens_eval.egg-info/top_level.txt +1 -0
  28. lens_eval-0.1.0/pyproject.toml +64 -0
  29. lens_eval-0.1.0/setup.cfg +4 -0
  30. lens_eval-0.1.0/tests/test_cli.py +198 -0
  31. lens_eval-0.1.0/tests/test_combiners.py +390 -0
  32. lens_eval-0.1.0/tests/test_diagnostics.py +215 -0
  33. lens_eval-0.1.0/tests/test_encoders.py +262 -0
  34. lens_eval-0.1.0/tests/test_lens.py +569 -0
  35. lens_eval-0.1.0/tests/test_persistence.py +119 -0
  36. lens_eval-0.1.0/tests/test_selection.py +232 -0
  37. lens_eval-0.1.0/tests/test_target_inference.py +66 -0
  38. lens_eval-0.1.0/tests/test_validate.py +106 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Foudil Chebbour
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: lens-eval
3
+ Version: 0.1.0
4
+ Summary: Interpretable multi-dimension text quality metric with combiner
5
+ Author-email: Foudil Chebbour <foudil.chebbour@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/foudil09/lens-eval
8
+ Keywords: nlp,evaluation,lens,interpretable
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy>=1.23
18
+ Requires-Dist: scipy>=1.10
19
+ Requires-Dist: scikit-learn>=1.2
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8.0; extra == "dev"
22
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
23
+ Provides-Extra: encoders
24
+ Requires-Dist: torch>=2.0; extra == "encoders"
25
+ Requires-Dist: transformers>=4.30; extra == "encoders"
26
+ Requires-Dist: sentence-transformers>=2.2; extra == "encoders"
27
+ Provides-Extra: statsmodels
28
+ Requires-Dist: statsmodels>=0.14; extra == "statsmodels"
29
+ Provides-Extra: ebm
30
+ Requires-Dist: interpret>=0.5; extra == "ebm"
31
+ Provides-Extra: gbm
32
+ Requires-Dist: lightgbm>=4.0; extra == "gbm"
33
+ Provides-Extra: report
34
+ Requires-Dist: jinja2>=3.1; extra == "report"
35
+ Provides-Extra: cli
36
+ Provides-Extra: all
37
+ Requires-Dist: torch>=2.0; extra == "all"
38
+ Requires-Dist: transformers>=4.30; extra == "all"
39
+ Requires-Dist: sentence-transformers>=2.2; extra == "all"
40
+ Requires-Dist: statsmodels>=0.14; extra == "all"
41
+ Requires-Dist: interpret>=0.5; extra == "all"
42
+ Requires-Dist: lightgbm>=4.0; extra == "all"
43
+ Requires-Dist: jinja2>=3.1; extra == "all"
44
+ Dynamic: license-file
File without changes
@@ -0,0 +1,55 @@
1
+ """lens-eval: interpretable multi-dimension text quality scoring.
2
+
3
+ Public entrypoints:
4
+
5
+ from lens_eval import LENS
6
+ from lens_eval import semantic_score, nli_score, naturalness_score, emotion_score
7
+ from lens_eval import configure # device, paths, naturalness mode/centroid
8
+
9
+ See README.md for usage.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ __version__ = "0.1.0"
15
+
16
+ from .encoders import (
17
+ DIMENSIONS,
18
+ configure,
19
+ emotion_score,
20
+ featurize,
21
+ free,
22
+ naturalness_score,
23
+ nli_score,
24
+ semantic_score,
25
+ )
26
+ from .errors import (
27
+ AmbiguousTaskError,
28
+ CombinerBackendMissing,
29
+ DegenerateTargetError,
30
+ EncoderVersionMismatchError,
31
+ InsufficientDataError,
32
+ LensEvalError,
33
+ ReferenceModeError,
34
+ )
35
+ from .lens import LENS
36
+
37
+ __all__ = [
38
+ "LENS",
39
+ "DIMENSIONS",
40
+ "configure",
41
+ "featurize",
42
+ "free",
43
+ "semantic_score",
44
+ "nli_score",
45
+ "naturalness_score",
46
+ "emotion_score",
47
+ "LensEvalError",
48
+ "InsufficientDataError",
49
+ "DegenerateTargetError",
50
+ "AmbiguousTaskError",
51
+ "ReferenceModeError",
52
+ "EncoderVersionMismatchError",
53
+ "CombinerBackendMissing",
54
+ "__version__",
55
+ ]
@@ -0,0 +1,85 @@
1
+ """Centralized structural validation for fit-time inputs.
2
+
3
+ Both ``LENS.fit`` and the CLI route their inputs through this module so a
4
+ missing ``groups`` array, an ambiguous task channel, or a malformed pairs
5
+ matrix surfaces the *same* typed exception with the *same* error message
6
+ regardless of where the call originated. The gateway is intentionally
7
+ narrow — it does shape and channel checks only, no semantic validation.
8
+ That belongs in the combiner layer.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, Optional, Sequence, Tuple
14
+
15
+ import numpy as np
16
+
17
+ from .errors import AmbiguousTaskError
18
+
19
+
20
+ TASK_CHANNELS = ("scores", "pairs", "ranks")
21
+ TASK_TO_NAME = {"scores": "regression", "pairs": "pairwise", "ranks": "ranking"}
22
+
23
+
24
+ def validate_task_channels(
25
+ *,
26
+ scores: Optional[Any] = None,
27
+ pairs: Optional[Any] = None,
28
+ ranks: Optional[Any] = None,
29
+ groups: Optional[Any] = None,
30
+ ) -> Tuple[str, str]:
31
+ """Resolve the task channel and validate channel-specific structure.
32
+
33
+ Returns ``(channel_name, task)`` where:
34
+ * ``channel_name`` is one of ``"scores" | "pairs" | "ranks"``.
35
+ * ``task`` is the inferred ``LENS`` task —
36
+ ``"regression" | "pairwise" | "ranking"``.
37
+
38
+ Raises ``AmbiguousTaskError`` if zero or multiple channels are supplied.
39
+ Raises ``ValueError`` for shape / dtype / coverage issues with the chosen
40
+ channel (e.g. pairs must be ``(M, 2)``, ranking requires ``groups``).
41
+
42
+ Used by both ``LENS.fit`` and the CLI so the user-visible failure modes
43
+ are identical across entry points.
44
+ """
45
+ provided = [k for k, v in (("scores", scores), ("pairs", pairs), ("ranks", ranks))
46
+ if v is not None]
47
+ if len(provided) != 1:
48
+ # Zero ⇒ nothing to fit on. Two+ ⇒ which to optimise? Both are bad.
49
+ raise AmbiguousTaskError(
50
+ f"fit() / CLI needs exactly one of (scores, pairs, ranks); got {provided!r}"
51
+ )
52
+ channel = provided[0]
53
+ task = TASK_TO_NAME[channel]
54
+
55
+ if channel == "pairs":
56
+ arr = np.asarray(pairs)
57
+ if arr.ndim != 2 or arr.shape[1] != 2:
58
+ raise ValueError(
59
+ f"`pairs` must have shape (M, 2) of (winner_idx, loser_idx); got {arr.shape}"
60
+ )
61
+ if arr.size and not np.issubdtype(arr.dtype, np.integer):
62
+ # Allow float-typed indices that round to int, but reject strings /
63
+ # floats with fractional parts — those are user-error.
64
+ if not np.allclose(arr, np.round(arr)):
65
+ raise ValueError("`pairs` indices must be integer-valued.")
66
+ elif channel == "ranks":
67
+ # Ranking is the only channel that needs an auxiliary grouping array —
68
+ # lambdarank needs to know which rows belong to the same query. Without
69
+ # groups every row is treated as its own group, which silently
70
+ # collapses to "fit a regressor on rank labels" rather than learning
71
+ # within-query orderings. Reject upfront.
72
+ if groups is None:
73
+ raise ValueError(
74
+ "task='ranking' requires `groups` so lambdarank can isolate "
75
+ "within-query orderings — pass a per-row group-id array."
76
+ )
77
+ ranks_arr = np.asarray(ranks)
78
+ groups_arr = np.asarray(groups)
79
+ if ranks_arr.shape[0] != groups_arr.shape[0]:
80
+ raise ValueError(
81
+ f"`ranks` ({ranks_arr.shape[0]}) and `groups` ({groups_arr.shape[0]}) "
82
+ f"must align row-wise."
83
+ )
84
+
85
+ return channel, task
@@ -0,0 +1,215 @@
1
+ """`lens-eval` CLI — thin wrapper around the Python API.
2
+
3
+ lens-eval fit \
4
+ --texts hyp.txt --refs ref.txt --scores scores.csv \
5
+ --output ./my-lens --task auto --verbose
6
+
7
+ lens-eval score \
8
+ --model ./my-lens \
9
+ --texts new_hyp.txt --refs new_ref.txt \
10
+ --output predictions.csv
11
+
12
+ lens-eval report ./my-lens --html report.html
13
+
14
+ All three accept ``--features path.csv`` to skip encoding entirely. The
15
+ features CSV must have one column per dimension; column order follows the
16
+ LENS ``dimensions_used_`` for ``score``, or the user-passed ``--dimensions``
17
+ for ``fit``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import csv
24
+ import sys
25
+ from pathlib import Path
26
+ from typing import List, Optional
27
+
28
+ import numpy as np
29
+
30
+
31
+ def _read_lines(path: str | Path) -> List[str]:
32
+ p = Path(path)
33
+ text = p.read_text(encoding="utf-8")
34
+ if p.suffix.lower() == ".csv":
35
+ return [row[0] for row in csv.reader(text.splitlines()) if row]
36
+ return [ln for ln in text.splitlines() if ln]
37
+
38
+
39
+ def _read_scalar_csv(path: str | Path) -> np.ndarray:
40
+ rows: List[float] = []
41
+ with open(path, newline="") as f:
42
+ for row in csv.reader(f):
43
+ if not row:
44
+ continue
45
+ try:
46
+ rows.append(float(row[0]))
47
+ except ValueError:
48
+ # Header row — skip silently.
49
+ continue
50
+ return np.asarray(rows, dtype=float)
51
+
52
+
53
+ def _read_features_csv(path: str | Path) -> np.ndarray:
54
+ arr = []
55
+ with open(path, newline="") as f:
56
+ for row in csv.reader(f):
57
+ if not row:
58
+ continue
59
+ try:
60
+ arr.append([float(x) for x in row])
61
+ except ValueError:
62
+ continue
63
+ return np.asarray(arr, dtype=float)
64
+
65
+
66
+ def _read_pairs_csv(path: str | Path) -> np.ndarray:
67
+ pairs = []
68
+ with open(path, newline="") as f:
69
+ for row in csv.reader(f):
70
+ if not row:
71
+ continue
72
+ try:
73
+ a, b = int(row[0]), int(row[1])
74
+ except (ValueError, IndexError):
75
+ continue
76
+ pairs.append((a, b))
77
+ if not pairs:
78
+ raise ValueError(f"no pair rows parsed from {path}")
79
+ return np.asarray(pairs, dtype=int)
80
+
81
+
82
+ def _read_int_column_csv(path: str | Path) -> np.ndarray:
83
+ vals: List[int] = []
84
+ with open(path, newline="") as f:
85
+ for row in csv.reader(f):
86
+ if not row:
87
+ continue
88
+ try:
89
+ vals.append(int(row[0]))
90
+ except ValueError:
91
+ continue
92
+ if not vals:
93
+ raise ValueError(f"no integer rows parsed from {path}")
94
+ return np.asarray(vals, dtype=int)
95
+
96
+
97
+ def _cmd_fit(args) -> int:
98
+ from . import encoders as enc
99
+ from ._validate import validate_task_channels
100
+ from .lens import LENS
101
+
102
+ if args.naturalness_mode:
103
+ enc.configure(naturalness_mode=args.naturalness_mode)
104
+
105
+ texts = _read_lines(args.texts) if args.texts else None
106
+ refs = _read_lines(args.refs) if args.refs else None
107
+ feats = _read_features_csv(args.features) if args.features else None
108
+ y = _read_scalar_csv(args.scores) if args.scores else None
109
+ pairs = _read_pairs_csv(args.pairs) if args.pairs else None
110
+ ranks = _read_int_column_csv(args.ranks) if args.ranks else None
111
+ groups = _read_int_column_csv(args.groups) if args.groups else None
112
+
113
+ try:
114
+ channel, _ = validate_task_channels(
115
+ scores=y, pairs=pairs, ranks=ranks, groups=groups,
116
+ )
117
+ except Exception as exc:
118
+ print(f"error: {exc}", file=sys.stderr)
119
+ return 2
120
+
121
+ lens = LENS()
122
+ lens.fit(
123
+ texts=texts,
124
+ references=refs,
125
+ features=feats,
126
+ scores=y, pairs=pairs, ranks=ranks, groups=groups,
127
+ task=args.task,
128
+ target_type=args.target_type,
129
+ selection=args.selection,
130
+ verbose=args.verbose,
131
+ )
132
+ lens.save(args.output)
133
+ if args.html:
134
+ lens.report_html(args.html)
135
+ print(f"saved fitted LENS to {args.output} ({channel} channel)")
136
+ return 0
137
+
138
+
139
+ def _cmd_score(args) -> int:
140
+ from .lens import LENS
141
+
142
+ lens = LENS.load(args.model)
143
+ texts = _read_lines(args.texts) if args.texts else None
144
+ refs = _read_lines(args.refs) if args.refs else None
145
+ feats = _read_features_csv(args.features) if args.features else None
146
+
147
+ if texts is None and feats is None:
148
+ print("error: provide --texts or --features", file=sys.stderr)
149
+ return 2
150
+
151
+ scores = lens.score(texts, references=refs, features=feats)
152
+
153
+ out = Path(args.output)
154
+ with open(out, "w", newline="") as f:
155
+ w = csv.writer(f)
156
+ w.writerow(["score"])
157
+ for s in scores:
158
+ w.writerow([float(s)])
159
+ print(f"wrote {len(scores)} scores to {out}")
160
+ return 0
161
+
162
+
163
+ def _cmd_report(args) -> int:
164
+ from .lens import LENS
165
+
166
+ lens = LENS.load(args.model)
167
+ lens.report()
168
+ if args.html:
169
+ lens.report_html(args.html)
170
+ print(f"wrote HTML report to {args.html}")
171
+ return 0
172
+
173
+
174
+ def main(argv: Optional[List[str]] = None) -> int:
175
+ p = argparse.ArgumentParser(prog="lens-eval", description="lens-eval CLI")
176
+ sub = p.add_subparsers(dest="command", required=True)
177
+
178
+ pf = sub.add_parser("fit", help="fit a LENS combiner")
179
+ pf.add_argument("--texts", help="path to candidate texts (txt or csv)")
180
+ pf.add_argument("--refs", help="path to references (txt or csv)")
181
+ pf.add_argument("--features", help="path to precomputed feature matrix CSV (D columns)")
182
+ pf.add_argument("--scores", help="scalar targets CSV (1 column)")
183
+ pf.add_argument("--pairs", help="pairwise CSV: 2 columns (winner_idx, loser_idx)")
184
+ pf.add_argument("--ranks", help="ranking CSV: 1 column of integer ranks")
185
+ pf.add_argument("--groups", help="ranking grouping CSV: 1 column of group ids — REQUIRED with --ranks")
186
+ pf.add_argument("--output", required=True, help="where to save the fitted LENS directory")
187
+ pf.add_argument("--task", default="auto", choices=("auto", "regression", "pairwise", "ranking"))
188
+ pf.add_argument("--target-type", default="auto",
189
+ choices=("auto", "bounded", "ordinal", "binary", "continuous"))
190
+ pf.add_argument("--selection", default="auto",
191
+ choices=("auto", "fast", "exhaustive", "glm", "glm_interactions", "ebm", "gbm"))
192
+ pf.add_argument("--naturalness-mode", default="centroid", choices=("centroid", "reference"))
193
+ pf.add_argument("--html", help="optional: also write an HTML report to this path")
194
+ pf.add_argument("--verbose", action="store_true")
195
+ pf.set_defaults(func=_cmd_fit)
196
+
197
+ ps = sub.add_parser("score", help="score new texts with a saved LENS")
198
+ ps.add_argument("--model", required=True, help="path to a saved LENS directory")
199
+ ps.add_argument("--texts", help="path to candidate texts (txt or csv)")
200
+ ps.add_argument("--refs", help="path to references (txt or csv)")
201
+ ps.add_argument("--features", help="path to precomputed feature matrix CSV (D columns)")
202
+ ps.add_argument("--output", required=True, help="output CSV path for predictions")
203
+ ps.set_defaults(func=_cmd_score)
204
+
205
+ pr = sub.add_parser("report", help="print/render the selection report from a saved LENS")
206
+ pr.add_argument("model", help="path to a saved LENS directory")
207
+ pr.add_argument("--html", help="optional: write an HTML report to this path too")
208
+ pr.set_defaults(func=_cmd_report)
209
+
210
+ args = p.parse_args(argv)
211
+ return int(args.func(args) or 0)
212
+
213
+
214
+ if __name__ == "__main__":
215
+ raise SystemExit(main())