Example #1
0
def get_fonts():
    if not constants.IGNORE_FONTS:
        if pconstants.SYSTEM == pconstants.WINDOWS:
            raise (NotImplementedError('Windows fonts to develop'))

        else:
            import fontconfig

            fonts = fontconfig.query(lang='en')
            n_fonts = len(fonts)
            for i in range(n_fonts):
                constants.PROGRESS_BAR_VALUE = min(
                    round(100 * (i + 1) / n_fonts), 99)
                if type(fonts[i]) is str:
                    font = fontconfig.FcFont(fonts[i])
                else:
                    font = fonts[i]
                if font.family and font.fontformat == 'TrueType':
                    name = dict(font.family)['en']
                    if name not in constants.FONTS_DICT:
                        constants.FONTS_DICT[name] = font.file
                        constants.FONTS.append(name)

            qfonts = QFontDatabase().families()
            constants.FONTS = sorted(
                [font for font in constants.FONTS if font in qfonts])
            constants.FONTS_DICT = dict([(font, constants.FONTS_DICT[font])
                                         for font in constants.FONTS])

    constants.PROGRESS_BAR_VALUE = 100
Example #2
0
File: font.py Project: run/scripts
def get_fonts():
    ret = []
    for f in fontconfig.query():
        f = fontconfig.FcFont(f)
        if f.has_char(ch):
            ret.append((f.file, f.fullname))
    return ret
Example #3
0
def annote_image(img, texte, x_pos=0, y_pos=0, taille_fonte=35, align='left'):
    """fonction qui ajoute du texte a une figure

    Entree:
    ------

    nom_fig : PIL.Image
        figure originale

    texte : string
        texte a ajouter

    x_pos, y_pos : float
        position en fraction de la taille de l'image

    nom_fig_sortie : string
        nom de la figure avec les annotations

    Sortie :
    ------

    img_sortie : PIL.Image
      figure avec l'annotation


    """
    # ajout des label sur les images
    import PIL
    from PIL import ImageFont
    from PIL import ImageDraw
    from PIL import ImageOps
    import fontconfig

    # find font
    # copy from https://stackoverflow.com/questions/24085996/how-i-can-load-a-font-file-with-pil-imagefont-truetype-without-specifying-the-ab
    fonts = fontconfig.query(lang='en')
    for i in range(1, len(fonts)):
        if fonts[i].fontformat == 'TrueType':
            font_path = fonts[i].file
            break

    #font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf", taille_fonte)
    font = ImageFont.truetype(font_path, taille_fonte)
    draw = ImageDraw.Draw(img)
    # position
    (nx, ny) = img.size
    x = int(nx * x_pos)
    y = int(ny - ny * y_pos)
    draw.text((x, y), texte, (0, 0, 0), font=font)
    draw = ImageDraw.Draw(img)

    # ajout bordure
    img = ImageOps.expand(img, border=5, fill='black')
    draw = ImageDraw.Draw(img)
    draw.rectangle((0, 0, 10, 10), fill='blue')

    # on retourne la figure
    return img
Example #4
0
 def _getFont(self, font):
     """
     Returns font paths from font name or path
     """
     if os.path.isfile(font):
         font_files = [font]
     else:
         font_files = fc.query(family=font)
         if not font_files:
             raise ValueError('No such font')
     return font_files
Example #5
0
 def _getFont(self, font):
     """
     Returns font paths from font name or path
     """
     if os.path.isfile(font):
         font_files = [font]
     else:
         font_files = fc.query(family=font)
         if not font_files:
             raise ValueError('No such font')
     return font_files
Example #6
0
def char_support(scr, character=chr(0x28a7)):
    font_names = fontconfig.query()
    row = 4

    for name in font_names:
        font = fontconfig.FcFont(name)
        if font.has_char(character) and font.fullname:
            # info = font.file
            # info = font.fullname[0][1] + ' [' + str(font.spacing) + ']'
            info = str(font.fullname)
            scr.addstr(row, 0, info)
            row += 1
Example #7
0
 def get_mono_fonts(self):
     fonts = set()
     family = "Roboto Mono"
     if fontconfig:
         available = fontconfig.query(family=family)
         if not available:
             self.err(
                 None,
                 "Needed font family '%s', but didn't find it.  Is it installed?"
                 % family)
     fonts = [
         family,
     ]
     self.note(None, "Found installed font: %s" % ', '.join(fonts))
     return fonts
    def _get_imprint_font(self,
                          desktop,
                          default='/usr/share/wine/fonts/arial.ttf'):
        conf = desktop.imprint_conf
        fonts = fontconfig.query(lang='en')
        try:
            for f in fonts:
                if conf.font_filename in f:
                    break

            font = pilImageFont.truetype(f, conf.font_size)
        except IOError:
            warn("Cannot open font file {}.".format(conf.font_filename))
            font = pilImageFont.truetype(default, conf.font_size)
        return font
Example #9
0
 def char(self, char):
     """
     Shows all system fonts that contain given character.
     """
     font_files = fc.query()
     if self._display['group']:
         font_files = self._getCharFont(font_files, char)
         font_families = self._groupFontByFamily(font_files)
         for font_family in sorted(font_families):
             print(font_family)
             if self._display['list']:
                 for font_file in font_families[font_family]:
                     print('  '+font_file)
         self._fontSummary(len(font_files), len(font_families))
     else:
         font_files = self._getCharFont(font_files, char)
         for font_file in sorted(font_files):
             print(font_file)
         self._fontSummary(len(font_files))
Example #10
0
 def char(self, char):
     """
     Shows all system fonts that contain given character.
     """
     font_files = fc.query()
     if self._display['group']:
         font_files = self._getCharFont(font_files, char)
         font_families = self._groupFontByFamily(font_files)
         for font_family in sorted(font_families):
             print(font_family)
             if self._display['list']:
                 for font_file in font_families[font_family]:
                     print('  ' + font_file)
         self._fontSummary(len(font_files), len(font_families))
     else:
         font_files = self._getCharFont(font_files, char)
         for font_file in sorted(font_files):
             print(font_file)
         self._fontSummary(len(font_files))
def does_support(enc, font, chars):
    import fontconfig
    fonts = fontconfig.query()
    font_re = re.compile(sys.argv[2])
    # print(fonts)
    fonts = [path for path in fonts if re.search(font_re, path) ]
    if len(fonts) == 0:
        return {'_error': 'No font found for '+font}
    # print(fonts)
    res = {}

    for c in chars:
        if c.startswith('U+'):
            if (sys.version_info > (3, 0)): # python 3
                c_dec = chr(int(c[2:], 16))
            else: # python 2
                c_dec =  ('\\U%08x' % int(c[2:], 16)).decode('unicode-escape')
        elif isinstance(c, bytes):
            c_dec = c.decode(enc)
        else:
            c_dec = c
        # print(c)
        # c_dec = c.decode(enc) if isinstance(c, bytes) else c
        cp = code_points(c_dec)
        # print(cp)
        if sys.maxunicode < cp[0]:
            # With some python versions, we cannot decode "high" unicode code points
            # even if the CP has a glyph in the current fontset :(
            res.update({c: 0})
            continue
        for path in fonts:
            font = fontconfig.FcFont(path)
            # print('%s ' % (c_dec, ))
            if font.has_char(c_dec):
                # print('%s -> OK in %s' % (c_dec, font))
                res.update({c_dec: 1})
                break
        else:
          res.update({c_dec: 0})

    return res
Example #12
0
class FcFontTestCase(unittest.TestCase):
    fonts = fontconfig.query(family='dejavu serif', lang='en')
    font = fontconfig.FcFont(fonts[0])

    def test_get_object_from_path(self):
        """Get FcFont instance"""
        fc = fontconfig.FcFont(self.font.file)
        self.assertIsInstance(fc, fontconfig.FcFont)

    def test_char_in_font(self):
        """Test the given character in font charset"""
        fc = fontconfig.FcFont(self.font.file)
        char = 'A' if pyver == 3 else 'A'.decode('utf8')
        self.assertTrue(fc.has_char(char))

    @unittest.expectedFailure
    def test_char_not_in_font(self):
        """Test the given character not in font charset"""
        fc = fontconfig.FcFont(self.font.file)
        char = 'ć°¸' if pyver == 3 else 'ć°¸'.decode('utf8')
        self.assertTrue(fc.has_char(char))
Example #13
0
 def get_serif_fonts(self):
     fonts = set()
     scripts = self.root.get('scripts').split(',')
     noto_serif = "'Noto Serif'"
     for script in scripts:
         family = get_noto_serif_family_for_script(script)
         fonts.add("'%s'" % family)
         if fontconfig:
             available = fontconfig.query(family=family)
             if not available:
                 self.warn(
                     None,
                     "Needed font family '%s', but didn't find it.  Is it installed?"
                     % family)
     fonts -= set([
         noto_serif,
     ])
     fonts = [
         noto_serif,
     ] + list(fonts)
     return fonts
Example #14
0
    def chars(self, font, block):
        """
        Analyses characters in single font or all fonts.
        """
        if font:
            font_files = self._getFont(font)
        else:
            font_files = fc.query()
        code_points = self._getFontChars(font_files)

        if not block:
            blocks = all_blocks
            ranges_column = map(itemgetter(3), blocks)
            overlapped = Ranges(code_points).getOverlappedList(ranges_column)
        else:
            blocks = [block]
            overlapped = [Ranges(code_points).getOverlapped(block[3])]

        if self._display['group']:
            char_count = block_count = 0
            for i, block in enumerate(blocks):
                o_count = len(overlapped[i])
                if o_count:
                    block_count += 1
                    char_count += o_count
                    total = sum(len(r) for r in block[3])
                    percent = 0 if total == 0 else o_count / total
                    print("{0:>6}  {1:47} {2:>4.0%} ({3}/{4})".format(
                        block[0], block[2], percent, o_count, total))
                    if self._display['list']:
                        for point in overlapped[i]:
                            self._charInfo(point, padding=9)
            self._charSummary(char_count, block_count)
        else:
            for point in code_points:
                self._charInfo(point, padding=7)
            self._charSummary(len(code_points))
Example #15
0
    def chars(self, font, block):
        """
        Analyses characters in single font or all fonts.
        """
        if font:
            font_files = self._getFont(font)
        else:
            font_files = fc.query()
        code_points = self._getFontChars(font_files)

        if not block:
            blocks = all_blocks
            ranges_column = map(itemgetter(3), blocks)
            overlapped = Ranges(code_points).getOverlappedList(ranges_column)
        else:
            blocks = [block]
            overlapped = [Ranges(code_points).getOverlapped(block[3])]

        if self._display['group']:
            char_count = block_count = 0
            for i, block in enumerate(blocks):
                o_count = len(overlapped[i])
                if o_count:
                    block_count += 1
                    char_count += o_count
                    total = sum(len(r) for r in block[3])
                    percent = 0 if total == 0 else o_count / total
                    print("{0:>6}  {1:47} {2:>4.0%} ({3}/{4})".format(block[0], block[2], percent, o_count, total))
                    if self._display['list']:
                        for point in overlapped[i]:
                            self._charInfo(point, padding=9)
            self._charSummary(char_count, block_count)
        else:
            for point in code_points:
                self._charInfo(point, padding=7)
            self._charSummary(len(code_points))
Example #16
0
#!/usr/bin/env python2
import re, sys
import fontconfig
if len(sys.argv) < 1:
    print('''Usage: ''' + sys.argv[0] + '''CHARS [REGEX]
Print the names of available fonts containing the code point(s) CHARS.
If CHARS contains multiple characters, they must all be present.
Alternatively you can use U+xxxx to search for a single character with
code point xxxx (hexadecimal digits).
If REGEX is specified, the font name must match this regular expression.''')
    sys.exit(0)
characters = sys.argv[1]
if characters.startswith('U+'):
    characters = unichr(int(characters[2:], 16))
else:
    characters = characters.decode(sys.stdout.encoding)
regexp = re.compile(sys.argv[2] if len(sys.argv) > 2 else '')

font_names = fontconfig.query()
found = False
for name in font_names:
    if not re.search(regexp, name): continue
    font = fontconfig.FcFont(name)
    if all(font.has_char(c) for c in characters):
        print(name)
        found = True

sys.exit(0 if found else 1)
def get_fonts_with_chars(chars):
    for font_file in fontconfig.query():
        font = fontconfig.FcFont(font_file)
        if all([font.has_char(char) for char in chars]):
            yield font
Example #18
0
 def test_get_list(self):
     """query should give a list for specified font"""
     fonts = fontconfig.query(family='dejavu serif', lang='en')
     self.assertIsInstance(fonts, list)
Example #19
0
def _uncached_get_font_paths_by_name(name):
    # Search in packaged folder:
    if DEBUG_FONTINFO:
        logdebug("get_font_paths_by_name: searching for '" + str(name) + "'")
    initialize_sdl()
    name_variants = []
    name_variants.append(name.lower())
    name_variants.append(name.replace(" ", "").lower())
    candidates = []
    for filename in os.listdir(
            os.path.abspath(
                os.path.join(os.path.dirname(__file__), "packaged-fonts"))):
        (variant_name, extracted_letters) = extract_name_ending(filename)
        if DEBUG_FONTINFO:
            logdebug("get_font_paths_by_name: " + "searching " +
                     str(name_variants) + " in " +
                     str((variant_name, extracted_letters)) + " of packaged " +
                     str(filename))
        if len(variant_name) > 0:
            for name_variant in name_variants:
                base = filename[:-extracted_letters].lower()
                if extracted_letters == 0:
                    base = filename
                if base.lower() == name_variant or \
                        (base.lower() + " " +
                        variant_name.lower()) == name_variant or \
                        (base.lower() + variant_name.lower()) == \
                        name_variant:
                    if variant_name.lower() != "regular":
                        candidates.append(
                            (base + variant_name[:1].upper() +
                             variant_name[1:].lower(),
                             os.path.normpath(
                                 os.path.join(
                                     os.path.abspath(
                                         os.path.dirname(__file__)),
                                     "packaged-fonts", filename))))
                    else:
                        candidates = [(
                            base,
                            os.path.normpath(
                                os.path.join(
                                    os.path.abspath(os.path.dirname(__file__)),
                                    "packaged-fonts", filename)))] + candidates
    if len(candidates) > 0:
        if DEBUG_FONTINFO:
            logdebug("get_font_paths_by_name: " + "got candidates for " +
                     str(name) + ": " + str(candidates))
        return candidates

    # Don't try other places on android:
    import sdl2 as sdl
    if sdl.SDL_GetPlatform().decode("utf-8", "replace").lower() != "android":
        return []

    # Search system-wide:
    try:
        import fontconfig, fontTools
    except ImportError:
        return []
    from wobblui.font.query import get_font_name
    candidates = []
    unspecific_variants = [
        "italic", "bold", "condensed", "oblique", "bolditalic", "italicbold",
        "boldoblique", "obliquebold"
    ]
    if DEBUG_FONTINFO:
        logdebug("get_font_paths_by_name: " + "got no candidates for " +
                 str(name) + ", searching system-wide...",
                 flush=True)

    def is_not_regular(font_name):
        for unspecific_variant in unspecific_variants:
            if font_name.lower().replace("-", "").replace(" ", "").\
                    replace("_", "").\
                    endswith(unspecific_variant):
                return True
        return False

    for fpath in fontconfig.query():
        if not os.path.exists(fpath):
            continue
        (specific_name, unspecific_name) = get_font_name(fpath)
        if specific_name is None:
            continue
        if unspecific_name.lower() == name.lower() and \
                specific_name.lower() != name.lower() and \
                is_not_regular(specific_name):
            # Not-so-good match:
            candidates.append((specific_name, fpath))
        elif unspecific_name.lower() == name.lower() or \
                specific_name.lower() == name.lower():
            # Good match:
            candidates = [(specific_name, fpath)] +\
                candidates
    return candidates
Example #20
0
 def test_query_font(self):
   """Get FcFont object from list"""
   fonts = fontconfig.query(family='dejavu serif', lang='en')
   font = fonts[0]
   self.assertIsInstance(font, str)
Example #21
0
 def test_query_font(self):
     """Get FcFont object from list"""
     fonts = fontconfig.query(family='dejavu serif', lang='en')
     font = fonts[0]
     self.assertIsInstance(font, str)
Example #22
0
from urllib.parse import urlparse
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib

from sqlalchemy import *
from sqlalchemy.orm import *

from PIL import Image,ImageFont,ImageDraw
from fontconfig import query

### configuration ###
progname = "notifier"

dir = "/tmp/" + progname + "/"

fonts = query(family='DejaVu Sans')
for i in range(0,len(fonts)):
    if fonts[i].fontformat == 'TrueType' and [item for item in fonts[i].style if 'Bold' in item] != []:
        #print(fonts[i].family)
        fontpath = fonts[i].file
        break

limit = 30

size = (128, 128)

#gi.require_version('AppIndicator3', '0.1')
#from gi.repository import AppIndicator3
#from gi.repository import Gtk
#notifierClass = lambda: GNotifier()
        font = service.find('font').text
        italic_font = service.find('italic_font').text
        italic = service.find('italic').text
        title_font_size = int(service.find('title_font_size').text)
        summary_font_size = int(service.find('summary_font_size').text)
        title_rows = int(service.find('title_rows').text)
        summary_rows = int(service.find('summary_rows').text)
        entry_number = int(service.find('entry_number').text)
        logo = service.find('logo').text
    elif service.get('name') == 'env':
        duration_time = service.find('duration_time').text
        repeat = service.find('repeat').text
        display_reset = service.find('display_reset').text

# font path
fonts = fontconfig.query(family=font, lang='en')
for i in range(0, len(fonts)):
    if fonts[i].style[0][1] == 'Regular':
        font_path = fonts[i].file

fonts = fontconfig.query(family=italic_font, lang='en')
for i in range(0, len(fonts)):
    if fonts[i].style[0][1] == 'Oblique':
        italic_font_path = fonts[i].file

# parse template file
template_file = 'template/' + template + '.xml'
tree = ET.parse(template_file)
root = tree.getroot()

for station in root.findall('station'):
Example #24
0
            ('PyPDF2', 'PyPDF2'),
            ('python-fontconfig', 'fontconfig'),
            ('tox', 'tox'),
            ('weasyprint', 'weasyprint'),
        ]:
    try:
        m = importlib.import_module(mname)
    except ModuleNotFoundError:
        errors += 1
        sys.stderr.write("  Missing package: %s\n" % (pname, ))

if errors:
    sys.stderr.write("Not all test requirements are fulfilled")
    sys.exit(errors)

import fontconfig
for (fname, fcount) in [
            ('Noto Serif', 72),
            ('Roboto Mono', 10)
        ]:
    available = fontconfig.query(family=fname)
    acount = len(available)
    if acount < fcount:
        errors += 1
        sys.stderr.write("  Missing fonts: found %s fonts for family %s, but expected at least %s\n" % (acount, fname, fcount))

if errors:
    sys.stderr.write("Not all test requirements are fulfilled")
    sys.exit(errors)

Example #25
0
#!/usr/bin/python3

# ****************************************************************************
# Copyright(c) 2017 Intel Corporation.
# License: MIT See LICENSE file in root directory.
# ****************************************************************************

# Utilities to help visualize the output from
# Intel® Movidius™ Neural Compute Stick (NCS)

import numpy
from PIL import Image, ImageDraw, ImageFilter, ImageFont
import fontconfig

fonts = fontconfig.query(family='FreeSerif', lang='en')


def draw_bounding_box(y1,
                      x1,
                      y2,
                      x2,
                      img,
                      thickness=4,
                      fontsize=15,
                      outlineColor=(255, 255, 0),
                      textColor=(255, 255, 0),
                      display_str=()):
    """ Inputs
    (x1, y1)  = Top left corner of the bounding box
    (x2, y2)  = Bottom right corner of the bounding box
    img       = Image/frame represented as numpy array
Example #26
0
WIDTH = 640
HEIGHT = 480
DURATION = 500
FONT_FAMILY = 'Inconsolata'
TEXT = sys.argv[1]

template = Image.new('RGB', (WIDTH, HEIGHT))

grad_start = [255, 0, 0]
grad_end = [0, 0, 255]

halfway = min(WIDTH, HEIGHT) / 4
midx, midy = WIDTH / 2, HEIGHT / 2

draw = ImageDraw.Draw(template)
fonts = fontconfig.query(family=FONT_FAMILY, lang='en')
ttf_fonts = [
    fonts[i].file for i in range(len(fonts))
    if fonts[i].fontformat == 'TrueType'
]
font = ImageFont.truetype(ttf_fonts[0], int(HEIGHT / 8))
fwidth, fheight = draw.textsize(TEXT, font=font)
draw.text((midx - fwidth / 2, midy - fheight / 2),
          TEXT,
          font=font,
          fill=(255, 255, 255))

indices = set()

for x in range(WIDTH):
    for y in range(HEIGHT):
Example #27
0
from distutils.version import StrictVersion
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image as PILImage
from PIL import ImageDraw, ImageFont
from fonts.otf import font_files
from IPython.display import display, Image

import tensorflow as tf
from object_detection.utils import ops as utils_ops
from utils import label_map_util

logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
system_fonts = fontconfig.query(family='ubuntu', lang='en')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'


def load_graph(model_path):

    try:

        detection_graph = tf.Graph()
        with detection_graph.as_default():
            od_graph_def = tf.GraphDef()
            with tf.gfile.GFile(model_path.as_posix(), 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')
        logging.info('Done loading frozen graph from {}'.format(model_path))
Example #28
0
 def test_get_list(self):
   """query should give a list for specified font"""
   fonts = fontconfig.query(family='dejavu serif', lang='en')
   self.assertIsInstance(fonts, list)