omarbajouk commited on
Commit
85ae317
·
verified ·
1 Parent(s): 7dad692

Update src/graphics.py

Browse files
Files changed (1) hide show
  1. src/graphics.py +65 -55
src/graphics.py CHANGED
@@ -1,6 +1,6 @@
1
  import os
2
  import uuid
3
- from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageOps
4
  from .config import TMP_DIR, W, H, THEMES, FONT_REG, FONT_BOLD
5
 
6
  # ----------------------------------------------------------------------
@@ -8,20 +8,16 @@ from .config import TMP_DIR, W, H, THEMES, FONT_REG, FONT_BOLD
8
  # ----------------------------------------------------------------------
9
 
10
  def safe_name(base):
11
- """Crée un nom de fichier sûr sans caractères spéciaux."""
12
  import re
13
  return re.sub(r'[^a-zA-Z0-9_-]+', '_', str(base)).strip('_')
14
 
15
  def _wrap_text(text, font, max_width, draw):
16
- """Découpe le texte pour qu’il tienne dans la largeur donnée."""
17
  words = text.split()
18
- lines = []
19
- line = ""
20
-
21
  for word in words:
22
- test_line = f"{line} {word}".strip()
23
- if draw.textlength(test_line, font=font) <= max_width:
24
- line = test_line
25
  else:
26
  lines.append(line)
27
  line = word
@@ -29,15 +25,14 @@ def _wrap_text(text, font, max_width, draw):
29
  lines.append(line)
30
  return "\n".join(lines)
31
 
32
- def _draw_text_shadow(draw, position, text, font, fill, shadow_color=(0, 0, 0)):
33
- """Dessine un texte avec ombre portée pour plus de lisibilité."""
34
- x, y = position
35
- shadow_offset = 3
36
- draw.text((x + shadow_offset, y + shadow_offset), text, font=font, fill=shadow_color)
37
  draw.text((x, y), text, font=font, fill=fill)
38
 
39
  # ----------------------------------------------------------------------
40
- # 🎨 Création du fond d’écran pour capsule
41
  # ----------------------------------------------------------------------
42
 
43
  def make_background(
@@ -48,34 +43,36 @@ def make_background(
48
  logo_path=None,
49
  logo_pos="haut-gauche",
50
  image_fond=None,
51
- fond_mode="plein écran"
 
 
52
  ):
53
  """
54
- Crée une image de fond personnalisée pour une capsule :
55
- - couleur et thème
56
- - logo et position
57
- - texte à l’écran
58
- - image de fond optionnelle
59
  """
60
 
61
- print(f"[Fond] Création du fond - Thème: {theme}")
62
 
63
  try:
64
  # ---- Définir les couleurs du thème ----
65
  couleur_1 = tuple(THEMES.get(theme, THEMES["Bleu Professionnel"])["primary"])
66
  couleur_2 = tuple(THEMES.get(theme, THEMES["Bleu Professionnel"])["secondary"])
67
 
68
- # ---- Créer un fond uni (ou gradient léger) ----
69
  bg = Image.new("RGB", (W, H), couleur_1)
70
  overlay = Image.new("RGB", (W, H), couleur_2)
71
  bg = Image.blend(bg, overlay, alpha=0.25)
72
-
73
  draw = ImageDraw.Draw(bg)
74
 
75
- # ---- Ajouter l’image de fond ----
76
  if image_fond and os.path.exists(image_fond):
77
- try:
78
- img = Image.open(image_fond).convert("RGB")
 
 
79
  if fond_mode == "plein écran":
80
  img = img.resize((W, H))
81
  bg.paste(img, (0, 0))
@@ -88,34 +85,48 @@ def make_background(
88
  elif fond_mode == "moitié bas":
89
  img = img.resize((W, H // 2))
90
  bg.paste(img, (0, H // 2))
91
- print(f"[Fond] ✅ Image de fond ajoutée ({fond_mode})")
92
- except Exception as e:
93
- print(f"[Fond] ⚠️ Erreur chargement image fond: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  # ---- Ajouter le logo ----
96
  if logo_path and os.path.exists(logo_path):
97
- try:
98
- logo = Image.open(logo_path).convert("RGBA")
99
- max_logo_w = int(W * 0.25)
100
- ratio = max_logo_w / logo.width
101
- logo = logo.resize((max_logo_w, int(logo.height * ratio)))
102
- margin = 50
103
-
104
- if logo_pos == "haut-gauche":
105
- pos = (margin, margin)
106
- elif logo_pos == "haut-droite":
107
- pos = (W - logo.width - margin, margin)
108
- elif logo_pos == "centre":
109
- pos = ((W - logo.width) // 2, (H - logo.height) // 2)
110
- else:
111
- pos = (margin, margin)
112
-
113
- bg.paste(logo, pos, mask=logo)
114
- print(f"[Fond] ✅ Logo ajouté à la position {logo_pos}")
115
- except Exception as e:
116
- print(f"[Fond] ⚠️ Erreur logo: {e}")
117
-
118
- # ---- Ajouter le texte principal ----
119
  font_title = ImageFont.truetype(FONT_BOLD, 80)
120
  font_sub = ImageFont.truetype(FONT_REG, 60)
121
  font_body = ImageFont.truetype(FONT_REG, 50)
@@ -133,12 +144,11 @@ def make_background(
133
  texte_multilignes = _wrap_text(texte_ecran, font_body, max_width, draw)
134
  _draw_text_shadow(draw, (margin_x, y_pos), texte_multilignes, font_body, fill=(255, 255, 255))
135
 
136
- # ---- Sauvegarder le fond dans un fichier unique ----
137
  fond_name = safe_name(titre) if titre else uuid.uuid4().hex[:6]
138
  out_path = os.path.join(TMP_DIR, f"fond_{fond_name}.png")
139
  bg.save(out_path)
140
- print(f"[Fond] ✅ Fond sauvegardé pour la capsule : {out_path}")
141
-
142
  return out_path
143
 
144
  except Exception as e:
 
1
  import os
2
  import uuid
3
+ from PIL import Image, ImageDraw, ImageFont
4
  from .config import TMP_DIR, W, H, THEMES, FONT_REG, FONT_BOLD
5
 
6
  # ----------------------------------------------------------------------
 
8
  # ----------------------------------------------------------------------
9
 
10
  def safe_name(base):
 
11
  import re
12
  return re.sub(r'[^a-zA-Z0-9_-]+', '_', str(base)).strip('_')
13
 
14
  def _wrap_text(text, font, max_width, draw):
 
15
  words = text.split()
16
+ lines, line = [], ""
 
 
17
  for word in words:
18
+ test = f"{line} {word}".strip()
19
+ if draw.textlength(test, font=font) <= max_width:
20
+ line = test
21
  else:
22
  lines.append(line)
23
  line = word
 
25
  lines.append(line)
26
  return "\n".join(lines)
27
 
28
+ def _draw_text_shadow(draw, pos, text, font, fill, shadow_color=(0, 0, 0)):
29
+ x, y = pos
30
+ s = 3
31
+ draw.text((x + s, y + s), text, font=font, fill=shadow_color)
 
32
  draw.text((x, y), text, font=font, fill=fill)
33
 
34
  # ----------------------------------------------------------------------
35
+ # 🎨 Création du fond + insertion d’image flexible
36
  # ----------------------------------------------------------------------
37
 
38
  def make_background(
 
43
  logo_path=None,
44
  logo_pos="haut-gauche",
45
  image_fond=None,
46
+ fond_mode="plein écran",
47
+ photo_mode="fond", # 🆕 "fond", "normal", ou "plein"
48
+ photo_pos="centre" # 🆕 Position si "normal"
49
  ):
50
  """
51
+ Crée un fond pour la capsule :
52
+ - photo_mode='fond' → image intégrée au fond
53
+ - photo_mode='normal' → image ajoutée par-dessus à une position donnée
54
+ - photo_mode='plein' → image superposée sur tout l'écran au-dessus du fond
 
55
  """
56
 
57
+ print(f"[Fond] Création du fond - Thème: {theme}, Mode photo: {photo_mode}")
58
 
59
  try:
60
  # ---- Définir les couleurs du thème ----
61
  couleur_1 = tuple(THEMES.get(theme, THEMES["Bleu Professionnel"])["primary"])
62
  couleur_2 = tuple(THEMES.get(theme, THEMES["Bleu Professionnel"])["secondary"])
63
 
64
+ # ---- Créer le fond uni / dégradé ----
65
  bg = Image.new("RGB", (W, H), couleur_1)
66
  overlay = Image.new("RGB", (W, H), couleur_2)
67
  bg = Image.blend(bg, overlay, alpha=0.25)
 
68
  draw = ImageDraw.Draw(bg)
69
 
70
+ # ---- Ajouter l’image selon le mode choisi ----
71
  if image_fond and os.path.exists(image_fond):
72
+ img = Image.open(image_fond).convert("RGBA")
73
+
74
+ if photo_mode == "fond":
75
+ # === Mode fond (classique) ===
76
  if fond_mode == "plein écran":
77
  img = img.resize((W, H))
78
  bg.paste(img, (0, 0))
 
85
  elif fond_mode == "moitié bas":
86
  img = img.resize((W, H // 2))
87
  bg.paste(img, (0, H // 2))
88
+ print(f"[Fond] ✅ Image appliquée comme fond ({fond_mode})")
89
+
90
+ elif photo_mode == "normal":
91
+ # === Mode image superposée ===
92
+ max_photo_w = int(W * 0.4)
93
+ ratio = max_photo_w / img.width
94
+ img = img.resize((max_photo_w, int(img.height * ratio)))
95
+
96
+ pos_map = {
97
+ "haut-gauche": (50, 50),
98
+ "haut-droite": (W - img.width - 50, 50),
99
+ "bas-gauche": (50, H - img.height - 50),
100
+ "bas-droite": (W - img.width - 50, H - img.height - 50),
101
+ "centre": ((W - img.width) // 2, (H - img.height) // 2)
102
+ }
103
+ bg.paste(img, pos_map.get(photo_pos, (50, 50)), mask=img)
104
+ print(f"[Fond] ✅ Photo ajoutée en mode normal ({photo_pos})")
105
+
106
+ elif photo_mode == "plein":
107
+ # === Mode superposition plein écran ===
108
+ img = img.resize((W, H))
109
+ bg.paste(img, (0, 0), mask=img)
110
+ print("[Fond] ✅ Photo superposée en plein écran (au-dessus du fond)")
111
 
112
  # ---- Ajouter le logo ----
113
  if logo_path and os.path.exists(logo_path):
114
+ logo = Image.open(logo_path).convert("RGBA")
115
+ max_logo_w = int(W * 0.25)
116
+ ratio = max_logo_w / logo.width
117
+ logo = logo.resize((max_logo_w, int(logo.height * ratio)))
118
+ margin = 50
119
+
120
+ pos_map = {
121
+ "haut-gauche": (margin, margin),
122
+ "haut-droite": (W - logo.width - margin, margin),
123
+ "centre": ((W - logo.width) // 2, (H - logo.height) // 2)
124
+ }
125
+ pos = pos_map.get(logo_pos, (margin, margin))
126
+ bg.paste(logo, pos, mask=logo)
127
+ print(f"[Fond] ✅ Logo ajouté à la position {logo_pos}")
128
+
129
+ # ---- Ajouter le texte ----
 
 
 
 
 
 
130
  font_title = ImageFont.truetype(FONT_BOLD, 80)
131
  font_sub = ImageFont.truetype(FONT_REG, 60)
132
  font_body = ImageFont.truetype(FONT_REG, 50)
 
144
  texte_multilignes = _wrap_text(texte_ecran, font_body, max_width, draw)
145
  _draw_text_shadow(draw, (margin_x, y_pos), texte_multilignes, font_body, fill=(255, 255, 255))
146
 
147
+ # ---- Sauvegarde ----
148
  fond_name = safe_name(titre) if titre else uuid.uuid4().hex[:6]
149
  out_path = os.path.join(TMP_DIR, f"fond_{fond_name}.png")
150
  bg.save(out_path)
151
+ print(f"[Fond] ✅ Fond sauvegardé : {out_path}")
 
152
  return out_path
153
 
154
  except Exception as e: