File size: 2,978 Bytes
d55c26f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
65
66
67
68
import gradio as gr
import torch
from diffusers import StableDiffusionPipeline
from PIL import Image, ImageDraw, ImageFont
import os

# Загрузка модели (кэшируется)
def load_model():
    pipe = StableDiffusionPipeline.from_pretrained(
        "runwayml/stable-diffusion-v1-5",
        torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
        use_auth_token=os.environ.get("HF_TOKEN")
    )
    if torch.cuda.is_available():
        pipe = pipe.to("cuda")
    return pipe

pipe = load_model()

# Проверка наличия шрифта
font_path = "font.ttf"
if not os.path.exists(font_path):
    raise FileNotFoundError("Файл font.ttf не найден! Загрузите его в корень Space.")
font = ImageFont.truetype(font_path, size=40)

# Главная функция генерации
def generate_image(prompt, text_overlay, text_color, stroke_color, stroke_width):
    # Генерация фона
    with torch.no_grad():
        image = pipe(prompt, height=512, width=512).images[0]

    # Наложение текста
    draw = ImageDraw.Draw(image)
    text_bbox = draw.textbbox((0, 0), text_overlay, font=font)
    text_width = text_bbox[2] - text_bbox[0]
    text_height = text_bbox[3] - text_bbox[1]
    x = (512 - text_width) / 2
    y = (512 - text_height) / 2

    # Обводка
    for adj_x in range(-stroke_width, stroke_width + 1):
        for adj_y in range(-stroke_width, stroke_width + 1):
            if adj_x != 0 or adj_y != 0:
                draw.text((x + adj_x, y + adj_y), text_overlay, font=font, fill=stroke_color)
    # Основной текст
    draw.text((x, y), text_overlay, font=font, fill=text_color)
    return image

# Интерфейс на Gradio
with gr.Blocks(title="Генератор картинок с текстом") as demo:
    gr.Markdown("# 🎨 Создай картинку с русским текстом")
    gr.Markdown("Опиши фон, введи текст — и получи готовое изображение. Бесплатно, без ограничений.")

    with gr.Row():
        with gr.Column():
            prompt = gr.Textbox(label="Описание фона", value="осенний парк, золотые листья")
            text = gr.Textbox(label="Текст на картинке", value="Скидка 50%")
            color = gr.ColorPicker(label="Цвет текста", value="#FFFFFF")
            stroke = gr.ColorPicker(label="Цвет обводки", value="#000000")
            stroke_w = gr.Slider(0, 5, value=2, step=1, label="Толщина обводки")
            btn = gr.Button("Сгенерировать", variant="primary")
        with gr.Column():
            output = gr.Image(label="Результат", type="pil")

    btn.click(fn=generate_image, inputs=[prompt, text, color, stroke, stroke_w], outputs=output)

if __name__ == "__main__":
    demo.launch()