[Python] 纯文本查看 复制代码
import tkinter as tk
from tkinter import filedialog, messagebox
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import requests
import os
import threading
class AIWriterApp:
def __init__(self, root):
self.root = root
self.root.title("AI写作助手")
self.root.geometry("600x500")
self.root.configure(bg="#f0f0f0")
# 初始化计数器
self.generated_count = 0
self.failed_count = 0
# 创建界面元素
self.create_widgets()
def create_widgets(self):
# 标题
title_label = ttk.Label(self.root, text="AI写作助手", font=("Helvetica", 24, "bold"), bootstyle="inverse-primary")
title_label.pack(pady=(20, 10))
# 关键词输入框
keyword_frame = ttk.Frame(self.root, bootstyle="light")
keyword_frame.pack(pady=5, fill=X, padx=20)
ttk.Label(keyword_frame, text="关键词:", font=("Helvetica", 12), bootstyle="inverse-light").pack(side=LEFT, padx=(0, 10))
self.keyword_entry = ttk.Entry(keyword_frame, width=50, font=("Helvetica", 12))
self.keyword_entry.pack(side=LEFT, fill=X, expand=True)
# 生成数量输入框
count_frame = ttk.Frame(self.root, bootstyle="light")
count_frame.pack(pady=5, fill=X, padx=20)
ttk.Label(count_frame, text="生成数量:", font=("Helvetica", 12), bootstyle="inverse-light").pack(side=LEFT, padx=(0, 10))
self.count_entry = ttk.Entry(count_frame, width=10, font=("Helvetica", 12))
self.count_entry.pack(side=LEFT)
# 文章字数输入框
word_count_frame = ttk.Frame(self.root, bootstyle="light")
word_count_frame.pack(pady=5, fill=X, padx=20)
ttk.Label(word_count_frame, text="建议字数:", font=("Helvetica", 12), bootstyle="inverse-light").pack(side=LEFT, padx=(0, 10))
self.word_count_entry = ttk.Entry(word_count_frame, width=10, font=("Helvetica", 12))
self.word_count_entry.pack(side=LEFT)
# 文章风格输入框
style_frame = ttk.Frame(self.root, bootstyle="light")
style_frame.pack(pady=5, fill=X, padx=20)
ttk.Label(style_frame, text="文章风格:", font=("Helvetica", 12), bootstyle="inverse-light").pack(side=LEFT, padx=(0, 10))
self.style_entry = ttk.Entry(style_frame, width=50, font=("Helvetica", 12))
self.style_entry.pack(side=LEFT, fill=X, expand=True)
# 导入关键词按钮
self.import_button = ttk.Button(self.root, text="导入关键词", bootstyle="outline-primary", command=self.import_keywords)
self.import_button.pack(pady=10, padx=20, side=LEFT, fill=X, expand=True)
# 生成文章按钮
self.generate_button = ttk.Button(self.root, text="生成文章", bootstyle="outline-primary", command=self.start_generate_articles)
self.generate_button.pack(pady=10, padx=20, side=LEFT, fill=X, expand=True)
# 进度条
self.progress = ttk.Progressbar(self.root, bootstyle="success", length=400, mode="determinate")
self.progress.pack(pady=10, padx=20, fill=X)
# 生成和失败计数器
counter_frame = ttk.Frame(self.root, bootstyle="light")
counter_frame.pack(pady=5, fill=X, padx=20)
self.generated_label = ttk.Label(counter_frame, text="生成文章数量: 0", font=("Helvetica", 12), bootstyle="inverse-light")
self.generated_label.pack(side=LEFT, padx=(0, 10))
self.failed_label = ttk.Label(counter_frame, text="失败数量: 0", font=("Helvetica", 12), bootstyle="inverse-light")
self.failed_label.pack(side=RIGHT)
# 状态标签
self.status_label = ttk.Label(self.root, text="", font=("Helvetica", 12), bootstyle="inverse-light")
self.status_label.pack(pady=10, padx=20, fill=X)
def import_keywords(self):
file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
if file_path:
with open(file_path, 'r', encoding='utf-8') as file:
keywords = file.read().splitlines()
self.keyword_entry.delete(0, tk.END)
self.keyword_entry.insert(0, ', '.join(keywords))
def start_generate_articles(self):
# 显示正在生成中的状态
self.status_label.config(text="正在生成中,请稍等...")
self.root.update_idletasks()
# 启动生成文章的线程
threading.Thread(target=self.generate_articles).start()
def generate_articles(self):
keywords = self.keyword_entry.get().split(',')
count = int(self.count_entry.get())
word_count = int(self.word_count_entry.get())
style = self.style_entry.get()
if not os.path.exists("文章"):
os.makedirs("文章")
total_articles = len(keywords) * count
self.progress["maximum"] = total_articles
self.progress["value"] = 0
self.generated_count = 0
self.failed_count = 0
for keyword in keywords:
for _ in range(count):
article = self.generate_article(keyword.strip(), word_count, style)
if article:
self.save_article(article)
self.generated_count += 1
else:
self.failed_count += 1
self.progress["value"] += 1
self.update_counters()
self.root.update_idletasks()
# 显示生成完成的状态
self.status_label.config(text="已完成,请查收")
def generate_article(self, keyword, word_count, style):
api_key = "替换api" # 替换为你的API Key
base_url = "https://api.moonshot.cn/v1"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
data = {
"model": "moonshot-v1-8k",
"messages": [
{"role": "system", "content": "你是文章创作大师,你擅长创作任何已知风格的文章,并且根据用户的要求,你会尝试不同风格,创作出有吸引力的文章,以及符合风格的标题。"},
{"role": "user", "content": f"请根据关键词'{keyword}'生成一篇{word_count}字左右的{style}风格的文章。"}
],
"temperature": 0.3
}
response = requests.post(f"{base_url}/chat/completions", headers=headers, json=data)
if response.status_code == 200:
return response.json()["choices"][0]["message"]["content"]
else:
messagebox.showerror("错误", f"API请求失败: {response.status_code}")
return None
def save_article(self, article):
title = article.split('\n')[0].strip()
with open(f"文章/{title}.txt", 'w', encoding='utf-8') as file:
file.write(article)
def update_counters(self):
self.generated_label.config(text=f"生成文章数量: {self.generated_count}")
self.failed_label.config(text=f"失败数量: {self.failed_count}")
if __name__ == "__main__":
root = ttk.Window(themename="cosmo")
app = AIWriterApp(root)
root.mainloop()