Spaces:
Sleeping
Sleeping
Update app.py
Browse files112345567899101112121314151617181920212219232425262728293031252627282932333435363738394041424344454647481 unmodified line5051525354554256575859606162636465666768697071724673747576777851798081828384855455565786878889909192939495969798991001016110210310410510610710810911011163112113114651151161171181191206712112212312412512670127128129130131747513213313413513613713813914014114214314414514614714877787980149150151152153154155821561578485868788899091158159939495160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229979899100230231232233234235236# --- 完整且修正過的 app.py ---# --- 完整且修正過的 app.py (Gradio Blocks 版本) ---
import gradio as grimport subprocessimport os # 確保 os 模組已被匯入import osimport pikepdffrom collections import defaultdict
# --- 色彩偵測功能 (保持不變) ---# --- 色彩偵測功能 ---
def get_color_spaces_from_resource(resource_dict, found_spaces): """從 PDF 資源字典中提取色彩空間資訊""" if not resource_dict: return if not resource_dict: return # 檢查 ColorSpace if '/ColorSpace' in resource_dict: cs_dict = resource_dict['/ColorSpace'] for key in cs_dict: try: if isinstance(cs_dict[key], pikepdf.Array): found_spaces.add(str(cs_dict[key][0])) except Exception: pass except Exception: pass # 檢查 XObject (圖像) if '/XObject' in resource_dict: xobj_dict = resource_dict['/XObject'] for key in xobj_dict: try: xobj = xobj_dict[key] if isinstance(xobj, pikepdf.Stream) and xobj.get('/Subtype') == '/Image' and '/ColorSpace' in xobj: cs = xobj['/ColorSpace'] if isinstance(cs, pikepdf.Name): found_spaces.add(str(cs)) elif isinstance(cs, pikepdf.Array): found_spaces.add(str(cs[0])) except Exception: pass if isinstance(xobj, pikepdf.Stream) and xobj.get('/Subtype') == '/Image': if '/ColorSpace' in xobj: cs = xobj['/ColorSpace'] if isinstance(cs, pikepdf.Name): found_spaces.add(str(cs)) elif isinstance(cs, pikepdf.Array): found_spaces.add(str(cs[0])) except Exception: pass
def detect_pdf_color_modes(pdf_path): """偵測 PDF 檔案中使用的色彩空間""" found_spaces = set() try: with pikepdf.Pdf.open(pdf_path) as pdf: for page in pdf.pages:1 unmodified line get_color_spaces_from_resource(page['/Resources'], found_spaces) except Exception as e: return f"無法分析 PDF 檔案:{str(e)}" if not found_spaces: return "未偵測到明確的色彩空間資訊 (可能是純黑白文字)。" friendly_names = {'/DeviceRGB': 'RGB', '/CalRGB': 'RGB (校準)', '/DeviceCMYK': 'CMYK', '/CalCMYK': 'CMYK (校準)', '/DeviceGray': '灰階', '/CalGray': '灰階 (校準)', '/Separation': '特別色', '/Indexed': '索引色', '/ICCBased': 'ICC Profile'} # 友善的色彩空間名稱對應 friendly_names = { '/DeviceRGB': 'RGB', '/CalRGB': 'RGB (校準)', '/DeviceCMYK': 'CMYK', '/CalCMYK': 'CMYK (校準)', '/DeviceGray': '灰階', '/CalGray': '灰階 (校準)', '/Separation': '特別色', '/Indexed': '索引色', '/ICCBased': 'ICC Profile' } detected_modes = {friendly_names.get(s, s) for s in found_spaces} return f"偵測到的色彩空間: {', '.join(sorted(list(detected_modes)))}"
# --- 更新後的轉換功能 (保持不變) ---# --- CMYK 轉換功能 ---
def convert_pdf_to_cmyk_profiled(input_path): """使用 Ghostscript 和 Japan Color 2001 Coated Profile 轉換 PDF 為 CMYK""" GS_EXECUTABLE = "gs" SETTINGS_FILE = "/app/cmyk_settings.ps" output_file = f"/tmp/{os.path.basename(os.path.splitext(input_path)[0])}_cmyk_jp2001.pdf" # 生成輸出檔名 base_name = os.path.basename(os.path.splitext(input_path)[0]) output_file = f"/tmp/{base_name}_cmyk_jp2001.pdf" # Ghostscript 命令 command = [ GS_EXECUTABLE, "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dNOCACHE", "-sDEVICE=pdfwrite", "-sProcessColorModel=DeviceCMYK", "-sColorConversionStrategy=CMYK", "-sOutputICCProfile=/usr/share/color/icc/JapanColor2001Coated.icc", f"-sOutputFile={output_file}", SETTINGS_FILE, "-f", input_path GS_EXECUTABLE, "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dNOCACHE", "-sDEVICE=pdfwrite", "-sProcessColorModel=DeviceCMYK", "-sColorConversionStrategy=CMYK", "-sOutputICCProfile=/usr/share/color/icc/JapanColor2001Coated.icc", f"-sOutputFile={output_file}", SETTINGS_FILE, "-f", input_path ] try: subprocess.run(command, check=True, capture_output=True, text=True) result = subprocess.run( command, check=True, capture_output=True, text=True, timeout=60 # 60 秒超時 ) # 檢查輸出檔案 if os.path.exists(output_file) and os.path.getsize(output_file) > 0: return output_file, f"轉換成功 (Japan Color 2001 Coated)!\n檔案大小: {round(os.path.getsize(output_file) / 1024, 2)} KB" file_size_kb = round(os.path.getsize(output_file) / 1024, 2) return output_file, f"✅ 轉換成功 (Japan Color 2001 Coated)!\n📦 檔案大小: {file_size_kb} KB" else: return None, "轉換失敗:輸出的 CMYK 檔案不存在或為空。" return None, "❌ 轉換失敗:輸出的 CMYK 檔案不存在或為空。" except subprocess.TimeoutExpired: return None, "❌ 轉換超時:處理時間超過 60 秒,請嘗試較小的檔案。" except subprocess.CalledProcessError as e: error_msg = f"轉換過程中 Ghostscript 發生錯誤。\n錯誤訊息: {e.stderr}" error_msg = f"❌ 轉換過程中 Ghostscript 發生錯誤。\n\n錯誤訊息:\n{e.stderr}" return None, error_msg except Exception as e: return None, f"❌ 發生未預期的錯誤:{str(e)}"
# --- 整合後的主要處理函數 (保持不變) ---# --- 主要處理函數 ---
def analyze_and_convert(input_file): """分析並轉換 PDF 檔案""" if input_file is None: # 這是因為上傳失敗時會發生的情況 return "錯誤:檔案上傳失敗,請刷新頁面再試一次。", None, "上傳通訊被瀏覽器阻擋。" return ( "⚠️ 錯誤:未選擇檔案,請上傳 PDF 檔案。", None, "" ) try: input_path = input_file.name if hasattr(input_file, 'name') else input_file # 步驟 1: 偵測色彩模式 detection_result = detect_pdf_color_modes(input_path) # 步驟 2: 轉換為 CMYK output_path, conversion_message = convert_pdf_to_cmyk_profiled(input_path) return detection_result, output_path, conversion_message input_path = input_file detection_result = detect_pdf_color_modes(input_path) output_path, conversion_message = convert_pdf_to_cmyk_profiled(input_path) return detection_result, output_path, conversion_message except Exception as e: return ( f"❌ 處理檔案時發生錯誤:{str(e)}", None, "處理失敗" )
# --- Gradio 介面設定 (保持不變) ---# --- Gradio Blocks 介面 ---
iface = gr.Interface( fn=analyze_and_convert, inputs=gr.File(label="上傳您的 PDF 檔案", file_types=[".pdf"]), outputs=[ gr.Textbox(label="色彩模式分析結果"), gr.File(label="下載轉換後的 CMYK PDF", file_types=[".pdf"]), gr.Textbox(label="轉換處理訊息") ],with gr.Blocks( title="PDF 精準色彩轉換工具 (RGB → CMYK)", description="上傳 PDF 檔案,工具會分析其色彩空間,並使用 **Japan Color 2001 Coated** Profile 將其精準轉換為印刷用 CMYK。", flagging_mode="never" # 使用新的 flagging_mode 參數) theme=gr.themes.Soft()) as iface: gr.Markdown( """ # 🎨 PDF 精準色彩轉換工具 (RGB → CMYK) 上傳 PDF 檔案,工具會自動: 1. 分析檔案中的色彩空間 2. 使用 **Japan Color 2001 Coated** ICC Profile 轉換為印刷用 CMYK 適用於印刷前置作業,確保色彩輸出準確。 """ ) with gr.Row(): with gr.Column(scale=1): input_file = gr.File( label="📄 上傳 PDF 檔案", file_types=[".pdf"], file_count="single" ) with gr.Row(): submit_btn = gr.Button("🚀 開始轉換", variant="primary", size="lg") clear_btn = gr.Button("🗑️ 清除", size="lg") with gr.Column(scale=1): detection_output = gr.Textbox( label="🔍 色彩模式分析結果", lines=3, interactive=False ) conversion_output = gr.Textbox( label="⚙️ 轉換處理訊息", lines=3, interactive=False ) download_output = gr.File( label="⬇️ 下載轉換後的 CMYK PDF", interactive=False ) gr.Markdown( """ --- ### 📋 使用說明 - 支援格式:PDF - 檔案大小:建議 < 50 MB - 轉換時間:視檔案大小而定,通常 10-30 秒 - ICC Profile:Japan Color 2001 Coated (日本印刷標準) """ ) # 事件處理 submit_btn.click( fn=analyze_and_convert, inputs=input_file, outputs=[detection_output, download_output, conversion_output] ) clear_btn.click( fn=lambda: (None, None, None, None), outputs=[input_file, detection_output, download_output, conversion_output] )
# --- 啟動應用 ---
# --- 啟動 Gradio 的關鍵修正 ---# 使用 Hugging Face 提供的環境變數來設定正確的根路徑# 這可以解決 HTTPS 反向代理下的混合內容 (Mixed Content) 錯誤iface.launch(root_path=os.environ.get('GRADIO_ROOT_PATH_PREFIX'))if __name__ == "__main__": iface.launch( server_name="0.0.0.0", server_port=7860, root_path=os.environ.get('GRADIO_ROOT_PATH_PREFIX', ''), show_error=True )app.py+180-44