Atom78 commited on
Commit
d55c26f
·
verified ·
1 Parent(s): b28f85a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from diffusers import StableDiffusionPipeline
4
+ from PIL import Image, ImageDraw, ImageFont
5
+ import os
6
+
7
+ # Загрузка модели (кэшируется)
8
+ def load_model():
9
+ pipe = StableDiffusionPipeline.from_pretrained(
10
+ "runwayml/stable-diffusion-v1-5",
11
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
12
+ use_auth_token=os.environ.get("HF_TOKEN")
13
+ )
14
+ if torch.cuda.is_available():
15
+ pipe = pipe.to("cuda")
16
+ return pipe
17
+
18
+ pipe = load_model()
19
+
20
+ # Проверка наличия шрифта
21
+ font_path = "font.ttf"
22
+ if not os.path.exists(font_path):
23
+ raise FileNotFoundError("Файл font.ttf не найден! Загрузите его в корень Space.")
24
+ font = ImageFont.truetype(font_path, size=40)
25
+
26
+ # Главная функция генерации
27
+ def generate_image(prompt, text_overlay, text_color, stroke_color, stroke_width):
28
+ # Генерация фона
29
+ with torch.no_grad():
30
+ image = pipe(prompt, height=512, width=512).images[0]
31
+
32
+ # Наложение текста
33
+ draw = ImageDraw.Draw(image)
34
+ text_bbox = draw.textbbox((0, 0), text_overlay, font=font)
35
+ text_width = text_bbox[2] - text_bbox[0]
36
+ text_height = text_bbox[3] - text_bbox[1]
37
+ x = (512 - text_width) / 2
38
+ y = (512 - text_height) / 2
39
+
40
+ # Обводка
41
+ for adj_x in range(-stroke_width, stroke_width + 1):
42
+ for adj_y in range(-stroke_width, stroke_width + 1):
43
+ if adj_x != 0 or adj_y != 0:
44
+ draw.text((x + adj_x, y + adj_y), text_overlay, font=font, fill=stroke_color)
45
+ # Основной текст
46
+ draw.text((x, y), text_overlay, font=font, fill=text_color)
47
+ return image
48
+
49
+ # Интерфейс на Gradio
50
+ with gr.Blocks(title="Генератор картинок с текстом") as demo:
51
+ gr.Markdown("# 🎨 Создай картинку с русским текстом")
52
+ gr.Markdown("Опиши фон, введи текст — и получи готовое изображение. Бесплатно, без ограничений.")
53
+
54
+ with gr.Row():
55
+ with gr.Column():
56
+ prompt = gr.Textbox(label="Описание фона", value="осенний парк, золотые листья")
57
+ text = gr.Textbox(label="Текст на картинке", value="Скидка 50%")
58
+ color = gr.ColorPicker(label="Цвет текста", value="#FFFFFF")
59
+ stroke = gr.ColorPicker(label="Цвет обводки", value="#000000")
60
+ stroke_w = gr.Slider(0, 5, value=2, step=1, label="Толщина обводки")
61
+ btn = gr.Button("Сгенерировать", variant="primary")
62
+ with gr.Column():
63
+ output = gr.Image(label="Результат", type="pil")
64
+
65
+ btn.click(fn=generate_image, inputs=[prompt, text, color, stroke, stroke_w], outputs=output)
66
+
67
+ if __name__ == "__main__":
68
+ demo.launch()