Skip to content

Commit

Permalink
Clean up (#95)
Browse files Browse the repository at this point in the history
* Clean up
  • Loading branch information
barseghyanartur authored Dec 25, 2024
1 parent 7020d4c commit a01689f
Show file tree
Hide file tree
Showing 24 changed files with 214 additions and 182 deletions.
6 changes: 3 additions & 3 deletions .secrets.baseline
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@
"filename": "examples/django_example/project/settings/base.py",
"hashed_secret": "2e56b31925af569c194d2cc738d1f1bc22b63df0",
"is_verified": true,
"line_number": 66
"line_number": 67
}
],
"examples/sqlalchemy_example/faker_file_admin/alembic/versions/2695cb77cdf2_create_product_table.py": [
Expand Down Expand Up @@ -197,7 +197,7 @@
"filename": "src/faker_file/tests/test_sftp_server.py",
"hashed_secret": "e8662cfb96bd9c7fe84c31d76819ec3a92c80e63",
"is_verified": true,
"line_number": 84
"line_number": 86
}
],
"src/faker_file/tests/test_sftp_storage.py": [
Expand All @@ -219,5 +219,5 @@
}
]
},
"generated_at": "2024-11-14T22:15:37Z"
"generated_at": "2024-12-24T23:25:39Z"
}
61 changes: 43 additions & 18 deletions examples/customizations/marytts_mp3_generator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,48 @@ def generate(self: "MaryTtsMp3Generator") -> bytes:
# Initialize with args
mary_tts = MaryTTS(locale=self.locale, voice=self.voice)

# Generate temporary filename for WAV file
filename = tempfile.NamedTemporaryFile(
prefix="_merytts_", suffix=".wav"
).name

# Write WAV file
with open(filename, "wb") as file:
file.write(mary_tts.speak(self.content))

# Convert WAV to MP3
ffmpeg.input(filename).output(filename + ".mp3").run()

with open(filename + ".mp3", "rb") as _fake_file:
return_value = _fake_file.read()
# Create temporary WAV file in memory
with tempfile.NamedTemporaryFile(
delete=False,
suffix=".wav",
) as temp_wav:
temp_wav.write(mary_tts.speak(self.content))
temp_wav_path = temp_wav.name

# Convert WAV to MP3 and store in memory
with tempfile.NamedTemporaryFile(
delete=False,
suffix=".mp3",
) as temp_mp3:
ffmpeg.input(temp_wav_path).output(temp_mp3.name).run()

# Read the MP3 file content into memory
with open(temp_mp3.name, "rb") as mp3_file:
mp3_content = mp3_file.read()

# Clean up temporary files
os.remove(filename)
os.remove(filename + ".mp3")

return return_value
os.remove(temp_wav.name)
os.remove(temp_mp3.name)

return mp3_content

# # Generate temporary filename for WAV file
# filename = tempfile.NamedTemporaryFile(
# prefix="_merytts_", suffix=".wav"
# ).name
#
# # Write WAV file
# with open(filename, "wb") as file:
# file.write(mary_tts.speak(self.content))
#
# # Convert WAV to MP3
# ffmpeg.input(filename).output(filename + ".mp3").run()
#
# with open(filename + ".mp3", "rb") as _fake_file:
# return_value = _fake_file.read()
#
# # Clean up temporary files
# os.remove(filename)
# os.remove(filename + ".mp3")
#
# return return_value
5 changes: 2 additions & 3 deletions examples/django_example/project/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from contextlib import suppress

from .core import PROJECT_DIR

Expand Down Expand Up @@ -200,7 +201,5 @@


# Do not put any settings below this line
try:
with suppress(ImportError):
from .local_settings import * # noqa
except ImportError:
pass
Empty file.
Empty file.
68 changes: 29 additions & 39 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,40 @@
# verbose regular expressions by Black. Use [ ] to denote a significant space
# character.

#[tool.black]
#line-length = 80
#target-version = ['py37', 'py38', 'py39', 'py310', 'py311']
#include = '\.pyi?$'
#extend-exclude = '''
#/(
# # The following are specific to Black, you probably don't want those.
# | blib2to3
# | tests/data
# | profiling
# | migrations
#)/
#'''

# Build system information below.
# NOTE: You don't need this in your own Black configuration.
[build-system]
requires = ["setuptools>=41.0", "setuptools-scm", "wheel"]
build-backend = "setuptools.build_meta"

#[tool.isort]
#profile = "black"
#combine_as_imports = true
#multi_line_output = 3
#include_trailing_comma = true
#force_grid_wrap = 0
#use_parentheses = true
#ensure_newline_before_comments = true
#line_length = 80
##known_first_party = "faker_file"
#known_first_party = [
# "upload",
# "factories",
# "project",
# "faker_file_admin",
# "instance",
# "sqlalchemy_factories",
# "marytts_mp3_generator",
#]
#known_third_party = ["django", "factory", "faker_file"]
#skip = ["wsgi.py", "builddocs/"]

[tool.ruff]
line-length = 80


# Enable Pyflakes `E` and `F` codes by default.
lint.select = ["E", "F", "I"]
lint.ignore = []
lint.select = [
# "ANN", # Annotations: missing (return) types
"B", # Bugbear: common bug patterns or design problems
"C4", # Complexity: McCabe complexity checker
"E", # Pycodesyle: Style guide enforcement
"F", # Pyflakes: Source files errors
"G", # Logging format: Basic logging format errors
"I", # Isort: import sorting
"ISC", # Naming: Variable naming convention
"INP", # Implicit namespace packages: Check if __init__.py is present
"N", # Naming: Variable naming convention
"PERF", # Perflint: Performance linting
"Q",
"SIM", # Simplify: Helps simplify your code
"TD", # TO DO: Format TO DO comments
]
lint.ignore = [
"G004", # Allow use of f-string in logging
"ISC003", # Allow explicitly concatenated strings
# "N805", # Allow first argument of a method be named other than `self`
"TD002", # Allow to do without author
"TD003", # Allow to do without URL
]
# Enable autofix for formatting and import sorting
fix = true
src = [
Expand Down Expand Up @@ -84,14 +70,18 @@ exclude = [
"examples/django_example/project/wsgi.py",
"docs",
]
lint.per-file-ignores = {}

# Allow unused variables when underscore-prefixed.
lint.dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"

# Assume Python 3.10.
target-version = "py310"

[tool.ruff.lint.per-file-ignores]
"conftest.py" = [
"PERF203" # Allow `try`-`except` within a loop incurs performance overhead
]

[tool.ruff.lint.isort]
known-first-party = [
"upload",
Expand Down
8 changes: 4 additions & 4 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os
import re
from pathlib import Path

from setuptools import find_packages, setup

Expand All @@ -19,9 +19,9 @@ def clean_readme(text: str) -> str:
version = "0.17.14"

try:
readme = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
readme = clean_readme(readme)
except OSError:
readme_path = Path(__file__).parent / "README.rst"
readme = clean_readme(readme_path.read_text())
except FileNotFoundError:
readme = ""

dependency_links = []
Expand Down
8 changes: 5 additions & 3 deletions src/faker_file/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,13 @@ def returns_list(func: Callable) -> bool:
# If it's a list, check the type of its elements
element_type = getattr(return_type, "__args__", [None])[0]
element_origin = getattr(element_type, "__origin__", None)
if element_origin is Union:
if set(getattr(element_type, "__args__", [])) == {
if (
element_origin is Union
and set(getattr(element_type, "__args__", [])) == {
BytesValue,
StringValue,
}:
}
):
return True

return False
2 changes: 1 addition & 1 deletion src/faker_file/cli/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def get_method_kwargs(

kwargs = deepcopy(method_specs.args[1:]) # Omit `self`
defaults = deepcopy(method_specs.defaults if method_specs.defaults else [])
model_props = dict(zip(kwargs, defaults))
model_props = dict(zip(kwargs, defaults, strict=False))
annotations = deepcopy(method_specs.annotations)

# Override the type definition for mp3_generator_cls
Expand Down
8 changes: 4 additions & 4 deletions src/faker_file/contrib/docx_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ def add_page_break(provider, document, data, counter, **kwargs):

def add_paragraph(provider, document, data, counter, **kwargs):
"""Callable responsible for the paragraph generation."""
content = kwargs.get("content", None)
content = kwargs.get("content")
max_nb_chars = kwargs.get("max_nb_chars", 5_000)
wrap_chars_after = kwargs.get("wrap_chars_after", None)
wrap_chars_after = kwargs.get("wrap_chars_after")
format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC)

_content = provider._generate_text_content(
Expand All @@ -94,9 +94,9 @@ def add_paragraph(provider, document, data, counter, **kwargs):

def add_heading(provider, document, data, counter, **kwargs):
"""Callable responsible for the heading generation."""
content = kwargs.get("content", None)
content = kwargs.get("content")
max_nb_chars = kwargs.get("max_nb_chars", 30)
wrap_chars_after = kwargs.get("wrap_chars_after", None)
wrap_chars_after = kwargs.get("wrap_chars_after")
format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC)
level = kwargs.get("level", 0)

Expand Down
26 changes: 20 additions & 6 deletions src/faker_file/contrib/image/weasyprint_snippets.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,20 @@
__author__ = "Artur Barseghyan <[email protected]>"
__copyright__ = "2022-2023 Artur Barseghyan"
__license__ = "MIT"
__all__ = (
"add_h1_heading",
"add_h2_heading",
"add_h3_heading",
"add_h4_heading",
"add_h5_heading",
"add_h6_heading",
"add_heading",
"add_page_break",
"add_paragraph",
"add_picture",
"add_table",
"create_data_url",
)


def create_data_url(image_bytes: bytes, image_format: str) -> str:
Expand All @@ -31,10 +45,10 @@ def add_table(
# Begin the HTML table
table_html = "<table>"

for row_num in range(rows):
for _row_num in range(rows):
table_html += "<tr>"

for col_num in range(cols):
for _col_num in range(cols):
text = provider.generator.paragraph()
table_html += f"<td>{text}</td>"

Expand Down Expand Up @@ -93,9 +107,9 @@ def add_paragraph(
**kwargs,
):
"""Callable responsible for paragraph generation using pdfkit."""
content = kwargs.get("content", None)
content = kwargs.get("content")
max_nb_chars = kwargs.get("max_nb_chars", 5_000)
wrap_chars_after = kwargs.get("wrap_chars_after", None)
wrap_chars_after = kwargs.get("wrap_chars_after")
format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC)

_content = provider._generate_text_content(
Expand Down Expand Up @@ -126,9 +140,9 @@ def add_heading(
**kwargs,
):
"""Callable responsible for heading generation using pdfkit."""
content = kwargs.get("content", None)
content = kwargs.get("content")
max_nb_chars = kwargs.get("max_nb_chars", 30)
wrap_chars_after = kwargs.get("wrap_chars_after", None)
wrap_chars_after = kwargs.get("wrap_chars_after")
format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC)
level = kwargs.get("level", 1)
if level < 1 or level > 6:
Expand Down
14 changes: 7 additions & 7 deletions src/faker_file/contrib/odt_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ def add_table(provider, document, data, counter, **kwargs):

# Create table
table = Table()
for i in range(rows):
for _row_num in range(rows):
table.addElement(TableColumn(stylename=table_col_style))

for row in range(cols):
for _row in range(cols):
tr = TableRow(stylename=table_row_style)
table.addElement(tr)
for col in range(4):
for _col in range(4):
tc = TableCell(stylename=table_cell_style)
tr.addElement(tc)
text = provider.generator.paragraph()
Expand Down Expand Up @@ -121,9 +121,9 @@ def add_page_break(provider, document, data, counter, **kwargs):

def add_paragraph(provider, document, data, counter, **kwargs):
"""Callable responsible for the paragraph generation."""
content = kwargs.get("content", None)
content = kwargs.get("content")
max_nb_chars = kwargs.get("max_nb_chars", 5_000)
wrap_chars_after = kwargs.get("wrap_chars_after", None)
wrap_chars_after = kwargs.get("wrap_chars_after")
format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC)

_content = provider._generate_text_content(
Expand All @@ -146,9 +146,9 @@ def add_paragraph(provider, document, data, counter, **kwargs):

def add_heading(provider, document, data, counter, **kwargs):
"""Callable responsible for the heading generation."""
content = kwargs.get("content", None)
content = kwargs.get("content")
max_nb_chars = kwargs.get("max_nb_chars", 30)
wrap_chars_after = kwargs.get("wrap_chars_after", None)
wrap_chars_after = kwargs.get("wrap_chars_after")
format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC)
level = kwargs.get("level", 1)

Expand Down
Loading

0 comments on commit a01689f

Please sign in to comment.