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

added automatic text size selection #15

Closed
wants to merge 5 commits into from

Conversation

Antohhin
Copy link
Contributor

@Antohhin Antohhin commented Jan 30, 2024

  • добавил папку с одним из популярных шрифтов /src/fonts/Gidole-Regular.ttf
  • новая функция подборки размера текста относительно размера картинки check_font_size()
    за этим стоит следующая идея:
  1. задать width_ratio какой пропорции относительно размера картинки текст должен быть
  2. задать начальные значения fontsize, learning_rate, где последнее это шаг с которым будем регулировать размер текста
  3. уменьшать/увеличивать текст пока не выбью breakpoint (идея как в бинарном поиске, чтоб поживее, но не перескочить)
  4. подгружаю шрифт с выбранным размером ImageFont.truetype(font_path, fontsize)

картинка в высоком разрешении

image2

шакальная картинка, честно говоря, так себе работает из-за супернизкого разрешения

image1

картинка для сравнения (справа старая вотермарка)

image3

@ohld
Copy link
Member

ohld commented Jan 30, 2024

Все статические файлы (не относящиеся к питоновскому коду) должны находиться в папке static.

@@ -88,8 +105,18 @@ def add_watermark(image_content: bytes) -> BytesIO | None:
return None

buff = BytesIO()
buff.name = 'image.jpeg'
buff.name = 'image_x.jpeg'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

почему поменял?)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тестил, забыл убрать

return buff
return buff#image

# if __name__ == '__main__':
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

закомментрированное нужно убрать

@Antohhin
Copy link
Contributor Author

Все статические файлы (не относящиеся к питоновскому коду) должны находиться в папке static.

папку fonts там создать или просто шрифт положить?

@ohld
Copy link
Member

ohld commented Jan 30, 2024

Папку fonts, да.

d = ImageDraw.Draw(txt)

width_ratio = .15 # Portion of the image the text width should be (between 0 and 1)
font_path = str(Path(Path.home(), "src", "fonts", font_family))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не уверен, что этот способ работы с путями сработает. Посмотри, как я с путями работаю в localizer, когда считываю yml файлы из папки static.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ага, понял
вообще я через докер поднимал, как в описании, тестил через Ipython и работало.
правильно понял, ты предлагаешь переписать через контекстный менеджер?

with open(localization_file, "r") as f:
            localizations |= yaml.safe_load(f)

if font.getlength(text) < breakpoint:
fontsize += learning_rate
else:
learning_rate = learning_rate // 2
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если честно я не понимаю, зачем тут бесконечный цикл и такой сложный алгоритм. Разве нельзя по размеру картинки прикинуть размер шрифта?

Copy link
Contributor Author

@Antohhin Antohhin Jan 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. шрифт — величина относительная (12, 18, 75 не понятно нифига это много или мало для картинки).
    поэтому, в моем видении, этот алгоритм занимается как раз прикидкой размера шрифта под размер картинки.
  2. по поводу while True — могу предложить другой вариант:
    сделать маленькое значение font и идти только на увеличение текста while font.getlength(text) < breakpoint
    будет работать быстрее, если мы как-то ограничены сверху по времени

@Antohhin Antohhin reopened this Feb 11, 2024
@ohld
Copy link
Member

ohld commented Feb 11, 2024

image

???

@Antohhin
Copy link
Contributor Author

image ???

win+wsl 😭
откачу, либо просто другой ПР создам

@Antohhin Antohhin closed this Feb 11, 2024
@Antohhin
Copy link
Contributor Author

Antohhin commented Feb 11, 2024

сделаю новый PR

@Antohhin Antohhin mentioned this pull request Feb 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants