3v324v23 commited on
Commit
74e8d5b
·
1 Parent(s): 2455e56

Исправлены проблемы с запуском Next.js и директориями для логов

Browse files
Files changed (1) hide show
  1. app.py +69 -58
app.py CHANGED
@@ -22,90 +22,101 @@ def main():
22
  if not playground_dir.exists():
23
  print(f"ERROR: Playground directory not found at {playground_dir}", file=sys.stderr)
24
  return 1
 
 
 
25
 
26
  # Запускаем API сервер
27
  print("Starting TEN-Agent API server on port 8080...")
28
- api_server_process = subprocess.Popen([str(api_binary)])
 
 
 
29
  processes.append(api_server_process)
30
 
31
  # Даем время API серверу запуститься
32
- time.sleep(3)
33
 
34
  # Запускаем Playground UI
35
  print("Starting Playground UI on port 3000...")
36
  playground_env = os.environ.copy()
37
  playground_env["AGENT_SERVER_URL"] = "http://localhost:8080" # Подключаемся к локальному API серверу
 
 
38
  playground_process = subprocess.Popen(
39
- ["pnpm", "start", "--", "-p", "3000"],
40
  cwd=str(playground_dir),
41
  env=playground_env
42
  )
43
  processes.append(playground_process)
44
 
45
- # Запускаем прокси для Hugging Face
 
 
 
46
  from http.server import HTTPServer, SimpleHTTPRequestHandler
47
- import http.client
48
- import socketserver
49
 
50
- class ProxyHandler(SimpleHTTPRequestHandler):
51
  def do_GET(self):
52
- # Направляем запросы к Playground UI
53
- if self.path == '/' or self.path.startswith('/about') or self.path.startswith('/_next') or self.path.startswith('/favicon.ico'):
54
- self._proxy_request('localhost', 3000, self.path)
55
- # Направляем API запросы к API серверу
56
- elif self.path.startswith('/health') or self.path.startswith('/list') or self.path.startswith('/graphs'):
57
- self._proxy_request('localhost', 8080, self.path)
58
- else:
59
- # По умолчанию отправляем на Playground
60
- self._proxy_request('localhost', 3000, self.path)
61
-
62
- def do_POST(self):
63
- # Все POST запросы направляем в API
64
- self._proxy_request('localhost', 8080, self.path)
65
 
66
- def _proxy_request(self, host, port, path):
67
- try:
68
- # Создаем соединение с целевым сервером
69
- conn = http.client.HTTPConnection(host, port)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- # Копируем заголовки запроса
72
- headers = {}
73
- for header in self.headers:
74
- headers[header] = self.headers[header]
75
 
76
- # Получаем данные запроса
77
- content_length = int(self.headers.get('Content-Length', 0))
78
- body = self.rfile.read(content_length) if content_length > 0 else None
 
 
 
 
79
 
80
- # Отправляем запрос на целевой сервер
81
- conn.request(self.command, path, body=body, headers=headers)
82
- resp = conn.getresponse()
 
 
 
 
 
 
83
 
84
- # Отправляем ответ клиенту
85
- self.send_response(resp.status)
86
- for header in resp.headers:
87
- self.send_header(header, resp.headers[header])
88
- self.end_headers()
89
-
90
- # Отправляем тело ответа
91
- self.wfile.write(resp.read())
92
- conn.close()
93
- except Exception as e:
94
- print(f"Proxy error: {e}", file=sys.stderr)
95
- self.send_response(500)
96
- self.send_header('Content-type', 'text/plain; charset=utf-8')
97
- self.end_headers()
98
- self.wfile.write(f"Proxy error: {e}".encode('utf-8'))
99
-
100
- # Запускаем HTTP прокси-сервер
101
- port = 7860 # Hugging Face Space ожидает сервер на этом порту
102
- print(f"Starting proxy server on port {port}, forwarding to Playground UI and API...")
103
 
104
- # Разрешаем повторное использование адреса и порта
105
- class ReuseAddressServer(socketserver.TCPServer):
106
- allow_reuse_address = True
107
-
108
- httpd = ReuseAddressServer(('0.0.0.0', port), ProxyHandler)
109
  httpd.serve_forever()
110
 
111
  except KeyboardInterrupt:
 
22
  if not playground_dir.exists():
23
  print(f"ERROR: Playground directory not found at {playground_dir}", file=sys.stderr)
24
  return 1
25
+
26
+ # Создаем директорию для логов
27
+ os.makedirs("/tmp/ten_agent", exist_ok=True)
28
 
29
  # Запускаем API сервер
30
  print("Starting TEN-Agent API server on port 8080...")
31
+ api_server_env = os.environ.copy()
32
+ api_server_env["LOG_PATH"] = "/tmp/ten_agent"
33
+ api_server_env["LOG_STDOUT"] = "true"
34
+ api_server_process = subprocess.Popen([str(api_binary)], env=api_server_env)
35
  processes.append(api_server_process)
36
 
37
  # Даем время API серверу запуститься
38
+ time.sleep(5)
39
 
40
  # Запускаем Playground UI
41
  print("Starting Playground UI on port 3000...")
42
  playground_env = os.environ.copy()
43
  playground_env["AGENT_SERVER_URL"] = "http://localhost:8080" # Подключаемся к локальному API серверу
44
+
45
+ # Исправляем параметры командной строки для Next.js
46
  playground_process = subprocess.Popen(
47
+ ["pnpm", "start", "--", "--port", "3000"],
48
  cwd=str(playground_dir),
49
  env=playground_env
50
  )
51
  processes.append(playground_process)
52
 
53
+ # Даем время Playground UI запуститься
54
+ time.sleep(5)
55
+
56
+ # Запускаем простую HTML страницу для Hugging Face
57
  from http.server import HTTPServer, SimpleHTTPRequestHandler
 
 
58
 
59
+ class SimpleHandler(SimpleHTTPRequestHandler):
60
  def do_GET(self):
61
+ self.send_response(200)
62
+ self.send_header('Content-type', 'text/html; charset=utf-8')
63
+ self.end_headers()
 
 
 
 
 
 
 
 
 
 
64
 
65
+ html_content = """
66
+ <!DOCTYPE html>
67
+ <html>
68
+ <head>
69
+ <title>TEN Agent - Hugging Face Space</title>
70
+ <meta charset="utf-8">
71
+ <style>
72
+ body { font-family: Arial, sans-serif; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px; }
73
+ h1 { color: #333; }
74
+ .info { background: #f8f9fa; border-left: 4px solid #28a745; padding: 15px; margin-bottom: 20px; }
75
+ .warning { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin-bottom: 20px; }
76
+ .endpoint { background: #e9ecef; padding: 10px; border-radius: 5px; font-family: monospace; }
77
+ .api { margin-top: 30px; }
78
+ </style>
79
+ </head>
80
+ <body>
81
+ <h1>TEN Agent запущен успешно!</h1>
82
+ <div class="info">
83
+ <p>TEN Agent API сервер работает на порту 8080.</p>
84
+ <p>Playground UI запущен на порту 3000.</p>
85
+ </div>
86
 
87
+ <div class="warning">
88
+ <p><strong>Внимание:</strong> Из-за огр��ничений Hugging Face Space, доступ к интерфейсу через прокси может быть нестабильным.</p>
89
+ </div>
 
90
 
91
+ <div class="api">
92
+ <h2>API эндпоинты:</h2>
93
+ <ul>
94
+ <li>API сервер: <span class="endpoint">http://localhost:8080</span></li>
95
+ <li>Playground UI: <span class="endpoint">http://localhost:3000</span></li>
96
+ </ul>
97
+ </div>
98
 
99
+ <h2>Инструкция по локальному использованию</h2>
100
+ <p>Для наилучшего опыта, подключите локальный Playground к этому API:</p>
101
+ <ol>
102
+ <li>Клонируйте репозиторий: <code>git clone https://github.com/TEN-framework/TEN-Agent.git</code></li>
103
+ <li>Перейдите в директорию playground: <code>cd TEN-Agent/playground</code></li>
104
+ <li>Установите зависимости: <code>pnpm install</code></li>
105
+ <li>Запустите Playground с подключением к API: <code>AGENT_SERVER_URL=https://nitrox-ten.hf.space pnpm dev</code></li>
106
+ <li>Откройте в браузере: <code>http://localhost:3000</code></li>
107
+ </ol>
108
 
109
+ <p>См. <a href="https://github.com/TEN-framework/TEN-Agent" target="_blank">документацию TEN Agent</a> для получения дополнительной информации.</p>
110
+ </body>
111
+ </html>
112
+ """
113
+
114
+ self.wfile.write(html_content.encode('utf-8'))
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
+ # Запускаем HTTP сервер
117
+ port = 7860 # Hugging Face Space обычно ожидает сервер на порту 7860
118
+ print(f"Starting HTTP server on port {port}...")
119
+ httpd = HTTPServer(('0.0.0.0', port), SimpleHandler)
 
120
  httpd.serve_forever()
121
 
122
  except KeyboardInterrupt: