FagerholmEmil commited on
Commit
5ea361f
·
1 Parent(s): bf075d7

Update README with comprehensive documentation for Real-Time Latent Consistency Model

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +4 -0
  2. Dockerfile +48 -0
  3. LICENSE +201 -0
  4. README.md +188 -5
  5. build-run.sh +20 -0
  6. frontend/.eslintignore +13 -0
  7. frontend/.eslintrc.cjs +30 -0
  8. frontend/.gitignore +11 -0
  9. frontend/.npmrc +1 -0
  10. frontend/.nvmrc +1 -0
  11. frontend/.prettierignore +13 -0
  12. frontend/.prettierrc +19 -0
  13. frontend/README.md +38 -0
  14. frontend/package-lock.json +0 -0
  15. frontend/package.json +43 -0
  16. frontend/postcss.config.js +6 -0
  17. frontend/src/app.css +3 -0
  18. frontend/src/app.d.ts +12 -0
  19. frontend/src/app.html +12 -0
  20. frontend/src/lib/components/AspectRatioSelect.svelte +27 -0
  21. frontend/src/lib/components/Button.svelte +15 -0
  22. frontend/src/lib/components/Checkbox.svelte +14 -0
  23. frontend/src/lib/components/ImagePlayer.svelte +74 -0
  24. frontend/src/lib/components/InputRange.svelte +50 -0
  25. frontend/src/lib/components/MediaListSwitcher.svelte +47 -0
  26. frontend/src/lib/components/PipelineOptions.svelte +60 -0
  27. frontend/src/lib/components/SeedInput.svelte +26 -0
  28. frontend/src/lib/components/Selectlist.svelte +24 -0
  29. frontend/src/lib/components/TextArea.svelte +23 -0
  30. frontend/src/lib/components/VideoInput.svelte +127 -0
  31. frontend/src/lib/components/Warning.svelte +27 -0
  32. frontend/src/lib/icons/aspect.svelte +10 -0
  33. frontend/src/lib/icons/expand.svelte +10 -0
  34. frontend/src/lib/icons/floppy.svelte +10 -0
  35. frontend/src/lib/icons/screen.svelte +10 -0
  36. frontend/src/lib/icons/spinner.svelte +10 -0
  37. frontend/src/lib/index.ts +1 -0
  38. frontend/src/lib/lcmLive.ts +97 -0
  39. frontend/src/lib/mediaStream.ts +118 -0
  40. frontend/src/lib/store.ts +14 -0
  41. frontend/src/lib/types.ts +39 -0
  42. frontend/src/lib/utils.ts +98 -0
  43. frontend/src/routes/+layout.svelte +5 -0
  44. frontend/src/routes/+page.svelte +152 -0
  45. frontend/src/routes/+page.ts +1 -0
  46. frontend/static/favicon.png +0 -0
  47. frontend/svelte.config.js +18 -0
  48. frontend/tailwind.config.js +8 -0
  49. frontend/tsconfig.json +17 -0
  50. frontend/vite.config.ts +15 -0
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ venv/
3
+ public/
4
+ *.pem
Dockerfile ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ RUN pip3 install --no-cache-dir --upgrade --pre -r /code/requirements.txt
40
+
41
+ # Set the working directory to the user's home directory
42
+ WORKDIR $HOME/app
43
+
44
+ # Copy the current directory contents into the container at $HOME/app setting the owner to the user
45
+ COPY --chown=user . $HOME/app
46
+
47
+ ENV LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc.so.4
48
+ CMD ["./build-run.sh"]
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,10 +1,193 @@
1
  ---
2
- title: Real Time Model
3
- emoji: 🐢
4
- colorFrom: green
5
- colorTo: yellow
6
  sdk: docker
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Real-Time Latent Consistency Model Image-to-Image ControlNet
3
+ emoji: 🖼️🖼️
4
+ colorFrom: gray
5
+ colorTo: indigo
6
  sdk: docker
7
  pinned: false
8
+ suggested_hardware: a10g-small
9
+ disable_embedding: true
10
  ---
11
 
12
+ # Real-Time Latent Consistency Model
13
+
14
+ This demo showcases [Latent Consistency Model (LCM)](https://latent-consistency-models.github.io/) using [Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/lcm) with a MJPEG stream server. You can read more about LCM + LoRAs with diffusers [here](https://huggingface.co/blog/lcm_lora).
15
+
16
+ You need a webcam to run this demo. 🤗
17
+
18
+ See a collecting with live demos [here](https://huggingface.co/collections/latent-consistency/latent-consistency-model-demos-654e90c52adb0688a0acbe6f)
19
+
20
+ ## Running Locally
21
+
22
+ You need CUDA and Python 3.10, Node > 19, Mac with an M1/M2/M3 chip or Intel Arc GPU
23
+
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ python -m venv venv
29
+ source venv/bin/activate
30
+ pip3 install -r server/requirements.txt
31
+ cd frontend && npm install && npm run build && cd ..
32
+ python server/main.py --reload --pipeline img2imgSDTurbo
33
+ ```
34
+
35
+ Don't forget to fuild the frontend!!!
36
+
37
+ ```bash
38
+ cd frontend && npm install && npm run build && cd ..
39
+ ```
40
+
41
+ # Pipelines
42
+ You can build your own pipeline following examples here [here](pipelines),
43
+
44
+
45
+ # LCM
46
+ ### Image to Image
47
+
48
+ ```bash
49
+ python server/main.py --reload --pipeline img2img
50
+ ```
51
+
52
+ # LCM
53
+ ### Text to Image
54
+
55
+ ```bash
56
+ python server/main.py --reload --pipeline txt2img
57
+ ```
58
+
59
+ ### Image to Image ControlNet Canny
60
+
61
+ ```bash
62
+ python server/main.py --reload --pipeline controlnet
63
+ ```
64
+
65
+
66
+ # LCM + LoRa
67
+
68
+ Using LCM-LoRA, giving it the super power of doing inference in as little as 4 steps. [Learn more here](https://huggingface.co/blog/lcm_lora) or [technical report](https://huggingface.co/papers/2311.05556)
69
+
70
+
71
+ ### Image to Image ControlNet Canny LoRa
72
+
73
+ ```bash
74
+ python server/main.py --reload --pipeline controlnetLoraSD15
75
+ ```
76
+ or SDXL, note that SDXL is slower than SD15 since the inference runs on 1024x1024 images
77
+
78
+ ```bash
79
+ python server/main.py --reload --pipeline controlnetLoraSDXL
80
+ ```
81
+
82
+ ### Text to Image
83
+
84
+ ```bash
85
+ python server/main.py --reload --pipeline txt2imgLora
86
+ ```
87
+
88
+ ```bash
89
+ python server/main.py --reload --pipeline txt2imgLoraSDXL
90
+ ```
91
+ # Available Pipelines
92
+
93
+ #### [LCM](https://huggingface.co/SimianLuo/LCM_Dreamshaper_v7)
94
+
95
+ `img2img`
96
+ `txt2img`
97
+ `controlnet`
98
+ `txt2imgLora`
99
+ `controlnetLoraSD15`
100
+
101
+ #### [SD15](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
102
+ `controlnetLoraSDXL`
103
+ `txt2imgLoraSDXL`
104
+
105
+ #### [SDXL Turbo](https://huggingface.co/stabilityai/sd-xl-turbo)
106
+
107
+ `img2imgSDXLTurbo`
108
+ `controlnetSDXLTurbo`
109
+
110
+
111
+ #### [SDTurbo](https://huggingface.co/stabilityai/sd-turbo)
112
+ `img2imgSDTurbo`
113
+ `controlnetSDTurbo`
114
+
115
+ #### [Segmind-Vega](https://huggingface.co/segmind/Segmind-Vega)
116
+ `controlnetSegmindVegaRT`
117
+ `img2imgSegmindVegaRT`
118
+
119
+
120
+ ### Setting environment variables
121
+
122
+
123
+ * `--host`: Host address (default: 0.0.0.0)
124
+ * `--port`: Port number (default: 7860)
125
+ * `--reload`: Reload code on change
126
+ * `--max-queue-size`: Maximum queue size (optional)
127
+ * `--timeout`: Timeout period (optional)
128
+ * `--safety-checker`: Enable Safety Checker (optional)
129
+ * `--torch-compile`: Use Torch Compile
130
+ * `--use-taesd` / `--no-taesd`: Use Tiny Autoencoder
131
+ * `--pipeline`: Pipeline to use (default: "txt2img")
132
+ * `--ssl-certfile`: SSL Certificate File (optional)
133
+ * `--ssl-keyfile`: SSL Key File (optional)
134
+ * `--debug`: Print Inference time
135
+ * `--compel`: Compel option
136
+ * `--sfast`: Enable Stable Fast
137
+ * `--onediff`: Enable OneDiff
138
+
139
+ If you run using `bash build-run.sh` you can set `PIPELINE` variables to choose the pipeline you want to run
140
+
141
+ ```bash
142
+ PIPELINE=txt2imgLoraSDXL bash build-run.sh
143
+ ```
144
+
145
+ and setting environment variables
146
+
147
+ ```bash
148
+ TIMEOUT=120 SAFETY_CHECKER=True MAX_QUEUE_SIZE=4 python server/main.py --reload --pipeline txt2imgLoraSDXL
149
+ ```
150
+
151
+ If you're running locally and want to test it on Mobile Safari, the webserver needs to be served over HTTPS, or follow this instruction on my [comment](https://github.com/radames/Real-Time-Latent-Consistency-Model/issues/17#issuecomment-1811957196)
152
+
153
+ ```bash
154
+ openssl req -newkey rsa:4096 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem
155
+ python server/main.py --reload --ssl-certfile=certificate.pem --ssl-keyfile=key.pem
156
+ ```
157
+
158
+ ## Docker
159
+
160
+ You need NVIDIA Container Toolkit for Docker, defaults to `controlnet``
161
+
162
+ ```bash
163
+ docker build -t lcm-live .
164
+ docker run -ti -p 7860:7860 --gpus all lcm-live
165
+ ```
166
+
167
+ reuse models data from host to avoid downloading them again, you can change `~/.cache/huggingface` to any other directory, but if you use hugingface-cli locally, you can share the same cache
168
+
169
+ ```bash
170
+ docker run -ti -p 7860:7860 -e HF_HOME=/data -v ~/.cache/huggingface:/data --gpus all lcm-live
171
+ ```
172
+
173
+
174
+ or with environment variables
175
+
176
+ ```bash
177
+ docker run -ti -e PIPELINE=txt2imgLoraSDXL -p 7860:7860 --gpus all lcm-live
178
+ ```
179
+
180
+
181
+ # Demo on Hugging Face
182
+
183
+
184
+ * [radames/Real-Time-Latent-Consistency-Model](https://huggingface.co/spaces/radames/Real-Time-Latent-Consistency-Model)
185
+ * [radames/Real-Time-SD-Turbo](https://huggingface.co/spaces/radames/Real-Time-SD-Turbo)
186
+ * [latent-consistency/Real-Time-LCM-ControlNet-Lora-SD1.5](https://huggingface.co/spaces/latent-consistency/Real-Time-LCM-ControlNet-Lora-SD1.5)
187
+ * [latent-consistency/Real-Time-LCM-Text-to-Image-Lora-SD1.5](https://huggingface.co/spaces/latent-consistency/Real-Time-LCM-Text-to-Image-Lora-SD1.5)
188
+ * [radames/Real-Time-Latent-Consistency-Model-Text-To-Image](https://huggingface.co/spaces/radames/Real-Time-Latent-Consistency-Model-Text-To-Image)
189
+
190
+
191
+
192
+
193
+ https://github.com/radames/Real-Time-Latent-Consistency-Model/assets/102277/c4003ac5-e7ff-44c0-97d3-464bb659de70
build-run.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd frontend
3
+ npm install
4
+ npm run build
5
+ if [ $? -eq 0 ]; then
6
+ echo -e "\033[1;32m\nfrontend build success \033[0m"
7
+ else
8
+ echo -e "\033[1;31m\nfrontend build failed\n\033[0m" >&2 exit 1
9
+ fi
10
+ cd ../
11
+ #check if var PIPELINE is set otherwise get default
12
+ if [ -z ${PIPELINE+x} ]; then
13
+ PIPELINE="controlnet"
14
+ fi
15
+ if [ -z ${COMPILE+x} ]; then
16
+ COMPILE="--sfast"
17
+ fi
18
+ echo -e "\033[1;32m\npipeline: $PIPELINE \033[0m"
19
+ echo -e "\033[1;32m\ncompile: $COMPILE \033[0m"
20
+ python3 ./server/main.py --port 7860 --host 0.0.0.0 --pipeline $PIPELINE $COMPILE
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
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
+ };
frontend/.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
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-*
11
+ public
frontend/.npmrc ADDED
@@ -0,0 +1 @@
 
 
1
+ engine-strict=true
frontend/.nvmrc ADDED
@@ -0,0 +1 @@
 
 
1
+ v20.14.0
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
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
+ }
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.
frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
frontend/package.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": "^3.0.0",
16
+ "@sveltejs/adapter-static": "^3",
17
+ "@sveltejs/kit": "^2.0.0",
18
+ "@sveltejs/vite-plugin-svelte": "^3.1.1",
19
+ "@types/eslint": "^8.56.0",
20
+ "@typescript-eslint/eslint-plugin": "^7.12.0",
21
+ "@typescript-eslint/parser": "^7.12.0",
22
+ "autoprefixer": "^10.4.16",
23
+ "eslint": "^8.56.0",
24
+ "eslint-config-prettier": "^9.1.0",
25
+ "eslint-plugin-svelte": "^2.35.1",
26
+ "postcss": "^8.4.31",
27
+ "prettier": "^3.3.1",
28
+ "prettier-plugin-organize-imports": "^3.2.4",
29
+ "prettier-plugin-svelte": "^3.2.4",
30
+ "prettier-plugin-tailwindcss": "^0.6.1",
31
+ "svelte": "^4.2.18",
32
+ "svelte-check": "^3.8.0",
33
+ "tailwindcss": "^3.4.4",
34
+ "tslib": "^2.6.3",
35
+ "typescript": "^5.0.0",
36
+ "vite": "^5.0.3"
37
+ },
38
+ "type": "module",
39
+ "dependencies": {
40
+ "piexifjs": "^1.0.6",
41
+ "rvfc-polyfill": "^1.0.7"
42
+ }
43
+ }
frontend/postcss.config.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {}
5
+ }
6
+ };
frontend/src/app.css ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
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 {};
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>
frontend/src/lib/components/AspectRatioSelect.svelte ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher } from 'svelte';
3
+
4
+ let options: string[] = ['1:1', '16:9', '4:3', '3:2', '3:4', '9:16'];
5
+ export let aspectRatio: number = 1;
6
+ const dispatchEvent = createEventDispatcher();
7
+
8
+ function onChange(e: Event) {
9
+ const target = e.target as HTMLSelectElement;
10
+ const value = target.value;
11
+ const [width, height] = value.split(':').map((v) => parseInt(v));
12
+ aspectRatio = width / height;
13
+ dispatchEvent('change', aspectRatio);
14
+ }
15
+ </script>
16
+
17
+ <div class="relative">
18
+ <select
19
+ on:change={onChange}
20
+ title="Aspect Ratio"
21
+ 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"
22
+ >
23
+ {#each options as option, i}
24
+ <option value={option}>{option}</option>
25
+ {/each}
26
+ </select>
27
+ </div>
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>
frontend/src/lib/components/Checkbox.svelte ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ onMount(() => {
7
+ value = Boolean(params?.default) ?? 8.0;
8
+ });
9
+ </script>
10
+
11
+ <div class="grid max-w-md grid-cols-4 items-center justify-items-start gap-3">
12
+ <label class="text-sm font-medium" for={params.id}>{params?.title}</label>
13
+ <input bind:checked={value} type="checkbox" id={params.id} class="cursor-pointer" />
14
+ </div>
frontend/src/lib/components/ImagePlayer.svelte ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Expand from '$lib/icons/expand.svelte';
8
+ import { snapImage, expandWindow } from '$lib/utils';
9
+
10
+ $: isLCMRunning = $lcmLiveStatus !== LCMLiveStatus.DISCONNECTED;
11
+ $: console.log('isLCMRunning', isLCMRunning);
12
+ let imageEl: HTMLImageElement;
13
+ let expandedWindow: Window;
14
+ let isExpanded = false;
15
+ async function takeSnapshot() {
16
+ if (isLCMRunning) {
17
+ await snapImage(imageEl, {
18
+ prompt: getPipelineValues()?.prompt,
19
+ negative_prompt: getPipelineValues()?.negative_prompt,
20
+ seed: getPipelineValues()?.seed,
21
+ guidance_scale: getPipelineValues()?.guidance_scale
22
+ });
23
+ }
24
+ }
25
+ async function toggleFullscreen() {
26
+ if (isLCMRunning && !isExpanded) {
27
+ expandedWindow = expandWindow('/api/stream/' + $streamId);
28
+ expandedWindow.addEventListener('beforeunload', () => {
29
+ isExpanded = false;
30
+ });
31
+ isExpanded = true;
32
+ } else {
33
+ expandedWindow?.close();
34
+ isExpanded = false;
35
+ }
36
+ }
37
+ </script>
38
+
39
+ <div
40
+ class="relative mx-auto aspect-square max-w-lg self-center overflow-hidden rounded-lg border border-slate-300"
41
+ >
42
+ <!-- svelte-ignore a11y-missing-attribute -->
43
+ {#if isLCMRunning}
44
+ {#if !isExpanded}
45
+ <img
46
+ bind:this={imageEl}
47
+ class="aspect-square w-full rounded-lg"
48
+ src={'/api/stream/' + $streamId}
49
+ />
50
+ {/if}
51
+ <div class="absolute bottom-1 right-1">
52
+ <Button
53
+ on:click={toggleFullscreen}
54
+ title={'Expand Fullscreen'}
55
+ classList={'text-sm ml-auto text-white p-1 shadow-lg rounded-lg opacity-50'}
56
+ >
57
+ <Expand classList={''} />
58
+ </Button>
59
+ <Button
60
+ on:click={takeSnapshot}
61
+ disabled={!isLCMRunning}
62
+ title={'Take Snapshot'}
63
+ classList={'text-sm ml-auto text-white p-1 shadow-lg rounded-lg opacity-50'}
64
+ >
65
+ <Floppy classList={''} />
66
+ </Button>
67
+ </div>
68
+ {:else}
69
+ <img
70
+ class="aspect-square w-full rounded-lg"
71
+ src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
72
+ />
73
+ {/if}
74
+ </div>
frontend/src/lib/components/InputRange.svelte ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ onMount(() => {
7
+ value = Number(params?.default) ?? 8.0;
8
+ });
9
+ </script>
10
+
11
+ <div class="grid max-w-md grid-cols-4 items-center gap-3">
12
+ <label class="text-sm font-medium" for={params.id}>{params?.title}</label>
13
+ <input
14
+ class="col-span-2 h-2 w-full cursor-pointer appearance-none rounded-lg bg-gray-300 dark:bg-gray-500"
15
+ bind:value
16
+ type="range"
17
+ id={params.id}
18
+ name={params.id}
19
+ min={params?.min}
20
+ max={params?.max}
21
+ step={params?.step ?? 1}
22
+ />
23
+ <input
24
+ type="number"
25
+ step={params?.step ?? 1}
26
+ bind:value
27
+ class="rounded-md border px-1 py-1 text-center text-xs font-bold dark:text-black"
28
+ />
29
+ </div>
30
+ <!--
31
+ <style lang="postcss" scoped>
32
+ input[type='range']::-webkit-slider-runnable-track {
33
+ @apply h-2 cursor-pointer rounded-lg dark:bg-gray-50;
34
+ }
35
+ input[type='range']::-webkit-slider-thumb {
36
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
37
+ }
38
+ input[type='range']::-moz-range-track {
39
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
40
+ }
41
+ input[type='range']::-moz-range-thumb {
42
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
43
+ }
44
+ input[type='range']::-ms-track {
45
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
46
+ }
47
+ input[type='range']::-ms-thumb {
48
+ @apply cursor-pointer rounded-lg dark:bg-gray-50;
49
+ }
50
+ </style> -->
frontend/src/lib/components/MediaListSwitcher.svelte ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { mediaDevices, mediaStreamActions } from '$lib/mediaStream';
3
+ import Screen from '$lib/icons/screen.svelte';
4
+ import AspectRatioSelect from './AspectRatioSelect.svelte';
5
+ import { onMount } from 'svelte';
6
+
7
+ let deviceId: string = '';
8
+ let aspectRatio: number = 1;
9
+
10
+ onMount(() => {
11
+ deviceId = $mediaDevices[0].deviceId;
12
+ });
13
+ $: {
14
+ console.log(deviceId);
15
+ }
16
+ $: {
17
+ console.log(aspectRatio);
18
+ }
19
+ </script>
20
+
21
+ <div class="flex items-center justify-center text-xs backdrop-blur-sm backdrop-grayscale">
22
+ <AspectRatioSelect
23
+ bind:aspectRatio
24
+ on:change={() => mediaStreamActions.switchCamera(deviceId, aspectRatio)}
25
+ />
26
+ <button
27
+ title="Share your screen"
28
+ 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"
29
+ on:click={() => mediaStreamActions.startScreenCapture()}
30
+ >
31
+ <span>Share</span>
32
+
33
+ <Screen classList={''} />
34
+ </button>
35
+ {#if $mediaDevices}
36
+ <select
37
+ bind:value={deviceId}
38
+ on:change={() => mediaStreamActions.switchCamera(deviceId, aspectRatio)}
39
+ id="devices-list"
40
+ 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"
41
+ >
42
+ {#each $mediaDevices as device, i}
43
+ <option value={device.deviceId}>{device.label}</option>
44
+ {/each}
45
+ </select>
46
+ {/if}
47
+ </div>
frontend/src/lib/components/PipelineOptions.svelte ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
13
+ $: advanceOptions = Object.values(pipelineParams)?.filter((e) => e?.hide == true);
14
+ $: featuredOptions = Object.values(pipelineParams)?.filter((e) => e?.hide !== true);
15
+ </script>
16
+
17
+ <div class="flex flex-col gap-3">
18
+ <div class="grid grid-cols-1 items-center gap-3">
19
+ {#if featuredOptions}
20
+ {#each featuredOptions as params}
21
+ {#if params.field === FieldType.RANGE}
22
+ <InputRange {params} bind:value={$pipelineValues[params.id]}></InputRange>
23
+ {:else if params.field === FieldType.SEED}
24
+ <SeedInput {params} bind:value={$pipelineValues[params.id]}></SeedInput>
25
+ {:else if params.field === FieldType.TEXTAREA}
26
+ <TextArea {params} bind:value={$pipelineValues[params.id]}></TextArea>
27
+ {:else if params.field === FieldType.CHECKBOX}
28
+ <Checkbox {params} bind:value={$pipelineValues[params.id]}></Checkbox>
29
+ {:else if params.field === FieldType.SELECT}
30
+ <Selectlist {params} bind:value={$pipelineValues[params.id]}></Selectlist>
31
+ {/if}
32
+ {/each}
33
+ {/if}
34
+ </div>
35
+
36
+ <details>
37
+ <summary class="cursor-pointer font-medium">Advanced Options</summary>
38
+ <div
39
+ class="grid grid-cols-1 items-center gap-3 {Object.values(pipelineParams).length > 5
40
+ ? 'sm:grid-cols-2'
41
+ : ''}"
42
+ >
43
+ {#if advanceOptions}
44
+ {#each advanceOptions as params}
45
+ {#if params.field === FieldType.RANGE}
46
+ <InputRange {params} bind:value={$pipelineValues[params.id]}></InputRange>
47
+ {:else if params.field === FieldType.SEED}
48
+ <SeedInput {params} bind:value={$pipelineValues[params.id]}></SeedInput>
49
+ {:else if params.field === FieldType.TEXTAREA}
50
+ <TextArea {params} bind:value={$pipelineValues[params.id]}></TextArea>
51
+ {:else if params.field === FieldType.CHECKBOX}
52
+ <Checkbox {params} bind:value={$pipelineValues[params.id]}></Checkbox>
53
+ {:else if params.field === FieldType.SELECT}
54
+ <Selectlist {params} bind:value={$pipelineValues[params.id]}></Selectlist>
55
+ {/if}
56
+ {/each}
57
+ {/if}
58
+ </div>
59
+ </details>
60
+ </div>
frontend/src/lib/components/SeedInput.svelte ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ onMount(() => {
9
+ value = Number(params?.default ?? '');
10
+ });
11
+ function randomize() {
12
+ value = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
13
+ }
14
+ </script>
15
+
16
+ <div class="grid max-w-md grid-cols-4 items-center gap-3">
17
+ <label class="text-sm font-medium" for="seed">Seed</label>
18
+ <input
19
+ bind:value
20
+ type="number"
21
+ id="seed"
22
+ name="seed"
23
+ class="col-span-2 rounded-md border border-gray-700 p-2 text-right font-light dark:text-black"
24
+ />
25
+ <Button on:click={randomize}>Rand</Button>
26
+ </div>
frontend/src/lib/components/Selectlist.svelte ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ onMount(() => {
7
+ value = String(params?.default);
8
+ });
9
+ </script>
10
+
11
+ <div class="grid max-w-md grid-cols-4 items-center justify-items-start gap-3">
12
+ <label for="model-list" class="text-sm font-medium">{params?.title} </label>
13
+ {#if params?.values}
14
+ <select
15
+ bind:value
16
+ id="model-list"
17
+ class="cursor-pointer rounded-md border-2 border-gray-500 p-2 font-light dark:text-black"
18
+ >
19
+ {#each params.values as model, i}
20
+ <option value={model} selected={i === 0}>{model}</option>
21
+ {/each}
22
+ </select>
23
+ {/if}
24
+ </div>
frontend/src/lib/components/TextArea.svelte ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ onMount(() => {
7
+ value = String(params?.default ?? '');
8
+ });
9
+ </script>
10
+
11
+ <div class="">
12
+ <label class="text-sm font-medium" for={params?.title}>
13
+ {params?.title}
14
+ </label>
15
+ <div class="text-normal flex items-center rounded-md border border-gray-700">
16
+ <textarea
17
+ class="mx-1 w-full px-3 py-2 font-light outline-none dark:text-black"
18
+ title={params?.title}
19
+ placeholder="Add your prompt here..."
20
+ bind:value
21
+ ></textarea>
22
+ </div>
23
+ </div>
frontend/src/lib/components/VideoInput.svelte ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ } from '$lib/mediaStream';
12
+ import MediaListSwitcher from './MediaListSwitcher.svelte';
13
+ import Button from '$lib/components/Button.svelte';
14
+ import Expand from '$lib/icons/expand.svelte';
15
+
16
+ export let width = 512;
17
+ export let height = 512;
18
+ const size = { width, height };
19
+
20
+ let videoEl: HTMLVideoElement;
21
+ let canvasEl: HTMLCanvasElement;
22
+ let ctx: CanvasRenderingContext2D;
23
+ let videoFrameCallbackId: number;
24
+
25
+ // ajust the throttle time to your needs
26
+ const THROTTLE = 1000 / 120;
27
+ let selectedDevice: string = '';
28
+ let videoIsReady = false;
29
+
30
+ onMount(() => {
31
+ ctx = canvasEl.getContext('2d') as CanvasRenderingContext2D;
32
+ canvasEl.width = size.width;
33
+ canvasEl.height = size.height;
34
+ });
35
+ $: {
36
+ console.log(selectedDevice);
37
+ }
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
+ // scale down video to fit canvas, size.width, size.height
55
+ const scale = Math.min(size.width / videoWidth, size.height / videoHeight);
56
+ const width0 = videoWidth * scale;
57
+ const height0 = videoHeight * scale;
58
+ const x0 = (size.width - width0) / 2;
59
+ const y0 = (size.height - height0) / 2;
60
+ ctx.clearRect(0, 0, size.width, size.height);
61
+ ctx.drawImage(videoEl, x0, y0, width0, height0);
62
+
63
+ const blob = await new Promise<Blob>((resolve) => {
64
+ canvasEl.toBlob(
65
+ (blob) => {
66
+ resolve(blob as Blob);
67
+ },
68
+ 'image/jpeg',
69
+ 1
70
+ );
71
+ });
72
+ onFrameChangeStore.set({ blob });
73
+ videoFrameCallbackId = videoEl.requestVideoFrameCallback(onFrameChange);
74
+ }
75
+
76
+ $: if ($mediaStreamStatus == MediaStreamStatusEnum.CONNECTED && videoIsReady) {
77
+ videoFrameCallbackId = videoEl.requestVideoFrameCallback(onFrameChange);
78
+ }
79
+
80
+ function toggleFullscreen() {
81
+ if (videoIsReady) {
82
+ if (document.fullscreenElement) {
83
+ document.exitFullscreen();
84
+ } else {
85
+ videoEl.requestFullscreen();
86
+ }
87
+ }
88
+ }
89
+ </script>
90
+
91
+ <div class="relative mx-auto max-w-lg overflow-hidden rounded-lg border border-slate-300">
92
+ <div class="relative z-10 flex aspect-square w-full items-center justify-center object-cover">
93
+ {#if $mediaDevices.length > 0}
94
+ <div class="absolute bottom-0 right-0 z-10 flex bg-slate-400 bg-opacity-40">
95
+ <MediaListSwitcher />
96
+ <Button
97
+ on:click={toggleFullscreen}
98
+ title={'Expand Fullscreen'}
99
+ classList={'text-sm ml-auto text-white p-1 shadow-lg rounded-lg opacity-50'}
100
+ >
101
+ <Expand classList={''} />
102
+ </Button>
103
+ </div>
104
+ {/if}
105
+ <video
106
+ class="pointer-events-none aspect-square w-full justify-center object-contain"
107
+ bind:this={videoEl}
108
+ on:loadeddata={() => {
109
+ videoIsReady = true;
110
+ }}
111
+ playsinline
112
+ autoplay
113
+ muted
114
+ loop
115
+ ></video>
116
+ <canvas bind:this={canvasEl} class="absolute left-0 top-0 aspect-square w-full object-cover"
117
+ ></canvas>
118
+ </div>
119
+ <div class="absolute left-0 top-0 flex aspect-square w-full items-center justify-center">
120
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 448" class="w-40 p-5 opacity-20">
121
+ <path
122
+ fill="currentColor"
123
+ 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"
124
+ />
125
+ </svg>
126
+ </div>
127
+ </div>
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>
frontend/src/lib/icons/aspect.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 0 448 512" height="16px" class={classList}>
6
+ <path
7
+ fill="currentColor"
8
+ d="M32 32C14.3 32 0 46.3 0 64v96c0 17.7 14.3 32 32 32s32-14.3 32-32V96h64c17.7 0 32-14.3 32-32s-14.3-32-32-32H32zM64 352c0-17.7-14.3-32-32-32s-32 14.3-32 32v96c0 17.7 14.3 32 32 32h96c17.7 0 32-14.3 32-32s-14.3-32-32-32H64V352zM320 32c-17.7 0-32 14.3-32 32s14.3 32 32 32h64v64c0 17.7 14.3 32 32 32s32-14.3 32-32V64c0-17.7-14.3-32-32-32H320zM448 352c0-17.7-14.3-32-32-32s-32 14.3-32 32v64H320c-17.7 0-32 14.3-32 32s14.3 32 32 32h96c17.7 0 32-14.3 32-32V352z"
9
+ />
10
+ </svg>
frontend/src/lib/icons/expand.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 0 512 512" height="1em" class={classList}>
6
+ <path
7
+ fill="currentColor"
8
+ d="M.3 89.5C.1 91.6 0 93.8 0 96V224 416c0 35.3 28.7 64 64 64l384 0c35.3 0 64-28.7 64-64V224 96c0-35.3-28.7-64-64-64H64c-2.2 0-4.4 .1-6.5 .3c-9.2 .9-17.8 3.8-25.5 8.2C21.8 46.5 13.4 55.1 7.7 65.5c-3.9 7.3-6.5 15.4-7.4 24zM48 224H464l0 192c0 8.8-7.2 16-16 16L64 432c-8.8 0-16-7.2-16-16l0-192z"
9
+ />
10
+ </svg>
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>
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>
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>
frontend/src/lib/index.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ // place files you want to import through the `$lib` alias in this folder.
frontend/src/lib/lcmLive.ts ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { writable } from 'svelte/store';
2
+
3
+ export enum LCMLiveStatus {
4
+ CONNECTED = 'connected',
5
+ DISCONNECTED = 'disconnected',
6
+ WAIT = 'wait',
7
+ SEND_FRAME = 'send_frame',
8
+ TIMEOUT = 'timeout'
9
+ }
10
+
11
+ const initStatus: LCMLiveStatus = LCMLiveStatus.DISCONNECTED;
12
+
13
+ export const lcmLiveStatus = writable<LCMLiveStatus>(initStatus);
14
+ export const streamId = writable<string | null>(null);
15
+
16
+ let websocket: WebSocket | null = null;
17
+ export const lcmLiveActions = {
18
+ async start(getSreamdata: () => any[]) {
19
+ return new Promise((resolve, reject) => {
20
+ try {
21
+ const userId = crypto.randomUUID();
22
+ const websocketURL = `${
23
+ window.location.protocol === 'https:' ? 'wss' : 'ws'
24
+ }:${window.location.host}/api/ws/${userId}`;
25
+
26
+ websocket = new WebSocket(websocketURL);
27
+ websocket.onopen = () => {
28
+ console.log('Connected to websocket');
29
+ };
30
+ websocket.onclose = () => {
31
+ lcmLiveStatus.set(LCMLiveStatus.DISCONNECTED);
32
+ console.log('Disconnected from websocket');
33
+ };
34
+ websocket.onerror = (err) => {
35
+ console.error(err);
36
+ };
37
+ websocket.onmessage = (event) => {
38
+ const data = JSON.parse(event.data);
39
+ switch (data.status) {
40
+ case 'connected':
41
+ lcmLiveStatus.set(LCMLiveStatus.CONNECTED);
42
+ streamId.set(userId);
43
+ resolve({ status: 'connected', userId });
44
+ break;
45
+ case 'send_frame':
46
+ lcmLiveStatus.set(LCMLiveStatus.SEND_FRAME);
47
+ const streamData = getSreamdata();
48
+ websocket?.send(JSON.stringify({ status: 'next_frame' }));
49
+ for (const d of streamData) {
50
+ this.send(d);
51
+ }
52
+ break;
53
+ case 'wait':
54
+ lcmLiveStatus.set(LCMLiveStatus.WAIT);
55
+ break;
56
+ case 'timeout':
57
+ console.log('timeout');
58
+ lcmLiveStatus.set(LCMLiveStatus.TIMEOUT);
59
+ streamId.set(null);
60
+ reject(new Error('timeout'));
61
+ break;
62
+ case 'error':
63
+ console.log(data.message);
64
+ lcmLiveStatus.set(LCMLiveStatus.DISCONNECTED);
65
+ streamId.set(null);
66
+ reject(new Error(data.message));
67
+ break;
68
+ }
69
+ };
70
+ } catch (err) {
71
+ console.error(err);
72
+ lcmLiveStatus.set(LCMLiveStatus.DISCONNECTED);
73
+ streamId.set(null);
74
+ reject(err);
75
+ }
76
+ });
77
+ },
78
+ send(data: Blob | { [key: string]: any }) {
79
+ if (websocket && websocket.readyState === WebSocket.OPEN) {
80
+ if (data instanceof Blob) {
81
+ websocket.send(data);
82
+ } else {
83
+ websocket.send(JSON.stringify(data));
84
+ }
85
+ } else {
86
+ console.log('WebSocket not connected');
87
+ }
88
+ },
89
+ async stop() {
90
+ lcmLiveStatus.set(LCMLiveStatus.DISCONNECTED);
91
+ if (websocket) {
92
+ websocket.close();
93
+ }
94
+ websocket = null;
95
+ streamId.set(null);
96
+ }
97
+ };
frontend/src/lib/mediaStream.ts ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { get, writable, type Writable } from 'svelte/store';
2
+
3
+ const BASE_HEIGHT = 720;
4
+ export enum MediaStreamStatusEnum {
5
+ INIT = 'init',
6
+ CONNECTED = 'connected',
7
+ DISCONNECTED = 'disconnected'
8
+ }
9
+ export const onFrameChangeStore: Writable<{ blob: Blob }> = writable({ blob: new Blob() });
10
+
11
+ export const mediaDevices = writable<MediaDeviceInfo[]>([]);
12
+ export const mediaStreamStatus = writable(MediaStreamStatusEnum.INIT);
13
+ export const mediaStream = writable<MediaStream | null>(null);
14
+
15
+ export const mediaStreamActions = {
16
+ async enumerateDevices() {
17
+ // console.log("Enumerating devices");
18
+ await navigator.mediaDevices
19
+ .enumerateDevices()
20
+ .then((devices) => {
21
+ const cameras = devices.filter((device) => device.kind === 'videoinput');
22
+ mediaDevices.set(cameras);
23
+ })
24
+ .catch((err) => {
25
+ console.error(err);
26
+ });
27
+ },
28
+ async start(mediaDevicedID?: string, aspectRatio: number = 1) {
29
+ const constraints = {
30
+ audio: false,
31
+ video: {
32
+ width: {
33
+ ideal: BASE_HEIGHT * aspectRatio
34
+ },
35
+ height: {
36
+ ideal: BASE_HEIGHT
37
+ },
38
+ deviceId: mediaDevicedID
39
+ }
40
+ };
41
+
42
+ await navigator.mediaDevices
43
+ .getUserMedia(constraints)
44
+ .then((stream) => {
45
+ mediaStreamStatus.set(MediaStreamStatusEnum.CONNECTED);
46
+ mediaStream.set(stream);
47
+ })
48
+ .catch((err) => {
49
+ console.error(`${err.name}: ${err.message}`);
50
+ mediaStreamStatus.set(MediaStreamStatusEnum.DISCONNECTED);
51
+ mediaStream.set(null);
52
+ });
53
+ },
54
+ async startScreenCapture() {
55
+ const displayMediaOptions = {
56
+ video: {
57
+ displaySurface: 'window'
58
+ },
59
+ audio: false,
60
+ surfaceSwitching: 'include'
61
+ };
62
+
63
+ let captureStream = null;
64
+
65
+ try {
66
+ captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
67
+ const videoTrack = captureStream.getVideoTracks()[0];
68
+
69
+ console.log('Track settings:');
70
+ console.log(JSON.stringify(videoTrack.getSettings(), null, 2));
71
+ console.log('Track constraints:');
72
+ console.log(JSON.stringify(videoTrack.getConstraints(), null, 2));
73
+ mediaStreamStatus.set(MediaStreamStatusEnum.CONNECTED);
74
+ mediaStream.set(captureStream);
75
+
76
+ const capabilities = videoTrack.getCapabilities();
77
+ const aspectRatio = capabilities.aspectRatio;
78
+ console.log('Aspect Ratio Constraints:', aspectRatio);
79
+ } catch (err) {
80
+ console.error(err);
81
+ }
82
+ },
83
+ async switchCamera(mediaDevicedID: string, aspectRatio: number) {
84
+ console.log('Switching camera');
85
+ if (get(mediaStreamStatus) !== MediaStreamStatusEnum.CONNECTED) {
86
+ return;
87
+ }
88
+ const constraints = {
89
+ audio: false,
90
+ video: {
91
+ width: {
92
+ ideal: BASE_HEIGHT * aspectRatio
93
+ },
94
+ height: {
95
+ ideal: BASE_HEIGHT
96
+ },
97
+ deviceId: mediaDevicedID
98
+ }
99
+ };
100
+ console.log('Switching camera', constraints);
101
+ await navigator.mediaDevices
102
+ .getUserMedia(constraints)
103
+ .then((stream) => {
104
+ mediaStreamStatus.set(MediaStreamStatusEnum.CONNECTED);
105
+ mediaStream.set(stream);
106
+ })
107
+ .catch((err) => {
108
+ console.error(`${err.name}: ${err.message}`);
109
+ });
110
+ },
111
+ async stop() {
112
+ navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
113
+ stream.getTracks().forEach((track) => track.stop());
114
+ });
115
+ mediaStreamStatus.set(MediaStreamStatusEnum.DISCONNECTED);
116
+ mediaStream.set(null);
117
+ }
118
+ };
frontend/src/lib/store.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { derived, get, writable, type Readable, type Writable } from 'svelte/store';
2
+
3
+ export const pipelineValues: Writable<Record<string, any>> = writable({});
4
+ export const deboucedPipelineValues: Readable<Record<string, any>> = derived(
5
+ pipelineValues,
6
+ ($pipelineValues, set) => {
7
+ const debounced = setTimeout(() => {
8
+ set($pipelineValues);
9
+ }, 100);
10
+ return () => clearTimeout(debounced);
11
+ }
12
+ );
13
+
14
+ export const getPipelineValues = () => get(pipelineValues);
frontend/src/lib/types.ts ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ export interface Fields {
15
+ [key: string]: FieldProps;
16
+ }
17
+
18
+ export interface FieldProps {
19
+ default: number | string;
20
+ max?: number;
21
+ min?: number;
22
+ title: string;
23
+ field: FieldType;
24
+ step?: number;
25
+ disabled?: boolean;
26
+ hide?: boolean;
27
+ id: string;
28
+ values?: string[];
29
+ }
30
+ export interface PipelineInfo {
31
+ title: {
32
+ default: string;
33
+ };
34
+ name: string;
35
+ description: string;
36
+ input_mode: {
37
+ default: PipelineMode;
38
+ };
39
+ }
frontend/src/lib/utils.ts ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ export enum windowType {
10
+ image = 'image',
11
+ video = 'video'
12
+ }
13
+
14
+ export function snapImage(imageEl: HTMLImageElement, info: IImageInfo) {
15
+ try {
16
+ const zeroth: { [key: string]: any } = {};
17
+ const exif: { [key: string]: any } = {};
18
+ const gps: { [key: string]: any } = {};
19
+ zeroth[piexif.ImageIFD.Make] = 'LCM Image-to-Image ControNet';
20
+ zeroth[piexif.ImageIFD.ImageDescription] =
21
+ `prompt: ${info?.prompt} | negative_prompt: ${info?.negative_prompt} | seed: ${info?.seed} | guidance_scale: ${info?.guidance_scale}`;
22
+ zeroth[piexif.ImageIFD.Software] =
23
+ 'https://github.com/radames/Real-Time-Latent-Consistency-Model';
24
+ exif[piexif.ExifIFD.DateTimeOriginal] = new Date().toISOString();
25
+
26
+ const exifObj = { '0th': zeroth, Exif: exif, GPS: gps };
27
+ const exifBytes = piexif.dump(exifObj);
28
+
29
+ const canvas = document.createElement('canvas');
30
+ canvas.width = imageEl.naturalWidth;
31
+ canvas.height = imageEl.naturalHeight;
32
+ const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
33
+ ctx.drawImage(imageEl, 0, 0);
34
+ const dataURL = canvas.toDataURL('image/jpeg');
35
+ const withExif = piexif.insert(exifBytes, dataURL);
36
+
37
+ const a = document.createElement('a');
38
+ a.href = withExif;
39
+ a.download = `lcm_txt_2_img${Date.now()}.png`;
40
+ a.click();
41
+ } catch (err) {
42
+ console.log(err);
43
+ }
44
+ }
45
+
46
+ export function expandWindow(streamURL: string, type: windowType = windowType.image) {
47
+ const newWindow = window.open(
48
+ '',
49
+ '_blank',
50
+ 'width=1024,height=1024,scrollbars=0,resizable=1,toolbar=0,menubar=0,location=0,directories=0,status=0'
51
+ ) as Window;
52
+
53
+ const html = `
54
+ <html>
55
+ <head>
56
+ <title>Real-Time Latent Consistency Model</title>
57
+ <style>
58
+ body {
59
+ margin: 0;
60
+ padding: 0;
61
+ background-color: black;
62
+ }
63
+ </style>
64
+ </head>
65
+ <body>
66
+ <script>
67
+ let isFullscreen = false;
68
+ window.onkeydown = function(event) {
69
+ switch (event.code) {
70
+ case "Escape":
71
+ window.close();
72
+ break;
73
+ case "Enter":
74
+ if (isFullscreen) {
75
+ document.exitFullscreen();
76
+ isFullscreen = false;
77
+ } else {
78
+ document.documentElement.requestFullscreen();
79
+ isFullscreen = true;
80
+ }
81
+ break;
82
+ }
83
+ }
84
+ </script>
85
+ </body>
86
+ </html>
87
+ `;
88
+ newWindow.document.write(html);
89
+
90
+ const img = newWindow.document.createElement('img');
91
+ img.src = streamURL;
92
+ img.style.width = '100%';
93
+ img.style.height = '100%';
94
+ img.style.objectFit = 'contain';
95
+ newWindow.document.body.appendChild(img);
96
+
97
+ return newWindow;
98
+ }
frontend/src/routes/+layout.svelte ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ <script>
2
+ import '../app.css';
3
+ </script>
4
+
5
+ <slot />
frontend/src/routes/+page.svelte ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { onMount } from 'svelte';
3
+ import type { Fields, PipelineInfo } from '$lib/types';
4
+ import { PipelineMode } from '$lib/types';
5
+ import ImagePlayer from '$lib/components/ImagePlayer.svelte';
6
+ import VideoInput from '$lib/components/VideoInput.svelte';
7
+ import Button from '$lib/components/Button.svelte';
8
+ import PipelineOptions from '$lib/components/PipelineOptions.svelte';
9
+ import Spinner from '$lib/icons/spinner.svelte';
10
+ import Warning from '$lib/components/Warning.svelte';
11
+ import { lcmLiveStatus, lcmLiveActions, LCMLiveStatus } from '$lib/lcmLive';
12
+ import { mediaStreamActions, onFrameChangeStore } from '$lib/mediaStream';
13
+ import { getPipelineValues, deboucedPipelineValues } from '$lib/store';
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
+ await mediaStreamActions.enumerateDevices();
70
+ await mediaStreamActions.start();
71
+ }
72
+ disabled = true;
73
+ await lcmLiveActions.start(getSreamdata);
74
+ disabled = false;
75
+ toggleQueueChecker(false);
76
+ } else {
77
+ if (isImageMode) {
78
+ mediaStreamActions.stop();
79
+ }
80
+ lcmLiveActions.stop();
81
+ toggleQueueChecker(true);
82
+ }
83
+ } catch (e) {
84
+ warningMessage = e instanceof Error ? e.message : '';
85
+ disabled = false;
86
+ toggleQueueChecker(true);
87
+ }
88
+ }
89
+ </script>
90
+
91
+ <svelte:head>
92
+ <script
93
+ src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.3.9/iframeResizer.contentWindow.min.js"
94
+ ></script>
95
+ </svelte:head>
96
+
97
+ <main class="container mx-auto flex max-w-5xl flex-col gap-3 px-4 py-4">
98
+ <Warning bind:message={warningMessage}></Warning>
99
+ <article class="text-center">
100
+ {#if pageContent}
101
+ {@html pageContent}
102
+ {/if}
103
+ {#if maxQueueSize > 0}
104
+ <p class="text-sm">
105
+ There are <span id="queue_size" class="font-bold">{currentQueueSize}</span>
106
+ user(s) sharing the same GPU, affecting real-time performance. Maximum queue size is {maxQueueSize}.
107
+ <a
108
+ href="https://huggingface.co/spaces/radames/Real-Time-Latent-Consistency-Model?duplicate=true"
109
+ target="_blank"
110
+ class="text-blue-500 underline hover:no-underline">Duplicate</a
111
+ > and run it on your own GPU.
112
+ </p>
113
+ {/if}
114
+ </article>
115
+ {#if pipelineParams}
116
+ <article class="my-3 grid grid-cols-1 gap-3 sm:grid-cols-4">
117
+ {#if isImageMode}
118
+ <div class="col-span-2 sm:col-start-1">
119
+ <VideoInput
120
+ width={Number(pipelineParams.width.default)}
121
+ height={Number(pipelineParams.height.default)}
122
+ ></VideoInput>
123
+ </div>
124
+ {/if}
125
+ <div class={isImageMode ? 'col-span-2 sm:col-start-3' : 'col-span-4'}>
126
+ <ImagePlayer />
127
+ </div>
128
+ <div class="sm:col-span-4 sm:row-start-2">
129
+ <Button on:click={toggleLcmLive} {disabled} classList={'text-lg my-1 p-2'}>
130
+ {#if isLCMRunning}
131
+ Stop
132
+ {:else}
133
+ Start
134
+ {/if}
135
+ </Button>
136
+ <PipelineOptions {pipelineParams}></PipelineOptions>
137
+ </div>
138
+ </article>
139
+ {:else}
140
+ <!-- loading -->
141
+ <div class="flex items-center justify-center gap-3 py-48 text-2xl">
142
+ <Spinner classList={'animate-spin opacity-50'}></Spinner>
143
+ <p>Loading...</p>
144
+ </div>
145
+ {/if}
146
+ </main>
147
+
148
+ <style lang="postcss">
149
+ :global(html) {
150
+ @apply text-black dark:bg-gray-900 dark:text-white;
151
+ }
152
+ </style>
frontend/src/routes/+page.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ export const prerender = true;
frontend/static/favicon.png ADDED
frontend/svelte.config.js ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import adapter from '@sveltejs/adapter-static';
2
+ import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
3
+
4
+ /** @type {import('@sveltejs/kit').Config} */
5
+ const config = {
6
+ preprocess: vitePreprocess({ postcss: true }),
7
+ kit: {
8
+ adapter: adapter({
9
+ pages: 'public',
10
+ assets: 'public',
11
+ fallback: undefined,
12
+ precompress: false,
13
+ strict: true
14
+ })
15
+ }
16
+ };
17
+
18
+ export default config;
frontend/tailwind.config.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ /** @type {import('tailwindcss').Config} */
2
+ export default {
3
+ content: ['./src/**/*.{html,js,svelte,ts}', '../pipelines/**/*.py'],
4
+ theme: {
5
+ extend: {}
6
+ },
7
+ plugins: []
8
+ };
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
+ }
frontend/vite.config.ts ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { sveltekit } from '@sveltejs/kit/vite';
2
+ import { defineConfig } from 'vite';
3
+
4
+ export default defineConfig({
5
+ plugins: [sveltekit()],
6
+ server: {
7
+ proxy: {
8
+ '/api': 'http://localhost:7860',
9
+ '/api/ws': {
10
+ target: 'ws://localhost:7860',
11
+ ws: true
12
+ }
13
+ }
14
+ }
15
+ });