File size: 32,462 Bytes
4ffe0a9
 
 
 
 
 
861f22f
4ffe0a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
861f22f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ffe0a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
861f22f
4ffe0a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
861f22f
4ffe0a9
861f22f
 
 
 
 
 
 
 
 
 
 
 
 
4ffe0a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
861f22f
4ffe0a9
 
 
 
 
 
 
 
861f22f
4ffe0a9
861f22f
 
 
 
 
 
 
 
 
 
 
 
 
4ffe0a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
861f22f
4ffe0a9
 
 
 
 
 
 
 
 
 
 
 
 
 
861f22f
4ffe0a9
 
 
 
 
 
 
 
 
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
from fastapi import APIRouter, Query, HTTPException
from fastapi.responses import StreamingResponse
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import requests
import re
from typing import Optional, List, Tuple, Union

router = APIRouter()

def download_image_from_url(url: str) -> Image.Image:
    headers = {
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/115.0.0.0 Safari/537.36"
        )
    }
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        return Image.open(BytesIO(response.content)).convert("RGBA")
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Erro ao baixar imagem: {url} ({str(e)})")

def resize_and_crop_to_fill(img: Image.Image, target_width: int, target_height: int) -> Image.Image:
    img_ratio = img.width / img.height
    target_ratio = target_width / target_height

    if img_ratio > target_ratio:
        scale_height = target_height
        scale_width = int(scale_height * img_ratio)
    else:
        scale_width = target_width
        scale_height = int(scale_width / img_ratio)

    img_resized = img.resize((scale_width, scale_height), Image.LANCZOS)
    left = (scale_width - target_width) // 2
    top = (scale_height - target_height) // 2
    return img_resized.crop((left, top, left + target_width, top + target_height))

def parse_image_urls(image_url_param: Union[str, List[str]]) -> List[str]:
    """Converte o parâmetro de URL(s) em lista de URLs"""
    if isinstance(image_url_param, list):
        return image_url_param
    elif isinstance(image_url_param, str):
        # Se contém vírgulas, divide em múltiplas URLs
        if ',' in image_url_param:
            return [url.strip() for url in image_url_param.split(',') if url.strip()]
        else:
            return [image_url_param]
    return []

def create_collage_background(image_urls: List[str], canvas_width: int, canvas_height: int) -> Image.Image:
    """Cria uma colagem como fundo baseada na lista de URLs para Instagram"""
    num_images = len(image_urls)
    border_size = 4 if num_images > 1 else 0  # Linha mais fina e elegante

    images = [download_image_from_url(url) for url in image_urls]
    canvas = Image.new("RGBA", (canvas_width, canvas_height), (255, 255, 255, 255))

    if num_images == 1:
        img = resize_and_crop_to_fill(images[0], canvas_width, canvas_height)
        canvas.paste(img, (0, 0))

    elif num_images == 2:
        # Lado a lado
        slot_width = (canvas_width - border_size) // 2
        img1 = resize_and_crop_to_fill(images[0], slot_width, canvas_height)
        img2 = resize_and_crop_to_fill(images[1], slot_width, canvas_height)
        canvas.paste(img1, (0, 0))
        canvas.paste(img2, (slot_width + border_size, 0))

    elif num_images == 3:
        # Layout: 2 em cima, 1 embaixo
        half_height = (canvas_height - border_size) // 2
        half_width = (canvas_width - border_size) // 2
        img1 = resize_and_crop_to_fill(images[0], half_width, half_height)
        img2 = resize_and_crop_to_fill(images[1], half_width, half_height)
        img3 = resize_and_crop_to_fill(images[2], canvas_width, half_height)
        canvas.paste(img1, (0, 0))
        canvas.paste(img2, (half_width + border_size, 0))
        canvas.paste(img3, (0, half_height + border_size))

    elif num_images == 4:
        # Layout 2x2
        half_height = (canvas_height - border_size) // 2
        half_width = (canvas_width - border_size) // 2
        img1 = resize_and_crop_to_fill(images[0], half_width, half_height)
        img2 = resize_and_crop_to_fill(images[1], half_width, half_height)
        img3 = resize_and_crop_to_fill(images[2], half_width, half_height)
        img4 = resize_and_crop_to_fill(images[3], half_width, half_height)
        canvas.paste(img1, (0, 0))
        canvas.paste(img2, (half_width + border_size, 0))
        canvas.paste(img3, (0, half_height + border_size))
        canvas.paste(img4, (half_width + border_size, half_height + border_size))

    elif num_images == 5:
        # Layout: 2 em cima, 3 embaixo
        top_height = (canvas_height - border_size) * 2 // 5
        bottom_height = canvas_height - top_height - border_size
        half_width = (canvas_width - border_size) // 2

        img1 = resize_and_crop_to_fill(images[0], half_width, top_height)
        img2 = resize_and_crop_to_fill(images[1], half_width, top_height)
        canvas.paste(img1, (0, 0))
        canvas.paste(img2, (half_width + border_size, 0))

        y_offset = top_height + border_size
        third_width = (canvas_width - 2 * border_size) // 3
        third_width_last = canvas_width - (third_width * 2 + border_size * 2)
        
        img3 = resize_and_crop_to_fill(images[2], third_width, bottom_height)
        img4 = resize_and_crop_to_fill(images[3], third_width, bottom_height)
        img5 = resize_and_crop_to_fill(images[4], third_width_last, bottom_height)
        canvas.paste(img3, (0, y_offset))
        canvas.paste(img4, (third_width + border_size, y_offset))
        canvas.paste(img5, (third_width * 2 + border_size * 2, y_offset))

    elif num_images == 6:
        # Layout 3x2
        half_height = (canvas_height - border_size) // 2
        third_width = (canvas_width - 2 * border_size) // 3
        third_width_last = canvas_width - (third_width * 2 + border_size * 2)

        # Primeira linha
        img1 = resize_and_crop_to_fill(images[0], third_width, half_height)
        img2 = resize_and_crop_to_fill(images[1], third_width, half_height)
        img3 = resize_and_crop_to_fill(images[2], third_width, half_height)
        canvas.paste(img1, (0, 0))
        canvas.paste(img2, (third_width + border_size, 0))
        canvas.paste(img3, (third_width * 2 + border_size * 2, 0))

        # Segunda linha
        y_offset = half_height + border_size
        img4 = resize_and_crop_to_fill(images[3], third_width, half_height)
        img5 = resize_and_crop_to_fill(images[4], third_width, half_height)
        img6 = resize_and_crop_to_fill(images[5], third_width_last, half_height)
        canvas.paste(img4, (0, y_offset))
        canvas.paste(img5, (third_width + border_size, y_offset))
        canvas.paste(img6, (third_width * 2 + border_size * 2, y_offset))

    else:
        raise HTTPException(status_code=400, detail="Apenas até 6 imagens são suportadas.")

    return canvas

def create_gradient_overlay(width: int, height: int, positions: List[str], expanded: bool = False) -> Image.Image:
    gradient = Image.new("RGBA", (width, height))
    draw = ImageDraw.Draw(gradient)
    
    for position in positions:
        if position.lower() == "bottom":
            if expanded:
                # Gradiente expandido para quando há texto + citação
                gradient_start = 500  # Começar mais alto
                gradient_height = 850  # Mais altura para cobrir ambos
            else:
                # Gradiente normal
                gradient_start = 650  # Começar mais baixo para ser mais sutil
                gradient_height = 700  # Altura menor para gradiente mais localizado
            
            for y in range(gradient_height):
                if y + gradient_start < height:
                    ratio = y / gradient_height
                    # Gradiente muito mais suave com opacidades menores
                    if ratio <= 0.3:
                        opacity = int(255 * 0.15 * (ratio / 0.3))  # Começar muito sutil
                    elif ratio <= 0.6:
                        opacity = int(255 * (0.15 + 0.20 * ((ratio - 0.3) / 0.3)))  # Crescimento gradual
                    else:
                        opacity = int(255 * (0.35 + 0.15 * ((ratio - 0.6) / 0.4)))  # Max de 50% de opacidade
                    
                    current_pixel = gradient.getpixel((0, y + gradient_start))
                    combined_opacity = min(255, current_pixel[3] + opacity)
                    draw.line([(0, y + gradient_start), (width, y + gradient_start)], fill=(0, 0, 0, combined_opacity))
        
        elif position.lower() == "top":
            if expanded:
                # Gradiente expandido para quando há texto + citação
                gradient_height = 850  # Maior altura para cobrir ambos
            else:
                # Gradiente normal
                gradient_height = 650  # Menor altura para ser mais sutil
            
            for y in range(gradient_height):
                if y < height:
                    ratio = (gradient_height - y) / gradient_height
                    # Opacidades muito menores para efeito mais sutil
                    if ratio <= 0.2:
                        opacity = int(255 * 0.12 * (ratio / 0.2))  # Muito sutil no início
                    elif ratio <= 0.5:
                        opacity = int(255 * (0.12 + 0.18 * ((ratio - 0.2) / 0.3)))  # Crescimento suave
                    else:
                        opacity = int(255 * (0.30 + 0.15 * ((ratio - 0.5) / 0.5)))  # Max de 45%
                    
                    current_pixel = gradient.getpixel((0, y))
                    combined_opacity = min(255, current_pixel[3] + opacity)
                    draw.line([(0, y), (width, y)], fill=(0, 0, 0, combined_opacity))
    
    return gradient

class TextSegment:
    def __init__(self, text: str, is_bold: bool = False, is_italic: bool = False):
        self.text = text
        self.is_bold = is_bold
        self.is_italic = is_italic

def parse_text_with_formatting(text: str) -> List[TextSegment]:
    pattern = r'(<(?:strong|em)>.*?</(?:strong|em)>|<(?:strong|em)><(?:strong|em)>.*?</(?:strong|em)></(?:strong|em)>)'
    parts = re.split(pattern, text)
    segments = []
    
    for part in parts:
        if not part:
            continue
            
        if match := re.match(r'<strong><em>(.*?)</em></strong>|<em><strong>(.*?)</strong></em>', part):
            content = match.group(1) or match.group(2)
            segments.append(TextSegment(content, True, True))
        elif match := re.match(r'<strong>(.*?)</strong>', part):
            segments.append(TextSegment(match.group(1), True, False))
        elif match := re.match(r'<em>(.*?)</em>', part):
            segments.append(TextSegment(match.group(1), False, True))
        else:
            segments.append(TextSegment(part, False, False))
    
    return segments

def get_font(segment: TextSegment, regular_font: ImageFont.FreeTypeFont, 
            bold_font: ImageFont.FreeTypeFont, italic_font: ImageFont.FreeTypeFont,
            bold_italic_font: ImageFont.FreeTypeFont) -> ImageFont.FreeTypeFont:
    if segment.is_bold and segment.is_italic:
        return bold_italic_font
    elif segment.is_bold:
        return bold_font
    elif segment.is_italic:
        return italic_font
    return regular_font

def wrap_text_with_formatting(segments: List[TextSegment], regular_font: ImageFont.FreeTypeFont, 
                             bold_font: ImageFont.FreeTypeFont, italic_font: ImageFont.FreeTypeFont,
                             bold_italic_font: ImageFont.FreeTypeFont, max_width: int, 
                             draw: ImageDraw.Draw) -> List[List[TextSegment]]:
    lines = []
    current_line = []
    current_width = 0
    first_in_line = True
    
    for segment in segments:
        if not segment.text:
            continue
            
        font = get_font(segment, regular_font, bold_font, italic_font, bold_italic_font)
        
        words = re.split(r'(\s+)', segment.text)
        
        for word in words:
            if not word:
                continue
                
            if re.match(r'\s+', word):
                if not first_in_line:
                    current_line.append(TextSegment(word, segment.is_bold, segment.is_italic))
                    current_width += draw.textlength(word, font=font)
                continue
            
            word_width = draw.textlength(word, font=font)
            
            if current_width + word_width <= max_width or first_in_line:
                current_line.append(TextSegment(word, segment.is_bold, segment.is_italic))
                current_width += word_width
                first_in_line = False
            else:
                if current_line:
                    lines.append(current_line)
                current_line = [TextSegment(word, segment.is_bold, segment.is_italic)]
                current_width = word_width
                first_in_line = False
    
    if current_line:
        lines.append(current_line)
    
    return lines

def wrap_simple_text(text: str, font: ImageFont.FreeTypeFont, max_width: int, 
                    draw: ImageDraw.Draw) -> List[str]:
    words = text.split()
    lines = []
    current_line = []
    
    for word in words:
        test_line = ' '.join(current_line + [word])
        if draw.textlength(test_line, font=font) <= max_width or not current_line:
            current_line.append(word)
        else:
            if current_line:
                lines.append(' '.join(current_line))
            current_line = [word]
    
    if current_line:
        lines.append(' '.join(current_line))
    
    return lines

def get_responsive_fonts(text: str, regular_font_path: str, bold_font_path: str, 
                        italic_font_path: str, bold_italic_font_path: str,
                        max_width: int, max_lines: int, max_font_size: int, min_font_size: int, 
                        draw: ImageDraw.Draw) -> Tuple[ImageFont.FreeTypeFont, ImageFont.FreeTypeFont, 
                        ImageFont.FreeTypeFont, ImageFont.FreeTypeFont, List[List[TextSegment]], int]:
    segments = parse_text_with_formatting(text)
    current_font_size = max_font_size
    
    while current_font_size >= min_font_size:
        try:
            fonts = [ImageFont.truetype(path, current_font_size) 
                    for path in [regular_font_path, bold_font_path, italic_font_path, bold_italic_font_path]]
            regular_font, bold_font, italic_font, bold_italic_font = fonts
        except Exception:
            fonts = [ImageFont.load_default()] * 4
            regular_font, bold_font, italic_font, bold_italic_font = fonts
        
        lines = wrap_text_with_formatting(segments, regular_font, bold_font, italic_font, bold_italic_font, max_width, draw)
        
        if len(lines) <= max_lines:
            return regular_font, bold_font, italic_font, bold_italic_font, lines, current_font_size
        
        current_font_size -= 1
    
    return regular_font, bold_font, italic_font, bold_italic_font, lines, min_font_size

def get_responsive_single_font(text: str, font_path: str, max_width: int, max_lines: int, 
                              max_font_size: int, min_font_size: int, draw: ImageDraw.Draw,
                              format_text: bool = False) -> Tuple[ImageFont.FreeTypeFont, List[str], int]:
    formatted_text = f"{text}" if format_text else text
    current_font_size = max_font_size
    
    while current_font_size >= min_font_size:
        try:
            font = ImageFont.truetype(font_path, current_font_size)
        except Exception:
            font = ImageFont.load_default()
        
        lines = wrap_simple_text(formatted_text, font, max_width, draw)
        
        if len(lines) <= max_lines:
            return font, lines, current_font_size
        
        current_font_size -= 2
    
    return font, lines, min_font_size

def draw_formatted_line(draw: ImageDraw.Draw, line_segments: List[TextSegment], 
                       x: int, y: int, regular_font: ImageFont.FreeTypeFont, 
                       bold_font: ImageFont.FreeTypeFont, italic_font: ImageFont.FreeTypeFont,
                       bold_italic_font: ImageFont.FreeTypeFont, color: tuple = (255, 255, 255)):
    current_x = x
    
    for segment in line_segments:
        font = get_font(segment, regular_font, bold_font, italic_font, bold_italic_font)
        draw.text((current_x, y), segment.text, font=font, fill=color)
        current_x += draw.textlength(segment.text, font=font)

def get_text_color_rgb(text_color: str) -> tuple[int, int, int]:
    """
    Converte o parâmetro text_color para RGB.
    """
    if text_color.lower() == "black":
        return (0, 0, 0)
    else:  # white por padrão
        return (255, 255, 255)

def get_device_dimensions() -> tuple[int, int]:
    return (1080, 1350)

def add_logo(canvas: Image.Image):
    try:
        logo = Image.open("recurve.png").convert("RGBA")
        logo_resized = logo.resize((121, 23))
        
        logo_with_opacity = Image.new("RGBA", logo_resized.size)
        for x in range(logo_resized.width):
            for y in range(logo_resized.height):
                r, g, b, a = logo_resized.getpixel((x, y))
                logo_with_opacity.putpixel((x, y), (r, g, b, int(a * 0.42)))
        
        canvas.paste(logo_with_opacity, (891, 1274), logo_with_opacity)
    except Exception as e:
        print(f"Aviso: Erro ao carregar a logo: {e}")

def create_canvas(image_url: Optional[Union[str, List[str]]], text: Optional[str], text_position: str = "bottom",
                 citation: Optional[str] = None, citation_direction: str = "bottom", 
                 text_color: str = "white") -> BytesIO:
    width, height = get_device_dimensions()
    padding_x, top_padding, citation_text_gap = 60, 60, 15
    max_width = width - 2 * padding_x
    text_rgb = get_text_color_rgb(text_color)

    # Validação das combinações de posições
    if text:
        valid_combinations = {
            "top": ["text-bottom", "text-top", "bottom"],
            "bottom": ["text-top", "text-bottom", "top"]
        }
        
        if citation and citation_direction not in valid_combinations.get(text_position, []):
            raise HTTPException(
                status_code=400, 
                detail=f"Combinação inválida: text_position='{text_position}' com citation_direction='{citation_direction}'. "
                      f"Para text_position='{text_position}', use citation_direction em: {valid_combinations.get(text_position, [])}"
            )

    canvas = Image.new("RGBA", (width, height), color=(255, 255, 255, 255))

    # Processar imagem(s) - suporte para colagem
    if image_url:
        parsed_urls = parse_image_urls(image_url)
        if parsed_urls:
            if len(parsed_urls) > 6:
                raise HTTPException(status_code=400, detail="Máximo de 6 imagens permitidas")
            
            if len(parsed_urls) == 1:
                # Uma única imagem - comportamento original
                img = download_image_from_url(parsed_urls[0])
                filled_img = resize_and_crop_to_fill(img, width, height)
                canvas.paste(filled_img, (0, 0))
            else:
                # Múltiplas imagens - criar colagem
                canvas = create_collage_background(parsed_urls, width, height)

    # Determinar posições do gradiente e se precisa expandir
    # Só aplicar gradiente se o texto não for preto
    gradient_positions = []
    needs_expanded_gradient = False
    
    if text_color.lower() != "black":
        if text and text_position.lower() == "bottom":
            gradient_positions.append("bottom")
            # Se há citação com text-top, expande o gradiente bottom
            if citation and citation_direction.lower() == "text-top":
                needs_expanded_gradient = True
        elif text and text_position.lower() == "top":
            gradient_positions.append("top")
            # Se há citação com text-bottom, expande o gradiente top
            if citation and citation_direction.lower() == "text-bottom":
                needs_expanded_gradient = True
        
        # Adicionar gradientes para citações em posições fixas
        if citation and citation_direction.lower() == "top" and "top" not in gradient_positions:
            gradient_positions.append("top")
        elif citation and citation_direction.lower() == "bottom" and "bottom" not in gradient_positions:
            gradient_positions.append("bottom")
    
    if gradient_positions:
        gradient_overlay = create_gradient_overlay(width, height, gradient_positions, needs_expanded_gradient)
        canvas = Image.alpha_composite(canvas, gradient_overlay)

    add_logo(canvas)

    if text or citation:
        canvas_rgb = canvas.convert("RGB")
        draw = ImageDraw.Draw(canvas_rgb)
        
        font_paths = {
            'regular': "fonts/WorkSans-Regular.ttf",
            'bold': "fonts/WorkSans-SemiBold.ttf",
            'italic': "fonts/WorkSans-Italic.ttf",
            'bold_italic': "fonts/WorkSans-SemiBoldItalic.ttf",
            'citation': "fonts/AGaramondPro-Semibold.ttf"
        }

        text_lines, text_height, citation_lines, citation_height = [], 0, [], 0
        
        if text:
            try:
                regular_font, bold_font, italic_font, bold_italic_font, text_lines, font_size = get_responsive_fonts(
                    text, font_paths['regular'], font_paths['bold'], font_paths['italic'], 
                    font_paths['bold_italic'], max_width, 5, 35, 15, draw
                )
                text_height = len(text_lines) * int(font_size * 1.2)
            except Exception:
                text_lines = [[TextSegment(word, False, False) for word in text.split()]]
                text_height = 40

        if citation:
            try:
                citation_font, citation_lines, citation_font_size = get_responsive_single_font(
                    citation, font_paths['citation'], max_width, 3, 60, 30, draw, True
                )
                citation_height = len(citation_lines) * int(citation_font_size * 1.05)
            except Exception:
                citation_lines = [citation]
                citation_height = 40

        # Calcular posições respeitando os limites da imagem
        text_y = citation_y = 0
        bottom_limit = 1274 - 50  # Limite inferior (antes da logo)
        
        if text and citation:
            # Calcular espaço total necessário quando há texto e citação
            total_gap = citation_text_gap if citation_direction in ["text-top", "text-bottom"] else 0
            total_content_height = text_height + citation_height + total_gap
            
            if citation_direction.lower() == "text-top":
                # Citação acima do texto
                if text_position.lower() == "bottom":
                    # Posicionar do bottom para cima
                    text_y = min(bottom_limit - text_height, bottom_limit - text_height)
                    citation_y = text_y - citation_text_gap - citation_height
                    # Verificar se vaza pelo topo
                    if citation_y < top_padding:
                        # Reajustar para caber tudo
                        available_height = bottom_limit - top_padding
                        if total_content_height <= available_height:
                            citation_y = top_padding
                            text_y = citation_y + citation_height + citation_text_gap
                else:  # text top
                    # Posicionar do top para baixo
                    citation_y = top_padding
                    text_y = citation_y + citation_height + citation_text_gap
                    # Verificar se vaza pelo bottom
                    if text_y + text_height > bottom_limit:
                        # Reajustar para caber tudo
                        available_height = bottom_limit - top_padding
                        if total_content_height <= available_height:
                            text_y = bottom_limit - text_height
                            citation_y = text_y - citation_text_gap - citation_height
            
            elif citation_direction.lower() == "text-bottom":
                # Citação abaixo do texto
                if text_position.lower() == "bottom":
                    # Posicionar do bottom para cima
                    citation_y = bottom_limit - citation_height
                    text_y = citation_y - citation_text_gap - text_height
                    # Verificar se vaza pelo topo
                    if text_y < top_padding:
                        # Reajustar para caber tudo
                        available_height = bottom_limit - top_padding
                        if total_content_height <= available_height:
                            text_y = top_padding
                            citation_y = text_y + text_height + citation_text_gap
                else:  # text top
                    # Posicionar do top para baixo
                    text_y = top_padding
                    citation_y = text_y + text_height + citation_text_gap
                    # Verificar se vaza pelo bottom
                    if citation_y + citation_height > bottom_limit:
                        # Reajustar para caber tudo
                        available_height = bottom_limit - top_padding
                        if total_content_height <= available_height:
                            citation_y = bottom_limit - citation_height
                            text_y = citation_y - citation_text_gap - text_height
            
            elif citation_direction.lower() == "top":
                # Citação no topo, texto na posição original
                citation_y = top_padding
                if text_position.lower() == "bottom":
                    text_y = bottom_limit - text_height
                else:
                    # Evitar sobreposição
                    text_y = max(top_padding + citation_height + citation_text_gap, top_padding)
            
            elif citation_direction.lower() == "bottom":
                # Citação no bottom, texto na posição original
                citation_y = bottom_limit - citation_height
                if text_position.lower() == "top":
                    text_y = top_padding
                else:
                    # Evitar sobreposição
                    text_y = min(bottom_limit - text_height, citation_y - citation_text_gap - text_height)
        
        elif text:
            # Apenas texto, posições fixas originais
            if text_position.lower() == "bottom":
                text_y = bottom_limit - text_height
            else:
                text_y = top_padding
        
        elif citation:
            # Apenas citação
            if citation_direction.lower() == "top":
                citation_y = top_padding
            elif citation_direction.lower() == "bottom":
                citation_y = bottom_limit - citation_height

        # Desenhar citação
        if citation_lines:
            line_height = int(citation_font_size * 1.05) if 'citation_font_size' in locals() else 40
            for i, line in enumerate(citation_lines):
                draw.text((padding_x, citation_y + i * line_height), line, 
                         font=citation_font if 'citation_font' in locals() else ImageFont.load_default(), 
                         fill=text_rgb)

        # Desenhar texto
        if text_lines:
            line_height = int(font_size * 1.2) if 'font_size' in locals() else 40
            for i, line in enumerate(text_lines):
                if 'regular_font' in locals():
                    draw_formatted_line(draw, line, padding_x, text_y + i * line_height, 
                                      regular_font, bold_font, italic_font, bold_italic_font, text_rgb)
                else:
                    draw.text((padding_x, text_y + i * line_height), ' '.join([s.text for s in line]), 
                             font=ImageFont.load_default(), fill=text_rgb)
        
        canvas = canvas_rgb.convert("RGBA")

    buffer = BytesIO()
    canvas.convert("RGB").save(buffer, format="PNG")
    buffer.seek(0)
    return buffer

def create_cover_canvas(image_url: Optional[Union[str, List[str]]], title: Optional[str], title_position: str = "bottom",
                       text_color: str = "white") -> BytesIO:
    width, height = get_device_dimensions()
    padding_x, top_padding = 60, 60
    max_width = width - 2 * padding_x
    text_rgb = get_text_color_rgb(text_color)

    canvas = Image.new("RGBA", (width, height), color=(255, 255, 255, 255))

    # Processar imagem(s) - suporte para colagem
    if image_url:
        parsed_urls = parse_image_urls(image_url)
        if parsed_urls:
            if len(parsed_urls) > 6:
                raise HTTPException(status_code=400, detail="Máximo de 6 imagens permitidas")
            
            if len(parsed_urls) == 1:
                # Uma única imagem - comportamento original
                img = download_image_from_url(parsed_urls[0])
                filled_img = resize_and_crop_to_fill(img, width, height)
                canvas.paste(filled_img, (0, 0))
            else:
                # Múltiplas imagens - criar colagem
                canvas = create_collage_background(parsed_urls, width, height)

    gradient_positions = []
    # Só aplicar gradiente se o texto não for preto
    if title and text_color.lower() != "black":
        gradient_positions.append(title_position.lower())
    
    if gradient_positions:
        gradient_overlay = create_gradient_overlay(width, height, gradient_positions)
        canvas = Image.alpha_composite(canvas, gradient_overlay)

    add_logo(canvas)

    if title:
        canvas_rgb = canvas.convert("RGB")
        draw = ImageDraw.Draw(canvas_rgb)
        
        try:
            title_font, title_lines, title_font_size = get_responsive_single_font(
                title, "fonts/AGaramondPro-Regular.ttf", max_width, 3, 85, 40, draw
            )
            title_line_height = int(title_font_size * 1.2)
            title_height = len(title_lines) * title_line_height
        except Exception:
            title_font = ImageFont.load_default()
            title_lines = [title]
            title_line_height = title_height = 50

        title_y = (1274 - 50 - title_height) if title_position.lower() == "bottom" else top_padding

        for i, line in enumerate(title_lines):
            draw.text((padding_x, title_y + i * title_line_height), line, font=title_font, fill=text_rgb)
        
        canvas = canvas_rgb.convert("RGBA")

    buffer = BytesIO()
    canvas.convert("RGB").save(buffer, format="PNG")
    buffer.seek(0)
    return buffer

@router.get("/create/image")
def get_news_image(
    image_url: Optional[Union[str, List[str]]] = Query(None, description="URL da imagem ou lista de URLs separadas por vírgula para colagem (máximo 6)"),
    text: Optional[str] = Query(None, description="Texto com suporte a tags <strong>"),
    text_position: str = Query("bottom", description="Posição do texto: 'top' para topo ou 'bottom' para parte inferior"),
    citation: Optional[str] = Query(None, description="Texto da citação"),
    citation_direction: str = Query("bottom", description="Posição da citação: 'top', 'bottom' ou 'text-top'"),
    text_color: str = Query("white", description="Cor do texto: 'white' (padrão) ou 'black'. Se 'black', remove o gradiente de fundo")
):
    try:
        buffer = create_canvas(image_url, text, text_position, citation, citation_direction, text_color)
        return StreamingResponse(buffer, media_type="image/png")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro ao gerar imagem: {str(e)}")

@router.get("/create/cover/image")
def get_cover_image(
    image_url: Optional[Union[str, List[str]]] = Query(None, description="URL da imagem ou lista de URLs separadas por vírgula para colagem (máximo 6)"),
    title: Optional[str] = Query(None, description="Título da capa"),
    title_position: str = Query("bottom", description="Posição do título: 'top' para topo ou 'bottom' para parte inferior"),
    text_color: str = Query("white", description="Cor do texto: 'white' (padrão) ou 'black'. Se 'black', remove o gradiente de fundo")
):
    try:
        buffer = create_cover_canvas(image_url, title, title_position, text_color)
        return StreamingResponse(buffer, media_type="image/png")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro ao gerar imagem: {str(e)}")