gradio-terminal 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Po-Hsuan Huang (aben20807)
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: gradio-terminal
3
+ Version: 0.1.0
4
+ Summary: A Gradio component that provides a fully functional terminal using xterm.js and PTY
5
+ Author: Po-Hsuan Huang
6
+ Author-email: Po-Hsuan Huang <aben20807@gmail.com>
7
+ License: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/aben20807/gradio-terminal
9
+ Project-URL: Repository, https://github.com/aben20807/gradio-terminal
10
+ Project-URL: Issues, https://github.com/aben20807/gradio-terminal/issues
11
+ Keywords: gradio,terminal,xterm,pty,shell
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: gradio>=6.3.0
26
+ Requires-Dist: flask>=3.1.2
27
+ Requires-Dist: flask-socketio>=5.6.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
30
+ Requires-Dist: black>=22.0.0; extra == "dev"
31
+ Requires-Dist: flake8>=4.0.0; extra == "dev"
32
+ Dynamic: author
33
+ Dynamic: license-file
34
+ Dynamic: requires-python
35
+
36
+ # Gradio Terminal
37
+
38
+ A Gradio component that provides a fully functional terminal in your browser. This package uses xterm.js on the frontend and a PTY on the backend to provide a real shell experience.
39
+
40
+ ![Gradio Terminal](https://github.com/user-attachments/assets/8a4cc81a-07a4-4c56-a008-bd438eae50de)
41
+
42
+ ## Installation
43
+
44
+ ```bash
45
+ pip install gradio-terminal
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ### Simple Usage
51
+
52
+ ```python
53
+ import gradio as gr
54
+ from gradio_terminal import Terminal
55
+ demo = gr.Blocks()
56
+ with demo:
57
+ terminal = Terminal()
58
+ demo.launch()
59
+ ```
60
+
61
+ ## API Reference
62
+
63
+ `launch_terminal(port=5000, host="127.0.0.1", command="bash", share=False, **launch_kwargs)`
64
+
65
+ Launch a standalone Gradio app with a terminal.
66
+
67
+ `create_terminal_demo(port=5000, host="127.0.0.1", command="bash", height=400)`
68
+
69
+ Create a Gradio Blocks demo with an embedded terminal.
70
+
71
+ `TerminalServer(port=5000, host="127.0.0.1", command="bash")`
72
+
73
+ Low-level terminal server for custom integrations.
74
+
75
+ - `start()`: Start the server and return the URL
76
+ - `get_url()`: Get the terminal server URL
77
+ - `stop()`: Stop the terminal server
78
+
79
+ ## Requirements
80
+
81
+ - Python 3.8+
82
+ - Linux
83
+ - Dependencies: gradio, flask, flask-socketio
84
+
85
+ ## Security Notice
86
+
87
+ This component provides shell access to your server. Use only in trusted environments.
88
+
89
+ ## License
90
+
91
+ This project is licensed under the Apache-2.0 License.
92
+
93
+ ## Acknowledgments
94
+
95
+ - [pyxtermjs](https://github.com/cs01/pyxtermjs) - Inspiration for the terminal implementation
96
+ - [xterm.js](https://xtermjs.org/) - Terminal emulator for the browser
97
+ - [Gradio](https://gradio.app/) - The awesome ML demo framework
@@ -0,0 +1,62 @@
1
+ # Gradio Terminal
2
+
3
+ A Gradio component that provides a fully functional terminal in your browser. This package uses xterm.js on the frontend and a PTY on the backend to provide a real shell experience.
4
+
5
+ ![Gradio Terminal](https://github.com/user-attachments/assets/8a4cc81a-07a4-4c56-a008-bd438eae50de)
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install gradio-terminal
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ### Simple Usage
16
+
17
+ ```python
18
+ import gradio as gr
19
+ from gradio_terminal import Terminal
20
+ demo = gr.Blocks()
21
+ with demo:
22
+ terminal = Terminal()
23
+ demo.launch()
24
+ ```
25
+
26
+ ## API Reference
27
+
28
+ `launch_terminal(port=5000, host="127.0.0.1", command="bash", share=False, **launch_kwargs)`
29
+
30
+ Launch a standalone Gradio app with a terminal.
31
+
32
+ `create_terminal_demo(port=5000, host="127.0.0.1", command="bash", height=400)`
33
+
34
+ Create a Gradio Blocks demo with an embedded terminal.
35
+
36
+ `TerminalServer(port=5000, host="127.0.0.1", command="bash")`
37
+
38
+ Low-level terminal server for custom integrations.
39
+
40
+ - `start()`: Start the server and return the URL
41
+ - `get_url()`: Get the terminal server URL
42
+ - `stop()`: Stop the terminal server
43
+
44
+ ## Requirements
45
+
46
+ - Python 3.8+
47
+ - Linux
48
+ - Dependencies: gradio, flask, flask-socketio
49
+
50
+ ## Security Notice
51
+
52
+ This component provides shell access to your server. Use only in trusted environments.
53
+
54
+ ## License
55
+
56
+ This project is licensed under the Apache-2.0 License.
57
+
58
+ ## Acknowledgments
59
+
60
+ - [pyxtermjs](https://github.com/cs01/pyxtermjs) - Inspiration for the terminal implementation
61
+ - [xterm.js](https://xtermjs.org/) - Terminal emulator for the browser
62
+ - [Gradio](https://gradio.app/) - The awesome ML demo framework
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gradio-terminal"
7
+ version = "0.1.0"
8
+ description = "A Gradio component that provides a fully functional terminal using xterm.js and PTY"
9
+ readme = "README.md"
10
+ license = {text = "Apache-2.0"}
11
+ authors = [
12
+ {name = "Po-Hsuan Huang", email = "aben20807@gmail.com"}
13
+ ]
14
+ keywords = ["gradio", "terminal", "xterm", "pty", "shell"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Operating System :: POSIX :: Linux",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.8",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ ]
27
+ requires-python = ">=3.8"
28
+ dependencies = [
29
+ "gradio>=6.3.0",
30
+ "flask>=3.1.2",
31
+ "flask-socketio>=5.6.0",
32
+ ]
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ "pytest>=7.0.0",
37
+ "black>=22.0.0",
38
+ "flake8>=4.0.0",
39
+ ]
40
+
41
+ [project.urls]
42
+ Homepage = "https://github.com/aben20807/gradio-terminal"
43
+ Repository = "https://github.com/aben20807/gradio-terminal"
44
+ Issues = "https://github.com/aben20807/gradio-terminal/issues"
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
48
+
49
+ [tool.black]
50
+ line-length = 100
51
+ target-version = ["py38", "py39", "py310", "py311", "py312"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,32 @@
1
+ from setuptools import find_packages, setup
2
+
3
+ setup(
4
+ name="gradio-terminal",
5
+ version="0.1.0",
6
+ author="Po-Hsuan Huang",
7
+ author_email="aben20807@gmail.com",
8
+ description="A Gradio component that provides a fully functional terminal using xterm.js and PTY",
9
+ long_description=open("README.md").read(),
10
+ long_description_content_type="text/markdown",
11
+ packages=find_packages(where="src"),
12
+ package_dir={"": "src"},
13
+ license="Apache-2.0",
14
+ install_requires=[
15
+ "gradio>=6.3.0",
16
+ "flask>=3.1.2",
17
+ "flask-socketio>=5.6.0",
18
+ ],
19
+ classifiers=[
20
+ "Development Status :: 3 - Alpha",
21
+ "Intended Audience :: Developers",
22
+ "License :: OSI Approved :: Apache Software License",
23
+ "Operating System :: POSIX :: Linux",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.8",
26
+ "Programming Language :: Python :: 3.9",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ ],
31
+ python_requires=">=3.8",
32
+ )
@@ -0,0 +1,43 @@
1
+ """
2
+ Gradio Terminal - A terminal component for Gradio.
3
+
4
+ This package provides a fully functional terminal that can be embedded
5
+ in Gradio applications. It uses xterm.js on the frontend and a PTY
6
+ (pseudo-terminal) on the backend to provide a real shell experience.
7
+
8
+ Example usage in Blocks:
9
+ import gradio as gr
10
+ from gradio_terminal import Terminal
11
+
12
+ with gr.Blocks() as demo:
13
+ gr.Markdown("# My App with Terminal")
14
+ with gr.Row():
15
+ with gr.Column():
16
+ gr.Markdown("Some content here")
17
+ with gr.Column():
18
+ terminal = Terminal()
19
+
20
+ demo.launch()
21
+
22
+ Or for quick usage:
23
+ from gradio_terminal import launch_terminal
24
+
25
+ launch_terminal()
26
+ """
27
+
28
+ from .terminal import (
29
+ Terminal,
30
+ TerminalServer,
31
+ create_terminal,
32
+ create_terminal_demo,
33
+ launch_terminal,
34
+ )
35
+
36
+ __version__ = "0.1.0"
37
+ __all__ = [
38
+ "Terminal",
39
+ "TerminalServer",
40
+ "create_terminal",
41
+ "create_terminal_demo",
42
+ "launch_terminal",
43
+ ]
@@ -0,0 +1,523 @@
1
+ """
2
+ Gradio Terminal Component using xterm.js and PTY.
3
+
4
+ This component provides a fully functional terminal in Gradio applications.
5
+ Based on pyxtermjs (https://github.com/cs01/pyxtermjs).
6
+
7
+ IMPORTANT: If using SSH tunneling, you need to tunnel BOTH ports:
8
+ - The Gradio port (default 7860)
9
+ - The terminal server port (default 5000)
10
+
11
+ Example SSH command:
12
+ ssh -L 7860:localhost:7860 -L 5000:localhost:5000 user@remote
13
+ """
14
+
15
+ """
16
+ Include pyxtermjs's MIT license:
17
+
18
+ MIT License
19
+
20
+ Copyright (c) 2018 Chad Smith
21
+
22
+ Permission is hereby granted, free of charge, to any person obtaining a copy
23
+ of this software and associated documentation files (the "Software"), to deal
24
+ in the Software without restriction, including without limitation the rights
25
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
26
+ copies of the Software, and to permit persons to whom the Software is
27
+ furnished to do so, subject to the following conditions:
28
+
29
+ The above copyright notice and this permission notice shall be included in all
30
+ copies or substantial portions of the Software.
31
+
32
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
38
+ SOFTWARE.
39
+ """
40
+ import atexit
41
+ import fcntl
42
+ import logging
43
+ import os
44
+ import pty
45
+ import select
46
+ import shlex
47
+ import signal
48
+ import struct
49
+ import subprocess
50
+ import termios
51
+ import threading
52
+ import time
53
+ from typing import Any
54
+
55
+ import gradio as gr
56
+
57
+ logging.getLogger("werkzeug").setLevel(logging.ERROR)
58
+
59
+ # Global registry to track terminal servers
60
+ _terminal_servers: dict[int, "TerminalServer"] = {}
61
+
62
+
63
+ def _cleanup_servers():
64
+ """Clean up all terminal servers on exit."""
65
+ for server in list(_terminal_servers.values()):
66
+ try:
67
+ server.stop()
68
+ except Exception:
69
+ pass
70
+
71
+
72
+ atexit.register(_cleanup_servers)
73
+
74
+
75
+ class TerminalServer:
76
+ """
77
+ A server that manages PTY sessions for terminal access.
78
+ Runs Flask-SocketIO in a background thread.
79
+ """
80
+
81
+ def __init__(self, port: int = 5000, host: str = "127.0.0.1", command: str = "bash"):
82
+ self.port = port
83
+ self.host = host
84
+ self.command = command
85
+ self._running = False
86
+ self._thread = None
87
+ self._app = None
88
+ self._socketio = None
89
+
90
+ # Register in global registry
91
+ _terminal_servers[port] = self
92
+
93
+ def _create_app(self):
94
+ """Create and configure the Flask app with SocketIO."""
95
+ from flask import Flask, render_template_string
96
+ from flask_socketio import SocketIO
97
+
98
+ app = Flask(__name__)
99
+ app.config["SECRET_KEY"] = "gradio-terminal-secret"
100
+ app.config["fd"] = None
101
+ app.config["child_pid"] = None
102
+ app.config["cmd"] = shlex.split(self.command)
103
+
104
+ socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
105
+
106
+ def set_winsize(fd, row, col, xpix=0, ypix=0):
107
+ winsize = struct.pack("HHHH", row, col, xpix, ypix)
108
+ fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
109
+
110
+ def read_and_forward_pty_output():
111
+ max_read_bytes = 1024 * 20
112
+ while True:
113
+ socketio.sleep(0.01)
114
+ if app.config["fd"]:
115
+ timeout_sec = 0
116
+ try:
117
+ data_ready, _, _ = select.select([app.config["fd"]], [], [], timeout_sec)
118
+ if data_ready:
119
+ output = os.read(app.config["fd"], max_read_bytes).decode(
120
+ errors="ignore"
121
+ )
122
+ socketio.emit("pty-output", {"output": output}, namespace="/pty")
123
+ except (OSError, ValueError):
124
+ break
125
+
126
+ @app.route("/")
127
+ def index():
128
+ return render_template_string(self._get_terminal_html())
129
+
130
+ @socketio.on("pty-input", namespace="/pty")
131
+ def pty_input(data):
132
+ if app.config["fd"]:
133
+ os.write(app.config["fd"], data["input"].encode())
134
+
135
+ @socketio.on("resize", namespace="/pty")
136
+ def resize(data):
137
+ if app.config["fd"]:
138
+ set_winsize(app.config["fd"], data["rows"], data["cols"])
139
+
140
+ @socketio.on("connect", namespace="/pty")
141
+ def connect():
142
+ if app.config["child_pid"]:
143
+ return
144
+
145
+ child_pid, fd = pty.fork()
146
+ if child_pid == 0:
147
+ subprocess.run(app.config["cmd"])
148
+ else:
149
+ app.config["fd"] = fd
150
+ app.config["child_pid"] = child_pid
151
+ set_winsize(fd, 24, 80)
152
+ socketio.start_background_task(target=read_and_forward_pty_output)
153
+
154
+ @socketio.on("disconnect", namespace="/pty")
155
+ def disconnect():
156
+ pass
157
+
158
+ return app, socketio
159
+
160
+ def _get_terminal_html(self) -> str:
161
+ """Return the HTML template for the terminal."""
162
+ return """
163
+ <!DOCTYPE html>
164
+ <html lang="en">
165
+ <head>
166
+ <meta charset="utf-8" />
167
+ <title>Gradio Terminal</title>
168
+ <style>
169
+ html, body {
170
+ margin: 0;
171
+ padding: 0;
172
+ height: 100%;
173
+ overflow: hidden;
174
+ background-color: #1e1e1e;
175
+ }
176
+ #terminal {
177
+ width: 100%;
178
+ height: 100%;
179
+ }
180
+ #status {
181
+ position: absolute;
182
+ top: 5px;
183
+ right: 10px;
184
+ font-size: 12px;
185
+ font-family: Arial, sans-serif;
186
+ z-index: 1000;
187
+ }
188
+ .connected {
189
+ background-color: #4CAF50;
190
+ color: white;
191
+ padding: 2px 8px;
192
+ border-radius: 3px;
193
+ }
194
+ .disconnected {
195
+ background-color: #f44336;
196
+ color: white;
197
+ padding: 2px 8px;
198
+ border-radius: 3px;
199
+ }
200
+ .connecting {
201
+ background-color: #ff9800;
202
+ color: white;
203
+ padding: 2px 8px;
204
+ border-radius: 3px;
205
+ }
206
+ </style>
207
+ <link rel="stylesheet" href="https://unpkg.com/xterm@4.11.0/css/xterm.css" />
208
+ </head>
209
+ <body>
210
+ <div id="status"><span class="connecting">connecting...</span></div>
211
+ <div id="terminal"></div>
212
+
213
+ <script src="https://unpkg.com/xterm@4.11.0/lib/xterm.js"></script>
214
+ <script src="https://unpkg.com/xterm-addon-fit@0.5.0/lib/xterm-addon-fit.js"></script>
215
+ <script src="https://unpkg.com/xterm-addon-web-links@0.4.0/lib/xterm-addon-web-links.js"></script>
216
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js"></script>
217
+
218
+ <script>
219
+ const term = new Terminal({
220
+ cursorBlink: true,
221
+ macOptionIsMeta: true,
222
+ scrollback: 5000,
223
+ fontSize: 14,
224
+ fontFamily: 'Consolas, Monaco, monospace',
225
+ theme: {
226
+ background: '#1e1e1e',
227
+ foreground: '#d4d4d4',
228
+ cursor: '#d4d4d4',
229
+ cursorAccent: '#1e1e1e',
230
+ selectionBackground: 'rgba(255, 255, 255, 0.3)',
231
+ }
232
+ });
233
+
234
+ const fit = new FitAddon.FitAddon();
235
+ term.loadAddon(fit);
236
+ term.loadAddon(new WebLinksAddon.WebLinksAddon());
237
+
238
+ term.open(document.getElementById("terminal"));
239
+ fit.fit();
240
+
241
+ term.attachCustomKeyEventHandler((e) => {
242
+ if (e.type !== "keydown") return true;
243
+ if (e.ctrlKey && e.shiftKey) {
244
+ const key = e.key.toLowerCase();
245
+ if (key === "v") {
246
+ navigator.clipboard.readText().then((text) => {
247
+ term.writeText(text);
248
+ });
249
+ return false;
250
+ } else if (key === "c" || key === "x") {
251
+ const selection = term.getSelection();
252
+ if (selection) {
253
+ navigator.clipboard.writeText(selection);
254
+ }
255
+ return false;
256
+ }
257
+ }
258
+ return true;
259
+ });
260
+
261
+ const socket = io.connect("/pty");
262
+ const status = document.getElementById("status");
263
+
264
+ term.onData((data) => {
265
+ socket.emit("pty-input", { input: data });
266
+ });
267
+
268
+ socket.on("pty-output", (data) => {
269
+ term.write(data.output);
270
+ });
271
+
272
+ socket.on("connect", () => {
273
+ status.innerHTML = '<span class="connected">connected</span>';
274
+ fitToScreen();
275
+ });
276
+
277
+ socket.on("disconnect", () => {
278
+ status.innerHTML = '<span class="disconnected">disconnected</span>';
279
+ });
280
+
281
+ socket.on("connect_error", (error) => {
282
+ status.innerHTML = '<span class="disconnected">error</span>';
283
+ });
284
+
285
+ function fitToScreen() {
286
+ fit.fit();
287
+ const dims = { cols: term.cols, rows: term.rows };
288
+ socket.emit("resize", dims);
289
+ }
290
+
291
+ function debounce(func, wait) {
292
+ let timeout;
293
+ return function(...args) {
294
+ clearTimeout(timeout);
295
+ timeout = setTimeout(() => func.apply(this, args), wait);
296
+ };
297
+ }
298
+
299
+ window.onresize = debounce(fitToScreen, 50);
300
+ setTimeout(fitToScreen, 100);
301
+ </script>
302
+ </body>
303
+ </html>
304
+ """
305
+
306
+ def start(self):
307
+ """Start the terminal server in a background thread."""
308
+ if self._running:
309
+ return self.get_url()
310
+
311
+ self._app, self._socketio = self._create_app()
312
+
313
+ def run_server():
314
+ self._socketio.run(
315
+ self._app,
316
+ host=self.host,
317
+ port=self.port,
318
+ debug=False,
319
+ use_reloader=False,
320
+ log_output=False,
321
+ )
322
+
323
+ self._thread = threading.Thread(target=run_server, daemon=True)
324
+ self._thread.start()
325
+ self._running = True
326
+
327
+ # Wait for server to start
328
+ time.sleep(1.0)
329
+
330
+ print(f"Terminal server started at http://{self.host}:{self.port}")
331
+ return self.get_url()
332
+
333
+ def get_url(self) -> str:
334
+ """Get the URL of the terminal server."""
335
+ return f"http://{self.host}:{self.port}"
336
+
337
+ def stop(self):
338
+ """Stop the terminal server."""
339
+ if self._app and self._app.config.get("child_pid"):
340
+ try:
341
+ os.kill(self._app.config["child_pid"], signal.SIGTERM)
342
+ time.sleep(0.1)
343
+ os.kill(self._app.config["child_pid"], signal.SIGKILL)
344
+ except (ProcessLookupError, OSError):
345
+ pass
346
+ self._app.config["child_pid"] = None
347
+ self._app.config["fd"] = None
348
+ self._running = False
349
+
350
+ if self.port in _terminal_servers:
351
+ del _terminal_servers[self.port]
352
+
353
+
354
+ class Terminal:
355
+ """
356
+ A Terminal component that can be embedded in Gradio Blocks.
357
+
358
+ This component provides an interactive terminal using xterm.js
359
+ that communicates with a PTY backend through Flask-SocketIO.
360
+
361
+ IMPORTANT: If using SSH tunneling, tunnel both Gradio port and terminal port:
362
+ ssh -L 7860:localhost:7860 -L 5000:localhost:5000 user@remote
363
+
364
+ Example:
365
+ import gradio as gr
366
+ from gradio_terminal import Terminal
367
+
368
+ with gr.Blocks() as demo:
369
+ gr.Markdown("# My App with Terminal")
370
+ terminal = Terminal()
371
+
372
+ demo.launch()
373
+ """
374
+
375
+ def __init__(
376
+ self,
377
+ port: int = 5000,
378
+ host: str = "127.0.0.1",
379
+ command: str = "bash",
380
+ height: int = 400,
381
+ label: str | None = None,
382
+ visible: bool = True,
383
+ elem_id: str | None = None,
384
+ elem_classes: list[str] | str | None = None,
385
+ ):
386
+ """
387
+ Create a Terminal component.
388
+
389
+ Args:
390
+ port: Port for the terminal WebSocket server (must be tunneled if using SSH).
391
+ host: Host for the terminal server.
392
+ command: Shell command to run (default: bash).
393
+ height: Height of the terminal in pixels.
394
+ label: Label for the component.
395
+ visible: Whether the terminal is visible.
396
+ elem_id: HTML element ID.
397
+ elem_classes: CSS classes.
398
+ """
399
+ self.port = port
400
+ self.host = host
401
+ self.command = command
402
+ self.height = height
403
+ self.label = label
404
+ self.visible = visible
405
+ self.elem_id = elem_id
406
+ self.elem_classes = elem_classes
407
+
408
+ # Start the terminal server
409
+ self._server = TerminalServer(port=port, host=host, command=command)
410
+ terminal_url = self._server.start()
411
+
412
+ # Build the HTML with iframe
413
+ label_html = ""
414
+ if label:
415
+ label_html = (
416
+ f'<div style="font-weight: bold; margin-bottom: 5px; color: #d4d4d4;">{label}</div>'
417
+ )
418
+
419
+ # Use localhost for iframe src (browser connects to tunneled port)
420
+ iframe_url = f"http://localhost:{port}"
421
+
422
+ self._component = gr.HTML(
423
+ value=f"""
424
+ {label_html}
425
+ <div style="border: 1px solid #444; border-radius: 5px; overflow: hidden;">
426
+ <iframe
427
+ src="{iframe_url}"
428
+ style="border: none; width: 100%; height: {height}px;"
429
+ allow="clipboard-read; clipboard-write"
430
+ ></iframe>
431
+ </div>
432
+ """,
433
+ visible=visible,
434
+ elem_id=elem_id,
435
+ elem_classes=elem_classes,
436
+ )
437
+
438
+ def stop(self):
439
+ """Stop the terminal server."""
440
+ self._server.stop()
441
+
442
+
443
+ def create_terminal(
444
+ port: int = 5000,
445
+ host: str = "127.0.0.1",
446
+ command: str = "bash",
447
+ height: int = 400,
448
+ label: str | None = None,
449
+ ) -> Terminal:
450
+ """
451
+ Create a terminal component that can be used in Gradio Blocks.
452
+
453
+ Args:
454
+ port: Port for the terminal WebSocket server.
455
+ host: Host for the terminal server.
456
+ command: Shell command to run (default: bash).
457
+ height: Height of the terminal in pixels.
458
+ label: Optional label for the terminal.
459
+
460
+ Returns:
461
+ A Terminal instance.
462
+ """
463
+ return Terminal(
464
+ port=port,
465
+ host=host,
466
+ command=command,
467
+ height=height,
468
+ label=label,
469
+ )
470
+
471
+
472
+ def create_terminal_demo(
473
+ port: int = 5000,
474
+ host: str = "127.0.0.1",
475
+ command: str = "bash",
476
+ height: int = 400,
477
+ ) -> gr.Blocks:
478
+ """
479
+ Create a Gradio Blocks demo with an embedded terminal.
480
+
481
+ Args:
482
+ port: Port for the terminal server.
483
+ host: Host for the terminal server.
484
+ command: Shell command to run.
485
+ height: Height of the terminal in pixels.
486
+
487
+ Returns:
488
+ A Gradio Blocks instance with the terminal.
489
+ """
490
+ with gr.Blocks(title="Gradio Terminal") as demo:
491
+ gr.Markdown("## Interactive Terminal")
492
+ gr.Markdown(f"Terminal server running on port {port}")
493
+
494
+ Terminal(port=port, host=host, command=command, height=height)
495
+
496
+ gr.Markdown(f"""
497
+ **Tips:**
498
+ - If using SSH tunneling, also tunnel port {port}:
499
+ `ssh -L 7860:localhost:7860 -L {port}:localhost:{port} user@remote`
500
+ """)
501
+
502
+ return demo
503
+
504
+
505
+ def launch_terminal(
506
+ port: int = 5000,
507
+ host: str = "127.0.0.1",
508
+ command: str = "bash",
509
+ share: bool = False,
510
+ **launch_kwargs,
511
+ ):
512
+ """
513
+ Launch a standalone Gradio app with a terminal.
514
+
515
+ Args:
516
+ port: Port for the terminal WebSocket server.
517
+ host: Host for the terminal server.
518
+ command: Shell command to run (default: bash).
519
+ share: Whether to create a public link.
520
+ **launch_kwargs: Additional arguments passed to demo.launch()
521
+ """
522
+ demo = create_terminal_demo(port=port, host=host, command=command)
523
+ demo.launch(share=share, **launch_kwargs)
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: gradio-terminal
3
+ Version: 0.1.0
4
+ Summary: A Gradio component that provides a fully functional terminal using xterm.js and PTY
5
+ Author: Po-Hsuan Huang
6
+ Author-email: Po-Hsuan Huang <aben20807@gmail.com>
7
+ License: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/aben20807/gradio-terminal
9
+ Project-URL: Repository, https://github.com/aben20807/gradio-terminal
10
+ Project-URL: Issues, https://github.com/aben20807/gradio-terminal/issues
11
+ Keywords: gradio,terminal,xterm,pty,shell
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: gradio>=6.3.0
26
+ Requires-Dist: flask>=3.1.2
27
+ Requires-Dist: flask-socketio>=5.6.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
30
+ Requires-Dist: black>=22.0.0; extra == "dev"
31
+ Requires-Dist: flake8>=4.0.0; extra == "dev"
32
+ Dynamic: author
33
+ Dynamic: license-file
34
+ Dynamic: requires-python
35
+
36
+ # Gradio Terminal
37
+
38
+ A Gradio component that provides a fully functional terminal in your browser. This package uses xterm.js on the frontend and a PTY on the backend to provide a real shell experience.
39
+
40
+ ![Gradio Terminal](https://github.com/user-attachments/assets/8a4cc81a-07a4-4c56-a008-bd438eae50de)
41
+
42
+ ## Installation
43
+
44
+ ```bash
45
+ pip install gradio-terminal
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ### Simple Usage
51
+
52
+ ```python
53
+ import gradio as gr
54
+ from gradio_terminal import Terminal
55
+ demo = gr.Blocks()
56
+ with demo:
57
+ terminal = Terminal()
58
+ demo.launch()
59
+ ```
60
+
61
+ ## API Reference
62
+
63
+ `launch_terminal(port=5000, host="127.0.0.1", command="bash", share=False, **launch_kwargs)`
64
+
65
+ Launch a standalone Gradio app with a terminal.
66
+
67
+ `create_terminal_demo(port=5000, host="127.0.0.1", command="bash", height=400)`
68
+
69
+ Create a Gradio Blocks demo with an embedded terminal.
70
+
71
+ `TerminalServer(port=5000, host="127.0.0.1", command="bash")`
72
+
73
+ Low-level terminal server for custom integrations.
74
+
75
+ - `start()`: Start the server and return the URL
76
+ - `get_url()`: Get the terminal server URL
77
+ - `stop()`: Stop the terminal server
78
+
79
+ ## Requirements
80
+
81
+ - Python 3.8+
82
+ - Linux
83
+ - Dependencies: gradio, flask, flask-socketio
84
+
85
+ ## Security Notice
86
+
87
+ This component provides shell access to your server. Use only in trusted environments.
88
+
89
+ ## License
90
+
91
+ This project is licensed under the Apache-2.0 License.
92
+
93
+ ## Acknowledgments
94
+
95
+ - [pyxtermjs](https://github.com/cs01/pyxtermjs) - Inspiration for the terminal implementation
96
+ - [xterm.js](https://xtermjs.org/) - Terminal emulator for the browser
97
+ - [Gradio](https://gradio.app/) - The awesome ML demo framework
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ src/gradio_terminal/__init__.py
6
+ src/gradio_terminal/terminal.py
7
+ src/gradio_terminal.egg-info/PKG-INFO
8
+ src/gradio_terminal.egg-info/SOURCES.txt
9
+ src/gradio_terminal.egg-info/dependency_links.txt
10
+ src/gradio_terminal.egg-info/requires.txt
11
+ src/gradio_terminal.egg-info/top_level.txt
@@ -0,0 +1,8 @@
1
+ gradio>=6.3.0
2
+ flask>=3.1.2
3
+ flask-socketio>=5.6.0
4
+
5
+ [dev]
6
+ pytest>=7.0.0
7
+ black>=22.0.0
8
+ flake8>=4.0.0
@@ -0,0 +1 @@
1
+ gradio_terminal