File size: 2,635 Bytes
9a25fdb 7059f42 e63d6e7 acf00c7 7059f42 1201054 5ef0a32 acf00c7 1201054 e63d6e7 acf00c7 1201054 acf00c7 1201054 acf00c7 1201054 acf00c7 1201054 acf00c7 e63d6e7 1201054 acf00c7 1201054 acf00c7 5ef0a32 acf00c7 1201054 b2d88c8 acf00c7 b2d88c8 1201054 b2d88c8 acf00c7 1201054 b2d88c8 7059f42 1201054 9a25fdb acf00c7 1201054 acf00c7 9a25fdb 1201054 acf00c7 1201054 | 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 | import subprocess
import gradio as gr
import threading
import time
import requests
# Fungsi untuk mengecek apakah Express server sudah berjalan
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
# Fungsi untuk menjalankan Express.js
def run_express():
try:
# Menjalankan Express server. subprocess.run akan menunggu sampai Express selesai
# atau mengalami error jika check=True. Karena ini dijalankan di thread,
# ini tidak akan memblokir main thread Python.
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.")
# Memulai Express di thread terpisah jika belum berjalan
# Penting: Fungsi is_server_running dan threading ini mungkin tidak terlalu diperlukan
# jika start.sh sudah menjalankan Node.js dengan benar.
# Namun, tidak ada salahnya sebagai lapisan pengaman.
if not is_server_running():
express_thread = threading.Thread(target=run_express, daemon=True)
express_thread.start()
# Beri waktu sebentar untuk server Express memulai
time.sleep(2)
# Antarmuka Gradio
def chat_with_ai(message, history):
try:
# Mengirim permintaan ke server Node.js lokal di port 3000
response = requests.post(
"http://localhost:3050/api/chat",
json={"messages": [{"role": "user", "content": message}]},
timeout=10
)
# Melemparkan pengecualian jika status respons adalah 4xx atau 5xx
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
# Menangkap error terkait permintaan HTTP (misalnya, koneksi ditolak, timeout)
return f"Error connecting to Node.js backend: {str(e)}"
except Exception as e:
# Menangkap error umum lainnya
return f"An unexpected error occurred: {str(e)}"
# Membuat blok Gradio
with gr.Blocks() as demo:
gr.Markdown("# AI Chat Interface")
# Menggunakan Gradio ChatInterface dengan fungsi chat_with_ai
chatbot = gr.ChatInterface(chat_with_ai)
# Meluncurkan aplikasi Gradio
if __name__ == "__main__":
# Penting: Mengatur server_name ke "0.0.0.0" agar dapat diakses dari luar kontainer
# dan server_port ke 7860 (port default Gradio yang diekspos Hugging Face).
demo.launch(server_name="0.0.0.0", server_port=7860)
|