Upload 6 files
Browse filesFiles changed (6)
- README.md+45-19
- app.pyAdded+355
- auth.pyAdded+20
- db.pyAdded+149
- providers.pyAdded+66
- requirements.txt+5-3
12345678910111213141516171819---title: ChatAIemoji: 🚀colorFrom: redcolorTo: redsdk: dockerapp_port: 8501tags:- streamlitpinned: falseshort_description: Streamlit template space---# Welcome to Streamlit!Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).123456789101112131415161718192021222324252627282930313233343536373839404142434445# ChatAI Streamlit App (with Admin, OpenAI & Ollama)A Streamlit app that provides:- Rounded chat interface with **+** button to upload **files** or **images**- Supports **OpenAI** and **Ollama** providers- **Admin** role can manage user accounts- Conversation history (SQLite)- Export chat to Markdown## Quickstart1) **Create a virtual environment (recommended)**```bashpython -m venv .venvsource .venv/bin/activate # On Windows: .venv\Scripts\activate```2) **Install dependencies**```bashpip install -r requirements.txt```3) **Run the app**```bashstreamlit run app.py```4) **Login**On first run, a default admin account is created:- **username**: `admin`- **password**: `admin123`👉 Immediately change this in **Admin > Users**.## Providers- **OpenAI**: Set your key in the sidebar **(OpenAI API Key)** or via env var `OPENAI_API_KEY`.- **Ollama**: Make sure Ollama is running locally (default endpoint `http://localhost:11434`).You can change endpoint in the sidebar.## Notes- This is a reference implementation for local use. For production:- Use a proper auth service (e.g., OAuth), secure key storage (e.g., Vault/KMS)- Harden the admin endpoints and network access- Add request limits, logging, and encryption-at-rest
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355import os, io, base64, jsonfrom datetime import datetimeimport streamlit as stfrom typing import List, Dict, Any
from db import init_db, get_user_by_username, create_conversation, list_conversations, rename_conversation, delete_conversation, add_message, get_messages, list_users, set_user_role, set_user_active, update_user_passwordfrom auth import hash_password, verify_password, ensure_adminfrom providers import OpenAIProvider, OllamaProvider, ProviderError
st.set_page_config(page_title="ChatAI (Streamlit)", page_icon="💬", layout="wide")
# --- CSS for rounded chat bubbles & '+' floating button ---custom_css = """<style>.stChatMessage .stMarkdown { border-radius: 16px; padding: 12px 14px; background: rgba(240, 242, 246, 0.6);}.stChatMessage[data-testid="stChatMessageUser"] .stMarkdown { background: rgba(147, 197, 253, 0.25);}.plus-fab { position: fixed; bottom: 24px; right: 24px; width: 52px; height: 52px; border-radius: 50%; background: #4F46E5; color: white; border: none; box-shadow: 0 8px 24px rgba(0,0,0,0.15); font-size: 28px; cursor: pointer; z-index: 9999;}.upload-card { position: fixed; bottom: 88px; right: 24px; width: 320px; background: white; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.15); padding: 16px; z-index: 9999; border: 1px solid rgba(0,0,0,0.06);}</style>"""st.markdown(custom_css, unsafe_allow_html=True)
# --- Initialize DB and default admin ---init_db()created_admin, admin_pwd = ensure_admin()
# --- Session State ---if "user" not in st.session_state: st.session_state.user = Noneif "conversation_id" not in st.session_state: st.session_state.conversation_id = Noneif "show_uploader" not in st.session_state: st.session_state.show_uploader = Falseif "messages_cache" not in st.session_state: st.session_state.messages_cache = []
def do_login(username, password): user = get_user_by_username(username) if not user or not user["is_active"]: st.error("Sai tài khoản hoặc tài khoản đang bị khóa.") return False if verify_password(password, user["password_hash"]): st.session_state.user = {"id": user["id"], "username": user["username"], "role": user["role"]} return True st.error("Mật khẩu không đúng.") return False
def logout(): st.session_state.user = None st.session_state.conversation_id = None st.session_state.messages_cache = []
# --- Sidebar: Auth & Settings ---with st.sidebar: st.header("⚙️ Cấu hình")
if st.session_state.user: st.success(f"Đã đăng nhập: **{st.session_state.user['username']}** ({st.session_state.user['role']})") if st.button("Đăng xuất"): logout() st.rerun() else: st.subheader("Đăng nhập") with st.form("login_form", clear_on_submit=False): u = st.text_input("Tên đăng nhập") p = st.text_input("Mật khẩu", type="password") submitted = st.form_submit_button("Đăng nhập") if submitted: if do_login(u, p): st.rerun()
st.divider() st.subheader("Nhà cung cấp AI") provider = st.selectbox("Provider", ["OpenAI", "Ollama"]) if provider == "OpenAI": openai_key = st.text_input("OpenAI API Key", type="password", value=os.environ.get("OPENAI_API_KEY", "")) model = st.text_input("Model", value="gpt-4o-mini") else: ollama_url = st.text_input("Ollama Endpoint", value="http://localhost:11434") model = st.text_input("Model", value="llama3.1:8b") temperature = st.slider("Temperature", 0.0, 1.0, 0.3, 0.05)
st.divider() st.subheader("Tùy chọn") sys_prompt = st.text_area("System Prompt (tùy chọn)", value="You are a helpful assistant. Answer in Vietnamese if the user speaks Vietnamese.") if created_admin: st.info(f"Admin mặc định đã được tạo. Tài khoản: admin / Mật khẩu: {admin_pwd} — hãy đổi ngay!")
# --- Page Router ---def page_chat(): st.title("💬 ChatAI")
if not st.session_state.user: st.info("Hãy đăng nhập để bắt đầu trò chuyện.") return
# Conversations list left, right = st.columns([1, 3]) with left: st.subheader("🗂 Cuộc trò chuyện") if st.button("➕ Tạo cuộc trò chuyện mới"): st.session_state.conversation_id = create_conversation(st.session_state.user["id"], title="New Chat") st.session_state.messages_cache = [] st.rerun() convs = list_conversations(st.session_state.user["id"]) for c in convs: selected = st.button(f"🗨 {c['title']}", key=f"conv_{c['id']}") if selected: st.session_state.conversation_id = c["id"] st.session_state.messages_cache = get_messages(c["id"]) st.rerun()
with right: if not st.session_state.conversation_id: st.info("Chưa có cuộc trò chuyện. Hãy tạo mới bên trái.") return
# Rename / Delete cc1, cc2 = st.columns([3,1]) with cc1: new_title = st.text_input("Tên cuộc trò chuyện", value="") if st.button("Đổi tên"): if new_title.strip(): rename_conversation(st.session_state.conversation_id, new_title.strip()) st.success("Đã đổi tên.") else: st.warning("Tên không hợp lệ.") with cc2: if st.button("🗑 Xóa cuộc trò chuyện", type="secondary"): delete_conversation(st.session_state.conversation_id) st.session_state.conversation_id = None st.session_state.messages_cache = [] st.rerun()
# Chat history UI msgs = st.session_state.messages_cache or get_messages(st.session_state.conversation_id) for m in msgs: role = m["role"] content = m["content"] with st.chat_message("assistant" if role=="assistant" else "user"): st.markdown(content) try: atts = json.loads(m.get("attachments") or "[]") for a in atts: st.caption(f"📎 {a.get('name','file')} ({a.get('type','file')})") except Exception: pass
# Chat input user_msg = st.chat_input("Nhập tin nhắn...")
# Floating '+' button for uploads st.markdown('<button class="plus-fab" onclick="window.parent.postMessage({type:\\'toggle_uploader\\'}, \\\"*\\\")">+</button>', unsafe_allow_html=True)
# Fallback toggle if st.button("Hiện/Tắt upload (fallback)"): st.session_state.show_uploader = not st.session_state.show_uploader
if st.session_state.show_uploader: with st.container(): st.markdown('<div class="upload-card">', unsafe_allow_html=True) st.write("**Tải lên để đính kèm**") file_uploader = st.file_uploader("Tệp (txt, pdf)", type=["txt","pdf"], accept_multiple_files=True, key="file_up") img_uploader = st.file_uploader("Ảnh", type=["png","jpg","jpeg","webp"], accept_multiple_files=True, key="img_up") if st.button("Đóng"): st.session_state.show_uploader = False st.markdown('</div>', unsafe_allow_html=True)
# Process send if user_msg or (st.session_state.get("file_up") or st.session_state.get("img_up")): attachments = []
def extract_text_from_file(f): name = f.name if name.lower().endswith(".txt"): return f.read().decode("utf-8", errors="ignore") if name.lower().endswith(".pdf"): try: import PyPDF2 reader = PyPDF2.PdfReader(io.BytesIO(f.read())) pages = [] for p in reader.pages: pages.append(p.extract_text() or "") return "\\n".join(pages) except Exception as e: return f"[Không thể trích xuất PDF: {e}]" return ""
uploaded_files = st.session_state.get("file_up") or [] uploaded_imgs = st.session_state.get("img_up") or []
context_snippets = [] for f in uploaded_files: text = extract_text_from_file(f) attachments.append({"name": f.name, "type": "file", "size": f.size}) if text: context_snippets.append(f"### {f.name}\\n{text[:6000]}")
image_refs = [] for img in uploaded_imgs: b64 = base64.b64encode(img.read()).decode("utf-8") mime = "image/png" if img.name.lower().endswith("png") else "image/jpeg" image_refs.append({"name": img.name, "type": "image", "b64": b64, "mime": mime}) attachments.append({"name": img.name, "type": "image", "size": img.size})
db_msgs = get_messages(st.session_state.conversation_id) chat_history = [{"role": m["role"], "content": m["content"]} for m in db_msgs]
system_preamble = sys_prompt.strip() if sys_prompt else "" if context_snippets: system_preamble += "\\n\\n# File context (tóm tắt)\\n" + "\\n\\n".join(context_snippets)
messages_for_provider: List[Dict[str, Any]] = [] if system_preamble: messages_for_provider.append({"role": "system", "content": system_preamble})
messages_for_provider.extend(chat_history[-12:]) if user_msg: messages_for_provider.append({"role": "user", "content": user_msg})
try: if provider == "OpenAI": p = OpenAIProvider(api_key=openai_key if openai_key else None) resp = p.generate(messages=messages_for_provider, model=model, temperature=temperature) else: p = OllamaProvider(base_url=ollama_url) resp = p.generate(messages=messages_for_provider, model=model, temperature=temperature) except ProviderError as e: resp = f"Lỗi nhà cung cấp: {e}" except Exception as e: resp = f"Lỗi không xác định: {e}"
if user_msg: add_message(st.session_state.conversation_id, "user", user_msg, attachments=json.dumps(attachments)) st.session_state.messages_cache.append({"role":"user","content":user_msg,"attachments":json.dumps(attachments)}) add_message(st.session_state.conversation_id, "assistant", resp) st.session_state.messages_cache.append({"role":"assistant","content":resp,"attachments":"[]"}) st.session_state.show_uploader = False st.rerun()
# Export st.divider() if st.button("⬇️ Xuất cuộc trò chuyện (Markdown)"): msgs = get_messages(st.session_state.conversation_id) md = ["# Lịch sử trò chuyện"] for m in msgs: who = "👤 User" if m["role"]=="user" else "🤖 Assistant" md.append(f"**{who}**\\n\\n{m['content']}\\n") b = "\\n\\n---\\n\\n".join(md).encode("utf-8") st.download_button("Tải về .md", data=b, file_name="chat_history.md", mime="text/markdown")
def page_admin(): if not st.session_state.user or st.session_state.user["role"] != "admin": st.warning("Chỉ Admin mới truy cập được trang này.") return
st.title("🛠 Admin Panel") st.subheader("Quản lý người dùng")
users = list_users() for u in users: cols = st.columns([2,1,1,1,2]) cols[0].write(f"**{u['username']}**") cols[1].write(u["role"]) cols[2].write("✅" if u["is_active"] else "🚫") if cols[3].button("Đổi vai trò", key=f"role_{u['id']}"): new_role = "admin" if u["role"]=="user" else "user" set_user_role(u["id"], new_role) st.rerun() with cols[4]: c1, c2, c3 = st.columns(3) if c1.button("Khóa/Mở", key=f"toggle_{u['id']}"): set_user_active(u["id"], not u["is_active"]) st.rerun() if c2.button("Đặt lại MK", key=f"reset_{u['id']}"): newpw = st.text_input(f"Mật khẩu mới cho {u['username']}", key=f"pw_{u['id']}") if newpw: update_user_password(u["id"], hash_password(newpw)) st.success("Đã cập nhật mật khẩu.") st.rerun() if c3.button("Xóa", key=f"del_{u['id']}"): from db import delete_user as delu if u["username"]=="admin": st.error("Không được xóa tài khoản admin gốc.") else: delu(u["id"]) st.rerun()
st.divider() st.subheader("Thêm người dùng mới") with st.form("new_user_form"): nu = st.text_input("Tên đăng nhập") np = st.text_input("Mật khẩu", type="password") role = st.selectbox("Vai trò", ["user", "admin"]) submitted = st.form_submit_button("Tạo") if submitted: if not nu or not np: st.error("Thiếu thông tin.") elif get_user_by_username(nu): st.error("Tên đăng nhập đã tồn tại.") else: from db import create_user create_user(nu, hash_password(np), role=role, is_active=True) st.success("Đã tạo người dùng.") st.rerun()
# --- Main ---tab = st.tabs(["💬 Chat", "🛠 Admin"])with tab[0]: page_chat()with tab[1]: page_admin()
# Small JS to listen to postMessage and toggle uploader (best-effort, uses the fallback button)st.markdown(\"""<script>window.addEventListener('message', (event) => { if (event.data && event.data.type === 'toggle_uploader') { const btns = window.parent.document.querySelectorAll('button'); if (btns && btns.length > 0) { btns[btns.length-1].click(); } }}, false);</script>\""", unsafe_allow_html=True)1234567891011121314151617181920import bcryptfrom db import init_db, create_user, get_user_by_username
def hash_password(plain: str) -> bytes: return bcrypt.hashpw(plain.encode("utf-8"), bcrypt.gensalt())
def verify_password(plain: str, hashed: bytes) -> bool: try: return bcrypt.checkpw(plain.encode("utf-8"), hashed) except Exception: return False
def ensure_admin(): # Ensure DB exists & default admin user init_db() if not get_user_by_username("admin"): pwd = "admin123" create_user("admin", hash_password(pwd), role="admin", is_active=True) return True, pwd return False, None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149import sqlite3from datetime import datetime
DB_PATH = "chatai.db"
def get_conn(): return sqlite3.connect(DB_PATH, check_same_thread=False)
def init_db(): conn = get_conn() c = conn.cursor() c.execute(""" CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash BLOB NOT NULL, role TEXT NOT NULL DEFAULT 'user', is_active INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL ) """) c.execute(""" CREATE TABLE IF NOT EXISTS conversations ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, title TEXT, created_at TEXT NOT NULL, FOREIGN KEY(user_id) REFERENCES users(id) ) """) c.execute(""" CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id INTEGER NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, attachments TEXT, created_at TEXT NOT NULL, FOREIGN KEY(conversation_id) REFERENCES conversations(id) ) """) conn.commit() return conn
# --- User CRUD ---def create_user(username, password_hash, role="user", is_active=True): conn = get_conn() c = conn.cursor() c.execute( "INSERT INTO users (username, password_hash, role, is_active, created_at) VALUES (?,?,?,?,?)", (username, password_hash, role, 1 if is_active else 0, datetime.utcnow().isoformat()), ) conn.commit() return c.lastrowid
def get_user_by_username(username): conn = get_conn() c = conn.cursor() c.execute("SELECT id, username, password_hash, role, is_active, created_at FROM users WHERE username = ?", (username,)) row = c.fetchone() if not row: return None return {"id": row[0], "username": row[1], "password_hash": row[2], "role": row[3], "is_active": bool(row[4]), "created_at": row[5]}
def get_user_by_id(user_id): conn = get_conn() c = conn.cursor() c.execute("SELECT id, username, password_hash, role, is_active, created_at FROM users WHERE id = ?", (user_id,)) row = c.fetchone() if not row: return None return {"id": row[0], "username": row[1], "password_hash": row[2], "role": row[3], "is_active": bool(row[4]), "created_at": row[5]}
def list_users(): conn = get_conn() c = conn.cursor() c.execute("SELECT id, username, role, is_active, created_at FROM users ORDER BY id ASC") rows = c.fetchall() return [{"id": r[0], "username": r[1], "role": r[2], "is_active": bool(r[3]), "created_at": r[4]} for r in rows]
def set_user_active(user_id, active: bool): conn = get_conn() c = conn.cursor() c.execute("UPDATE users SET is_active=? WHERE id=?", (1 if active else 0, user_id)) conn.commit()
def set_user_role(user_id, role: str): conn = get_conn() c = conn.cursor() c.execute("UPDATE users SET role=? WHERE id=?", (role, user_id)) conn.commit()
def update_user_password(user_id, new_password_hash): conn = get_conn() c = conn.cursor() c.execute("UPDATE users SET password_hash=? WHERE id=?", (new_password_hash, user_id)) conn.commit()
def delete_user(user_id): conn = get_conn() c = conn.cursor() c.execute("DELETE FROM users WHERE id=?", (user_id,)) conn.commit()
# --- Conversations & Messages ---def create_conversation(user_id, title="New Chat"): conn = get_conn() c = conn.cursor() c.execute("INSERT INTO conversations (user_id, title, created_at) VALUES (?,?,?)", (user_id, title, datetime.utcnow().isoformat())) conn.commit() return c.lastrowid
def list_conversations(user_id): conn = get_conn() c = conn.cursor() c.execute("SELECT id, title, created_at FROM conversations WHERE user_id=? ORDER BY id DESC", (user_id,)) rows = c.fetchall() return [{"id": r[0], "title": r[1], "created_at": r[2]} for r in rows]
def rename_conversation(conversation_id, title): conn = get_conn() c = conn.cursor() c.execute("UPDATE conversations SET title=? WHERE id=?", (title, conversation_id)) conn.commit()
def delete_conversation(conversation_id): conn = get_conn() c = conn.cursor() c.execute("DELETE FROM messages WHERE conversation_id=?", (conversation_id,)) c.execute("DELETE FROM conversations WHERE id=?", (conversation_id,)) conn.commit()
def add_message(conversation_id, role, content, attachments=None): conn = get_conn() c = conn.cursor() c.execute("INSERT INTO messages (conversation_id, role, content, attachments, created_at) VALUES (?,?,?,?,?)", (conversation_id, role, content, attachments or "[]", datetime.utcnow().isoformat())) conn.commit() return c.lastrowid
def get_messages(conversation_id): conn = get_conn() c = conn.cursor() c.execute("SELECT role, content, attachments, created_at FROM messages WHERE conversation_id=? ORDER BY id ASC", (conversation_id,)) rows = c.fetchall() msgs = [] for r in rows: msgs.append({"role": r[0], "content": r[1], "attachments": r[2], "created_at": r[3]}) return msgs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import os, requestsfrom typing import List, Dict, Any, Optional
# --- Provider base ---class ProviderError(Exception): pass
class ChatProvider: def generate(self, messages: List[Dict[str, Any]], **kwargs) -> str: raise NotImplementedError
# --- OpenAI ---class OpenAIProvider(ChatProvider): def __init__(self, api_key: Optional[str] = None): self.api_key = api_key or os.environ.get("OPENAI_API_KEY") if not self.api_key: raise ProviderError("OpenAI API key missing. Provide it in the sidebar or set OPENAI_API_KEY.")
try: # Use official library (>=1.0) from openai import OpenAI self.client = OpenAI(api_key=self.api_key) except Exception as e: raise ProviderError(f"OpenAI library error: {e}")
def generate(self, messages: List[Dict[str, Any]], model: str = "gpt-4o-mini", temperature: float = 0.3, **kwargs) -> str: try: resp = self.client.chat.completions.create( model=model, messages=messages, temperature=temperature ) return resp.choices[0].message.content or "" except Exception as e: raise ProviderError(f"OpenAI API error: {e}")
# --- Ollama ---class OllamaProvider(ChatProvider): def __init__(self, base_url: str = "http://localhost:11434"): self.base_url = base_url.rstrip("/")
def generate(self, messages: List[Dict[str, Any]], model: str = "llama3.1:8b", temperature: float = 0.3, **kwargs) -> str: url = f"{self.base_url}/api/chat" payload = {"model": model, "messages": messages, "stream": False, "options": {"temperature": temperature}} try: r = requests.post(url, json=payload, timeout=120) r.raise_for_status() data = r.json() msg = data.get("message", {}).get("content", "") if not msg and "choices" in data: msg = data["choices"][0]["message"]["content"] return msg except Exception as e: raise ProviderError(f"Ollama API error: {e}")
# --- Helper ---def convert_streamlit_messages_to_openai(messages: List[Dict[str, Any]]): converted = [] for m in messages: role = m.get("role", "user") content = m.get("content", "") attachments = m.get("attachments", []) if attachments: content += "\\n\\n[Attachments]\\n" + "\\n".join([f"- {a.get('name','file')} ({a.get('type','file')})" for a in attachments]) converted.append({"role": role, "content": content}) return converted123altairpandasstreamlit12345streamlit>=1.32openai>=1.37.0requests>=2.31.0bcrypt>=4.1.2PyPDF2>=3.0.1
README.md+45-19
app.pyAdded+355
auth.pyAdded+20
db.pyAdded+149
providers.pyAdded+66
requirements.txt+5-3