最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于python與streamlit構(gòu)建簡單的內(nèi)網(wǎng)智能聊天室應(yīng)用

 更新時(shí)間:2025年11月07日 09:02:44   作者:Atlas Shepherd  
這篇文章主要為大家詳細(xì)介紹了如何基于python與streamlit構(gòu)建簡單的內(nèi)網(wǎng)智能聊天室應(yīng)用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

這是一個(gè)基于Streamlit 構(gòu)建的內(nèi)網(wǎng)智能聊天室應(yīng)用。最后界面效果圖如下:

核心功能

1.數(shù)據(jù)存儲(chǔ)配置

SAVE_PATH = Path(r"D:\daku\內(nèi)網(wǎng)共享")  # 數(shù)據(jù)保存路徑
CHAT_HISTORY_FILE = SAVE_PATH / "chat_history.json"  # 聊天記錄
ONLINE_STATUS_FILE = SAVE_PATH / "online_status.json"  # 在線狀態(tài)
USER_PROFILES_FILE = SAVE_PATH / "user_profiles.json"  # 用戶資料
FILES_DIR = SAVE_PATH / "uploaded_files"  # 上傳文件目錄

2.主要特性

用戶系統(tǒng)

  • 簡單的用戶名登錄
  • 在線狀態(tài)管理(10分鐘超時(shí))
  • 用戶區(qū)分顯示(當(dāng)前用戶高亮)

聊天功能

  • 實(shí)時(shí)消息發(fā)送和顯示
  • 消息氣泡式界面(自己/他人消息不同樣式)
  • 支持文件上傳和下載
  • 聊天記錄持久化存儲(chǔ)

文件共享

  • 無限制文件類型和大小上傳
  • 文件列表展示和下載
  • 文件信息顯示(大小、上傳時(shí)間)

界面設(shè)計(jì)

  • 漸變色彩主題
  • 自定義CSS樣式
  • 響應(yīng)式布局

技術(shù)實(shí)現(xiàn)亮點(diǎn)

數(shù)據(jù)安全處理

def save_json_file(self, file_path: Path, data):
    # 使用臨時(shí)文件+備份機(jī)制,避免寫入中斷導(dǎo)致數(shù)據(jù)損壞
    temp_file → 備份原文件 → 替換新文件

消息格式兼容

def fix_historical_messages(self):
    # 自動(dòng)修復(fù)歷史消息格式,確保向后兼容
    # 添加缺失的日期、時(shí)間、類型字段

自動(dòng)清理機(jī)制

  • 在線用戶10分鐘超時(shí)清理
  • 聊天記錄限制2000條(防內(nèi)存溢出)
  • 備份文件清理功能

界面布局結(jié)構(gòu)

側(cè)邊欄(Sidebar)

  • 用戶登錄區(qū)域
  • 在線用戶列表
  • 文件傳輸功能

主區(qū)域(Main)

  • 聊天室標(biāo)簽頁:消息顯示 + 輸入框
  • 設(shè)置標(biāo)簽頁:統(tǒng)計(jì)信息 + 管理功能

核心業(yè)務(wù)流程

用戶登錄→ 更新在線狀態(tài)

發(fā)送消息→ 保存到JSON → 顯示更新

文件上傳→ 保存到本地 → 生成下載鏈接

自動(dòng)刷新→ 每分鐘更新界面狀態(tài)

安全與穩(wěn)定性

輸入驗(yàn)證:用戶名和消息內(nèi)容過濾

錯(cuò)誤恢復(fù):備份文件自動(dòng)恢復(fù)機(jī)制

權(quán)限檢查:目錄寫入權(quán)限驗(yàn)證

資源管理:文件大小格式化顯示

特色功能

  • 消息氣泡樣式:區(qū)分自己和他人的消息
  • 文件預(yù)覽下載:直接內(nèi)嵌下載按鈕
  • 實(shí)時(shí)在線狀態(tài):顯示用戶活躍時(shí)長
  • 數(shù)據(jù)導(dǎo)出:完整聊天記錄導(dǎo)出功能
  • 響應(yīng)式設(shè)計(jì):適配不同屏幕尺寸

完整代碼 

import streamlit as st
import os
import json
import time
import datetime
from pathlib import Path
import hashlib
import uuid
import mimetypes
from typing import Dict, List, Optional
import sys
import shutil

# 配置保存路徑
SAVE_PATH = Path(r"D:\daku\內(nèi)網(wǎng)共享")
SAVE_PATH.mkdir(parents=True, exist_ok=True)

# 文件路徑配置
CHAT_HISTORY_FILE = SAVE_PATH / "chat_history.json"
ONLINE_STATUS_FILE = SAVE_PATH / "online_status.json"
USER_PROFILES_FILE = SAVE_PATH / "user_profiles.json"
FILES_DIR = SAVE_PATH / "uploaded_files"
FILES_DIR.mkdir(exist_ok=True)


class EnhancedChatApplication:
    def __init__(self):
        self.setup_page_config()
        self.load_data()
        self.inject_custom_css()

    def setup_page_config(self):
        """設(shè)置頁面配置"""
        st.set_page_config(
            page_title="內(nèi)網(wǎng)智能聊天室",
            page_icon="??",
            layout="wide",
            initial_sidebar_state="expanded",
            menu_items={
                'Get Help': 'https',
                'Report a bug': 'https',
                'About': '# 內(nèi)網(wǎng)智能聊天應(yīng)用 v4.0'
            }
        )

    def inject_custom_css(self):
        """注入自定義CSS樣式"""
        st.markdown("""
        <style>
        /* 主容器樣式 */
        .main-container {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        /* 聊天消息樣式 */
        .user-message {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px;
            border-radius: 18px 18px 0px 18px;
            margin: 8px 0;
            max-width: 80%;
            margin-left: auto;
        }

        .other-message {
            background: #f0f2f6;
            color: #333;
            padding: 12px;
            border-radius: 18px 18px 18px 0px;
            margin: 8px 0;
            max-width: 80%;
        }

        /* 在線用戶樣式 */
        .online-user {
            background: #e8f5e8;
            padding: 8px;
            margin: 4px 0;
            border-radius: 8px;
            border-left: 4px solid #4CAF50;
        }

        /* 文件卡片樣式 */
        .file-card {
            background: white;
            padding: 12px;
            margin: 8px 0;
            border-radius: 12px;
            border: 1px solid #e0e0e0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        /* 按鈕樣式 */
        .stButton>button {
            width: 100%;
            border-radius: 8px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px;
            font-weight: bold;
        }

        /* 輸入框樣式 */
        .stTextArea textarea {
            border-radius: 8px;
            border: 2px solid #e0e0e0;
        }

        /* 側(cè)邊欄樣式 */
        .css-1d391kg {
            background: #f8f9fa;
        }

        /* 消息氣泡樣式 */
        .message-bubble-own {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 12px 16px;
            border-radius: 18px 18px 0 18px;
            max-width: 70%;
            margin-left: auto;
            margin-bottom: 10px;
        }

        .message-bubble-other {
            background: #f0f2f6;
            color: #333;
            padding: 12px 16px;
            border-radius: 18px 18px 18px 0;
            max-width: 70%;
            margin-bottom: 10px;
        }
        </style>
        """, unsafe_allow_html=True)

    def load_data(self):
        """加載所有數(shù)據(jù)"""
        self.chat_history = self.load_json_file(CHAT_HISTORY_FILE, [])
        self.online_users = self.load_json_file(ONLINE_STATUS_FILE, {})
        self.user_profiles = self.load_json_file(USER_PROFILES_FILE, {})
        self.user_files = self.load_file_list()

        # 修復(fù)歷史消息數(shù)據(jù)格式
        self.fix_historical_messages()

    def fix_historical_messages(self):
        """修復(fù)歷史消息數(shù)據(jù)格式,確保所有消息都有必要的字段"""
        fixed_count = 0
        for msg in self.chat_history:
            # 確保消息有必要的字段
            if 'date_str' not in msg:
                if 'timestamp' in msg:
                    msg['date_str'] = datetime.datetime.fromtimestamp(msg['timestamp']).strftime('%Y-%m-%d')
                else:
                    msg['date_str'] = datetime.datetime.now().strftime('%Y-%m-%d')
                fixed_count += 1

            if 'time_str' not in msg:
                if 'timestamp' in msg:
                    msg['time_str'] = datetime.datetime.fromtimestamp(msg['timestamp']).strftime('%H:%M:%S')
                else:
                    msg['time_str'] = datetime.datetime.now().strftime('%H:%M:%S')
                fixed_count += 1

            if 'type' not in msg:
                msg['type'] = 'text'
                fixed_count += 1

        if fixed_count > 0:
            st.info(f"修復(fù)了 {fixed_count} 條歷史消息的格式")
            self.save_json_file(CHAT_HISTORY_FILE, self.chat_history)

    def load_json_file(self, file_path: Path, default):
        """加載JSON文件"""
        if file_path.exists():
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                st.error(f"加載文件失敗 {file_path}: {e}")
                # 如果文件損壞,嘗試備份
                backup_path = file_path.with_suffix('.bak')
                if backup_path.exists():
                    try:
                        with open(backup_path, 'r', encoding='utf-8') as f:
                            data = json.load(f)
                        st.success("從備份文件恢復(fù)數(shù)據(jù)成功")
                        return data
                    except:
                        pass
        return default

    def save_json_file(self, file_path: Path, data):
        """保存JSON文件 - 修復(fù)備份邏輯"""
        try:
            # 創(chuàng)建臨時(shí)文件
            temp_file = file_path.with_suffix('.tmp')

            # 先寫入臨時(shí)文件
            with open(temp_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)

            # 如果原文件存在,先備份
            if file_path.exists():
                backup_path = file_path.with_suffix('.bak')
                # 如果備份文件已存在,先刪除
                if backup_path.exists():
                    backup_path.unlink()
                # 重命名原文件為備份文件
                file_path.rename(backup_path)

            # 重命名臨時(shí)文件為目標(biāo)文件
            temp_file.rename(file_path)

            return True
        except Exception as e:
            st.error(f"保存文件失敗 {file_path}: {e}")
            # 清理臨時(shí)文件
            if 'temp_file' in locals() and temp_file.exists():
                try:
                    temp_file.unlink()
                except:
                    pass
            return False

    def load_file_list(self) -> List[Dict]:
        """加載文件列表"""
        files = []
        for file_path in FILES_DIR.glob("*"):
            if file_path.is_file():
                file_info = {
                    'filename': file_path.name,
                    'size': file_path.stat().st_size,
                    'upload_time': datetime.datetime.fromtimestamp(
                        file_path.stat().st_mtime
                    ).strftime('%Y-%m-%d %H:%M:%S'),
                    'path': file_path,
                    'file_id': file_path.stem.split('_')[0] if '_' in file_path.stem else file_path.stem
                }
                files.append(file_info)
        return sorted(files, key=lambda x: x['upload_time'], reverse=True)

    def update_online_status(self, username: str):
        """更新用戶在線狀態(tài)"""
        current_time = time.time()
        self.online_users[username] = current_time

        # 清理超時(shí)用戶(10分鐘無活動(dòng))
        timeout = 600
        current_users = list(self.online_users.keys())
        for user in current_users:
            if current_time - self.online_users[user] > timeout:
                del self.online_users[user]

        self.save_json_file(ONLINE_STATUS_FILE, self.online_users)

    def send_message(self, username: str, message: str, file_data=None, message_type: str = "text"):
        """發(fā)送消息"""
        message_id = str(uuid.uuid4())
        timestamp = time.time()

        chat_message = {
            'id': message_id,
            'username': username,
            'message': message,
            'type': message_type,
            'timestamp': timestamp,
            'time_str': datetime.datetime.now().strftime('%H:%M:%S'),
            'date_str': datetime.datetime.now().strftime('%Y-%m-%d'),
            'has_file': file_data is not None
        }

        if file_data is not None:
            # 保存文件(無大小限制)
            filename = file_data.name
            file_ext = Path(filename).suffix
            file_path = FILES_DIR / f"{message_id}_{filename}"

            try:
                with open(file_path, 'wb') as f:
                    f.write(file_data.getvalue())

                chat_message.update({
                    'filename': filename,
                    'file_path': str(file_path),
                    'file_size': file_path.stat().st_size,
                    'file_type': mimetypes.guess_type(filename)[0] or 'application/octet-stream'
                })
                st.success(f"文件 '{filename}' 上傳成功!")
            except Exception as e:
                st.error(f"文件上傳失敗: {e}")
                return False

        self.chat_history.append(chat_message)

        # 限制聊天記錄數(shù)量,保存最近的2000條
        if len(self.chat_history) > 2000:
            self.chat_history = self.chat_history[-2000:]

        return self.save_json_file(CHAT_HISTORY_FILE, self.chat_history)

    def get_online_users(self) -> List[str]:
        """獲取在線用戶列表"""
        current_time = time.time()
        online = []
        for user, last_seen in self.online_users.items():
            if current_time - last_seen < 600:  # 10分鐘內(nèi)活躍
                online.append(user)
        return sorted(online)

    def display_login_section(self):
        """顯示登錄區(qū)域"""
        st.sidebar.title("?? 內(nèi)網(wǎng)智能聊天室")

        with st.sidebar.expander("?? 用戶登錄", expanded=True):
            if 'username' not in st.session_state:
                username = st.text_input("用戶名:", placeholder="請輸入您的用戶名", key="username_input")
                if st.button("進(jìn)入聊天室", type="primary", key="login_btn"):
                    if username and username.strip():
                        st.session_state.username = username.strip()
                        st.rerun()
                    else:
                        st.warning("請輸入有效的用戶名")
                return False
            return True

    def display_online_users(self):
        """顯示在線用戶"""
        st.sidebar.subheader("?? 在線用戶")
        online_users = self.get_online_users()
        current_user = st.session_state.username

        for user in online_users:
            is_current = user == current_user
            status_emoji = "??" if is_current else "??"
            user_display = f"**{user}**" if is_current else user

            with st.sidebar.container():
                col1, col2 = st.sidebar.columns([1, 4])
                with col1:
                    st.write(status_emoji)
                with col2:
                    st.write(user_display)

            if is_current:
                st.sidebar.caption("在線時(shí)長: " + self.format_duration(
                    time.time() - self.online_users[user]
                ))

        if not online_users:
            st.sidebar.info("暫無其他在線用戶")

    def display_file_section(self):
        """顯示文件傳輸區(qū)域"""
        with st.sidebar.expander("?? 文件傳輸", expanded=True):
            # 文件上傳
            uploaded_file = st.file_uploader(
                "選擇要發(fā)送的文件:",
                type=None,
                key="file_uploader",
                help="支持任意類型和大小的文件"
            )

            if uploaded_file is not None:
                file_size = len(uploaded_file.getvalue())
                st.info(f"文件: {uploaded_file.name} | 大小: {self.format_file_size(file_size)}")

                if st.button("?? 發(fā)送文件", key="send_file"):
                    if self.send_message(st.session_state.username,
                                         f"分享了文件: {uploaded_file.name}",
                                         uploaded_file, "file"):
                        st.success("文件發(fā)送成功!")
                        st.rerun()

            # 文件列表
            st.subheader("共享文件庫")
            self.user_files = self.load_file_list()

            if not self.user_files:
                st.info("暫無共享文件")
            else:
                for file_info in self.user_files[:10]:  # 顯示最近10個(gè)文件
                    with st.container():
                        col1, col2 = st.columns([3, 1])
                        with col1:
                            st.write(f"**{file_info['filename']}**")
                            st.caption(f"{self.format_file_size(file_info['size'])} | {file_info['upload_time']}")
                        with col2:
                            with open(file_info['path'], 'rb') as f:
                                st.download_button(
                                    label="??",
                                    data=f,
                                    file_name=file_info['filename'],
                                    key=f"dl_{file_info['file_id']}_{uuid.uuid4()}",
                                    use_container_width=True
                                )

    def display_chat_interface(self):
        """顯示主聊天界面"""
        st.header("?? 智能聊天室")

        # 創(chuàng)建標(biāo)簽頁布局
        tab1, tab2 = st.tabs(["?? 聊天室", "?? 設(shè)置"])

        with tab1:
            self.display_chat_messages()
            self.display_message_input()

        with tab2:
            self.display_settings()

    def display_chat_messages(self):
        """顯示聊天消息"""
        chat_container = st.container(height=500)

        with chat_container:
            if not self.chat_history:
                st.info("暫無聊天記錄,開始第一個(gè)對話吧!")
                return

            current_user = st.session_state.username

            for i, msg in enumerate(self.chat_history[-100:]):  # 顯示最近100條消息
                # 安全地獲取消息字段,提供默認(rèn)值
                date_str = msg.get('date_str', '未知日期')
                time_str = msg.get('time_str', '未知時(shí)間')
                username = msg.get('username', '未知用戶')
                message_content = msg.get('message', '')

                is_current_user = username == current_user

                # 顯示日期分隔(安全地比較日期)
                if i > 0:
                    prev_date_str = self.chat_history[i - 1].get('date_str', '未知日期')
                    if date_str != prev_date_str:
                        st.markdown(f"---\n**{date_str}**\n---")

                # 使用更安全的消息顯示方式
                col1, col2 = st.columns([1, 20])
                with col2:
                    if is_current_user:
                        # 自己的消息靠右顯示
                        message_html = f"""
                        <div style="display: flex; justify-content: flex-end; margin: 10px 0;">
                            <div class="message-bubble-own">
                                <div><strong>{username}</strong></div>
                                <div>{message_content}</div>
                                <div style="font-size: 0.8em; opacity: 0.8; text-align: right;">{time_str}</div>
                            </div>
                        </div>
                        """
                    else:
                        # 他人的消息靠左顯示
                        message_html = f"""
                        <div style="display: flex; justify-content: flex-start; margin: 10px 0;">
                            <div class="message-bubble-other">
                                <div><strong>{username}</strong></div>
                                <div>{message_content}</div>
                                <div style="font-size: 0.8em; opacity: 0.8;">{time_str}</div>
                            </div>
                        </div>
                        """

                    st.markdown(message_html, unsafe_allow_html=True)

                    # 文件下載按鈕(安全地處理文件信息)
                    if msg.get('has_file'):
                        filename = msg.get('filename', '文件')
                        file_size = msg.get('file_size', 0)
                        file_info = f"{filename} ({self.format_file_size(file_size)})"
                        file_path_str = msg.get('file_path', '')

                        if file_path_str:
                            file_path = Path(file_path_str)
                            if file_path.exists():
                                with open(file_path, 'rb') as f:
                                    st.download_button(
                                        label=f"?? 下載附件: {file_info}",
                                        data=f,
                                        file_name=filename,
                                        key=f"file_{msg.get('id', str(i))}_{uuid.uuid4()}",
                                        use_container_width=True
                                    )

    def display_message_input(self):
        """顯示消息輸入?yún)^(qū)域"""
        col1, col2 = st.columns([5, 1])

        with col1:
            message = st.text_area(
                "輸入消息:",
                placeholder="輸入您要發(fā)送的消息...",
                height=100,
                key="message_input",
                label_visibility="collapsed"
            )

        with col2:
            send_col1, send_col2 = st.columns(2)
            with send_col1:
                if st.button("?? 發(fā)送", use_container_width=True, key="send_msg_btn"):
                    if message and message.strip():
                        if self.send_message(st.session_state.username, message.strip()):
                            # 清空輸入框
                            st.session_state.message_input = ""
                            st.rerun()
                    else:
                        st.warning("請輸入消息內(nèi)容")

            with send_col2:
                if st.button("?? 刷新", use_container_width=True, key="refresh_btn"):
                    st.rerun()

    def display_settings(self):
        """顯示設(shè)置頁面"""
        st.subheader("應(yīng)用設(shè)置")

        col1, col2 = st.columns(2)

        with col1:
            st.metric("在線用戶", len(self.get_online_users()))
            st.metric("總消息數(shù)", len(self.chat_history))
            st.metric("共享文件", len(self.user_files))

        with col2:
            if st.button("清空聊天記錄", type="secondary", key="clear_chat_btn"):
                if st.checkbox("確認(rèn)清空(此操作不可逆)", key="confirm_clear"):
                    if st.button("確認(rèn)清空", type="primary", key="confirm_clear_btn"):
                        self.chat_history = []
                        self.save_json_file(CHAT_HISTORY_FILE, [])
                        st.success("聊天記錄已清空")
                        st.rerun()

            if st.button("導(dǎo)出聊天記錄", key="export_chat_btn"):
                self.export_chat_history()

            if st.button("清理備份文件", key="cleanup_backups_btn"):
                self.cleanup_backup_files()

        # 系統(tǒng)信息
        st.subheader("系統(tǒng)信息")
        st.info(f"數(shù)據(jù)保存路徑: {SAVE_PATH}")
        st.info(f"最后更新: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

        # 調(diào)試信息
        with st.expander("調(diào)試信息"):
            st.json({
                "chat_history_count": len(self.chat_history),
                "online_users_count": len(self.online_users),
                "files_count": len(self.user_files)
            })

    def export_chat_history(self):
        """導(dǎo)出聊天記錄"""
        export_data = {
            "export_time": datetime.datetime.now().isoformat(),
            "total_messages": len(self.chat_history),
            "online_users": self.get_online_users(),
            "chat_history": self.chat_history
        }

        export_file = SAVE_PATH / f"chat_export_{int(time.time())}.json"
        if self.save_json_file(export_file, export_data):
            st.success(f"聊天記錄已導(dǎo)出到: {export_file}")

    def cleanup_backup_files(self):
        """清理備份文件"""
        backup_files = list(SAVE_PATH.glob("*.bak"))
        cleaned_count = 0

        for backup_file in backup_files:
            try:
                backup_file.unlink()
                cleaned_count += 1
            except Exception as e:
                st.error(f"刪除備份文件失敗 {backup_file}: {e}")

        if cleaned_count > 0:
            st.success(f"已清理 {cleaned_count} 個(gè)備份文件")
        else:
            st.info("沒有找到可清理的備份文件")

    def format_file_size(self, size_bytes: int) -> str:
        """格式化文件大小顯示"""
        if size_bytes == 0:
            return "0 B"
        size_names = ["B", "KB", "MB", "GB", "TB"]
        i = 0
        while size_bytes >= 1024 and i < len(size_names) - 1:
            size_bytes /= 1024.0
            i += 1
        return f"{size_bytes:.1f} {size_names[i]}"

    def format_duration(self, seconds: float) -> str:
        """格式化時(shí)間間隔"""
        if seconds < 60:
            return f"{int(seconds)}秒"
        elif seconds < 3600:
            return f"{int(seconds / 60)}分鐘"
        else:
            hours = int(seconds / 3600)
            minutes = int((seconds % 3600) / 60)
            return f"{hours}小時(shí){minutes}分鐘"

    def run(self):
        """運(yùn)行應(yīng)用"""
        # 自動(dòng)刷新邏輯
        if 'last_refresh' not in st.session_state:
            st.session_state.last_refresh = time.time()

        # 每分鐘自動(dòng)刷新一次
        if time.time() - st.session_state.last_refresh > 60:
            st.session_state.last_refresh = time.time()
            st.rerun()

        # 主界面邏輯
        if not self.display_login_section():
            return

        username = st.session_state.username
        self.update_online_status(username)

        # 主布局
        self.display_online_users()
        self.display_file_section()
        self.display_chat_interface()


def main():
    """主函數(shù)"""
    # 檢查保存目錄權(quán)限
    if not SAVE_PATH.exists():
        try:
            SAVE_PATH.mkdir(parents=True, exist_ok=True)
            st.success(f"創(chuàng)建保存目錄: {SAVE_PATH}")
        except Exception as e:
            st.error(f"創(chuàng)建目錄失敗: {e}")
            return

    # 檢查寫入權(quán)限
    try:
        test_file = SAVE_PATH / "test_write.txt"
        with open(test_file, 'w') as f:
            f.write("test")
        test_file.unlink()
    except PermissionError:
        st.error(f"沒有寫入權(quán)限: {SAVE_PATH}")
        st.info("請檢查目錄權(quán)限或更換保存路徑")
        return

    # 運(yùn)行應(yīng)用
    app = EnhancedChatApplication()
    app.run()


if __name__ == "__main__":
    main()

到此這篇關(guān)于基于python與streamlit構(gòu)建簡單的內(nèi)網(wǎng)聊天應(yīng)用的文章就介紹到這了,更多相關(guān)python streamlit內(nèi)網(wǎng)聊天內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中讀取文件名中的數(shù)字的實(shí)例詳解

    Python中讀取文件名中的數(shù)字的實(shí)例詳解

    在本篇文章里小編給大家整理了一篇關(guān)于Python中讀取文件名中的數(shù)字的實(shí)例詳解內(nèi)容,有興趣的朋友們可以參考下。
    2020-12-12
  • Flask傳遞URL參數(shù)的實(shí)現(xiàn)

    Flask傳遞URL參數(shù)的實(shí)現(xiàn)

    在Flask中,傳遞URL參數(shù)是一種常見且強(qiáng)大的功能,本文主要介紹了Flask傳遞URL參數(shù)的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-09-09
  • python中np是做什么的

    python中np是做什么的

    在本篇內(nèi)容里小編給大家整理的是一篇關(guān)于python中np的作用的相關(guān)文章,有興趣的朋友們跟著學(xué)習(xí)下。
    2020-07-07
  • python_tkinter彈出對話框創(chuàng)建2

    python_tkinter彈出對話框創(chuàng)建2

    這篇文章主要介紹了python_tkinter彈出對話框創(chuàng)建,上以篇文章我們簡單的對對話框創(chuàng)建做了簡單介紹,本文將繼續(xù)更多相關(guān)內(nèi)容,需要的小伙伴可以參考一下
    2022-03-03
  • python導(dǎo)入csv文件出現(xiàn)SyntaxError問題分析

    python導(dǎo)入csv文件出現(xiàn)SyntaxError問題分析

    這篇文章主要介紹了python導(dǎo)入csv文件出現(xiàn)SyntaxError問題分析,同時(shí)涉及python導(dǎo)入csv文件的三種方法,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • Python3自定義json逐層解析器代碼

    Python3自定義json逐層解析器代碼

    這篇文章主要介紹了Python3自定義json逐層解析器代碼,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Python中import導(dǎo)入不同目錄的模塊方法詳解

    Python中import導(dǎo)入不同目錄的模塊方法詳解

    這篇文章主要介紹了Python中import導(dǎo)入不同目錄的模塊方法詳解,需要的朋友可以參考下
    2020-02-02
  • Python endswith()函數(shù)的具體使用

    Python endswith()函數(shù)的具體使用

    本文主要介紹了Python endswith()函數(shù)的具體使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • yolov5使用flask部署至前端實(shí)現(xiàn)照片\視頻識(shí)別功能

    yolov5使用flask部署至前端實(shí)現(xiàn)照片\視頻識(shí)別功能

    初學(xué)者在使用YOLO和Flask構(gòu)建應(yīng)用時(shí),往往需要實(shí)現(xiàn)上傳圖片和視頻的識(shí)別功能,本文介紹了如何在Flask框架中實(shí)現(xiàn)這一功能,包括文件上傳、圖片放大查看、視頻識(shí)別以及識(shí)別后的文件下載,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-09-09
  • 探索Python神奇算術(shù)用代碼輕松求和的幾種方法

    探索Python神奇算術(shù)用代碼輕松求和的幾種方法

    求和是數(shù)學(xué)中最基本的運(yùn)算之一,也是編程中常見的任務(wù)之一,Python 提供了多種方法來計(jì)算和求和數(shù)字,本文將掏出計(jì)算求和的不同方法,包括使用循環(huán)、內(nèi)置函數(shù)以及第三方庫
    2023-11-11

最新評論

广南县| 民勤县| 阳泉市| 图木舒克市| 汕头市| 昌吉市| 台州市| 绵竹市| 屏东县| 天祝| 伊宁市| 柳林县| 阿拉尔市| 桐梓县| 西和县| 岫岩| 宁南县| 凤城市| 奇台县| 巨鹿县| 米泉市| 固镇县| 岳西县| 永兴县| 肥西县| 大足县| 涪陵区| 和平区| 海宁市| 顺昌县| 梧州市| 明溪县| 行唐县| 徐水县| 琼结县| 平乐县| 平凉市| 定南县| 襄樊市| 稷山县| 贡山|