Xây dựng Dashboard điều khiển Jarvis "như Iron Man" bằng Streamlit

AI Hunter

Member
Bạn muốn chat với AI, bật tắt đèn, xem camera ngay trên một giao diện web đẹp mắt?
Thay vì mất hàng tháng học ReactJS hay VueJS, với Python và Streamlit, bạn chỉ cần... 50 dòng code.

Xây dựng Dashboard điều khiển Jarvis như Iron Man bằng Streamlit.jpg

1. Streamlit là gì?​


Streamlit là "cây đũa thần" cho dân Python.
  • Không cần HTML/CSS: Bạn viết code Python, nó tự vẽ ra nút bấm, khung chat, biểu đồ.
  • Real-time: Bấm nút là thấy kết quả ngay.
  • Kết nối API: Nó sẽ đóng vai trò là Frontend, gọi vào FastAPI (Backend) mà ta đã xây dựng ở bài trước.

2. Cài đặt​


Mã:
pip install streamlit requests

3. Triển khai Code (Full Source)​


Tạo file `dashboard.py`. Chúng ta sẽ chia màn hình làm 2 phần:
* Sidebar (Cột trái): Các nút điều khiển hệ thống (Đèn, Camera).
* Main (Ở giữa): Khung chat với Llama 3.

Python:
import streamlit as st
import requests
import json

# --- CẤU HÌNH ---
API_URL = "http://localhost:8000" # Địa chỉ API Docker bài trước

st.set_page_config(page_title="Jarvis Dashboard", page_icon="🤖", layout="wide")

# --- CSS TÙY CHỈNH (Cho đẹp hơn) ---
st.markdown("""
<style>
    .stTextInput input {
        background-color: #2b313e;
        color: white;
    }
</style>
""", unsafe_allow_html=True)

# --- SIDEBAR: TRUNG TÂM ĐIỀU KHIỂN ---
with st.sidebar:
    st.title("🎛️ Control Center")
    st.write("Trạng thái hệ thống: 🟢 Online")
   
    st.divider()
   
    st.subheader("💡 Smart Home")
    col1, col2 = st.columns(2)
    with col1:
        if st.button("Bật Đèn", type="primary"):
            try:
                # Gọi API điều khiển đèn
                requests.get(f"{API_URL}/control/light/on")
                st.success("Đã BẬT đèn!")
            except:
                st.error("Lỗi kết nối API")
               
    with col2:
        if st.button("Tắt Đèn"):
            try:
                requests.get(f"{API_URL}/control/light/off")
                st.info("Đã TẮT đèn.")
            except:
                st.error("Lỗi kết nối API")

    st.divider()
    st.subheader("📸 Camera AI")
    st.image("https://media.giphy.com/media/oEnTTI3ZdK6ic/giphy.gif", caption="Live Feed (Giả lập)")

# --- MAIN: CHAT VỚI LLAMA 3 ---
st.title("🤖 Jarvis AI Assistant")

# Khởi tạo lịch sử chat nếu chưa có
if "messages" not in st.session_state:
    st.session_state.messages = []

# Hiển thị lịch sử chat cũ
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# Nhập câu hỏi mới
if prompt := st.chat_input("Nhập lệnh cho Jarvis..."):
    # 1. Hiển thị câu hỏi của bạn
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    # 2. Gọi API Llama 3 để lấy câu trả lời
    with st.chat_message("assistant"):
        message_placeholder = st.empty()
        message_placeholder.markdown("typing...")
       
        try:
            # Gửi request sang FastAPI (Docker)
            payload = {"prompt": prompt, "model": "llama3"}
            response = requests.post(f"{API_URL}/chat", json=payload)
           
            if response.status_code == 200:
                full_response = response.json().get("reply", "Lỗi phản hồi")
            else:
                full_response = f"Lỗi Server: {response.text}"
               
        except Exception as e:
            full_response = f"Không kết nối được Jarvis: {str(e)}"
           
        message_placeholder.markdown(full_response)
   
    # 3. Lưu câu trả lời vào lịch sử
    st.session_state.messages.append({"role": "assistant", "content": full_response})

4. Chạy Dashboard​


Mở Terminal và gõ lệnh:
Mã:
streamlit run dashboard.py

Trình duyệt sẽ tự động bật lên tại địa chỉ `http://localhost:8501`.
Bùm! Bạn đã có một giao diện web xịn xò, có nút bấm, có khung chat, trông không khác gì ChatGPT phiên bản "nhà làm".

5. Giải thích kỹ thuật​


  • `st.session_state`: Streamlit hoạt động theo cơ chế "vẽ lại từ đầu" mỗi khi bạn bấm nút. Session State giúp lưu lại lịch sử chat để nó không bị mất đi khi bạn tương tác.
  • `requests.post`: Đây là cầu nối. Dashboard (Frontend) không chứa Llama 3, nó chỉ gửi câu hỏi sang FastAPI (Backend) mà ta đã chạy Docker ở bài trước. Điều này giúp tách biệt giao diện và xử lý, giúp hệ thống chạy mượt hơn.

6. Ý tưởng nâng cấp​


* Upload File: Thêm nút upload file PDF để Llama 3 đọc và tóm tắt.
* Biểu đồ Chứng khoán: Kết hợp với bài "FinTech Bot" để vẽ biểu đồ giá Bitcoin ngay trên Dashboard.
* Deploy: Bạn cũng có thể đóng gói Dashboard này vào Docker (giống bài trước) để truy cập từ xa.
 
Back
Top