pdf / setup_fonts.py
fokan's picture
Upload 49 files
dc4dad8 verified
#!/usr/bin/env python3
"""
Setup script to install Arabic fonts for Hugging Face Spaces
This script downloads and installs Arabic fonts that are not available in Debian repositories
"""
import os
import subprocess
import urllib.request
import zipfile
import tempfile
import shutil
def run_command(cmd):
"""Run a shell command and return the result"""
try:
result = subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
return result.stdout
except subprocess.CalledProcessError as e:
print(f"Error running command '{cmd}': {e}")
print(f"Error output: {e.stderr}")
return None
def download_and_extract(url, extract_to):
"""Download a zip file and extract it"""
try:
with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as tmp_file:
print(f"Downloading {url}...")
urllib.request.urlretrieve(url, tmp_file.name)
with zipfile.ZipFile(tmp_file.name, 'r') as zip_ref:
zip_ref.extractall(extract_to)
os.unlink(tmp_file.name)
return True
except Exception as e:
print(f"Error downloading/extracting {url}: {e}")
return False
def setup_arabic_fonts():
"""Setup Arabic fonts for LibreOffice"""
print("🔤 Setting up Arabic fonts for RTL support...")
# Use /tmp for font installation to avoid permission issues
fonts_dir = "/tmp/fonts/truetype/arabic-enhanced"
try:
os.makedirs(fonts_dir, exist_ok=True)
# Ensure proper permissions
os.chmod(fonts_dir, 0o777)
except PermissionError:
# If we can't change permissions, continue anyway
print(f"⚠️ Permission denied when setting up {fonts_dir}, continuing anyway...")
pass
# Try to download and install Amiri font
print("📥 Installing Amiri font...")
amiri_installed = False
with tempfile.TemporaryDirectory() as tmp_dir:
try:
amiri_url = "https://github.com/aliftype/amiri/releases/download/0.117/Amiri-0.117.zip"
if download_and_extract(amiri_url, tmp_dir):
amiri_dir = os.path.join(tmp_dir, "Amiri-0.117")
if os.path.exists(amiri_dir):
for file in os.listdir(amiri_dir):
if file.endswith('.ttf'):
src = os.path.join(amiri_dir, file)
dst = os.path.join(fonts_dir, file)
shutil.copy2(src, dst)
try:
os.chmod(dst, 0o644)
except PermissionError:
# If we can't change permissions, continue anyway
pass
print("✅ Amiri font installed successfully")
amiri_installed = True
else:
print("❌ Amiri font directory not found")
else:
print("❌ Failed to download Amiri font")
except Exception as e:
print(f"❌ Error installing Amiri font: {e}")
# Try to download and install Scheherazade New font
print("📥 Installing Scheherazade New font...")
scheherazade_installed = False
with tempfile.TemporaryDirectory() as tmp_dir:
try:
scheherazade_url = "https://github.com/silnrsi/font-scheherazade/releases/download/v3.300/ScheherazadeNew-3.300.zip"
if download_and_extract(scheherazade_url, tmp_dir):
scheherazade_dir = os.path.join(tmp_dir, "ScheherazadeNew-3.300")
if os.path.exists(scheherazade_dir):
for file in os.listdir(scheherazade_dir):
if file.endswith('.ttf'):
src = os.path.join(scheherazade_dir, file)
dst = os.path.join(fonts_dir, file)
shutil.copy2(src, dst)
try:
os.chmod(dst, 0o644)
except PermissionError:
# If we can't change permissions, continue anyway
pass
print("✅ Scheherazade New font installed successfully")
scheherazade_installed = True
else:
print("❌ Scheherazade New font directory not found")
else:
print("❌ Failed to download Scheherazade New font")
except Exception as e:
print(f"❌ Error installing Scheherazade New font: {e}")
# If both fonts failed to install, try to copy local Arial font
if not amiri_installed and not scheherazade_installed:
print("📥 Copying local Arial font as fallback...")
try:
if os.path.exists("arial.ttf"):
dst = os.path.join(fonts_dir, "arial.ttf")
shutil.copy2("arial.ttf", dst)
try:
os.chmod(dst, 0o644)
except PermissionError:
# If we can't change permissions, continue anyway
pass
print("✅ Arial font copied successfully")
else:
print("❌ Local Arial font not found")
except Exception as e:
print(f"❌ Error copying Arial font: {e}")
# Update font cache
print("🔄 Updating font cache...")
try:
run_command("fc-cache -fv")
print("✅ Font cache updated successfully")
except Exception as e:
print(f"❌ Error updating font cache: {e}")
# Verify installation
print("✅ Verifying Arabic fonts installation...")
try:
result = run_command("fc-list | grep -i 'amiri\\|scheherazade\\|noto.*arabic\\|arial' | head -10")
if result:
print("Available Arabic fonts:")
print(result)
else:
print("No Arabic fonts found in font list")
except Exception as e:
print(f"❌ Error verifying font installation: {e}")
print("🎯 Arabic fonts setup completed!")
if __name__ == "__main__":
try:
setup_arabic_fonts()
except Exception as e:
print(f"❌ Font setup failed with error: {e}")
print("Continuing with default system fonts...")