Spaces:
Sleeping
Sleeping
Update app_gradio.py
Browse files- app_gradio.py +140 -9
app_gradio.py
CHANGED
|
@@ -1,16 +1,147 @@
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
|
| 9 |
-
return "Hello " + name + "!"
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
gr_interface = gr.Interface(fn=greet, inputs="text", outputs="text", title="Gradio Space Example")
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
app = gr.mount_gradio_app(app, gr_interface, path="/")
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
import gradio as gr
|
| 3 |
+
import os
|
| 4 |
+
import sqlalchemy
|
| 5 |
+
from sqlalchemy import create_engine, text, Column, Integer, String, DateTime
|
| 6 |
+
from sqlalchemy.orm import sessionmaker, declarative_base
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import time
|
| 9 |
|
| 10 |
+
# --- Cấu hình Biến Database (PHẢI KHỚP VỚI run.sh) ---
|
| 11 |
+
DB_USER="gradio_user"
|
| 12 |
+
DB_PASS="local_password_123"
|
| 13 |
+
DB_NAME="gradio_db"
|
| 14 |
+
DB_HOST="localhost" # Kết nối cục bộ
|
| 15 |
+
DB_PORT="5432"
|
| 16 |
+
|
| 17 |
+
# --- Thiết lập Cơ sở dữ liệu (Database Setup) ---
|
| 18 |
+
|
| 19 |
+
# 1. Tạo chuỗi kết nối cục bộ
|
| 20 |
+
DATABASE_URL = f"postgresql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
|
| 21 |
+
DB_IS_LOCAL = True
|
| 22 |
+
|
| 23 |
+
# 2. Tạo kết nối
|
| 24 |
+
print("Đang kết nối tới cơ sở dữ liệu PostgreSQL cục bộ...")
|
| 25 |
+
try:
|
| 26 |
+
engine = create_engine(DATABASE_URL)
|
| 27 |
+
# Thử kết nối nhanh
|
| 28 |
+
with engine.connect() as connection:
|
| 29 |
+
print("Kết nối PostgreSQL cục bộ thành công.")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"LỖI NGHIÊM TRỌNG: Không thể kết nối tới DB cục bộ: {e}")
|
| 32 |
+
print("Sử dụng cơ sở dữ liệu SQLite trong bộ nhớ để demo.")
|
| 33 |
+
engine = create_engine("sqlite:///:memory:")
|
| 34 |
+
DB_IS_LOCAL = False # Đánh dấu là đang chạy demo
|
| 35 |
+
|
| 36 |
+
Base = declarative_base()
|
| 37 |
+
|
| 38 |
+
# 3. Định nghĩa mô hình bảng (Table Model)
|
| 39 |
+
class Note(Base):
|
| 40 |
+
__tablename__ = 'notes'
|
| 41 |
+
id = Column(Integer, primary_key=True, autoincrement=True)
|
| 42 |
+
username = Column(String(100), nullable=False)
|
| 43 |
+
message = Column(String(500), nullable=False)
|
| 44 |
+
created_at = Column(DateTime, default=datetime.utcnow)
|
| 45 |
+
|
| 46 |
+
# 4. Tạo bảng (nếu chưa tồn tại)
|
| 47 |
+
try:
|
| 48 |
+
Base.metadata.create_all(engine)
|
| 49 |
+
print("Bảng 'notes' đã được kiểm tra/tạo thành công.")
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"Lỗi khi tạo bảng (có thể bảng đã tồn tại): {e}")
|
| 52 |
|
| 53 |
+
# 5. Tạo một Session để tương tác với DB
|
| 54 |
+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
| 55 |
|
| 56 |
+
# --- Hàm xử lý Gradio ---
|
|
|
|
| 57 |
|
| 58 |
+
def add_entry(username, message):
|
| 59 |
+
"""Thêm một mục mới vào cơ sở dữ liệu."""
|
| 60 |
+
if not DB_IS_LOCAL:
|
| 61 |
+
print("Chạy ở chế độ demo (SQLite), không thêm vào DB.")
|
| 62 |
+
return get_entries()
|
| 63 |
+
|
| 64 |
+
if not username or not message:
|
| 65 |
+
return get_entries() # Chỉ tải lại, không thêm gì
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
db = SessionLocal()
|
| 69 |
+
new_note = Note(username=username, message=message)
|
| 70 |
+
db.add(new_note)
|
| 71 |
+
db.commit()
|
| 72 |
+
print(f"Đã thêm mục mới từ: {username}")
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"Lỗi khi thêm mục: {e}")
|
| 75 |
+
db.rollback()
|
| 76 |
+
return f"Lỗi khi thêm mục: {e}"
|
| 77 |
+
finally:
|
| 78 |
+
db.close()
|
| 79 |
+
|
| 80 |
+
# Sau khi thêm, tải lại các mục
|
| 81 |
+
return get_entries()
|
| 82 |
+
|
| 83 |
+
def get_entries():
|
| 84 |
+
"""Lấy tất cả các mục từ cơ sở dữ liệu và định dạng chúng."""
|
| 85 |
+
if not DB_IS_LOCAL:
|
| 86 |
+
return "Ứng dụng đang chạy ở chế độ demo (SQLite). Không thể kết nối với DB cục bộ."
|
| 87 |
+
|
| 88 |
+
output = ""
|
| 89 |
+
try:
|
| 90 |
+
db = SessionLocal()
|
| 91 |
+
# Lấy 20 mục gần nhất
|
| 92 |
+
notes = db.query(Note).order_by(Note.created_at.desc()).limit(20).all()
|
| 93 |
+
|
| 94 |
+
if not notes:
|
| 95 |
+
output = "Chưa có tin nhắn nào. Hãy là người đầu tiên!"
|
| 96 |
+
else:
|
| 97 |
+
# Định dạng đầu ra (hiển thị từ mới nhất)
|
| 98 |
+
for note in notes:
|
| 99 |
+
time_str = note.created_at.strftime('%Y-%m-%d %H:%M')
|
| 100 |
+
output += f"[{time_str}] {note.username}:\n{note.message}\n" + "-"*20 + "\n"
|
| 101 |
+
|
| 102 |
+
except Exception as e:
|
| 103 |
+
print(f"Lỗi khi tải mục: {e}")
|
| 104 |
+
output = f"Lỗi khi tải mục: {e}"
|
| 105 |
+
finally:
|
| 106 |
+
db.close()
|
| 107 |
+
|
| 108 |
+
return output
|
| 109 |
+
|
| 110 |
+
# --- Giao diện Gradio (Sử dụng Blocks) ---
|
| 111 |
+
# (Giữ nguyên giao diện Gradio Blocks như cũ)
|
| 112 |
+
|
| 113 |
+
with gr.Blocks(title="Gradio + PG (Local)") as gr_interface:
|
| 114 |
+
gr.Markdown("# Sổ khách (Gradio + PostgreSQL Cục bộ)")
|
| 115 |
+
gr.Markdown("Để lại tin nhắn và xem các tin nhắn trước đó. CẢNH BÁO: Dữ liệu sẽ bị mất khi Space khởi động lại!")
|
| 116 |
+
|
| 117 |
+
with gr.Row():
|
| 118 |
+
with gr.Column(scale=1):
|
| 119 |
+
username_input = gr.Textbox(label="Tên của bạn")
|
| 120 |
+
message_input = gr.Textbox(label="Tin nhắn của bạn", lines=4, placeholder="Viết gì đó...")
|
| 121 |
+
submit_button = gr.Button("Gửi tin nhắn", variant="primary")
|
| 122 |
+
|
| 123 |
+
with gr.Column(scale=2):
|
| 124 |
+
output_display = gr.Textbox(
|
| 125 |
+
label="Tin nhắn đã lưu (Tải lại tự động)",
|
| 126 |
+
lines=12,
|
| 127 |
+
interactive=False
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# Tải các mục khi giao diện khởi động
|
| 131 |
+
gr_interface.load(get_entries, outputs=output_display)
|
| 132 |
+
|
| 133 |
+
# Liên kết nút Gửi
|
| 134 |
+
submit_button.click(
|
| 135 |
+
fn=add_entry,
|
| 136 |
+
inputs=[username_input, message_input],
|
| 137 |
+
outputs=output_display
|
| 138 |
+
).then(
|
| 139 |
+
# Xóa các ô input sau khi gửi
|
| 140 |
+
lambda: (gr.update(value=""), gr.update(value="")),
|
| 141 |
+
outputs=[username_input, message_input]
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# --- Gắn vào FastAPI (Giống như dự án cũ của bạn) ---
|
| 146 |
+
app = FastAPI()
|
| 147 |
app = gr.mount_gradio_app(app, gr_interface, path="/")
|