|
|
import subprocess |
|
|
import gradio as gr |
|
|
import threading |
|
|
import time |
|
|
import requests |
|
|
|
|
|
|
|
|
def is_server_running(url="http://localhost:3050", timeout=5): |
|
|
try: |
|
|
response = requests.get(url, timeout=timeout) |
|
|
return response.status_code < 400 |
|
|
except: |
|
|
return False |
|
|
|
|
|
|
|
|
def run_express(): |
|
|
try: |
|
|
|
|
|
|
|
|
|
|
|
subprocess.run(["node", "src/app.js"], check=True) |
|
|
except subprocess.CalledProcessError as e: |
|
|
print(f"Express server failed: {e}") |
|
|
except FileNotFoundError: |
|
|
print("Error: 'node' command not found. Make sure Node.js is installed and in PATH.") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if not is_server_running(): |
|
|
express_thread = threading.Thread(target=run_express, daemon=True) |
|
|
express_thread.start() |
|
|
|
|
|
time.sleep(2) |
|
|
|
|
|
|
|
|
def chat_with_ai(message, history): |
|
|
try: |
|
|
|
|
|
response = requests.post( |
|
|
"http://localhost:3050/api/chat", |
|
|
json={"messages": [{"role": "user", "content": message}]}, |
|
|
timeout=10 |
|
|
) |
|
|
|
|
|
response.raise_for_status() |
|
|
return response.text |
|
|
except requests.exceptions.RequestException as e: |
|
|
|
|
|
return f"Error connecting to Node.js backend: {str(e)}" |
|
|
except Exception as e: |
|
|
|
|
|
return f"An unexpected error occurred: {str(e)}" |
|
|
|
|
|
|
|
|
with gr.Blocks() as demo: |
|
|
gr.Markdown("# AI Chat Interface") |
|
|
|
|
|
chatbot = gr.ChatInterface(chat_with_ai) |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
|
|
|
demo.launch(server_name="0.0.0.0", server_port=7860) |
|
|
|