gradio-tunneling 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,9 @@
1
+ Metadata-Version: 1.2
2
+ Name: gradio-tunneling
3
+ Version: 0.1.0
4
+ Summary: UNKNOWN
5
+ Home-page: UNKNOWN
6
+ License: UNKNOWN
7
+ Description: UNKNOWN
8
+ Platform: UNKNOWN
9
+ Requires-Python: >=3.8
@@ -0,0 +1,11 @@
1
+ ## Setup
2
+
3
+ ```sh
4
+ pip install -r requirements.txt
5
+ ```
6
+
7
+ ## Run tunnel
8
+
9
+ ```sh
10
+ python tunneling.py --port 7860
11
+ ```
File without changes
@@ -0,0 +1,186 @@
1
+ import atexit
2
+ import os
3
+ import platform
4
+ import re
5
+ import stat
6
+ import subprocess
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+ from typing import List, Optional
11
+
12
+ import requests
13
+
14
+ VERSION = "0.2"
15
+ CURRENT_TUNNELS: List["Tunnel"] = []
16
+
17
+ machine = platform.machine()
18
+ if machine == "x86_64":
19
+ machine = "amd64"
20
+
21
+ BINARY_REMOTE_NAME = f"frpc_{platform.system().lower()}_{machine.lower()}"
22
+ EXTENSION = ".exe" if os.name == "nt" else ""
23
+ BINARY_URL = f"https://cdn-media.huggingface.co/frpc-gradio-{VERSION}/{BINARY_REMOTE_NAME}{EXTENSION}"
24
+
25
+ BINARY_FILENAME = f"{BINARY_REMOTE_NAME}_v{VERSION}"
26
+ BINARY_FOLDER = Path(__file__).parent.absolute()
27
+ BINARY_PATH = f"{BINARY_FOLDER / BINARY_FILENAME}"
28
+
29
+ TUNNEL_TIMEOUT_SECONDS = 30
30
+ TUNNEL_ERROR_MESSAGE = (
31
+ "Could not create share URL. "
32
+ "Please check the appended log from frpc for more information:"
33
+ )
34
+
35
+ GRADIO_API_SERVER = "https://api.gradio.app/v2/tunnel-request"
36
+ GRADIO_SHARE_SERVER_ADDRESS = None
37
+
38
+
39
+ class Tunnel:
40
+ def __init__(self, remote_host, remote_port, local_host, local_port, share_token):
41
+ self.proc = None
42
+ self.url = None
43
+ self.remote_host = remote_host
44
+ self.remote_port = remote_port
45
+ self.local_host = local_host
46
+ self.local_port = local_port
47
+ self.share_token = share_token
48
+
49
+ @staticmethod
50
+ def download_binary():
51
+ if not Path(BINARY_PATH).exists():
52
+ resp = requests.get(BINARY_URL)
53
+
54
+ if resp.status_code == 403:
55
+ raise OSError(
56
+ f"Cannot set up a share link as this platform is incompatible. Please "
57
+ f"create a GitHub issue with information about your platform: {platform.uname()}"
58
+ )
59
+
60
+ resp.raise_for_status()
61
+
62
+ # Save file data to local copy
63
+ with open(BINARY_PATH, "wb") as file:
64
+ file.write(resp.content)
65
+ st = os.stat(BINARY_PATH)
66
+ os.chmod(BINARY_PATH, st.st_mode | stat.S_IEXEC)
67
+
68
+ def start_tunnel(self) -> str:
69
+ self.download_binary()
70
+ self.url = self._start_tunnel(BINARY_PATH)
71
+ return self.url
72
+
73
+ def kill(self):
74
+ if self.proc is not None:
75
+ print(f"Killing tunnel {self.local_host}:{self.local_port} <> {self.url}")
76
+ self.proc.terminate()
77
+ self.proc = None
78
+
79
+ def _start_tunnel(self, binary: str) -> str:
80
+ CURRENT_TUNNELS.append(self)
81
+ command = [
82
+ binary,
83
+ "http",
84
+ "-n",
85
+ self.share_token,
86
+ "-l",
87
+ str(self.local_port),
88
+ "-i",
89
+ self.local_host,
90
+ "--uc",
91
+ "--sd",
92
+ "random",
93
+ "--ue",
94
+ "--server_addr",
95
+ f"{self.remote_host}:{self.remote_port}",
96
+ "--disable_log_color",
97
+ ]
98
+ self.proc = subprocess.Popen(
99
+ command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
100
+ )
101
+ atexit.register(self.kill)
102
+ return self._read_url_from_tunnel_stream()
103
+
104
+ def _read_url_from_tunnel_stream(self) -> str:
105
+ start_timestamp = time.time()
106
+
107
+ log = []
108
+ url = ""
109
+
110
+ def _raise_tunnel_error():
111
+ log_text = "\n".join(log)
112
+ print(log_text, file=sys.stderr)
113
+ raise ValueError(f"{TUNNEL_ERROR_MESSAGE}\n{log_text}")
114
+
115
+ while url == "":
116
+ # check for timeout and log
117
+ if time.time() - start_timestamp >= TUNNEL_TIMEOUT_SECONDS:
118
+ _raise_tunnel_error()
119
+
120
+ assert self.proc is not None
121
+ if self.proc.stdout is None:
122
+ continue
123
+
124
+ line = self.proc.stdout.readline()
125
+ line = line.decode("utf-8")
126
+
127
+ if line == "":
128
+ continue
129
+
130
+ log.append(line.strip())
131
+
132
+ if "start proxy success" in line:
133
+ result = re.search("start proxy success: (.+)\n", line)
134
+ if result is None:
135
+ _raise_tunnel_error()
136
+ else:
137
+ url = result.group(1)
138
+ elif "login to server failed" in line:
139
+ _raise_tunnel_error()
140
+
141
+ return url
142
+
143
+
144
+ def setup_tunnel(
145
+ local_host: str, local_port: int, share_token: str, share_server_address: Optional[str]
146
+ ) -> str:
147
+ share_server_address = (
148
+ GRADIO_SHARE_SERVER_ADDRESS
149
+ if share_server_address is None
150
+ else share_server_address
151
+ )
152
+ if share_server_address is None:
153
+ response = requests.get(GRADIO_API_SERVER)
154
+ if not (response and response.status_code == 200):
155
+ raise RuntimeError("Could not get share link from Gradio API Server.")
156
+ payload = response.json()[0]
157
+ remote_host, remote_port = payload["host"], int(payload["port"])
158
+ else:
159
+ remote_host, remote_port = share_server_address.split(":")
160
+ remote_port = int(remote_port)
161
+ try:
162
+ tunnel = Tunnel(remote_host, remote_port, local_host, local_port, share_token)
163
+ address = tunnel.start_tunnel()
164
+ return address
165
+ except Exception as e:
166
+ raise RuntimeError(str(e)) from e
167
+
168
+
169
+ def main():
170
+ import argparse
171
+ import secrets
172
+ import time
173
+
174
+ parser = argparse.ArgumentParser(description='Set up a tunnel.')
175
+ parser.add_argument('--port', type=int, default=8080, help='the port number to use for the tunnel.')
176
+ args = parser.parse_args()
177
+
178
+ address = setup_tunnel('127.0.0.1', args.port, secrets.token_urlsafe(32), None)
179
+
180
+ print(f"公网访问地址:{address}")
181
+ print("这个共享链接将在 72 小时后过期,此程序将在 72 小时后关闭。")
182
+ time.sleep(3600 * 24 * 3)
183
+
184
+
185
+ if __name__ == '__main__':
186
+ main()
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 1.2
2
+ Name: gradio-tunneling
3
+ Version: 0.1.0
4
+ Summary: UNKNOWN
5
+ Home-page: UNKNOWN
6
+ License: UNKNOWN
7
+ Description: UNKNOWN
8
+ Platform: UNKNOWN
9
+ Requires-Python: >=3.8
@@ -0,0 +1,16 @@
1
+ README.md
2
+ setup.py
3
+ gradio_tunneling/__init__.py
4
+ gradio_tunneling/frpc_darwin_amd64_v0.2
5
+ gradio_tunneling/frpc_darwin_arm64_v0.2
6
+ gradio_tunneling/frpc_linux_amd64_v0.2
7
+ gradio_tunneling/frpc_linux_arm64_v0.2
8
+ gradio_tunneling/frpc_windows_amd64_v0.2
9
+ gradio_tunneling/frpc_windows_amd64_v0.2.exe
10
+ gradio_tunneling/main.py
11
+ gradio_tunneling.egg-info/PKG-INFO
12
+ gradio_tunneling.egg-info/SOURCES.txt
13
+ gradio_tunneling.egg-info/dependency_links.txt
14
+ gradio_tunneling.egg-info/entry_points.txt
15
+ gradio_tunneling.egg-info/requires.txt
16
+ gradio_tunneling.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ gradio-tunneling = gradio_tunneling.main:main
3
+
@@ -0,0 +1 @@
1
+ gradio_tunneling
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,24 @@
1
+ # setup.py
2
+
3
+ from setuptools import setup, find_packages
4
+
5
+ setup(
6
+ name='gradio-tunneling',
7
+ version='0.1.0',
8
+ packages=find_packages(),
9
+ package_data={
10
+ 'gradio_tunneling': ['frpc*'],
11
+ },
12
+ install_requires=[
13
+ # List your dependencies here
14
+ 'requests',
15
+ # 'some-other-package',
16
+ ],
17
+ entry_points={
18
+ 'console_scripts': [
19
+ 'gradio-tunneling=gradio_tunneling.main:main',
20
+ ],
21
+ },
22
+ python_requires='>=3.8',
23
+ )
24
+