├── .gitignore
├── .streamlit
├── config.toml
├── credentials.toml
└── secrets.toml
├── Home.py
├── LICENSE
├── README.md
├── README_zh-CN.md
├── bin
├── creator_daemon.sh
├── creator_run.bat
├── creator_run.sh
└── creator_stop.sh
├── docs
└── images
│ ├── demo-webapp.png
│ ├── demo-workflow.png
│ └── how-to-use-it.png
├── manager
├── app_manager.py
└── comfyflow_app.py
├── modules
├── __init__.py
├── authenticate.py
├── comfyclient.py
├── comfyflow.py
├── myapp_model.py
├── new_app.py
├── page.py
├── preview_app.py
├── publish_app.py
└── workspace_model.py
├── pages
├── 1_📱_My Apps.py
└── 3_📚_Workspace.py
├── public
└── images
│ ├── app-150.png
│ ├── logo.png
│ └── output-none.png
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | __pycache__/
3 | *.log
4 | .vscode/*
5 | .VSCodeCounter/*
6 | .apps/*
7 | comfyflow.db
8 | .devcontainer/*
--------------------------------------------------------------------------------
/.streamlit/config.toml:
--------------------------------------------------------------------------------
1 |
2 | [server]
3 |
4 | # List of folders that should not be watched for changes. This
5 | # impacts both "Run on Save" and @st.cache.
6 |
7 | # Relative paths will be taken as relative to the current working directory.
8 |
9 | # Example: ['/home/user1/env', 'relative/path/to/folder']
10 |
11 | # Default: []
12 | folderWatchBlacklist = []
13 |
14 | # Change the type of file watcher used by Streamlit, or turn it off
15 | # completely.
16 |
17 | # Allowed values:
18 | # * "auto" : Streamlit will attempt to use the watchdog module, and
19 | # falls back to polling if watchdog is not available.
20 | # * "watchdog" : Force Streamlit to use the watchdog module.
21 | # * "poll" : Force Streamlit to always use polling.
22 | # * "none" : Streamlit will not watch files.
23 |
24 | # Default: "auto"
25 | fileWatcherType = "auto"
26 |
27 | # Symmetric key used to produce signed cookies. If deploying on multiple
28 | # replicas, this should be set to the same value across all replicas to ensure
29 | # they all share the same secret.
30 |
31 | # Default: randomly generated secret key.
32 | cookieSecret = "a-random-key-appears-here"
33 |
34 | # If false, will attempt to open a browser window on start.
35 |
36 | # Default: false unless (1) we are on a Linux box where DISPLAY is unset, or
37 | # (2) we are running in the Streamlit Atom plugin.
38 | # headless = false
39 |
40 | # Automatically rerun script when the file is modified on disk.
41 |
42 | # Default: false
43 | runOnSave = false
44 |
45 | # The address where the server will listen for client and browser
46 | # connections. Use this if you want to bind the server to a specific address.
47 | # If set, the server will only be accessible from this address, and not from
48 | # any aliases (like localhost).
49 |
50 | # Default: (unset)
51 | # address =
52 |
53 | # The port where the server will listen for browser connections.
54 |
55 | # Default: 8501
56 | port = 8501
57 |
58 | # The base path for the URL where Streamlit should be served from.
59 |
60 | # Default: ""
61 | baseUrlPath = ""
62 |
63 | # Enables support for Cross-Origin Resource Sharing (CORS) protection, for
64 | # added security.
65 |
66 | # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is
67 | # on and `server.enableCORS` is off at the same time, we will prioritize
68 | # `server.enableXsrfProtection`.
69 |
70 | # Default: true
71 | enableCORS = false
72 |
73 | # Enables support for Cross-Site Request Forgery (XSRF) protection, for added
74 | # security.
75 |
76 | # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is
77 | # on and `server.enableCORS` is off at the same time, we will prioritize
78 | # `server.enableXsrfProtection`.
79 |
80 | # Default: true
81 | enableXsrfProtection = false
82 |
83 | # Max size, in megabytes, for files uploaded with the file_uploader.
84 |
85 | # Default: 200
86 | maxUploadSize = 20
87 |
88 | # Max size, in megabytes, of messages that can be sent via the WebSocket
89 | # connection.
90 |
91 | # Default: 200
92 | maxMessageSize = 200
93 |
94 | # Enables support for websocket compression.
95 |
96 | # Default: false
97 | enableWebsocketCompression = false
98 |
99 | # Enable serving files from a `static` directory in the running app's
100 | # directory.
101 |
102 | # Default: false
103 | enableStaticServing = false
104 |
105 | # Server certificate file for connecting via HTTPS.
106 | # Must be set at the same time as "server.sslKeyFile".
107 |
108 | # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through
109 | # security audits or performance tests. For the production environment, we
110 | # recommend performing SSL termination by the load balancer or the reverse
111 | # proxy.']
112 | # sslCertFile =
113 |
114 | # Cryptographic key file for connecting via HTTPS.
115 | # Must be set at the same time as "server.sslCertFile".
116 |
117 | # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through
118 | # security audits or performance tests. For the production environment, we
119 | # recommend performing SSL termination by the load balancer or the reverse
120 | # proxy.']
121 | # sslKeyFile =
122 |
123 |
124 | [client]
125 | # Default: true
126 | showErrorDetails = true
127 |
128 | # Change the visibility of items in the toolbar, options menu,
129 | # and settings dialog (top right of the app).
130 | # Allowed values:
131 | # * "auto" : Show the developer options if the app is accessed through
132 | # localhost or through Streamlit Community Cloud as a developer.
133 | # Hide them otherwise.
134 | # * "developer" : Show the developer options.
135 | # * "viewer" : Hide the developer options.
136 | # * "minimal" : Show only options set externally (e.g. through
137 | # Streamlit Community Cloud) or through st.set_page_config.
138 | # If there are no options left, hide the menu.
139 |
140 | # Default: "auto"
141 | toolbarMode = "viewer"
--------------------------------------------------------------------------------
/.streamlit/credentials.toml:
--------------------------------------------------------------------------------
1 | [general]
2 | email = "yexingren@gmail.com"
--------------------------------------------------------------------------------
/.streamlit/secrets.toml:
--------------------------------------------------------------------------------
1 | COMFYFLOW_API_URL="https://api.comfyflow.app"
2 |
3 | [connections.comfyflow_db]
4 | url = "sqlite:///comfyflow.db"
--------------------------------------------------------------------------------
/Home.py:
--------------------------------------------------------------------------------
1 | import streamlit as st
2 | import requests
3 | import os
4 | from loguru import logger
5 | from streamlit_authenticator.exceptions import RegisterError
6 | from streamlit_extras.row import row
7 | from modules import page
8 | from modules.authenticate import MyAuthenticate
9 | from modules.authenticate import Validator
10 |
11 |
12 | def gen_invite_code(source: str, uid: str):
13 | invate_code = f"oauth_{source}_{uid}"
14 | return invate_code
15 |
16 | def back_home_signup():
17 | st.session_state.pop('user_data', None)
18 | logger.info("back home login")
19 |
20 |
21 | page.init_env_default()
22 | page.page_init(layout="centered")
23 |
24 | with st.container():
25 | header_row = row([0.87, 0.13], vertical_align="bottom")
26 | header_row.title("""
27 | Welcome to ComfyFlowApp
28 | From comfyui workflow to web application in seconds, and share with others.
29 | """)
30 | header_button = header_row.empty()
31 |
32 | auth_instance = MyAuthenticate("comfyflow_token", "ComfyFlowApp: Load ComfyUI workflow as webapp in seconds.")
33 | if not st.session_state['authentication_status']:
34 | # with header_button:
35 | # client_id = os.getenv('DISCORD_CLIENT_ID')
36 | # redirect_uri = os.getenv('DISCORD_REDIRECT_URI')
37 | # signup_url = f"https://discord.com/oauth2/authorize?client_id={client_id}&scope=identify+email&redirect_uri={redirect_uri}&response_type=code"
38 | # st.link_button("Sign Up", type="primary", url=signup_url, help="Sign up with Discord")
39 |
40 | with st.container():
41 | try:
42 | st.markdown("ComfyFlowApp offers an in-built test account(username: demo) with the credentials(password: comfyflowapp).")
43 | auth_instance.login("Login to ComfyFlowApp")
44 | except Exception as e:
45 | st.error(f"Login failed, {e}")
46 |
47 | else:
48 | with header_button:
49 | auth_instance.logout(button_name="Logout", location="main", key="home_logout_button")
50 |
51 |
52 | with st.container():
53 | name = st.session_state['name']
54 | username = st.session_state['username']
55 | st.markdown(f"Hello, {name}({username}) :smile:")
56 |
57 | st.markdown("""
58 | ### 📌 What is ComfyFlowApp?
59 | ComfyFlowApp is an extension tool for ComfyUI, making it easy to develop a user-friendly web application from a ComfyUI workflow and share it with others.
60 | """)
61 | st.markdown("""
62 | ### 📌 Why You Need ComfyFlowApp?
63 | ComfyFlowApp helps creator to develop a web app from comfyui workflow in seconds.
64 |
65 | If you need to share workflows developed in ComfyUI with other users, ComfyFlowApp can significantly lower the barrier for others to use your workflows:
66 | - Users don't need to understand the principles of AI generation models.
67 | - Users don't need to know the tuning parameters of various AI models.
68 | - Users don't need to understand where to download models.
69 | - Users don't need to know how to set up ComfyUI workflows.
70 | - Users don't need to understand Python installation requirements.
71 |
72 | """)
73 | st.markdown("""
74 | ### 📌 Use Cases
75 | """)
76 | st.image("./docs/images/how-to-use-it.png", use_column_width=True)
77 | st.markdown("""
78 | :point_right: Follow the repo [ComfyFlowApp](https://github.com/xingren23/ComfyFlowApp) to get the latest updates.
79 | """)
80 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | **We have launch a online service for ComfyFlowApp, you could develop app online and share it with your friends and anyone.** WebSite: [ComfyFlow](https://comfyflow.app)
2 |
3 | # 📌 Welcome to ComfyFlowApp
4 |
5 | ComfyFlowApp is a tool to help you develop AI webapp from ComfyUI workflow and share to others.
6 |
7 | English | [简体中文](./README_zh-CN.md)
8 |
9 | ## 📌 What is ComfyFlowApp?
10 |
11 | ComfyFlowApp is an extension tool for ComfyUI, making it easy to create a user-friendly application from a ComfyUI workflow and lowering the barrier to using ComfyUI.
12 |
13 | As shown in the images below, you can develop a web application from the workflow like "portrait retouching"
14 |
15 | 
16 | 
17 |
18 | ### Why You Need ComfyFlowApp?
19 |
20 | If you want to generate an image using AI tools, you can choose MidJourney, DALL-E3, Fairfly (Adobe), or similar tools. These tools allow anyone to generate a beautiful image based on prompts. However, if you need more control over the generated results, like dressing a model in specific clothing, these tools may not suffice. Additionally, if your scenario has specific copyright requirements for images, you can use the open-source Stable Diffusion to build an AI image processing application. You have the choice of Stable-Diffusion-WebUI or ComfyUI, with WebUI being simple to use and having a rich plugin ecosystem for various processing needs. On the other hand, ComfyUI has a higher learning curve but offers more flexible workflow customization, allowing you to develop workflows for a wide range of scenarios.
21 |
22 | If you need to share workflows developed in ComfyUI with other users, ComfyFlowApp can significantly lower the barrier for others to use your workflows:
23 |
24 | - Users don't need to understand the principles of AI generation models.
25 | - Users don't need to know the tuning parameters of various AI models.
26 | - Users don't need to understand where to download models.
27 | - Users don't need to know how to set up ComfyUI workflows.
28 | - Users don't need to understand Python installation requirements.
29 |
30 |
31 | **In summary, ComfyFlowApp make comfyui workflow easy to use.**
32 |
33 |
34 | ### Use Cases
35 |
36 | 
37 |
38 | **1. For internal corporate collaboration**
39 |
40 | * Creators develop workflows in ComfyUI and productize these workflows into web applications using ComfyFlowApp.
41 | * Users access and utilize the workflow applications through ComfyFlowApp to enhance work efficiency.
42 |
43 | **2. For remote corporate collaboration**
44 |
45 | * Deploy ComfyUI and ComfyFlowApp to cloud services like RunPod/Vast.ai/AWS, and map the server ports for public access, such as https://{POD_ID}-{INTERNAL_PORT}.proxy.runpod.net.
46 | * Creators develop workflows in ComfyUI and productize these workflows into web applications using ComfyFlowApp.
47 | * Users access and utilize these workflow applications through ComfyFlowApp to enhance work efficiency.
48 |
49 |
50 | **Follow the repo to get the latest updates.**
51 |
52 |
53 | ### 📌 Quick Start
54 |
55 | ComfyFlowApp offers an in-built test account(username: demo) with the credentials(password: comfyflowapp). For an enhanced user experience, please sign up your account at https://comfyflow.app.
56 |
57 | ```bash
58 | # download project
59 | git clone https://github.com/xingren23/ComfyFlowApp
60 |
61 | # create and activate python env
62 | # Note: pytorch does not support python 3.12 yet so make sure your python version is 3.11 or earlier.
63 | conda create -n comfyflowapp python=3.11
64 | conda activate comfyflowapp
65 |
66 | # install requirements
67 | pip install -r requirements.txt
68 |
69 | # start or run
70 | # linux
71 | sh bin/creator_run.sh
72 | # windows
73 | .\bin\creator_run.bat
74 | ```
75 |
76 | or you could download integrated package fow windows
77 | [comfyflowapp-python-3.11-amd64.7z](https://github.com/xingren23/ComfyFlowApp/releases)
78 |
79 |
80 | env var, you could modify some env var as needed
81 |
82 | ```bash
83 | :: log level default: INFO
84 | set LOGURU_LEVEL=INFO
85 |
86 | :: ComfyflowApp address,default: https://api.comfyflow.app
87 | set COMFYFLOW_API_URL=https://api.comfyflow.app
88 |
89 | :: comfyui env for developping,you could use other machine in the same LAN, default: http://localhost:8188
90 | set COMFYUI_SERVER_ADDR=http://localhost:8188
91 |
92 | :: webapp server address, others in the same LAN could visit your webapp, default: localhost
93 | set STREAMLIT_SERVER_ADDRESS=192.168.1.100
94 | ```
95 |
96 | ### 📌 Related Projects
97 |
98 | - [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
99 |
100 | ### 📌 Contact Us
101 |
102 | - [GitHub Issues](https://github.com/xingren23/ComfyWorkflowApp/issues)
103 |
104 | - [ComfyFlowApp Discord](https://discord.gg/rjbdD3EkYw)
105 |
106 |
--------------------------------------------------------------------------------
/README_zh-CN.md:
--------------------------------------------------------------------------------
1 | 我们发布了ComfyFlowApp在线服务,创作者可以在线创建ComfyUI工作流应用,并分享给他人使用.
2 | 服务地址:[ComfyFlow](https://comfyflow.app)
3 |
4 | # ComfyFlowApp
5 |
6 | 只要几秒就可以将你的ComfyUI工作流开发成一个Web应用,并分享给其他用户使用。
7 |
8 | ## ComfyFlowApp 是什么?
9 |
10 | ComfyFlowApp 是一个 ComfyUI 的扩展工具, 可以轻松从 ComfyUI 工作流开发出一个简单易用的 Web 应用,降低 ComfyUI 的使用门槛。
11 | 如下图所示,将一个人像修复的工作流开发成一个 ComfyFlowApp 应用。
12 | 
13 |
14 | 
15 |
16 | ### ComfyFlowApp 有什么用?
17 |
18 | 如果你想通过 AI 工具来生成一张图片,可以选择的 MidJourney、DALL-E3、Fairfly(Adobe),使用这些工具任何人都可以通过提示词来生成一幅精美的图片,如果你想进一步控制生成的结果,如让模特穿上指定的衣服,这些工具可能都无法实现,或者你所在的场景对图片版权有特殊的要求,你可以使用开源的 Stable Diffusion 来构建 AI 图片处理应用,可以选择 Stable-Diffusion-WebUI 或者 ComfyUI,其中 WebUI 简单易用,插件生态丰富,可以满足很多场景的处理需求,而 ComfyUI 使用门槛较高,但支持更灵活的工作流定制,开发出满足各种场景需求的工作流。
19 |
20 | 如果你需要将 ComfyUI 中开发的工作流分享给其他用户使用,ComfyFlowApp 可以显著降低其他用户使用你的工作流的门槛。
21 |
22 | - 用户不需要懂 AI 生成模型的原理;
23 | - 用户不需要懂各种 AI 模型的调优参数;
24 | - 用户不需要懂模型从哪里下载;
25 | - 用户不需要懂如何搭建 ComfyUI 工作流;
26 | - 用户不需要懂 Python 安装环境;
27 |
28 | **总结,ComfyFlowApp 帮助工作流开发者简化工作流的使用难度,用户只需要像普通应用一样使用即可。**
29 |
30 |
31 | ### 使用场景
32 |
33 | 
34 |
35 | **1. 企业内部协作**
36 |
37 | * 创作者在ComfyUI中开发工作流,并使用ComfyFlowApp将这些工作流产品化为Web应用。
38 | * 使用者通过ComfyFlowApp使用这些工作流应用,以提高工作效率。
39 |
40 | **2. 远程企业协作**
41 |
42 | * 将ComfyUI和ComfyFlowApp部署到像RunPod/Vast.ai/AWS这样的云服务上,并将服务器端口映射为公网访问,例如https://{POD_ID}-{INTERNAL_PORT}.proxy.runpod.net。
43 | * 创作者在ComfyUI中开发工作流,并使用ComfyFlowApp将这些工作流产品化为Web应用。
44 | * 使用者通过ComfyFlowApp使用这些工作流应用,以提高工作效率。
45 |
46 | 关注本项目,获取最新动态。
47 |
48 | ### 快速开始
49 |
50 | ComfyFlowApp 提供了一个测试账号:demo 密码:comfyflowapp,为了更好的用户体验,你可以在 https://comfyflow.app 注册自己的账号。
51 |
52 | ```bash
53 | # 下载项目
54 | git clone https://github.com/xingren23/ComfyFlowApp
55 |
56 | # 使用Conda创建并管理python环境
57 | conda create -n comfyflowapp python=3.11
58 | conda activate comfyflowapp
59 |
60 | # 安装ComfyFlowApp依赖
61 | pip install -r requirements.txt
62 |
63 | # 启动
64 | # linux
65 | sh bin/creator_run.sh
66 | # windows
67 | .\bin\creator_run.bat
68 |
69 | ```
70 | Windows用户可以直接下载一键包:[comfyflowapp-python-3.11-amd64.7z](https://github.com/xingren23/ComfyFlowApp/releases)
71 |
72 |
73 | 环境变量, 在启动脚本中可以修改相关变量
74 |
75 | ```
76 | :: ComfyflowApp 地址,默认:https://api.comfyflow.app
77 | set COMFYFLOW_API_URL=https://api.comfyflow.app
78 |
79 | :: 开发联调外部ComfyUI地址,可以连接局域网内其他服务器地址,默认:http://localhost:8188
80 | set COMFYUI_SERVER_ADDR=http://localhost:8188
81 |
82 | :: 设置web应用启动地址,让局域网内其他用户可以访问你的应用,默认:localhost
83 | set STREAMLIT_SERVER_ADDRESS=192.168.1.100
84 | ```
85 |
86 |
87 | ## 相关项目
88 |
89 | - [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
90 |
91 | ## 联系我们
92 |
93 | ComfyWorkflowApp 项目还处于早期阶段,如果您有任何问题或建议,欢迎通过以下方式联系我们:
94 |
95 | - [GitHub Issues](https://github.com/xingren23/ComfyWorkflowApp/issues)
96 |
97 | - [ComfyFlowApp Discord](https://discord.gg/rjbdD3EkYw)
98 |
--------------------------------------------------------------------------------
/bin/creator_daemon.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # get current path
4 | CUR_DIR="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"
5 | PROJECT_PATH=$(dirname $(dirname "$CUR_DIR"))
6 | echo "$PROJECT_PATH"
7 | cd $PROJECT_PATH
8 |
9 | # set LOGURU_LEVEL to ERROR
10 | export LOGURU_LEVEL=INFO
11 |
12 | export STREAMLIT_SERVER_PORT=8501
13 | # set COMFYFLOW_API_URL to comfyflow api url
14 | export COMFYFLOW_API_URL=https://api.comfyflow.app
15 | # set COMFYUI_SERVER_ADDR to comfyui server addr
16 | export COMFYUI_SERVER_ADDR=http://localhost:8188
17 | # set MODE to Creator
18 | export MODE=Creator
19 |
20 | # script params
21 | nohup python -m streamlit run Home.py > app.log 2>&1 &
--------------------------------------------------------------------------------
/bin/creator_run.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | setlocal
3 |
4 | :: get current directory
5 | set CUR_DIR=%~dp0
6 | set PROJECT_DIR=%CUR_DIR%..\
7 | cd /d %PROJECT_DIR%
8 |
9 | :: set LOGURU_LEVEL to INFO
10 | set LOGURU_LEVEL=INFO
11 |
12 | set STREAMLIT_SERVER_PORT=8501
13 | :: set COMFYFLOW_API_URL to https://api.comfyflow.app
14 | set COMFYFLOW_API_URL=https://api.comfyflow.app
15 | :: set COMFYUI_SERVER_ADDR to localhost:8188
16 | set COMFYUI_SERVER_ADDR=http://localhost:8188
17 | :: set MODE
18 | set MODE=Creator
19 |
20 | :: start server
21 | python -m streamlit run Home.py
22 | pause
23 | endlocal
--------------------------------------------------------------------------------
/bin/creator_run.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # get current path
4 | CUR_DIR="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"
5 | PROJECT_PATH=$(dirname $(dirname "$CUR_DIR"))
6 | echo "$PROJECT_PATH"
7 | cd $PROJECT_PATH
8 |
9 | # set LOGURU_LEVEL to ERROR
10 | export LOGURU_LEVEL=INFO
11 |
12 | export STREAMLIT_SERVER_PORT=8501
13 | # set COMFYFLOW_API_URL to comfyflow api url
14 | export COMFYFLOW_API_URL=https://api.comfyflow.app
15 | # set COMFYUI_SERVER_ADDR to comfyui server addr
16 | export COMFYUI_SERVER_ADDR=http://localhost:8188
17 | # set MODE to Creator
18 | export MODE=Creator
19 |
20 | # script params
21 | python -m streamlit run Home.py
--------------------------------------------------------------------------------
/bin/creator_stop.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # 停止脚本
4 | APP_NAME="streamlit"
5 |
6 | # 查找并终止正在运行的 Flask 应用程序进程
7 | PID=$(ps aux | grep "$APP_NAME" | grep -v grep | awk '{print $2}')
8 | if [ -n "$PID" ]; then
9 | echo "Stopping $APP_NAME $PID..."
10 | kill $PID
11 | echo "Stoped $APP_NAME"
12 | else
13 | echo "$APP_NAME is not running."
14 | fi
--------------------------------------------------------------------------------
/docs/images/demo-webapp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xingren23/ComfyFlowApp/c4d26a4ac307e01db0498207c51a58bfe2d638e9/docs/images/demo-webapp.png
--------------------------------------------------------------------------------
/docs/images/demo-workflow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xingren23/ComfyFlowApp/c4d26a4ac307e01db0498207c51a58bfe2d638e9/docs/images/demo-workflow.png
--------------------------------------------------------------------------------
/docs/images/how-to-use-it.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xingren23/ComfyFlowApp/c4d26a4ac307e01db0498207c51a58bfe2d638e9/docs/images/how-to-use-it.png
--------------------------------------------------------------------------------
/manager/app_manager.py:
--------------------------------------------------------------------------------
1 | import os
2 | from loguru import logger
3 | import threading
4 | import subprocess
5 | import psutil
6 | import shutil
7 | from modules.workspace_model import AppStatus
8 | from streamlit.runtime.scriptrunner import add_script_run_ctx
9 |
10 | class CommandThread(threading.Thread):
11 | def __init__(self, path, command):
12 | super(CommandThread, self).__init__()
13 | self.path = path
14 | self.command = command
15 |
16 | def run(self):
17 | logger.info(f"Run command {self.command} in path {self.path}")
18 | result = subprocess.run(self.command, shell=True, cwd=self.path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
19 | if result.returncode == 0:
20 | logger.info("Command output:", result.stdout)
21 | else:
22 | logger.warning(f"{self.command} return ", result.stderr)
23 |
24 |
25 | def is_process_running(app_name, args):
26 | """
27 | ['/usr/local/anaconda3/bin/python', '/usr/local/anaconda3/bin/streamlit', 'run', 'comfyflow_app.py', '--server.port', '8198', '--server.address', 'localhost', '--', '--app', '11']
28 | """
29 | for process in psutil.process_iter(attrs=['pid', 'cmdline']):
30 | if process.info['cmdline']:
31 | cmdline = process.info['cmdline']
32 | # check all args is in cmdline
33 | if all(arg in cmdline for arg in args):
34 | logger.info(f"Process {app_name} is running, pid: {process.info['pid']}")
35 | return True
36 | return False
37 |
38 | def kill_all_process(app_name, args):
39 | """
40 | ['/usr/local/anaconda3/bin/python', '/usr/local/anaconda3/bin/streamlit', 'run', 'comfyflow_app.py', '--server.port', '8198', '--server.address', 'localhost', '--', '--app', '11']
41 | """
42 | for process in psutil.process_iter(attrs=['pid', 'cmdline']):
43 | if process.info['cmdline']:
44 | cmdline = process.info['cmdline']
45 | # check all args is in cmdline
46 | if all(arg in cmdline for arg in args):
47 | logger.info(f"Kill process {app_name}, pid: {process.info['pid']}")
48 | process.kill()
49 |
50 | def make_app_home(app_name):
51 | # remove app home first
52 | remove_app_home(app_name)
53 |
54 | app_path = os.path.join(os.getcwd(), ".apps", app_name)
55 | if not os.path.exists(app_path):
56 | os.makedirs(app_path)
57 | logger.info(f"make App {app_name} dir, {app_path}")
58 |
59 | try:
60 | # cp comfyflow_app.py, comfyflow.db, public, modules, .streamlit to app_path
61 | shutil.copyfile("./manager/comfyflow_app.py", os.path.join(app_path, "comfyflow_app.py"))
62 | shutil.copyfile("./comfyflow.db", os.path.join(app_path, "comfyflow.db"))
63 | shutil.copytree("./public", os.path.join(app_path, "public"))
64 | shutil.copytree("./modules", os.path.join(app_path, "modules"))
65 | shutil.copytree("./.streamlit", os.path.join(app_path, ".streamlit"))
66 |
67 | logger.info(f"App {app_name} generated, path: {app_path}")
68 | return app_path
69 | except Exception as e:
70 | logger.error(f"Error: {e}")
71 | return None
72 |
73 | def remove_app_home(app_name):
74 | app_path = os.path.join(os.getcwd(), ".apps", app_name)
75 | if os.path.exists(app_path):
76 | shutil.rmtree(app_path)
77 | logger.info(f"App {app_name} removed, path: {app_path}")
78 | return True
79 | else:
80 | logger.info(f"App {app_name} does not exist, path: {app_path}")
81 | return False
82 |
83 | def start_app(app_name, app_id, url):
84 | # url, parse server and port
85 | address = url.split("//")[1].split(":")[0]
86 | port = url.split("//")[1].split(":")[1]
87 | command = f"streamlit run comfyflow_app.py --server.port {port} --server.address {address} -- --app {app_id}"
88 | if is_process_running(app_name, ["run", "comfyflow_app.py", str(port), address]):
89 | logger.info(f"App {app_name} is already running, url: {url}")
90 | return AppStatus.RUNNING.value
91 | else:
92 | logger.info(f"start comfyflow app {app_name}")
93 | app_path = make_app_home(app_name)
94 | if app_path is None:
95 | logger.error(f"App {app_name} dir generated failed, path: {app_path}")
96 | return "failed"
97 | app_thread = CommandThread(app_path, command)
98 | add_script_run_ctx(app_thread)
99 | app_thread.start()
100 | logger.info(f"App {app_name} started, url: {url}")
101 | return AppStatus.STARTED.value
102 |
103 | def stop_app(app_name, url):
104 | # url, parse server and port
105 | address = url.split("//")[1].split(":")[0]
106 | port = url.split("//")[1].split(":")[1]
107 | if is_process_running(app_name, ["run", "comfyflow_app.py", str(port), address]):
108 | logger.info(f"stop comfyflow app {app_name}")
109 | kill_all_process(app_name, ["run", "comfyflow_app.py", str(port), address])
110 | remove_app_home(app_name)
111 | return AppStatus.STOPPING.value
112 | else:
113 | logger.info(f"App {app_name} is not running, url: {url}")
114 | return AppStatus.STOPPED.value
115 |
116 |
--------------------------------------------------------------------------------
/manager/comfyflow_app.py:
--------------------------------------------------------------------------------
1 | import streamlit as st
2 | import argparse
3 | from loguru import logger
4 | from streamlit_extras.badges import badge
5 |
6 | from modules import get_workspace_model, get_comfy_client
7 |
8 | def page_header():
9 | st.set_page_config(page_title="ComfyFlowApp: Load a comfyui workflow as webapp in seconds.",
10 | page_icon=":artist:", layout="wide")
11 |
12 | # reduce top padding
13 | st.markdown("""
14 |
22 | """, unsafe_allow_html=True)
23 |
24 | hide_streamlit_style = """
25 |
29 | """
30 | st.markdown(hide_streamlit_style, unsafe_allow_html=True)
31 |
32 | with st.sidebar:
33 | st.sidebar.markdown("""
34 |
39 | """, unsafe_allow_html=True)
40 |
41 | st.image("public/images/logo.png", width=200)
42 |
43 | st.sidebar.markdown("""
44 | ### ComfyFlowApp
45 | Load a comfyui workflow as webapp in seconds.
46 | """)
47 |
48 | badge(type="github", name="xingren23/ComfyFlowApp", url="https://github.com/xingren23/ComfyFlowApp")
49 | badge(type="twitter", name="xingren23", url="https://twitter.com/xingren23")
50 |
51 | parser = argparse.ArgumentParser(description='Comfyflow manager')
52 | parser.add_argument('--app', type=str, default='', help='comfyflow app id')
53 | args = parser.parse_args()
54 |
55 | page_header()
56 |
57 | with st.container():
58 | apps = get_workspace_model().get_all_apps()
59 | app_id_map = { str(app.id): app for app in apps}
60 | app_id = args.app
61 | logger.info(f"load app app_id {app_id}")
62 |
63 | if app_id not in app_id_map:
64 | st.warning(f"App {app_id} hasn't existed")
65 | else:
66 | app = app_id_map[app_id]
67 | app_data = app.app_conf
68 | api_data = app.api_conf
69 |
70 | from modules.comfyflow import Comfyflow
71 | comfy_flow = Comfyflow(comfy_client=get_comfy_client(), api_data=api_data, app_data=app_data)
72 | comfy_flow.create_ui(show_header=True)
--------------------------------------------------------------------------------
/modules/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 | from loguru import logger
3 | import streamlit as st
4 | from enum import Enum
5 |
6 | # enum app status
7 | class AppStatus(Enum):
8 | CREATED = "Created"
9 | PREVIEWED = "Previewed"
10 | PUBLISHED = "Published"
11 | RUNNING = "Running"
12 | STARTED = "Started"
13 | STOPPING = "Stopping"
14 | STOPPED = "Stopped"
15 | INSTALLING = "Installing"
16 | INSTALLED = "Installed"
17 | UNINSTALLED = "Uninstalled"
18 | ERROR = "Error"
19 |
20 |
21 | @st.cache_resource
22 | def get_workspace_model():
23 | logger.debug("get_workspace_instance")
24 | from modules.workspace_model import WorkspaceModel
25 | sqliteInstance = WorkspaceModel()
26 | return sqliteInstance
27 |
28 | @st.cache_resource
29 | def get_myapp_model():
30 | logger.debug("get_myapp_model")
31 | from modules.myapp_model import MyAppModel
32 | myapp_model = MyAppModel()
33 | return myapp_model
34 |
35 | @st.cache_resource
36 | def get_comfy_client():
37 | logger.debug("get_comfy_client")
38 | from modules.comfyclient import ComfyClient
39 | server_addr = os.getenv('COMFYUI_SERVER_ADDR')
40 | comfy_client = ComfyClient(server_addr=server_addr)
41 | return comfy_client
42 |
43 | def check_comfyui_alive():
44 | try:
45 | get_comfy_client().queue_remaining()
46 | return True
47 | except Exception as e:
48 | logger.warning(f"check comfyui alive error, {e}")
49 | return False
50 |
51 | @st.cache_data(ttl=60)
52 | def get_comfyui_object_info():
53 | logger.debug("get_comfy_object_info")
54 | comfy_client = get_comfy_client()
55 | comfy_object_info = comfy_client.get_node_class()
56 | return comfy_object_info
57 |
58 |
59 | def get_comfyflow_token():
60 | import extra_streamlit_components as stx
61 | cookie_manager = stx.CookieManager("token")
62 | token = cookie_manager.get('comfyflow_token')
63 | return token
--------------------------------------------------------------------------------
/modules/authenticate.py:
--------------------------------------------------------------------------------
1 | from loguru import logger
2 | import os
3 | import re
4 | import jwt
5 | import requests
6 | import streamlit as st
7 | from streamlit_authenticator.exceptions import RegisterError
8 | from datetime import datetime, timedelta
9 | import extra_streamlit_components as stx
10 |
11 | class Validator:
12 | """
13 | This class will check the validity of the entered username, name, and email for a
14 | newly registered user.
15 | """
16 | def validate_username(self, username: str) -> bool:
17 | """
18 | Checks the validity of the entered username.
19 | """
20 | pattern = r"^[a-zA-Z0-9_-]{1,20}$"
21 | return bool(re.match(pattern, username))
22 |
23 | def validate_name(self, name: str) -> bool:
24 | """
25 | Checks the validity of the entered name.
26 | """
27 | return 1 < len(name) < 100
28 |
29 | def validate_email(self, email: str) -> bool:
30 | """
31 | Checks the validity of the entered email.
32 | """
33 | return "@" in email and 2 < len(email) < 320
34 |
35 | class MyAuthenticate():
36 | def __init__(self, cookie_name: str, key:str, cookie_expiry_days: float=30.0):
37 | self.cookie_name = cookie_name
38 | self.key = key
39 | self.cookie_expiry_days = cookie_expiry_days
40 | self.cookie_manager = stx.CookieManager()
41 | self.validator = Validator()
42 |
43 | if 'name' not in st.session_state:
44 | st.session_state['name'] = None
45 | if 'authentication_status' not in st.session_state:
46 | st.session_state['authentication_status'] = None
47 | if 'username' not in st.session_state:
48 | st.session_state['username'] = None
49 | if 'logout' not in st.session_state:
50 | st.session_state['logout'] = None
51 |
52 | self._check_cookie()
53 | st.session_state['comfyflow_token'] = self.get_token()
54 | self.comfyflow_url = os.getenv('COMFYFLOW_API_URL')
55 | logger.info(f"username {st.session_state['username']}")
56 |
57 | def get_token(self) -> str:
58 | """
59 | Gets the token from the cookie.
60 |
61 | Returns
62 | -------
63 | str
64 | The token.
65 | """
66 | return self.cookie_manager.get(self.cookie_name)
67 |
68 | def _token_encode(self) -> str:
69 | """
70 | Encodes the contents of the reauthentication cookie.
71 |
72 | Returns
73 | -------
74 | str
75 | The JWT cookie for passwordless reauthentication.
76 | """
77 | return jwt.encode({'name':st.session_state['name'],
78 | 'username':st.session_state['username'],
79 | 'exp_date':self.exp_date}, self.key, algorithm='HS256')
80 |
81 |
82 | def _token_decode(self) -> str:
83 | """
84 | Decodes the contents of the reauthentication cookie.
85 |
86 | Returns
87 | -------
88 | str
89 | The decoded JWT cookie for passwordless reauthentication.
90 | """
91 | try:
92 | return jwt.decode(self.token, self.key, algorithms=['HS256'])
93 | except:
94 | return False
95 |
96 | def _set_exp_date(self) -> str:
97 | """
98 | Creates the reauthentication cookie's expiry date.
99 |
100 | Returns
101 | -------
102 | str
103 | The JWT cookie's expiry timestamp in Unix epoch.
104 | """
105 | return (datetime.utcnow() + timedelta(days=self.cookie_expiry_days)).timestamp()
106 |
107 | def _check_pw(self) -> bool:
108 | # check username and password
109 | username = self.username
110 | login_json = {
111 | "username": username,
112 | "password": self.password
113 | }
114 | ret = requests.post(f"{self.comfyflow_url}/api/user/login", json=login_json)
115 | if ret.status_code != 200:
116 | logger.error(f"login error, {ret.text}")
117 | st.error(f"Login failed, {ret.text}")
118 | return False
119 | else:
120 | st.session_state['username'] = ret.json()['username']
121 | st.session_state['name'] = ret.json()['nickname']
122 |
123 | logger.info(f"login success, {ret.text}")
124 | st.success(f"Login success, {username}")
125 | return True
126 |
127 | def _check_credentials(self, inplace: bool = True) -> bool:
128 | try:
129 | if self._check_pw():
130 | if inplace:
131 | self.exp_date = self._set_exp_date()
132 | self.token = self._token_encode()
133 | st.session_state['token'] = self.token
134 | self.cookie_manager.set(self.cookie_name, self.token,
135 | expires_at=datetime.now() + timedelta(days=self.cookie_expiry_days))
136 | st.session_state['authentication_status'] = True
137 | else:
138 | return True
139 | else:
140 | if inplace:
141 | st.session_state['authentication_status'] = False
142 | else:
143 | return False
144 | except Exception as e:
145 | logger.error(f"check credentials error, {e}")
146 |
147 | def login(self, form_name: str, location: str='main') -> tuple:
148 | """
149 | Creates a login widget.
150 |
151 | Parameters
152 | ----------
153 | form_name: str
154 | The rendered name of the login form.
155 | location: str
156 | The location of the login form i.e. main or sidebar.
157 | Returns
158 | -------
159 | str
160 | Name of the authenticated user.
161 | bool
162 | The status of authentication, None: no credentials entered,
163 | False: incorrect credentials, True: correct credentials.
164 | str
165 | Username of the authenticated user.
166 | """
167 | if location not in ['main', 'sidebar']:
168 | raise ValueError("Location must be one of 'main' or 'sidebar'")
169 | if not st.session_state['authentication_status']:
170 | self._check_cookie()
171 | if not st.session_state['authentication_status']:
172 | if location == 'main':
173 | login_form = st.form('Login')
174 | elif location == 'sidebar':
175 | login_form = st.sidebar.form('Login')
176 |
177 | login_form.subheader(form_name)
178 | self.username = login_form.text_input('Username')
179 | st.session_state['username'] = self.username
180 | self.password = login_form.text_input('Password', type='password')
181 |
182 | if login_form.form_submit_button('Login'):
183 | self._check_credentials()
184 |
185 | def logout(self, button_name: str, location: str='main', key: str=None):
186 | """
187 | Creates a logout button.
188 |
189 | Parameters
190 | ----------
191 | button_name: str
192 | The rendered name of the logout button.
193 | location: str
194 | The location of the logout button i.e. main or sidebar.
195 | """
196 | if location not in ['main', 'sidebar']:
197 | raise ValueError("Location must be one of 'main' or 'sidebar'")
198 | if location == 'main':
199 | if st.button(button_name, key):
200 | self.cookie_manager.delete(self.cookie_name)
201 | st.session_state['logout'] = True
202 | st.session_state['name'] = None
203 | st.session_state['username'] = None
204 | st.session_state['authentication_status'] = None
205 | elif location == 'sidebar':
206 | if st.sidebar.button(button_name, key):
207 | self.cookie_manager.delete(self.cookie_name)
208 | st.session_state['logout'] = True
209 | st.session_state['name'] = None
210 | st.session_state['username'] = None
211 | st.session_state['authentication_status'] = None
212 |
213 | def _check_cookie(self):
214 | """
215 | Checks the validity of the reauthentication cookie.
216 | """
217 | self.token = self.cookie_manager.get(self.cookie_name)
218 | if self.token is not None:
219 | self.token = self._token_decode()
220 | if self.token is not False:
221 | if not st.session_state['logout']:
222 | if self.token['exp_date'] > datetime.utcnow().timestamp():
223 | if 'name' and 'username' in self.token:
224 | st.session_state['name'] = self.token['name']
225 | st.session_state['username'] = self.token['username']
226 | st.session_state['authentication_status'] = True
227 |
228 | def _register_credentials(self, username: str, name: str, password: str, email: str, invite_code: str = ""):
229 | # register credentials to comfyflowapp
230 | if not self.validator.validate_username(username):
231 | raise RegisterError('Username is not valid')
232 | if not self.validator.validate_name(name):
233 | raise RegisterError('Name is not valid')
234 | if not self.validator.validate_email(email):
235 | raise RegisterError('Email is not valid')
236 | if not len(password) >= 8:
237 | raise RegisterError('Password is not valid, length > 8')
238 |
239 | # register user
240 | register_json = {
241 | "nickname": name,
242 | "username": username,
243 | "password": password,
244 | "email": email,
245 | "invite_code": invite_code
246 | }
247 | ret = requests.post(f"{self.comfyflow_url}/api/user/register", json=register_json)
248 | if ret.status_code != 200:
249 | raise RegisterError(f"register user error, {ret.text}")
250 | else:
251 | logger.info(f"register user success, {ret.json()}")
252 | st.success(f"Register user success, {username}")
253 |
254 |
255 | def register_user_info(self, form_name: str, location: str = 'main', data: dict={}) -> bool:
256 | if location not in ['main', 'sidebar']:
257 | raise ValueError("Location must be one of 'main' or 'sidebar'")
258 | if location == 'main':
259 | register_user_form = st.form('Register user')
260 | elif location == 'sidebar':
261 | register_user_form = st.sidebar.form('Register user')
262 |
263 | register_user_form.subheader(form_name)
264 | new_email = register_user_form.text_input('Email', value=data['email'], help='Please enter a valid email address')
265 | new_username = register_user_form.text_input('Username', value=data['username'], help='Please enter a username, 0-9, a-z, A-Z, -, _, max length 20')
266 | new_name = register_user_form.text_input('Name', value=data['username'],help='Please enter your name')
267 |
268 | new_password = register_user_form.text_input('Password', type='password')
269 | new_password_repeat = register_user_form.text_input('Repeat password', type='password')
270 |
271 | if register_user_form.form_submit_button('Register'):
272 | if len(new_email) and len(new_username) and len(new_name) and len(new_password) > 0:
273 | if new_username not in self.credentials['usernames']:
274 | if new_password == new_password_repeat:
275 | self._register_credentials(new_username, new_name, new_password, new_email)
276 | return True
277 | else:
278 | raise RegisterError('Passwords do not match')
279 | else:
280 | raise RegisterError('Username already taken')
281 | else:
282 | raise RegisterError('Please enter an email, username, name, and password')
283 |
284 |
285 |
286 | def register_user(self, form_name: str, location: str = 'main') -> bool:
287 | """
288 | Creates a register new user widget, add field: invite_code
289 |
290 | Parameters
291 | ----------
292 | form_name: str
293 | The rendered name of the register new user form.
294 | location: str
295 | The location of the register new user form i.e. main or sidebar.
296 | preauthorization: bool
297 | The preauthorization requirement, True: user must be preauthorized to register,
298 | False: any user can register.
299 | Returns
300 | -------
301 | bool
302 | The status of registering the new user, True: user registered successfully.
303 | """
304 | if location not in ['main', 'sidebar']:
305 | raise ValueError("Location must be one of 'main' or 'sidebar'")
306 | if location == 'main':
307 | register_user_form = st.form('Register user')
308 | elif location == 'sidebar':
309 | register_user_form = st.sidebar.form('Register user')
310 |
311 | register_user_form.subheader(form_name)
312 | new_email = register_user_form.text_input('Email', help='Please enter a valid email address')
313 | new_username = register_user_form.text_input('Username', help='Please enter a username')
314 | new_name = register_user_form.text_input('Name', help='Please enter your name')
315 | invite_code = register_user_form.text_input('Invite code', help='Please enter an invite code')
316 | new_password = register_user_form.text_input('Password', type='password')
317 | new_password_repeat = register_user_form.text_input('Repeat password', type='password')
318 |
319 | if register_user_form.form_submit_button('Register'):
320 | if len(new_email) and len(new_username) and len(new_name) and len(new_password) > 0:
321 | if new_username not in self.credentials['usernames']:
322 | if new_password == new_password_repeat:
323 | self._register_credentials(new_username, new_name, new_password, new_email, invite_code)
324 | return True
325 | else:
326 | raise RegisterError('Passwords do not match')
327 | else:
328 | raise RegisterError('Username already taken')
329 | else:
330 | raise RegisterError('Please enter an email, username, name, and password')
331 |
332 |
333 |
--------------------------------------------------------------------------------
/modules/comfyclient.py:
--------------------------------------------------------------------------------
1 | import json
2 | import uuid
3 | import requests
4 | import websocket
5 | from PIL import Image
6 | import io
7 | import threading
8 | from loguru import logger
9 | import urllib.parse as urlparse
10 |
11 |
12 | class ComfyClient:
13 | def __init__(self, server_addr) -> None:
14 | self.client_id = str(uuid.uuid4())
15 | self.server_addr = server_addr
16 | logger.info(f"Comfy client id: {self.client_id}")
17 |
18 | def get_node_class(self):
19 | object_info_url = f"{self.server_addr}/object_info"
20 | logger.info(f"Got object info from {object_info_url}")
21 | resp = requests.get(object_info_url)
22 | if resp.status_code != 200:
23 | raise Exception(f"Failed to get object info from {object_info_url}")
24 | return resp.json()
25 |
26 | def queue_remaining(self):
27 | """
28 | return:
29 | "exec_info": {
30 | "queue_remaining": 0
31 | }
32 | """
33 | url = f"{self.server_addr}/prompt"
34 | logger.info(f"Got remaining from {url}")
35 | resp = requests.get(url)
36 | if resp.status_code != 200:
37 | raise Exception(f"Failed to get queue from {url}")
38 | return resp.json()['exec_info']['queue_remaining']
39 |
40 | def queue_prompt(self, prompt):
41 | p = {"prompt": prompt, "client_id": self.client_id}
42 | data = json.dumps(p).encode('utf-8')
43 | logger.info(f"Sending prompt to server, {self.client_id}")
44 | resp = requests.post(f"{self.server_addr}/prompt", data=data)
45 | if resp.status_code != 200:
46 | raise Exception(f"Failed to send prompt to server, {resp.status_code}")
47 | return resp.json()
48 |
49 | def get_image(self, filename, subfolder, folder_type):
50 | url = f"{self.server_addr}/view?filename={filename}&subfolder={subfolder}&type={folder_type}"
51 | logger.info(f"Getting image from server, {url}")
52 | resp = requests.get(url)
53 | if resp.status_code != 200:
54 | raise Exception(f"Failed to get image from server, {resp.status_code}")
55 | return resp.content
56 |
57 | def get_image_url(self, filename, subfolder, folder_type):
58 | url = f"{self.server_addr}/view?filename={filename}&subfolder={subfolder}&type={folder_type}"
59 | logger.info(f"Getting image url, {url}")
60 | return url
61 |
62 | def upload_image(self, imagefile, subfolder, type, overwrite):
63 | data = {"subfolder": subfolder, "type": type, "overwrite": overwrite}
64 | logger.info(f"Uploading image to server, {data}")
65 | resp = requests.post(f"{self.server_addr}/upload/image", data=data, files=imagefile)
66 | if resp.status_code != 200:
67 | raise Exception(f"Failed to upload image to server, {resp.status_code}")
68 | return resp.json()
69 |
70 | def get_history(self, prompt_id):
71 | logger.info(f"Getting history from server, {prompt_id}")
72 | resp = requests.get(f"{self.server_addr}/history/{prompt_id}")
73 | if resp.status_code != 200:
74 | raise Exception(f"Failed to get history from server, {resp.status_code}")
75 | return resp.json()
76 |
77 |
78 | def gen_images(self, prompt, queue):
79 | logger.info(f"Generating images from comfyui, {prompt}")
80 | thread = threading.Thread(target=self._websocket_loop, args=(prompt, queue))
81 | thread.start()
82 |
83 | # queue prompt
84 | prompt_id = self.queue_prompt(prompt)['prompt_id']
85 | logger.info(f"Send prompt to comfyui, {prompt_id}")
86 |
87 | return prompt_id
88 |
89 | def _websocket_loop(self, prompt, queue):
90 | urlresult = urlparse.urlparse(self.server_addr)
91 | if urlresult.scheme == "http":
92 | wc_connect = "ws://{}/ws?clientId={}".format(urlresult.netloc, self.client_id)
93 | elif urlresult.scheme == "https":
94 | wc_connect = "wss://{}/ws?clientId={}".format(urlresult.netloc, self.client_id)
95 | logger.info(f"Websocket connect url, {wc_connect}")
96 | ws = websocket.WebSocket()
97 | ws.connect(wc_connect)
98 |
99 | def dispatch_event(queue, event):
100 | if queue is not None:
101 | event_type = event['type']
102 | if event_type == 'b_preview':
103 | logger.debug(f"Dispatch event, {event_type}")
104 | else:
105 | logger.debug(f"Dispatch event, {event}")
106 | queue.put(event)
107 | else:
108 | logger.info("queue is none")
109 |
110 | while True:
111 | out = ws.recv()
112 | try:
113 | if isinstance(out, str):
114 | msg = json.loads(out)
115 | msg_type = msg['type']
116 | logger.debug(f"Got message from websocket server, {msg_type}, {msg}")
117 | if msg_type == "status":
118 | if "sid" in msg.get("data"):
119 | self.client_id = msg["data"]["sid"]
120 | # Set window.name to self.client_id
121 | status_data = msg["data"]["status"]
122 | # Dispatch status event with status_data
123 | dispatch_event(queue, {"type": "status", "data": status_data})
124 | elif msg_type == "progress":
125 | # Dispatch progress event with msg["data"]
126 | dispatch_event(queue, {"type": "progress", "data": msg["data"]})
127 | elif msg_type == "executing":
128 | # Dispatch executing event with msg["data"]["node"]
129 | dispatch_event(queue, {"type": "executing", "data": msg["data"]["node"]})
130 | if msg["data"]["node"] is None:
131 | logger.info("workflow finished, exiting websocket loop")
132 | break
133 | elif msg_type == "executed":
134 | # Dispatch executed event with msg["data"]
135 | dispatch_event(queue, {"type": "executed", "data": msg["data"]})
136 | elif msg_type == "execution_start":
137 | # Dispatch execution_start event with msg["data"]
138 | dispatch_event(queue, {"type": "execution_start", "data": msg["data"]})
139 | elif msg_type == "execution_error":
140 | # Dispatch execution_error event with msg["data"]
141 | dispatch_event(queue, {"type": "execution_error", "data": msg["data"]})
142 | elif msg_type == "execution_cached":
143 | # Dispatch execution_cached event with msg["data"]
144 | dispatch_event(queue, {"type": "execution_cached", "data": msg["data"]})
145 | else:
146 | logger.warning(f"Unknown message type {msg_type}")
147 |
148 | elif isinstance(out, bytes):
149 | view = memoryview(out)
150 | event_type = int.from_bytes(view[:4], 'big')
151 | buffer = view[4:]
152 | if event_type == 1:
153 | view2 = memoryview(buffer)
154 | image_type = int.from_bytes(view2[:4], 'big')
155 | image_mime = ""
156 | if image_type == 1:
157 | image_mime = "image/jpeg"
158 | elif image_type == 2:
159 | image_mime = "image/png"
160 |
161 | image_blob = buffer[4:]
162 | logger.debug(f"Got binary websocket message of type {event_type}, {image_mime}, {len(image_blob)}")
163 | # Dispatch b_preview event with image_blob
164 | image = Image.open(io.BytesIO(image_blob))
165 | dispatch_event(queue, {"type": "b_preview", "data": image})
166 | else:
167 | logger.warning(f"Unknown binary websocket message of type {event_type}")
168 |
169 | except Exception as e:
170 | logger.error(f"Error while processing websocket message, {e}")
171 | raise e
172 |
--------------------------------------------------------------------------------
/modules/comfyflow.py:
--------------------------------------------------------------------------------
1 | from typing import Any
2 | import random
3 | import json
4 | import copy
5 | from PIL import Image
6 | from loguru import logger
7 | import queue
8 |
9 | import streamlit as st
10 | from streamlit_extras.row import row
11 | from modules.page import custom_text_area
12 |
13 | class Comfyflow:
14 | def __init__(self, comfy_client, api_data, app_data) -> Any:
15 |
16 | self.comfy_client = comfy_client
17 | self.api_json = json.loads(api_data)
18 | self.app_json = json.loads(app_data)
19 |
20 | def generate(self):
21 | prompt = copy.deepcopy(self.api_json)
22 | if prompt is not None:
23 | # update seed and noise_seed for random, if not set
24 | for node_id in prompt:
25 | node = prompt[node_id]
26 | node_inputs = node['inputs']
27 | for param_name in node_inputs:
28 | param_value = node_inputs[param_name]
29 | if isinstance(param_value, int):
30 | if (param_name == "seed" or param_name == "noise_seed"):
31 | random_value = random.randint(0, 0x7fffffffffffffff)
32 | prompt[node_id]['inputs'][param_name] = random_value
33 | logger.info(f"update prompt with random, {node_id} {param_name} {param_value} to {random_value}")
34 |
35 | # update prompt inputs with app_json config
36 | for node_id in self.app_json['inputs']:
37 | node = self.app_json['inputs'][node_id]
38 | node_inputs = node['inputs']
39 | for param_item in node_inputs:
40 | logger.info(f"update param {param_item}, {node_inputs[param_item]}")
41 | param_type = node_inputs[param_item]['type']
42 | if param_type == "TEXT":
43 | param_name = node_inputs[param_item]['name']
44 | param_key = f"{node_id}_{param_name}"
45 | param_value = st.session_state[param_key]
46 | logger.info(f"update param {param_key} {param_name} {param_value}")
47 | prompt[node_id]["inputs"][param_item] = param_value
48 |
49 | elif param_type == "NUMBER":
50 | param_name = node_inputs[param_item]['name']
51 | param_key = f"{node_id}_{param_name}"
52 | param_value = st.session_state[param_key]
53 | logger.info(f"update param {param_key} {param_name} {param_value}")
54 | prompt[node_id]["inputs"][param_item] = param_value
55 |
56 | elif param_type == "SELECT":
57 | param_name = node_inputs[param_item]['name']
58 | param_key = f"{node_id}_{param_name}"
59 | param_value = st.session_state[param_key]
60 | logger.info(f"update param {param_key} {param_name} {param_value}")
61 | prompt[node_id]["inputs"][param_item] = param_value
62 |
63 | elif param_type == "CHECKBOX":
64 | param_name = node_inputs[param_item]['name']
65 | param_key = f"{node_id}_{param_name}"
66 | param_value = st.session_state[param_key]
67 | logger.info(f"update param {param_key} {param_name} {param_value}")
68 | prompt[node_id]["inputs"][param_item] = param_value
69 |
70 | elif param_type == 'UPLOADIMAGE':
71 | param_name = node_inputs[param_item]['name']
72 | param_key = f"{node_id}_{param_name}"
73 | if param_key in st.session_state:
74 | param_value = st.session_state[param_key]
75 |
76 | logger.info(f"update param {param_key} {param_name} {param_value}")
77 | if param_value is not None:
78 | prompt[node_id]["inputs"][param_item] = param_value.name
79 | else:
80 | st.error(f"Please select input image for param {param_name}")
81 | return
82 | elif param_type == 'UPLOADVIDEO':
83 | param_name = node_inputs[param_item]['name']
84 | param_key = f"{node_id}_{param_name}"
85 | if param_key in st.session_state:
86 | param_value = st.session_state[param_key]
87 |
88 | logger.info(f"update param {param_key} {param_name} {param_value}")
89 | if param_value is not None:
90 | prompt[node_id]["inputs"][param_item] = param_value.name
91 | else:
92 | st.error(f"Please select input video for param {param_name}")
93 | return
94 |
95 | logger.info(f"Sending prompt to server, {prompt}")
96 | queue = st.session_state.get('progress_queue', None)
97 | try:
98 | prompt_id = self.comfy_client.gen_images(prompt, queue)
99 | st.session_state['preview_prompt_id'] = prompt_id
100 | logger.info(f"generate prompt id: {prompt_id}")
101 | except Exception as e:
102 | st.session_state['preview_prompt_id'] = None
103 | logger.warning(f"generate prompt error, {e}")
104 |
105 | def get_outputs(self):
106 | # get output images by prompt_id
107 | prompt_id = st.session_state['preview_prompt_id']
108 | if prompt_id is None:
109 | return None
110 | history = self.comfy_client.get_history(prompt_id)[prompt_id]
111 | for node_id in self.app_json['outputs']:
112 | node_output = history['outputs'][node_id]
113 | logger.info(f"Got output from server, {node_id}, {node_output}")
114 | if 'images' in node_output:
115 | images_output = []
116 | for image in node_output['images']:
117 | # image_url = self.comfy_client.get_image_url(image['filename'], image['subfolder'], image['type'])
118 | # images_output.append(image_url)
119 | image_data = self.comfy_client.get_image(image['filename'], image['subfolder'], image['type'])
120 | images_output.append(image_data)
121 |
122 | logger.info(f"Got images from server, {node_id}, {len(images_output)}")
123 | return 'images', images_output
124 | elif 'gifs' in node_output:
125 | gifs_output = []
126 | format = 'gifs'
127 | for gif in node_output['gifs']:
128 | if gif['format'] == 'image/gif' or gif['format'] == 'image/webp':
129 | format = 'images'
130 | gif_url = self.comfy_client.get_image_url(gif['filename'], gif['subfolder'], gif['type'])
131 | gifs_output.append(gif_url)
132 |
133 | logger.info(f"Got gifs from server, {node_id}, {len(gifs_output)}")
134 | return format, gifs_output
135 |
136 |
137 | def create_ui_input(self, node_id, node_inputs):
138 | def random_seed(param_key):
139 | random_value = random.randint(0, 0x7fffffffffffffff)
140 | st.session_state[param_key] = random_value
141 | logger.info(f"update {param_key} with random {random_value}")
142 |
143 | custom_text_area()
144 | for param_item in node_inputs:
145 | param_node = node_inputs[param_item]
146 | logger.info(f"create ui input: {param_item} {param_node}")
147 | param_type = param_node['type']
148 | if param_type == "TEXT":
149 | param_name = param_node['name']
150 | param_default = param_node['default']
151 | param_help = param_node['help']
152 | param_max = param_node['max']
153 |
154 | param_key = f"{node_id}_{param_name}"
155 | st.text_area(param_name, value =param_default, key=param_key, help=param_help, max_chars=param_max, height=500)
156 | elif param_type == "NUMBER":
157 | param_name = param_node['name']
158 | param_default = param_node['default']
159 | param_help = param_node['help']
160 | param_min = param_node['min']
161 | param_max = param_node['max']
162 | param_step = param_node['step']
163 |
164 | param_key = f"{node_id}_{param_name}"
165 | if param_item == 'seed' or param_item == 'noise_seed':
166 | seed_row = row([0.8, 0.2], vertical_align="bottom")
167 | seed_row.number_input(param_name, value =param_default, key=param_key, help=param_help, min_value=param_min, step=param_step)
168 | seed_row.button("Rand", on_click=random_seed, args=(param_key,))
169 | else:
170 | st.number_input(param_name, value =param_default, key=param_key, help=param_help, min_value=param_min, max_value=param_max, step=param_step)
171 | elif param_type == "SELECT":
172 | param_name = param_node['name']
173 | if 'default' in param_node:
174 | param_default = param_node['default']
175 | else:
176 | param_default = param_node['options'][0]
177 | param_help = param_node['help']
178 | param_options = param_node['options']
179 |
180 | param_key = f"{node_id}_{param_name}"
181 | st.selectbox(param_name, options=param_options, key=param_key, help=param_help)
182 |
183 | elif param_type == "CHECKBOX":
184 | param_name = param_node['name']
185 | param_default = param_node['default']
186 | param_help = param_node['help']
187 |
188 | param_key = f"{node_id}_{param_name}"
189 | st.checkbox(param_name, value=param_default, key=param_key, help=param_help)
190 | elif param_type == 'UPLOADIMAGE':
191 | param_name = param_node['name']
192 | param_help = param_node['help']
193 | param_subfolder = param_node.get('subfolder', '')
194 | param_key = f"{node_id}_{param_name}"
195 | uploaded_file = st.file_uploader(param_name, help=param_help, key=param_key, type=['png', 'jpg', 'jpeg'], accept_multiple_files=False)
196 | if uploaded_file is not None:
197 | logger.info(f"uploading image, {uploaded_file}")
198 | # upload to server
199 | upload_type = "input"
200 | imagefile = {'image': (uploaded_file.name, uploaded_file)} # 替换为要上传的文件名和路径
201 | self.comfy_client.upload_image(imagefile, param_subfolder, upload_type, 'true')
202 |
203 | # show image preview
204 | image = Image.open(uploaded_file)
205 | st.image(image, use_column_width=True, caption='Input Image')
206 | elif param_type == 'UPLOADVIDEO':
207 | param_name = param_node['name']
208 | param_help = param_node['help']
209 | param_subfolder = param_node.get('subfolder', '')
210 | param_key = f"{node_id}_{param_name}"
211 | uploaded_file = st.file_uploader(param_name, help=param_help, key=param_key, type=['mp4', "h264"], accept_multiple_files=False)
212 | if uploaded_file is not None:
213 | logger.info(f"uploading image, {uploaded_file}")
214 | # upload to server
215 | upload_type = "input"
216 | imagefile = {'image': (uploaded_file.name, uploaded_file)} # 替换为要上传的文件名和路径
217 | self.comfy_client.upload_image(imagefile, param_subfolder, upload_type, 'true')
218 |
219 | # show video preview
220 | st.video(uploaded_file, format="video/mp4", start_time=0)
221 |
222 | def create_ui(self, show_header=True):
223 | logger.info("Creating UI")
224 |
225 | if 'progress_queue' not in st.session_state:
226 | st.session_state['progress_queue'] = queue.Queue()
227 |
228 | app_name = self.app_json['name']
229 | app_description = self.app_json['description']
230 | if show_header:
231 | st.title(f'{app_name}')
232 | st.markdown(f'{app_description}')
233 | st.divider()
234 |
235 | input_col, _, output_col, _ = st.columns([0.45, 0.05, 0.5, 0.1], gap="medium")
236 | with input_col:
237 | # st.subheader('Inputs')
238 | with st.container():
239 | logger.info(f"app_data: {self.app_json}")
240 | for node_id in self.app_json['inputs']:
241 | node = self.app_json['inputs'][node_id]
242 | node_inputs = node['inputs']
243 | self.create_ui_input(node_id, node_inputs)
244 |
245 | gen_button = st.button(label='Generate', use_container_width=True, on_click=self.generate)
246 |
247 |
248 | with output_col:
249 | # st.subheader('Outputs')
250 | with st.container():
251 | node_size = len(self.api_json)
252 | executed_nodes = []
253 | queue_remaining = self.comfy_client.queue_remaining()
254 | output_queue_remaining = st.text(f"Queue: {queue_remaining}")
255 | progress_placeholder = st.empty()
256 | img_placeholder = st.empty()
257 | if gen_button:
258 | if st.session_state['preview_prompt_id'] is None:
259 | st.warning("Generate failed, please check ComfyFlowApp and ComfyUI console log.")
260 | st.stop()
261 |
262 | # update progress
263 | output_progress = progress_placeholder.progress(value=0.0, text="Generate image")
264 | while True:
265 | try:
266 | progress_queue = st.session_state.get('progress_queue')
267 | event = progress_queue.get()
268 | logger.debug(f"event: {event}")
269 |
270 | event_type = event['type']
271 | if event_type == 'status':
272 | remaining = event['data']['exec_info']['queue_remaining']
273 | output_queue_remaining.text(f"Queue: {remaining}")
274 | elif event_type == 'execution_cached':
275 | executed_nodes.extend(event['data']['nodes'])
276 | output_progress.progress(len(executed_nodes)/node_size, text="Generate image...")
277 | elif event_type == 'executing':
278 | node = event['data']
279 | if node is None:
280 | type, outputs = self.get_outputs()
281 | if type == 'images' and outputs is not None:
282 | img_placeholder.image(outputs, use_column_width=True)
283 | elif type == 'gifs' and outputs is not None:
284 | for output in outputs:
285 | img_placeholder.markdown(f'', unsafe_allow_html=True)
286 |
287 | output_progress.progress(1.0, text="Generate finished")
288 | logger.info("Generating finished")
289 | st.session_state[f'{app_name}_previewed'] = True
290 | break
291 | else:
292 | executed_nodes.append(node)
293 | output_progress.progress(len(executed_nodes)/node_size, text="Generating image...")
294 | elif event_type == 'b_preview':
295 | preview_image = event['data']
296 | img_placeholder.image(preview_image, use_column_width=True, caption="Preview")
297 | except Exception as e:
298 | logger.warning(f"get progress exception, {e}")
299 | # st.warning(f"get progress exception {e}")
300 | else:
301 | output_image = Image.open('./public/images/output-none.png')
302 | logger.info("default output")
303 | img_placeholder.image(output_image, use_column_width=True, caption='None Image, Generate it!')
304 |
--------------------------------------------------------------------------------
/modules/myapp_model.py:
--------------------------------------------------------------------------------
1 | from loguru import logger
2 | import base64
3 | import streamlit as st
4 | from sqlalchemy import text
5 | from modules import AppStatus
6 |
7 | """
8 | my_apps table
9 | id TEXT
10 | name TEXT
11 | description TEXT
12 | image TEXT
13 | app_conf TEXT
14 | api_conf TEXT
15 | template TEXT
16 | status TEXT
17 | created_at TEXT
18 | updated_at TEXT
19 | """
20 |
21 | class MyAppModel:
22 | def __init__(self) -> None:
23 | self.db_conn = st.connection('comfyflow_db', type='sql')
24 | self.app_table_name = 'my_apps'
25 | self._init_table()
26 | logger.debug(f"db_conn: {self.db_conn}, app_table_name: {self.app_table_name}")
27 |
28 | @property
29 | def session(self):
30 | return self.db_conn.session
31 |
32 | def _init_table(self):
33 | # Create a table if it doesn't exist.
34 | with self.session as s:
35 | sql = text(f'CREATE TABLE IF NOT EXISTS {self.app_table_name} (id TEXT PRIMARY KEY, name TEXT, description TEXT, image TEXT, app_conf TEXT, api_conf TEXT, template TEXT, url TEXT, status TEXT, created_at TEXT, updated_at TEXT);')
36 | s.execute(sql)
37 |
38 | # create index on name
39 | sql = text(f'CREATE INDEX IF NOT EXISTS {self.app_table_name}_name_index ON {self.app_table_name} (name);')
40 | s.execute(sql)
41 | s.commit()
42 | logger.info(f"init app table {self.app_table_name} and index")
43 |
44 | def sync_apps(self, apps):
45 |
46 | with self.session as s:
47 | # reset local apps
48 | sql = text(f'SELECT id, status FROM {self.app_table_name} where status!=:status order by id;')
49 | local_apps = s.execute(sql, dict(status=AppStatus.INSTALLED.value)).fetchall()
50 | delete_apps = []
51 | for app in local_apps:
52 | delete_apps.append(app.id)
53 | self.delete_app_by_id(app.id)
54 | logger.info(f"reset local apps, {delete_apps}")
55 |
56 | # sync apps from comfyflow.app
57 | with self.session as s:
58 | sql = text(f'SELECT id, status FROM {self.app_table_name} order by id;')
59 | local_apps = s.execute(sql).fetchall()
60 | local_app_ids = {app.id: app for app in local_apps}
61 | sync_apps = []
62 | for app in apps:
63 | # convert base64 image to bytes
64 | base64_data = app['image'].split(',')[-1]
65 | image_bytes = base64.b64decode(base64_data)
66 |
67 | if app['id'] in local_app_ids:
68 | if local_app_ids[app['id']].status == AppStatus.PUBLISHED.value:
69 | # update app
70 | sql = text(f'UPDATE {self.app_table_name} SET name=:name, description=:description, image=:image, template=:template, status=:status, updated_at=datetime("now") WHERE id=:id;')
71 | s.execute(sql, dict(id=app['id'], name=app['name'], description=app['description'], image=image_bytes, template=app['template'], status=AppStatus.PUBLISHED.value))
72 | s.commit()
73 | sync_apps.append(app['name'])
74 | logger.info(f"update app {app['name']} to my apps")
75 | else:
76 | # insert app
77 | sql = text(f'INSERT INTO {self.app_table_name} (id, name, description, image, template, status, created_at, updated_at) VALUES (:id, :name, :description, :image, :template, :status, datetime("now"), datetime("now") );')
78 | s.execute(sql, dict(id=app['id'], name=app['name'], description=app['description'], image=image_bytes, template=app['template'], status=AppStatus.PUBLISHED.value))
79 | s.commit()
80 | sync_apps.append(app['name'])
81 | logger.info(f"insert app {app['name']} my apps")
82 | logger.info(f"sync apps from comfyflow.app, {sync_apps}")
83 | return sync_apps
84 |
85 | def get_all_apps(self):
86 | with self.session as s:
87 | logger.info("get apps from db")
88 | sql = text(f'SELECT id, name, description, image, app_conf, api_conf, endpoint, template, url, status, username FROM {self.app_table_name} order by id desc;')
89 | apps = s.execute(sql).fetchall()
90 | return apps
91 |
92 | def get_my_installed_apps(self):
93 | # get installed apps
94 | with self.session as s:
95 | logger.debug("get my apps from db")
96 | sql = text(f'SELECT id, name, description, image, app_conf, api_conf, template, url, status, username FROM {self.app_table_name} WHERE status=:status order by id desc;')
97 | apps = s.execute(sql, {'status': AppStatus.INSTALLED.value}).fetchall()
98 | return apps
99 |
100 | def get_app(self, name):
101 | with self.session as s:
102 | logger.debug(f"get app by name: {name}")
103 | sql = text(f'SELECT * FROM {self.app_table_name} WHERE name=:name;')
104 | app = s.execute(sql, {'name': name}).fetchone()
105 | return app
106 |
107 | def get_app_by_id(self, id):
108 | with self.session as s:
109 | logger.debug(f"get app by id: {id}")
110 | sql = text(f'SELECT * FROM {self.app_table_name} WHERE id=:id;')
111 | app = s.execute(sql, {'id': id}).fetchone()
112 | return app
113 |
114 | def delete_app(self, name):
115 | with self.session as s:
116 | logger.info(f"delete app: {name}")
117 | sql = text(f'DELETE FROM {self.app_table_name} WHERE name=:name;')
118 | s.execute(sql, dict(name=name))
119 | s.commit()
120 |
121 | def delete_app_by_id(self, id):
122 | with self.session as s:
123 | logger.info(f"delete app: {id}")
124 | sql = text(f'DELETE FROM {self.app_table_name} WHERE id=:id;')
125 | s.execute(sql, dict(id=id))
126 | s.commit()
127 |
128 | def update_app_status(self, id, status):
129 | with self.session as s:
130 | logger.info(f"update app status: {id}, {status}")
131 | sql = text(f'UPDATE {self.app_table_name} SET status=:status WHERE id=:id;')
132 | s.execute(sql, dict(id=id, status=status))
133 | s.commit()
134 |
135 | def update_api_conf(self, id, api_conf):
136 | with self.session as s:
137 | logger.info(f"update app api_conf: {id}, {api_conf}")
138 | sql = text(f'UPDATE {self.app_table_name} SET api_conf=:api_conf WHERE id=:id;')
139 | s.execute(sql, dict(id=id, api_conf=api_conf))
140 | s.commit()
141 |
142 | def update_app_conf(self, id, app_conf):
143 | with self.session as s:
144 | logger.info(f"update app app_conf: {id}, {app_conf}")
145 | sql = text(f'UPDATE {self.app_table_name} SET app_conf=:app_conf WHERE id=:id;')
146 | s.execute(sql, dict(id=id, app_conf=app_conf))
147 | s.commit()
148 |
149 |
--------------------------------------------------------------------------------
/modules/new_app.py:
--------------------------------------------------------------------------------
1 | from loguru import logger
2 | from PIL import Image, ImageOps
3 | from io import BytesIO
4 | import json
5 | import streamlit as st
6 | import modules.page as page
7 | from streamlit_extras.row import row
8 | from modules import get_comfyui_object_info, get_workspace_model, check_comfyui_alive
9 |
10 | NODE_SEP = '||'
11 | FAQ_URL = "https://github.com/xingren23/ComfyFlowApp/wiki/FAQ"
12 | SUPPORTED_COMFYUI_CLASSTYPE_OUTPUT = ['PreviewImage', 'SaveImage', 'SaveAnimatedWEBP', 'SaveAnimatedPNG', 'VHS_VideoCombine']
13 |
14 | def format_input_node_info(param):
15 | # format {id}.{class_type}.{alias}.{param_name}
16 | params_inputs = st.session_state.get('create_prompt_inputs', {})
17 | params_value = params_inputs[param]
18 | logger.debug(f"format_input_node_info, {param} {params_value}")
19 | node_id, class_type, param_name, param_value = params_value.split(NODE_SEP)
20 | return f"{node_id}:{class_type}:{param_name}:{param_value}"
21 |
22 | def format_output_node_info(param):
23 | # format {id}.{class_type}
24 | params_outputs = st.session_state.get('create_prompt_outputs', {})
25 | params_value = params_outputs[param]
26 | logger.debug(f"format_output_node_info, {param} {params_value}")
27 | node_id, class_type, input_values = params_value.split(NODE_SEP)
28 | return f"{node_id}:{class_type}:{input_values}"
29 |
30 | def process_workflow_meta(image_upload):
31 | # parse meta data from image, save image to local
32 | try:
33 | logger.info(f"process_workflow_meta, {image_upload}")
34 | img = Image.open(image_upload)
35 | tran_img = ImageOps.exif_transpose(img)
36 | logger.debug(f"process_workflow_meta, {tran_img.info.get('workflow')} {tran_img.info.get('prompt')}")
37 | return tran_img.info
38 | except Exception as e:
39 | logger.error(f"process_workflow_meta error, {e}")
40 | return None
41 |
42 |
43 | def parse_prompt(prompt_info, object_info_meta):
44 | # parse prompt to inputs and outputs
45 | try:
46 | prompt = json.loads(prompt_info)
47 | params_inputs = {}
48 | params_outputs = {}
49 | for node_id in prompt:
50 | node = prompt[node_id]
51 | class_type = prompt[node_id]['class_type']
52 | node_inputs = []
53 | for param in node['inputs']:
54 | param_value = node['inputs'][param]
55 | option_key = f"{node_id}{NODE_SEP}{param}"
56 | option_value = f"{node_id}{NODE_SEP}{class_type}{NODE_SEP}{param}{NODE_SEP}{param_value}"
57 | logger.debug(f"parse_prompt, {option_key} {option_value}")
58 | # check param_value is []
59 | if isinstance(param_value, list):
60 | logger.debug(f"ignore {option_key}, param_value is list, {param_value}")
61 | continue
62 | if param == "choose file to upload":
63 | logger.debug(f"ignore {option_key}, param for 'choose file to upload'")
64 | continue
65 |
66 | params_inputs.update({option_key: option_value})
67 | node_inputs.append(param_value)
68 |
69 | is_output = object_info_meta[class_type]['output_node']
70 | if is_output:
71 | # TODO: support multi output
72 | if class_type in SUPPORTED_COMFYUI_CLASSTYPE_OUTPUT:
73 | option_key = f"{node_id}{NODE_SEP}{class_type}"
74 | if len(node_inputs) == 0:
75 | option_value = f"{node_id}{NODE_SEP}{class_type}{NODE_SEP}None"
76 | else:
77 | option_value = f"{node_id}{NODE_SEP}{class_type}{NODE_SEP}{node_inputs}"
78 | params_outputs.update({option_key: option_value})
79 | else:
80 | logger.warning(f"Only support SaveImage as output node, {class_type}")
81 |
82 | return (params_inputs, params_outputs)
83 | except Exception as e:
84 | st.error(f"parse_prompt error, {e} refer to {FAQ_URL}")
85 | return (None, None)
86 |
87 |
88 | def process_image_change():
89 | comfyui_object_info = st.session_state.get('comfyui_object_info')
90 | upload_image = st.session_state['create_upload_image']
91 | if upload_image:
92 | metas = process_workflow_meta(upload_image)
93 | if metas and 'prompt' in metas.keys() and 'workflow' in metas.keys():
94 | st.session_state['create_prompt'] = metas.get('prompt')
95 | st.session_state['create_workflow'] = metas.get('workflow')
96 | inputs, outputs = parse_prompt(metas.get('prompt'), comfyui_object_info)
97 | if inputs:
98 | logger.info(f"create_prompt_inputs, {inputs}")
99 | st.success(f"parse inputs from workflow image, input nodes {len(inputs)}")
100 | st.session_state['create_prompt_inputs'] = inputs
101 | else:
102 | st.error(f"parse workflow from image error, inputs is None, refer to {FAQ_URL}")
103 |
104 | if outputs:
105 | logger.info(f"create_prompt_outputs, {outputs}")
106 | st.success(f"parse outputs from workflow image, output nodes {len(outputs)}")
107 | st.session_state['create_prompt_outputs'] = outputs
108 | else:
109 | st.error(f"parse workflow from image error, outputs is None, refer to {FAQ_URL}")
110 |
111 | else:
112 | st.error(f"the image don't contain workflow info, refer to {FAQ_URL}")
113 | else:
114 | st.session_state['create_prompt'] = None
115 | st.session_state['create_workflow'] = None
116 | st.session_state['create_prompt_inputs'] = {}
117 | st.session_state['create_prompt_outputs'] = {}
118 |
119 | def process_image_edit(api_prompt):
120 | comfyui_object_info = st.session_state.get('comfyui_object_info')
121 | if api_prompt:
122 | st.session_state['create_prompt'] =api_prompt
123 | inputs, outputs = parse_prompt(api_prompt, comfyui_object_info)
124 | if inputs:
125 | logger.info(f"create_prompt_inputs, {inputs}")
126 | st.success(f"parse inputs from workflow image, input nodes {len(inputs)}")
127 | st.session_state['create_prompt_inputs'] = inputs
128 | else:
129 | st.error(f"parse workflow from image error, inputs is None, refer to {FAQ_URL}")
130 |
131 | if outputs:
132 | logger.info(f"create_prompt_outputs, {outputs}")
133 | st.success(f"parse outputs from workflow image, output nodes {len(outputs)}")
134 | st.session_state['create_prompt_outputs'] = outputs
135 | else:
136 | st.error(f"parse workflow from image error, outputs is None, refer to {FAQ_URL}")
137 | else:
138 | st.error(f"the image don't contain workflow info, refer to {FAQ_URL}")
139 |
140 |
141 | def get_node_input_config(input_param, app_input_name, app_input_description):
142 | params_inputs = st.session_state.get('create_prompt_inputs', {})
143 | option_params_value = params_inputs[input_param]
144 | logger.debug(f"get_node_input_config, {input_param} {option_params_value}")
145 | node_id, class_type, param, param_value = option_params_value.split(NODE_SEP)
146 | comfyui_object_info = st.session_state.get('comfyui_object_info')
147 | class_meta = comfyui_object_info[class_type]
148 | class_input = class_meta['input']['required']
149 | if 'optional' in class_meta['input'].keys():
150 | class_input.update(class_meta['input']['optional'])
151 |
152 | logger.debug(f"{node_id} {class_type} {param} {param_value}, class input {class_input}")
153 |
154 | input_config = {}
155 | if isinstance(class_input[param][0], str):
156 |
157 | if class_input[param][0] == 'STRING':
158 | input_config = {
159 | "type": "TEXT",
160 | "name": app_input_name,
161 | "help": app_input_description,
162 | "default": str(param_value),
163 | "max": 500,
164 | }
165 | elif class_input[param][0] == 'INT':
166 | defaults = class_input[param][1]
167 | input_config = {
168 | "type": "NUMBER",
169 | "name": app_input_name,
170 | "help": app_input_description,
171 | "default": int(param_value),
172 | "min": defaults.get('min', 0),
173 | "max": min(defaults.get('max', 100), 4503599627370496),
174 | "step": defaults.get('step', 1),
175 | }
176 | elif class_input[param][0] == 'FLOAT':
177 | defaults = class_input[param][1]
178 | input_config = {
179 | "type": "NUMBER",
180 | "name": app_input_name,
181 | "help": app_input_description,
182 | "default": float(param_value),
183 | "min": defaults.get('min', 0),
184 | "max": min(defaults.get('max', 100), 4503599627370496),
185 | "step": defaults.get('step', 1),
186 | }
187 | elif class_input[param][0] == 'BOOLEAN':
188 | defaults = class_input[param][1]
189 | input_config = {
190 | "type": "CHECKBOX",
191 | "name": app_input_name,
192 | "help": app_input_description,
193 | "default": param_value,
194 | }
195 | elif isinstance(class_input[param][0], list):
196 | if class_type == 'LoadImage' and param == 'image':
197 | input_config = {
198 | "type": "UPLOADIMAGE",
199 | "name": app_input_name,
200 | "help": app_input_description,
201 | }
202 | elif class_type == 'VHS_LoadVideo' and param == 'video':
203 | input_config = {
204 | "type": "UPLOADVIDEO",
205 | "name": app_input_name,
206 | "help": app_input_description,
207 | }
208 | else:
209 | input_config = {
210 | "type": "SELECT",
211 | "name": app_input_name,
212 | "help": app_input_description,
213 | "options": class_input[param][0],
214 | }
215 | return node_id, param, input_config
216 |
217 |
218 | def get_node_output_config(output_param):
219 | params_outputs = st.session_state.get('create_prompt_outputs', {})
220 | output_param_value = params_outputs[output_param]
221 | node_id, class_type, param = output_param_value.split(NODE_SEP)
222 | output_param_inputs = {
223 | "outputs": {
224 | }
225 | }
226 | return node_id, output_param_inputs
227 |
228 |
229 | def gen_app_config():
230 | prompt = st.session_state['create_prompt']
231 | input_param1 = st.session_state['input_param1']
232 | input_param1_name = st.session_state['input_param1_name']
233 | input_param1_desc = st.session_state['input_param1_desc']
234 | output_param1 = st.session_state['output_param1']
235 | app_name = st.session_state['create_app_name']
236 | app_description = st.session_state['create_app_description']
237 | logger.info(f"gen_app_config, {prompt} {input_param1} {output_param1} {app_name} {app_description}")
238 | if prompt and input_param1 and output_param1 and app_name and app_description:
239 | # gen and upload app.json
240 | app_config = {
241 | "name": app_name,
242 | "description": app_description,
243 | "inputs": {},
244 | "outputs": {}
245 | }
246 | # parse input_param1
247 | node_id, param, input_param1_inputs = get_node_input_config(
248 | input_param1, input_param1_name, input_param1_desc)
249 | if node_id not in app_config['inputs'].keys():
250 | app_config['inputs'][node_id] = {"inputs": {}}
251 | app_config['inputs'][node_id]['inputs'][param] = input_param1_inputs
252 |
253 | # parse input_param2
254 | input_param2 = st.session_state['input_param2']
255 | input_param2_name = st.session_state['input_param2_name']
256 | input_param2_desc = st.session_state['input_param2_desc']
257 | if input_param2:
258 | node_id, param, input_param2_inputs = get_node_input_config(
259 | input_param2, input_param2_name, input_param2_desc)
260 | if node_id not in app_config['inputs'].keys():
261 | app_config['inputs'][node_id] = {"inputs": {}}
262 | app_config['inputs'][node_id]['inputs'][param] = input_param2_inputs
263 |
264 | # parse input_param3
265 | input_param3 = st.session_state['input_param3']
266 | input_param3_name = st.session_state['input_param3_name']
267 | input_param3_desc = st.session_state['input_param3_desc']
268 | if input_param3:
269 | node_id, param, input_param3_inputs = get_node_input_config(
270 | input_param3, input_param3_name, input_param3_desc)
271 | if node_id not in app_config['inputs'].keys():
272 | app_config['inputs'][node_id] = {"inputs": {}}
273 | app_config['inputs'][node_id]['inputs'][param] = input_param3_inputs
274 |
275 | # parse output_param1
276 | node_id, output_param1_inputs = get_node_output_config(output_param1)
277 | app_config['outputs'][node_id] = output_param1_inputs
278 | return app_config
279 |
280 |
281 | def submit_app():
282 | app_config = gen_app_config()
283 | if app_config:
284 | # check user login
285 | if not st.session_state.get('username'):
286 | st.warning("Please go to homepage for your login :point_left:")
287 | st.stop()
288 |
289 | # submit to sqlite
290 | if get_workspace_model().get_app(app_config['name']):
291 | st.session_state['create_submit_info'] = "exist"
292 | else:
293 | # resize image
294 | img = Image.open(st.session_state['create_upload_image'])
295 | img = img.resize((64,64))
296 | img_bytesio = BytesIO()
297 | img.save(img_bytesio, format="PNG")
298 |
299 | app = {}
300 | app['name'] = app_config['name']
301 | app['description'] = app_config['description']
302 | app['app_conf'] = json.dumps(app_config)
303 | app['api_conf'] = st.session_state['create_prompt']
304 | app['workflow_conf'] = st.session_state['create_workflow']
305 | app['status'] = 'created'
306 | app['template'] = 'default'
307 | app['image'] = img_bytesio.getvalue()
308 | app['username'] = st.session_state['username']
309 | get_workspace_model().create_app(app)
310 |
311 | logger.info(f"submit app successfully, {app_config['name']}")
312 | st.session_state['create_submit_info'] = "success"
313 | else:
314 | logger.info(f"submit app error, {app_config['name']}")
315 | st.session_state['create_submit_info'] = "error"
316 |
317 | def save_app(app):
318 | app_config = gen_app_config()
319 | if app_config:
320 | get_workspace_model().edit_app(app.id, app_config['name'], app_config['description'],
321 | json.dumps(app_config))
322 |
323 | logger.info(f"save app successfully, {app_config['name']}")
324 | st.session_state['save_submit_info'] = "success"
325 | else:
326 | logger.info(f"save app error, {app_config['name']}")
327 | st.session_state['save_submit_info'] = "error"
328 |
329 | def check_app_name():
330 | app_name_text = st.session_state['create_app_name']
331 | app = get_workspace_model().get_app(app_name_text)
332 | if app:
333 | st.session_state['create_exist_app_name'] = True
334 | else:
335 | st.session_state['create_exist_app_name'] = False
336 |
337 | def on_edit_workspace():
338 | st.session_state.pop('edit_app', None)
339 | logger.info("back to workspace")
340 |
341 | def edit_app_ui(app):
342 | with page.stylable_button_container():
343 | header_row = row([0.85, 0.15], vertical_align="top")
344 | header_row.title("🌱 Edit app")
345 | header_row.button("Back Workspace", help="Back to your workspace", key="edit_back_workspace", on_click=on_edit_workspace)
346 |
347 | try:
348 | if not check_comfyui_alive():
349 | logger.warning("ComfyUI server is not alive, please check it")
350 | st.error(f"Edit app {app.name} error, ComfyUI server is not alive")
351 | st.stop()
352 |
353 | comfyui_object_info = get_comfyui_object_info()
354 | st.session_state['comfyui_object_info'] = comfyui_object_info
355 | except Exception as e:
356 | st.error(f"connect to comfyui node error, {e}")
357 | st.stop()
358 |
359 | # upload workflow image and config params
360 | with st.expander("### :one: Upload image of comfyui workflow", expanded=True):
361 | image_col1, image_col2 = st.columns([0.5, 0.5])
362 |
363 | process_image_edit(app.api_conf)
364 |
365 | with image_col2:
366 | image_icon = BytesIO(app.image)
367 | input_params = st.session_state.get('create_prompt_inputs')
368 | output_params = st.session_state.get('create_prompt_outputs')
369 | if image_icon and input_params and output_params:
370 | logger.debug(f"input_params: {input_params}, output_params: {output_params}")
371 | _, image_col, _ = st.columns([0.2, 0.6, 0.2])
372 | with image_col:
373 | st.image(image_icon, use_column_width=True, caption='ComfyUI Image with workflow info')
374 | else:
375 | st.warning("Can't load comfyui workflow image")
376 |
377 |
378 | with st.expander("### :two: Config params of app", expanded=True):
379 | app_conf = json.loads(app.app_conf)
380 |
381 | with st.container():
382 | name_col1, desc_col2 = st.columns([0.2, 0.8])
383 | with name_col1:
384 | st.text_input("App Name *", value=app.name, placeholder="input app name",
385 | key="create_app_name", help="Input app name")
386 |
387 | with desc_col2:
388 | st.text_input("App Description *", value=app.description, placeholder="input app description",
389 | key="create_app_description", help="Input app description")
390 |
391 | with st.container():
392 |
393 | st.markdown("Input Params:")
394 | params_inputs = st.session_state.get('create_prompt_inputs', {})
395 | params_inputs_options = list(params_inputs.keys())
396 |
397 | input_params = []
398 | for node_id in app_conf['inputs']:
399 | node_inputs = app_conf['inputs'][node_id]['inputs']
400 | for param in node_inputs:
401 | param_name = node_inputs[param]['name']
402 | param_help = node_inputs[param]['help']
403 |
404 | param = {
405 | 'index': f"{node_id}{NODE_SEP}{param}",
406 | 'name': param_name,
407 | 'help': param_help,
408 | }
409 | input_params.append(param)
410 |
411 | logger.info(f"params_inputs_options {params_inputs_options}, input_params: {input_params}")
412 |
413 | if len(input_params) > 0:
414 | input_param = input_params[0]
415 | add_input_config_param(params_inputs_options, 1, input_param)
416 | else:
417 | add_input_config_param(params_inputs_options, 1, None)
418 |
419 | if len(input_params) > 1:
420 | input_param_2 = input_params[1]
421 | add_input_config_param(params_inputs_options, 2, input_param_2)
422 | else:
423 | add_input_config_param(params_inputs_options, 2, None)
424 |
425 | if len(input_params) > 2:
426 | input_param_3 = input_params[2]
427 | add_input_config_param(params_inputs_options, 3, input_param_3)
428 | else:
429 | add_input_config_param(params_inputs_options, 3, None)
430 |
431 | with st.container():
432 |
433 | st.markdown("Output Params:")
434 | params_outputs = st.session_state.get('create_prompt_outputs', {})
435 | params_outputs_options = list(params_outputs.keys())
436 |
437 | output_params = []
438 | for node_id in app_conf['outputs']:
439 | node_inputs = app_conf['outputs'][node_id]['outputs']
440 | for param in node_inputs:
441 | param_name = node_inputs[param]['name']
442 | param_help = node_inputs[param]['help']
443 |
444 | param = {
445 | 'index': f"{node_id}{NODE_SEP}{param}",
446 | 'name': param_name,
447 | 'help': param_help,
448 | }
449 | input_params.append(param)
450 |
451 | if len(output_params) > 0:
452 | output_param_1 = output_params[0]
453 | add_output_config_param(params_outputs_options, 1, output_param_1)
454 | else:
455 | add_output_config_param(params_outputs_options, 1, None)
456 |
457 | with st.container():
458 | operation_row = row([0.15, 0.7, 0.15])
459 | submit_button = operation_row.button("Save", key='edit_submit_app', type="primary",
460 | use_container_width=True,
461 | help="Save app params",on_click=save_app, args=(app,))
462 | if submit_button:
463 | submit_info = st.session_state.get('save_submit_info')
464 | if submit_info == 'success':
465 | st.success("Save app successfully, back your workspace")
466 | st.stop()
467 | else:
468 | st.error(f"Save app error, please check up app params, refer to {FAQ_URL}")
469 |
470 | operation_row.empty()
471 | next_placeholder = operation_row.empty()
472 |
473 | def on_new_workspace():
474 | st.session_state.pop('new_app', None)
475 | logger.info("back to workspace")
476 |
477 | def add_input_config_param(params_inputs_options, index, input_param):
478 | if not input_param:
479 | input_param = {
480 | 'name': None,
481 | 'help': None,
482 | }
483 | option_index = None
484 | else:
485 | option_index = params_inputs_options.index(input_param['index'])
486 |
487 | param_input_row = row([0.4, 0.2, 0.4], vertical_align="bottom")
488 | param_input_row.selectbox("Select input of workflow *", options=params_inputs_options, key=f"input_param{index}",
489 | index=option_index,format_func=format_input_node_info, help="Select a param from workflow")
490 | param_input_row.text_input("App Input Name *", placeholder="Param Name", key=f"input_param{index}_name",
491 | value=input_param['name'], help="Input param name")
492 | param_input_row.text_input("App Input Description", value=input_param['help'], placeholder="Param Description",
493 | key=f"input_param{index}_desc", help="Input param description")
494 |
495 | def add_output_config_param(params_outputs_options, index, output_param):
496 | if not output_param:
497 | output_param = {
498 | 'name': None,
499 | 'help': None,
500 | }
501 | option_index = None
502 | else:
503 | option_index = params_outputs_options.index(output_param['index'])
504 |
505 | param_output_row = row([0.4, 0.2, 0.4], vertical_align="bottom")
506 | param_output_row.selectbox("Select output of workflow *", options=params_outputs_options,
507 | key=f"output_param{index}", index=option_index, format_func=format_output_node_info, help="Select a param from workflow")
508 | param_output_row.text_input("Apn Output Name *", placeholder="Param Name", key=f"output_param{index}_name",
509 | value=output_param['name'],help="Input param name")
510 | param_output_row.text_input("App Output Description", value=output_param['help'], placeholder="Param Description",
511 | key=f"output_param{index}_desc", help="Input param description")
512 |
513 | def new_app_ui():
514 | logger.info("Loading create page")
515 | with page.stylable_button_container():
516 | header_row = row([0.85, 0.15], vertical_align="top")
517 | header_row.title("🌱 Create app from comfyui workflow")
518 | header_row.button("Back Workspace", help="Back to your workspace", key="create_back_workspace", on_click=on_new_workspace)
519 |
520 | # check user login
521 | if not st.session_state.get('username'):
522 | st.warning("Please go to homepage for your login :point_left:")
523 | st.stop()
524 |
525 | try:
526 | if not check_comfyui_alive():
527 | logger.warning("ComfyUI server is not alive, please check it")
528 | st.error(f"New app error, ComfyUI server is not alive")
529 | st.stop()
530 |
531 | comfyui_object_info = get_comfyui_object_info()
532 | st.session_state['comfyui_object_info'] = comfyui_object_info
533 | except Exception as e:
534 | st.error(f"connect to comfyui node error, {e}")
535 | st.stop()
536 |
537 | # upload workflow image and config params
538 | with st.expander("### :one: Upload image of comfyui workflow", expanded=True):
539 | image_col1, image_col2 = st.columns([0.5, 0.5])
540 | with image_col1:
541 | st.file_uploader("Upload image from comfyui outputs *", type=["png", "jpg", "jpeg", "webp"],
542 | key="create_upload_image",
543 | help="upload image from comfyui output folder", accept_multiple_files=False)
544 | process_image_change()
545 |
546 | with image_col2:
547 | image_upload = st.session_state.get('create_upload_image')
548 | input_params = st.session_state.get('create_prompt_inputs')
549 | output_params = st.session_state.get('create_prompt_outputs')
550 | if image_upload and input_params and output_params:
551 | logger.debug(f"input_params: {input_params}, output_params: {output_params}")
552 | _, image_col, _ = st.columns([0.2, 0.6, 0.2])
553 | with image_col:
554 | st.image(image_upload, use_column_width=True, caption='ComfyUI Image with workflow info')
555 |
556 |
557 | with st.expander("### :two: Config params of app", expanded=True):
558 | with st.container():
559 | name_col1, desc_col2 = st.columns([0.2, 0.8])
560 | with name_col1:
561 | st.text_input("App Name *", value="", placeholder="input app name",
562 | key="create_app_name", help="Input app name")
563 |
564 | with desc_col2:
565 | st.text_input("App Description *", value="", placeholder="input app description",
566 | key="create_app_description", help="Input app description")
567 |
568 | with st.container():
569 | st.markdown("Input Params:")
570 | params_inputs = st.session_state.get('create_prompt_inputs', {})
571 | params_inputs_options = list(params_inputs.keys())
572 |
573 | add_input_config_param(params_inputs_options, 1, None)
574 | add_input_config_param(params_inputs_options, 2, None)
575 | add_input_config_param(params_inputs_options, 3, None)
576 | with st.container():
577 | st.markdown("Output Params:")
578 | params_outputs = st.session_state.get('create_prompt_outputs', {})
579 | params_outputs_options = list(params_outputs.keys())
580 |
581 | add_output_config_param(params_outputs_options, 1, None)
582 |
583 |
584 | with st.container():
585 | operation_row = row([0.15, 0.7, 0.15])
586 | submit_button = operation_row.button("Submit", key='create_submit_app', type="primary",
587 | use_container_width=True,
588 | help="Submit app params",on_click=submit_app)
589 | if submit_button:
590 | submit_info = st.session_state.get('create_submit_info')
591 | if submit_info == 'success':
592 | st.success("Submit app successfully, back your workspace or preview this app")
593 | st.stop()
594 | elif submit_info == 'exist':
595 | st.error("Submit app error, app name has existed")
596 | else:
597 | st.error(f"Submit app error, please check up app params, refer to {FAQ_URL}")
598 |
599 | operation_row.empty()
600 |
601 | next_placeholder = operation_row.empty()
--------------------------------------------------------------------------------
/modules/page.py:
--------------------------------------------------------------------------------
1 | from loguru import logger
2 | import os
3 | import streamlit as st
4 | import streamlit_extras.app_logo as app_logo
5 | from streamlit_extras.badges import badge
6 | from htbuilder import a, img
7 | from streamlit_extras.stylable_container import stylable_container
8 | from streamlit.source_util import (
9 | get_pages,
10 | _on_pages_changed,
11 | invalidate_pages_cache,
12 | )
13 |
14 | def change_mode_pages(mode):
15 | main_script_path = os.path.abspath('../Home.py')
16 | invalidate_pages_cache()
17 | all_pages = get_pages(main_script_path)
18 | if mode == "Creator":
19 | pages = ['Home', 'Workspace', "My_Apps"]
20 | else:
21 | pages = [page['page_name'] for _, page in all_pages.items()]
22 | logger.info(f"pages: {pages}, mode: {mode}")
23 |
24 | current_pages = [key for key, value in all_pages.items() if value['page_name'] not in pages]
25 | for key in current_pages:
26 | all_pages.pop(key)
27 |
28 | _on_pages_changed.send()
29 |
30 | def init_env_default():
31 | # init env default
32 | if 'MODE' in st.secrets:
33 | os.environ.setdefault('MODE', st.secrets['MODE'])
34 |
35 | if 'COMFYFLOW_API_URL' in st.secrets:
36 | os.environ.setdefault('COMFYFLOW_API_URL', st.secrets['COMFYFLOW_API_URL'])
37 | if 'COMFYUI_SERVER_ADDR' in st.secrets:
38 | os.environ.setdefault('COMFYUI_SERVER_ADDR', st.secrets['COMFYUI_SERVER_ADDR'])
39 |
40 | if 'DISCORD_CLIENT_ID' in st.secrets:
41 | os.environ.setdefault('DISCORD_CLIENT_ID', st.secrets['DISCORD_CLIENT_ID'])
42 | if 'DISCORD_CLIENT_SECRET' in st.secrets:
43 | os.environ.setdefault('DISCORD_CLIENT_SECRET', st.secrets['DISCORD_CLIENT_SECRET'])
44 | if 'DISCORD_REDIRECT_URI' in st.secrets:
45 | os.environ.setdefault('DISCORD_REDIRECT_URI', st.secrets['DISCORD_REDIRECT_URI'])
46 |
47 |
48 | def page_init(layout="wide"):
49 | """
50 | mode, studio or creator
51 | """
52 | st.set_page_config(page_title="ComfyFlowApp: Load a comfyui workflow as webapp in seconds.",
53 | page_icon=":artist:", layout=layout)
54 |
55 | change_mode_pages(os.environ.get('MODE'))
56 |
57 | app_logo.add_logo("public/images/logo.png", height=70)
58 |
59 | # reduce top padding
60 | st.markdown("""
61 |
69 | """, unsafe_allow_html=True)
70 |
71 | hide_streamlit_style = """
72 |
76 | """
77 | st.markdown(hide_streamlit_style, unsafe_allow_html=True)
78 |
79 | with st.sidebar:
80 | st.markdown(f"Mode: {os.environ.get('MODE')} :smile:")
81 |
82 | st.sidebar.markdown("""
83 |
88 | """, unsafe_allow_html=True)
89 |
90 | badge(type="github", name="xingren23/ComfyFlowApp", url="https://github.com/xingren23/ComfyFlowApp")
91 | badge(type="twitter", name="xingren23", url="https://twitter.com/xingren23")
92 | discord_badge_html = str(
93 | a(href="https://discord.gg/jkrPRNKp5R")(
94 | img(
95 | src="https://img.shields.io/discord/1184762864678998077?style=social&logo=discord&label=join ComfyFlowApp"
96 | )
97 | )
98 | )
99 | st.write(discord_badge_html, unsafe_allow_html=True)
100 |
101 |
102 |
103 | def stylable_button_container():
104 | return stylable_container(
105 | key="app_button",
106 | css_styles="""
107 | button {
108 | background-color: rgb(28 131 225);
109 | color: white;
110 | border-radius: 4px;
111 | width: 120px;
112 | }
113 | button:hover, button:focus {
114 | border: 0px solid rgb(28 131 225);
115 | }
116 | """,
117 | )
118 |
119 | def exchange_button_container():
120 | return stylable_container(
121 | key="exchange_button",
122 | css_styles="""
123 | button {
124 | background-color: rgb(28 131 225);
125 | color: white;
126 | border-radius: 4px;
127 | width: 200px;
128 | }
129 | button:hover, button:focus {
130 | border: 0px solid rgb(28 131 225);
131 | }
132 | """,
133 | )
134 |
135 | def custom_text_area():
136 | custom_css = """
137 |
143 | """
144 | # 将自定义CSS样式添加到Streamlit中
145 | st.markdown(custom_css, unsafe_allow_html=True)
--------------------------------------------------------------------------------
/modules/preview_app.py:
--------------------------------------------------------------------------------
1 | from loguru import logger
2 | from modules.comfyflow import Comfyflow
3 | import streamlit as st
4 | import modules.page as page
5 | from streamlit_extras.row import row
6 | from modules import get_comfy_client, get_workspace_model, check_comfyui_alive
7 | from modules.workspace_model import AppStatus
8 |
9 | def on_preview_workspace():
10 | st.session_state.pop('preview_app', None)
11 | logger.info("back to workspace")
12 |
13 | def preview_app_ui(app):
14 | with page.stylable_button_container():
15 | header_row = row([0.85, 0.15], vertical_align="top")
16 | header_row.title("💡Preview app")
17 | header_row.button("Back Workspace", help="Back to your workspace", key='preview_back_workspace', on_click=on_preview_workspace)
18 |
19 | # check user login
20 | if not st.session_state.get('username'):
21 | st.warning("Please go to homepage for your login :point_left:")
22 | st.stop()
23 |
24 |
25 | with st.container():
26 | name = app.name
27 | status = app.status
28 | api_data = app.api_conf
29 | app_data = app.app_conf
30 |
31 | if not check_comfyui_alive():
32 | logger.warning("ComfyUI server is not alive, please check it")
33 | st.error(f"Prview app {name} error, ComfyUI server is not alive")
34 | st.stop()
35 |
36 | comfy_client = get_comfy_client()
37 | comfyflow = Comfyflow(comfy_client=comfy_client, api_data=api_data, app_data=app_data)
38 | comfyflow.create_ui()
39 | if status == AppStatus.CREATED.value:
40 | if f"{name}_previewed" in st.session_state:
41 | previewed = st.session_state[f"{name}_previewed"]
42 | if previewed:
43 | st.success(f"Preview app {name} success, you could install or publish the app at Workspace page.")
44 | get_workspace_model().update_app_preview(name)
45 | logger.info(f"update preview status for app: {name}")
46 | st.stop()
47 | else:
48 | st.warning(f"Preview app {name} failed.")
49 |
50 |
51 | def on_back_apps():
52 | st.session_state.pop('enter_app', None)
53 | logger.info("back to my apps")
54 |
55 | def enter_app_ui(app):
56 | with st.container():
57 | name = app.name
58 | description = app.description
59 | status = app.status
60 | logger.info(f"enter app {name}, status: {status}")
61 |
62 | with page.stylable_button_container():
63 | header_row = row([0.85, 0.15], vertical_align="top")
64 | header_row.title(f"{name}")
65 | header_row.button("My Apps", help="Back to your apps", key='enter_back_apps', on_click=on_back_apps)
66 |
67 | if not check_comfyui_alive():
68 | logger.warning("ComfyUI server is not alive, please check it")
69 | st.error(f"Enter app {name} failed, ComfyUI server is not alive")
70 | st.stop()
71 |
72 | st.markdown(f"{description}")
73 | api_data = app.api_conf
74 | app_data = app.app_conf
75 | comfy_client = get_comfy_client()
76 | comfyflow = Comfyflow(comfy_client=comfy_client, api_data=api_data, app_data=app_data)
77 | comfyflow.create_ui(show_header=False)
--------------------------------------------------------------------------------
/modules/publish_app.py:
--------------------------------------------------------------------------------
1 | from loguru import logger
2 | import json
3 | import os
4 | import base64
5 | import requests
6 | import streamlit as st
7 | import modules.page as page
8 | from modules.workspace_model import AppStatus
9 | from streamlit_extras.row import row
10 |
11 | MODEL_SEP = '##'
12 | comfyui_supported_pt_extensions = set(['.ckpt', '.pt', '.bin', '.pth', '.safetensors'])
13 |
14 | @st.cache_data(ttl=60*60)
15 | def get_comfyflow_object_info(cookies):
16 | comfyflow_api = os.getenv('COMFYFLOW_API_URL')
17 | # request comfyflow object info
18 | object_info = requests.get(f"{comfyflow_api}/api/comfyflow/object_info", cookies=cookies)
19 | if object_info.status_code != 200:
20 | logger.error(f"Get comfyflow object info failed, {object_info.text} {cookies}")
21 | st.session_state['get_comfyflow_object_info_error'] = f"Get comfyflow object info failed, {object_info.text}"
22 | return None
23 | logger.info(f"get_comfyflow_object_info, {object_info}")
24 | return object_info.json()
25 |
26 | @st.cache_data(ttl=60*60)
27 | def get_comfyflow_model_info(cookies):
28 | comfyflow_api = os.getenv('COMFYFLOW_API_URL')
29 | # request comfyflow object info
30 | model_info = requests.get(f"{comfyflow_api}/api/comfyflow/model_info", cookies=cookies)
31 | if model_info.status_code != 200:
32 | logger.error(f"Get comfyflow model info failed, {model_info.text}")
33 | st.session_state['get_comfyflow_model_info_error'] = f"Get comfyflow model info failed, {model_info.text}"
34 | return None
35 | logger.info(f"get_comfyflow_model_info, {model_info}")
36 | return model_info.json()
37 |
38 | def do_submit_comfyflow_missing(data, cookies):
39 | comfyflow_api = os.getenv('COMFYFLOW_API_URL')
40 | # request comfyflow missing
41 | ret = requests.post(f"{comfyflow_api}/api/comfyflow/missing", json=data, cookies=cookies)
42 | if ret.status_code != 200:
43 | logger.error(f"Submit comfyflow missing failed, {ret.text}")
44 | st.error(f"Submit comfyflow missing failed, {ret.text}")
45 | return None
46 |
47 | st.success(f"submit comfyflow missing success, thanks for your feedback.")
48 | return ret.json()
49 |
50 | def do_publish_app(name, description, image, app_conf, api_conf, workflow_conf, endpoint, template, status, cookies=None):
51 | comfyflow_api = os.getenv('COMFYFLOW_API_URL')
52 | # post app to comfyflow.app
53 | app = {
54 | "name": name,
55 | "description": description,
56 | "image": image,
57 | "app_conf": app_conf,
58 | "api_conf": api_conf,
59 | "workflow_conf": workflow_conf,
60 | "endpoint": endpoint,
61 | "template": template,
62 | "status": status
63 | }
64 | ret = requests.post(f"{comfyflow_api}/api/app/publish", json=app, cookies=cookies)
65 | if ret.status_code != 200:
66 | logger.error(f"publish app failed, {name} {ret.content}")
67 | st.error(f"publish app failed, {name} {ret.content}")
68 | return ret
69 | else:
70 | logger.info(f"publish app success, {name}")
71 | st.success(f"publish app success, {name}, you could preview and modify on https://comfyflow.app")
72 | return ret
73 |
74 | def on_publish_workspace():
75 | st.session_state.pop('publish_app', None)
76 | logger.info("back to workspace")
77 |
78 | def is_comfyui_model_path(model_path):
79 | for ext in comfyui_supported_pt_extensions:
80 | if isinstance(model_path, str) and model_path.endswith(ext):
81 | return True
82 | return False
83 |
84 |
85 | def publish_app_ui(app, cookies):
86 | logger.info("Loading publish page")
87 |
88 | with page.stylable_button_container():
89 | header_row = row([0.85, 0.15], vertical_align="top")
90 | header_row.title("✈️ Publish app")
91 | header_row.button("Back Workspace", help="Back to your workspace", key='publish_back_workspace', on_click=on_publish_workspace)
92 |
93 | # check user login
94 | if not st.session_state.get('username'):
95 | st.warning("Please go to homepage for your login :point_left:")
96 | st.stop()
97 | elif st.session_state['username'] == 'demo':
98 | st.warning("Account(demo) is a test account, Please login your account to publish app :point_left:")
99 | st.stop()
100 |
101 | with st.container():
102 | api_data_json = json.loads(app.api_conf)
103 | app_data_json = json.loads(app.app_conf)
104 |
105 | # get comfyflow object info
106 | comfyflow_object_info = get_comfyflow_object_info(cookies)
107 | if not comfyflow_object_info:
108 | st.error(f"Failed to get comfyflow object info, please check comfyflow node.")
109 | st.stop()
110 |
111 |
112 | # parse app nodes
113 | missing_nodes = []
114 | with st.expander("Parse comfyui node info", expanded=True):
115 | for node_id in api_data_json:
116 | inputs = api_data_json[node_id]['inputs']
117 | # check node type
118 | class_type = api_data_json[node_id]['class_type']
119 | if class_type in comfyflow_object_info:
120 | st.write(f":green[Check node info\, {node_id}\:{class_type}]")
121 | else:
122 | st.write(f":red[Node info not found\, {node_id}\:{class_type}]")
123 | missing_nodes.append(class_type)
124 |
125 | # parse app models
126 | missing_models = []
127 | with st.expander("Parse comfyui model info", expanded=True):
128 | for node_id in api_data_json:
129 | inputs = api_data_json[node_id]['inputs']
130 | class_type = api_data_json[node_id]['class_type']
131 | # check model path
132 | logger.debug(f"inputs, {inputs}")
133 | for key, value in inputs.items():
134 | try:
135 | if isinstance(value, str):
136 | if is_comfyui_model_path(value):
137 | if key in comfyflow_object_info[class_type]['input']['required']:
138 | model_options = comfyflow_object_info[class_type]['input']['required'][key][0]
139 | elif key in comfyflow_object_info[class_type]['input']['optional']:
140 | model_options = comfyflow_object_info[class_type]['input']['optional'][key][0]
141 | else:
142 | model_options = []
143 |
144 | if value not in model_options:
145 | st.write(f":blue[Invalid model path\, {value}]")
146 | missing_models.append({class_type: value})
147 | else:
148 | st.write(f":green[Check model path\, {value}]")
149 | elif isinstance(value, dict):
150 | for k, v in value.items():
151 | if is_comfyui_model_path(v):
152 | st.write(f":green[ignore path\, {k} {value}]")
153 |
154 | except Exception as e:
155 | st.write(f":blue[Invalid model path\, {value}]")
156 | missing_models.append({class_type: value})
157 |
158 | with st.container():
159 | operation_row = row([3, 6, 1])
160 |
161 | missing_button = operation_row.button("Request missing nodes and models", key='missing_button',
162 | help="Request missing comfyui custom nodes and models", disabled=len(missing_nodes) == 0 and len(missing_models) == 0)
163 | if missing_button:
164 | # request comfyui custom nodes and models
165 | data = {
166 | 'app_id': app.id,
167 | 'missing': json.dumps({
168 | 'nodes': missing_nodes,
169 | 'models': missing_models
170 | })
171 | }
172 | do_submit_comfyflow_missing(data, cookies)
173 |
174 | operation_row.write("")
175 |
176 | publish_button = operation_row.button("Publish", key='publish_button', type='primary',
177 | help="Publish app to https://comfyflow.app", disabled=len(missing_nodes) > 0)
178 | if publish_button:
179 | # convert image to base64
180 | image_base64 = base64.b64encode(app.image).decode('utf-8')
181 | # call api to publish app
182 | do_publish_app(app.name, app.description, image_base64, app.app_conf, app.api_conf, app.workflow_conf, "", app.template, AppStatus.PUBLISHED.value, cookies)
183 |
--------------------------------------------------------------------------------
/modules/workspace_model.py:
--------------------------------------------------------------------------------
1 | from loguru import logger
2 | import streamlit as st
3 | from sqlalchemy import text
4 | from modules import AppStatus
5 |
6 | """
7 | comfyflow_apps table
8 | id INTEGER
9 | name TEXT
10 | description TEXT
11 | image TEXT
12 | app_conf TEXT
13 | api_conf TEXT
14 | template TEXT
15 | url TEXT
16 | status TEXT
17 | created_at TEXT
18 | updated_at TEXT
19 | """
20 |
21 | class WorkspaceModel:
22 | def __init__(self) -> None:
23 | self.db_conn = st.connection('comfyflow_db', type='sql')
24 | self.app_talbe_name = 'comfyflow_apps'
25 | self._init_table()
26 | logger.info(f"db_conn: {self.db_conn}, app_talbe_name: {self.app_talbe_name}")
27 |
28 | @property
29 | def session(self):
30 | return self.db_conn.session
31 |
32 | def _init_table(self):
33 | # Create a table if it doesn't exist.
34 | with self.session as s:
35 | sql = text(f'CREATE TABLE IF NOT EXISTS {self.app_talbe_name} (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT, image TEXT, app_conf TEXT, api_conf TEXT, template TEXT, url TEXT, status TEXT, created_at TEXT, updated_at TEXT);')
36 | s.execute(sql)
37 |
38 | # alert table: add username column
39 | try:
40 | s.execute(f'ALTER TABLE {self.app_talbe_name} ADD COLUMN username TEXT;' )
41 | except:
42 | columns = s.execute("PRAGMA table_info(asin)").fetchall()
43 | logger.info(f"{self.app_talbe_name} columns: {columns}")
44 | # alert table: add workflow_conf column
45 | try:
46 | s.execute(f'ALTER TABLE {self.app_talbe_name} ADD COLUMN workflow_conf TEXT;' )
47 | except:
48 | columns = s.execute("PRAGMA table_info(asin)").fetchall()
49 | logger.info(f"{self.app_talbe_name} columns: {columns}")
50 |
51 |
52 | # create index on name
53 | sql = text(f'CREATE INDEX IF NOT EXISTS {self.app_talbe_name}_name_index ON {self.app_talbe_name} (name);')
54 | s.execute(sql)
55 |
56 | s.commit()
57 | logger.info(f"init app table {self.app_talbe_name} and index")
58 |
59 | def get_all_apps(self):
60 | with self.session as s:
61 | logger.info("get apps from db")
62 | sql = text(f'SELECT id, name, description, image, app_conf, api_conf, workflow_conf, template, url, status, username FROM {self.app_talbe_name} order by id desc;')
63 | apps = s.execute(sql).fetchall()
64 | return apps
65 |
66 | def get_installed_apps(self):
67 | with self.session as s:
68 | logger.info("get installed apps from db")
69 | sql = text(f'SELECT id, name, description, image, app_conf, api_conf, workflow_conf, template, url, status, username FROM {self.app_talbe_name} WHERE status=:status order by id desc;')
70 | apps = s.execute(sql, {'status': AppStatus.INSTALLED.value}).fetchall()
71 | return apps
72 |
73 |
74 | def get_app(self, name):
75 | with self.session as s:
76 | logger.info(f"get app by name: {name}")
77 | sql = text(f'SELECT * FROM {self.app_talbe_name} WHERE name=:name;')
78 | app = s.execute(sql, {'name': name}).fetchone()
79 | return app
80 |
81 | def get_app_by_id(self, id):
82 | with self.session as s:
83 | logger.info(f"get app by id: {id}")
84 | sql = text(f'SELECT * FROM {self.app_talbe_name} WHERE id=:id;')
85 | app = s.execute(sql, {'id': id}).fetchone()
86 | return app
87 |
88 | def create_app(self, app):
89 | with self.session as s:
90 | app['status'] = AppStatus.CREATED.value
91 | logger.info(f"insert app: {app['name']} {app['description']}")
92 |
93 | sql = text(f'INSERT INTO {self.app_talbe_name} (username, name, description, image, template, app_conf, api_conf, workflow_conf, status, created_at) VALUES (:username, :name, :description, :image, :template, :app_conf, :api_conf, :workflow_conf, :status, datetime("now"));')
94 | s.execute(sql, app)
95 | s.commit()
96 |
97 | def edit_app(self, id, name, description, app_conf):
98 | # update name, description, app_conf, could not update image, api_conf
99 | with self.session as s:
100 | logger.info(f"update app conf: {id} {name} {description} {app_conf}")
101 |
102 | sql = text(f'UPDATE {self.app_talbe_name} SET name=:name, description=:description, app_conf=:app_conf, updated_at=datetime("now") WHERE id=:id;')
103 | s.execute(sql, dict(id=id, name=name, description=description, app_conf=app_conf))
104 | s.commit()
105 |
106 | def update_app_preview(self, name):
107 | # update preview_image
108 | with self.session as s:
109 | logger.info(f"update app preview: {name}")
110 | sql = text(f'UPDATE {self.app_talbe_name} SET status=:status, updated_at=datetime("now") WHERE name=:name;')
111 | s.execute(sql, dict(status=AppStatus.PREVIEWED.value, name=name))
112 | s.commit()
113 |
114 | def update_app_publish(self, name, app_conf):
115 | # update publish
116 | with self.session as s:
117 | logger.info(f"update app publish: {name} {app_conf}")
118 | sql = text(f'UPDATE {self.app_talbe_name} SET app_conf=:app_conf, status=:status, updated_at=datetime("now") WHERE name=:name;')
119 | s.execute(sql, dict(app_conf=app_conf, status=AppStatus.PUBLISHED.value, name=name))
120 | s.commit()
121 |
122 | def update_app_install(self, name):
123 | # update install
124 | with self.session as s:
125 | logger.info(f"update app install: {name}")
126 | sql = text(f'UPDATE {self.app_talbe_name} SET status=:status, updated_at=datetime("now") WHERE name=:name;')
127 | s.execute(sql, dict(status=AppStatus.INSTALLED.value, name=name))
128 | s.commit()
129 |
130 | def update_app_uninstall(self, name):
131 | # update uninstall
132 | with self.session as s:
133 | logger.info(f"update app uninstall: {name}")
134 | sql = text(f'UPDATE {self.app_talbe_name} SET status=:status, updated_at=datetime("now") WHERE name=:name;')
135 | s.execute(sql, dict(status=AppStatus.UNINSTALLED.value, name=name))
136 | s.commit()
137 |
138 | def delete_app(self, name):
139 | with self.session as s:
140 | logger.info(f"delete app: {name}")
141 | sql = text(f'DELETE FROM {self.app_talbe_name} WHERE name=:name;')
142 | s.execute(sql, dict(name=name))
143 | s.commit()
144 |
145 | def update_app_url(self, name, url):
146 | with self.session as s:
147 | logger.info(f"update app url: {name} {url}")
148 | sql = text(f'UPDATE {self.app_talbe_name} SET url=:url, updated_at=datetime("now") WHERE name=:name;')
149 | s.execute(sql, dict(url=url, name=name))
150 | s.commit()
--------------------------------------------------------------------------------
/pages/1_📱_My Apps.py:
--------------------------------------------------------------------------------
1 | from loguru import logger
2 | import streamlit as st
3 | import os
4 | from modules import get_workspace_model
5 | import modules.page as page
6 | from streamlit_extras.row import row
7 | from streamlit_extras.switch_page_button import switch_page
8 | from modules import AppStatus, check_comfyui_alive
9 | from modules.preview_app import enter_app_ui
10 |
11 | def uninstall_app(app):
12 | logger.info(f"uninstall app {app.name}")
13 | get_workspace_model().update_app_uninstall(app.name)
14 |
15 |
16 | def enter_app(app):
17 | logger.info(f"enter app {app.name}")
18 | st.session_state["enter_app"] = app
19 |
20 |
21 | def create_app_info_ui(app):
22 | app_row = row([1, 5.4, 1.2, 1.4, 1], vertical_align="bottom")
23 | try:
24 | if app.image is not None:
25 | app_row.image(app.image)
26 | else:
27 | app_row.image("public/images/app-150.png")
28 | except Exception as e:
29 | logger.error(f"load app image error, {e}")
30 |
31 | # get description limit to 200 chars
32 | description = app.description
33 | if len(description) > 160:
34 | description = description[:160] + "..."
35 | app_row.markdown(f"""
36 | #### {app.name}
37 | {description}
38 | """)
39 |
40 | app_author = app.username
41 | app_row.markdown(f"""
42 | #### Author
43 | {app_author}
44 | """)
45 | uninstall_button = app_row.button("🚮 Uninstall", help="Uninstall app from app store",
46 | key=f"uninstall_{app.id}", on_click=uninstall_app, args=(app,))
47 | if uninstall_button:
48 | logger.info(f"uninstall app {app.name}")
49 |
50 | enter_button = app_row.button("Enter", type='primary', help="Enter app to use", key=f"enter_{app.id}",
51 | on_click=enter_app, args=(app,))
52 | if enter_button:
53 | logger.info(f"enter app {app.name}")
54 |
55 |
56 |
57 | page.page_init()
58 |
59 | with st.container():
60 |
61 | container_empty = st.empty()
62 | if 'enter_app' in st.session_state:
63 | app = st.session_state['enter_app']
64 | logger.info(f"Start app ..., {app.name}")
65 | enter_app_ui(app)
66 | else:
67 | with page.stylable_button_container():
68 | header_row = row([0.85, 0.15], vertical_align="bottom")
69 | header_row.title("My Apps")
70 | explore_button = header_row.button(
71 | "Install", help="Install more apps from your workspace.")
72 | if explore_button:
73 | switch_page("Workspace")
74 |
75 | with st.container():
76 | apps = get_workspace_model().get_installed_apps()
77 | if len(apps) == 0:
78 | st.divider()
79 | st.info("No apps, you could create and install app from your workspace")
80 | else:
81 | for app in apps:
82 | st.divider()
83 | logger.info(f"load app info for {app.name} {app}")
84 | create_app_info_ui(app)
85 |
--------------------------------------------------------------------------------
/pages/3_📚_Workspace.py:
--------------------------------------------------------------------------------
1 | import os
2 | import requests
3 | from io import BytesIO
4 | from loguru import logger
5 | import streamlit as st
6 | import modules.page as page
7 | from modules import get_workspace_model, check_comfyui_alive, get_comfyflow_token
8 | from streamlit_extras.row import row
9 | from manager.app_manager import start_app, stop_app
10 | from modules.workspace_model import AppStatus
11 | from streamlit import config
12 | from modules.new_app import new_app_ui, edit_app_ui
13 | from modules.preview_app import preview_app_ui
14 | from modules.publish_app import publish_app_ui
15 | import random
16 |
17 |
18 | def create_app_info_ui(app):
19 | app_row = row([1, 4.6, 1.2, 2, 1.2], vertical_align="bottom")
20 | try:
21 | if app.image is not None:
22 |
23 | app_row.image(BytesIO(app.image))
24 | else:
25 | app_row.image("./public/images/app-150.png")
26 | except Exception as e:
27 | logger.error(f"load app image error, {e}")
28 |
29 | # get description limit to 200 chars
30 | description = app.description
31 | if len(description) > 160:
32 | description = description[:160] + "..."
33 | app_row.markdown(f"""
34 | #### {app.name}
35 | {description}
36 | """)
37 | app_author = app.username
38 | app_row.markdown(f"""
39 | #### Author
40 | {app_author}
41 | """)
42 | app_row.markdown(f"""
43 | #### Web Site
44 | 🌐 {app.url}
45 | """)
46 | app_row.markdown(f"""
47 | #### Status
48 | {app.status}
49 | """)
50 |
51 |
52 | def click_new_app():
53 | logger.info("new app...")
54 | st.session_state['new_app'] = True
55 | st.session_state.pop('edit_app', None)
56 | st.session_state.pop('preview_app', None)
57 | st.session_state.pop('publish_app', None)
58 |
59 | def click_edit_app(app):
60 | logger.info(f"edit app: {app.name}")
61 | st.session_state['edit_app'] = app
62 | st.session_state.pop('new_app', None)
63 | st.session_state.pop('preview_app', None)
64 | st.session_state.pop('publish_app', None)
65 |
66 | def click_preview_app(app):
67 | logger.info(f"preview app: {app.name}")
68 | st.session_state['preview_app'] = app
69 | st.session_state.pop('new_app', None)
70 | st.session_state.pop('edit_app', None)
71 | st.session_state.pop('publish_app', None)
72 |
73 |
74 | def click_publish_app(app):
75 | if app.status == AppStatus.CREATED.value:
76 | logger.warning(f"Please preview the app {app.name} first")
77 | return
78 |
79 | logger.info(f"publish app: {app.name} status: {app.status}")
80 | st.session_state['publish_app'] = app
81 | st.session_state.pop('new_app', None)
82 | st.session_state.pop('preview_app', None)
83 |
84 |
85 | def click_delete_app(name):
86 | logger.info(f"delete app: {name}")
87 | get_workspace_model().delete_app(name)
88 |
89 | def click_install_app(app):
90 | if app.status == AppStatus.CREATED.value:
91 | logger.warning(f"Please preview the app {app.name} first")
92 | return
93 |
94 | get_workspace_model().update_app_install(app.name)
95 | logger.info(f"install App {app.name} success")
96 | st.session_state['app_install_ret'] = AppStatus.INSTALLED.value
97 |
98 | def ready_start_app(status):
99 | if status == AppStatus.PREVIEWED.value or status == AppStatus.PUBLISHED.value or status == AppStatus.INSTALLED.value:
100 | return True
101 | else:
102 | return False
103 |
104 | def click_start_app(name, id, status):
105 | logger.info(f"start app: {name} status: {status}")
106 | if ready_start_app(status):
107 | if not check_comfyui_alive():
108 | logger.error("ComfyUI server is not alive, please check it")
109 | st.session_state['app_start_ret'] = AppStatus.ERROR.value
110 | return
111 |
112 | # comfyflowapp address
113 | app_server = config.get_option('server.address')
114 | if app_server is None or app_server == "":
115 | app_server = "localhost"
116 | app_port = int(id) + random.randint(10000, 20000)
117 | url = f"http://{app_server}:{app_port}"
118 |
119 | ret = start_app(name, id, url)
120 | st.session_state['app_start_ret'] = ret
121 | if ret == AppStatus.RUNNING.value:
122 | get_workspace_model().update_app_url(name, url)
123 | logger.info(f"App {name} is running yet, you could share {url} to your friends")
124 | elif ret == AppStatus.STARTED.value:
125 | get_workspace_model().update_app_url(name, url)
126 | logger.info(f"Start app {name} success, you could share {url} to your friends")
127 | else:
128 | logger.info(f"Start app {name} failed")
129 | else:
130 | logger.warning(f"Please preview the app {name} first")
131 |
132 | def click_stop_app(name, status, url):
133 | logger.info(f"stop app: {name} status: {status} url: {url}")
134 | if ready_start_app(status):
135 | if url == "":
136 | logger.info(f"App {name} url is empty, maybe it is stopped")
137 | st.session_state['app_stop_ret'] = AppStatus.STOPPED.value
138 | else:
139 | ret = stop_app(name, url)
140 | st.session_state['app_stop_ret'] = ret
141 | if ret == AppStatus.STOPPING.value:
142 | get_workspace_model().update_app_url(name, "")
143 | logger.info(f"Stop app {name} success, {url}")
144 | elif ret == AppStatus.STOPPED.value:
145 | get_workspace_model().update_app_url(name, "")
146 | logger.info(f"App {name} has stopped, {url}")
147 | else:
148 | logger.error(f"Stop app {name} failed, please check the log")
149 | else:
150 | logger.warning(f"Please preview the app {name} first")
151 |
152 |
153 | def create_operation_ui(app):
154 | id = app.id
155 | name = app.name
156 | status = app.status
157 | url = app.url
158 | disabled = True
159 | if st.session_state.get('username', 'anonymous') == app.username:
160 | disabled = False
161 |
162 | operate_row = row([1.2, 1.0, 1.1, 1.1, 4.5, 1.1], vertical_align="bottom")
163 | preview_button = operate_row.button("✅ Preview", help="Preview and check the app",
164 | key=f"{id}-button-preview",
165 | on_click=click_preview_app, args=(app,), disabled=disabled)
166 | if preview_button:
167 | if not check_comfyui_alive():
168 | logger.warning("ComfyUI server is not alive, please check it")
169 | st.error(f"Preview app {name} failed, please check the log")
170 | st.stop()
171 |
172 | edit_button = operate_row.button("✏️ Edit", help="Edit the app", key=f"{id}-button-edit",
173 | on_click=click_edit_app, args=(app,), disabled=disabled)
174 | if edit_button:
175 | app_preview_ret = st.session_state['app_edit_ret']
176 | if app_preview_ret == AppStatus.ERROR.value:
177 | st.error(f"Edit app {name} failed, please check the log")
178 |
179 | if app.workflow_conf is not None:
180 | operate_row.download_button("💾 Export", data=app.workflow_conf, file_name=f"{app.name}_workflow.json", help="Export workflow to json", key=f"{id}-button-export",
181 | disabled=disabled)
182 | else:
183 | operate_row.button("💾 Export", help="Export workflow to json", key=f"{id}-button-export", disabled=True)
184 |
185 | install_button = operate_row.button("📲 Install", help="Install the app", key=f"{id}-button-install",
186 | on_click=click_install_app, args=(app,), disabled=disabled)
187 | if install_button:
188 | if status == AppStatus.CREATED.value:
189 | st.warning(f"Please preview the app {name} first")
190 | else:
191 | app_install_ret = st.session_state['app_install_ret']
192 | if app_install_ret == AppStatus.INSTALLED.value:
193 | st.success(f"App {name} has installed yet, you could use it at My Apps page")
194 | else:
195 | st.error(f"Install app {name} failed, please check the log")
196 |
197 |
198 | # start_button = operate_row.button("▶️ Start", help="Start the app", key=f"{id}-button-start",
199 | # on_click=click_start_app, args=(name, id, status), disabled=disabled)
200 | # if start_button:
201 | # if ready_start_app(status):
202 | # app_preview_ret = st.session_state['app_start_ret']
203 | # if app_preview_ret == AppStatus.RUNNING.value:
204 | # st.info(f"App {name} is running yet, you could share {url} to your friends")
205 | # elif app_preview_ret == AppStatus.STARTED.value:
206 | # st.success(f"Start app {name} success, you could share {url} to your friends")
207 | # else:
208 | # st.error(f"Start app {name} failed")
209 | # else:
210 | # st.warning(f"Please preview the app {name} first")
211 |
212 | # stop_button = operate_row.button("⏹️ Stop", help="Stop the app", key=f"{id}-button-stop",
213 | # on_click=click_stop_app, args=(name, status, url), disabled=disabled)
214 | # if stop_button:
215 | # if ready_start_app(status):
216 | # app_stop_ret = st.session_state['app_stop_ret']
217 | # if app_stop_ret == AppStatus.STOPPING.value:
218 | # st.success(f"Stop app {name} success, {url}")
219 | # elif app_stop_ret == AppStatus.STOPPED.value:
220 | # st.success(f"App {name} has stopped, {url}")
221 | # else:
222 | # st.error(f"Stop app {name} failed, please check the log")
223 | # else:
224 | # st.warning(f"Please preview the app {name} first")
225 |
226 | operate_row.markdown("")
227 |
228 | operate_row.button("❌ Delete", help="Delete the app", key=f"{id}-button-delete",
229 | on_click=click_delete_app, args=(name,), disabled=disabled)
230 |
231 |
232 | # publish_button = operate_row.button("✈️ Publish", help="Publish the app with template",
233 | # key=f"{id}-button-publish",
234 | # on_click=click_publish_app, args=(app,), disabled=disabled)
235 | # if publish_button:
236 | # if status == AppStatus.CREATED.value:
237 | # st.warning(f"Please preview the app {name} first")
238 | # else:
239 | # if 'token_cookie' not in st.session_state:
240 | # st.warning("Please go to homepage for your login :point_left:")
241 |
242 |
243 | def is_load_workspace_page():
244 | if 'new_app' in st.session_state:
245 | return False
246 | if 'preview_app' in st.session_state:
247 | return False
248 | if 'publish_app' in st.session_state:
249 | return False
250 | if 'edit_app' in st.session_state:
251 | return False
252 | return True
253 |
254 |
255 | logger.info("Loading workspace page")
256 | page.page_init()
257 |
258 | with st.container():
259 | if 'token_cookie' not in st.session_state:
260 | comfyflow_token = get_comfyflow_token()
261 | if comfyflow_token is not None:
262 | cookies = {'comfyflow_token': comfyflow_token}
263 | st.session_state['token_cookie'] = cookies
264 | else:
265 | cookies = None
266 | else:
267 | cookies = st.session_state['token_cookie']
268 |
269 | if 'new_app' in st.session_state:
270 | new_app_ui()
271 | elif 'edit_app' in st.session_state:
272 | edit_app_ui(app=st.session_state['edit_app'])
273 | elif 'preview_app' in st.session_state:
274 | preview_app_ui(st.session_state['preview_app'])
275 | elif 'publish_app' in st.session_state:
276 | publish_app_ui(app=st.session_state['publish_app'], cookies=cookies)
277 |
278 | elif is_load_workspace_page():
279 | with page.stylable_button_container():
280 | header_row = row([0.85, 0.15], vertical_align="top")
281 | header_row.markdown("""
282 | ### My Workspace
283 | create and manage your comfyflowapps.
284 | """)
285 | new_app_button = header_row.button("New App", help="Create a new app from comfyui workflow.", on_click=click_new_app)
286 |
287 | if not st.session_state.get('username'):
288 | st.warning("Please go to homepage for your login :point_left:")
289 |
290 | with st.container():
291 | apps = get_workspace_model().get_all_apps()
292 | if len(apps) == 0:
293 | st.divider()
294 | st.info("No apps, please create a new app.")
295 | else:
296 | for app in apps:
297 | st.divider()
298 | logger.info(f"load app info {app}")
299 | create_app_info_ui(app)
300 | create_operation_ui(app)
301 |
302 |
--------------------------------------------------------------------------------
/public/images/app-150.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xingren23/ComfyFlowApp/c4d26a4ac307e01db0498207c51a58bfe2d638e9/public/images/app-150.png
--------------------------------------------------------------------------------
/public/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xingren23/ComfyFlowApp/c4d26a4ac307e01db0498207c51a58bfe2d638e9/public/images/logo.png
--------------------------------------------------------------------------------
/public/images/output-none.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xingren23/ComfyFlowApp/c4d26a4ac307e01db0498207c51a58bfe2d638e9/public/images/output-none.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | loguru==0.7.0
2 | SQLAlchemy>=1.4, <2.0
3 | streamlit==1.28.0
4 | streamlit-extras==0.3.4
5 | websocket-client==0.58.0
6 | psutil==5.9.5
7 | streamlit-authenticator==0.2.3
8 | discord-oauth2.py==1.2.1
--------------------------------------------------------------------------------