daswer123 commited on
Commit
b7ff52b
1 Parent(s): ea21152

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +42 -0
  2. funcs.py +70 -0
  3. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from funcs import process_image
3
+
4
+ def process_image_gradio(image_path, watermark_text, font_path, font_size, opacity, color, right_margin, bottom_margin):
5
+ # Вызываем функцию process_image из funcs.py
6
+ output_paths = process_image(image_path, "output", watermark_text, font_path.name, font_size, opacity, color, right_margin, bottom_margin)
7
+
8
+ # Cover obj to json str
9
+ generation_params_str = f"Watermark Text: {watermark_text}\nFont Size: {font_size}\nOpacity: {opacity}\nColor: {color}\nRight Margin: {right_margin}\nBottom Margin: {bottom_margin}"
10
+
11
+ # Возвращаем путь к изображению с водяным знаком
12
+ return output_paths[0], output_paths[1], generation_params_str
13
+
14
+ # Определяем интерфейс с использованием Gradio
15
+ with gr.Blocks() as demo:
16
+ with gr.Row():
17
+ with gr.Column():
18
+ # Компоненты для настроек
19
+ image = gr.Image(label="Upload Image", type="filepath")
20
+ font_path = gr.File(label="Font Path", file_types=[".ttf"])
21
+ watermark_text = gr.Textbox(label="Watermark Text")
22
+ font_size = gr.Slider(minimum=6, maximum=100, step=1, label="Font Size", value=30)
23
+ opacity = gr.Slider(minimum=0, maximum=1, step=0.01, label="Opacity", value=0.5)
24
+ color = gr.ColorPicker(label="Color",value="#000000")
25
+ right_margin = gr.Slider(minimum=0, maximum=1, step=0.01, label="Right Margin", value=0.05)
26
+ bottom_margin = gr.Slider(minimum=0, maximum=1, step=0.01, label="Bottom Margin", value=0.02)
27
+
28
+ with gr.Column():
29
+ # Компонент для отображения результата
30
+ process_button = gr.Button("Process Image")
31
+ generation_params = gr.Textbox(label="Generation Parameters",interactive=False,show_copy_button=True)
32
+ output_image = gr.Image(label="Output Image",interactive=False)
33
+ output_mini = gr.Image(label="Output Image (Mini)",interactive=False)
34
+
35
+
36
+
37
+ # Обработчик нажатия кнопки "Process Image"
38
+ process_button.click(process_image_gradio, inputs=[image, watermark_text, font_path, font_size, opacity, color, right_margin, bottom_margin], outputs=[output_image,output_mini,generation_params])
39
+
40
+ # Запускаем интерфейс
41
+ demo.queue()
42
+ demo.launch()
funcs.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ from PIL import Image, ImageDraw, ImageFont
4
+
5
+ def add_watermark(image, watermark_text, font_path, font_size, opacity, color, right_margin, bottom_margin):
6
+ # Load the custom font
7
+ font = ImageFont.truetype(font_path, font_size)
8
+
9
+ # Create a drawing context
10
+ draw = ImageDraw.Draw(image)
11
+
12
+ # Get the image dimensions
13
+ image_width, image_height = image.size
14
+
15
+ # Calculate the position for the watermark
16
+ text_bbox = draw.textbbox((0, 0), watermark_text, font=font)
17
+ text_width = text_bbox[2] - text_bbox[0]
18
+ text_height = text_bbox[3] - text_bbox[1] + math.floor(font_size / 2)
19
+ x = image_width - text_width - int(image_width * right_margin)
20
+ y = image_height - text_height - int(image_height * bottom_margin) # Добавляем отступ снизу
21
+
22
+ # Create a new image for the watermark with alpha channel
23
+ watermark = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 0))
24
+ watermark_draw = ImageDraw.Draw(watermark)
25
+
26
+ # Convert the color tuple to a hexadecimal color string
27
+ hex_color = "#%02x%02x%02x" % color
28
+
29
+ print(color, hex_color)
30
+
31
+ # Draw the watermark text on the new image
32
+ watermark_draw.text((0, 0), watermark_text, font=font, fill=color + (int(255 * opacity),))
33
+
34
+ # Paste the watermark onto the original image
35
+ image.paste(watermark, (x, y), mask=watermark)
36
+
37
+
38
+
39
+ def process_image(image_path, output_dir, watermark_text=None, font_path=None, font_size=30, opacity=0.5,
40
+ color="#000000", right_margin=0.05, bottom_margin=0.02):
41
+ # Convert the color string to a tuple
42
+ color_tuple = tuple(int(color.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
43
+
44
+ # Create output folder
45
+ os.makedirs(output_dir, exist_ok=True)
46
+
47
+ # Открываем исходное изображение
48
+ with Image.open(image_path) as img:
49
+ # Конвертируем изображение в режим RGBA, если необходимо
50
+ if img.mode != 'RGBA':
51
+ img = img.convert('RGBA')
52
+
53
+ # Добавляем водяной знак на исходное изображение, если указан текст
54
+ if watermark_text and font_path:
55
+ add_watermark(img, watermark_text, font_path, font_size, opacity, color_tuple, right_margin, bottom_margin)
56
+
57
+ # Сохраняем исходное изображение с водяным знаком
58
+ watermarked_file = os.path.join(output_dir, 'watermarked.png')
59
+ img.save(watermarked_file, format='PNG')
60
+
61
+ # Создаем миниатюру изображения
62
+ thumbnail_size = (200, 200) # Укажите нужный размер миниатюры
63
+ img.thumbnail(thumbnail_size)
64
+
65
+ # Сохраняем миниатюру
66
+ thumbnail_file = os.path.join(output_dir, 'thumbnail.png')
67
+ img.save(thumbnail_file, format='PNG')
68
+
69
+ # Возвращаем список с путями к полученным файлам
70
+ return [watermarked_file, thumbnail_file]
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio
2
+ pillow