pileorder 0.1.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.
Files changed (59) hide show
  1. pileorder/__init__.py +3 -0
  2. pileorder/adapters/__init__.py +5 -0
  3. pileorder/adapters/images.py +94 -0
  4. pileorder/adapters/registry.py +12 -0
  5. pileorder/app.py +177 -0
  6. pileorder/checks/__init__.py +10 -0
  7. pileorder/checks/builtin.py +138 -0
  8. pileorder/checks/registry.py +19 -0
  9. pileorder/cli.py +206 -0
  10. pileorder/data/__init__.py +0 -0
  11. pileorder/data/prices.yaml +18 -0
  12. pileorder/engine/__init__.py +18 -0
  13. pileorder/engine/actions/__init__.py +11 -0
  14. pileorder/engine/actions/call.py +37 -0
  15. pileorder/engine/actions/ingest.py +86 -0
  16. pileorder/engine/actions/prepare.py +68 -0
  17. pileorder/engine/orchestrator.py +178 -0
  18. pileorder/engine/planner.py +55 -0
  19. pileorder/engine/prompt.py +41 -0
  20. pileorder/engine/retry.py +44 -0
  21. pileorder/engine/scanner.py +88 -0
  22. pileorder/engine/validation.py +54 -0
  23. pileorder/engine/worker.py +54 -0
  24. pileorder/env.py +25 -0
  25. pileorder/errors.py +59 -0
  26. pileorder/export/__init__.py +16 -0
  27. pileorder/export/files.py +85 -0
  28. pileorder/export/rows.py +40 -0
  29. pileorder/interfaces.py +85 -0
  30. pileorder/job/__init__.py +6 -0
  31. pileorder/job/compiler.py +194 -0
  32. pileorder/job/loader.py +38 -0
  33. pileorder/job/prices.py +41 -0
  34. pileorder/job/raw_models.py +153 -0
  35. pileorder/job/schema_builder.py +86 -0
  36. pileorder/manifest/__init__.py +13 -0
  37. pileorder/manifest/schema.sql +47 -0
  38. pileorder/manifest/store.py +497 -0
  39. pileorder/models/__init__.py +68 -0
  40. pileorder/models/chunk.py +135 -0
  41. pileorder/models/job.py +125 -0
  42. pileorder/models/run.py +119 -0
  43. pileorder/models/unit.py +67 -0
  44. pileorder/plugins.py +83 -0
  45. pileorder/providers/__init__.py +23 -0
  46. pileorder/providers/dry_run.py +22 -0
  47. pileorder/providers/fake.py +127 -0
  48. pileorder/providers/openai_chat.py +152 -0
  49. pileorder/providers/tokens.py +178 -0
  50. pileorder/report/__init__.py +15 -0
  51. pileorder/report/builder.py +72 -0
  52. pileorder/report/cost.py +38 -0
  53. pileorder/report/renderers/__init__.py +5 -0
  54. pileorder/report/renderers/markdown.py +124 -0
  55. pileorder-0.1.0.dist-info/METADATA +190 -0
  56. pileorder-0.1.0.dist-info/RECORD +59 -0
  57. pileorder-0.1.0.dist-info/WHEEL +4 -0
  58. pileorder-0.1.0.dist-info/entry_points.txt +2 -0
  59. pileorder-0.1.0.dist-info/licenses/LICENSE +21 -0
pileorder/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """pileorder: turn piles of images into structured, checked data with AI."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ """Input adapters: images (M1); pdf and csv rows are registered stubs."""
2
+
3
+ from pileorder.adapters.registry import ADAPTERS
4
+
5
+ __all__ = ["ADAPTERS"]
@@ -0,0 +1,94 @@
1
+ """Images adapter: one image file = one unit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import io
7
+ import os
8
+ from collections.abc import Iterator
9
+ from pathlib import Path
10
+
11
+ from PIL import Image, ImageOps, UnidentifiedImageError
12
+
13
+ from pileorder.errors import ConfigError, UnreadableInput
14
+ from pileorder.models import ImagePart, InputSpec, JobSpec, ScanEntry, SkippedEntry, Unit, UnitPayload
15
+
16
+ JPEG_QUALITY = 85
17
+
18
+
19
+ class ImagesAdapter:
20
+ kind = "image"
21
+
22
+ def scan(self, spec: InputSpec) -> Iterator[ScanEntry | SkippedEntry]:
23
+ root = spec.path
24
+ if not root.is_dir():
25
+ raise ConfigError(f"input.path is not a folder: {root}")
26
+ extensions = {f".{e}" for e in spec.extensions}
27
+ limit_mb = round(spec.max_file_bytes / (1024 * 1024), 3)
28
+ for path in _walk(root):
29
+ if path.suffix.lower() not in extensions:
30
+ continue
31
+ unit_id = path.relative_to(root).as_posix()
32
+ try:
33
+ st = path.stat()
34
+ except OSError as e:
35
+ yield SkippedEntry(unit_id, path, self.kind, f"cannot read file: {e.strerror}")
36
+ continue
37
+ if st.st_size > spec.max_file_bytes:
38
+ yield SkippedEntry(unit_id, path, self.kind, f"larger than {limit_mb:g} MB")
39
+ continue
40
+ if st.st_size == 0:
41
+ yield SkippedEntry(unit_id, path, self.kind, "empty file")
42
+ continue
43
+ yield ScanEntry(unit_id, path, self.kind, st.st_size, st.st_mtime_ns)
44
+
45
+ def fingerprint(self, entry: ScanEntry) -> str:
46
+ try:
47
+ data = entry.source.read_bytes()
48
+ except OSError as e:
49
+ raise UnreadableInput(f"cannot read file: {e.strerror}") from e
50
+ try:
51
+ with Image.open(io.BytesIO(data)) as img:
52
+ img.verify()
53
+ except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as e:
54
+ raise UnreadableInput("not a readable image") from e
55
+ return hashlib.sha256(data).hexdigest()
56
+
57
+ def load(self, unit: Unit, spec: JobSpec) -> UnitPayload:
58
+ parts = tuple(_encode(src, spec.model.image_max_side) for src in unit.sources)
59
+ return UnitPayload(unit.id, parts)
60
+
61
+
62
+ def _walk(root: Path) -> Iterator[Path]:
63
+ """Depth-first, sorted by name, hidden files and folders skipped — stable order across runs."""
64
+ try:
65
+ entries = sorted(os.scandir(root), key=lambda e: e.name)
66
+ except OSError:
67
+ return
68
+ for entry in entries:
69
+ if entry.name.startswith("."):
70
+ continue
71
+ if entry.is_dir(follow_symlinks=False):
72
+ yield from _walk(Path(entry.path))
73
+ elif entry.is_file():
74
+ yield Path(entry.path)
75
+
76
+
77
+ def _encode(path: Path, max_side: int) -> ImagePart:
78
+ """Resize to fit `max_side`, flatten transparency on white, re-encode as JPEG."""
79
+ try:
80
+ with Image.open(path) as img:
81
+ img = ImageOps.exif_transpose(img)
82
+ img.thumbnail((max_side, max_side))
83
+ if img.mode in ("RGBA", "LA", "P"):
84
+ img = img.convert("RGBA")
85
+ background = Image.new("RGB", img.size, "white")
86
+ background.paste(img, mask=img.getchannel("A"))
87
+ img = background
88
+ elif img.mode != "RGB":
89
+ img = img.convert("RGB")
90
+ buf = io.BytesIO()
91
+ img.save(buf, format="JPEG", quality=JPEG_QUALITY, optimize=True)
92
+ except (UnidentifiedImageError, OSError) as e:
93
+ raise UnreadableInput(f"cannot decode image: {e}") from e
94
+ return ImagePart(buf.getvalue(), "image/jpeg")
@@ -0,0 +1,12 @@
1
+ """Input adapters by name. Planned adapters are registered as stubs that name their milestone."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pileorder.adapters.images import ImagesAdapter
6
+ from pileorder.interfaces import InputAdapter
7
+ from pileorder.plugins import Registry
8
+
9
+ ADAPTERS: Registry[InputAdapter] = Registry("input adapter")
10
+ ADAPTERS.register("images", ImagesAdapter)
11
+ ADAPTERS.register_planned("pdf", "pdf input", "M2")
12
+ ADAPTERS.register_planned("csv", "spreadsheet rows (csv input)", "M2")
pileorder/app.py ADDED
@@ -0,0 +1,177 @@
1
+ """`Pipeline` facade — the composition root. The CLI calls only this."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Callable, Sequence
7
+ from dataclasses import replace
8
+ from pathlib import Path
9
+ from types import TracebackType
10
+
11
+ from pileorder.adapters import ADAPTERS
12
+ from pileorder.checks import build_checks
13
+ from pileorder.engine import DEFAULT_SEED, ChunkWorker, Orchestrator, Progress, RetryPolicy, RunPlanner, Scanner
14
+ from pileorder.engine.prompt import build_system_prompt
15
+ from pileorder.env import load_env_file
16
+ from pileorder.errors import ConfigChanged
17
+ from pileorder.export import EXPORTERS
18
+ from pileorder.interfaces import InputAdapter, ModelProvider
19
+ from pileorder.job import JobCompiler
20
+ from pileorder.manifest import ManifestStore
21
+ from pileorder.models import JobSpec, Money, RunPlan, RunResult, ScanReport, Usage
22
+ from pileorder.providers import PROVIDERS, DryRunProvider, create_provider
23
+ from pileorder.providers.tokens import estimate_note, text_tokens
24
+ from pileorder.report import RENDERERS, CostEstimator, ReportBuilder
25
+
26
+ # The composition root imports every registry, so all planned stubs are known (see `not-included`).
27
+ __all__ = ["ADAPTERS", "EXPORTERS", "PROVIDERS", "RENDERERS", "Pipeline"]
28
+
29
+
30
+ class Pipeline:
31
+ def __init__(self, spec: JobSpec, store: ManifestStore, adapter: InputAdapter) -> None:
32
+ self.spec = spec
33
+ self.store = store
34
+ self.adapter = adapter
35
+
36
+ @classmethod
37
+ def from_config(cls, config_path: Path) -> Pipeline:
38
+ """Compile the config and pick plugs. Fails fast on config errors, before any work or API call."""
39
+ spec = JobCompiler().compile_file(config_path)
40
+ load_env_file(spec.config_path.parent / ".env")
41
+ load_env_file(Path.cwd() / ".env")
42
+ adapter = ADAPTERS.create(spec.input.adapter)
43
+ PROVIDERS.reject_planned(spec.model.provider)
44
+ for fmt in spec.output.formats:
45
+ EXPORTERS.reject_planned(fmt)
46
+ store = ManifestStore.open(spec.manifest_path)
47
+ return cls(spec, store, adapter)
48
+
49
+ @property
50
+ def costs(self) -> CostEstimator:
51
+ return CostEstimator(self.spec.model.price)
52
+
53
+ def scan(self) -> ScanReport:
54
+ return Scanner(self.adapter, self.store).scan(self.spec.input)
55
+
56
+ def sample(
57
+ self,
58
+ n: int,
59
+ seed: int = DEFAULT_SEED,
60
+ *,
61
+ dry_run: bool = False,
62
+ provider: ModelProvider | None = None,
63
+ on_progress: Callable[[Progress], None] | None = None,
64
+ ) -> RunResult:
65
+ """Run a seeded random subset. Each sample replaces the previous one; config edits need no `--force`."""
66
+ if not dry_run:
67
+ self.store.reset_sample()
68
+ plan = self.planner().sample(n, seed)
69
+ return self._execute(plan, dry_run=dry_run, provider=provider, on_progress=on_progress)
70
+
71
+ def run(
72
+ self,
73
+ *,
74
+ retry_failed: bool = False,
75
+ limit: int | None = None,
76
+ force: bool = False,
77
+ dry_run: bool = False,
78
+ provider: ModelProvider | None = None,
79
+ on_progress: Callable[[Progress], None] | None = None,
80
+ ) -> RunResult:
81
+ """Process every pending unit. Sample results made with the same config are kept, not paid twice."""
82
+ config_hash = self.spec.semantic_hash
83
+ stale = self.store.stale_full_count(config_hash)
84
+ if stale and not force:
85
+ raise ConfigChanged(stale)
86
+ if not dry_run:
87
+ self.store.adopt_sample(config_hash)
88
+ self.store.sync_duplicates()
89
+ plan = self.planner().full(config_hash, retry_failed=retry_failed, force=force, limit=limit)
90
+ return self._execute(plan, dry_run=dry_run, provider=provider, on_progress=on_progress)
91
+
92
+ def planner(self) -> RunPlanner:
93
+ return RunPlanner(self.store, self.spec.batching)
94
+
95
+ def _execute(
96
+ self,
97
+ plan: RunPlan,
98
+ *,
99
+ dry_run: bool,
100
+ provider: ModelProvider | None,
101
+ on_progress: Callable[[Progress], None] | None,
102
+ ) -> RunResult:
103
+ if dry_run:
104
+ provider = DryRunProvider(self.spec.model.name, self.spec.fields)
105
+ elif provider is None:
106
+ provider = create_provider(self.spec.model)
107
+ concurrency = self.spec.batching.concurrency
108
+ worker = ChunkWorker.standard(
109
+ self.spec, self.adapter, provider, asyncio.Semaphore(concurrency), checks=build_checks(self.spec)
110
+ )
111
+ orchestrator = Orchestrator(
112
+ self.store,
113
+ worker,
114
+ self.planner(),
115
+ RetryPolicy(self.spec.batching.max_attempts),
116
+ concurrency,
117
+ commit=not dry_run,
118
+ on_progress=on_progress,
119
+ )
120
+ try:
121
+ result = asyncio.run(_execute_and_close(orchestrator, plan, self.spec.semantic_hash, provider))
122
+ except KeyboardInterrupt:
123
+ if orchestrator.last_result is None:
124
+ raise
125
+ return self._priced(orchestrator.last_result)
126
+ if dry_run:
127
+ result = replace(result, estimate_note=estimate_note(self.spec.model.name))
128
+ else:
129
+ self.store.sync_duplicates()
130
+ return self._priced(result)
131
+
132
+ def _priced(self, result: RunResult) -> RunResult:
133
+ return replace(result, cost=self.costs.cost(result.usage))
134
+
135
+ def report(self, result: RunResult) -> Path:
136
+ """Write the sample report (markdown) into the output folder. Returns its path."""
137
+ prompt = build_system_prompt(self.spec)
138
+ prefix = text_tokens(prompt) + text_tokens(str(dict(self.spec.response_schema)))
139
+ data = ReportBuilder(self.spec, self.store).build(result, prefix_tokens=prefix)
140
+ return RENDERERS.create("md").render(data, self.spec.output.dir)
141
+
142
+ def export(self, formats: Sequence[str] | None = None) -> list[Path]:
143
+ """Write result files from the manifest. Never calls the model; can be repeated any time."""
144
+ formats = list(dict.fromkeys(formats or self.spec.output.formats))
145
+ exporters = [EXPORTERS.create(f) for f in formats] # fail on a bad format before writing anything
146
+ return [e.export(self.store, self.spec) for e in exporters]
147
+
148
+ def status(self) -> dict[str, int]:
149
+ return self.store.stats()
150
+
151
+ def spent(self) -> tuple[Usage, Money | None]:
152
+ """Tokens and cost of every run so far (retries and replaced samples included)."""
153
+ usage = Usage(*self.store.spent_tokens())
154
+ return usage, self.costs.cost(usage)
155
+
156
+ def close(self) -> None:
157
+ self.store.close()
158
+
159
+ def __enter__(self) -> Pipeline:
160
+ return self
161
+
162
+ def __exit__(
163
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
164
+ ) -> None:
165
+ self.close()
166
+
167
+
168
+ async def _execute_and_close(
169
+ orchestrator: Orchestrator, plan: RunPlan, config_hash: str, provider: ModelProvider
170
+ ) -> RunResult:
171
+ """Run the plan and close the provider's connections inside the same event loop."""
172
+ try:
173
+ return await orchestrator.execute(plan, config_hash)
174
+ finally:
175
+ close = getattr(provider, "aclose", None)
176
+ if close is not None:
177
+ await close()
@@ -0,0 +1,10 @@
1
+ """Field checks: cheap, deterministic rules run on every returned item.
2
+
3
+ A failed check never retries a unit — the unit is `done` and flagged `needs_review`. The model's own
4
+ "confidence" is not a check and is never asked for.
5
+ """
6
+
7
+ from pileorder.checks.builtin import EnumCheck, LimitsCheck, RegexCheck, RequiredCheck, TypeCheck
8
+ from pileorder.checks.registry import DEFAULT_CHECKS, build_checks
9
+
10
+ __all__ = ["DEFAULT_CHECKS", "EnumCheck", "LimitsCheck", "RegexCheck", "RequiredCheck", "TypeCheck", "build_checks"]
@@ -0,0 +1,138 @@
1
+ """The M1 checks: required, type / format, enum, limits, regex.
2
+
3
+ Each returns at most one `CheckFailure` per field. A `null` optional value passes every check; the
4
+ `required` check is the only one that looks at missing or empty values.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import difflib
10
+ import math
11
+ from datetime import date
12
+ from typing import Any
13
+
14
+ from pileorder.models import CheckFailure, FieldSpec, FieldType
15
+
16
+
17
+ def _empty(value: Any) -> bool:
18
+ if isinstance(value, str):
19
+ return not value.strip()
20
+ if isinstance(value, list):
21
+ return not value
22
+ return value is None
23
+
24
+
25
+ def _strings(value: Any) -> list[str]:
26
+ """The string values a text rule applies to: the value itself, or each list item."""
27
+ if isinstance(value, str):
28
+ return [value]
29
+ if isinstance(value, list):
30
+ return [v for v in value if isinstance(v, str)]
31
+ return []
32
+
33
+
34
+ def _is_date(value: Any) -> bool:
35
+ """Exactly YYYY-MM-DD and a real day (`fromisoformat` alone also accepts `20240101` and week dates)."""
36
+ if not isinstance(value, str) or len(value) != 10 or value[4] != "-" or value[7] != "-":
37
+ return False
38
+ try:
39
+ date.fromisoformat(value)
40
+ except ValueError:
41
+ return False
42
+ return True
43
+
44
+
45
+ class RequiredCheck:
46
+ """A required field must be present and non-empty (an empty string or list is not a value)."""
47
+
48
+ name = "required"
49
+
50
+ def applies_to(self, field: FieldSpec) -> bool:
51
+ return field.required
52
+
53
+ def check(self, field: FieldSpec, value: Any) -> CheckFailure | None:
54
+ return CheckFailure(field.name, value, "required value is empty") if _empty(value) else None
55
+
56
+
57
+ class TypeCheck:
58
+ """Formats the response schema cannot express: a real calendar date, a finite number."""
59
+
60
+ name = "type"
61
+
62
+ def applies_to(self, field: FieldSpec) -> bool:
63
+ return field.type in (FieldType.DATE, FieldType.NUMBER)
64
+
65
+ def check(self, field: FieldSpec, value: Any) -> CheckFailure | None:
66
+ if _empty(value):
67
+ return None
68
+ if field.type is FieldType.DATE:
69
+ if not _is_date(value):
70
+ return CheckFailure(field.name, value, "not a date in YYYY-MM-DD format")
71
+ elif isinstance(value, float) and not math.isfinite(value):
72
+ return CheckFailure(field.name, value, "not a finite number")
73
+ return None
74
+
75
+
76
+ class EnumCheck:
77
+ """The value must be one of the allowed values, after trimming and case-folding.
78
+
79
+ The value is never replaced: a miss records the closest allowed value as a suggestion. The escape value
80
+ ("none of these fits") is allowed by the schema but always goes to review.
81
+ """
82
+
83
+ name = "enum"
84
+
85
+ def applies_to(self, field: FieldSpec) -> bool:
86
+ return field.type is FieldType.ENUM and field.enum is not None
87
+
88
+ def check(self, field: FieldSpec, value: Any) -> CheckFailure | None:
89
+ enum = field.enum
90
+ assert enum is not None
91
+ if _empty(value) or not isinstance(value, str):
92
+ return None
93
+ key = value.strip().casefold()
94
+ if key == enum.escape_value.strip().casefold():
95
+ return CheckFailure(field.name, value, "no allowed value fits (escape value)")
96
+ if key in enum.lookup:
97
+ return None
98
+ close = difflib.get_close_matches(key, enum.lookup.keys(), n=1, cutoff=0.6)
99
+ return CheckFailure(
100
+ field.name, value, "not in the list of allowed values", enum.lookup[close[0]] if close else None
101
+ )
102
+
103
+
104
+ class LimitsCheck:
105
+ """`max_words` and `max_length` (for a list: per item), `max_items` for lists."""
106
+
107
+ name = "limits"
108
+
109
+ def applies_to(self, field: FieldSpec) -> bool:
110
+ return any(x is not None for x in (field.max_words, field.max_items, field.max_length))
111
+
112
+ def check(self, field: FieldSpec, value: Any) -> CheckFailure | None:
113
+ if isinstance(value, list) and field.max_items is not None and len(value) > field.max_items:
114
+ return CheckFailure(field.name, value, f"{len(value)} items, at most {field.max_items} allowed")
115
+ for text in _strings(value):
116
+ if field.max_words is not None and (words := len(text.split())) > field.max_words:
117
+ return CheckFailure(field.name, value, f"{words} words, at most {field.max_words} allowed")
118
+ if field.max_length is not None and len(text) > field.max_length:
119
+ return CheckFailure(
120
+ field.name, value, f"{len(text)} characters, at most {field.max_length} allowed"
121
+ )
122
+ return None
123
+
124
+
125
+ class RegexCheck:
126
+ """The whole value (for a list: each item) must match the field's pattern, compiled once by the compiler."""
127
+
128
+ name = "regex"
129
+
130
+ def applies_to(self, field: FieldSpec) -> bool:
131
+ return field.pattern is not None
132
+
133
+ def check(self, field: FieldSpec, value: Any) -> CheckFailure | None:
134
+ assert field.pattern is not None
135
+ for text in _strings(value):
136
+ if not field.pattern.fullmatch(text):
137
+ return CheckFailure(field.name, value, f"does not match the pattern {field.pattern.pattern}")
138
+ return None
@@ -0,0 +1,19 @@
1
+ """Which checks apply to which field — decided once per run, not per value."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from types import MappingProxyType
7
+
8
+ from pileorder.checks.builtin import EnumCheck, LimitsCheck, RegexCheck, RequiredCheck, TypeCheck
9
+ from pileorder.interfaces import FieldCheck
10
+ from pileorder.models import JobSpec
11
+
12
+ DEFAULT_CHECKS: tuple[FieldCheck, ...] = (RequiredCheck(), TypeCheck(), EnumCheck(), LimitsCheck(), RegexCheck())
13
+
14
+
15
+ def build_checks(
16
+ spec: JobSpec, checks: Sequence[FieldCheck] = DEFAULT_CHECKS
17
+ ) -> Mapping[str, tuple[FieldCheck, ...]]:
18
+ """Field name → the checks that apply to it, in a stable order."""
19
+ return MappingProxyType({f.name: tuple(c for c in checks if c.applies_to(f)) for f in spec.fields})
pileorder/cli.py ADDED
@@ -0,0 +1,206 @@
1
+ """Command line. Thin: parses arguments, calls the `Pipeline` facade, prints summaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from collections.abc import Callable
7
+ from pathlib import Path
8
+ from typing import Annotated
9
+
10
+ import typer
11
+
12
+ from pileorder import __version__
13
+ from pileorder.app import Pipeline
14
+ from pileorder.engine import DEFAULT_SEED, Progress
15
+ from pileorder.errors import PileorderError
16
+ from pileorder.plugins import FEATURES, planned_features
17
+
18
+ app = typer.Typer(
19
+ help="Turn piles of images into structured, checked data with AI.",
20
+ no_args_is_help=True,
21
+ add_completion=False,
22
+ )
23
+
24
+ ConfigOption = Annotated[Path, typer.Option("--config", "-c", help="Job config (YAML).")]
25
+
26
+
27
+ def _fail(e: PileorderError) -> typer.Exit:
28
+ typer.secho(f"Error: {e}", fg=typer.colors.RED, err=True)
29
+ return typer.Exit(e.exit_code)
30
+
31
+
32
+ @app.command()
33
+ def scan(config: ConfigOption = Path("job.yaml")) -> None:
34
+ """Find units on disk and record them in the manifest."""
35
+ try:
36
+ with Pipeline.from_config(config) as pipeline:
37
+ report = pipeline.scan()
38
+ except PileorderError as e:
39
+ raise _fail(e) from None
40
+ typer.echo(report.summary())
41
+
42
+
43
+ @app.command()
44
+ def status(config: ConfigOption = Path("job.yaml")) -> None:
45
+ """Show unit counts by status."""
46
+ try:
47
+ with Pipeline.from_config(config) as pipeline:
48
+ counts = pipeline.status()
49
+ usage, cost = pipeline.spent()
50
+ except PileorderError as e:
51
+ raise _fail(e) from None
52
+ duplicates = counts.pop("duplicates")
53
+ typer.echo(" ".join(f"{k}: {v}" for k, v in counts.items() if v or k in ("pending", "done", "failed")))
54
+ typer.echo(f"duplicates (processed once): {duplicates}")
55
+ cost_text = f", cost {cost}" if cost else ""
56
+ typer.echo(f"spent so far: {usage.input_tokens} in / {usage.output_tokens} out tokens{cost_text}")
57
+
58
+
59
+ DryRunOption = Annotated[
60
+ bool, typer.Option("--dry-run", help="Build the requests and estimate tokens and cost; call no API.")
61
+ ]
62
+
63
+
64
+ @app.command()
65
+ def sample(
66
+ config: ConfigOption = Path("job.yaml"),
67
+ n: Annotated[int, typer.Option("--n", "-n", min=1, help="How many random units to process.")] = 30,
68
+ seed: Annotated[int, typer.Option(help="Random seed: the same seed picks the same units.")] = DEFAULT_SEED,
69
+ dry_run: DryRunOption = False,
70
+ ) -> None:
71
+ """Process a random sample and write report.md with the measured cost and a projection for the full run.
72
+
73
+ Each sample replaces the previous one, so edit the config and sample again as often as needed.
74
+ """
75
+ try:
76
+ with Pipeline.from_config(config) as pipeline:
77
+ line = _ProgressLine(pipeline)
78
+ try:
79
+ result = pipeline.sample(n, seed, dry_run=dry_run, on_progress=line.callback)
80
+ finally:
81
+ line.end()
82
+ typer.echo(result.summary())
83
+ if not dry_run and not result.interrupted:
84
+ typer.echo(f"Report: {pipeline.report(result)}")
85
+ except PileorderError as e:
86
+ raise _fail(e) from None
87
+ except KeyboardInterrupt:
88
+ raise typer.Exit(130) from None
89
+
90
+
91
+ @app.command()
92
+ def run(
93
+ config: ConfigOption = Path("job.yaml"),
94
+ retry_failed: Annotated[bool, typer.Option("--retry-failed", help="Process failed units again.")] = False,
95
+ limit: Annotated[int | None, typer.Option(min=1, help="Process at most this many units.")] = None,
96
+ force: Annotated[
97
+ bool, typer.Option("--force", help="After a config change, redo earlier results with the new config.")
98
+ ] = False,
99
+ dry_run: DryRunOption = False,
100
+ ) -> None:
101
+ """Process every pending unit. Safe to stop and re-run: finished units are never sent twice."""
102
+ try:
103
+ with Pipeline.from_config(config) as pipeline:
104
+ line = _ProgressLine(pipeline)
105
+ try:
106
+ result = pipeline.run(
107
+ retry_failed=retry_failed, limit=limit, force=force, dry_run=dry_run, on_progress=line.callback
108
+ )
109
+ finally:
110
+ line.end()
111
+ if not dry_run and result.requests == 0 and not (result.done or result.failed):
112
+ typer.echo("Nothing to process: every unit is done or failed (--retry-failed processes failed ones).")
113
+ return
114
+ typer.echo(result.summary())
115
+ if not dry_run and result.done:
116
+ typer.echo("Next: pileorder export")
117
+ except PileorderError as e:
118
+ raise _fail(e) from None
119
+ except KeyboardInterrupt:
120
+ raise typer.Exit(130) from None
121
+
122
+
123
+ @app.command()
124
+ def export(
125
+ config: ConfigOption = Path("job.yaml"),
126
+ formats: Annotated[
127
+ list[str] | None,
128
+ typer.Option("--format", "-f", help="csv, json, jsonl (comma-separated or repeated); default: the config."),
129
+ ] = None,
130
+ ) -> None:
131
+ """Write the results from the manifest to files. Calls no API; repeat it any time."""
132
+ formats = [f.strip() for value in formats or [] for f in value.split(",") if f.strip()]
133
+ try:
134
+ with Pipeline.from_config(config) as pipeline:
135
+ paths = pipeline.export(formats or None)
136
+ except PileorderError as e:
137
+ raise _fail(e) from None
138
+ for path in paths:
139
+ typer.echo(f"Wrote {path}")
140
+
141
+
142
+ class _ProgressLine:
143
+ """A one-line progress display on stderr — only when stderr is a terminal."""
144
+
145
+ def __init__(self, pipeline: Pipeline) -> None:
146
+ self.pipeline = pipeline
147
+ self.enabled = sys.stderr.isatty()
148
+ self.shown = False
149
+
150
+ @property
151
+ def callback(self) -> Callable[[Progress], None] | None:
152
+ return self.show if self.enabled else None
153
+
154
+ def show(self, p: Progress) -> None:
155
+ self.shown = True
156
+ cost = self.pipeline.costs.cost(p.usage)
157
+ text = (
158
+ f"done {p.done}/{p.total} failed {p.failed} review {p.needs_review} retrying {p.retrying} "
159
+ f"requests {p.requests}" + (f" {cost}" if cost else "")
160
+ )
161
+ sys.stderr.write("\r" + text.ljust(100))
162
+ sys.stderr.flush()
163
+
164
+ def end(self) -> None:
165
+ if self.shown:
166
+ sys.stderr.write("\n")
167
+ self.shown = False
168
+
169
+
170
+ @app.command()
171
+ def init(directory: Annotated[Path, typer.Argument()] = Path(".")) -> None:
172
+ """Create an example config and folder layout (planned)."""
173
+ try:
174
+ FEATURES.reject_planned("init")
175
+ except PileorderError as e:
176
+ raise _fail(e) from None
177
+
178
+
179
+ @app.command("not-included")
180
+ def not_included() -> None:
181
+ """List planned features that are not in this version yet."""
182
+ for p in planned_features():
183
+ typer.echo(f"- {p.feature} — {p.milestone}")
184
+
185
+
186
+ def _version(value: bool) -> None:
187
+ if value:
188
+ typer.echo(f"pileorder {__version__}")
189
+ raise typer.Exit()
190
+
191
+
192
+ @app.callback()
193
+ def _root(
194
+ version: Annotated[
195
+ bool, typer.Option("--version", callback=_version, is_eager=True, help="Show the version and exit.")
196
+ ] = False,
197
+ ) -> None:
198
+ pass
199
+
200
+
201
+ def main() -> None:
202
+ app()
203
+
204
+
205
+ if __name__ == "__main__":
206
+ main()
File without changes