-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·1311 lines (1175 loc) · 41.5 KB
/
Copy pathcli.py
File metadata and controls
executable file
·1311 lines (1175 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright 2025 Pasteur Labs. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import logging
import re
import shlex
import sys
import time
import webbrowser
from collections.abc import Iterable
from contextlib import nullcontext
from enum import Enum
from logging import getLogger
from pathlib import Path
from types import SimpleNamespace
from typing import Annotated, Any, NoReturn
import typer
import yaml
from jinja2 import Environment, PackageLoader, StrictUndefined
from pydantic import ValidationError as PydanticValidationError
from rich.console import Console as RichConsole
from rich.table import Table as RichTable
from . import engine
from .api_parse import (
EXPECTED_OBJECTS,
TesseractBuildConfig,
TesseractConfig,
ValidationError,
get_submodel_fields_in_tesseract_config,
)
from .config import get_config
from .docker_client import (
APIError,
BuildError,
CLIDockerClient,
Container,
ContainerError,
Image,
ImageNotFound,
NotFound,
)
from .exceptions import UserError
from .logs import DEFAULT_CONSOLE, set_logger
# typer >= 0.26 vendors its own click (and drops the click dependency), so the
# Context type, exceptions, and context lookups must come from the click typer
# actually runs; fall back to real click on older typer (which still ships it).
try:
from typer._click.core import Context
from typer._click.exceptions import UsageError
from typer._click.globals import get_current_context
except ImportError: # typer < 0.26
from click import Context, UsageError, get_current_context
logger = getLogger("tesseract")
# Jinja2 Template Environment
ENV = Environment(
loader=PackageLoader("tesseract_core.sdk", "templates"),
undefined=StrictUndefined,
)
docker_client = CLIDockerClient()
class SpellcheckedTyperGroup(typer.core.TyperGroup):
"""A Typer group that suggests similar commands if a command is not found."""
def get_command(self, ctx: Context, invoked_command: str) -> Any:
"""Get a command from the Typer group, suggesting similar commands if the command is not found."""
import difflib
possible_commands = self.list_commands(ctx)
if invoked_command not in possible_commands:
close_match = difflib.get_close_matches(
invoked_command, possible_commands, n=1, cutoff=0.6
)
if close_match:
raise UsageError(
f"No such command '{invoked_command}'. Did you mean '{close_match[0]}'?",
ctx,
)
return super().get_command(ctx, invoked_command)
app = typer.Typer(
# Make -h an alias for --help
context_settings={"help_option_names": ["-h", "--help"]},
name="tesseract",
pretty_exceptions_show_locals=False,
cls=SpellcheckedTyperGroup,
)
# Module-wide config
state = SimpleNamespace()
state.print_user_error_tracebacks = False
# Create a list of possible commands based on the ones in api_parse (kebab-cased)
POSSIBLE_CMDS = set(
re.sub(r"([a-z])([A-Z])", r"\1-\2", object.name).replace("_", "-").lower()
for object in EXPECTED_OBJECTS
)
POSSIBLE_CMDS.update(
{
"health",
"openapi-schema",
"check",
"check-gradients",
"test",
"serve",
}
)
# All fields in TesseractConfig and TesseractBuildConfig for config override
POSSIBLE_KEYPATHS = TesseractConfig.model_fields.keys()
# Check that the only field that has nested models is build_config
assert len(get_submodel_fields_in_tesseract_config()) == 1
POSSIBLE_BUILD_CONFIGS = TesseractBuildConfig.model_fields.keys()
# Traverse templates folder to seach for recipes
AVAILABLE_RECIPES = set()
for temp_with_path in ENV.list_templates(extensions=["py"]):
temp_with_path = Path(temp_with_path)
if temp_with_path.name == "tesseract_api.py" and temp_with_path.parent:
AVAILABLE_RECIPES.add(str(temp_with_path.parent))
AVAILABLE_RECIPES = sorted(AVAILABLE_RECIPES)
LOGLEVELS = ("debug", "info", "warning", "error", "critical")
OUTPUT_FORMATS = ("json", "json+base64", "json+binref")
def make_choice_enum(name: str, choices: Iterable[str]) -> type[Enum]:
"""Create a choice enum for Typer."""
return Enum(name, [(choice.upper(), choice) for choice in choices], type=str)
def _enum_to_val(val: Any) -> Any:
"""Convert an Enum value to its raw representation."""
if isinstance(val, Enum):
return val.value
return val
def _validate_tesseract_name(name: str | None) -> str:
if name is None:
if sys.stdout.isatty() and sys.stdin.isatty():
name = typer.prompt("Enter a name for the Tesseract")
else:
raise typer.BadParameter(
"Name must be provided as an argument or interactively."
)
forbidden_characters: str = ":;,.@#$%^&*()[]{}<>?|\\`~"
if any(char in forbidden_characters for char in name) or any(
char.isspace() for char in name
):
raise typer.BadParameter(
f"Name cannot contain whitespace or any of the following characters: {forbidden_characters}"
)
return name
def version_callback(value: bool | None) -> None:
"""Typer callback for version option."""
if value:
from tesseract_core import __version__
typer.echo(__version__)
raise typer.Exit()
LogLevelChoices = make_choice_enum("LogLevel", LOGLEVELS)
@app.callback()
def main_callback(
loglevel: Annotated[
LogLevelChoices,
typer.Option(
help="Set the logging level. At debug level, also print tracebacks for user errors.",
case_sensitive=False,
show_default=True,
metavar="LEVEL",
),
] = "info",
version: Annotated[
bool | None,
typer.Option(
"--version",
callback=version_callback,
is_eager=True,
help="Print Tesseract CLI version and exit.",
),
] = None,
) -> None:
"""Tesseract: A toolkit for universal, autodiff-native software components."""
loglevel: str = _enum_to_val(loglevel).lower()
verbose_tracebacks = loglevel == "debug"
state.print_user_error_tracebacks = verbose_tracebacks
app.pretty_exceptions_show_locals = verbose_tracebacks
set_logger(loglevel, catch_warnings=True, rich_format=True)
try:
get_config()
except PydanticValidationError as err:
message = [
"Error while parsing Tesseract configuration. "
"Please check your environment variables.",
"Errors found:",
]
for error in err.errors():
message.append(
f' - TESSERACT_{str(error["loc"][0]).upper()}="{error["input"]}": {error["msg"]}'
)
raise UserError("\n".join(message)) from None
def _parse_config_override(
options: list[str] | None,
) -> dict[tuple[str, ...], Any]:
"""Parse `["path1.path2.path3=value"]` into `[(["path1", "path2", "path3"], "value")]`."""
if options is None:
return {}
def _parse_option(option: str) -> tuple[tuple[str, ...], Any]:
if "=" not in option:
raise typer.BadParameter(
f'Invalid config override "{option}" (must be `keypath=value`)',
param_hint="config_override",
)
key, value = option.split("=", maxsplit=1)
if not re.match(r"\w[\w|\.]*", key):
raise typer.BadParameter(
f'Invalid keypath "{key}" in config override "{option}"',
param_hint="config_override",
)
path = tuple(key.split("."))
try:
value = yaml.safe_load(value)
except yaml.YAMLError as e:
raise typer.BadParameter(
f'Invalid value for config override "{option}", could not parse value as YAML: {e}',
param_hint="config_override",
) from e
return path, value
return dict(_parse_option(option) for option in options)
@app.command("build")
@engine.needs_docker
def build_image(
src_dir: Annotated[
Path,
typer.Argument(
help=(
"Source directory for the Tesseract. Must contain `tesseract_api.py` "
"and `tesseract_config.yaml`."
),
dir_okay=True,
exists=True,
file_okay=False,
readable=True,
),
],
tag: Annotated[
str | None,
typer.Option(
"--tag",
"-t",
help="Tag for the resulting Tesseract. By default, this will "
"be inferred from the version specified in tesseract_config.yaml, "
"and the Tesseract will also be tagged as `latest`.",
),
] = None,
build_dir: Annotated[
Path | None,
typer.Option(
help="Directory to use for the build. Defaults to a temporary directory.",
dir_okay=True,
file_okay=False,
writable=True,
),
] = None,
forward_ssh_agent: Annotated[
bool,
typer.Option(
help=(
"Forward the SSH agent to the Docker build environment. "
"Has to be provided if requirements.txt contains private dependencies."
),
),
] = False,
config_override: Annotated[
list[str] | None,
typer.Option(
help=(
"Override a configuration option in the Tesseract. "
"Format: ``keypath=value`` where ``keypath`` is a dot-separated path to the "
"attribute in tesseract_config.yaml. "
"Possible keypaths are: "
f"{', '.join(POSSIBLE_KEYPATHS)}. \n"
"\n Possible build_config options are: "
f"{', '.join(POSSIBLE_BUILD_CONFIGS)}. \n"
"\nExample: ``--config-override build_config.target_platform=linux/arm64``."
),
metavar="KEYPATH=VALUE",
),
] = None,
generate_only: Annotated[
bool,
typer.Option(
help="Only generate the build context and do not actually build the image."
),
] = False,
) -> None:
"""Build a new Tesseract from a context directory.
The passed directory must contain the files `tesseract_api.py` and `tesseract_config.yaml`
(can be created via `tesseract init`).
Prints the built images as JSON array to stdout, for example: `["mytesseract:latest"]`.
If `--generate-only` is set, the path to the build context is printed instead.
"""
if config_override is None:
config_override = []
parsed_config_override = _parse_config_override(config_override)
if generate_only:
progress_indicator = nullcontext()
else:
progress_indicator = DEFAULT_CONSOLE.status(
"[white]Processing", spinner="dots", spinner_style="white"
)
try:
with progress_indicator:
build_out = engine.build_tesseract(
src_dir,
tag,
build_dir=build_dir,
inject_ssh=forward_ssh_agent,
config_override=parsed_config_override,
generate_only=generate_only,
stream_logs=logger.debug,
)
except BuildError as e:
loglevel = logging.getLogger("tesseract").handlers[0].level
error_string = "Error building Tesseract."
if loglevel <= logging.DEBUG:
# Build logs already streamed via logger.debug
pass
elif loglevel <= logging.ERROR:
# Re-emit build log at error level so it's visible
logger.error("\n".join(e.build_log))
else:
error_string = (
"Error building Tesseract. "
"Run with `--loglevel debug` for more details."
)
raise UserError(error_string) from None
except APIError as e:
raise UserError(f"Docker server error: {e}") from e
except TypeError as e:
raise UserError(f"Input error building Tesseract: {e}") from e
except PermissionError as e:
raise UserError(f"Permission denied: {e}") from e
except ValidationError as e:
raise UserError(f"Error validating tesseract_api.py: {e}") from e
if generate_only:
# output is the path to the build context
build_dir = build_out
typer.echo(build_dir)
else:
# output is the built image
image = build_out
logger.info(f"Built image {image.short_id}, {image.tags}")
typer.echo(json.dumps(image.tags))
RecipeChoices = make_choice_enum("Recipe", AVAILABLE_RECIPES)
@app.command("init")
def init(
name: Annotated[
# Guaranteed to be a string by _validate_tesseract_name
str,
typer.Option(
help="Tesseract name as specified in tesseract_config.yaml. Will be empty if not provided.",
callback=_validate_tesseract_name,
show_default=False,
),
] = "",
target_dir: Annotated[
Path,
typer.Option(
help="Path to the directory where the Tesseract API module should be created.",
dir_okay=True,
file_okay=False,
writable=True,
show_default="current directory",
),
] = Path("."),
recipe: Annotated[
RecipeChoices,
typer.Option(
help="Use a pre-configured template to initialize Tesseract API and configuration.",
),
] = "base",
) -> None:
"""Initialize a new Tesseract API module."""
recipe: str = _enum_to_val(recipe)
logger.info(f"Initializing Tesseract {name} in directory: {target_dir}")
engine.init_api(target_dir, name, recipe=recipe)
def _validate_port(port: str | None) -> str | None:
"""Validate port input."""
if port is None:
return None
port = port.strip()
if "-" in port:
start, end = port.split("-")
else:
start = end = port
try:
start, end = int(start), int(end)
except ValueError as ex:
raise typer.BadParameter(
(f"Port '{port}' must be single integer or a range (e.g. -p '8000-8080')."),
param_hint="port",
) from ex
if start > end:
raise typer.BadParameter(
(
f"Start port '{start}' must be less than "
f"or equal to end port '{end}' (e.g. -p '8000-8080')."
),
param_hint="port",
)
if not (0 <= start <= 65535) or not (0 <= end <= 65535):
raise typer.BadParameter(
f"Ports '{port}' must be between 0 and 65535.",
param_hint="port",
)
return port
def _parse_environment(
environment: list[str] | None,
) -> dict[str, str] | None:
"""Parse environment variables from a list to a dictionary."""
if environment is None:
return None
env_dict = {}
for env in environment:
if "=" not in env:
raise typer.BadParameter(
f"Environment variable '{env}' must be in the format 'key=value'.",
param_hint="environment",
)
key, value = env.split("=", maxsplit=1)
env_dict[key] = value
return env_dict
OutputFormatChoices = make_choice_enum("OutputFormat", OUTPUT_FORMATS)
@app.command("serve")
@engine.needs_docker
def serve(
image_name: Annotated[
str,
typer.Argument(..., help="Tesseract image name"),
],
volume: Annotated[
list[str] | None,
typer.Option(
"-v",
"--volume",
help="Bind mount a volume in all Tesseracts, in Docker format: source:target[:ro|rw]",
metavar="source:target",
show_default=False,
),
] = None,
environment: Annotated[
list[str] | None,
typer.Option(
"--env",
"-e",
help="Set environment variables in the Tesseract containers, in Docker format: key=value.",
),
] = None,
port: Annotated[
str | None,
typer.Option(
"--port",
"-p",
help="Optional port/port range to serve the Tesseract on (e.g. -p '8080-8082'). "
"Port must be between 1025 and 65535.",
callback=_validate_port,
),
] = None,
network: Annotated[
str | None,
typer.Option(
"--network",
help="Network to use for the Tesseract container, analogous to Docker's --network option. "
"For example, 'host' uses the host system's network. Alternatively, you can create a custom "
"network with `docker network create <network-name>` and use it here.",
show_default=False,
),
] = None,
network_alias: Annotated[
str | None,
typer.Option(
"--network-alias",
help="Network alias to use for the Tesseract container. This makes the Tesseract accessible "
"via this alias within the specified network. Must be used with --network.",
show_default=False,
),
] = None,
host_ip: Annotated[
str,
typer.Option(
"--host-ip",
help=(
"IP address of the host to bind the Tesseract to. "
"Defaults to 127.0.0.1 (localhost). To bind to all interfaces, use '0.0.0.0'. "
"WARNING: This may expose Tesseract to all local networks, use with caution."
),
),
] = "127.0.0.1",
gpus: Annotated[
list[str] | None,
typer.Option(
"--gpus",
metavar="'all' | int",
help=(
"IDs of host Nvidia GPUs to make available in the Tesseract. "
"You can use all GPUs via `--gpus all` or pass (multiple) IDs: `--gpus 0 --gpus 1`."
),
),
] = None,
num_workers: Annotated[
int,
typer.Option(
"--num-workers",
help="Number of worker processes to use when serving the Tesseract.",
show_default=True,
),
] = 1,
debug: Annotated[
bool,
typer.Option(
"--debug",
help=(
"Enable debug mode. This will propagate full tracebacks to the client "
"and start a debugpy server in the Tesseract. "
"WARNING: This may expose sensitive information, use with caution (and never in production)."
),
),
] = False,
skip_health_check: Annotated[
bool,
typer.Option(
"--skip-health-check",
help=(
"Skip the startup health check. Useful for Tesseracts with slow "
"initialization (e.g., Julia runtime startup, large model loading). "
"The caller is responsible for ensuring readiness, e.g. by polling /health."
),
),
] = False,
user: Annotated[
str | None,
typer.Option(
"--user",
help=(
"User to run the Tesseracts as e.g. '1000' or '1000:1000' (uid:gid). "
"Defaults to the current user."
),
),
] = None,
memory: Annotated[
str | None,
typer.Option(
"--memory",
"-m",
help=(
"Memory limit for the container (e.g., '512m', '2g'). "
"Minimum allowed value is 6m (6 megabytes)."
),
),
] = None,
input_path: Annotated[
str | None,
typer.Option(
"--input-path",
"-i",
help=(
"Input path to read input files from, such as local directory or S3 URI "
"(may be anything supported by fsspec)."
),
),
] = None,
output_path: Annotated[
str | None,
typer.Option(
"--output-path",
"-o",
help=(
"Output path to write output files to, such as local directory or S3 URI "
"(may be anything supported by fsspec)."
),
),
] = None,
output_format: Annotated[
OutputFormatChoices | None,
typer.Option(
"--output-format",
"-f",
help=("Output format to use for the Tesseract."),
),
] = None,
docker_args: Annotated[
str | None,
typer.Option(
"--runtime-args",
help=(
"Additional arguments to pass to the underlying container runtime (e.g., Docker). "
"Example: --runtime-args '--shm-size=1g --cpus=2'"
),
metavar="ARGS",
show_default=False,
),
] = None,
) -> None:
"""Serve one or more Tesseract images.
A successful serve command will display on standard output a JSON object
with the Tesseract container name, which is required to run the teardown
command and its respective port.
"""
output_format: str | None = _enum_to_val(output_format)
parsed_environment = _parse_environment(environment)
if network_alias is not None and network is None:
raise typer.BadParameter(
"Network alias can only be used with a specified network.",
param_hint="network_alias",
)
try:
container_name, container = engine.serve(
image_name,
host_ip=host_ip,
port=port,
network=network,
network_alias=network_alias,
volumes=volume,
environment=parsed_environment,
gpus=gpus,
debug=debug,
num_workers=num_workers,
user=user,
memory=memory,
input_path=input_path,
output_path=output_path,
output_format=_enum_to_val(output_format),
docker_args=shlex.split(docker_args) if docker_args else None,
skip_health_check=skip_health_check,
)
except RuntimeError as ex:
raise UserError(
f"Internal Docker error occurred while serving Tesseracts: {ex}"
) from ex
container_ports = _display_container_meta(container)
logger.info(
f"Tesseract container name, use it with 'tesseract teardown' command: {container_name}"
)
container_meta = {"container_name": container_name, "containers": [container_ports]}
json_info = json.dumps(container_meta)
typer.echo(json_info, nl=False)
@app.command("list")
@engine.needs_docker
def list_tesseract_images() -> None:
"""Display all Tesseract images."""
_display_tesseract_image_meta()
@app.command("ps")
@engine.needs_docker
def list_tesseract_containers() -> None:
"""Display all Tesseract containers."""
_display_tesseract_containers_meta()
def _display_tesseract_image_meta() -> None:
"""Display Tesseract image metadata."""
table = RichTable("ID", "Tags", "Name", "Version", "Description")
images = docker_client.images.list()
for image in images:
tesseract_vals = _get_tesseract_env_vals(image)
if tesseract_vals:
table.add_row(
# Checksum Type + First 12 Chars of ID
image.id[:19],
str(image.tags),
tesseract_vals["TESSERACT_NAME"],
tesseract_vals.get("TESSERACT_VERSION", ""),
tesseract_vals.get("TESSERACT_DESCRIPTION", "").replace("\n", " "),
)
RichConsole().print(table)
def _display_tesseract_containers_meta() -> None:
"""Display Tesseract containers metadata."""
table = RichTable(
"ID", "Name", "Version", "Host Address", "Container Name", "Description"
)
containers = docker_client.containers.list()
for container in containers:
tesseract_vals = _get_tesseract_env_vals(container)
if tesseract_vals:
table.add_row(
container.id[:12],
tesseract_vals["TESSERACT_NAME"],
tesseract_vals["TESSERACT_VERSION"],
f"{container.host_ip}:{container.host_port}",
container.name,
tesseract_vals.get("TESSERACT_DESCRIPTION", "").replace("\\n", " "),
)
RichConsole().print(table)
def _get_tesseract_env_vals(
docker_asset: Image | Container,
) -> dict:
"""Convert Tesseract environment variables from list to dictionary."""
env_vals = [s for s in docker_asset.attrs["Config"]["Env"] if "TESSERACT_" in s]
return {item.split("=")[0]: item.split("=")[1] for item in env_vals}
def _get_tesseract_network_meta(container: Container) -> dict:
"""Retrieve network addresses from container."""
network_meta = {}
docker_network_ips = container.docker_network_ips
if docker_network_ips:
for network_name, ip in docker_network_ips.items():
network_meta[network_name] = {
"ip": ip,
"port": container.api_port,
}
return network_meta
@app.command("apidoc")
@engine.needs_docker
def apidoc(
image_name: Annotated[
str,
typer.Argument(..., help="Tesseract image name"),
],
browser: Annotated[
bool,
typer.Option(help="Open the browser after serving the OpenAPI schema"),
] = True,
) -> None:
"""Serve the OpenAPI schema for a Tesseract."""
host_ip = "127.0.0.1"
container_name, container = engine.serve(image_name, host_ip=host_ip)
try:
url = f"http://{host_ip}:{container.host_port}/docs"
logger.info(f"Serving OpenAPI docs for Tesseract {image_name} at {url}")
logger.info(" Press Ctrl+C to stop")
if browser:
webbrowser.open(url)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
return
finally:
engine.teardown(container_name)
def _display_container_meta(container: Container) -> dict:
"""Display container metadata.
Returns a dictionary {name: container_name, port: host_port, ip: host_ip}.
"""
logger.info(f"Container ID: {container.id}")
logger.info(f"Name: {container.name}")
entrypoint = container.attrs["Config"]["Entrypoint"]
logger.info(f"Entrypoint: {entrypoint}")
host_port = container.host_port
host_ip = container.host_ip
logger.info(f"View Tesseract: http://{host_ip}:{host_port}/docs")
network_meta = _get_tesseract_network_meta(container)
if container.host_debugpy_port:
logger.info(
f"Debugpy server listening at http://{host_ip}:{container.host_debugpy_port}"
)
return {
"name": container.name,
"port": host_port,
"ip": host_ip,
"networks": network_meta,
}
@app.command("teardown")
@engine.needs_docker
def teardown(
container_names: Annotated[
list[str] | None,
typer.Argument(..., help="Tesseract container names"),
] = None,
tear_all: Annotated[
bool,
typer.Option(
"--all",
help="Tear down all Tesseracts currently being served.",
),
] = False,
) -> None:
"""Tear down one or more Tesseracts that were previously started with `tesseract serve`.
One or more Tesseract container names must be specified unless `--all` is set.
"""
if not container_names and not tear_all:
raise typer.BadParameter(
"Either container names or --all flag must be provided",
param_hint="container_names",
)
if container_names and tear_all:
raise typer.BadParameter(
"Either container names or --all flag must be provided, but not both",
param_hint="container_names",
)
try:
if not container_names:
container_names = [] # Pass in empty list if no container_names are provided.
engine.teardown(container_names, tear_all=tear_all)
except ValueError as ex:
raise UserError(
f"Input error occurred while tearing down Tesseracts: {ex}"
) from ex
except RuntimeError as ex:
raise UserError(
f"Internal Docker error occurred while tearing down Tesseracts: {ex}"
) from ex
except NotFound as ex:
raise UserError(
f"Tesseract container not found: {ex}\n"
"Use `tesseract ps` to list running containers."
) from ex
def _sanitize_error_output(error_output: str, tesseract_image: str) -> str:
"""Remove references to tesseract-runtime and unavailable commands from error output."""
# Replace references to tesseract-runtime with tesseract run
error_output = re.sub(
r"Try 'tesseract-runtime",
f"Try 'tesseract run {tesseract_image}",
error_output,
)
error_output = re.sub(
r"Usage: tesseract-runtime",
f"Usage: tesseract run {tesseract_image}",
error_output,
)
# Hide commands in help strings that users are not supposed to use via tesseract run
error_output = re.sub(
r"^│\s+(serve|health)\s+.*?$\n",
"",
error_output,
flags=re.MULTILINE,
)
return error_output
CmdChoices = make_choice_enum("Cmd", sorted(POSSIBLE_CMDS))
def _extract_cli_config(
test_spec: dict,
base_dir: Path,
) -> tuple[str | None, list[str], str | None]:
"""Extracts and resolve (input_path, volume_mounts, user) from a parsed test spec."""
cli_config = test_spec.get("cli_config", {})
if input_path := cli_config.get("input_path"):
if not Path(input_path).is_absolute():
input_path = str(base_dir / input_path)
from tesseract_core.sdk.engine import _split_volume_spec
volume_mounts = []
for vol_mount in cli_config.get("volume_mounts", []):
source = _split_volume_spec(vol_mount)[0]
if not Path(source).is_absolute():
volume_mounts.append(str(base_dir / vol_mount))
else:
volume_mounts.append(vol_mount)
user = cli_config.get("user")
return input_path, volume_mounts, user
@app.command(
"run",
# We implement --help manually to forward the help of the Tesseract container
add_help_option=False,
epilog=(
"For more information about a specific Tesseract, try `tesseract run <tesseract-name> <cmd> --help`.\n"
"For example, `tesseract run helloworld apply --help`.\n"
),
)
@engine.needs_docker
def run_container(
tesseract_image: Annotated[
str | None,
typer.Argument(
help="Tesseract image name", metavar="TESSERACT_IMAGE", show_default=False
),
] = None,
cmd: Annotated[
CmdChoices | None,
typer.Argument(
help=f"Tesseract command to run, must be one of {sorted(POSSIBLE_CMDS)}",
metavar="CMD",
show_default=False,
),
] = None,
payload: Annotated[
str | None,
typer.Argument(
help=(
"Optional payload to pass to the Tesseract command. "
"This can be a JSON string or an @ prefixed path to a JSON file."
),
show_default=False,
),
] = None,
input_path: Annotated[
str | None,
typer.Option(
"--input-path",
"-i",
help=(
"Input path to read input files from, such as local directory or S3 URI "
"(may be anything supported by fsspec)."
),
),
] = None,
output_path: Annotated[
str | None,
typer.Option(
"--output-path",
"-o",
help=(
"Output path to write output files to, such as local directory or S3 URI "
"(may be anything supported by fsspec)."
),
),
] = None,
output_format: Annotated[
OutputFormatChoices | None,