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

Python使用PyQt5實(shí)現(xiàn)與DeepSeek聊天的圖形化小軟件

 更新時(shí)間:2025年03月11日 10:35:55   作者:老胖閑聊  
在?PyQt5?中,菜單欄(QMenuBar)、工具欄(QToolBar)和狀態(tài)欄(QStatusBar)是?QMainWindow?提供的標(biāo)準(zhǔn)控件,用于幫助用戶更好地與應(yīng)用程序交互,所以本文給大家介紹了Python使用PyQt5實(shí)現(xiàn)與DeepSeek聊天的圖形化小軟件,需要的朋友可以參考下

1. 導(dǎo)入依賴庫(kù)

import sys
import requests
import json
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QLineEdit, QPushButton, QLabel, QFileDialog
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QPixmap
  • sys: 用于處理 Python 的系統(tǒng)相關(guān)功能,例如退出程序。
  • requests: 用于發(fā)送 HTTP 請(qǐng)求,與 DeepSeek API 進(jìn)行通信。
  • json: 用于處理 JSON 格式的數(shù)據(jù)。
  • PyQt5: 用于創(chuàng)建圖形用戶界面(GUI)。
    • QApplication: 管理應(yīng)用程序的控制流和主要設(shè)置。
    • QWidget: 所有用戶界面對(duì)象的基類。
    • QVBoxLayout: 垂直布局管理器,用于排列控件。
    • QTextEdit: 多行文本輸入框,用于顯示聊天記錄。
    • QLineEdit: 單行文本輸入框,用于用戶輸入消息。
    • QPushButton: 按鈕控件,用于觸發(fā)事件。
    • QLabel: 標(biāo)簽控件,用于顯示文本或圖像。
    • QFileDialog: 文件選擇對(duì)話框,用于上傳圖像。
  • QThread: 用于創(chuàng)建多線程,避免阻塞主線程。
  • pyqtSignal: 用于在線程和主線程之間傳遞信號(hào)。
  • QPixmap: 用于加載和顯示圖像。

2. DeepSeek API 配置

DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
DEEPSEEK_API_KEY = "your_deepseek_api_key"  # 替換為自己的 DeepSeek API Key
  • DEEPSEEK_API_URL: DeepSeek API 的端點(diǎn) URL。
  • DEEPSEEK_API_KEY: DeepSeek API 密鑰,用于身份驗(yàn)證。

3. ChatThread 類

class ChatThread(QThread):
    response_received = pyqtSignal(str)
    stream_response_received = pyqtSignal(str)

    def __init__(self, messages, stream=False):
        super().__init__()
        self.messages = messages
        self.stream = stream

    def run(self):
        headers = {
            "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
            "Content-Type": "application/json"
        }

        data = {
            "model": "deepseek-chat",
            "messages": self.messages,
            "stream": self.stream
        }

        if self.stream:
            response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data, stream=True)
            for line in response.iter_lines():
                if line:
                    decoded_line = line.decode('utf-8')
                    if decoded_line.startswith("data:"):
                        json_data = json.loads(decoded_line[5:])
                        if "choices" in json_data:
                            content = json_data["choices"][0]["delta"].get("content", "")
                            self.stream_response_received.emit(content)
        else:
            response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
            if response.status_code == 200:
                json_data = response.json()
                content = json_data["choices"][0]["message"]["content"]
                self.response_received.emit(content)
            else:
                self.response_received.emit("Error: 無(wú)法從DeepSeekAPI獲得響應(yīng).")

功能說(shuō)明

  • ChatThread 是一個(gè)繼承自 QThread 的類,用于在后臺(tái)與 DeepSeek API 進(jìn)行通信。
  • response_received 和 stream_response_received: 這兩個(gè)信號(hào)用于將 API 的響應(yīng)傳遞回主線程。
  • __init__ 方法:
    • 接受 messages(聊天記錄)和 stream(是否啟用流式輸出)作為參數(shù)。
  • run 方法:
    • 發(fā)送 HTTP POST 請(qǐng)求到 DeepSeek API。
    • 如果啟用流式輸出(stream=True),則逐行讀取響應(yīng)并發(fā)送信號(hào)。
    • 如果禁用流式輸出,則等待完整響應(yīng)后發(fā)送信號(hào)。

4. ChatApp 類

class ChatApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.messages = []

    def initUI(self):
        self.setWindowTitle('DeepSeek Chat')
        self.setGeometry(100, 100, 600, 400)

        layout = QVBoxLayout()

        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        layout.addWidget(self.chat_display)

        self.input_box = QLineEdit()
        self.input_box.setPlaceholderText("在此留下你的千言萬(wàn)語(yǔ)...")
        layout.addWidget(self.input_box)

        self.send_button = QPushButton('發(fā)送')
        self.send_button.clicked.connect(self.send_message)
        layout.addWidget(self.send_button)

        self.image_label = QLabel()
        layout.addWidget(self.image_label)

        self.upload_image_button = QPushButton('上傳圖片')
        self.upload_image_button.clicked.connect(self.upload_image)
        layout.addWidget(self.upload_image_button)

        self.setLayout(layout)

功能說(shuō)明

  • ChatApp 是主應(yīng)用程序類,繼承自 QWidget
  • __init__ 方法:
    • 初始化界面并創(chuàng)建一個(gè)空的消息列表 self.messages。
  • initUI 方法:
    • 設(shè)置窗口標(biāo)題和大小。
    • 使用 QVBoxLayout 垂直排列控件。
    • chat_display: 用于顯示聊天記錄的多行文本框。
    • input_box: 用于用戶輸入消息的單行文本框。
    • send_button: 發(fā)送消息的按鈕,點(diǎn)擊后觸發(fā) send_message 方法。
    • image_label: 用于顯示上傳的圖像。
    • upload_image_button: 上傳圖像的按鈕,點(diǎn)擊后觸發(fā) upload_image 方法。

5. 核心功能方法

5.1 send_message 方法

def send_message(self):
    user_input = self.input_box.text()
    if user_input:
        self.messages.append({"role": "user", "content": user_input})
        self.chat_display.append(f"You: {user_input}")
        self.input_box.clear()

        self.chat_thread = ChatThread(self.messages, stream=True)
        self.chat_thread.stream_response_received.connect(self.update_chat_display_stream)
        self.chat_thread.start()
  • 獲取用戶輸入的消息。
  • 將消息添加到 self.messages 列表中。
  • 在聊天顯示區(qū)域顯示用戶的消息。
  • 清空輸入框。
  • 啟動(dòng) ChatThread 線程與 DeepSeek API 通信,并啟用流式輸出。

5.2 update_chat_display_stream 方法

def update_chat_display_stream(self, content):
    self.chat_display.moveCursor(self.chat_display.textCursor().End)
    self.chat_display.insertPlainText(content)
    self.chat_display.moveCursor(self.chat_display.textCursor().End)
  • 將 DeepSeek API 的流式響應(yīng)逐字添加到聊天顯示區(qū)域。
  • 確保光標(biāo)始終在文本末尾,以便用戶可以看到最新的內(nèi)容。

5.3 upload_image 方法

def upload_image(self):
    options = QFileDialog.Options()
    file_name, _ = QFileDialog.getOpenFileName(self, "上傳圖片", "", "Images (*.png *.jpg *.jpeg)", options=options)
    if file_name:
        pixmap = QPixmap(file_name)
        self.image_label.setPixmap(pixmap.scaled(200, 200))
        self.messages.append({"role": "user", "content": f"Image: {file_name}"})
  • 打開(kāi)文件選擇對(duì)話框,允許用戶選擇圖像文件。
  • 加載圖像并顯示在 image_label 中。
  • 將圖像路徑添加到 self.messages 列表中。

6. 主程序入口

if __name__ == '__main__':
    app = QApplication(sys.argv)
    chat_app = ChatApp()
    chat_app.show()
    sys.exit(app.exec_())
  • 創(chuàng)建 QApplication 實(shí)例。
  • 創(chuàng)建 ChatApp 實(shí)例并顯示窗口。
  • 進(jìn)入主事件循環(huán),等待用戶交互。

7、完整代碼如下:

需要安裝PyQt5和requests

pip install PyQt5 requests
import sys
import requests
import json
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QLineEdit, QPushButton, QLabel, QFileDialog
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QPixmap

# DeepSeek API 配置
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
DEEPSEEK_API_KEY = "your_deepseek_api_key"  # 替換為自己的 DeepSeek API Key,去DeepSeek注冊(cè)獲取

class ChatThread(QThread):
    response_received = pyqtSignal(str)
    stream_response_received = pyqtSignal(str)

    def __init__(self, messages, stream=False):
        super().__init__()
        self.messages = messages
        self.stream = stream

    def run(self):
        headers = {
            "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
            "Content-Type": "application/json"
        }

        data = {
            "model": "deepseek-chat",
            "messages": self.messages,
            "stream": self.stream
        }

        if self.stream:
            response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data, stream=True)
            for line in response.iter_lines():
                if line:
                    decoded_line = line.decode('utf-8')
                    if decoded_line.startswith("data:"):
                        json_data = json.loads(decoded_line[5:])
                        if "choices" in json_data:
                            content = json_data["choices"][0]["delta"].get("content", "")
                            self.stream_response_received.emit(content)
        else:
            response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
            if response.status_code == 200:
                json_data = response.json()
                content = json_data["choices"][0]["message"]["content"]
                self.response_received.emit(content)
            else:
                self.response_received.emit("Error: 無(wú)法從DeepSeekAPI獲得響應(yīng).")

class ChatApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.messages = []

    def initUI(self):
        self.setWindowTitle('DeepSeek Chat')
        self.setGeometry(100, 100, 600, 400)

        layout = QVBoxLayout()

        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        layout.addWidget(self.chat_display)

        self.input_box = QLineEdit()
        self.input_box.setPlaceholderText("在此留下你的千言萬(wàn)語(yǔ)...")
        layout.addWidget(self.input_box)

        self.send_button = QPushButton('發(fā)送')
        self.send_button.clicked.connect(self.send_message)
        layout.addWidget(self.send_button)

        self.image_label = QLabel()
        layout.addWidget(self.image_label)

        self.upload_image_button = QPushButton('上傳圖片')
        self.upload_image_button.clicked.connect(self.upload_image)
        layout.addWidget(self.upload_image_button)

        self.setLayout(layout)

    def send_message(self):
        user_input = self.input_box.text()
        if user_input:
            self.messages.append({"role": "user", "content": user_input})
            self.chat_display.append(f"You: {user_input}")
            self.input_box.clear()

            self.chat_thread = ChatThread(self.messages, stream=True)
            self.chat_thread.stream_response_received.connect(self.update_chat_display_stream)
            self.chat_thread.start()

    def update_chat_display_stream(self, content):
        self.chat_display.moveCursor(self.chat_display.textCursor().End)
        self.chat_display.insertPlainText(content)
        self.chat_display.moveCursor(self.chat_display.textCursor().End)

    def upload_image(self):
        options = QFileDialog.Options()
        file_name, _ = QFileDialog.getOpenFileName(self, "上傳圖片", "", "Images (*.png *.jpg *.jpeg)", options=options)
        if file_name:
            pixmap = QPixmap(file_name)
            self.image_label.setPixmap(pixmap.scaled(200, 200))
            self.messages.append({"role": "user", "content": f"Image: {file_name}"})

if __name__ == '__main__':
    app = QApplication(sys.argv)
    chat_app = ChatApp()
    chat_app.show()
    sys.exit(app.exec_())

8. 總結(jié)

  • 使用 PyQt5 創(chuàng)建了一個(gè)簡(jiǎn)單的圖形化聊天界面。
  • 通過(guò) ChatThread 實(shí)現(xiàn)了與 DeepSeek API 的異步通信,支持流式和非流式輸出。
  • 支持多輪對(duì)話和多模態(tài)輸入(如圖像上傳)。
  • 代碼結(jié)構(gòu)清晰,易于擴(kuò)展和優(yōu)化。

以上就是Python使用PyQt5實(shí)現(xiàn)與DeepSeek聊天的圖形化小軟件的詳細(xì)內(nèi)容,更多關(guān)于Python PyQt5與DeepSeek聊天軟件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python批量實(shí)現(xiàn)word中查找關(guān)鍵字的示例代碼

    Python批量實(shí)現(xiàn)word中查找關(guān)鍵字的示例代碼

    本文主要介紹了Python批量實(shí)現(xiàn)word中查找關(guān)鍵字的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • windows支持哪個(gè)版本的python

    windows支持哪個(gè)版本的python

    在本篇文章中小編給大家分享了關(guān)于windows支持python的版本的相關(guān)內(nèi)容知識(shí)點(diǎn),需要的朋友們可以學(xué)習(xí)下。
    2020-07-07
  • 快速進(jìn)修Python指南之控制if-else循環(huán)技巧

    快速進(jìn)修Python指南之控制if-else循環(huán)技巧

    這篇文章主要為大家介紹了Java開(kāi)發(fā)者的Python快速進(jìn)修指南之控制之if-else和循環(huán)技巧示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • Python Selenium防檢測(cè)策略匯總

    Python Selenium防檢測(cè)策略匯總

    這篇文章主要為大家詳細(xì)介紹了Python Selenium防檢測(cè)的一些策略匯總,文中的示例代碼簡(jiǎn)潔易懂,有需要的小伙伴可以根據(jù)自己的需要進(jìn)行選擇
    2025-04-04
  • 使用Python實(shí)現(xiàn)音頻雙通道分離

    使用Python實(shí)現(xiàn)音頻雙通道分離

    這篇文章主要介紹了使用Python實(shí)現(xiàn)音頻雙通道分離的方法,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-12-12
  • Centos安裝python3與scapy模塊的問(wèn)題及解決方法

    Centos安裝python3與scapy模塊的問(wèn)題及解決方法

    這篇文章主要介紹了Centos安裝python3與scapy模塊的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07
  • 2021年最新用于圖像處理的Python庫(kù)總結(jié)

    2021年最新用于圖像處理的Python庫(kù)總結(jié)

    為了快速地處理大量信息,科學(xué)家需要利用圖像準(zhǔn)備工具來(lái)完成人工智能和深度學(xué)習(xí)任務(wù).在本文中,我將深入研究Python中最有用的圖像處理庫(kù),這些庫(kù)正在人工智能和深度學(xué)習(xí)任務(wù)中得到大力利用.我們開(kāi)始吧,需要的朋友可以參考下
    2021-06-06
  • Python使用Seaborn快速生成高顏值業(yè)務(wù)圖表

    Python使用Seaborn快速生成高顏值業(yè)務(wù)圖表

    本文介紹了Python數(shù)據(jù)可視化庫(kù)Seaborn的核心功能與應(yīng)用場(chǎng)景,掌握Seaborn與Matplotlib的關(guān)系,學(xué)習(xí)使用Seaborn美化圖表繪制各類分布圖、分類圖、回歸圖和配對(duì)圖,提升數(shù)據(jù)可視化能力,需要的朋友可以參考下
    2026-06-06
  • 基于python編寫(xiě)圖片高斯模糊處理腳本

    基于python編寫(xiě)圖片高斯模糊處理腳本

    gaussian_blur.py是一個(gè)基于 Python 的圖片處理腳本,使用 Pillow 庫(kù)對(duì)圖片應(yīng)用高斯模糊效果,支持自定義模糊強(qiáng)度,下面小編就和大家詳細(xì)介紹一下具體的實(shí)現(xiàn)步驟吧
    2026-03-03
  • Python強(qiáng)大的自省機(jī)制詳解

    Python強(qiáng)大的自省機(jī)制詳解

    這篇文章主要為大家介紹了Python強(qiáng)大的自省機(jī)制,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2021-11-11

最新評(píng)論

锡林郭勒盟| 嘉黎县| 砚山县| 仪征市| 阿坝县| 莱州市| 华坪县| 萍乡市| 溧阳市| 临潭县| 屏山县| 吴旗县| 绩溪县| 扶风县| 威宁| 甘德县| 平度市| 尼木县| 兴城市| 津市市| 遵化市| 衡东县| 宣威市| 榕江县| 财经| 措勤县| 梁河县| 灵武市| 栾城县| 林甸县| 宁夏| 罗江县| 都江堰市| 怀柔区| 泸溪县| 梁平县| 呈贡县| 兴和县| 来宾市| 钦州市| 南昌县|