Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines456789244 unmodified lines254255256257258259376 unmodified lines636637638639640641168 unmodified lines81081181281381481553 unmodified lines8698708718723 unmodified linesimport shutilimport subprocessimport tempfilefrom pathlib import Pathimport pikepdf244 unmodified linesreturn "ℹ️ 色彩預檢:未偵測到 RGB,但也未辨識出明確 CMYK;文件可能主要為灰階或純文字。"# ============================================================# DOCX 轉中介 PDF# ============================================================376 unmodified lines"可能因字型替代、表格、文字方塊、浮動圖片、分節或頁首頁尾設定而與 Microsoft Word 版面不同。""正式付印前請逐頁核對;最穩妥的方式是先由 Microsoft Word 匯出 PDF,再上傳轉換。")progress(0.10, desc="以 LibreOffice 轉換 DOCX...")source_pdf, docx_message = convert_docx_to_pdf(input_path, work_dir)status_messages.append(docx_message)168 unmodified lines- 單色圖片:最高保留 1200 ppi- 低於 300 ppi:列入預���警示- 低於 200 ppi:列入嚴重警示""")53 unmodified linesshow_error=True,share=False,allowed_paths=["/tmp"],)3 unmodified lines4567891011244 unmodified lines256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491376 unmodified lines868869870871872873874875876877878168 unmodified lines104710481049105010511052105353 unmodified lines11071108110911103 unmodified linesimport shutilimport subprocessimport tempfileimport zipfileimport xml.etree.ElementTree as ETfrom pathlib import Pathimport pikepdf244 unmodified linesreturn "ℹ️ 色彩預檢:未偵測到 RGB,但也未辨識出明確 CMYK;文件可能主要為灰階或純文字。"# ============================================================# DOCX 字型預檢# ============================================================# 常見 Microsoft 字型與 Linux 度量相容/近似替代字型。# 「替代可用」不代表外觀或中文字寬完全相同,正式印刷仍須人工核對。FONT_SUBSTITUTION_HINTS = {"arial": ["Liberation Sans", "Arimo"],"arial narrow": ["Liberation Sans Narrow"],"times new roman": ["Liberation Serif", "Tinos"],"courier new": ["Liberation Mono", "Cousine"],"calibri": ["Carlito"],"cambria": ["Caladea"],"aptos": ["Carlito", "Liberation Sans"],"segoe ui": ["Noto Sans", "Liberation Sans"],"microsoft jhenghei": ["Noto Sans CJK TC", "Noto Sans TC"],"微軟正黑體": ["Noto Sans CJK TC", "Noto Sans TC"],"microsoft yahei": ["Noto Sans CJK SC", "Noto Sans SC"],"新細明體": ["Noto Serif CJK TC", "Noto Serif TC"],"pmingliu": ["Noto Serif CJK TC", "Noto Serif TC"],"細明體": ["Noto Serif CJK TC", "Noto Serif TC"],"mingliu": ["Noto Serif CJK TC", "Noto Serif TC"],"標楷體": ["Noto Serif CJK TC", "Noto Serif TC"],"dfkai-sb": ["Noto Serif CJK TC", "Noto Serif TC"],"simhei": ["Noto Sans CJK SC", "Noto Sans SC"],"simsun": ["Noto Serif CJK SC", "Noto Serif SC"],"ms gothic": ["Noto Sans CJK JP"],"ms mincho": ["Noto Serif CJK JP"],}def normalize_font_name(name):"""正規化字型名稱,供不分大小寫及空白比對。"""return re.sub(r"\s+", " ", str(name or "").strip()).casefold()def extract_docx_fonts(docx_path):"""從 DOCX 壓縮檔內的 Word XML 擷取宣告使用的字型。檢查 document、styles、numbering、header、footer、footnotes、endnotes、comments、fontTable 及 theme 等 Word XML。"""fonts = set()relevant_prefixes = ("word/document.xml","word/styles.xml","word/numbering.xml","word/fontTable.xml","word/theme/","word/header","word/footer","word/footnotes.xml","word/endnotes.xml","word/comments.xml",)try:with zipfile.ZipFile(str(docx_path), "r") as archive:for member in archive.namelist():if not member.endswith(".xml") or not member.startswith(relevant_prefixes):continuetry:root = ET.fromstring(archive.read(member))except (ET.ParseError, KeyError):continuefor element in root.iter():local_tag = element.tag.rsplit("}", 1)[-1]if local_tag == "rFonts":for attr_name, value in element.attrib.items():local_attr = attr_name.rsplit("}", 1)[-1]if local_attr in {"ascii", "hAnsi", "eastAsia", "cs"} and value:# Theme 參照(如 majorEastAsia)不是實際字型名稱,另由 theme XML 擷取。if not value.lower().endswith("theme"):fonts.add(value.strip())elif local_tag == "font":for attr_name, value in element.attrib.items():if attr_name.rsplit("}", 1)[-1] == "name" and value:fonts.add(value.strip())# theme1.xml 內的 latin / ea / cs 以 typeface 儲存。elif local_tag in {"latin", "ea", "cs"}:typeface = element.attrib.get("typeface")if typeface:fonts.add(typeface.strip())return sorted(font for font in fonts if font), Noneexcept zipfile.BadZipFile:return [], "DOCX 結構損壞或不是有效的 Office Open XML 文件。"except Exception as error:return [], str(error)def get_installed_font_families():"""使用 fontconfig 的 fc-list 取得 Space Linux 環境已安裝字型家族。"""fc_list = shutil.which("fc-list")if not fc_list:return {}, "找不到 fc-list;請確認系統已安裝 fontconfig。"try:result = subprocess.run([fc_list, ":", "family"],capture_output=True,text=True,timeout=30,check=True,)families = {}for line in result.stdout.splitlines():# fc-list 一行可能列出多個別名,以逗號分隔。for family in line.split(","):family = family.strip()if family:families.setdefault(normalize_font_name(family), family)return families, Noneexcept Exception as error:return {}, str(error)def get_fontconfig_match(font_name):"""查詢 fontconfig 對指定字型實際選擇的替代字型。"""fc_match = shutil.which("fc-match")if not fc_match:return Nonetry:result = subprocess.run([fc_match, "-f", "%{family}", font_name],capture_output=True,text=True,timeout=10,check=True,)return (result.stdout or "").split(",", 1)[0].strip() or Noneexcept Exception:return Nonedef inspect_docx_fonts(docx_path):"""比對 DOCX 宣告字型與 Hugging Face Space 已安裝字型。"""declared_fonts, extract_error = extract_docx_fonts(docx_path)if extract_error:return f"⚠️ DOCX 字型預檢失敗:{extract_error}"if not declared_fonts:return ("ℹ️ DOCX 字型預檢:未從文件 XML 擷取到明確字型名稱。""文件可能依賴主題字型、預設樣式或外部範本,仍須人工核對。")installed, installed_error = get_installed_font_families()if installed_error:return f"⚠️ DOCX 使用字型:{', '.join(declared_fonts)}\n無法比對系統字型:{installed_error}"exact = []substitute = []missing = []for font in declared_fonts:key = normalize_font_name(font)if key in installed:exact.append((font, installed[key]))continuesuggested = Nonefor candidate in FONT_SUBSTITUTION_HINTS.get(key, []):candidate_key = normalize_font_name(candidate)if candidate_key in installed:suggested = installed[candidate_key]breakactual_match = get_fontconfig_match(font)actual_is_same = actual_match and normalize_font_name(actual_match) == keyif actual_is_same:exact.append((font, actual_match))elif suggested or actual_match:substitute.append((font, suggested or actual_match, actual_match))else:missing.append(font)lines = ["🔤 DOCX 字型預檢",f"文件宣告字型:{len(declared_fonts)} 種",f"原字型可用:{len(exact)} 種",f"將使用替代字型:{len(substitute)} 種",f"無法判定替代字型:{len(missing)} 種","",]if exact:lines.append("【原字型可用】")lines.extend(f"✅ {source}" for source, _ in exact)lines.append("")if substitute:lines.append("【可能被替代】")for source, preferred, actual in substitute:if actual and normalize_font_name(actual) != normalize_font_name(preferred):lines.append(f"⚠️ {source} → 建議 {preferred};fontconfig 實際匹配 {actual}")else:lines.append(f"⚠️ {source} → {preferred}")lines.append("")if missing:lines.append("【無法判定】")lines.extend(f"❌ {font}:找不到原字型或明確替代字型" for font in missing)lines.append("")if substitute or missing:lines.append("結論:存在字型替代風險,可能影響換行、行距、表格尺寸、頁碼及總頁數。""正式印刷建議先由 Microsoft Word 匯出 PDF,再上傳本工具轉換。")else:lines.append("結論:文件宣告字型在 Space 中均可找到;但 LibreOffice 與 Microsoft Word 排版引擎不同,""仍不保證版面完全一致。")return "\n".join(lines).strip()# ============================================================# DOCX 轉中介 PDF# ============================================================376 unmodified lines"可能因字型替代、表格、文字方塊、浮動圖片、分節或頁首頁尾設定而與 Microsoft Word 版面不同。""正式付印前請逐頁核對;最穩妥的方式是先由 Microsoft Word 匯出 PDF,再上傳轉換。")progress(0.05, desc="預檢 DOCX 使用字型...")docx_font_report = inspect_docx_fonts(input_path)status_messages.append(docx_font_report)progress(0.10, desc="以 LibreOffice 轉換 DOCX...")source_pdf, docx_message = convert_docx_to_pdf(input_path, work_dir)status_messages.append(docx_message)168 unmodified lines- 單色圖片:最高保留 1200 ppi- 低於 300 ppi:列入預���警示- 低於 200 ppi:列入嚴重警示- DOCX:轉檔前擷取文件宣告字型,與 Space 已安裝字型及 fontconfig 實際匹配結果比對""")53 unmodified linesshow_error=True,share=False,allowed_paths=["/tmp"],)
app.py+239-1