leoxing1996 commited on
Commit
d16b52d
1 Parent(s): f1efa0a
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitmodules +3 -0
  2. Dockerfile +62 -0
  3. demo/.gitattributes +35 -0
  4. demo/.gitignore +6 -0
  5. demo/README.md +70 -0
  6. demo/app.py +149 -0
  7. demo/config.py +121 -0
  8. demo/connection_manager.py +111 -0
  9. demo/demo_cfg.yaml +47 -0
  10. demo/demo_cfg_arknight.yaml +48 -0
  11. demo/frontend/.eslintignore +13 -0
  12. demo/frontend/.eslintrc.cjs +30 -0
  13. demo/frontend/.gitignore +10 -0
  14. demo/frontend/.npmrc +1 -0
  15. demo/frontend/.prettierignore +13 -0
  16. demo/frontend/.prettierrc +19 -0
  17. demo/frontend/README.md +38 -0
  18. demo/frontend/package-lock.json +0 -0
  19. demo/frontend/package.json +41 -0
  20. demo/frontend/postcss.config.js +6 -0
  21. demo/frontend/src/app.css +3 -0
  22. demo/frontend/src/app.d.ts +12 -0
  23. demo/frontend/src/app.html +12 -0
  24. demo/frontend/src/lib/components/Button.svelte +15 -0
  25. demo/frontend/src/lib/components/Checkbox.svelte +15 -0
  26. demo/frontend/src/lib/components/ImagePlayer.svelte +50 -0
  27. demo/frontend/src/lib/components/InputRange.svelte +52 -0
  28. demo/frontend/src/lib/components/MediaListSwitcher.svelte +40 -0
  29. demo/frontend/src/lib/components/PipelineOptions.svelte +62 -0
  30. demo/frontend/src/lib/components/SeedInput.svelte +28 -0
  31. demo/frontend/src/lib/components/Selectlist.svelte +26 -0
  32. demo/frontend/src/lib/components/TextArea.svelte +25 -0
  33. demo/frontend/src/lib/components/VideoInput.svelte +139 -0
  34. demo/frontend/src/lib/components/Warning.svelte +27 -0
  35. demo/frontend/src/lib/icons/floppy.svelte +10 -0
  36. demo/frontend/src/lib/icons/screen.svelte +10 -0
  37. demo/frontend/src/lib/icons/spinner.svelte +10 -0
  38. demo/frontend/src/lib/index.ts +1 -0
  39. demo/frontend/src/lib/lcmLive.ts +99 -0
  40. demo/frontend/src/lib/mediaStream.ts +98 -0
  41. demo/frontend/src/lib/store.ts +15 -0
  42. demo/frontend/src/lib/types.ts +40 -0
  43. demo/frontend/src/lib/utils.ts +38 -0
  44. demo/frontend/src/routes/+layout.svelte +5 -0
  45. demo/frontend/src/routes/+page.svelte +160 -0
  46. demo/frontend/src/routes/+page.ts +1 -0
  47. demo/frontend/static/favicon.png +0 -0
  48. demo/frontend/svelte.config.js +17 -0
  49. demo/frontend/tailwind.config.js +8 -0
  50. demo/frontend/tsconfig.json +17 -0
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "MiDaS"]
2
+ path = live2diff/MiDaS
3
+ url = git@github.com:lewiji/MiDaS.git
Dockerfile ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:12.1.1-cudnn8-devel-ubuntu22.04
2
+
3
+ ARG DEBIAN_FRONTEND=noninteractive
4
+
5
+ ENV PYTHONUNBUFFERED=1
6
+ ENV NODE_MAJOR=20
7
+
8
+ RUN apt-get update && apt-get install --no-install-recommends -y \
9
+ build-essential \
10
+ python3.9 \
11
+ python3-pip \
12
+ python3-dev \
13
+ git \
14
+ ffmpeg \
15
+ google-perftools \
16
+ ca-certificates curl gnupg \
17
+ && apt-get clean && rm -rf /var/lib/apt/lists/*
18
+
19
+ WORKDIR /code
20
+
21
+ RUN mkdir -p /etc/apt/keyrings
22
+ RUN curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
23
+ RUN echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_${NODE_MAJOR}.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list > /dev/null
24
+ RUN apt-get update && apt-get install nodejs -y
25
+
26
+ COPY ./requirements.txt /code/requirements.txt
27
+
28
+ # Set up a new user named "user" with user ID 1000
29
+ RUN useradd -m -u 1000 user
30
+ # Switch to the "user" user
31
+ USER user
32
+ # Set home to the user's home directory
33
+ ENV HOME=/home/user \
34
+ PATH=/home/user/.local/bin:$PATH \
35
+ PYTHONPATH=$HOME/app \
36
+ PYTHONUNBUFFERED=1 \
37
+ SYSTEM=spaces
38
+
39
+ # Set the working directory to the user's home directory
40
+ WORKDIR $HOME/app
41
+
42
+ # Copy the current directory contents into the container at $HOME/app setting the owner to the user
43
+ COPY --chown=user . $HOME/app
44
+
45
+ ENV LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc.so.4
46
+
47
+ # install dependencies
48
+ RUN git submodule update --init --recursive
49
+ RUN pip install -e ."[tensorrt]"
50
+
51
+ # download models`
52
+ RUN mkdir models
53
+ RUN huggingface-cli download Leoxing/Live2Diff live2diff.ckpt --local-dir ./models
54
+ RUN huggingface-cli download runwayml/stable-diffusion-v1-5 \
55
+ --local-dir ./models/Model/stable-diffusion-v1-5
56
+ RUN bash scripts/download.sh felted
57
+ RUN wget https://github.com/isl-org/MiDaS/releases/download/v3/dpt_hybrid_384.pt -P models
58
+
59
+ RUN cd demo
60
+ RUN pip install -r requirements.txt
61
+ CMD ["bash ./start.sh"]
62
+
demo/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
demo/.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ venv/
3
+ public/
4
+ *.pem
5
+ !lib/
6
+ !static/
demo/README.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Video2Video Example
2
+
3
+ <div align="center">
4
+ <table align="center">
5
+ <tbody>
6
+ <tr align="center">
7
+ <td>
8
+ <p> Human Face (Web Camera Input) </p>
9
+ </td>
10
+ <td>
11
+ <p> Anime Character (Screen Video Input) </p>
12
+ </td>
13
+ </tr>
14
+ <tr align="center">
15
+ <td>
16
+ <video controls autoplay src="https://github-production-user-asset-6210df.s3.amazonaws.com/28132635/346031564-a56bea4f-9aed-497c-9cb9-868db72599fb.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAVCODYLSA53PQK4ZA%2F20240705%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240705T064755Z&X-Amz-Expires=300&X-Amz-Signature=3d0890fa6af8b86d10c69de9c31b8f97ff1d35cdbcdd4b1a9e465e49dd8d8194&X-Amz-SignedHeaders=host&actor_id=28132635&key_id=0&repo_id=819189683" width="100%">
17
+ </td>
18
+ <td>
19
+ <video controls autoplay src="https://github-production-user-asset-6210df.s3.amazonaws.com/28132635/346055688-00f873dc-7348-458d-a814-7a7e8d158db5.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAVCODYLSA53PQK4ZA%2F20240705%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240705T081427Z&X-Amz-Expires=300&X-Amz-Signature=609199998d9f10a814d7a65e6dbff980a84bba77f25f43f99a1607bd0cee2f01&X-Amz-SignedHeaders=host&actor_id=28132635&key_id=0&repo_id=819189683" width="80%">
20
+ </td>
21
+ </tr>
22
+ </tbody>
23
+ </table>
24
+
25
+ </div>
26
+
27
+ This example, based on this [MJPEG server](https://github.com/radames/Real-Time-Latent-Consistency-Model/), runs image-to-image with a live webcam feed or screen capture on a web browser.
28
+
29
+ ## Usage
30
+
31
+ ### 1. Prepare Dependencies
32
+
33
+ You need Node.js 18+ and Python 3.10 to run this example. Please make sure you've installed all dependencies according to the [installation instructions](../README.md#installation).
34
+
35
+ ```bash
36
+ cd frontend
37
+ npm i
38
+ npm run build
39
+ cd ..
40
+ pip install -r requirements.txt
41
+ ```
42
+
43
+ If you face some difficulties in install `npm`, you can try to install it via `conda`:
44
+
45
+ ```bash
46
+ conda install -c conda-forge nodejs
47
+ ```
48
+
49
+ ### 2. Run Demo
50
+
51
+ If you run the demo with default [setting](./demo_cfg.yaml), you should download the model for style `felted`.
52
+
53
+ ```bash
54
+ bash ../scripts/download_model.sh felted
55
+ ```
56
+
57
+ Then, you can run the demo with the following command, and open `http://127.0.0.1:7860` in your browser:
58
+
59
+ ```bash
60
+ # with TensorRT acceleration, please pay patience for the first time, may take more than 20 minutes
61
+ python main.py --port 7860 --host 127.0.0.1 --acceleration tensorrt
62
+ # if you don't have TensorRT, you can run it with `none` acceleration
63
+ python main.py --port 7860 --host 127.0.0.1 --acceleration none
64
+ ```
65
+
66
+ If you want to run this demo on a remote server, you can set host to `0.0.0.0`, e.g.
67
+
68
+ ```bash
69
+ python main.py --port 7860 --host 0.0.0.0 --acceleration tensorrt
70
+ ```
demo/app.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import mimetypes
3
+ import os
4
+ import time
5
+ import uuid
6
+ from types import SimpleNamespace
7
+
8
+ import markdown2
9
+ import torch
10
+ from config import Args, config
11
+ from connection_manager import ConnectionManager, ServerFullException
12
+ from fastapi import FastAPI, HTTPException, Request, WebSocket
13
+ from fastapi.middleware.cors import CORSMiddleware
14
+ from fastapi.responses import JSONResponse, StreamingResponse
15
+ from fastapi.staticfiles import StaticFiles
16
+ from util import bytes_to_pil, pil_to_frame
17
+ from vid2vid import Pipeline
18
+
19
+
20
+ # fix mime error on windows
21
+ mimetypes.add_type("application/javascript", ".js")
22
+
23
+ THROTTLE = 1.0 / 120
24
+ # logging.basicConfig(level=logging.DEBUG)
25
+
26
+
27
+ class App:
28
+ def __init__(self, config: Args):
29
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
30
+ torch_dtype = torch.float16
31
+ pipeline = Pipeline(config, device, torch_dtype)
32
+ self.args = config
33
+ self.pipeline = pipeline
34
+ self.app = FastAPI()
35
+ self.conn_manager = ConnectionManager()
36
+ self.init_app()
37
+
38
+ def init_app(self):
39
+ self.app.add_middleware(
40
+ CORSMiddleware,
41
+ allow_origins=["*"],
42
+ allow_credentials=True,
43
+ allow_methods=["*"],
44
+ allow_headers=["*"],
45
+ )
46
+
47
+ @self.app.websocket("/api/ws/{user_id}")
48
+ async def websocket_endpoint(user_id: uuid.UUID, websocket: WebSocket):
49
+ try:
50
+ await self.conn_manager.connect(user_id, websocket, self.args.max_queue_size)
51
+ await handle_websocket_data(user_id)
52
+ except ServerFullException as e:
53
+ logging.error(f"Server Full: {e}")
54
+ finally:
55
+ await self.conn_manager.disconnect(user_id)
56
+ logging.info(f"User disconnected: {user_id}")
57
+
58
+ async def handle_websocket_data(user_id: uuid.UUID):
59
+ if not self.conn_manager.check_user(user_id):
60
+ return HTTPException(status_code=404, detail="User not found")
61
+ last_time = time.time()
62
+ try:
63
+ while True:
64
+ if self.args.timeout > 0 and time.time() - last_time > self.args.timeout:
65
+ await self.conn_manager.send_json(
66
+ user_id,
67
+ {
68
+ "status": "timeout",
69
+ "message": "Your session has ended",
70
+ },
71
+ )
72
+ await self.conn_manager.disconnect(user_id)
73
+ return
74
+ data = await self.conn_manager.receive_json(user_id)
75
+ if data["status"] == "next_frame":
76
+ info = self.pipeline.Info()
77
+ params = await self.conn_manager.receive_json(user_id)
78
+ params = self.pipeline.InputParams(**params)
79
+ params = SimpleNamespace(**params.model_dump())
80
+ if info.input_mode == "image":
81
+ image_data = await self.conn_manager.receive_bytes(user_id)
82
+ if len(image_data) == 0:
83
+ await self.conn_manager.send_json(user_id, {"status": "send_frame"})
84
+ continue
85
+ params.image = bytes_to_pil(image_data)
86
+ await self.conn_manager.update_data(user_id, params)
87
+
88
+ except Exception as e:
89
+ logging.error(f"Websocket Error: {e}, {user_id} ")
90
+ await self.conn_manager.disconnect(user_id)
91
+
92
+ @self.app.get("/api/queue")
93
+ async def get_queue_size():
94
+ queue_size = self.conn_manager.get_user_count()
95
+ return JSONResponse({"queue_size": queue_size})
96
+
97
+ @self.app.get("/api/stream/{user_id}")
98
+ async def stream(user_id: uuid.UUID, request: Request):
99
+ try:
100
+
101
+ async def generate():
102
+ while True:
103
+ last_time = time.time()
104
+ await self.conn_manager.send_json(user_id, {"status": "send_frame"})
105
+ params = await self.conn_manager.get_latest_data(user_id)
106
+ if params is None:
107
+ continue
108
+ image = self.pipeline.predict(params)
109
+ if image is None:
110
+ continue
111
+ frame = pil_to_frame(image)
112
+ yield frame
113
+ if self.args.debug:
114
+ print(f"Time taken: {time.time() - last_time}")
115
+
116
+ return StreamingResponse(
117
+ generate(),
118
+ media_type="multipart/x-mixed-replace;boundary=frame",
119
+ headers={"Cache-Control": "no-cache"},
120
+ )
121
+ except Exception as e:
122
+ logging.error(f"Streaming Error: {e}, {user_id} ")
123
+ return HTTPException(status_code=404, detail="User not found")
124
+
125
+ # route to setup frontend
126
+ @self.app.get("/api/settings")
127
+ async def settings():
128
+ info_schema = self.pipeline.Info.model_json_schema()
129
+ info = self.pipeline.Info()
130
+ if info.page_content:
131
+ page_content = markdown2.markdown(info.page_content)
132
+
133
+ input_params = self.pipeline.InputParams.model_json_schema()
134
+ return JSONResponse(
135
+ {
136
+ "info": info_schema,
137
+ "input_params": input_params,
138
+ "max_queue_size": self.args.max_queue_size,
139
+ "page_content": page_content if info.page_content else "",
140
+ }
141
+ )
142
+
143
+ if not os.path.exists("public"):
144
+ os.makedirs("public")
145
+
146
+ self.app.mount("/", StaticFiles(directory="./frontend/public", html=True), name="public")
147
+
148
+
149
+ app = App(config).app
demo/config.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ from typing import List, NamedTuple
4
+
5
+
6
+ class Args(NamedTuple):
7
+ host: str
8
+ port: int
9
+ reload: bool
10
+ max_queue_size: int
11
+ timeout: float
12
+ safety_checker: bool
13
+ taesd: bool
14
+ ssl_certfile: str
15
+ ssl_keyfile: str
16
+ debug: bool
17
+ acceleration: str
18
+ engine_dir: str
19
+ config: str
20
+ seed: int
21
+ num_inference_steps: int
22
+ strength: float
23
+ t_index_list: List[int]
24
+ prompt: str
25
+
26
+ def pretty_print(self):
27
+ print("\n")
28
+ for field, value in self._asdict().items():
29
+ print(f"{field}: {value}")
30
+ print("\n")
31
+
32
+
33
+ MAX_QUEUE_SIZE = int(os.environ.get("MAX_QUEUE_SIZE", 0))
34
+ TIMEOUT = float(os.environ.get("TIMEOUT", 0))
35
+ SAFETY_CHECKER = os.environ.get("SAFETY_CHECKER", None) == "True"
36
+ USE_TAESD = os.environ.get("USE_TAESD", "True") == "True"
37
+ ENGINE_DIR = os.environ.get("ENGINE_DIR", "engines")
38
+ ACCELERATION = os.environ.get("ACCELERATION", "tensorrt")
39
+
40
+ default_host = os.getenv("HOST", "0.0.0.0")
41
+ default_port = int(os.getenv("PORT", "7860"))
42
+ default_mode = os.getenv("MODE", "default")
43
+
44
+ parser = argparse.ArgumentParser(description="Run the app")
45
+ parser.add_argument("--host", type=str, default=default_host, help="Host address")
46
+ parser.add_argument("--port", type=int, default=default_port, help="Port number")
47
+ parser.add_argument("--reload", action="store_true", help="Reload code on change")
48
+ parser.add_argument(
49
+ "--max-queue-size",
50
+ dest="max_queue_size",
51
+ type=int,
52
+ default=MAX_QUEUE_SIZE,
53
+ help="Max Queue Size",
54
+ )
55
+ parser.add_argument("--timeout", type=float, default=TIMEOUT, help="Timeout")
56
+ parser.add_argument(
57
+ "--safety-checker",
58
+ dest="safety_checker",
59
+ action="store_true",
60
+ default=SAFETY_CHECKER,
61
+ help="Safety Checker",
62
+ )
63
+ parser.add_argument(
64
+ "--taesd",
65
+ dest="taesd",
66
+ action="store_true",
67
+ help="Use Tiny Autoencoder",
68
+ )
69
+ parser.add_argument(
70
+ "--no-taesd",
71
+ dest="taesd",
72
+ action="store_false",
73
+ help="Use Tiny Autoencoder",
74
+ )
75
+ parser.add_argument(
76
+ "--ssl-certfile",
77
+ dest="ssl_certfile",
78
+ type=str,
79
+ default=None,
80
+ help="SSL certfile",
81
+ )
82
+ parser.add_argument(
83
+ "--ssl-keyfile",
84
+ dest="ssl_keyfile",
85
+ type=str,
86
+ default=None,
87
+ help="SSL keyfile",
88
+ )
89
+ parser.add_argument(
90
+ "--debug",
91
+ action="store_true",
92
+ default=False,
93
+ help="Debug",
94
+ )
95
+ parser.add_argument(
96
+ "--acceleration",
97
+ type=str,
98
+ default=ACCELERATION,
99
+ choices=["none", "xformers", "tensorrt"],
100
+ help="Acceleration",
101
+ )
102
+ parser.add_argument(
103
+ "--engine-dir",
104
+ dest="engine_dir",
105
+ type=str,
106
+ default=ENGINE_DIR,
107
+ help="Engine Dir",
108
+ )
109
+ parser.add_argument(
110
+ "--config",
111
+ default="./demo_cfg.yaml",
112
+ )
113
+ parser.add_argument("--num-inference-steps", type=int, default=None)
114
+ parser.add_argument("--strength", type=float, default=None)
115
+ parser.add_argument("--t-index-list", type=list)
116
+ parser.add_argument("--seed", default=42)
117
+ parser.add_argument("--prompt", type=str)
118
+
119
+ parser.set_defaults(taesd=USE_TAESD)
120
+ config = Args(**vars(parser.parse_args()))
121
+ config.pretty_print()
demo/connection_manager.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from types import SimpleNamespace
4
+ from typing import Dict, Union
5
+ from uuid import UUID
6
+
7
+ from fastapi import WebSocket
8
+ from starlette.websockets import WebSocketState
9
+
10
+
11
+ Connections = Dict[UUID, Dict[str, Union[WebSocket, asyncio.Queue]]]
12
+
13
+
14
+ class ServerFullException(Exception):
15
+ """Exception raised when the server is full."""
16
+
17
+ pass
18
+
19
+
20
+ class ConnectionManager:
21
+ def __init__(self):
22
+ self.active_connections: Connections = {}
23
+
24
+ async def connect(self, user_id: UUID, websocket: WebSocket, max_queue_size: int = 0):
25
+ await websocket.accept()
26
+ user_count = self.get_user_count()
27
+ print(f"User count: {user_count}")
28
+ if max_queue_size > 0 and user_count >= max_queue_size:
29
+ print("Server is full")
30
+ await websocket.send_json({"status": "error", "message": "Server is full"})
31
+ await websocket.close()
32
+ raise ServerFullException("Server is full")
33
+ print(f"New user connected: {user_id}")
34
+ self.active_connections[user_id] = {
35
+ "websocket": websocket,
36
+ "queue": asyncio.Queue(),
37
+ }
38
+ await websocket.send_json(
39
+ {"status": "connected", "message": "Connected"},
40
+ )
41
+ await websocket.send_json({"status": "wait"})
42
+ await websocket.send_json({"status": "send_frame"})
43
+
44
+ def check_user(self, user_id: UUID) -> bool:
45
+ return user_id in self.active_connections
46
+
47
+ async def update_data(self, user_id: UUID, new_data: SimpleNamespace):
48
+ user_session = self.active_connections.get(user_id)
49
+ if user_session:
50
+ queue = user_session["queue"]
51
+ await queue.put(new_data)
52
+
53
+ async def get_latest_data(self, user_id: UUID) -> SimpleNamespace:
54
+ user_session = self.active_connections.get(user_id)
55
+ if user_session:
56
+ queue = user_session["queue"]
57
+ try:
58
+ return await queue.get()
59
+ except asyncio.QueueEmpty:
60
+ return None
61
+
62
+ def delete_user(self, user_id: UUID):
63
+ user_session = self.active_connections.pop(user_id, None)
64
+ if user_session:
65
+ queue = user_session["queue"]
66
+ while not queue.empty():
67
+ try:
68
+ queue.get_nowait()
69
+ except asyncio.QueueEmpty:
70
+ continue
71
+
72
+ def get_user_count(self) -> int:
73
+ return len(self.active_connections)
74
+
75
+ def get_websocket(self, user_id: UUID) -> WebSocket:
76
+ user_session = self.active_connections.get(user_id)
77
+ if user_session:
78
+ websocket = user_session["websocket"]
79
+ if websocket.client_state == WebSocketState.CONNECTED:
80
+ return user_session["websocket"]
81
+ return None
82
+
83
+ async def disconnect(self, user_id: UUID):
84
+ websocket = self.get_websocket(user_id)
85
+ if websocket:
86
+ await websocket.close()
87
+ self.delete_user(user_id)
88
+
89
+ async def send_json(self, user_id: UUID, data: Dict):
90
+ try:
91
+ websocket = self.get_websocket(user_id)
92
+ if websocket:
93
+ await websocket.send_json(data)
94
+ except Exception as e:
95
+ logging.error(f"Error: Send json: {e}")
96
+
97
+ async def receive_json(self, user_id: UUID) -> Dict:
98
+ try:
99
+ websocket = self.get_websocket(user_id)
100
+ if websocket:
101
+ return await websocket.receive_json()
102
+ except Exception as e:
103
+ logging.error(f"Error: Receive json: {e}")
104
+
105
+ async def receive_bytes(self, user_id: UUID) -> bytes:
106
+ try:
107
+ websocket = self.get_websocket(user_id)
108
+ if websocket:
109
+ return await websocket.receive_bytes()
110
+ except Exception as e:
111
+ logging.error(f"Error: Receive bytes: {e}")
demo/demo_cfg.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pretrained_model_path: "../models/Model/stable-diffusion-v1-5"
2
+
3
+ motion_module_path: '../models/live2diff.ckpt'
4
+ depth_model_path: '../models/dpt_hybrid_384.pt'
5
+
6
+ unet_additional_kwargs:
7
+ cond_mapping: true
8
+ use_inflated_groupnorm: true
9
+ use_motion_module : true
10
+ motion_module_resolutions : [ 1,2,4,8 ]
11
+ unet_use_cross_frame_attention : false
12
+ unet_use_temporal_attention : false
13
+
14
+ motion_module_type: Streaming
15
+ motion_module_kwargs:
16
+ num_attention_heads : 8
17
+ num_transformer_block : 1
18
+ attention_block_types : [ "Temporal_Self", "Temporal_Self" ]
19
+ temporal_position_encoding : true
20
+ temporal_position_encoding_max_len : 24
21
+ temporal_attention_dim_div : 1
22
+ zero_initialize : true
23
+
24
+ attention_class_name : 'stream'
25
+
26
+ attention_kwargs:
27
+ window_size: 16
28
+ sink_size: 8
29
+
30
+ noise_scheduler_kwargs:
31
+ num_train_timesteps: 1000
32
+ beta_start: 0.00085
33
+ beta_end: 0.012
34
+ beta_schedule: "linear"
35
+ steps_offset: 1
36
+ clip_sample: False
37
+
38
+ third_party_dict:
39
+ dreambooth: "../models/Model/revAnimated_v2RebirthVAE.safetensors"
40
+ lora_list:
41
+ - lora: '../models/LoRA/kFeltedReV.safetensors'
42
+ lora_alpha: 1
43
+ clip_skip: 2
44
+
45
+ num_inference_steps: 50
46
+ t_index_list: [30, 40]
47
+ prompt: "masterpiece, best quality, felted, 1man with glasses, glasses, play with his pen"
demo/demo_cfg_arknight.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pretrained_model_path: "../models/Model/stable-diffusion-v1-5"
2
+
3
+ motion_module_path: '../models/live2diff.ckpt'
4
+ depth_model_path: '../models/dpt_hybrid_384.pt'
5
+
6
+ unet_additional_kwargs:
7
+ cond_mapping: true
8
+ use_inflated_groupnorm: true
9
+ use_motion_module : true
10
+ motion_module_resolutions : [ 1,2,4,8 ]
11
+ unet_use_cross_frame_attention : false
12
+ unet_use_temporal_attention : false
13
+
14
+ motion_module_type: Streaming
15
+ motion_module_kwargs:
16
+ num_attention_heads : 8
17
+ num_transformer_block : 1
18
+ attention_block_types : [ "Temporal_Self", "Temporal_Self" ]
19
+ temporal_position_encoding : true
20
+ temporal_position_encoding_max_len : 24
21
+ temporal_attention_dim_div : 1
22
+ zero_initialize : true
23
+
24
+ attention_class_name : 'stream'
25
+
26
+ attention_kwargs:
27
+ window_size: 16
28
+ sink_size: 8
29
+
30
+ noise_scheduler_kwargs:
31
+ num_train_timesteps: 1000
32
+ beta_start: 0.00085
33
+ beta_end: 0.012
34
+ beta_schedule: "linear"
35
+ steps_offset: 1
36
+ clip_sample: False
37
+
38
+ third_party_dict:
39
+ dreambooth: "../models/Model/aziibpixelmix_v10.safetensors"
40
+ lora_list:
41
+ - lora: '../models/LoRA/kFeltedReV.safetensors'
42
+ lora_alpha: 1
43
+ clip_skip: 2
44
+
45
+ num_inference_steps: 50
46
+ t_index_list: [35, 40, 45]
47
+
48
+ prompt: "masterpiece, best quality, 1gril"
demo/frontend/.eslintignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ node_modules
3
+ /build
4
+ /.svelte-kit
5
+ /package
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+
10
+ # Ignore files for PNPM, NPM and YARN
11
+ pnpm-lock.yaml
12
+ package-lock.json
13
+ yarn.lock
demo/frontend/.eslintrc.cjs ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ root: true,
3
+ extends: [
4
+ 'eslint:recommended',
5
+ 'plugin:@typescript-eslint/recommended',
6
+ 'plugin:svelte/recommended',
7
+ 'prettier'
8
+ ],
9
+ parser: '@typescript-eslint/parser',
10
+ plugins: ['@typescript-eslint'],
11
+ parserOptions: {
12
+ sourceType: 'module',
13
+ ecmaVersion: 2020,
14
+ extraFileExtensions: ['.svelte']
15
+ },
16
+ env: {
17
+ browser: true,
18
+ es2017: true,
19
+ node: true
20
+ },
21
+ overrides: [
22
+ {
23
+ files: ['*.svelte'],
24
+ parser: 'svelte-eslint-parser',
25
+ parserOptions: {
26
+ parser: '@typescript-eslint/parser'
27
+ }
28
+ }
29
+ ]
30
+ };
demo/frontend/.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ node_modules
3
+ /build
4
+ /.svelte-kit
5
+ /package
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+ vite.config.js.timestamp-*
10
+ vite.config.ts.timestamp-*
demo/frontend/.npmrc ADDED
@@ -0,0 +1 @@
 
 
1
+ engine-strict=true
demo/frontend/.prettierignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ node_modules
3
+ /build
4
+ /.svelte-kit
5
+ /package
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+
10
+ # Ignore files for PNPM, NPM and YARN
11
+ pnpm-lock.yaml
12
+ package-lock.json
13
+ yarn.lock
demo/frontend/.prettierrc ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "useTabs": false,
3
+ "singleQuote": true,
4
+ "trailingComma": "none",
5
+ "printWidth": 100,
6
+ "plugins": [
7
+ "prettier-plugin-svelte",
8
+ "prettier-plugin-organize-imports",
9
+ "prettier-plugin-tailwindcss"
10
+ ],
11
+ "overrides": [
12
+ {
13
+ "files": "*.svelte",
14
+ "options": {
15
+ "parser": "svelte"
16
+ }
17
+ }
18
+ ]
19
+ }
demo/frontend/README.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # create-svelte
2
+
3
+ Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte).
4
+
5
+ ## Creating a project
6
+
7
+ If you're seeing this, you've probably already done this step. Congrats!
8
+
9
+ ```bash
10
+ # create a new project in the current directory
11
+ npm create svelte@latest
12
+
13
+ # create a new project in my-app
14
+ npm create svelte@latest my-app
15
+ ```
16
+
17
+ ## Developing
18
+
19
+ Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
20
+
21
+ ```bash
22
+ npm run dev
23
+
24
+ # or start the server and open the app in a new browser tab
25
+ npm run dev -- --open
26
+ ```
27
+
28
+ ## Building
29
+
30
+ To create a production version of your app:
31
+
32
+ ```bash
33
+ npm run build
34
+ ```
35
+
36
+ You can preview the production build with `npm run preview`.
37
+
38
+ > To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
demo/frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
demo/frontend/package.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "frontend",
3
+ "version": "0.0.1",
4
+ "private": true,
5
+ "scripts": {
6
+ "dev": "vite dev",
7
+ "build": "vite build",
8
+ "preview": "vite preview",
9
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
10
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
11
+ "lint": "prettier --check . && eslint .",
12
+ "format": "prettier --write ."
13
+ },
14
+ "devDependencies": {
15
+ "@sveltejs/adapter-auto": "^2.0.0",
16
+ "@sveltejs/adapter-static": "^2.0.3",
17
+ "@sveltejs/kit": "^1.20.4",
18
+ "@typescript-eslint/eslint-plugin": "^6.0.0",
19
+ "@typescript-eslint/parser": "^6.0.0",
20
+ "autoprefixer": "^10.4.16",
21
+ "eslint": "^8.28.0",
22
+ "eslint-config-prettier": "^9.0.0",
23
+ "eslint-plugin-svelte": "^2.30.0",
24
+ "postcss": "^8.4.31",
25
+ "prettier": "^3.1.0",
26
+ "prettier-plugin-organize-imports": "^3.2.4",
27
+ "prettier-plugin-svelte": "^3.1.0",
28
+ "prettier-plugin-tailwindcss": "^0.5.7",
29
+ "svelte": "^4.0.5",
30
+ "svelte-check": "^3.4.3",
31
+ "tailwindcss": "^3.3.5",
32
+ "tslib": "^2.4.1",
33
+ "typescript": "^5.0.0",
34
+ "vite": "^4.4.2"
35
+ },
36
+ "type": "module",
37
+ "dependencies": {
38
+ "piexifjs": "^1.0.6",
39
+ "rvfc-polyfill": "^1.0.7"
40
+ }
41
+ }
demo/frontend/postcss.config.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {}
5
+ }
6
+ };
demo/frontend/src/app.css ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
demo/frontend/src/app.d.ts ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // See https://kit.svelte.dev/docs/types#app
2
+ // for information about these interfaces
3
+ declare global {
4
+ namespace App {
5
+ // interface Error {}
6
+ // interface Locals {}
7
+ // interface PageData {}
8
+ // interface Platform {}
9
+ }
10
+ }
11
+
12
+ export {};
demo/frontend/src/app.html ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <link rel="icon" href="%sveltekit.assets%/favicon.png" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
7
+ %sveltekit.head%
8
+ </head>
9
+ <body data-sveltekit-preload-data="hover">
10
+ <div style="display: contents">%sveltekit.body%</div>
11
+ </body>
12
+ </html>
demo/frontend/src/lib/components/Button.svelte ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let classList: string = 'p-2';
3
+ export let disabled: boolean = false;
4
+ export let title: string = '';
5
+ </script>
6
+
7
+ <button class="button {classList}" on:click {disabled} {title}>
8
+ <slot />
9
+ </button>
10
+
11
+ <style lang="postcss" scoped>
12
+ .button {
13
+ @apply rounded bg-gray-700 font-normal text-white hover:bg-gray-800 disabled:cursor-not-allowed disabled:bg-gray-300 dark:disabled:bg-gray-700 dark:disabled:text-black;
14
+ }
15
+ </style>
demo/frontend/src/lib/components/Checkbox.svelte ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { FieldProps } from '$lib/types';
3
+ import { onMount } from 'svelte';
4
+ export let value = false;
5
+ export let params: FieldProps;
6
+ export let disabled: boolean = false;
7
+ onMount(() => {
8
+ value = Boolean(params?.default) ?? 8.0;
9
+ });
10
+ </script>
11
+
12
+ <div class="grid max-w-md grid-cols-4 items-center justify-items-start gap-3">
13
+ <label class="text-sm font-medium" for={params.id}>{params?.title}</label>
14
+ <input bind:checked={value} disabled={disabled} type="checkbox" id={params.id} class="cursor-pointer" />
15
+ </div>
demo/frontend/src/lib/components/ImagePlayer.svelte ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { lcmLiveStatus, LCMLiveStatus, streamId } from '$lib/lcmLive';
3
+ import { getPipelineValues } from '$lib/store';
4
+
5
+ import Button from '$lib/components/Button.svelte';
6
+ import Floppy from '$lib/icons/floppy.svelte';
7
+ import { snapImage } from '$lib/utils';
8
+
9
+ $: isLCMRunning = $lcmLiveStatus !== LCMLiveStatus.DISCONNECTED;
10
+ $: console.log('isLCMRunning', isLCMRunning);
11
+ let imageEl: HTMLImageElement;
12
+ async function takeSnapshot() {
13
+ if (isLCMRunning) {
14
+ await snapImage(imageEl, {
15
+ prompt: getPipelineValues()?.prompt,
16
+ negative_prompt: getPipelineValues()?.negative_prompt,
17
+ seed: getPipelineValues()?.seed,
18
+ guidance_scale: getPipelineValues()?.guidance_scale
19
+ });
20
+ }
21
+ }
22
+ </script>
23
+
24
+ <div
25
+ class="relative mx-auto aspect-square max-w-lg self-center overflow-hidden rounded-lg border border-slate-300"
26
+ >
27
+ <!-- svelte-ignore a11y-missing-attribute -->
28
+ {#if isLCMRunning && $streamId}
29
+ <img
30
+ bind:this={imageEl}
31
+ class="aspect-square w-full rounded-lg"
32
+ src={'/api/stream/' + $streamId}
33
+ />
34
+ <div class="absolute bottom-1 right-1">
35
+ <Button
36
+ on:click={takeSnapshot}
37
+ disabled={!isLCMRunning}
38
+ title={'Take Snapshot'}
39
+ classList={'text-sm ml-auto text-white p-1 shadow-lg rounded-lg opacity-50'}
40
+ >
41
+ <Floppy classList={''} />
42
+ </Button>
43
+ </div>
44
+ {:else}
45
+ <img
46
+ class="aspect-square w-full rounded-lg"
47
+ src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
48
+ />
49
+ {/if}
50
+ </div>
demo/frontend/src/lib/components/InputRange.svelte ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { FieldProps } from '$lib/types';
3
+ import { onMount } from 'svelte';
4
+ export let value = 8.0;
5
+ export let params: FieldProps;
6
+ export let disabled: boolean = false;
7
+ onMount(() => {
8
+ value = Number(params?.default) ?? 8.0;
9
+ });
10
+ </script>
11
+
12
+ <div class="grid max-w-md grid-cols-4 items-center gap-3">
13
+ <label class="text-sm font-medium" for={params.id}>{params?.title}</label>
14
+ <input
15
+ class="col-span-2 h-2 w-full cursor-pointer appearance-none rounded-lg bg-gray-300 dark:bg-gray-500"
16
+ bind:value
17
+ type="range"
18
+ id={params.id}
19
+ name={params.id}
20
+ min={params?.min}
21
+ max={params?.max}
22
+ step={params?.step ?? 1}
23
+ />
24
+ <input
25
+ type="number"
26
+ step={params?.step ?? 1}
27
+ bind:value
28
+ disabled={disabled}
29
+ class="rounded-md border px-1 py-1 text-center text-xs font-bold dark:text-black"
30
+ />
31
+ </div>
32
+ <!--
33
+ <style lang="postcss" scoped>
34
+ input[type='range']::-webkit-slider-runnable-track {
35
+ @apply h-2 cursor-pointer rounded-lg dark:bg-gray-50;
36
+ }
37
+ input[type='range']::-webkit-slider-thumb {
38
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
39
+ }
40
+ input[type='range']::-moz-range-track {
41
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
42
+ }
43
+ input[type='range']::-moz-range-thumb {
44
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
45
+ }
46
+ input[type='range']::-ms-track {
47
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
48
+ }
49
+ input[type='range']::-ms-thumb {
50
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
51
+ }
52
+ </style> -->
demo/frontend/src/lib/components/MediaListSwitcher.svelte ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { mediaDevices, mediaStreamActions } from '$lib/mediaStream';
3
+ import Screen from '$lib/icons/screen.svelte';
4
+ import { onMount } from 'svelte';
5
+
6
+ let deviceId: string = '';
7
+ $: {
8
+ console.log($mediaDevices);
9
+ }
10
+ $: {
11
+ console.log(deviceId);
12
+ }
13
+ onMount(() => {
14
+ deviceId = $mediaDevices[0].deviceId;
15
+ });
16
+ </script>
17
+
18
+ <div class="flex items-center justify-center text-xs">
19
+ <button
20
+ title="Share your screen"
21
+ class="border-1 my-1 flex cursor-pointer gap-1 rounded-md border-gray-500 border-opacity-50 bg-slate-100 bg-opacity-30 p-1 font-medium text-white"
22
+ on:click={() => mediaStreamActions.startScreenCapture()}
23
+ >
24
+ <span>Share</span>
25
+
26
+ <Screen classList={''} />
27
+ </button>
28
+ {#if $mediaDevices}
29
+ <select
30
+ bind:value={deviceId}
31
+ on:change={() => mediaStreamActions.switchCamera(deviceId)}
32
+ id="devices-list"
33
+ class="border-1 block cursor-pointer rounded-md border-gray-800 border-opacity-50 bg-slate-100 bg-opacity-30 p-1 font-medium text-white"
34
+ >
35
+ {#each $mediaDevices as device, i}
36
+ <option value={device.deviceId}>{device.label}</option>
37
+ {/each}
38
+ </select>
39
+ {/if}
40
+ </div>
demo/frontend/src/lib/components/PipelineOptions.svelte ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { Fields } from '$lib/types';
3
+ import { FieldType } from '$lib/types';
4
+ import InputRange from './InputRange.svelte';
5
+ import SeedInput from './SeedInput.svelte';
6
+ import TextArea from './TextArea.svelte';
7
+ import Checkbox from './Checkbox.svelte';
8
+ import Selectlist from './Selectlist.svelte';
9
+ import { pipelineValues } from '$lib/store';
10
+
11
+ export let pipelineParams: Fields;
12
+ export let disabled: boolean = false;
13
+
14
+ $: advanceOptions = Object.values(pipelineParams)?.filter(
15
+ (e) => e?.hide == true && e?.disabled !== true
16
+ );
17
+ $: featuredOptions = Object.values(pipelineParams)?.filter((e) => e?.hide !== true);
18
+ </script>
19
+
20
+ <div class="flex flex-col gap-3">
21
+ <div class="grid grid-cols-1 items-center gap-3">
22
+ {#if featuredOptions}
23
+ {#each featuredOptions as params}
24
+ {#if params.field === FieldType.RANGE}
25
+ <InputRange {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></InputRange>
26
+ {:else if params.field === FieldType.SEED}
27
+ <SeedInput {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></SeedInput>
28
+ {:else if params.field === FieldType.TEXTAREA}
29
+ <TextArea {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></TextArea>
30
+ {:else if params.field === FieldType.CHECKBOX}
31
+ <Checkbox {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></Checkbox>
32
+ {:else if params.field === FieldType.SELECT}
33
+ <Selectlist {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></Selectlist>
34
+ {/if}
35
+ {/each}
36
+ {/if}
37
+ </div>
38
+ {#if advanceOptions && advanceOptions.length > 0}
39
+ <details>
40
+ <summary class="cursor-pointer font-medium">Advanced Options</summary>
41
+ <div
42
+ class="grid grid-cols-1 items-center gap-3 {Object.values(pipelineParams).length > 5
43
+ ? 'sm:grid-cols-2'
44
+ : ''}"
45
+ >
46
+ {#each advanceOptions as params}
47
+ {#if params.field === FieldType.RANGE}
48
+ <InputRange {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></InputRange>
49
+ {:else if params.field === FieldType.SEED}
50
+ <SeedInput {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></SeedInput>
51
+ {:else if params.field === FieldType.TEXTAREA}
52
+ <TextArea {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></TextArea>
53
+ {:else if params.field === FieldType.CHECKBOX}
54
+ <Checkbox {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></Checkbox>
55
+ {:else if params.field === FieldType.SELECT}
56
+ <Selectlist {params} bind:value={$pipelineValues[params.id]} disabled={disabled}></Selectlist>
57
+ {/if}
58
+ {/each}
59
+ </div>
60
+ </details>
61
+ {/if}
62
+ </div>
demo/frontend/src/lib/components/SeedInput.svelte ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { FieldProps } from '$lib/types';
3
+ import { onMount } from 'svelte';
4
+ import Button from './Button.svelte';
5
+ export let value = 299792458;
6
+ export let params: FieldProps;
7
+ export let disabled: boolean = false;
8
+
9
+ onMount(() => {
10
+ value = Number(params?.default ?? '');
11
+ });
12
+ function randomize() {
13
+ value = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
14
+ }
15
+ </script>
16
+
17
+ <div class="grid max-w-md grid-cols-4 items-center gap-3">
18
+ <label class="text-sm font-medium" for="seed">Seed</label>
19
+ <input
20
+ bind:value
21
+ type="number"
22
+ id="seed"
23
+ name="seed"
24
+ class="col-span-2 rounded-md border border-gray-700 p-2 text-right font-light dark:text-black"
25
+ disabled={disabled}
26
+ />
27
+ <Button on:click={randomize}>Rand</Button>
28
+ </div>
demo/frontend/src/lib/components/Selectlist.svelte ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { FieldProps } from '$lib/types';
3
+ import { onMount } from 'svelte';
4
+ export let value = '';
5
+ export let params: FieldProps;
6
+ export let disabled: boolean = false;
7
+ onMount(() => {
8
+ value = String(params?.default);
9
+ });
10
+ </script>
11
+
12
+ <div class="grid max-w-md grid-cols-4 items-center justify-items-start gap-3">
13
+ <label for="model-list" class="text-sm font-medium">{params?.title} </label>
14
+ {#if params?.values}
15
+ <select
16
+ bind:value
17
+ disabled={disabled}
18
+ id="model-list"
19
+ class="cursor-pointer rounded-md border-2 border-gray-500 p-2 font-light dark:text-black"
20
+ >
21
+ {#each params.values as model, i}
22
+ <option value={model} selected={i === 0}>{model}</option>
23
+ {/each}
24
+ </select>
25
+ {/if}
26
+ </div>
demo/frontend/src/lib/components/TextArea.svelte ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { FieldProps } from '$lib/types';
3
+ import { onMount } from 'svelte';
4
+ export let value: string;
5
+ export let params: FieldProps;
6
+ export let disabled: boolean = false;
7
+ onMount(() => {
8
+ value = String(params?.default ?? '');
9
+ });
10
+ </script>
11
+
12
+ <div class="">
13
+ <label class="text-sm font-medium" for={params?.title}>
14
+ {params?.title}
15
+ </label>
16
+ <div class="text-normal flex items-center rounded-md border border-gray-700">
17
+ <textarea
18
+ class="mx-1 w-full px-3 py-2 font-light outline-none dark:text-black"
19
+ title={params?.title}
20
+ placeholder="Add your prompt here..."
21
+ bind:value
22
+ disabled={disabled}
23
+ ></textarea>
24
+ </div>
25
+ </div>
demo/frontend/src/lib/components/VideoInput.svelte ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import 'rvfc-polyfill';
3
+
4
+ import { onDestroy, onMount } from 'svelte';
5
+ import {
6
+ mediaStreamStatus,
7
+ MediaStreamStatusEnum,
8
+ onFrameChangeStore,
9
+ mediaStream,
10
+ mediaDevices,
11
+ mediaStreamActions
12
+ } from '$lib/mediaStream';
13
+ import Button from './Button.svelte';
14
+ import MediaListSwitcher from './MediaListSwitcher.svelte';
15
+ export let width = 512;
16
+ export let height = 512;
17
+ const size = { width, height };
18
+
19
+ let videoEl: HTMLVideoElement;
20
+ let canvasEl: HTMLCanvasElement;
21
+ let ctx: CanvasRenderingContext2D;
22
+ let videoFrameCallbackId: number;
23
+
24
+ let isWebCamActive: boolean = false;
25
+
26
+ // adjust the throttle time to your needs
27
+ const THROTTLE = 1000 / 120;
28
+ let selectedDevice: string = '';
29
+ let videoIsReady = false;
30
+
31
+ onMount(() => {
32
+ ctx = canvasEl.getContext('2d') as CanvasRenderingContext2D;
33
+ canvasEl.width = size.width;
34
+ canvasEl.height = size.height;
35
+ });
36
+ $: {
37
+ console.log(selectedDevice);
38
+ }
39
+ onDestroy(() => {
40
+ if (videoFrameCallbackId) videoEl.cancelVideoFrameCallback(videoFrameCallbackId);
41
+ });
42
+
43
+ $: if (videoEl) {
44
+ videoEl.srcObject = $mediaStream;
45
+ }
46
+ let lastMillis = 0;
47
+ async function onFrameChange(now: DOMHighResTimeStamp, metadata: VideoFrameCallbackMetadata) {
48
+ if (now - lastMillis < THROTTLE) {
49
+ videoFrameCallbackId = videoEl.requestVideoFrameCallback(onFrameChange);
50
+ return;
51
+ }
52
+ const videoWidth = videoEl.videoWidth;
53
+ const videoHeight = videoEl.videoHeight;
54
+ let height0 = videoHeight;
55
+ let width0 = videoWidth;
56
+ let x0 = 0;
57
+ let y0 = 0;
58
+ if (videoWidth > videoHeight) {
59
+ width0 = videoHeight;
60
+ x0 = (videoWidth - videoHeight) / 2;
61
+ } else {
62
+ height0 = videoWidth;
63
+ y0 = (videoHeight - videoWidth) / 2;
64
+ }
65
+ ctx.drawImage(videoEl, x0, y0, width0, height0, 0, 0, size.width, size.height);
66
+ const blob = await new Promise<Blob>((resolve) => {
67
+ canvasEl.toBlob(
68
+ (blob) => {
69
+ resolve(blob as Blob);
70
+ },
71
+ 'image/jpeg',
72
+ 1
73
+ );
74
+ });
75
+ onFrameChangeStore.set({ blob });
76
+ videoFrameCallbackId = videoEl.requestVideoFrameCallback(onFrameChange);
77
+ }
78
+
79
+ $: if ($mediaStreamStatus == MediaStreamStatusEnum.CONNECTED && videoIsReady) {
80
+ videoFrameCallbackId = videoEl.requestVideoFrameCallback(onFrameChange);
81
+ }
82
+
83
+ $: isWebCamActive = $mediaStreamStatus === MediaStreamStatusEnum.CONNECTED;
84
+ async function startWebCam() {
85
+ await mediaStreamActions.enumerateDevices();
86
+ await mediaStreamActions.start();
87
+ }
88
+
89
+ function stopWebCam() {
90
+ mediaStreamActions.stop();
91
+ }
92
+
93
+ async function toggleWebCam() {
94
+ if (isWebCamActive) {
95
+ stopWebCam();
96
+ } else {
97
+ await startWebCam();
98
+ }
99
+ }
100
+ </script>
101
+
102
+ <div class="relative mx-auto max-w-lg overflow-hidden rounded-lg border border-slate-300">
103
+ <div class="relative z-10 aspect-square w-full object-cover">
104
+ {#if $mediaDevices.length > 0}
105
+ <div class="absolute bottom-0 right-0 z-10">
106
+ <MediaListSwitcher />
107
+ </div>
108
+ {/if}
109
+ <video
110
+ class="pointer-events-none aspect-square w-full object-cover"
111
+ bind:this={videoEl}
112
+ on:loadeddata={() => {
113
+ videoIsReady = true;
114
+ }}
115
+ playsinline
116
+ autoplay
117
+ muted
118
+ loop
119
+ ></video>
120
+ <canvas bind:this={canvasEl} class="absolute left-0 top-0 aspect-square w-full object-cover"
121
+ ></canvas>
122
+ </div>
123
+ <div class="absolute left-0 top-0 flex aspect-square w-full items-center justify-center">
124
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 448" class="w-40 p-5 opacity-20">
125
+ <path
126
+ fill="currentColor"
127
+ d="M224 256a128 128 0 1 0 0-256 128 128 0 1 0 0 256zm-45.7 48A178.3 178.3 0 0 0 0 482.3 29.7 29.7 0 0 0 29.7 512h388.6a29.7 29.7 0 0 0 29.7-29.7c0-98.5-79.8-178.3-178.3-178.3h-91.4z"
128
+ />
129
+ </svg>
130
+ </div>
131
+ </div>
132
+
133
+ <Button on:click={toggleWebCam}>
134
+ {#if isWebCamActive}
135
+ <span>Stop WebCam</span>
136
+ {:else}
137
+ <span>Start WebCam</span>
138
+ {/if}
139
+ </Button>
demo/frontend/src/lib/components/Warning.svelte ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let message: string = '';
3
+
4
+ let timeout = 0;
5
+ $: if (message !== '') {
6
+ console.log('message', message);
7
+ clearTimeout(timeout);
8
+ timeout = setTimeout(() => {
9
+ message = '';
10
+ }, 5000);
11
+ }
12
+ </script>
13
+
14
+ {#if message}
15
+ <div class="fixed right-0 top-0 m-4 cursor-pointer" on:click={() => (message = '')}>
16
+ <div class="rounded bg-red-800 p-4 text-white">
17
+ {message}
18
+ </div>
19
+ <div class="bar transition-all duration-500" style="width: 0;"></div>
20
+ </div>
21
+ {/if}
22
+
23
+ <style lang="postcss" scoped>
24
+ .button {
25
+ @apply rounded bg-gray-700 font-normal text-white hover:bg-gray-800 disabled:cursor-not-allowed disabled:bg-gray-300 dark:disabled:bg-gray-700 dark:disabled:text-black;
26
+ }
27
+ </style>
demo/frontend/src/lib/icons/floppy.svelte ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let classList: string;
3
+ </script>
4
+
5
+ <svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 448 512" class={classList}>
6
+ <path
7
+ fill="currentColor"
8
+ d="M48 96v320a16 16 0 0 0 16 16h320a16 16 0 0 0 16-16V170.5a16 16 0 0 0-4.7-11.3l33.9-33.9a64 64 0 0 1 18.7 45.3V416a64 64 0 0 1-64 64H64a64 64 0 0 1-64-64V96a64 64 0 0 1 64-64h245.5a64 64 0 0 1 45.3 18.7l74.5 74.5-33.9 33.9-74.6-74.4-.8-.8V184a24 24 0 0 1-24 24H104a24 24 0 0 1-24-24V80H64a16 16 0 0 0-16 16zm80-16v80h144V80H128zm32 240a64 64 0 1 1 128 0 64 64 0 1 1-128 0z"
9
+ />
10
+ </svg>
demo/frontend/src/lib/icons/screen.svelte ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let classList: string = '';
3
+ </script>
4
+
5
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -32 576 576" height="16px" class={classList}>
6
+ <path
7
+ fill="currentColor"
8
+ d="M64 0A64 64 0 0 0 0 64v288a64 64 0 0 0 64 64h176l-10.7 32H160a32 32 0 1 0 0 64h256a32 32 0 1 0 0-64h-69.3L336 416h176a64 64 0 0 0 64-64V64a64 64 0 0 0-64-64H64zm448 64v288H64V64h448z"
9
+ />
10
+ </svg>
demo/frontend/src/lib/icons/spinner.svelte ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let classList: string;
3
+ </script>
4
+
5
+ <svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 512 512" class={classList}>
6
+ <path
7
+ fill="currentColor"
8
+ d="M304 48a48 48 0 1 0 -96 0 48 48 0 1 0 96 0zm0 416a48 48 0 1 0 -96 0 48 48 0 1 0 96 0zM48 304a48 48 0 1 0 0-96 48 48 0 1 0 0 96zm464-48a48 48 0 1 0 -96 0 48 48 0 1 0 96 0zM142.9 437A48 48 0 1 0 75 369.1 48 48 0 1 0 142.9 437zm0-294.2A48 48 0 1 0 75 75a48 48 0 1 0 67.9 67.9zM369.1 437A48 48 0 1 0 437 369.1 48 48 0 1 0 369.1 437z"
9
+ />
10
+ </svg>
demo/frontend/src/lib/index.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ // place files you want to import through the `$lib` alias in this folder.
demo/frontend/src/lib/lcmLive.ts ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { writable } from 'svelte/store';
2
+
3
+
4
+ export enum LCMLiveStatus {
5
+ CONNECTED = "connected",
6
+ DISCONNECTED = "disconnected",
7
+ WAIT = "wait",
8
+ SEND_FRAME = "send_frame",
9
+ TIMEOUT = "timeout",
10
+ }
11
+
12
+ const initStatus: LCMLiveStatus = LCMLiveStatus.DISCONNECTED;
13
+
14
+ export const lcmLiveStatus = writable<LCMLiveStatus>(initStatus);
15
+ export const streamId = writable<string | null>(null);
16
+
17
+ let websocket: WebSocket | null = null;
18
+ export const lcmLiveActions = {
19
+ async start(getSreamdata: () => any[]) {
20
+ return new Promise((resolve, reject) => {
21
+
22
+ try {
23
+ const userId = crypto.randomUUID();
24
+ const websocketURL = `${window.location.protocol === "https:" ? "wss" : "ws"
25
+ }:${window.location.host}/api/ws/${userId}`;
26
+
27
+ websocket = new WebSocket(websocketURL);
28
+ websocket.onopen = () => {
29
+ console.log("Connected to websocket");
30
+ };
31
+ websocket.onclose = () => {
32
+ lcmLiveStatus.set(LCMLiveStatus.DISCONNECTED);
33
+ console.log("Disconnected from websocket");
34
+ };
35
+ websocket.onerror = (err) => {
36
+ console.error(err);
37
+ };
38
+ websocket.onmessage = (event) => {
39
+ const data = JSON.parse(event.data);
40
+ switch (data.status) {
41
+ case "connected":
42
+ lcmLiveStatus.set(LCMLiveStatus.CONNECTED);
43
+ streamId.set(userId);
44
+ resolve({ status: "connected", userId });
45
+ break;
46
+ case "send_frame":
47
+ lcmLiveStatus.set(LCMLiveStatus.SEND_FRAME);
48
+ const streamData = getSreamdata();
49
+ websocket?.send(JSON.stringify({ status: "next_frame" }));
50
+ for (const d of streamData) {
51
+ this.send(d);
52
+ }
53
+ break;
54
+ case "wait":
55
+ lcmLiveStatus.set(LCMLiveStatus.WAIT);
56
+ break;
57
+ case "timeout":
58
+ console.log("timeout");
59
+ lcmLiveStatus.set(LCMLiveStatus.TIMEOUT);
60
+ streamId.set(null);
61
+ reject(new Error("timeout"));
62
+ break;
63
+ case "error":
64
+ console.log(data.message);
65
+ lcmLiveStatus.set(LCMLiveStatus.DISCONNECTED);
66
+ streamId.set(null);
67
+ reject(new Error(data.message));
68
+ break;
69
+ }
70
+ };
71
+
72
+ } catch (err) {
73
+ console.error(err);
74
+ lcmLiveStatus.set(LCMLiveStatus.DISCONNECTED);
75
+ streamId.set(null);
76
+ reject(err);
77
+ }
78
+ });
79
+ },
80
+ send(data: Blob | { [key: string]: any }) {
81
+ if (websocket && websocket.readyState === WebSocket.OPEN) {
82
+ if (data instanceof Blob) {
83
+ websocket.send(data);
84
+ } else {
85
+ websocket.send(JSON.stringify(data));
86
+ }
87
+ } else {
88
+ console.log("WebSocket not connected");
89
+ }
90
+ },
91
+ async stop() {
92
+ lcmLiveStatus.set(LCMLiveStatus.DISCONNECTED);
93
+ if (websocket) {
94
+ websocket.close();
95
+ }
96
+ websocket = null;
97
+ streamId.set(null);
98
+ },
99
+ };
demo/frontend/src/lib/mediaStream.ts ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { writable, type Writable, get } from 'svelte/store';
2
+
3
+ export enum MediaStreamStatusEnum {
4
+ INIT = "init",
5
+ CONNECTED = "connected",
6
+ DISCONNECTED = "disconnected",
7
+ }
8
+ export const onFrameChangeStore: Writable<{ blob: Blob }> = writable({ blob: new Blob() });
9
+
10
+ export const mediaDevices = writable<MediaDeviceInfo[]>([]);
11
+ export const mediaStreamStatus = writable(MediaStreamStatusEnum.INIT);
12
+ export const mediaStream = writable<MediaStream | null>(null);
13
+
14
+ export const mediaStreamActions = {
15
+ async enumerateDevices() {
16
+ // console.log("Enumerating devices");
17
+ await navigator.mediaDevices.enumerateDevices()
18
+ .then(devices => {
19
+ const cameras = devices.filter(device => device.kind === 'videoinput');
20
+ mediaDevices.set(cameras);
21
+ })
22
+ .catch(err => {
23
+ console.error(err);
24
+ });
25
+ },
26
+ async start(mediaDevicedID?: string) {
27
+ const constraints = {
28
+ audio: false,
29
+ video: {
30
+ width: 1024, height: 1024, deviceId: mediaDevicedID
31
+ }
32
+ };
33
+
34
+ await navigator.mediaDevices
35
+ .getUserMedia(constraints)
36
+ .then((stream) => {
37
+ mediaStreamStatus.set(MediaStreamStatusEnum.CONNECTED);
38
+ mediaStream.set(stream);
39
+ })
40
+ .catch((err) => {
41
+ console.error(`${err.name}: ${err.message}`);
42
+ mediaStreamStatus.set(MediaStreamStatusEnum.DISCONNECTED);
43
+ mediaStream.set(null);
44
+ });
45
+ },
46
+ async startScreenCapture() {
47
+ const displayMediaOptions = {
48
+ video: {
49
+ displaySurface: "window",
50
+ },
51
+ audio: false,
52
+ surfaceSwitching: "include"
53
+ };
54
+
55
+
56
+ let captureStream = null;
57
+
58
+ try {
59
+ captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
60
+ const videoTrack = captureStream.getVideoTracks()[0];
61
+
62
+ console.log("Track settings:");
63
+ console.log(JSON.stringify(videoTrack.getSettings(), null, 2));
64
+ console.log("Track constraints:");
65
+ console.log(JSON.stringify(videoTrack.getConstraints(), null, 2));
66
+ mediaStreamStatus.set(MediaStreamStatusEnum.CONNECTED);
67
+ mediaStream.set(captureStream)
68
+ } catch (err) {
69
+ console.error(err);
70
+ }
71
+
72
+ },
73
+ async switchCamera(mediaDevicedID: string) {
74
+ if (get(mediaStreamStatus) !== MediaStreamStatusEnum.CONNECTED) {
75
+ return;
76
+ }
77
+ const constraints = {
78
+ audio: false,
79
+ video: { width: 1024, height: 1024, deviceId: mediaDevicedID }
80
+ };
81
+ await navigator.mediaDevices
82
+ .getUserMedia(constraints)
83
+ .then((stream) => {
84
+ mediaStreamStatus.set(MediaStreamStatusEnum.CONNECTED);
85
+ mediaStream.set(stream)
86
+ })
87
+ .catch((err) => {
88
+ console.error(`${err.name}: ${err.message}`);
89
+ });
90
+ },
91
+ async stop() {
92
+ navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
93
+ stream.getTracks().forEach((track) => track.stop());
94
+ });
95
+ mediaStreamStatus.set(MediaStreamStatusEnum.DISCONNECTED);
96
+ mediaStream.set(null);
97
+ },
98
+ };
demo/frontend/src/lib/store.ts ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { derived, writable, get, type Writable, type Readable } from 'svelte/store';
3
+
4
+ export const pipelineValues: Writable<Record<string, any>> = writable({});
5
+ export const deboucedPipelineValues: Readable<Record<string, any>>
6
+ = derived(pipelineValues, ($pipelineValues, set) => {
7
+ const debounced = setTimeout(() => {
8
+ set($pipelineValues);
9
+ }, 100);
10
+ return () => clearTimeout(debounced);
11
+ });
12
+
13
+
14
+
15
+ export const getPipelineValues = () => get(pipelineValues);
demo/frontend/src/lib/types.ts ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const enum FieldType {
2
+ RANGE = "range",
3
+ SEED = "seed",
4
+ TEXTAREA = "textarea",
5
+ CHECKBOX = "checkbox",
6
+ SELECT = "select",
7
+ }
8
+ export const enum PipelineMode {
9
+ IMAGE = "image",
10
+ VIDEO = "video",
11
+ TEXT = "text",
12
+ }
13
+
14
+
15
+ export interface Fields {
16
+ [key: string]: FieldProps;
17
+ }
18
+
19
+ export interface FieldProps {
20
+ default: number | string;
21
+ max?: number;
22
+ min?: number;
23
+ title: string;
24
+ field: FieldType;
25
+ step?: number;
26
+ disabled?: boolean;
27
+ hide?: boolean;
28
+ id: string;
29
+ values?: string[];
30
+ }
31
+ export interface PipelineInfo {
32
+ title: {
33
+ default: string;
34
+ }
35
+ name: string;
36
+ description: string;
37
+ input_mode: {
38
+ default: PipelineMode;
39
+ }
40
+ }
demo/frontend/src/lib/utils.ts ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as piexif from "piexifjs";
2
+
3
+ interface IImageInfo {
4
+ prompt?: string;
5
+ negative_prompt?: string;
6
+ seed?: number;
7
+ guidance_scale?: number;
8
+ }
9
+
10
+ export function snapImage(imageEl: HTMLImageElement, info: IImageInfo) {
11
+ try {
12
+ const zeroth: { [key: string]: any } = {};
13
+ const exif: { [key: string]: any } = {};
14
+ const gps: { [key: string]: any } = {};
15
+ zeroth[piexif.ImageIFD.Make] = "LCM Image-to-Image ControNet";
16
+ zeroth[piexif.ImageIFD.ImageDescription] = `prompt: ${info?.prompt} | negative_prompt: ${info?.negative_prompt} | seed: ${info?.seed} | guidance_scale: ${info?.guidance_scale}`;
17
+ zeroth[piexif.ImageIFD.Software] = "https://github.com/radames/Real-Time-Latent-Consistency-Model";
18
+ exif[piexif.ExifIFD.DateTimeOriginal] = new Date().toISOString();
19
+
20
+ const exifObj = { "0th": zeroth, "Exif": exif, "GPS": gps };
21
+ const exifBytes = piexif.dump(exifObj);
22
+
23
+ const canvas = document.createElement("canvas");
24
+ canvas.width = imageEl.naturalWidth;
25
+ canvas.height = imageEl.naturalHeight;
26
+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
27
+ ctx.drawImage(imageEl, 0, 0);
28
+ const dataURL = canvas.toDataURL("image/jpeg");
29
+ const withExif = piexif.insert(exifBytes, dataURL);
30
+
31
+ const a = document.createElement("a");
32
+ a.href = withExif;
33
+ a.download = `lcm_txt_2_img${Date.now()}.png`;
34
+ a.click();
35
+ } catch (err) {
36
+ console.log(err);
37
+ }
38
+ }
demo/frontend/src/routes/+layout.svelte ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ <script>
2
+ import '../app.css';
3
+ </script>
4
+
5
+ <slot />
demo/frontend/src/routes/+page.svelte ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import Button from '$lib/components/Button.svelte';
3
+ import ImagePlayer from '$lib/components/ImagePlayer.svelte';
4
+ import PipelineOptions from '$lib/components/PipelineOptions.svelte';
5
+ import VideoInput from '$lib/components/VideoInput.svelte';
6
+ import Warning from '$lib/components/Warning.svelte';
7
+ import Spinner from '$lib/icons/spinner.svelte';
8
+ import { lcmLiveActions, lcmLiveStatus, LCMLiveStatus } from '$lib/lcmLive';
9
+ import { mediaStreamActions, mediaStreamStatus, MediaStreamStatusEnum, onFrameChangeStore } from '$lib/mediaStream';
10
+ import { deboucedPipelineValues, getPipelineValues } from '$lib/store';
11
+ import type { Fields, PipelineInfo } from '$lib/types';
12
+ import { PipelineMode } from '$lib/types';
13
+ import { onMount } from 'svelte';
14
+
15
+ let pipelineParams: Fields;
16
+ let pipelineInfo: PipelineInfo;
17
+ let pageContent: string;
18
+ let isImageMode: boolean = false;
19
+ let maxQueueSize: number = 0;
20
+ let currentQueueSize: number = 0;
21
+ let queueCheckerRunning: boolean = false;
22
+ let warningMessage: string = '';
23
+ onMount(() => {
24
+ getSettings();
25
+ });
26
+
27
+ async function getSettings() {
28
+ const settings = await fetch('/api/settings').then((r) => r.json());
29
+ pipelineParams = settings.input_params.properties;
30
+ pipelineInfo = settings.info.properties;
31
+ isImageMode = pipelineInfo.input_mode.default === PipelineMode.IMAGE;
32
+ maxQueueSize = settings.max_queue_size;
33
+ pageContent = settings.page_content;
34
+ console.log(pipelineParams);
35
+ toggleQueueChecker(true);
36
+ }
37
+ function toggleQueueChecker(start: boolean) {
38
+ queueCheckerRunning = start && maxQueueSize > 0;
39
+ if (start) {
40
+ getQueueSize();
41
+ }
42
+ }
43
+ async function getQueueSize() {
44
+ if (!queueCheckerRunning) {
45
+ return;
46
+ }
47
+ const data = await fetch('/api/queue').then((r) => r.json());
48
+ currentQueueSize = data.queue_size;
49
+ setTimeout(getQueueSize, 10000);
50
+ }
51
+
52
+ function getSreamdata() {
53
+ if (isImageMode) {
54
+ return [getPipelineValues(), $onFrameChangeStore?.blob];
55
+ } else {
56
+ return [$deboucedPipelineValues];
57
+ }
58
+ }
59
+
60
+ $: isLCMRunning = $lcmLiveStatus !== LCMLiveStatus.DISCONNECTED;
61
+ $: if ($lcmLiveStatus === LCMLiveStatus.TIMEOUT) {
62
+ warningMessage = 'Session timed out. Please try again.';
63
+ }
64
+ let disabled = false;
65
+ async function toggleLcmLive() {
66
+ try {
67
+ if (!isLCMRunning) {
68
+ if (isImageMode) {
69
+ if ($mediaStreamStatus === MediaStreamStatusEnum.DISCONNECTED) {
70
+ warningMessage = 'Please allow camera access.';
71
+ return
72
+ }
73
+ // await mediaStreamActions.enumerateDevices();
74
+ // await mediaStreamActions.start();
75
+ }
76
+ disabled = true;
77
+ await lcmLiveActions.start(getSreamdata);
78
+ disabled = false;
79
+ toggleQueueChecker(false);
80
+ } else {
81
+ // if (isImageMode) {
82
+ // mediaStreamActions.stop();
83
+ // }
84
+ lcmLiveActions.stop();
85
+ mediaStreamActions.stop()
86
+ toggleQueueChecker(true);
87
+ }
88
+ } catch (e) {
89
+ warningMessage = e instanceof Error ? e.message : '';
90
+ console.error(warningMessage)
91
+ disabled = false;
92
+ toggleQueueChecker(true);
93
+ }
94
+ }
95
+ </script>
96
+
97
+ <svelte:head>
98
+ <script
99
+ src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.3.9/iframeResizer.contentWindow.min.js"
100
+ ></script>
101
+ </svelte:head>
102
+
103
+ {@debug isImageMode, pipelineParams}
104
+
105
+ <main class="container mx-auto flex max-w-5xl flex-col gap-3 px-4 py-4">
106
+ <Warning bind:message={warningMessage}></Warning>
107
+ <article class="text-center">
108
+ {#if pageContent}
109
+ {@html pageContent}
110
+ {/if}
111
+ {#if maxQueueSize > 0}
112
+ <p class="text-sm">
113
+ There are <span id="queue_size" class="font-bold">{currentQueueSize}</span>
114
+ user(s) sharing the same GPU, affecting real-time performance. Maximum queue size is {maxQueueSize}.
115
+ <a
116
+ href="https://huggingface.co/spaces/radames/Real-Time-Latent-Consistency-Model?duplicate=true"
117
+ target="_blank"
118
+ class="text-blue-500 underline hover:no-underline">Duplicate</a
119
+ > and run it on your own GPU.
120
+ </p>
121
+ {/if}
122
+ </article>
123
+ {#if pipelineParams}
124
+ <article class="my-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
125
+ {#if isImageMode}
126
+ <div class="sm:col-start-1">
127
+ <VideoInput
128
+ width={Number(pipelineParams.width.default)}
129
+ height={Number(pipelineParams.height.default)}
130
+ ></VideoInput>
131
+ </div>
132
+ {/if}
133
+ <div class={isImageMode ? 'sm:col-start-2' : 'col-span-2'}>
134
+ <ImagePlayer />
135
+ </div>
136
+ <div class="sm:col-span-2">
137
+ <Button on:click={toggleLcmLive} {disabled} classList={'text-lg my-1 p-2'}>
138
+ {#if isLCMRunning}
139
+ Stop
140
+ {:else}
141
+ Start
142
+ {/if}
143
+ </Button>
144
+ <PipelineOptions {pipelineParams} disabled={isLCMRunning}></PipelineOptions>
145
+ </div>
146
+ </article>
147
+ {:else}
148
+ <!-- loading -->
149
+ <div class="flex items-center justify-center gap-3 py-48 text-2xl">
150
+ <Spinner classList={'animate-spin opacity-50'}></Spinner>
151
+ <p>Loading...</p>
152
+ </div>
153
+ {/if}
154
+ </main>
155
+
156
+ <style lang="postcss">
157
+ :global(html) {
158
+ @apply text-black dark:bg-gray-900 dark:text-white;
159
+ }
160
+ </style>
demo/frontend/src/routes/+page.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ export const prerender = true
demo/frontend/static/favicon.png ADDED
demo/frontend/svelte.config.js ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import adapter from '@sveltejs/adapter-static';
2
+ import { vitePreprocess } from '@sveltejs/kit/vite';
3
+ /** @type {import('@sveltejs/kit').Config} */
4
+ const config = {
5
+ preprocess: vitePreprocess({ postcss: true }),
6
+ kit: {
7
+ adapter: adapter({
8
+ pages: 'public',
9
+ assets: 'public',
10
+ fallback: undefined,
11
+ precompress: false,
12
+ strict: true
13
+ })
14
+ }
15
+ };
16
+
17
+ export default config;
demo/frontend/tailwind.config.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ /** @type {import('tailwindcss').Config} */
2
+ export default {
3
+ content: ['./src/**/*.{html,js,svelte,ts}', '../**/*.py'],
4
+ theme: {
5
+ extend: {}
6
+ },
7
+ plugins: []
8
+ };
demo/frontend/tsconfig.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "extends": "./.svelte-kit/tsconfig.json",
3
+ "compilerOptions": {
4
+ "allowJs": true,
5
+ "checkJs": true,
6
+ "esModuleInterop": true,
7
+ "forceConsistentCasingInFileNames": true,
8
+ "resolveJsonModule": true,
9
+ "skipLibCheck": true,
10
+ "sourceMap": true,
11
+ "strict": true
12
+ }
13
+ // Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
14
+ //
15
+ // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
16
+ // from the referenced tsconfig.json - TypeScript does not merge them in
17
+ }