Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions examples/flow_ui_assistant/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Example: Flow web worker for assistant video jobs

Render an Omni first/last-frame scene through the signed-in Flow web composer and let the existing `assistant` provider write the result to the scene. This example uses Flow's displayed credits and its own Generate and Download controls. It does not need the Flow Kit browser extension, access to browser credentials, or changes to the core providers.

The example has two halves: `worker.py` holds a job lease and returns the downloaded file to FlowKit; `browser.js` is loaded by an active browser operator (tested with Codex) that can use the signed-in tab. It is not a standalone browser daemon. Use the Simplified Chinese Flow interface; the browser labels and selectors in this example are pinned to that interface. Expect it to stop if the Flow controls change.

## Prerequisites

- Run FlowKit and this example on the same machine. Use Python 3.10+ and put `ffprobe` and `ffmpeg` on `PATH`.
- Open an existing Flow project in a normally signed-in browser with the Flow Kit extension disabled for the test. In FlowKit, use a project with that same `flow_project_id`, `video_model_family: omni_flash`, and a scene with a duration of 4, 6, 8 or 10 seconds. Both scene frames must already exist in the Flow project. Use a linked child scene for the tail frame so the batch producer can resolve `end_url`.
- Copy `config.example.json` outside the repository and replace its project UUID, frame media UUIDs and exact Flow asset names. The start and end UUIDs must match the ones already on the scene and its chain. Set the model, resolution, and maximum credits per job. In the Flow composer select Video → Frames, choose the matching aspect, model and duration, and set `x1`. Leave the composer empty.
- Keep a single worker on the test queue so another `assistant` worker does not take the job. This example handles an explicit request ID and ignores unrelated jobs.

## Walkthrough

Run the following from the repository root. Keep the state directory outside the checkout and retain it while FlowKit references its outputs. Add `--api http://127.0.0.1:<port>/api` before a subcommand if using a custom port.

1. Submit the scene through the normal `POST /api/requests/batch` endpoint. Example body (replace the IDs):

```json
{
"requests": [{
"type": "GENERATE_VIDEO",
"provider": "assistant",
"orientation": "VERTICAL",
"project_id": "<project-id>",
"video_id": "<video-id>",
"scene_id": "<scene-id>"
}]
}
```

2. Take the ID returned by the batch request. When `GET /api/provider-jobs/<request-id>` reports `QUEUED`, claim it:

```bash
python examples/flow_ui_assistant/worker.py --state-dir /path/to/state claim REQUEST_ID --config /path/to/config.json
```

Load `browser.js` in the browser operator, create `const worker = createFlowUiWorker(tab)` with the signed-in project tab, and pass the claim command's JSON output to `await worker.prepare(job)`. It checks the project, frames, composer settings and displayed credits before submission.

3. Record a submit intent and then invoke `await worker.submit(job)` **once**:

```bash
python examples/flow_ui_assistant/worker.py --state-dir /path/to/state mark-submit REQUEST_ID
```

If the click times out, inspect `await worker.status(job)` and the existing Flow result. Do not submit a second time. For longer waits, run `heartbeat REQUEST_ID` about every 100 seconds to renew the worker lease. Stop on Flow warnings or a challenge. Do not automate a challenge or switch to another provider on failure. `fail REQUEST_ID --reason ...` can report a known failure on the live lease; the example will not reclaim a job it has handled.

4. When `await worker.status(job)` reports `ready`, call `await worker.requestDownload(job)` once. Identify the new MP4 in Chrome's configured download directory using the returned timestamp. Complete the job with that file:

```bash
python examples/flow_ui_assistant/worker.py --state-dir /path/to/state complete REQUEST_ID --video /path/to/download.mp4
```

The helper checks size, duration and full decode, stages the MP4 and reports its `file://` URL to the provider job. Check `GET /api/requests/<request-id>` and `GET /api/scenes/<scene-id>`: the request and scene video status should be `COMPLETED` with the same media UUID and file URL. The example never patches the scene to set the result.
106 changes: 106 additions & 0 deletions examples/flow_ui_assistant/browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Load this factory in the browser operator and pass the signed-in Flow tab.
// Labels are from the Simplified Chinese Flow UI. This uses visible controls only.
function createFlowUiWorker(tab) {
const p = tab.playwright;
const button = (name, scope = p) => scope.getByRole('button', {name, exact: true});
const findRow = job => p.locator('.batch-container').filter({hasText: job.prompt});
const restriction = /异常活动|unusual activity|reCAPTCHA|(?:修改|更改|改动).{0,16}(?:网页|页面).{0,16}(?:扩展|插件)|(?:扩展|插件).{0,24}(?:修改|更改|改动)|extension.{0,50}(?:modify|interfer)/i;
const click = locator => locator.click({timeoutMs: 5000});
const requireOne = async (locator, message) => {
if (await locator.count() !== 1) throw Error(message);
return locator;
};
const assertProject = async job => {
if (!/^https:\/\/flow\.google\.com\/project\/[0-9a-f-]{36}$/.test(job.extra.project_url) ||
(await tab.url()) !== job.extra.project_url) throw Error('Flow project mismatch');
};
const assertClear = async () => {
const snap = await p.domSnapshot();
if (restriction.test(snap)) throw Error('Flow displayed a restriction; stop the queue');
return snap;
};
async function frame(slot, name) {
await click(button(slot));
const heading = p.getByRole('heading', {name: '选择画面图像', exact: true});
await heading.waitFor({state: 'visible', timeoutMs: 5000});
await click(await requireOne(p.getByRole('option', {name, exact: true}), `Missing or ambiguous asset: ${name}`));
await p.domSnapshot();
// Flow applies a click on the current selection immediately. Selecting a
// different asset opens its preview and requires one extra confirmation.
if (await heading.isVisible()) {
await p.getByRole('img', {name: `“${name}”的预览`, exact: true}).waitFor({state: 'visible', timeoutMs: 5000});
await click(button('添加到提示'));
}
await heading.waitFor({state: 'hidden', timeoutMs: 5000});
if (await button(slot).isVisible()) throw Error(`Frame did not attach: ${slot}`);
}
return {
async prepare(job) {
await assertProject(job);
await assertClear();
const {start_asset, end_asset, resolution, duration, aspect, model, max_credits} = job.extra;
if (!job.prompt?.trim() || !start_asset || !end_asset) throw Error('Prompt and both assets are required');
if (await findRow(job).count()) throw Error('A matching Flow row exists; reconcile before resubmitting');
if (!await button('开始').isVisible() || !await button('结束').isVisible() || await button('清除提示').isVisible()) {
throw Error('Composer has a draft or is not in Frames mode');
}
await click(button('设置触发器'));
const settings = await assertClear();
const checked = (radio) => settings.split('\n').some(line => line.includes(`radio "${radio}" [checked]`));
const resLine = settings.split('\n').find(line => line.includes(`radio "${resolution}`) && line.includes('[checked]'));
const modelButton = await button('选择模型系列').innerText({timeoutMs: 3000});
if (!['视频','帧',aspect,`${duration} 秒`,'x1'].every(checked) || !resLine || !modelButton.includes(model)) {
throw Error('Current Flow settings differ from the queue manifest');
}
const credits = settings.match(/link "(\d+) 个点数"/)?.[1];
if (credits === undefined || !Number.isInteger(max_credits) || Number(credits) > max_credits) {
throw Error('Flow points unknown or above the per-job cap');
}
await click(button('设置触发器'));
await frame('开始', start_asset);
await frame('结束', end_asset);
await p.getByRole('textbox', {name: '您希望创作什么?', exact: true}).fill(job.prompt, {timeoutMs: 5000});
return {id: job.id, points: Number(credits), status: 'prepared'};
},
async submit(job) {
await assertProject(job);
const snap = await assertClear();
if (await findRow(job).count()) throw Error('Matching Flow row already exists; will not resubmit');
const textbox = p.getByRole('textbox', {name: '您希望创作什么?', exact: true});
if ((await textbox.innerText({timeoutMs: 5000})).trim() !== job.prompt.trim() ||
!snap.includes(`视频 · ${job.extra.resolution} · ${job.extra.duration} 秒`) ||
!snap.includes('text: x1') || await button('图片素材').count() !== 2 || !await button('开始生成').isEnabled()) {
throw Error('Composer no longer matches the prepared job');
}
// If this call fails, its outcome is unknown. Reconcile by job prompt; never retry blindly.
await click(button('开始生成'));
return this.status(job);
},
async status(job) {
await assertProject(job);
await assertClear();
const row = findRow(job);
const n = await row.count();
if (n > 1) throw Error('Duplicate matching result cards; stop the queue');
if (n === 0) return {id: job.id, status: 'not_visible'};
const details = await row.innerText({timeoutMs: 5000});
if (/生成失败|无法生成|^\s*失败\s*$/m.test(details)) throw Error(`Flow rejected job ${job.id}`);
const download = button('下载', row);
const video = row.getByRole('img', {name: '生成的视频缩略图', exact: true})
.or(row.locator('[aria-label="生成的视频"]'));
if (await download.count() === 1 && await download.isEnabled() && await video.count() > 0) {
return {id: job.id, status: 'ready'};
}
const percent = details.match(/(\d{1,3})%/)?.[1];
return {id: job.id, status: 'pending', percent: percent === undefined ? null : Number(percent)};
},
async requestDownload(job) {
if ((await this.status(job)).status !== 'ready') throw Error('Video is not ready');
// Chrome saves to its configured download directory; the browser bridge
// did not emit a download event for this control. Check the file locally.
const requestedAt = new Date().toISOString();
await click(button('下载', findRow(job)));
return {id: job.id, requestedAt};
},
};
}
10 changes: 10 additions & 0 deletions examples/flow_ui_assistant/config.example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"project_id": "00000000-0000-4000-8000-000000000001",
"model": "Omni 1.1 Flash",
"resolution": "360p",
"max_credits": 4,
"assets": {
"00000000-0000-4000-8000-000000000002": "first-frame.png",
"00000000-0000-4000-8000-000000000003": "last-frame.png"
}
}
169 changes: 169 additions & 0 deletions examples/flow_ui_assistant/worker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
"""Bridge one existing assistant provider job to a browser operator.

Run from the same machine as the FlowKit server. This example never enqueues
jobs, changes scenes, or sends requests to Google. See README.md for the
browser half and the explicit handoff between steps.
"""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
from urllib.parse import urlsplit
from urllib.request import Request, urlopen
from uuid import UUID, uuid4


def browser_job(job: dict, config: dict) -> dict:
"""Translate the batch producer's payload into one browser operation."""
extra = job.get("extra") or {}
if job.get("provider") != "assistant" or job.get("kind") != "video":
raise ValueError("Expected an assistant i2v job")
if extra.get("model_family") != "omni_flash" or not job.get("start_url") or not job.get("end_url"):
raise ValueError("This example needs Omni and both scene frame URLs")
project = str(UUID(config["project_id"]))
if project != extra.get("project_id"):
raise ValueError("Flow project does not match the job")
try:
start, end = (config["assets"][str(UUID(extra[f"{key}_media_id"]))] for key in ("start", "end"))
except (KeyError, ValueError, AttributeError) as exc:
raise ValueError("Both job frame IDs need a mapping to existing Flow assets") from exc
duration = extra.get("duration_s")
aspect = {"VERTICAL": "9:16", "HORIZONTAL": "16:9"}.get(job.get("orientation"))
resolution = config["resolution"]
model = config["model"]
cap = config["max_credits"]
prompt = job.get("prompt", "").strip()
if (duration not in (4, 6, 8, 10) or not aspect or resolution not in ("360p", "720p")
or not isinstance(model, str) or not model.startswith("Omni ") or type(cap) is not int or cap < 0
or not prompt or not all(isinstance(name, str) and name.strip() for name in (start, end))):
raise ValueError("Unsupported Omni settings or empty prompt/asset name")
return {"id": job["id"], "prompt": prompt, "extra": {
"project_url": f"https://flow.google.com/project/{project}",
"start_asset": start, "end_asset": end, "aspect": aspect,
"duration": int(duration), "resolution": resolution, "model": model, "max_credits": cap,
}}


def queue_call(api: str, path: str, body: dict | None = None) -> dict:
url = urlsplit(api)
if (url.scheme != "http" or url.hostname not in ("localhost", "127.0.0.1", "::1")
or url.username or url.password or url.path.rstrip("/") != "/api" or url.query or url.fragment):
raise ValueError("Use a local FlowKit API base such as http://127.0.0.1:8100/api")
request = Request(api.rstrip("/") + "/provider-jobs/" + path,
data=None if body is None else json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
with urlopen(request, timeout=10) as response:
return json.load(response)


def stage_mp4(source: Path, output: Path, settings: dict) -> str:
"""Validate the downloaded file before reporting a result to FlowKit."""
if source.suffix.lower() != ".mp4" or not source.is_file():
raise ValueError("Expected a downloaded MP4")
probe = json.loads(subprocess.check_output([
"ffprobe", "-v", "error", "-show_entries", "stream=codec_type,width,height:format=duration",
"-of", "json", str(source),
], timeout=30))
short = int(settings["resolution"][:-1])
long = round(short * 16 / 9)
expected = (short, long) if settings["aspect"] == "9:16" else (long, short)
video = [(s.get("width"), s.get("height")) for s in probe["streams"] if s["codec_type"] == "video"]
if video != [expected] or abs(float(probe["format"]["duration"]) - settings["duration"]) > 0.25:
raise ValueError("Downloaded video does not match the job's size or duration")
subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-xerror", "-i", str(source),
"-map", "0:v", "-map", "0:a?", "-f", "null", "-"], check=True, timeout=120)

def sha256(path: Path) -> bytes:
digest = hashlib.sha256()
with path.open("rb") as file:
for chunk in iter(lambda: file.read(1024 * 1024), b""):
digest.update(chunk)
return digest.digest()

if not output.exists():
with source.open("rb") as src, output.open("xb") as dst:
shutil.copyfileobj(src, dst)
if sha256(source) != sha256(output):
raise ValueError("Existing staged file differs; no result was sent")
return output.resolve().as_uri()


def run(args: argparse.Namespace) -> dict:
job_id = args.job_id
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,79}", job_id):
raise ValueError("Invalid provider job ID")
job = queue_call(args.api, job_id)
lease_path = args.state_dir / f"{job_id}.json"
intent_path = args.state_dir / f"{job_id}.submit-intent"

if args.action == "claim":
if lease_path.exists() or intent_path.exists() or job["status"] != "QUEUED" or job["retry_count"] != 0:
raise ValueError("Job was already handled; reconcile in Flow before submitting again")
config = json.loads(args.config.read_text(encoding="utf-8-sig"))
prepared = browser_job(job, config)
args.state_dir.mkdir(parents=True, exist_ok=True)
worker_id = f"flow-ui-example-{uuid4().hex}"
claimed = queue_call(args.api, f"{job_id}/claim", {"worker_id": worker_id, "lease_ttl_s": 300})
if claimed["retry_count"] != 1 or claimed["claimed_by"] != worker_id:
raise ValueError("Expected a fresh, owned lease")
with lease_path.open("x", encoding="utf-8") as lease:
json.dump({"worker_id": worker_id, "job": prepared}, lease, ensure_ascii=False)
return prepared

lease = json.loads(lease_path.read_text(encoding="utf-8"))
owner = {"worker_id": lease["worker_id"]}
if job.get("claimed_by") != owner["worker_id"] or job.get("retry_count") != 1:
raise ValueError("Job lease is no longer owned; reconcile in Flow")
if args.action == "complete" and job["status"] == "SUCCEEDED":
return job # Recover a lost local /complete response without downloading again.
if job["status"] not in ("CLAIMED", "RUNNING"):
raise ValueError("Job is no longer live; reconcile in Flow")
if args.action == "heartbeat":
return queue_call(args.api, f"{job_id}/heartbeat", {**owner, "lease_ttl_s": 300})
if args.action == "fail":
return queue_call(args.api, f"{job_id}/fail", {**owner, "error": args.reason})
if args.action == "mark-submit":
if job["progress"] != 0:
raise ValueError("Submit intent already recorded")
with intent_path.open("x", encoding="utf-8") as intent:
intent.write("Do not submit again. Inspect the existing Flow result.\n")
return queue_call(args.api, f"{job_id}/progress", {
**owner, "progress": 1, "message": "Flow UI submit intent; reconcile before another click",
})
if not intent_path.is_file() or job["progress"] < 1:
raise ValueError("Expected a recorded submit intent")
output_url = stage_mp4(args.video, args.state_dir / f"{job_id}.mp4", lease["job"]["extra"])
return queue_call(args.api, f"{job_id}/complete", {**owner, "result": {"output_url": output_url}})


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--api", default="http://127.0.0.1:8100/api")
parser.add_argument("--state-dir", type=Path, required=True)
commands = parser.add_subparsers(dest="action", required=True)
for action in ("claim", "mark-submit", "heartbeat", "complete", "fail"):
command = commands.add_parser(action)
command.add_argument("job_id")
if action == "claim":
command.add_argument("--config", type=Path, required=True)
if action == "complete":
command.add_argument("--video", type=Path, required=True)
if action == "fail":
command.add_argument("--reason", required=True)
try:
# ASCII JSON keeps captured output portable across terminal encodings.
print(json.dumps(run(parser.parse_args())))
except (OSError, ValueError, KeyError, subprocess.SubprocessError) as exc:
print(f"Flow UI worker stopped: {exc}", file=sys.stderr)
return 1
return 0


if __name__ == "__main__":
sys.exit(main())
Loading