# 스크립팅

> nolan Python 클라이언트와 nolan-cli로 nolanlabs 다루기. 버튼, 에이전트와 같은 작업을 쓰고, 모든 변경을 검사하며, 스크립트 하나가 작업 기록의 한 단계가 됩니다.

Page: https://nolanlabs.io/ko/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)` 안에서는 배치가 트랜잭션으로 가고, 페이지는 이를 에이전트의 제안처럼 보여 주며, 블록이 끝나면 한 단계로 유지됩니다. 엔진이 거부한 배치는 명령을 가리키는 `op_index`와 함께 `nolan.NolanError`를 일으키고, 아무것도 바꾸지 않습니다.

## 아무 작업이나 호출하기

모든 작업은 분야별 함수이고, 항목이 인수이며, 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")
```

각 메서드는 배치 하나를 보내고 타임라인을 다시 읽으므로, 객체는 변경 후의 타임라인을 그대로 보여 줍니다. 둘로 자른 클립은 왼쪽 조각이 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`가 파이프에서 raw 데이터를 읽습니다.

```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/ko/docs/known-limits)를 보세요. 직접 작성한 스크립트에서 나온 제안에는 **유지**와 **버리기**가 있습니다. [제안](https://nolanlabs.io/ko/docs/proposals)을 보세요.
