Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334351 unmodified line373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100# --- 完整且修正過的 app.py ---import gradio as grimport subprocessimport os # 確保 os 模組已被匯入import pikepdffrom collections import defaultdict# --- 色彩偵測功能 (保持不變) ---def get_color_spaces_from_resource(resource_dict, found_spaces):if not resource_dict: returnif '/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: passif '/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: passdef detect_pdf_color_modes(pdf_path):found_spaces = set()try:with pikepdf.Pdf.open(pdf_path) as pdf:for page in pdf.pages:1 unmodified lineget_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'}detected_modes = {friendly_names.get(s, s) for s in found_spaces}return f"偵測到的色彩空間: {', '.join(sorted(list(detected_modes)))}"# --- 更新後的轉換功能 (保持不變) ---def convert_pdf_to_cmyk_profiled(input_path):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"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]try:subprocess.run(command, check=True, capture_output=True, text=True)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"else:return None, "轉換失敗:輸出的 CMYK 檔案不存在或為空。"except subprocess.CalledProcessError as e:error_msg = f"轉換過程中 Ghostscript 發生錯誤。\n錯誤訊息: {e.stderr}"return None, error_msg# --- 整合後的主要處理函數 (保持不變) ---def analyze_and_convert(input_file):if input_file is None:# 這是因為上傳失敗時會發生的情況return "錯誤:檔案上傳失敗,請刷新頁面再試一次。", None, "上傳通訊被瀏覽器阻擋。"input_path = input_filedetection_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# --- Gradio 介面設定 (保持不變) ---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="轉換處理訊息")],title="PDF 精準色彩轉換工具 (RGB → CMYK)",description="上傳 PDF 檔案,工具會分析其色彩空間,並使用 **Japan Color 2001 Coated** Profile 將其精準轉換為印刷用 CMYK。",flagging_mode="never" # 使用新的 flagging_mode 參數)# --- 啟動 Gradio 的關鍵修正 ---# 使用 Hugging Face 提供的環境變數來設定正確的根路徑# 這可以解決 HTTPS 反向代理下的混合內容 (Mixed Content) 錯誤iface.launch(root_path=os.environ.get('GRADIO_ROOT_PATH_PREFIX'))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647481 unmodified line5051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236# --- 完整且修正過的 app.py (Gradio Blocks 版本) ---import gradio as grimport subprocessimport osimport pikepdffrom collections import defaultdict# --- 色彩偵測功能 ---def get_color_spaces_from_resource(resource_dict, found_spaces):"""從 PDF 資源字典中提取色彩空間資訊"""if not resource_dict:return# 檢查 ColorSpaceif '/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# 檢查 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':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:passdef 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 lineget_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'}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"# 生成輸出檔名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]try: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: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 檔案不存在或為空。"except subprocess.TimeoutExpired:return None, "❌ 轉換超時:處理時間超過 60 秒,請嘗試較小的檔案。"except subprocess.CalledProcessError as e:error_msg = f"❌ 轉換過程中 Ghostscript 發生錯誤。\n\n錯誤訊息:\n{e.stderr}"return None, error_msgexcept Exception as e:return None, f"❌ 發生未預期的錯誤:{str(e)}"# --- 主要處理函數 ---def analyze_and_convert(input_file):"""分析並轉換 PDF 檔案"""if input_file is 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: 轉換為 CMYKoutput_path, conversion_message = convert_pdf_to_cmyk_profiled(input_path)return detection_result, output_path, conversion_messageexcept Exception as e:return (f"❌ 處理檔案時發生錯誤:{str(e)}",None,"處理失敗")# --- Gradio Blocks 介面 ---with gr.Blocks(title="PDF 精準色彩轉換工具 (RGB → CMYK)",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])# --- 啟動應用 ---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