Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google #7

Merged
merged 3 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
# Install pre-commit hooks via
# pre-commit install

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: 2c9f875913ee60ca25ce70243dc24d5b6415598c # frozen: v4.6.0
Expand Down Expand Up @@ -46,6 +43,23 @@ repos:
hooks:
- id: codespell
args: ["-w", "-L", "ist,cant,connexion,multline,checkin"]

- repo: local
hooks:
- id: custom-script
name: Verify requirements file
entry: python req.py
language: system
types: [python]

- repo: local
hooks:
- id: tests
name: Run tests
entry: pytest tests/
language: system
types: [python]

ci:
autofix_prs: false
autofix_commit_msg: "[pre-commit.ci 🤖] Apply code format tools to PR"
Expand Down
58 changes: 3 additions & 55 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<img src="https://github.com/JosephBARBIERDARNAL/static/blob/main/python-libs/pyfonts/image.png?raw=true" alt="pyfonts logo" align="right" width="200px"/>

A simple way to load fonts for matplotlib.
A simple (and reproducible) way to load fonts for `matplotlib`.

Check out [the online documentation](https://python-graph-gallery.com/pyfonts/).

Expand All @@ -18,12 +18,6 @@ You can install `pyfonts` directly from PyPI with:
pip install pyfonts
```

(not recommended) Alternatively you can install the **development version** with:

```
pip install git+https://github.com/JosephBARBIERDARNAL/pyfonts.git
```

<br><br>

# Quick start
Expand All @@ -36,7 +30,6 @@ font = load_font(
font_url="https://github.com/google/fonts/raw/main/apache/ultra/Ultra-Regular.ttf"
)

# check how the font looks on a minimalist example
fig, ax = plt.subplots(figsize=(10, 6))
ax.text(
x=0.5,
Expand All @@ -61,53 +54,8 @@ Check out [the online documentation](https://python-graph-gallery.com/pyfonts/).

# Contributions

Contributions (and feedback) are welcome.

### TODO features:

- check the [issues](https://github.com/JosephBARBIERDARNAL/pyfonts/issues) for ideas
- suggest something (:

### Installation for contributions

_Follow the steps below for your OS._

1. **Fork the Repository:**
Fork this repository to your GitHub account.

2. **Clone the Repository:**

```bash
git clone https://github.com/yourusername/pyfonts.git
cd pyfonts
```

3. **Set Up a Virtual Environment:**

- **Mac/Linux:**
```bash
python -m venv venv
source venv/bin/activate
```
- **Windows:**
```cmd
python -m venv venv
venv\Scripts\activate
```

4. **Install Dependencies:**

```bash
pip install -r requirements-dev.txt
pip install -e .
```

5. **Create a Feature Branch:**

```bash
git checkout -b feature-name
```
Contributions and feedback are welcome.

6. **Start Coding!**
There's not much that needs to be implemented at the moment. If you've found a bug or want to request a new feature, open an [issue](https://github.com/JosephBARBIERDARNAL/pyfonts/issues).

<br><br><br>
15 changes: 2 additions & 13 deletions pyfonts/get_font.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def _get_font_from_url(font_location: str) -> FontProperties:
font found and returns a FontProperties.

Params:
- font_location (str): url that points to the binary font file on Github
- font_location: url that points to the binary font file on Github

Returns:
- matplotlib.font_manager.FontProperties: A FontProperties object containing the loaded font.
Expand Down Expand Up @@ -57,7 +57,7 @@ def _get_local_font(font_location: str) -> FontProperties:
Retrieves a font from a local path.

Params:
- font_location (str): path to a font file.
- font_location: path to a font file.

Returns:
- matplotlib.font_manager.FontProperties: A FontProperties object containing the loaded font.
Expand All @@ -74,14 +74,3 @@ def _get_local_font(font_location: str) -> FontProperties:
raise ValueError(f"Font file not found at : '{font_location}'")

return font


def _get_font_from_google(
font_location: str, weight: str, style: str
) -> FontProperties:
raise ValueError("Feature not available yet")

# font_dir = font_location.lower()
# available_files = _get_github_dir_files(path=f"ofl/{font_dir}")
# available_font_files = _filter_font_files(available_files)
# raw_tag = "?raw=true"
13 changes: 0 additions & 13 deletions pyfonts/is_valid.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,3 @@ def _is_valid_raw_url(url: str) -> bool:
return True

return False


def _is_safe_input(font_name, font_url, font_path) -> bool:
if font_name and (font_url or font_path):
return False
elif font_url and (font_name or font_path):
return False
elif font_path and (font_name or font_url):
return False
elif not font_name and not font_url and not font_path:
return False
else:
return True
35 changes: 11 additions & 24 deletions pyfonts/main.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,33 @@
from matplotlib.font_manager import FontProperties
from typing import Optional

from .get_font import _get_font_from_url, _get_local_font, _get_font_from_google
from .is_valid import _is_safe_input
from .get_font import _get_font_from_url, _get_local_font


def load_font(
font_url: Optional[str] = None,
font_path: Optional[str] = None,
font_name: Optional[str] = None,
weight: Optional[str] = None,
style: Optional[str] = None,
) -> FontProperties:
"""
Loads a font from one of the following:
- An url that points to a binary font file if `font_url`
- A locally stored font if `font_path`
- A font from Google font repo if `font_name`
Loads a FontProperties object from a remote Github repo or a local file.

Parameters:
- font_url (Optional[str]): A URL pointing to a binary font file.
- font_path (Optional[str]): The local file path of the font.
- font_name (Optional[str]): The name of the font to load from Google Fonts.
- weight (Optional[str]): The weight of the font to load.
- style (Optional[str]):
- font_url: A URL pointing to a binary font file from Github.
- font_path: The local file path of the font.

Returns:
- matplotlib.font_manager.FontProperties: A FontProperties object containing the loaded font.
"""

if not _is_safe_input(font_name, font_url, font_path):
if font_url and font_path:
raise ValueError(
"You must provide only one of the following: `font_name`, `font_url` or `font_path`."
"You must provide only one of the following: `font_url` or `font_path`."
)

if font_url:
elif font_url:
font = _get_font_from_url(font_url)

elif font_path:
font = _get_local_font(font_path)

elif font_name:
font = _get_font_from_google(font_name, weight=weight, style=style)

else:
raise ValueError(
"You must provide one of the following: `font_url` or `font_path`."
)
return font
5 changes: 1 addition & 4 deletions pyfonts/preview_font.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,11 @@
def preview_font(
font_url: Optional[str] = None,
font_path: Optional[str] = None,
font_name: Optional[str] = None,
weight: Optional[str] = None,
style: Optional[str] = None,
):
"""
Preview a font.
"""
font = load_font(font_url, font_path, font_name, weight, style)
font = load_font(font_url, font_path)

plt.figure(figsize=(10, 5))
plt.text(
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ authors = [
]
description = "A simple way to load fonts for matplotlib"
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.9"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
Expand All @@ -23,4 +23,4 @@ build-backend = "setuptools.build_meta"

[project.urls]
Homepage = "https://github.com/JosephBARBIERDARNAL/pyfonts"
Issues = "https://github.com/JosephBARBIERDARNAL/pyfonts/issues"
Issues = "https://github.com/JosephBARBIERDARNAL/pyfonts/issues"
17 changes: 2 additions & 15 deletions req.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import subprocess

packages = ["matplotlib"]
packages_dev = packages + ["pytest"]
packages = ["matplotlib", "pytest"]
REQUIREMENTS_FILE = "requirements.txt"
REQUIREMENTS_FILE_DEV = "requirements-dev.txt"


def get_package_version(package_name: str) -> str:
Expand Down Expand Up @@ -34,15 +32,4 @@ def get_package_version(package_name: str) -> str:
file.write(packageVersion + "\n")
else:
print(f"Version not found for package {package}")
print(f"{REQUIREMENTS_FILE} file updated\n\n")

with open(REQUIREMENTS_FILE_DEV, "w") as file:
for package in packages_dev:
version = get_package_version(package)
if version:
packageVersion = f"{package}=={version}"
print(packageVersion)
file.write(packageVersion + "\n")
else:
print(f"Version not found for package {package}")
print(f"{REQUIREMENTS_FILE_DEV} file updated")
print(f"\n{REQUIREMENTS_FILE} file updated")
2 changes: 0 additions & 2 deletions requirements-dev.txt

This file was deleted.

1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
matplotlib==3.9.1
pytest==8.3.2
14 changes: 1 addition & 13 deletions tests/test_is_valid.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
import pytest
from pyfonts.is_valid import _is_valid_raw_url, _is_url, _is_safe_input


def test_safe_input():
assert _is_safe_input("font_name", None, None) == True
assert _is_safe_input(None, "font_url", None) == True
assert _is_safe_input(None, None, "font_path") == True
assert _is_safe_input("font_name", "font_url", None) == False
assert _is_safe_input(None, "font_url", "font_path") == False
assert _is_safe_input("font_name", None, "font_path") == False
assert _is_safe_input("font_name", "font_url", "font_path") == False
assert _is_safe_input(None, None, None) == False
assert _is_safe_input("font_name", "font_url", "font_path") == False
from pyfonts.is_valid import _is_valid_raw_url, _is_url


@pytest.mark.parametrize(
Expand Down
30 changes: 0 additions & 30 deletions tests/test_load_font.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,6 @@
from pyfonts import load_font


@pytest.fixture(autouse=True)
def mock_imported_functions():
with patch("pyfonts.is_valid._is_safe_input") as mock_is_safe_input, patch(
"pyfonts.get_font._get_font_from_url"
) as mock_get_font_from_url, patch(
"pyfonts.get_font._get_local_font"
) as mock_get_local_font, patch(
"pyfonts.get_font._get_font_from_google"
) as mock_get_font_from_google:
mock_is_safe_input.return_value = True
mock_get_font_from_url.return_value = FontProperties()
mock_get_local_font.return_value = FontProperties()
mock_get_font_from_google.return_value = FontProperties()

yield (
mock_is_safe_input,
mock_get_font_from_url,
mock_get_local_font,
mock_get_font_from_google,
)


def test_load_font_with_url():
font = load_font(
font_url="https://github.com/JosephBARBIERDARNAL/pyfonts/blob/main/tests/Ultra-Regular.ttf?raw=true"
Expand All @@ -46,11 +24,3 @@ def test_load_font_invalid_input():
def test_load_font_no_input():
with pytest.raises(ValueError):
load_font()


def test_load_font_unsafe_input(mock_imported_functions):
mock_is_safe_input, _, _, _ = mock_imported_functions
mock_is_safe_input.return_value = False

with pytest.raises(ValueError):
load_font(font_url="http://example.com/font.ttf")
Loading