File size: 5,223 Bytes
04f192c | 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 | # SPDX-FileCopyrightText: Copyright contributors to the CopilotJ project.
#
# SPDX-License-Identifier: Apache-2.0
import asyncio
import base64
import json
from collections.abc import Callable
from io import BytesIO
import click
import rich
import textual_image.renderable
from PIL import Image as PILImage
from copilotj.core import load_config
from copilotj.plugin import HTTPPluginAPI, Verbosity
from copilotj.plugin.api import ClientPluginAPI
from copilotj.util import extract_base64_image
@click.group()
@click.option("--server", default="http://127.0.0.1:8786", help="ImageJ plugin server address")
@click.option("--verbosity", type=click.Choice(["low", "normal", "high"]), default="normal")
@click.pass_context
def cli(ctx, server, verbosity):
"""CLI for interacting with the ImageJ plugin API."""
load_config()
ctx.ensure_object(dict)
ctx.obj["server"] = server
match verbosity:
case "low":
ctx.obj["verbosity"] = Verbosity.NORMAL
case "normal":
ctx.obj["verbosity"] = Verbosity.NORMAL
case "high":
ctx.obj["verbosity"] = Verbosity.HIGH
case _:
ctx.obj["verbosity"] = Verbosity.NORMAL
def run(get_api: Callable[[ClientPluginAPI], Callable], ctx, *args, **kwargs):
async def runner():
apis = HTTPPluginAPI(ctx.obj["server"])
client_apis = apis.attach_single_client()
api = get_api(client_apis)
try:
response = await api(*args, **kwargs)
finally:
await apis.close()
return response
loop = asyncio.new_event_loop()
response = loop.run_until_complete(runner())
loop.close()
if callable(getattr(response, "describe")):
resp = response.describe(level=1, verbosity=ctx.obj["verbosity"])
else:
resp = str(response)
console = rich.console.Console()
console.print(resp)
@cli.command()
@click.option("--snapshot", type=int, help="ID of the snapshot")
@click.option("--action", type=int, help="Id of the action")
@click.option("--parameters", type=str, default=None, help="JSON-encoded parameter list")
@click.pass_context
def call_action(ctx, snapshot, action, parameters):
"""Capture the image from ImageJ."""
parsed = json.loads(parameters) if parameters else None
run(lambda a: a.call_action, ctx, snapshot, action, parsed)
@cli.command()
@click.option("--title", type=str, default=None, help="Title of the image")
@click.pass_context
def capture_image(ctx, title):
"""Capture the image from ImageJ."""
def capture_image(client: ClientPluginAPI):
async def wrapper(title: str):
result = await client.capture_image(title)
b64 = extract_base64_image(result.image)
image = PILImage.open(BytesIO(base64.b64decode(b64)))
console = rich.console.Console()
console.print(textual_image.renderable.Image(image))
return result
return wrapper
run(capture_image, ctx, title)
@cli.command()
@click.pass_context
def capture_screen(ctx):
"""Capture the current screen from ImageJ."""
def capture_screen(client: ClientPluginAPI):
async def wrapper():
result = await client.capture_screen()
console = rich.console.Console()
for screen in result.screenshots:
b64 = extract_base64_image(screen.image)
image = PILImage.open(BytesIO(base64.b64decode(b64)))
console.print(textual_image.renderable.Image(image))
return result
return wrapper
run(capture_screen, ctx)
@cli.command()
@click.pass_context
@click.argument("early", type=int, required=True) # ID of the early snapshot
@click.argument("later", type=int, required=False, default=None) # ID of the later snapshot
def compare_snapshots(ctx, early, later):
"""Compare two snapshots from ImageJ."""
run(lambda a: a.compare_snapshots, ctx, early, later)
@cli.command()
@click.pass_context
@click.argument("since", type=click.DateTime(), required=False, default=None)
def get_operation_history(ctx, since):
"""Get the operation history from ImageJ."""
run(lambda a: a.get_operation_history, ctx, since)
@cli.command()
@click.pass_context
def take_snapshot(ctx):
"""Take a snapshot of the current ImageJ state."""
run(lambda a: a.take_snapshot, ctx)
@cli.command()
@click.option("--language", default="macro", help="Scripting language")
@click.option("--script", type=str, default=None, help="Path to the script file")
@click.option("--script-file", type=str, default=None, help="Path to the script file")
@click.pass_context
def run_script(ctx, language, script, script_file):
"""Run a script in ImageJ."""
# If a script file is provided, read its content
if script_file:
with open(script_file, "r") as f:
script = f.read()
assert script or script_file, "Either --script or --script-file must be provided"
run(lambda a: a.run_script, ctx, language, script)
@cli.command()
@click.pass_context
def summarise_environment(ctx):
"""Get a summary of the current ImageJ environment."""
run(lambda a: a.summarise_environment, ctx)
cli()
|