# スクリプト

> nolan Python クライアントと nolan-cli で nolanlabs を動かす方法です。ボタンやエージェントと同じ操作を使い、変更はすべてチェックされ、スクリプトはヒストリーのひとつのステップになります。

Page: https://nolanlabs.io/ja/docs/scripting

プログラムにしたほうが楽な作業にはスクリプトを使います。すべてのビートでカットする、すべてのヒットにエフェクトをかける、カットの前に測る、といった作業です。`nolan` Python クライアントと `nolan-cli` は、ボタンやエージェントと同じ操作を使うので、変更はすべてチェックされ、スクリプトによる変更はヒストリーのひとつのステップになります。

## セットアップ

クライアントに必要なのは Python 3.10 以降だけです。OpenTimelineIO は任意で、`to_otio()` に使います。アプリはクライアントをリソース内の `python-client` というフォルダに入れています。Mac で、アプリが「アプリケーション」にある場合は次のとおりです。

```sh
pip install /Applications/nolanlabs.app/Contents/Resources/python-client
```

OpenTimelineIO を使うにはパスの末尾に `[otio]` を付けます。または、代わりにそのフォルダを `PYTHONPATH` に入れます。

クライアントは、起動中のアプリを自分で見つけます。`NOLAN_URL` を設定すれば、そちらが優先されます。リクエストにはすべてサービスのシークレットが付きます。起動中のアプリと同じマシンでは、クライアントと CLI がそれを自分で読むので、設定するものはありません。別の場所のサービスには `NOLAN_TOKEN` で指定します。

## 最初のスクリプト

```python
import nolan

s = nolan.connect()                         # NOLAN_URL, or http://127.0.0.1:8790
tl = s.timeline()                           # NOLAN_TIMELINE, or the first timeline
music = s.sources("Music")[0]["id"]
beats = s.sound(music, fps=tl.fps)["beats"]

with tl.transaction("Cut to the beat"):     # one step in the history; dropped if the block raises
    for clip, beat in zip(tl.track("V1").items, beats[4::4]):
        if clip.end > beat:
            clip.trim("tail", beat - clip.end, ripple=True)
    tl.track("V1").items[0].effect("grain", 0.3)

print(tl.summary()["mean_shot_s"])
```

トランザクションの外では、各バッチがそれぞれひとつのステップとしてタイムラインに入ります。`with tl.transaction(label)` の中では、バッチはトランザクションに送られ、ページはそれをエージェントの提案と同じように表示し、ブロックの終わりでひとつのステップとして採用されます。エンジンが拒否したバッチは `nolan.NolanError` を送出し、`op_index` でどのコマンドかを示し、何も変更しません。

## どの操作でも呼び出す

操作はすべて領域ごとの関数で、フィールドが引数になり、docstring にそれぞれの単位と範囲が書かれています。存在しないフィールドは、存在するフィールドの一覧と一緒に拒否されます。ここでの `session` は、`nolan.connect()` が返すものです。

```python
nolan.ops.clip.trim(clip="c4", edge="tail", delta=-6, tl=tl)
nolan.ops.text.add(at=24, len=48, text="NEXT LEVEL", look="impact", y=0.2, in_="slam", in_len=6, tl=tl)
beats = nolan.analyse.sound("Rocket")["beats"]          # nolan.analyse and nolan.track are nolan.ops.analyse and .track
tl.edit([{"op": "clip.dissolve", "clip": "c5", "frames": 12},
         {"op": "grade.primary", "clip": "c5", "temp": 0.15}], name="Warmer")
tl.do("timeline.marker_add", at=96, name="Drop")
session.op("deliver.render", preset="prores", path="/out/master.mov")
```

Python の予約語と同じ名前のフィールドは、引数では末尾に `_` を付けます（`in_`、`from_`）。`tl.edit` と `tl.do` では元の名前のままです。`nolan.ops.CATALOGUE` にはすべての操作とそのフィールドがあり、`nolan.ops.catalogue()` はプラグインも含めて編集ソフトに問い合わせます。

## やりたいことから

```python
# Bring things in, and cut them
s.import_media(["/footage/a.mov", "/footage/b.mov"])
tl.insert("a", 0, length=48, overwrite=True)

# Grade with wheels and curves, and a LUT
clip.grade(lift=[0, 0, .02], gain=[.05, 0, -.03], curves={"m": [[0, 0], [.5, .55], [1, 1]]})
clip.grade(lut="film.cube", lut_mix=.6)  # in the project's LUTs folder, or a full path

# Read the frame from the originals, and check the numbers
print(tl.scopes(at=48)["luma"])

# Mask, track and move the mask with what it follows
clip.set(masks=[{"shape": "ellipse", "x": .5, "y": .4, "w": .3, "h": .5, "feather": .05, "invert": True}])
path = s.track(clip.src, clip.source_in, clip.source_in + clip.length, x=.5, y=.4, w=.3, h=.5, mode="move")
clip.track_apply(path, target="mask:0")

# Words on an arc, letter by letter
tl.title("STUNT SHOW", 0, 72, path=[[.2, .6], [.5, .4], [.8, .6]], by="char",
         per=[{"prop": "opacity", "stagger": 2, "keys": [{"f": 0, "v": 0}, {"f": 8, "v": 1}]}])

# Sound
clip.set(afx=[{"kind": "highpass", "freq": 80}, {"kind": "reverb", "size": .4, "mix": .15}], pan=-.2)

# Cameras
angles = s.sync(["cam_a", "cam_b"])
tl.multicam(angles, at=0, length=240)

# Deliver anything
tl.render("/out/master.mov", preset="prores", profile="hq", audio="pcm24", loudness=-16)
tl.render("/out/frames", sequence="exr", alpha=True)
tl.render("/out/hdr.mov", codec="prores", profile="hq", hdr="pq")   # cache=True does nothing for HDR or EXR
tl.export("fcpxml", "/out/cut.fcpxml")
```

各メソッドはバッチをひとつ送ってタイムラインを読み戻すので、オブジェクトは変更後のタイムラインの状態を表します。2つに分割したクリップは、左側の部分が ID を引き継ぎます。

## コードからメディアを作る

プログラムは、タイムラインに置くものを自分で作れます。次のどれも、ファイルをプロジェクトの `Media/Generated` に書き出し、読み込み、既存のものの上に何も動かさずに重ね、ヒストリーのひとつのステップにします。取り消すとクリップは外れ、ソースはプールに残ります。

```python
import numpy as np
from PIL import Image, ImageDraw

# A picture: an array or a Pillow image, for 5 seconds at the end of the track unless you say
picture = Image.new("RGBA", (tl.width, tl.height), (0, 0, 0, 0))
ImageDraw.Draw(picture).ellipse((200, 100, 600, 500), fill=(255, 80, 0, 255))
tl.add_image(picture, at=0, length=48, track="V2", name="Disc")

# Moving pictures: a generator is sent as it makes them, so length costs no memory
def noise():
    rng = np.random.default_rng(7)
    for i in range(96):
        yield rng.random((tl.height, tl.width, 3)) * (i / 96)
tl.add_frames(noise(), fps=tl.fps, at=48, name="Noise")

# Sound: float from -1 to 1, or int16; one channel or (samples, channels)
t = np.arange(96000) / 48000
tl.add_audio(np.sin(2 * np.pi * 110 * t) * 0.3, rate=48000, at=0, track="A2", name="Hum")
```

| 呼び出し | 受け取るもの | できるもの |
| --- | --- | --- |
| `tl.add_image(image, at, length, track, name)` | (H, W)、(H, W, 1)、(H, W, 3)、(H, W, 4) の配列（uint8、uint16、または 0〜1 の float）、または Pillow の画像 | PNG。uint16 か float からなら 16 ビット |
| `tl.add_frames(frames, fps, at, length, track, name)` | それらのジェネレーターかリスト、または (T, H, W[, C]) の配列 | ProRes 422 HQ、アルファ付きなら 4444 |
| `tl.add_audio(samples, rate, at, length, track, name)` | (N,) または (N, channels) の配列（float か int16）、またはチャンクのジェネレーター | 24 ビット WAV |

配列や画像はあなたのプログラム自身のものなので、これらに使う NumPy と Pillow はご自身でインストールしてください。

## シェルから使う

```
nolan-cli [--url URL] [--project NAME|FOLDER|ID] [--timeline ID] COMMAND

projects | open PATH [--force] | close [NAME] [--stop]    the projects open at once
runs [--state S] | ask PROMPT [--thread T] [--wait]       the agent of --project (or the one the app shows)
answer RUN OPTION [--note N] | cancel RUN
host status | host restart|stop [--when idle|now] | host cancel

run [--label L] [--dry-run] script.py [-- args]    a script, in one transaction
summary | ops [WORDS] | lookup WORDS               read; ops lists every op with its fields
op NAME [FIELD=JSON ...] [--dry-run]               any op: op clip.trim clip=c4 edge=tail delta=-6
inspect WHAT [FIELD=JSON ...]                      the agent's inspect tool: inspect clips track=V1
look WHAT [FIELD=JSON ...] [--out DIR]             the agent's look tool; pictures saved to DIR, their paths printed
wait ID [--timeout S] | busy | background          wait for a script in the background (r1) or a render (j1); what still runs
apply '[{"op": "split", "at": 48}]' [--dry-run]    any engine commands
clip ID [FIELD=JSON ...]                           read or change a clip
render [--out F] [--preset P] [--from A] [--to B] [FIELD=JSON ...]    waits for it
export otio|fcpxml|edl|aaf [OUT] [--track V2]      import FILE
scopes [--at F] | cache [--from A --to B --wait]   sheet OUT.jpg [--count N]
fonts | font FILE | relink [--folder D | --src ID --path F]
add image|frames|audio [--name N] [--at F] [--length L] [--track V2]
    [--width W --height H --pix rgb24 --fps F | --rate R --channels C --format f32le] < RAW
```

`run` は、`nolan`、`session`、`tl` を用意したうえで、スクリプトをひとつのトランザクションの中で実行します。正常に終わればひとつのステップとして採用し、例外が出れば破棄します。`--dry-run` は何をしたかを示してから破棄します。この方法で実行するスクリプトはあなた自身のものなので、セーフモードなしで動きます。`python -m nolan` も同じコマンドです。

どの言語からでも、`nolan-cli add` でパイプから生データを読めます。

```sh
my_renderer | nolan-cli add frames --width 1920 --height 1080 --pix rgb24 --fps 24 --track V2 --name Sim
my_synth | nolan-cli add audio --rate 48000 --channels 2 --format f32le --at 96
```

## 開いているどのプロジェクトにも

`nolan-cli --project NAME` は、アプリのウィンドウを切り替えずにそのプロジェクトで作業します。Python の `nolan.project(name)` も同じです。

```python
import nolan
teaser = nolan.project("Launch Teaser")
teaser.timeline().marker(48, "From the script")         # edits that project, whatever the app's window shows
run = teaser.agent.ask("Tighten the second half")      # a Run: id, thread, status (running, paused, done, failed, cancelled), and what it waits on you for
run.wait()                                             # waits through a restart: a paused run carries on by itself
for r in nolan.runs(state="waiting"):                  # every open project's runs that wait for an answer
    print(r.project, r.title)
teaser.close(stop=False)                               # refused while its work goes, unless stop=True
nolan.host.status(); nolan.host.restart(when="idle")
```

## モードの切り替えとアップデート

`s.mode` はアプリのモードで、`"lite"` か `"pro"` です。`s.set_mode("pro")` で切り替えます。`nolan-cli mode` で表示し、`nolan-cli mode lite` で切り替えます。

```sh
nolan-cli update          # or: update check, update install
```

## 各オブジェクトが持つもの

| オブジェクト | 持つもの |
| --- | --- |
| `Session` | `project`, `timelines`, `timeline(id)`, `new_timeline`, `new_project`, `open`, `import_media`, `add_media`, `sources(q)`, `sound`, `sfx`, `sync(srcs, by)`, `motion`, `track`, `shake`, `subject`, `key_colour`, `relink`, `fonts()`, `import_font(path)`, `import_timeline(path)`, `set_proxy(size)`, `set_agent(access, ask_me)`, `style()`, `set_style(user, project)`, `plugins()`, `save_generator(name, code, params)`, `op(name, **fields)`, `run_script(code)` |
| `Timeline` | 読み取り：`fps`, `width`, `height`, `length`, `markers`, `tracks`, `track(id)`, `clips`, `clip(id)`, `at(frame, track)`, `summary()`, `checks()`, `frame(at, path)`, `still(at, path)`, `contact_sheet(path)`, `scopes(at, pictures, hdr)`, `cache(frm, to, wait)`, `mix()`, `watch()`。変更：`edit(ops, name)`, `do(name, **fields)`, `apply(commands)`, `op(command, **fields)`, `dry_run(commands)`, `transaction(label)`, `undo()`, `insert`, `lay`, `add_image`, `add_frames`, `add_audio`, `split`, `title`, `marker`, `add_track`, `compound(frm, to)`, `decompose(clip)`, `multicam(angles, at)`。出力：`render(path, preset, frm, to, **deliver)`, `export(kind, path, track)`, `otio_json()`, `to_otio()` |
| `Track` | `id`, `kind`, `name`, `items`, `set(**fields)` |
| `Clip` | `id`, `track`, `src`, `at`, `end`, `length`, `source_in`, `title`, `anim`, `fx`, `speed`; `trim`, `roll`, `slip`, `slide`, `move`, `split`, `delete`, `set`, `keyframe`, `effect`, `motion`, `transition`, `grade`, `track_matte`, `track_apply`, `stabilize` |

## エージェントのスクリプト

エージェントもこのクライアントを持っています。エージェントが実行するスクリプトは、下書き、つまり提案のコピーの上で動きます。スクリプトが正常に終わると、すべてがひとつのバッチとして提案に入ります。失敗すると何も残らず、作ったメディアも消えます。

エージェントのスクリプトはセーフモードで動きます。読み込めるモジュールの制限、書き込みは専用の一時フォルダの中だけ、新しいプロセスはなし、時間、CPU、メモリの制限があります。Windows では、ディスクの読み取り専用ビューもメモリの制限もありません。セーフモードはミスを防ぐためのもので、セキュリティの境界ではありません。[既知の制限](https://nolanlabs.io/ja/docs/known-limits)を参照してください。自分のスクリプトからの提案には**採用**と**破棄**があります。[提案](https://nolanlabs.io/ja/docs/proposals)を参照してください。
