[Python] 纯文本查看 复制代码
import os
import json
import requests
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from tkinterdnd2 import TkinterDnD, DND_FILES
from pathlib import Path
class DeepSeekRenamer(TkinterDnD.Tk):
def __init__(self):
super().__init__()
self.title("DeepSeek智能文件助手 v1.0")
self.geometry("800x600")
self.api_key = "your-api-key-here" # 替换为实际API密钥
self.setup_ui()
def setup_ui(self):
# 拖放区域
self.drop_frame = ttk.LabelFrame(self, text="拖放文件/文件夹至此")
self.drop_frame.pack(pady=10, padx=10, fill="both", expand=True)
# 控制面板
control_frame = ttk.Frame(self)
control_frame.pack(pady=5, fill="x")
ttk.Label(control_frame, text="目标字数:").pack(side="left")
self.word_count = ttk.Spinbox(control_frame, from_=5, to=100, width=5)
self.word_count.set(30)
self.word_count.pack(side="left", padx=5)
self.ai_toggle = ttk.Checkbutton(control_frame, text="启用AI优化")
self.ai_toggle.state(["selected"])
self.ai_toggle.pack(side="left", padx=10)
self.process_btn = ttk.Button(control_frame, text="开始处理", command=self.process_files)
self.process_btn.pack(side="right")
# 日志窗口
self.log = tk.Text(self, state="disabled")
self.log.pack(pady=10, padx=10, fill="both", expand=True)
# 拖放事件绑定
self.drop_frame.drop_target_register(DND_FILES)
self.drop_frame.dnd_bind("<<Drop>>", self.handle_drop)
def handle_drop(self, event):
self.file_paths = []
for item in event.data.split():
path = item.replace("{", "").replace("}", "")
if os.path.exists(path):
self.file_paths.append(path)
self.log_message(f"已加载 {len(self.file_paths)} 个待处理对象")
def process_files(self):
if not hasattr(self, "file_paths"):
messagebox.showwarning("警告", "请先拖放文件或文件夹")
return
try:
for path in self.file_paths:
if os.path.isfile(path):
self.process_single_file(path)
elif os.path.isdir(path):
self.process_directory(path)
messagebox.showinfo("完成", "所有文件处理完成")
except Exception as e:
messagebox.showerror("错误", f"处理失败: {str(e)}")
def process_directory(self, dir_path):
for root, dirs, files in os.walk(dir_path):
for file in files:
self.process_single_file(os.path.join(root, file))
for dir in dirs:
self.process_directory(os.path.join(root, dir))
def process_single_file(self, file_path):
original_name = Path(file_path).stem
extension = Path(file_path).suffix
try:
if "selected" in self.ai_toggle.state():
new_name = self.generate_ai_title(original_name)
else:
new_name = original_name[:int(self.word_count.get())]
new_path = self.get_available_path(
os.path.join(os.path.dirname(file_path), f"{new_name}{extension}")
)
os.rename(file_path, new_path)
self.log_message(f"重命名成功: {Path(file_path).name} → {Path(new_path).name}")
except Exception as e:
self.log_message(f"处理失败 [{Path(file_path).name}]: {str(e)}")
def generate_ai_title(self, original_text):
headers = {"Authorization": f"Bearer {self.api_key}"}
prompt = f"""请将以下文件标题优化为中文,保留关键信息,字数严格限制在{self.word_count.get()}字:
原始标题:{original_text}
优化后的标题:"""
response = requests.post(
"https://api.deepseek.com/v1/chat/completions",
headers=headers,
json={
"model": "deepseek-chat",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.3
}
)
if response.status_code != 200:
raise Exception(f"API错误: {response.text}")
return json.loads(response.text)["choices"][0]["message"]["content"].strip()
def get_available_path(self, target_path):
if not os.path.exists(target_path):
return target_path
base, ext = os.path.splitext(target_path)
counter = 1
while os.path.exists(f"{base}_{counter}{ext}"):
counter += 1
return f"{base}_{counter}{ext}"
def log_message(self, message):
self.log.configure(state="normal")
self.log.insert("end", message + "\n")
self.log.configure(state="disabled")
self.log.see("end")
if __name__ == "__main__":
app = DeepSeekRenamer()
app.mainloop()