File size: 15,306 Bytes
58cec34 2839144 d7f0eff 44a0185 d7f0eff 3c7d3b0 9f18430 44a0185 457c6f9 588adc0 44a0185 588adc0 44a0185 588adc0 44a0185 588adc0 44a0185 588adc0 44a0185 588adc0 9710cde 588adc0 457c6f9 588adc0 9710cde 588adc0 9710cde 588adc0 9710cde 9f18430 588adc0 9f18430 588adc0 db0df50 588adc0 2839144 588adc0 d7f0eff db0df50 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
#!/usr/bin/env python3
import os
import subprocess
import sys
import time
import json
from pathlib import Path
import signal
import threading
import shutil
import http.server
import socketserver
import urllib.request
import urllib.error
import gradio as gr
# Проверяем, запущены ли мы в HuggingFace Space
IS_HF_SPACE = os.environ.get("SPACE_ID") is not None
print(f"Running in HuggingFace Space: {IS_HF_SPACE}")
# Конфигурация путей
TMP_DIR = Path("/tmp/ten_user")
AGENTS_DIR = TMP_DIR / "agents"
LOGS_DIR = TMP_DIR / "logs"
NEXTJS_PORT = int(os.environ.get("UI_PORT", 3000))
API_PORT = int(os.environ.get("API_PORT", 8080))
GRADIO_PORT = int(os.environ.get("GRADIO_PORT", 7860))
# Адрес для подключения к UI в iframe
if IS_HF_SPACE:
# В HuggingFace Space нужно использовать внутренний URL
UI_URL = f"https://{os.environ.get('SPACE_ID', 'unknown-space')}.hf.space/_next/iframe/3000"
INTERNAL_HOST = "0.0.0.0"
else:
# В локальном окружении используем localhost
UI_URL = f"http://localhost:{NEXTJS_PORT}"
INTERNAL_HOST = "localhost"
def create_directories():
"""Создает необходимые директории"""
print("Создание директорий...")
TMP_DIR.mkdir(exist_ok=True, parents=True)
AGENTS_DIR.mkdir(exist_ok=True, parents=True)
LOGS_DIR.mkdir(exist_ok=True, parents=True)
# Создаем пустой файл логов
(LOGS_DIR / "server.log").touch()
print(f"Директории созданы в {TMP_DIR}")
def create_config_files():
"""Создает базовые файлы конфигурации"""
print("Создание конфигурационных файлов...")
# Создаем property.json с графами
property_data = {
"name": "TEN Agent Demo",
"version": "0.0.1",
"extensions": ["openai_chatgpt", "elevenlabs_tts", "deepgram_asr"],
"description": "TEN Agent on Hugging Face Space",
"graphs": [
{
"name": "Voice Agent",
"description": "Basic voice agent with OpenAI and ElevenLabs",
"file": "voice_agent.json"
},
{
"name": "Chat Agent",
"description": "Simple chat agent with OpenAI",
"file": "chat_agent.json"
}
]
}
with open(AGENTS_DIR / "property.json", "w") as f:
json.dump(property_data, f, indent=2)
# Создаем voice_agent.json
voice_agent = {
"_ten": {"version": "0.0.1"},
"nodes": [
{
"id": "start",
"type": "start",
"data": {"x": 100, "y": 100}
},
{
"id": "openai_chatgpt",
"type": "openai_chatgpt",
"data": {
"x": 300,
"y": 200,
"properties": {
"model": "gpt-3.5-turbo",
"temperature": 0.7,
"system_prompt": "You are a helpful assistant."
}
}
},
{
"id": "elevenlabs_tts",
"type": "elevenlabs_tts",
"data": {
"x": 500,
"y": 200,
"properties": {
"voice_id": "21m00Tcm4TlvDq8ikWAM"
}
}
},
{
"id": "deepgram_asr",
"type": "deepgram_asr",
"data": {
"x": 300,
"y": 300,
"properties": {
"language": "ru"
}
}
},
{
"id": "end",
"type": "end",
"data": {"x": 700, "y": 100}
}
],
"edges": [
{"id": "start_to_chatgpt", "source": "start", "target": "openai_chatgpt"},
{"id": "chatgpt_to_tts", "source": "openai_chatgpt", "target": "elevenlabs_tts"},
{"id": "tts_to_end", "source": "elevenlabs_tts", "target": "end"},
{"id": "asr_to_chatgpt", "source": "deepgram_asr", "target": "openai_chatgpt"}
],
"groups": [],
"templates": [],
"root": "start"
}
with open(AGENTS_DIR / "voice_agent.json", "w") as f:
json.dump(voice_agent, f, indent=2)
# Создаем chat_agent.json (упрощенная версия)
chat_agent = {
"_ten": {"version": "0.0.1"},
"nodes": [
{
"id": "start",
"type": "start",
"data": {"x": 100, "y": 100}
},
{
"id": "openai_chatgpt",
"type": "openai_chatgpt",
"data": {
"x": 300,
"y": 200,
"properties": {
"model": "gpt-3.5-turbo",
"temperature": 0.7,
"system_prompt": "You are a helpful chat assistant."
}
}
},
{
"id": "end",
"type": "end",
"data": {"x": 500, "y": 100}
}
],
"edges": [
{"id": "start_to_chatgpt", "source": "start", "target": "openai_chatgpt"},
{"id": "chatgpt_to_end", "source": "openai_chatgpt", "target": "end"}
],
"groups": [],
"templates": [],
"root": "start"
}
with open(AGENTS_DIR / "chat_agent.json", "w") as f:
json.dump(chat_agent, f, indent=2)
print("Конфигурационные файлы созданы успешно")
def start_api_server():
"""Запускает API сервер"""
print("Запуск API сервера...")
# Устанавливаем переменные окружения
api_env = os.environ.copy()
api_env["TEN_AGENT_DIR"] = str(AGENTS_DIR)
api_env["API_PORT"] = str(API_PORT)
# В HuggingFace Space нужны дополнительные настройки
if IS_HF_SPACE:
print("Configuring API server for HuggingFace Space environment...")
# Указываем серверу специально использовать API wrapper
api_env["USE_WRAPPER"] = "true"
# Отключаем логирование в файл
api_env["TEN_LOG_DISABLE_FILE"] = "true"
# Указываем путь для временных файлов
api_env["TMP_DIR"] = str(TMP_DIR)
# Запускаем Python API wrapper
api_cmd = ["python", "api_wrapper.py"]
print(f"Running API command: {' '.join(api_cmd)}")
api_process = subprocess.Popen(
api_cmd,
env=api_env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Ждем запуска сервера
time.sleep(2)
# Проверяем, что процесс не упал
if api_process.poll() is not None:
stdout, stderr = api_process.communicate()
print(f"API сервер не запустился!")
print(f"STDOUT: {stdout.decode()}")
print(f"STDERR: {stderr.decode()}")
return None
print(f"API server started and listening on port {API_PORT}")
# Запускаем поток для вывода логов
def log_output(process, prefix):
for line in iter(process.stdout.readline, b''):
print(f"[{prefix}] {line.decode().strip()}")
for line in iter(process.stderr.readline, b''):
print(f"[{prefix} ERROR] {line.decode().strip()}")
log_thread = threading.Thread(target=log_output, args=(api_process, "API"))
log_thread.daemon = True
log_thread.start()
return api_process
def start_playground():
"""Запускает Playground UI через Next.js"""
print("Запуск Playground UI...")
# Устанавливаем переменные окружения
ui_env = os.environ.copy()
ui_env["PORT"] = str(NEXTJS_PORT)
ui_env["AGENT_SERVER_URL"] = f"http://{INTERNAL_HOST}:{API_PORT}"
ui_env["NEXT_PUBLIC_EDIT_GRAPH_MODE"] = "true"
ui_env["NEXT_PUBLIC_DISABLE_CAMERA"] = "false"
# В HuggingFace Space нужны дополнительные настройки
if IS_HF_SPACE:
print("Configuring for HuggingFace Space environment...")
ui_env["NEXT_PUBLIC_IS_HF_SPACE"] = "true"
# Отключаем строгие проверки CORS для работы в iframe
ui_env["NEXT_PUBLIC_DISABLE_CORS"] = "true"
# Запускаем UI
ui_cmd = "cd playground && npm run dev"
print(f"Running UI command: {ui_cmd}")
ui_process = subprocess.Popen(
ui_cmd,
env=ui_env,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Ждем запуска UI
time.sleep(5)
# Проверяем, что процесс не упал
if ui_process.poll() is not None:
stdout, stderr = ui_process.communicate()
print(f"Playground UI не запустился!")
print(f"STDOUT: {stdout.decode()}")
print(f"STDERR: {stderr.decode()}")
return None
# Запускаем поток для вывода логов
def log_output(process, prefix):
for line in iter(process.stdout.readline, b''):
print(f"[{prefix}] {line.decode().strip()}")
for line in iter(process.stderr.readline, b''):
print(f"[{prefix} ERROR] {line.decode().strip()}")
log_thread = threading.Thread(target=log_output, args=(ui_process, "UI"))
log_thread.daemon = True
log_thread.start()
return ui_process
def create_interface():
"""Создает Gradio интерфейс для редиректа"""
with gr.Blocks() as demo:
gr.Markdown("# TEN Agent на Hugging Face Space")
gr.Markdown("## Загрузка приложения...")
# Статус серверов
status_md = gr.Markdown("### Статус: Инициализация...")
with gr.Row():
col1, col2 = gr.Column(), gr.Column()
with col1:
# Кнопка для открытия UI в iframe
open_iframe = gr.Button("Показать TEN Agent в iframe")
# Функция для открытия UI в iframe
def show_iframe():
return f"""
<div style="border: 1px solid #ccc; padding: 10px; border-radius: 5px;">
<iframe src="{UI_URL}" width="100%" height="600px" frameborder="0"></iframe>
</div>
"""
iframe_area = gr.HTML()
open_iframe.click(show_iframe, outputs=iframe_area)
with col2:
# Ссылка на UI
gr.Markdown(f"""
### Открыть TEN Agent в новой вкладке:
<a href="{UI_URL}" target="_blank" style="display: inline-block; padding: 10px 15px; background-color: #4CAF50; color: white; text-decoration: none; border-radius: 4px; margin: 10px 0;">Открыть TEN Agent UI</a>
### ВАЖНО:
Настройте API ключи в интерфейсе для полноценной работы:
- OpenAI API Key
- ElevenLabs API Key
- Deepgram API Key
- Agora App ID и Certificate
""")
# Статус серверов и логи
with gr.Accordion("Системная информация", open=False):
api_status = gr.Textbox(label="Статус API сервера", value="Запускается...", interactive=False)
ui_status = gr.Textbox(label="Статус UI сервера", value="Запускается...", interactive=False)
# Функция обновления статуса
def update_status():
api_status_msg = "✅ Активен" if is_port_in_use(API_PORT) else "❌ Не активен"
ui_status_msg = "✅ Активен" if is_port_in_use(NEXTJS_PORT) else "❌ Не активен"
status_md_msg = f"### Статус: {'✅ Все системы работают' if is_port_in_use(API_PORT) and is_port_in_use(NEXTJS_PORT) else '⚠️ Есть проблемы'}"
return [api_status_msg, ui_status_msg, status_md_msg]
status_btn = gr.Button("Обновить статус")
status_btn.click(update_status, outputs=[api_status, ui_status, status_md])
return demo
# Вспомогательная функция для проверки, используется ли порт
def is_port_in_use(port):
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect(('localhost', port))
return True
except:
return False
def main():
# Создаем директории и файлы конфигурации
create_directories()
create_config_files()
# Запускаем API сервер
api_process = start_api_server()
if not api_process:
print("Не удалось запустить API сервер")
return
# Запускаем Playground UI
ui_process = start_playground()
if not ui_process:
print("Не удалось запустить Playground UI")
api_process.terminate()
return
# Создаем Gradio интерфейс
demo = create_interface()
# Запускаем Gradio
demo.launch(server_port=GRADIO_PORT, server_name=INTERNAL_HOST, share=False)
# Остаемся в цикле до завершения процессов
try:
while True:
if api_process.poll() is not None:
print("API сервер остановлен")
ui_process.terminate()
break
if ui_process.poll() is not None:
print("UI остановлен")
api_process.terminate()
break
time.sleep(1)
except KeyboardInterrupt:
print("Принудительная остановка...")
api_process.terminate()
ui_process.terminate()
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()) |