Donlagon007's picture
Upload 2 files
813be6a verified
from pathlib import Path
import requests
# ดาวน์โหลดฟอนต์ Noto Sans CJK (ครั้งแรกเท่านั้น) แล้วใช้ทันที
def ensure_local_cjk_font(font_filename="NotoSansCJKsc-Regular.otf"):
here = Path(__file__).resolve().parent
fonts_dir = here / "fonts"
fonts_dir.mkdir(exist_ok=True)
dest = fonts_dir / font_filename
if not dest.exists():
url = "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf"
r = requests.get(url, timeout=60)
r.raise_for_status()
dest.write_bytes(r.content)
print("⬇️ Downloaded font to", dest)
fm.fontManager.addfont(str(dest))
prop = fm.FontProperties(fname=str(dest))
family = prop.get_name()
matplotlib.rcParams["font.sans-serif"] = [family, "DejaVu Sans"]
matplotlib.rcParams["axes.unicode_minus"] = False
print("✅ Using CJK font (local):", dest.name, "->", family)
return str(dest), family
import os, warnings
import streamlit as st
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager as fm
st.set_page_config(page_title="CJK Font Debug", layout="wide")
# ---------- ตรวจระบบฟอนต์ ----------
@st.cache_resource
def inspect_fonts():
info = {}
# 0) พยายามให้มีฟอนต์ในโปรเจ็กต์ก่อน (สำคัญ) <<<
local_path, local_family = ensure_local_cjk_font() # <<< โหลด/ลงทะเบียนฟอนต์
info["local_font"] = {"path": local_path, "family": local_family} # <<<
# 1) อ่าน apt.txt (กัน commit ผิด)
try:
with open("apt.txt", "r", encoding="utf-8") as f:
info["apt.txt"] = f.read().strip()
except FileNotFoundError:
info["apt.txt"] = "(no apt.txt)"
# 2) path ที่มักจะมีใน Ubuntu/HF + ใส่ path โลคัลไว้หัวแถว <<<
candidates = [
local_path, # <<< ใช้ไฟล์ที่เราเพิ่งดาวน์โหลดเป็นตัวเลือกแรก
"/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Sc-Regular.otf",
"/usr/share/fonts/opentype/noto/NotoSansCJK-TC-Regular.otf",
"/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
]
info["exists"] = {p: os.path.exists(p) for p in candidates}
# 3) สแกน directory ทั่วไป
sysfonts = fm.findSystemFonts(fontpaths=["/usr/share/fonts", "/usr/local/share/fonts"])
hits = [p for p in sysfonts if any(k in p.lower() for k in ["wqy", "noto", "cjk", "droid"])]
info["scan_count"] = len(hits)
info["scan_sample"] = hits[:15]
# 4) เลือกฟอนต์ตัวแรกที่พบ
chosen = None
for p in candidates + hits:
if os.path.exists(p):
fm.fontManager.addfont(p) # register
prop = fm.FontProperties(fname=p)
family = prop.get_name()
matplotlib.rcParams["font.sans-serif"] = [family, "DejaVu Sans"]
matplotlib.rcParams["axes.unicode_minus"] = False
chosen = {"path": p, "family": family}
break
if not chosen:
warnings.warn("ไม่พบฟอนต์จีน ใช้ DejaVu Sans ชั่วคราว")
matplotlib.rcParams["font.sans-serif"] = ["DejaVu Sans"]
matplotlib.rcParams["axes.unicode_minus"] = False
try:
fm._rebuild()
except Exception:
pass
info["chosen"] = chosen or "(none)"
info["rcParams.font.sans-serif"] = matplotlib.rcParams.get("font.sans-serif")
info["rcParams.axes.unicode_minus"] = matplotlib.rcParams.get("axes.unicode_minus")
return info, chosen
info, chosen = inspect_fonts()
st.sidebar.subheader("Font debug")
st.sidebar.json(info)
# ---------- พล็อตตัวอย่าง ----------
st.subheader("Example plot")
sample_text = "測試:我今年35歲,在科技業工作。"
fig, ax = plt.subplots(figsize=(4, 2.2), dpi=150)
if isinstance(chosen, dict):
prop = fm.FontProperties(family=chosen["family"])
else:
prop = None # จะใช้ DejaVu Sans (และจะเตือน glyph missing)
ax.set_title(sample_text, fontproperties=prop)
ax.plot([0,1,2],[0,1,0])
ax.set_xlabel("X 軸", fontproperties=prop)
ax.set_ylabel("Y 軸", fontproperties=prop)
plt.tight_layout()
st.pyplot(fig, clear_figure=True, use_container_width=True)
# ---------- แผนสำรอง: โหลดฟอนต์จากโฟลเดอร์ภายใน repo ----------
st.markdown("### Local font fallback (optional)")
st.caption("ถ้า apt.txt ไม่เวิร์ก ให้แนบไฟล์ฟอนต์เองในโฟลเดอร์ fonts/ แล้ว uncomment โค้ดด้านล่าง")
with st.expander("Show fallback code"):
st.code("""
from pathlib import Path
from matplotlib import font_manager as fm, pyplot as plt
font_path = Path(__file__).with_name("fonts") / "NotoSansCJKsc-Regular.otf"
fm.fontManager.addfont(str(font_path))
prop = fm.FontProperties(fname=str(font_path))
plt.rcParams["font.sans-serif"] = [prop.get_name(), "DejaVu Sans"]
plt.rcParams["axes.unicode_minus"] = False
""", language="python")