File size: 2,230 Bytes
cf51ebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from pathlib import Path
from fontTools.ttLib import TTFont
import logging
from typing import Dict

logger = logging.getLogger(__name__)

class FontManager:
    FONT_MAPPING = {
        'Gotham Black': 'Gotham-Black.otf',
        'Montserrat': 'Montserrat-Black.ttf',
        'Montserrat Bold': 'Montserrat-Bold.ttf',
        'Montserrat Extra': 'Montserrat-ExtraBold.ttf',
        'Urbanist Italic': 'Urbanist-Italic.ttf',
        'Urbanist': 'Urbanist-Variable.ttf'
    }

    def __init__(self):
        self.font_dir = Path(__file__).parent.parent / "fonts"
        self.font_dir.mkdir(exist_ok=True)
        self.fonts_cache: Dict[str, str] = {}
        self.default_font = "Montserrat-Black.ttf"
        self._load_fonts()

    def _load_fonts(self):
        """Charge et valide toutes les polices disponibles"""
        for font_path in self.font_dir.glob("*.[ot]tf"):
            try:
                font = TTFont(font_path)
                font_name = font['name'].getName(4, 3, 1, 1033)
                if font_name:
                    self.fonts_cache[font_path.name.lower()] = str(font_path)
                font.close()
            except Exception as e:
                logger.warning(f"Impossible de charger la police {font_path}: {e}")

    def get_font_path(self, font_name: str) -> str:
        """Retourne le chemin de la police demandée ou de la police par défaut"""
        if not font_name:
            return str(self.font_dir / self.default_font)

        # Chercher d'abord dans le mapping des noms
        mapped_name = self.FONT_MAPPING.get(font_name)
        if mapped_name:
            font_path = self.fonts_cache.get(mapped_name.lower())
            if font_path:
                return font_path

        # Si pas trouvé, essayer avec le nom direct
        font_name = font_name.lower().replace(" ", "-")
        font_path = self.fonts_cache.get(f"{font_name}.ttf") or self.fonts_cache.get(f"{font_name}.otf")
        
        if not font_path:
            logger.warning(f"Police {font_name} non trouvée, utilisation de la police par défaut")
            return str(self.font_dir / self.default_font)
        
        return font_path