吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 583|回复: 3
收起左侧

[求助] 对Python比较熟悉的大哥看一下,这个代码检测EPS不准确,帮我指出问题

[复制链接]
52pjXXB0614 发表于 2026-1-17 18:58
本帖最后由 cattie 于 2026-1-17 20:47 编辑
import tkinter as tk
from tkinter import filedialog, ttk, scrolledtext, messagebox
import os
import re
import subprocess
import tempfile
import shutil
import threading
import queue
import hashlib
from datetime import datetime
import mmap

class EPSConverterDetector:
    def __init__(self, root):
        self.root = root
        self.root.title("EPS文字转曲专业分析工具")
        self.root.geometry("1200x850")

        # 初始化
        self.eps_files = []
        self.results = []
        self.is_checking = False
        self.check_queue = queue.Queue()

        # 检测配置
        self.config = {
            'gs_path': self.find_ghostscript(),
            'detection_mode': 'advanced',  # basic, advanced, expert
            'analyze_vectors': True,
            'check_embedded_fonts': True,
            'timeout': 30
        }

        # 创建UI
        self.create_widgets()
        self.setup_text_tags()

    def find_ghostscript(self):
        [i]"""[i]查找[i]Ghostscript[i]安装路径[i]"""
[i]        # 尝试多个可能的路径
        gs_names = ['gswin64c', 'gswin32c', 'gs']

        for name in gs_names:
            path = shutil.which(name)
            if path:
                return path

        # 检查Windows注册表
        if os.name == 'nt':
            try:
                import winreg
                try:
                    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                         r"SOFTWARE\GPL Ghostscript")
                    for i in range(winreg.QueryInfoKey(key)[0]):
                        subkey_name = winreg.EnumKey(key, i)
                        subkey = winreg.OpenKey(key, subkey_name)
                        try:
                            gs_path = winreg.QueryValueEx(subkey, "GS_DLL")[0]
                            gs_dir = os.path.dirname(gs_path)
                            exe_path = os.path.join(gs_dir, "gswin64c.exe")
                            if os.path.exists(exe_path):
                                return exe_path
                        finally:
                            winreg.CloseKey(subkey)
                except:
                    pass
            except ImportError:
                pass

        return None

    def create_widgets(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="15")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 标题区域
        title_frame = ttk.Frame(main_frame)
        title_frame.pack(fill=tk.X, pady=(0, 15))

        title_label = ttk.Label(title_frame, text="EPS文字转曲专业分析工具",
                                font=('Arial', 20, 'bold'), foreground="#2c3e50")
        title_label.pack(side=tk.LEFT)

        # 检测状态
        status_frame = ttk.Frame(title_frame)
        status_frame.pack(side=tk.RIGHT)

        gs_status = "✓ GS已安装" if self.config['gs_path'] else "✗ GS未安装"
        gs_color = "#27ae60" if self.config['gs_path'] else "#e74c3c"
        self.gs_status_label = ttk.Label(status_frame, text=gs_status,
                                         foreground=gs_color, font=('Arial', 10))
        self.gs_status_label.pack()

        # 控制面板
        control_frame = ttk.LabelFrame(main_frame, text="控制面板", padding=10)
        control_frame.pack(fill=tk.X, pady=(0, 15))

        # 文件夹选择
        folder_frame = ttk.Frame(control_frame)
        folder_frame.pack(fill=tk.X, pady=(0, 10))

        ttk.Label(folder_frame, text="文件夹路径:").pack(side=tk.LEFT)
        self.folder_var = tk.StringVar()
        folder_entry = ttk.Entry(folder_frame, textvariable=self.folder_var, width=70)
        folder_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)

        ttk.Button(folder_frame, text="浏览", command=self.browse_folder).pack(side=tk.LEFT, padx=2)
        ttk.Button(folder_frame, text="扫描", command=self.scan_folder).pack(side=tk.LEFT)

        # 检测按钮
        button_frame = ttk.Frame(control_frame)
        button_frame.pack(fill=tk.X)

        # 第一行按钮
        btn_row1 = ttk.Frame(button_frame)
        btn_row1.pack(fill=tk.X, pady=(0, 5))

        detection_modes = [
            ("基础检测", lambda: self.start_detection('basic')),
            ("高级检测", lambda: self.start_detection('advanced')),
            ("专家模式", lambda: self.start_detection('expert')),
        ]

        for text, command in detection_modes:
            btn = ttk.Button(btn_row1, text=text, command=command, width=15)
            btn.pack(side=tk.LEFT, padx=2)

        # 第二行按钮
        btn_row2 = ttk.Frame(button_frame)
        btn_row2.pack(fill=tk.X)

        other_buttons = [
            ("停止检测", self.stop_detection),
            ("导出报告", self.export_report),
            ("清空结果", self.clear_results),
            ("分析设置", self.open_settings),
        ]

        for text, command in other_buttons:
            ttk.Button(btn_row2, text=text, command=command, width=15).pack(side=tk.LEFT, padx=2)

        # 进度区域
        progress_frame = ttk.Frame(main_frame)
        progress_frame.pack(fill=tk.X, pady=(0, 15))

        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(progress_frame,
                                            variable=self.progress_var,
                                            maximum=100,
                                            style="green.Horizontal.TProgressbar")
        self.progress_bar.pack(fill=tk.X)

        self.progress_label = ttk.Label(progress_frame, text="就绪",
                                        font=('Arial', 10))
        self.progress_label.pack(pady=(5, 0))

        # 主内容区域
        content_paned = ttk.PanedWindow(main_frame, orient=tk.HORIZONTAL)
        content_paned.pack(fill=tk.BOTH, expand=True)

        # 左侧文件列表
        left_frame = ttk.Frame(content_paned, width=350)
        content_paned.add(left_frame, weight=1)

        # 文件列表
        list_frame = ttk.LabelFrame(left_frame, text="文件列表", padding=10)
        list_frame.pack(fill=tk.BOTH, expand=True)

        # 文件统计
        stats_frame = ttk.Frame(list_frame)
        stats_frame.pack(fill=tk.X, pady=(0, 10))

        self.total_files_label = ttk.Label(stats_frame, text="0 个文件",
                                           font=('Arial', 10, 'bold'))
        self.total_files_label.pack(side=tk.LEFT)

        self.selected_label = ttk.Label(stats_frame, text="已选: 0",
                                        foreground="#3498db")
        self.selected_label.pack(side=tk.RIGHT)

        # 文件列表框
        listbox_frame = ttk.Frame(list_frame)
        listbox_frame.pack(fill=tk.BOTH, expand=True)

        scrollbar = ttk.Scrollbar(listbox_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        self.file_listbox = tk.Listbox(listbox_frame,
                                       yscrollcommand=scrollbar.set,
                                       selectmode=tk.EXTENDED,
                                       font=('Consolas', 10),
                                       bg="#f8f9fa",
                                       relief=tk.FLAT)
        self.file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.config(command=self.file_listbox.yview)

        # 绑定选择事件
        self.file_listbox.bind('<<ListboxSelect>>', self.on_file_select)

        # 右侧结果区域
        right_frame = ttk.Frame(content_paned)
        content_paned.add(right_frame, weight=3)

        # 使用Notebook
        self.notebook = ttk.Notebook(right_frame)
        self.notebook.pack(fill=tk.BOTH, expand=True)

        # 检测结果标签页
        result_frame = ttk.Frame(self.notebook)
        self.notebook.add(result_frame, text="检测结果")

        self.result_text = scrolledtext.ScrolledText(result_frame,
                                                     wrap=tk.WORD,
                                                     font=('Consolas', 10),
                                                     bg="#ffffff")
        self.result_text.pack(fill=tk.BOTH, expand=True)

        # 详细分析标签页
        detail_frame = ttk.Frame(self.notebook)
        self.notebook.add(detail_frame, text="详细分析")

        self.detail_text = scrolledtext.ScrolledText(detail_frame,
                                                     wrap=tk.WORD,
                                                     font=('Consolas', 9),
                                                     bg="#fafafa")
        self.detail_text.pack(fill=tk.BOTH, expand=True)

        # 统计信息标签页
        stats_tab_frame = ttk.Frame(self.notebook)
        self.notebook.add(stats_tab_frame, text="统计信息")

        self.stats_text = scrolledtext.ScrolledText(stats_tab_frame,
                                                    wrap=tk.WORD,
                                                    font=('Consolas', 10),
                                                    bg="#ffffff")
        self.stats_text.pack(fill=tk.BOTH, expand=True)

        # 状态栏
        self.status_bar = ttk.Label(self.root, text="就绪",
                                    relief=tk.SUNKEN, anchor=tk.W,
                                    background="#ecf0f1",
                                    foreground="#2c3e50")
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    def setup_text_tags(self):
        [i]"""[i]设置文本标签样式[i]"""
[i]        tags = [
            ('header', {'font': ('Arial', 12, 'bold'), 'foreground': '#2c3e50'}),
            ('subheader', {'font': ('Arial', 11, 'bold'), 'foreground': '#34495e'}),
            ('unconverted', {'font': ('Arial', 10, 'bold'), 'foreground': '#e74c3c', 'background': '#ffebee'}),
            ('converted', {'font': ('Arial', 10, 'bold'), 'foreground': '#27ae60', 'background': '#e8f5e9'}),
            ('warning', {'font': ('Arial', 10, 'bold'), 'foreground': '#f39c12', 'background': '#fff3e0'}),
            ('info', {'font': ('Arial', 10), 'foreground': '#3498db'}),
            ('error', {'font': ('Arial', 10), 'foreground': '#c0392b', 'background': '#ffebee'}),
            ('success', {'font': ('Arial', 10), 'foreground': '#27ae60'}),
            ('highlight', {'background': '#fff9c4'}),
            ('bold', {'font': ('Arial', 10, 'bold')}),
            ('italic', {'font': ('Arial', 10, 'italic')}),
            ('filepath', {'font': ('Consolas', 9), 'foreground': '#7f8c8d'}),
        ]

        for tag_name, config in tags:
            self.result_text.tag_config(tag_name, **config)
            self.detail_text.tag_config(tag_name, **config)
            self.stats_text.tag_config(tag_name, **config)

    def browse_folder(self):
        [i]"""[i]浏览文件夹[i]"""
[i]        folder_path = filedialog.askdirectory(
            title="选择包含EPS文件的文件夹",
            initialdir=os.path.expanduser("~")
        )
        if folder_path:
            self.folder_var.set(folder_path)

    def scan_folder(self):
        [i]"""[i]扫描文件夹[i]"""
[i]        folder_path = self.folder_var.get()
        if not folder_path or not os.path.exists(folder_path):
            messagebox.showwarning("警告", "请选择有效的文件夹路径")
            return

        self.eps_files = []
        self.file_listbox.delete(0, tk.END)

        try:
            # 支持的扩展名
            supported_extensions = {'.eps', '.ai', '.ps', '.EPS', '.AI', '.PS'}

            # 收集文件
            for root_dir, dirs, files in os.walk(folder_path):
                for file in files:
                    ext = os.path.splitext(file)[1]
                    if ext in supported_extensions:
                        full_path = os.path.join(root_dir, file)
                        self.eps_files.append(full_path)

            if not self.eps_files:
                messagebox.showinfo("提示", "未找到EPS/AI/PS文件")
                return

            # 按修改时间排序
            self.eps_files.sort(key=lambda x: os.path.getmtime(x), reverse=True)

            # 更新UI
            self.update_file_list()

            self.total_files_label.config(text=f"{len(self.eps_files)} 个文件")
            self.log(f"扫描完成,找到 {len(self.eps_files)} 个文件", "success")

        except Exception as e:
            self.log(f"扫描失败: {str(e)}", "error")

    def update_file_list(self):
        [i]"""[i]更新文件列表[i]"""
[i]        self.file_listbox.delete(0, tk.END)

        for idx, file_path in enumerate(self.eps_files):
            filename = os.path.basename(file_path)

            try:
                size = os.path.getsize(file_path)
                mtime = datetime.fromtimestamp(os.path.getmtime(file_path))

                # 格式化显示
                if size < 1024:
                    size_str = f"{size} B"
                elif size < 1024 * 1024:
                    size_str = f"{size / 1024:.0f} KB"
                else:
                    size_str = f"{size / (1024 * 1024):.1f} MB"

                time_str = mtime.strftime("%m-%d %H:%M")
                display_text = f"{idx + 1:3d}. {filename[:30]:30} {size_str:>8} {time_str}"

            except:
                display_text = f"{idx + 1:3d}. {filename}"

            self.file_listbox.insert(tk.END, display_text)

    def on_file_select(self, event):
        [i]"""[i]文件选择事件[i]"""
[i]        selection = self.file_listbox.curselection()
        self.selected_label.config(text=f"已选: {len(selection)}")

    def start_detection(self, mode):
        [i]"""[i]开始检测[i]"""
[i]        if not self.eps_files:
            messagebox.showwarning("警告", "没有可检测的文件")
            return

        if self.is_checking:
            messagebox.showinfo("提示", "检测正在进行中")
            return

        self.is_checking = True
        self.results = []
        self.config['detection_mode'] = mode

        # 清空结果区域
        self.result_text.delete(1.0, tk.END)
        self.detail_text.delete(1.0, tk.END)
        self.stats_text.delete(1.0, tk.END)

        # 重置进度
        self.progress_var.set(0)
        self.progress_label.config(text="初始化检测引擎...")

        # 显示开始信息
        self.display_header()

        self.log(f"开始{mode}检测,共{len(self.eps_files)}个文件", "info")

        # 启动检测线程
        thread = threading.Thread(target=self.perform_detection, daemon=True)
        thread.start()

        # 启动UI更新循环
        self.update_detection_progress()

    def display_header(self):
        [i]"""[i]显示检测头部信息[i]"""
[i]        self.result_text.insert(tk.END, "╔══════════════════════════════════════════════════════════════════╗\n")
        self.result_text.insert(tk.END, "║                    EPS文字转曲专业分析工具                      ║\n")
        self.result_text.insert(tk.END, "╠══════════════════════════════════════════════════════════════════╣\n")

        self.result_text.insert(tk.END,
                                f"║  检测模式: {self.config['detection_mode']:<10}   时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S'):<19}  ║\n",
                                "header")
        self.result_text.insert(tk.END,
                                f"║  文件数量: {len(self.eps_files):<5}          Ghostscript: {'可用' if self.config['gs_path'] else '不可用':<10}    ║\n")
        self.result_text.insert(tk.END, "╚══════════════════════════════════════════════════════════════════╝\n")

        self.result_text.insert(tk.END, "\n")

    def perform_detection(self):
        [i]"""[i]执行检测[i]"""
[i]        total = len(self.eps_files)

        for i, eps_file in enumerate(self.eps_files):
            if not self.is_checking:
                break

            try:
                # 更新进度
                progress = (i + 1) / total * 100
                filename = os.path.basename(eps_file)
                self.check_queue.put(('progress', progress, f"检测中: {i + 1}/{total} - {filename}"))

                # 执行检测
                result = self.detect_file(eps_file, self.config['detection_mode'])
                self.results.append(result)

                # 发送结果
                self.check_queue.put(('result', result))

            except Exception as e:
                error_result = {
                    'file': os.path.basename(eps_file),
                    'path': eps_file,
                    'status': '检测失败',
                    'confidence': 0,
                    'analysis': {'error': str(e)}
                }
                self.results.append(error_result)
                self.check_queue.put(('result', error_result))

        self.check_queue.put(('done', None))

    def detect_file(self, file_path, mode):
        [i]"""[i]检测单个文件[i]"""
[i]        filename = os.path.basename(file_path)
        analysis = {
            'basic': {},
            'text_analysis': {},
            'font_analysis': {},
            'vector_analysis': {},
            'gs_analysis': {}
        }

        try:
            # 1. 基础文件分析
            analysis['basic'] = self.analyze_basic_info(file_path)

            # 2. 文件内容读取
            content = self.read_file_content(file_path)
            if not content:
                return {
                    'file': filename,
                    'path': file_path,
                    'status': '读取失败',
                    'confidence': 0,
                    'analysis': analysis
                }

            # 3. 文本分析
            analysis['text_analysis'] = self.analyze_text_content(content)

            # 4. 字体分析
            analysis['font_analysis'] = self.analyze_fonts(content)

            # 5. 矢量分析
            if self.config['analyze_vectors']:
                analysis['vector_analysis'] = self.analyze_vectors(content)

            # 6. Ghostscript分析
            if mode in ['advanced', 'expert'] and self.config['gs_path']:
                analysis['gs_analysis'] = self.analyze_with_ghostscript(file_path)

            # 7. 综合判断
            judgment = self.make_judgment(analysis, mode)

            return {
                'file': filename,
                'path': file_path,
                'status': judgment['status'],
                'confidence': judgment['confidence'],
                'analysis': analysis,
                'judgment': judgment
            }

        except Exception as e:
            return {
                'file': filename,
                'path': file_path,
                'status': '检测失败',
                'confidence': 0,
                'analysis': analysis,
                'error': str(e)
            }

    def analyze_basic_info(self, file_path):
        [i]"""[i]分析基础信息[i]"""
[i]        info = {
            'size': os.path.getsize(file_path),
            'created': datetime.fromtimestamp(os.path.getctime(file_path)).strftime('%Y-%m-%d %H:%M'),
            'modified': datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d %H:%M'),
            'is_eps': False,
            'is_ai': False
        }

        # 检查文件类型
        try:
            with open(file_path, 'rb') as f:
                header = f.read(100).decode('ascii', errors='ignore')

                if '%!PS-Adobe' in header:
                    info['is_eps'] = True
                if '%AI5' in header or '%AI9' in header:
                    info['is_ai'] = True
                    info['ai_version'] = '5' if '%AI5' in header else '9' if '%AI9' in header else 'unknown'
        except:
            pass

        return info

    def read_file_content(self, file_path):
        [i]"""[i]读取文件内容[i]"""
[i]        try:
            # 使用内存映射提高大文件读取性能
            with open(file_path, 'rb') as f:
                # 只读取前1MB内容进行分析
                return f.read(min(1024 * 1024, os.path.getsize(file_path)))
        except:
            return None

    def analyze_text_content(self, content):
        [i]"""[i]分析文本内容[i]"""
[i]        result = {
            'text_objects': [],
            'text_strings': [],
            'has_text': False,
            'score': 0
        }

        try:
            # 转换为文本
            text = content.decode('latin-1', errors='ignore')

            # 文本操作符检测
            text_operators = [
                # 核心文本操作符
                (r'\(([^)]+)\)\s+show', 'show操作符'),
                (r'\(([^)]+)\)\s+Tj', 'Tj操作符'),
                (r'\[([^\]]+)\]\s+TJ', 'TJ操作符'),
                # 十六进制文本
                (r'<([0-9A-F\s]+)>\s+Tj', '十六进制Tj'),
                (r'<([0-9A-F\s]+)>\s+TJ', '十六进制TJ'),
                # 文本状态
                (r'\bBT\b.*?\bET\b', '文本对象块', re.DOTALL),
            ]

            for pattern, description, *flags in text_operators:
                re_flags = re.IGNORECASE
                if flags and flags[0] == re.DOTALL:
                    re_flags |= re.DOTALL

                matches = re.findall(pattern, text, re_flags)
                if matches:
                    count = len(matches)
                    result['text_objects'].append({
                        'type': description,
                        'count': count,
                        'samples': matches[:3]
                    })
                    result['has_text'] = True
                    result['score'] += count * 10

            # 提取文本字符串
            text_strings = re.findall(r'\(([^)]+)\)', text)
            if text_strings:
                # 过滤出有意义的文本
                meaningful_strings = []
                for string in text_strings[:20]:  # 最多处理20个
                    clean_string = string.replace('\\', '').strip()
                    if len(clean_string) > 1 and not clean_string.isdigit():
                        meaningful_strings.append(clean_string[:100])

                result['text_strings'] = meaningful_strings
                if meaningful_strings:
                    result['score'] += len(meaningful_strings) * 5

        except Exception as e:
            result['error'] = str(e)

        return result

    def analyze_fonts(self, content):
        [i]"""[i]分析字体[i]"""
[i]        result = {
            'font_definitions': [],
            'font_references': [],
            'has_fonts': False,
            'score': 0
        }

        try:
            text = content.decode('latin-1', errors='ignore')

            # 字体定义检测
            font_patterns = [
                # 字体资源
                (r'/Font\s*<<', '字体字典'),
                (r'/FontDescriptor\s*<<', '字体描述符'),
                (r'/FontFile\d*\s+\d+\s+\d+\s+R', '字体文件'),
                # 字体名
                (r'/FontName\s+/([^\s]+)', '字体名'),
                (r'/BaseFont\s+/([^\s]+)', '基础字体'),
                # 字体操作
                (r'/([A-Za-z0-9_]+)\s+findfont', '查找字体'),
                (r'/([A-Za-z0-9_]+)\s+setfont', '设置字体'),
                (r'/([A-Za-z0-9_]+)\s+scalefont', '缩放字体'),
                (r'/([A-Za-z0-9_]+)\s+selectfont', '选择字体'),
            ]

            for pattern, description in font_patterns:
                matches = re.findall(pattern, text, re.IGNORECASE)
                if matches:
                    result['font_definitions'].append({
                        'type': description,
                        'count': len(matches),
                        'samples': matches[:3]
                    })
                    result['has_fonts'] = True
                    result['score'] += len(matches) * 15

            # 字体引用检测
            font_refs = re.findall(r'/F(\d+)\s+(\d+)\s+Tf', text, re.IGNORECASE)
            if font_refs:
                result['font_references'] = font_refs[:10]  # 最多10个
                result['score'] += len(font_refs) * 10

        except Exception as e:
            result['error'] = str(e)

        return result

    def analyze_vectors(self, content):
        [i]"""[i]分析矢量路径[i]"""
[i]        result = {
            'path_operators': [],
            'has_vectors': False,
            'score': 0
        }

        try:
            text = content.decode('latin-1', errors='ignore')

            # 矢量路径操作符
            vector_patterns = [
                (r'\bmoveto\b', 'moveto'),
                (r'\blineto\b', 'lineto'),
                (r'\bcurveto\b', 'curveto'),
                (r'\bclosepath\b', 'closepath'),
                (r'\bstroke\b', 'stroke'),
                (r'\bfill\b', 'fill'),
                (r'\beofill\b', 'eofill'),
                (r'\bclip\b', 'clip'),
                (r'\bnewpath\b', 'newpath'),
            ]

            for pattern, name in vector_patterns:
                matches = re.findall(pattern, text, re.IGNORECASE)
                if matches:
                    result['path_operators'].append({
                        'name': name,
                        'count': len(matches)
                    })
                    result['has_vectors'] = True
                    # 路径多不一定代表已转曲,给较低权重
                    result['score'] += len(matches) * 2

        except Exception as e:
            result['error'] = str(e)

        return result

    def analyze_with_ghostscript(self, file_path):
        [i]"""[i]使用[i]Ghostscript[i]分析[i]"""
[i]        if not self.config['gs_path']:
            return {'error': 'Ghostscript未安装'}

        result = {
            'text_detected': False,
            'fonts_detected': False,
            'error': None,
            'score': 0
        }

        try:
            # 方法1: 使用txtwrite提取文本
            text_content = self.gs_extract_text(file_path)
            if text_content and len(text_content) > 20:
                result['text_detected'] = True
                result['score'] += 30

            # 方法2: 使用pdfwrite分析结构
            pdf_analysis = self.gs_analyze_pdf(file_path)
            if 'text_objects' in pdf_analysis and pdf_analysis['text_objects'] > 0:
                result['text_detected'] = True
                result['score'] += 20

            if 'font_objects' in pdf_analysis and pdf_analysis['font_objects'] > 0:
                result['fonts_detected'] = True
                result['score'] += 20

        except Exception as e:
            result['error'] = str(e)

        return result

    def gs_extract_text(self, file_path):
        [i]"""[i]使用[i]GS[i]提取文本[i]"""
[i]        try:
            with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as tmp:
                txt_file = tmp.name

            cmd = [
                self.config['gs_path'],
                '-dNOPAUSE',
                '-dBATCH',
                '-dSAFER',
                '-sDEVICE=txtwrite',
                '-dTextFormat=3',
                '-dFirstPage=1',
                '-dLastPage=1',
                '-c', '300 300 translate',  # 确保文本可读
                '-c', '.setpdfwrite',
                f'-sOutputFile={txt_file}',
                file_path
            ]

            subprocess.run(cmd, capture_output=True, timeout=self.config['timeout'])

            if os.path.exists(txt_file):
                with open(txt_file, 'r', encoding='utf-8', errors='ignore') as f:
                    content = f.read()
                os.unlink(txt_file)

                # 清理文本
                lines = content.split('\n')
                meaningful = []
                skip_patterns = ['GPL Ghostscript', 'Copyright', 'Page', '%%']

                for line in lines:
                    line = line.strip()
                    if not line:
                        continue
                    if not any(pattern in line for pattern in skip_patterns):
                        if len(line) > 2 and not re.match(r'^[\d\s\-\.]+$', line):
                            meaningful.append(line)

                return '\n'.join(meaningful[:10])  # 最多10行

        except Exception as e:
            return None

        return None

    def gs_analyze_pdf(self, file_path):
        [i]"""[i]使用[i]GS[i]分析[i]PDF[i]结构[i]"""
[i]        try:
            cmd = [
                self.config['gs_path'],
                '-dNOPAUSE',
                '-dBATCH',
                '-dSAFER',
                '-sDEVICE=pdfwrite',
                '-dPDFSETTINGS=/prepress',
                '-dCompressPages=false',
                f'-sOutputFile=-',  # 输出到stdout
                file_path
            ]

            process = subprocess.run(cmd, capture_output=True, text=True, timeout=self.config['timeout'])
            output = process.stdout + process.stderr

            # 分析输出
            return {
                'text_objects': output.count('(text)'),
                'font_objects': output.count('/Font'),
                'image_objects': output.count('(image)'),
                'path_objects': output.count('(path)')
            }

        except Exception as e:
            return {'error': str(e)}

    def make_judgment(self, analysis, mode):
        [i]"""[i]做出判断[i]"""
[i]        total_score = 0
        factors = []

        # 1. 文本分析 (40%)
        text_score = analysis['text_analysis'].get('score', 0)
        if text_score > 0:
            factors.append(f"发现文本对象(得分: {text_score})")
        total_score += min(text_score, 40)

        # 2. 字体分析 (30%)
        font_score = analysis['font_analysis'].get('score', 0)
        if font_score > 0:
            factors.append(f"发现字体定义(得分: {font_score})")
        total_score += min(font_score, 30)

        # 3. 矢量分析 (10%)
        vector_score = analysis['vector_analysis'].get('score', 0)
        total_score += min(vector_score, 10)

        # 4. Ghostscript分析 (20%)
        gs_score = analysis['gs_analysis'].get('score', 0)
        if gs_score > 0:
            gs_text = analysis['gs_analysis'].get('text_detected', False)
            gs_fonts = analysis['gs_analysis'].get('fonts_detected', False)
            if gs_text:
                factors.append("GS检测到文本")
            if gs_fonts:
                factors.append("GS检测到字体")
        total_score += min(gs_score, 20)

        # 根据模式调整阈值
        if mode == 'basic':
            threshold = 30
            max_threshold = 60
        elif mode == 'advanced':
            threshold = 40
            max_threshold = 70
        else:  # expert
            threshold = 50
            max_threshold = 80

        # 判断结果
        if total_score >= threshold:
            status = "未转曲"
            confidence = min(95, (total_score - threshold) / (max_threshold - threshold) * 100)
        elif total_score >= threshold * 0.5:
            status = "疑似未转曲"
            confidence = total_score
        else:
            status = "已转曲"
            confidence = 100 - total_score

        return {
            'status': status,
            'confidence': int(confidence),
            'score': int(total_score),
            'factors': factors
        }

    def update_detection_progress(self):
        [i]"""[i]更新检测进度[i]"""
[i]        try:
            while True:
                try:
                    item_type, *data = self.check_queue.get_nowait()

                    if item_type == 'progress':
                        progress, message = data
                        self.progress_var.set(progress)
                        self.progress_label.config(text=message)
                        self.status_bar.config(text=message)

                    elif item_type == 'result':
                        result = data[0]
                        self.display_result(result)

                    elif item_type == 'done':
                        self.is_checking = False
                        self.progress_var.set(100)
                        self.progress_label.config(text="检测完成")
                        self.display_statistics()
                        self.status_bar.config(text="检测完成")
                        break

                except queue.Empty:
                    if not self.is_checking:
                        break
                    self.root.after(100, self.update_detection_progress)
                    break

        except Exception as e:
            self.log(f"进度更新错误: {str(e)}", "error")

    def display_result(self, result):
        [i]"""[i]显示单个结果[i]"""
[i]        # 状态颜色映射
        status_colors = {
            '未转曲': 'unconverted',
            '已转曲': 'converted',
            '疑似未转曲': 'warning',
            '检测失败': 'error',
            '读取失败': 'error'
        }

        color_tag = status_colors.get(result['status'], 'info')

        # 在主结果中显示
        self.result_text.insert(tk.END, f"📄 {result['file']}\n", "bold")

        # 状态指示器
        if result['status'] == '未转曲':
            indicator = "🔴"
        elif result['status'] == '已转曲':
            indicator = "🟢"
        elif result['status'] == '疑似未转曲':
            indicator = "🟡"
        else:
            indicator = "⚪"

        self.result_text.insert(tk.END, f"   {indicator} 状态: ")
        self.result_text.insert(tk.END, f"{result['status']}\n", color_tag)
        self.result_text.insert(tk.END, f"   📊 置信度: {result['confidence']}%\n")

        if 'judgment' in result and result['judgment']['factors']:
            self.result_text.insert(tk.END, f"   📋 检测因素:\n")
            for factor in result['judgment']['factors'][:3]:
                self.result_text.insert(tk.END, f"      • {factor}\n")

        # 提取的文本样本
        if 'analysis' in result and result['analysis']['text_analysis'].get('text_strings'):
            strings = result['analysis']['text_analysis']['text_strings']
            if strings:
                self.result_text.insert(tk.END, f"   📝 发现文本: {strings[0][:50]}")
                if len(strings) > 1:
                    self.result_text.insert(tk.END, f" 等{len(strings)}处")
                self.result_text.insert(tk.END, "\n")

        self.result_text.insert(tk.END, "-" * 70 + "\n\n")

        # 在详细分析中显示
        self.display_detailed_analysis(result)

        # 滚动到底部
        self.result_text.see(tk.END)
        self.detail_text.see(tk.END)

    def display_detailed_analysis(self, result):
        [i]"""[i]显示详细分析[i]"""
[i]        self.detail_text.insert(tk.END, f"文件分析: {result['file']}\n", "header")
        self.detail_text.insert(tk.END, f"路径: {result['path']}\n", "filepath")
        self.detail_text.insert(tk.END, f"检测状态: {result['status']} (置信度: {result['confidence']}%)\n\n")

        analysis = result.get('analysis', {})

        # 基础信息
        if 'basic' in analysis:
            basic = analysis['basic']
            self.detail_text.insert(tk.END, "📁 基础信息\n", "subheader")
            self.detail_text.insert(tk.END, f"  文件大小: {basic.get('size', 0):,} bytes\n")
            if basic.get('is_eps'):
                self.detail_text.insert(tk.END, "  文件类型: EPS\n")
            if basic.get('is_ai'):
                self.detail_text.insert(tk.END, f"  AI版本: {basic.get('ai_version', 'unknown')}\n")
            self.detail_text.insert(tk.END, f"  修改时间: {basic.get('modified', 'unknown')}\n")
            self.detail_text.insert(tk.END, "\n")

        # 文本分析
        if 'text_analysis' in analysis:
            text = analysis['text_analysis']
            self.detail_text.insert(tk.END, "📝 文本分析\n", "subheader")
            self.detail_text.insert(tk.END, f"  发现文本: {'是' if text.get('has_text') else '否'}\n")
            self.detail_text.insert(tk.END, f"  文本得分: {text.get('score', 0)}\n")

            if text.get('text_objects'):
                self.detail_text.insert(tk.END, "  文本操作符:\n")
                for obj in text['text_objects'][:5]:
                    self.detail_text.insert(tk.END, f"    • {obj['type']}: {obj['count']}次\n")

            if text.get('text_strings'):
                self.detail_text.insert(tk.END, f"  文本字符串: {len(text['text_strings'])}个\n")
                for string in text['text_strings'][:3]:
                    self.detail_text.insert(tk.END, f"    • {string[:50]}\n")

            self.detail_text.insert(tk.END, "\n")

        # 字体分析
        if 'font_analysis' in analysis:
            fonts = analysis['font_analysis']
            self.detail_text.insert(tk.END, "🔤 字体分析\n", "subheader")
            self.detail_text.insert(tk.END, f"  发现字体: {'是' if fonts.get('has_fonts') else '否'}\n")
            self.detail_text.insert(tk.END, f"  字体得分: {fonts.get('score', 0)}\n")

            if fonts.get('font_definitions'):
                self.detail_text.insert(tk.END, "  字体定义:\n")
                for font in fonts['font_definitions'][:5]:
                    self.detail_text.insert(tk.END, f"    • {font['type']}: {font['count']}个\n")

            if fonts.get('font_references'):
                self.detail_text.insert(tk.END, f"  字体引用: {len(fonts['font_references'])}个\n")

            self.detail_text.insert(tk.END, "\n")

        # Ghostscript分析
        if 'gs_analysis' in analysis:
            gs = analysis['gs_analysis']
            self.detail_text.insert(tk.END, "🔍 Ghostscript分析\n", "subheader")

            if 'error' in gs:
                self.detail_text.insert(tk.END, f"  错误: {gs['error']}\n", "error")
            else:
                self.detail_text.insert(tk.END, f"  检测到文本: {'是' if gs.get('text_detected') else '否'}\n")
                self.detail_text.insert(tk.END, f"  检测到字体: {'是' if gs.get('fonts_detected') else '否'}\n")
                self.detail_text.insert(tk.END, f"  GS得分: {gs.get('score', 0)}\n")

            self.detail_text.insert(tk.END, "\n")

        self.detail_text.insert(tk.END, "═" * 70 + "\n\n")

    def display_statistics(self):
        [i]"""[i]显示统计信息[i]"""
[i]        if not self.results:
            return

        # 计算统计
        total = len(self.results)
        status_counts = {}
        confidence_sum = 0

        for result in self.results:
            status = result['status']
            status_counts[status] = status_counts.get(status, 0) + 1
            confidence_sum += result.get('confidence', 0)

        avg_confidence = confidence_sum / total if total > 0 else 0

        # 显示统计
        self.stats_text.insert(tk.END, "📈 检测统计报告\n", "header")
        self.stats_text.insert(tk.END, "═" * 70 + "\n\n")

        self.stats_text.insert(tk.END, f"📅 检测时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        self.stats_text.insert(tk.END, f"🎯 检测模式: {self.config['detection_mode']}\n")
        self.stats_text.insert(tk.END, f"📁 总文件数: {total}\n")
        self.stats_text.insert(tk.END, f"📊 平均置信度: {avg_confidence:.1f}%\n")
        self.stats_text.insert(tk.END, f"👻 Ghostscript: {'已使用' if self.config['gs_path'] else '未使用'}\n\n")

        self.stats_text.insert(tk.END, "📊 状态分布\n", "subheader")

        # 饼图数据准备
        status_order = ['未转曲', '已转曲', '疑似未转曲', '检测失败', '读取失败']
        status_data = []

        for status in status_order:
            count = status_counts.get(status, 0)
            if count > 0:
                percentage = (count / total) * 100
                color_tag = 'unconverted' if status == '未转曲' else 'converted' if status == '已转曲' else 'warning' if status == '疑似未转曲' else 'error'

                self.stats_text.insert(tk.END, f"  {status}: ", "bold")
                self.stats_text.insert(tk.END, f"{count}个 ({percentage:.1f}%)\n", color_tag)
                status_data.append((status, count, percentage))

        # 显示详细信息
        self.stats_text.insert(tk.END, "\n📋 详细统计\n", "subheader")

        # 按置信度排序
        sorted_results = sorted(self.results, key=lambda x: x.get('confidence', 0), reverse=True)

        for result in sorted_results[:20]:  # 显示前20个
            status = result['status']
            color_tag = 'unconverted' if status == '未转曲' else 'converted' if status == '已转曲' else 'warning' if status == '疑似未转曲' else 'error'

            self.stats_text.insert(tk.END, f"  {result['file']}: ", color_tag)
            self.stats_text.insert(tk.END, f"{status} ({result.get('confidence', 0)}%)\n")

        if len(sorted_results) > 20:
            self.stats_text.insert(tk.END, f"  ... 还有 {len(sorted_results) - 20} 个文件\n")

        self.log(f"检测完成,共检测 {total} 个文件", "success")

    def stop_detection(self):
        [i]"""[i]停止检测[i]"""
[i]        if self.is_checking:
            self.is_checking = False
            self.progress_label.config(text="检测已停止")
            self.status_bar.config(text="检测已停止")
            self.log("检测已停止", "warning")

    def export_report(self):
        [i]"""[i]导出报告[i]"""
[i]        if not self.results:
            messagebox.showwarning("警告", "没有检测结果可导出")
            return

        file_path = filedialog.asksaveasfilename(
            title="保存检测报告",
            defaultextension=".html",
            filetypes=[
                ("HTML报告", "*.html"),
                ("文本报告", "*.txt"),
                ("CSV报告", "*.csv"),
                ("所有文件", "*.*")
            ]
        )

        if not file_path:
            return

        try:
            if file_path.lower().endswith('.html'):
                self.export_html_report(file_path)
            elif file_path.lower().endswith('.csv'):
                self.export_csv_report(file_path)
            else:
                self.export_text_report(file_path)

            self.log(f"报告已导出: {file_path}", "success")
            messagebox.showinfo("成功", f"报告已保存到:\n{file_path}")

            # 尝试打开文件
            try:
                if os.name == 'nt':
                    os.startfile(file_path)
                elif os.name == 'posix':
                    subprocess.run(['open' if sys.platform == 'darwin' else 'xdg-open', file_path])
            except:
                pass

        except Exception as e:
            self.log(f"导出报告失败: {str(e)}", "error")
            messagebox.showerror("错误", f"导出报告失败:\n{str(e)}")

    def export_html_report(self, file_path):
        [i]"""[i]导出[i]HTML[i]报告[i]"""
[i]        # 计算统计
        status_counts = {}
        for result in self.results:
            status = result['status']
            status_counts[status] = status_counts.get(status, 0) + 1

        html = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EPS文字转曲检测报告</title>
    <style>
        body {{
            font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif;
            margin: 40px;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }}
        h1 {{
            color: #2c3e50;
            text-align: center;
            margin-bottom: 30px;
            font-size: 2.5em;
            background: linear-gradient(90deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }}
        .summary {{
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 25px;
            border-radius: 15px;
            margin-bottom: 30px;
        }}
        .stats-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }}
        .stat-card {{
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }}
        .stat-card:hover {{
            transform: translateY(-5px);
        }}
        .stat-value {{
            font-size: 2em;
            font-weight: bold;
            margin: 10px 0;
        }}
        .unconverted {{ color: #e74c3c; }}
        .converted {{ color: #27ae60; }}
        .warning {{ color: #f39c12; }}
        .results-table {{
            width: 100%;
            border-collapse: collapse;
            margin: 30px 0;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }}
        .results-table th, .results-table td {{
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }}
        .results-table th {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: bold;
        }}
        .status-badge {{
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: bold;
        }}
        .badge-unconverted {{ background: #ffebee; color: #e74c3c; }}
        .badge-converted {{ background: #e8f5e9; color: #27ae60; }}
        .badge-warning {{ background: #fff3e0; color: #f39c12; }}
        .footer {{
            text-align: center;
            margin-top: 40px;
            color: #7f8c8d;
            font-size: 0.9em;
        }}
        @media print {{
            body {{ background: white !important; }}
            .container {{ box-shadow: none !important; }}
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>📊 EPS文字转曲检测报告</h1>

        <div class="summary">
            <p><strong>生成时间:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
            <p><strong>检测模式:</strong> {self.config['detection_mode']}</p>
            <p><strong>总文件数:</strong> {len(self.results)}</p>
            <p><strong>检测工具:</strong> EPS文字转曲专业分析工具</p>
        </div>

        <div class="stats-grid">
            <div class="stat-card">
                <div>总文件数</div>
                <div class="stat-value">{len(self.results)}</div>
            </div>
'''

        for status, count in status_counts.items():
            color_class = 'unconverted' if status == '未转曲' else 'converted' if status == '已转曲' else 'warning'
            percentage = (count / len(self.results)) * 100

            html += f'''
            <div class="stat-card">
                <div>{status}</div>
                <div class="stat-value {color_class}">{count}</div>
                <div>({percentage:.1f}%)</div>
            </div>
'''

        html += '''
        </div>

        <h2>📋 详细检测结果</h2>
        <table class="results-table">
            <thead>
                <tr>
                    <th>文件名</th>
                    <th>状态</th>
                    <th>置信度</th>
                    <th>文件路径</th>
                </tr>
            </thead>
            <tbody>
'''

        for result in self.results:
            badge_class = 'badge-unconverted' if result['status'] == '未转曲' else 'badge-converted' if result[
                                                                                                            'status'] == '已转曲' else 'badge-warning'

            html += f'''
                <tr>
                    <td>{result['file']}</td>
                    <td><span class="status-badge {badge_class}">{result['status']}</span></td>
                    <td>{result.get('confidence', 0)}%</td>
                    <td style="font-size: 0.9em; color: #666;">{result['path']}</td>
                </tr>
'''

        html += '''
            </tbody>
        </table>

        <div class="footer">
            <p>📧 本报告由 EPS文字转曲专业分析工具 生成</p>
            <p>⏰ 报告生成时间: ''' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '''</p>
        </div>
    </div>
</body>
</html>'''

        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(html)

    def export_text_report(self, file_path):
        [i]"""[i]导出文本报告[i]"""
[i]        with open(file_path, 'w', encoding='utf-8') as f:
            f.write("=" * 80 + "\n")
            f.write("EPS文字转曲专业检测报告\n")
            f.write("=" * 80 + "\n\n")

            f.write(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"检测模式: {self.config['detection_mode']}\n")
            f.write(f"总文件数: {len(self.results)}\n")
            f.write(f"Ghostscript: {'已使用' if self.config['gs_path'] else '未使用'}\n\n")

            # 统计信息
            status_counts = {}
            for result in self.results:
                status = result['status']
                status_counts[status] = status_counts.get(status, 0) + 1

            f.write("统计信息:\n")
            f.write("-" * 40 + "\n")
            for status in ['未转曲', '已转曲', '疑似未转曲', '检测失败']:
                count = status_counts.get(status, 0)
                if count > 0:
                    percentage = (count / len(self.results)) * 100
                    f.write(f"{status}: {count}个 ({percentage:.1f}%)\n")
            f.write("\n")

            # 详细结果
            f.write("详细检测结果:\n")
            f.write("=" * 80 + "\n")

            for result in self.results:
                f.write(f"\n文件名: {result['file']}\n")
                f.write(f"状态: {result['status']}\n")
                f.write(f"置信度: {result.get('confidence', 0)}%\n")
                f.write(f"路径: {result['path']}\n")

                if 'judgment' in result and result['judgment']['factors']:
                    f.write("检测因素:\n")
                    for factor in result['judgment']['factors']:
                        f.write(f"  • {factor}\n")

                f.write("-" * 60 + "\n")

    def export_csv_report(self, file_path):
        [i]"""[i]导出[i]CSV[i]报告[i]"""
[i]        import csv

        with open(file_path, 'w', encoding='utf-8', newline='') as f:
            writer = csv.writer(f)

            # 写入标题
            writer.writerow(['文件名', '状态', '置信度%', '文件路径', '检测时间'])

            # 写入数据
            for result in self.results:
                writer.writerow([
                    result['file'],
                    result['status'],
                    result.get('confidence', 0),
                    result['path'],
                    datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                ])

    def clear_results(self):
        [i]"""[i]清空结果[i]"""
[i]        if self.is_checking:
            messagebox.showwarning("警告", "请先停止检测")
            return

        if messagebox.askyesno("确认", "确定要清空所有结果吗?"):
            self.results = []
            self.result_text.delete(1.0, tk.END)
            self.detail_text.delete(1.0, tk.END)
            self.stats_text.delete(1.0, tk.END)
            self.progress_var.set(0)
            self.progress_label.config(text="就绪")
            self.status_bar.config(text="已清空结果")
            self.log("已清空所有结果", "info")

    def open_settings(self):
        [i]"""[i]打开设置[i]"""
[i]        settings_window = tk.Toplevel(self.root)
        settings_window.title("检测设置")
        settings_window.geometry("500x400")
        settings_window.transient(self.root)
        settings_window.grab_set()

        # 设置标题
        title_frame = ttk.Frame(settings_window)
        title_frame.pack(fill=tk.X, pady=(20, 10))

        ttk.Label(title_frame, text="🔧 检测设置",
                  font=('Arial', 14, 'bold')).pack()

        # Ghostscript设置
        gs_frame = ttk.LabelFrame(settings_window, text="Ghostscript设置", padding=15)
        gs_frame.pack(fill=tk.X, padx=20, pady=10)

        gs_var = tk.StringVar(value=self.config['gs_path'] or "")
        ttk.Entry(gs_frame, textvariable=gs_var, width=50).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))

        def browse_gs():
            file_path = filedialog.askopenfilename(
                title="选择Ghostscript可执行文件",
                filetypes=[("可执行文件", "*.exe"), ("所有文件", "*.*")]
            )
            if file_path:
                gs_var.set(file_path)

        ttk.Button(gs_frame, text="浏览", command=browse_gs, width=10).pack(side=tk.RIGHT)

        # 检测模式设置
        mode_frame = ttk.LabelFrame(settings_window, text="检测模式", padding=15)
        mode_frame.pack(fill=tk.X, padx=20, pady=10)

        self.mode_var = tk.StringVar(value=self.config['detection_mode'])

        modes = [
            ("基础模式 (快速检测,适合初步检查)", 'basic'),
            ("高级模式 (综合检测,推荐使用)", 'advanced'),
            ("专家模式 (深度分析,最准确)", 'expert')
        ]

        for text, value in modes:
            ttk.Radiobutton(mode_frame, text=text, variable=self.mode_var,
                            value=value).pack(anchor=tk.W, pady=2)

        # 其他设置
        other_frame = ttk.LabelFrame(settings_window, text="其他设置", padding=15)
        other_frame.pack(fill=tk.X, padx=20, pady=10)

        self.analyze_vectors_var = tk.BooleanVar(value=self.config['analyze_vectors'])
        ttk.Checkbutton(other_frame, text="分析矢量路径",
                        variable=self.analyze_vectors_var).pack(anchor=tk.W)

        timeout_frame = ttk.Frame(other_frame)
        timeout_frame.pack(fill=tk.X, pady=5)
        ttk.Label(timeout_frame, text="检测超时:").pack(side=tk.LEFT)
        self.timeout_var = tk.StringVar(value=str(self.config['timeout']))
        ttk.Entry(timeout_frame, textvariable=self.timeout_var, width=10).pack(side=tk.LEFT, padx=5)
        ttk.Label(timeout_frame, text="秒").pack(side=tk.LEFT)

        def save_settings():
            # 更新配置
            new_gs_path = gs_var.get()
            if new_gs_path and os.path.exists(new_gs_path):
                self.config['gs_path'] = new_gs_path
                self.gs_status_label.config(text="✓ GS已安装", foreground="#27ae60")

            self.config['detection_mode'] = self.mode_var.get()
            self.config['analyze_vectors'] = self.analyze_vectors_var.get()

            try:
                self.config['timeout'] = int(self.timeout_var.get())
            except:
                self.config['timeout'] = 30

            self.log("检测设置已更新", "success")
            settings_window.destroy()

        # 保存按钮
        ttk.Button(settings_window, text="💾 保存设置",
                   command=save_settings).pack(pady=20)

    def log(self, message, tag="info"):
        [i]"""[i]记录日志[i]"""
[i]        self.status_bar.config(text=message)
        print(f"[{datetime.now().strftime('%H:%M:%S')}] {message}")

def main():
    root = tk.Tk()

    # 设置窗口图标和样式
    try:
        if os.name == 'nt':
            root.iconbitmap(default='icon.ico')
    except:
        pass

    # 设置窗口最小尺寸
    root.minsize(1000, 700)

    # 创建应用
    app = EPSConverterDetector(root)
    root.mainloop()

if __name__ == "__main__":
    main()

免费评分

参与人数 2吾爱币 +2 热心值 +1 收起 理由
燕丹 + 1 我很赞同!
cjcmxc + 1 + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

头像被屏蔽
5209520 发表于 2026-1-17 23:57
提示: 该帖被管理员或版主屏蔽
 楼主| 52pjXXB0614 发表于 2026-1-18 10:39
5209520 发表于 2026-1-17 23:57
# -*- coding: utf-8 -*-
"""
EPS文字转曲专业分析工具 - 修正增强版

这个导出还是不准确,转曲的,检测结果是未转曲

这个导出还是不准确,转曲的,检测结果是未转曲

这个导出还是不准确,转曲过的图片的,检测结果是未转曲


这个地方设置的是什么辅助程序吗

这个地方设置的是什么辅助程序吗

这个地方设置的是什么辅助程序吗
xinchenmetx 发表于 2026-1-18 10:40
本帖最后由 xinchenmetx 于 2026-1-18 10:43 编辑

[Python] 纯文本查看 复制代码
def make_judgment(self, analysis, mode):
    """
    综合判断 EPS 文件是否已转曲
    """
    text_score = analysis['text_analysis'].get('score', 0)
    font_score = analysis['font_analysis'].get('score', 0)
    vector_score = analysis['vector_analysis'].get('score', 0)
    gs_score = analysis['gs_analysis'].get('score', 0)

    # 判定逻辑
    if text_score > 0 and font_score > 0:
        status = "未转曲"
        confidence = 90
    elif text_score == 0 and font_score == 0 and vector_score > 40:
        status = "已转曲"
        confidence = 85
    elif gs_score > 20 and text_score > 0:
        status = "未转曲"
        confidence = 80
    elif gs_score == 0 and vector_score > 30:
        status = "已转曲"
        confidence = 75
    else:
        status = "不确定"
        confidence = 50

    # 专家模式提高置信度
    if mode == "expert":
        confidence = min(100, confidence + 5)

    return {
        'status': status,
        'confidence': confidence
    }
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-2-20 15:40

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表