Spaces:
Runtime error
Runtime error
Upload tunnel_manager.py with huggingface_hub
Browse files- tunnel_manager.py +118 -0
tunnel_manager.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pyngrok import ngrok, conf
|
2 |
+
import psutil
|
3 |
+
import time
|
4 |
+
import os
|
5 |
+
import json
|
6 |
+
import yaml
|
7 |
+
import requests
|
8 |
+
from requests.exceptions import ConnectionError
|
9 |
+
|
10 |
+
class TunnelManager:
|
11 |
+
DEFAULT_PORT = 5000
|
12 |
+
_current_tunnel = None
|
13 |
+
_ngrok_process = None
|
14 |
+
|
15 |
+
@staticmethod
|
16 |
+
def load_config():
|
17 |
+
"""Carga la configuración desde config.yaml"""
|
18 |
+
try:
|
19 |
+
config_path = os.path.join(os.path.dirname(__file__), 'config.yaml')
|
20 |
+
with open(config_path, 'r') as f:
|
21 |
+
return yaml.safe_load(f)
|
22 |
+
except Exception as e:
|
23 |
+
print(f"Error al cargar config.yaml: {e}")
|
24 |
+
return {}
|
25 |
+
|
26 |
+
@staticmethod
|
27 |
+
def setup_ngrok():
|
28 |
+
"""Configura ngrok con el token del archivo config.yaml"""
|
29 |
+
config = TunnelManager.load_config()
|
30 |
+
token = config.get('NGROK_TOKEN')
|
31 |
+
|
32 |
+
if token:
|
33 |
+
try:
|
34 |
+
ngrok.set_auth_token(token)
|
35 |
+
return True
|
36 |
+
except Exception as e:
|
37 |
+
print(f"Error al configurar el token de ngrok: {e}")
|
38 |
+
return False
|
39 |
+
|
40 |
+
@staticmethod
|
41 |
+
def cleanup():
|
42 |
+
"""Limpia todas las sesiones de ngrok existentes"""
|
43 |
+
try:
|
44 |
+
print("\nLimpiando sesiones anteriores...")
|
45 |
+
# Intentar matar procesos de ngrok usando psutil
|
46 |
+
for proc in psutil.process_iter(['pid', 'name']):
|
47 |
+
try:
|
48 |
+
if 'ngrok' in proc.name().lower():
|
49 |
+
proc.kill()
|
50 |
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
51 |
+
pass
|
52 |
+
|
53 |
+
# Usar el método de pyngrok para limpiar
|
54 |
+
ngrok.kill()
|
55 |
+
time.sleep(2) # Dar tiempo para que los procesos terminen
|
56 |
+
print("✓ Limpieza completada")
|
57 |
+
TunnelManager._current_tunnel = None
|
58 |
+
except Exception as e:
|
59 |
+
print(f"Error durante la limpieza: {e}")
|
60 |
+
|
61 |
+
@classmethod
|
62 |
+
def get_active_tunnel(cls):
|
63 |
+
"""Obtiene la URL del túnel activo más reciente"""
|
64 |
+
try:
|
65 |
+
# Intentar diferentes puertos comunes de ngrok
|
66 |
+
ports = [4040, 4041, 5000]
|
67 |
+
for port in ports:
|
68 |
+
try:
|
69 |
+
response = requests.get(f"http://127.0.0.1:{port}/api/tunnels", timeout=1)
|
70 |
+
if response.status_code == 200:
|
71 |
+
tunnels = response.json()["tunnels"]
|
72 |
+
if tunnels:
|
73 |
+
for tunnel in tunnels:
|
74 |
+
if tunnel["proto"] == "https":
|
75 |
+
cls._current_tunnel = tunnel["public_url"]
|
76 |
+
return cls._current_tunnel
|
77 |
+
except ConnectionError:
|
78 |
+
continue
|
79 |
+
except Exception:
|
80 |
+
continue
|
81 |
+
return None
|
82 |
+
except Exception as e:
|
83 |
+
print(f"No se encontraron túneles activos")
|
84 |
+
return None
|
85 |
+
|
86 |
+
@classmethod
|
87 |
+
def start(cls, port=5000):
|
88 |
+
"""Inicia un túnel de ngrok"""
|
89 |
+
if cls._current_tunnel:
|
90 |
+
return cls._current_tunnel
|
91 |
+
|
92 |
+
try:
|
93 |
+
# Asegurarse de que no hay túneles activos
|
94 |
+
cls.cleanup()
|
95 |
+
|
96 |
+
# Configurar e iniciar nuevo túnel
|
97 |
+
tunnel = ngrok.connect(port, "http")
|
98 |
+
cls._current_tunnel = tunnel.public_url
|
99 |
+
|
100 |
+
# Verificar que el túnel está activo
|
101 |
+
time.sleep(1)
|
102 |
+
tunnels = ngrok.get_tunnels()
|
103 |
+
if not tunnels:
|
104 |
+
raise Exception("No se pudo establecer el túnel")
|
105 |
+
|
106 |
+
return cls._current_tunnel
|
107 |
+
|
108 |
+
except Exception as e:
|
109 |
+
print(f"Error iniciando túnel: {e}")
|
110 |
+
return None
|
111 |
+
|
112 |
+
@staticmethod
|
113 |
+
def get_tunnels():
|
114 |
+
"""Obtiene la lista de túneles activos"""
|
115 |
+
try:
|
116 |
+
return ngrok.get_tunnels()
|
117 |
+
except:
|
118 |
+
return []
|