206 lines
6.8 KiB
Python
206 lines
6.8 KiB
Python
"""中奖记录 Tab 视图相关:截图列表、预览、误识别记录管理。
|
|
|
|
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内一组互相调用的闭包,
|
|
共享 ``_win_file_paths`` / ``_win_img_ref`` / 多个 widgets。
|
|
|
|
抽出后通过 ``WinRecordView`` 容器把状态聚一起,7 个动作函数接收容器作为参数。
|
|
``gui_app.py`` 在创建好 widgets 后调用 ``install_win_record_view`` 绑定按钮和
|
|
回调,并拿到 ``refresh`` / ``load_false_positives`` 两个函数用于 ``after`` 调度。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import tkinter as tk
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime
|
|
from tkinter import ttk
|
|
from typing import Any, Callable, Dict
|
|
|
|
from PIL import Image, ImageTk # type: ignore[import]
|
|
|
|
|
|
@dataclass
|
|
class WinRecordView:
|
|
"""中奖记录 Tab 的 widgets + 状态容器。"""
|
|
|
|
listbox: tk.Listbox
|
|
image_label: ttk.Label
|
|
preview_frame: tk.Misc
|
|
false_positive_text: tk.Text
|
|
on_line: Callable[[str], None]
|
|
file_paths: Dict[int, str] = field(default_factory=dict)
|
|
img_ref: Dict[str, Any] = field(default_factory=lambda: {"photo": None})
|
|
|
|
|
|
def _get_pic_dir() -> str:
|
|
try:
|
|
from douyin.core.path_config import get_pic_dir
|
|
|
|
return get_pic_dir()
|
|
except Exception:
|
|
from douyin.core import path_config
|
|
|
|
return path_config.get_pic_dir()
|
|
|
|
|
|
def scan_win_images() -> list:
|
|
"""扫描中奖截图目录,返回 ``[(filename, abs_path, mtime), ...]`` 按时间倒序。"""
|
|
pic_dir = _get_pic_dir()
|
|
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
|
|
win_images: list = []
|
|
|
|
if os.path.exists(prize_dir):
|
|
for file in os.listdir(prize_dir):
|
|
if file.lower().endswith((".png", ".jpg", ".jpeg")):
|
|
file_path = os.path.join(prize_dir, file)
|
|
# 获取文件修改时间
|
|
try:
|
|
mtime = os.path.getmtime(file_path)
|
|
win_images.append((file, file_path, mtime))
|
|
except Exception:
|
|
win_images.append((file, file_path, 0))
|
|
|
|
# 按时间倒序排序(最新的在前)
|
|
win_images.sort(key=lambda x: x[2], reverse=True)
|
|
return win_images
|
|
|
|
|
|
def refresh_win_record(view: WinRecordView) -> None:
|
|
"""刷新中奖记录列表"""
|
|
try:
|
|
win_images = scan_win_images()
|
|
view.listbox.delete(0, tk.END)
|
|
view.file_paths.clear()
|
|
|
|
for idx, (file, file_path, mtime) in enumerate(win_images):
|
|
# 格式化显示:文件名 + 时间
|
|
try:
|
|
dt = datetime.fromtimestamp(mtime)
|
|
time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
|
|
display_text = f"{file} ({time_str})"
|
|
except Exception:
|
|
display_text = file
|
|
|
|
view.listbox.insert(tk.END, display_text)
|
|
# 存储文件路径映射
|
|
view.file_paths[idx] = file_path
|
|
|
|
if win_images:
|
|
view.on_line(f"[中奖记录] 扫描到 {len(win_images)} 张中奖截图")
|
|
else:
|
|
view.on_line("[中奖记录] 暂无中奖截图")
|
|
except Exception as e:
|
|
view.on_line(f"[中奖记录] 刷新失败:{e}")
|
|
|
|
|
|
def _load_win_image(view: WinRecordView, img_path: str) -> None:
|
|
"""加载并显示中奖截图"""
|
|
if not os.path.exists(img_path):
|
|
view.image_label.configure(image="")
|
|
view.img_ref["photo"] = None
|
|
return
|
|
|
|
try:
|
|
img = Image.open(img_path)
|
|
img.load()
|
|
img = img.convert("RGB")
|
|
except Exception as e:
|
|
view.on_line(f"[中奖记录] 图片加载失败:{e}")
|
|
return
|
|
|
|
# 获取预览区域尺寸
|
|
try:
|
|
view.preview_frame.update_idletasks()
|
|
w = view.preview_frame.winfo_width()
|
|
h = view.preview_frame.winfo_height()
|
|
if w <= 1 or h <= 1:
|
|
w, h = 400, 600
|
|
except Exception:
|
|
w, h = 400, 600
|
|
|
|
max_w = max(200, w - 20)
|
|
max_h = max(300, h - 20)
|
|
|
|
try:
|
|
resample = Image.Resampling.LANCZOS
|
|
except AttributeError:
|
|
resample = 1
|
|
|
|
img.thumbnail((max_w, max_h), resample)
|
|
photo = ImageTk.PhotoImage(img)
|
|
view.img_ref["photo"] = photo
|
|
view.image_label.configure(image=photo)
|
|
|
|
|
|
def on_win_list_select(view: WinRecordView, _event=None) -> None:
|
|
"""当选择中奖截图时,显示预览"""
|
|
try:
|
|
selection = view.listbox.curselection()
|
|
if not selection:
|
|
return
|
|
|
|
index = selection[0]
|
|
# 从映射中获取文件路径
|
|
if index in view.file_paths:
|
|
file_path = view.file_paths[index]
|
|
_load_win_image(view, file_path)
|
|
except Exception as e:
|
|
view.on_line(f"[中奖记录] 预览失败:{e}")
|
|
|
|
|
|
def open_win_folder(view: WinRecordView) -> None:
|
|
"""打开中奖截图目录"""
|
|
pic_dir = _get_pic_dir()
|
|
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
|
|
os.makedirs(prize_dir, exist_ok=True)
|
|
try:
|
|
os.startfile(prize_dir) # type: ignore[attr-defined]
|
|
except Exception as e:
|
|
view.on_line(f"[中奖记录] 打开目录失败:{e}")
|
|
|
|
|
|
def load_false_positives(view: WinRecordView) -> None:
|
|
"""加载误识别记录"""
|
|
pic_dir = _get_pic_dir()
|
|
false_positive_file = os.path.join(
|
|
pic_dir, "lottery_prize_captures", "false_positives.json"
|
|
)
|
|
if not os.path.exists(false_positive_file):
|
|
view.false_positive_text.delete("1.0", "end")
|
|
view.false_positive_text.insert("1.0", "暂无误识别记录")
|
|
return
|
|
|
|
try:
|
|
with open(false_positive_file, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
false_positives = data.get("false_positives", [])
|
|
view.false_positive_text.delete("1.0", "end")
|
|
if false_positives:
|
|
view.false_positive_text.insert("1.0", "\n".join(false_positives))
|
|
else:
|
|
view.false_positive_text.insert("1.0", "暂无误识别记录")
|
|
except Exception as e:
|
|
view.false_positive_text.delete("1.0", "end")
|
|
view.false_positive_text.insert("1.0", f"加载失败:{e}")
|
|
|
|
|
|
def save_false_positives(view: WinRecordView) -> None:
|
|
"""保存误识别记录"""
|
|
pic_dir = _get_pic_dir()
|
|
false_positive_file = os.path.join(
|
|
pic_dir, "lottery_prize_captures", "false_positives.json"
|
|
)
|
|
os.makedirs(os.path.dirname(false_positive_file), exist_ok=True)
|
|
|
|
content = view.false_positive_text.get("1.0", "end-1c")
|
|
lines = [line.strip() for line in content.splitlines() if line.strip()]
|
|
|
|
try:
|
|
with open(false_positive_file, "w", encoding="utf-8") as f:
|
|
json.dump({"false_positives": lines}, f, ensure_ascii=False, indent=2)
|
|
view.on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录")
|
|
except Exception as e:
|
|
view.on_line(f"[中奖记录] 保存失败:{e}")
|