33 lines
1.2 KiB
Python
33 lines
1.2 KiB
Python
from PyQt6.QtCore import QThread, pyqtSignal
|
||
|
||
class BookReviewWorker(QThread):
|
||
"""后台获取书籍 AI 简评的线程(迁移自 ibook_export_app.py)。"""
|
||
finished = pyqtSignal(str, str) # bookname, review
|
||
|
||
def __init__(self, bookname, prompt, json_path, parent=None):
|
||
super().__init__(parent)
|
||
self.bookname = bookname
|
||
self.prompt = prompt
|
||
self.json_path = json_path
|
||
|
||
def run(self):
|
||
import json
|
||
try:
|
||
from ai_interface import DashScopeChatClient
|
||
chat = DashScopeChatClient()
|
||
review = chat.ask(self.prompt)
|
||
except Exception as e:
|
||
review = f"[AI简评获取失败: {e}]"
|
||
try:
|
||
try:
|
||
with open(self.json_path, 'r', encoding='utf-8') as f:
|
||
intro_dict = json.load(f)
|
||
except Exception:
|
||
intro_dict = {}
|
||
intro_dict[self.bookname] = review
|
||
with open(self.json_path, 'w', encoding='utf-8') as f:
|
||
json.dump(intro_dict, f, ensure_ascii=False, indent=2)
|
||
except Exception as e:
|
||
print(f"写入 bookintro.json 失败: {e}")
|
||
self.finished.emit(self.bookname, review)
|