File size: 5,656 Bytes
58cec34
 
2839144
 
d7f0eff
 
3c7d3b0
58cec34
d7f0eff
3c7d3b0
d7f0eff
3c7d3b0
d7f0eff
3c7d3b0
d7f0eff
3c7d3b0
d7f0eff
 
 
 
3c7d3b0
 
 
 
d7f0eff
3c7d3b0
 
 
 
 
 
d7f0eff
3c7d3b0
 
 
 
 
 
 
 
 
 
 
 
d7f0eff
 
 
 
3c7d3b0
d7f0eff
3c7d3b0
 
 
 
d7f0eff
3c7d3b0
d7f0eff
2839144
d7f0eff
 
 
 
 
3c7d3b0
d7f0eff
 
 
 
 
3c7d3b0
 
d7f0eff
 
 
 
 
 
3c7d3b0
 
 
 
d7f0eff
 
 
 
 
 
 
 
 
 
 
2839144
3c7d3b0
d7f0eff
3c7d3b0
d7f0eff
 
 
2839144
d7f0eff
2839144
d7f0eff
2839144
3c7d3b0
 
 
 
 
 
 
d7f0eff
 
 
 
3c7d3b0
 
 
 
d7f0eff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/env python3
import os
import subprocess
import sys
import time
from pathlib import Path
import signal

def main():
    processes = []
    try:
        # Пути к исполняемым файлам
        api_binary = Path("/app/server/bin/api")
        playground_dir = Path("/app/playground")
        
        # Проверяем существование файлов
        if not api_binary.exists():
            print(f"ERROR: API binary not found at {api_binary}", file=sys.stderr)
            return 1
        
        if not playground_dir.exists():
            print(f"ERROR: Playground directory not found at {playground_dir}", file=sys.stderr)
            return 1
        
        # Запускаем API сервер
        print("Starting TEN-Agent API server on port 8080...")
        api_server_process = subprocess.Popen([str(api_binary)])
        processes.append(api_server_process)
        
        # Даем время API серверу запуститься
        time.sleep(3)
        
        # Запускаем Playground UI
        print("Starting Playground UI on port 3000...")
        playground_env = os.environ.copy()
        playground_env["AGENT_SERVER_URL"] = "http://localhost:8080"  # Подключаемся к локальному API серверу
        playground_process = subprocess.Popen(
            ["pnpm", "start", "--", "-p", "3000"],
            cwd=str(playground_dir),
            env=playground_env
        )
        processes.append(playground_process)
        
        # Запускаем простой HTTP сервер для Hugging Face
        from http.server import HTTPServer, SimpleHTTPRequestHandler
        
        class CustomHandler(SimpleHTTPRequestHandler):
            def do_GET(self):
                # Перенаправляем корневой запрос на Playground
                if self.path == '/':
                    self.send_response(301)
                    self.send_header('Location', 'http://localhost:3000')
                    self.end_headers()
                else:
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html; charset=utf-8')
                    self.end_headers()
                    
                    html_content = """
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>TEN Agent - Hugging Face Space</title>
                        <meta charset="utf-8">
                        <style>
                            body { font-family: Arial, sans-serif; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px; }
                            h1 { color: #333; }
                            .info { background: #f8f9fa; border-left: 4px solid #28a745; padding: 15px; margin-bottom: 20px; }
                            .endpoint { background: #e9ecef; padding: 10px; border-radius: 5px; font-family: monospace; }
                            .link { font-size: 18px; margin-top: 30px; text-align: center; }
                            .link a { display: inline-block; background: #0d6efd; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; }
                        </style>
                    </head>
                    <body>
                        <h1>TEN Agent запущен успешно!</h1>
                        <div class="info">
                            <p>TEN Agent API сервер работает на порту 8080.</p>
                            <p>Playground UI доступен на порту 3000.</p>
                        </div>
                        <div class="link">
                            <a href="http://localhost:3000">Открыть Playground UI</a>
                        </div>
                        <h2>API эндпоинты:</h2>
                        <ul>
                            <li><span class="endpoint">GET /health</span> - проверка состояния сервера</li>
                            <li><span class="endpoint">GET /list</span> - список запущенных агентов</li>
                            <li><span class="endpoint">GET /graphs</span> - доступные графы</li>
                        </ul>
                        <p>См. <a href="https://github.com/TEN-framework/TEN-Agent" target="_blank">документацию TEN Agent</a> для получения дополнительной информации.</p>
                    </body>
                    </html>
                    """
                    
                    self.wfile.write(html_content.encode('utf-8'))
        
        # Запускаем HTTP сервер для Hugging Face
        port = 7860  # Hugging Face Space обычно ожидает сервер на порту 7860
        print(f"Starting HTTP server on port {port}...")
        httpd = HTTPServer(('0.0.0.0', port), CustomHandler)
        httpd.serve_forever()
    
    except KeyboardInterrupt:
        print("Shutting down...")
    finally:
        # Завершаем все процессы при выходе
        for proc in processes:
            try:
                proc.terminate()
                proc.wait(timeout=5)
            except:
                proc.kill()
    
    return 0

if __name__ == "__main__":
    # Корректная обработка сигналов завершения
    signal.signal(signal.SIGINT, lambda sig, frame: sys.exit(0))
    signal.signal(signal.SIGTERM, lambda sig, frame: sys.exit(0))
    
    sys.exit(main())