Astridkraft commited on
Commit
d0e1b15
·
verified ·
1 Parent(s): 74554e3

Update text_integration.py

Browse files
Files changed (1) hide show
  1. text_integration.py +106 -58
text_integration.py CHANGED
@@ -1,6 +1,66 @@
1
  from PIL import Image, ImageDraw, ImageFont
2
  import gradio as gr
3
  import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  def add_text_to_image(image, text, text_x, text_y, font_size="80px", font_family="Roboto", font_color="Weiß"):
6
  """Fügt Text mit PIL zum Bild hinzu mit Formatierungsoptionen"""
@@ -15,14 +75,14 @@ def add_text_to_image(image, text, text_x, text_y, font_size="80px", font_family
15
  image_with_text = image.copy()
16
  draw = ImageDraw.Draw(image_with_text)
17
 
18
- # Schriftgröße direkt aus dem Dropdown-Wert extrahieren (z.B. "80px" -> 80)
19
  try:
20
  pixel_size = int(font_size.replace("px", ""))
21
  print(f"Schriftgröße direkt: {font_size} -> {pixel_size}px")
22
  except:
23
- pixel_size = 80 # Fallback
24
 
25
- # Schriftfarbe Mapping - schwarz, weiß, rot
26
  color_mapping = {
27
  "Weiß": "white",
28
  "Schwarz": "black",
@@ -32,28 +92,32 @@ def add_text_to_image(image, text, text_x, text_y, font_size="80px", font_family
32
  actual_color = color_mapping.get(font_color, "white")
33
  print(f"Schriftfarbe Mapping: {font_color} -> {actual_color}")
34
 
35
- # NEU: 3 garantierte TrueType-Schriftarten mit relativen Pfaden
36
- font_paths = {
37
- "Roboto": "./fonts/Roboto-Regular.ttf",
38
- "Open Sans": "./fonts/OpenSans-Regular.ttf",
39
- "DejaVu Sans": "./fonts/DejaVuSans.ttf"
40
- }
41
 
42
- try:
43
- font_path = font_paths.get(font_family, "./fonts/Roboto-Regular.ttf")
44
- font = ImageFont.truetype(font_path, pixel_size)
45
- print(f"Schriftart geladen: {font_family} mit Größe {pixel_size}px")
46
-
47
- except Exception as font_error:
48
- print(f"Fehler beim Laden der Schriftart {font_family}: {font_error}")
49
- # Fallback: Versuche die erste verfügbare Schriftart
50
  try:
51
- font = ImageFont.truetype("./fonts/Roboto-Regular.ttf", pixel_size)
52
- print(f"Fallback auf Roboto mit Größe {pixel_size}px")
53
- except:
54
- # Letzter Fallback - sollte nicht passieren wenn Schriftarten vorhanden sind
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  font = ImageFont.load_default()
56
- print(f"KRITISCH: Keine TrueType-Schriftart gefunden! Verwende Default (nicht skalierbar)")
57
 
58
  # Text zeichnen
59
  draw.text((text_x, text_y), text, fill=actual_color, font=font)
@@ -65,22 +129,19 @@ def add_text_to_image(image, text, text_x, text_y, font_size="80px", font_family
65
  return image
66
 
67
  def create_text_preview(image, text, text_x, text_y, font_size="80px", font_family="Roboto", font_color="Weiß"):
68
- """Erstellt eine Vorschau mit Text und rotem Marker - nur EINEN Punkt"""
69
  if image is None:
70
  return image
71
 
72
  try:
73
- # Konvertiere numpy array zu PIL Image falls nötig
74
  if isinstance(image, np.ndarray):
75
  image = Image.fromarray(image)
76
 
77
- # Immer vom Originalbild starten, nicht von der vorherigen Vorschau
78
  preview = image.copy()
79
  draw = ImageDraw.Draw(preview)
80
 
81
- # Nur roten Marker zeichnen wenn Text vorhanden UND Position nicht Standard (100,100)
82
  if text and text_x is not None and text_y is not None and (text_x != 100 or text_y != 100):
83
- # Rote Marker an Textposition
84
  marker_radius = 8
85
  marker_color = (255, 0, 0)
86
  draw.ellipse([
@@ -90,15 +151,13 @@ def create_text_preview(image, text, text_x, text_y, font_size="80px", font_fami
90
  text_y + marker_radius
91
  ], fill=marker_color)
92
 
93
- # Text zeichnen wenn vorhanden
94
  if text:
95
- # Schriftgröße direkt aus dem Dropdown-Wert extrahieren
96
  try:
97
  pixel_size = int(font_size.replace("px", ""))
98
  except:
99
  pixel_size = 80
100
 
101
- # Schriftfarbe Mapping für Vorschau
102
  color_mapping = {
103
  "Weiß": "white",
104
  "Schwarz": "black",
@@ -107,24 +166,24 @@ def create_text_preview(image, text, text_x, text_y, font_size="80px", font_fami
107
 
108
  actual_color = color_mapping.get(font_color, "white")
109
 
110
- # NEU: Gleiche Schriftart-Logik wie in add_text_to_image
111
- font_paths = {
112
- "Roboto": "./fonts/Roboto-Regular.ttf",
113
- "Open Sans": "./fonts/OpenSans-Regular.ttf",
114
- "DejaVu Sans": "./fonts/DejaVuSans.ttf"
115
- }
116
 
117
- try:
118
- font_path = font_paths.get(font_family, "./fonts/Roboto-Regular.ttf")
119
- font = ImageFont.truetype(font_path, pixel_size)
120
- except Exception as font_error:
121
- print(f"Fehler beim Laden der Schriftart für Vorschau: {font_error}")
122
- # Fallback
123
  try:
124
- font = ImageFont.truetype("./fonts/Roboto-Regular.ttf", pixel_size)
125
  except:
 
 
 
 
 
 
 
 
 
 
126
  font = ImageFont.load_default()
127
- print("WARNUNG: Fallback auf nicht-skalierbare Default-Schriftart")
128
 
129
  draw.text((text_x, text_y), text, fill=actual_color, font=font)
130
  print(f"Vorschau: Text mit Größe {pixel_size}px, Farbe {actual_color} gezeichnet")
@@ -135,31 +194,25 @@ def create_text_preview(image, text, text_x, text_y, font_size="80px", font_fami
135
  print(f"Fehler bei Text-Vorschau: {e}")
136
  return image
137
 
 
138
  def update_text_preview_i2i(original_image, generated_image, text, text_x, text_y, target_selector):
139
- """Aktualisiert die Text-Vorschau für Bild-zu-Bild"""
140
  if target_selector == "Originalbild":
141
  target_image = original_image
142
- else: # "Generiertes Bild"
143
  target_image = generated_image
144
-
145
  return create_text_preview(target_image, text, text_x, text_y)
146
 
147
  def update_text_preview_t2i(image, text, text_x, text_y, font_size, font_family, font_color):
148
- """Aktualisiert die Text-Vorschau für Text-zu-Bild mit Formatierung"""
149
  print(f"Update Vorschau - Größe: {font_size}, Schrift: {font_family}, Farbe: {font_color}")
150
  return create_text_preview(image, text, text_x, text_y, font_size, font_family, font_color)
151
 
152
  def capture_click(event: gr.SelectData):
153
- """Handhabt Klicks in beiden Tabs"""
154
  if event and hasattr(event, 'index'):
155
  print(f"🎯 CLICK ERFOLGREICH: ({event.index[0]}, {event.index[1]})")
156
  return event.index[0], event.index[1]
157
- print("❌ CLICK FEHLGESCHLAGEN - Event oder Index fehlt")
158
  return 100, 100
159
 
160
  def create_text_integration_section_t2i():
161
- """Erstellt die UI-Komponenten für Text-Integration in Text-zu-Bild"""
162
-
163
  with gr.Row():
164
  gr.Markdown("### 📝 Text auf Bild integrieren")
165
 
@@ -171,7 +224,6 @@ def create_text_integration_section_t2i():
171
  scale=3
172
  )
173
 
174
- # TEXT-FORMATIERUNGSOPTIONEN
175
  with gr.Row():
176
  with gr.Column():
177
  font_size_t2i = gr.Dropdown(
@@ -181,7 +233,7 @@ def create_text_integration_section_t2i():
181
  )
182
  with gr.Column():
183
  font_family_t2i = gr.Dropdown(
184
- choices=["Roboto", "Open Sans", "DejaVu Sans"], # NEU: 3 TrueType-Schriftarten
185
  value="Roboto",
186
  label="Schriftart"
187
  )
@@ -193,7 +245,6 @@ def create_text_integration_section_t2i():
193
  )
194
 
195
  with gr.Row():
196
- # Start mit None statt 100, damit kein Marker an Standard-Position
197
  text_x_t2i = gr.Number(value=None, visible=False)
198
  text_y_t2i = gr.Number(value=None, visible=False)
199
 
@@ -203,8 +254,6 @@ def create_text_integration_section_t2i():
203
  return text_input_t2i, text_x_t2i, text_y_t2i, font_size_t2i, font_family_t2i, font_color_t2i, text_btn_t2i
204
 
205
  def create_text_integration_section_i2i():
206
- """Erstellt die UI-Komponenten für Text-Integration in Bild-zu-Bild"""
207
-
208
  with gr.Row():
209
  gr.Markdown("### 📝 Text auf Bild integrieren")
210
 
@@ -217,7 +266,6 @@ def create_text_integration_section_i2i():
217
  )
218
 
219
  with gr.Row():
220
- # Start mit None statt 100, damit kein Marker an Standard-Position
221
  text_x_i2i = gr.Number(value=None, visible=False)
222
  text_y_i2i = gr.Number(value=None, visible=False)
223
 
 
1
  from PIL import Image, ImageDraw, ImageFont
2
  import gradio as gr
3
  import numpy as np
4
+ import os
5
+ import requests
6
+ import tempfile
7
+
8
+ # URLs zu freien Schriftarten auf GitHub
9
+ FONT_URLS = {
10
+ "Roboto": "https://github.com/google/fonts/raw/main/apache/roboto/Roboto-Regular.ttf",
11
+ "Open Sans": "https://github.com/google/fonts/raw/main/apache/opensans/OpenSans-Regular.ttf",
12
+ "DejaVu Sans": "https://github.com/dejavu-fonts/dejavu-fonts/raw/master/ttf/DejaVuSans.ttf"
13
+ }
14
+
15
+ def download_font(font_name):
16
+ """Lädt eine Schriftart von GitHub herunter und gibt den lokalen Pfad zurück"""
17
+ try:
18
+ if font_name not in FONT_URLS:
19
+ return None
20
+
21
+ # Temporäre Datei erstellen
22
+ temp_dir = tempfile.gettempdir()
23
+ font_path = os.path.join(temp_dir, f"{font_name.replace(' ', '_')}.ttf")
24
+
25
+ # Wenn bereits vorhanden, wiederverwenden
26
+ if os.path.exists(font_path):
27
+ print(f"✅ Schriftart bereits vorhanden: {font_path}")
28
+ return font_path
29
+
30
+ # Schriftart von GitHub downloaden
31
+ print(f"⬇️ Lade Schriftart herunter: {font_name}")
32
+ response = requests.get(FONT_URLS[font_name], timeout=30)
33
+ response.raise_for_status()
34
+
35
+ # Schriftart speichern
36
+ with open(font_path, 'wb') as f:
37
+ f.write(response.content)
38
+
39
+ print(f"✅ Schriftart heruntergeladen: {font_path}")
40
+ return font_path
41
+
42
+ except Exception as e:
43
+ print(f"❌ Fehler beim Download von {font_name}: {e}")
44
+ return None
45
+
46
+ def get_available_font():
47
+ """Gibt eine verfügbare Schriftart zurück (Download falls nötig)"""
48
+ # Versuche zuerst Roboto
49
+ roboto_path = download_font("Roboto")
50
+ if roboto_path:
51
+ return roboto_path
52
+
53
+ # Fallback zu Open Sans
54
+ open_sans_path = download_font("Open Sans")
55
+ if open_sans_path:
56
+ return open_sans_path
57
+
58
+ # Letzter Fallback zu DejaVu Sans
59
+ dejavu_path = download_font("DejaVu Sans")
60
+ if dejavu_path:
61
+ return dejavu_path
62
+
63
+ return None
64
 
65
  def add_text_to_image(image, text, text_x, text_y, font_size="80px", font_family="Roboto", font_color="Weiß"):
66
  """Fügt Text mit PIL zum Bild hinzu mit Formatierungsoptionen"""
 
75
  image_with_text = image.copy()
76
  draw = ImageDraw.Draw(image_with_text)
77
 
78
+ # Schriftgröße direkt aus dem Dropdown-Wert extrahieren
79
  try:
80
  pixel_size = int(font_size.replace("px", ""))
81
  print(f"Schriftgröße direkt: {font_size} -> {pixel_size}px")
82
  except:
83
+ pixel_size = 80
84
 
85
+ # Schriftfarbe Mapping
86
  color_mapping = {
87
  "Weiß": "white",
88
  "Schwarz": "black",
 
92
  actual_color = color_mapping.get(font_color, "white")
93
  print(f"Schriftfarbe Mapping: {font_color} -> {actual_color}")
94
 
95
+ # NEU: Schriftart downloaden oder vorhandene verwenden
96
+ font_path = download_font(font_family)
 
 
 
 
97
 
98
+ if font_path:
 
 
 
 
 
 
 
99
  try:
100
+ font = ImageFont.truetype(font_path, pixel_size)
101
+ print(f" TrueType-Schriftart geladen: {font_family} mit Größe {pixel_size}px")
102
+ except Exception as e:
103
+ print(f"❌ Fehler beim Laden der Schriftart {font_family}: {e}")
104
+ # Fallback auf andere Schriftart
105
+ fallback_font = get_available_font()
106
+ if fallback_font:
107
+ font = ImageFont.truetype(fallback_font, pixel_size)
108
+ print(f"⚠️ Fallback auf: {fallback_font}")
109
+ else:
110
+ font = ImageFont.load_default()
111
+ print("⚠️ Fallback auf Default-Schriftart (nicht skalierbar)")
112
+ else:
113
+ # Fallback falls Download fehlschlägt
114
+ fallback_font = get_available_font()
115
+ if fallback_font:
116
+ font = ImageFont.truetype(fallback_font, pixel_size)
117
+ print(f"⚠️ Download fehlgeschlagen - verwende Fallback: {fallback_font}")
118
+ else:
119
  font = ImageFont.load_default()
120
+ print("⚠️ Keine TrueType-Schriftart verfügbar - verwende Default (nicht skalierbar)")
121
 
122
  # Text zeichnen
123
  draw.text((text_x, text_y), text, fill=actual_color, font=font)
 
129
  return image
130
 
131
  def create_text_preview(image, text, text_x, text_y, font_size="80px", font_family="Roboto", font_color="Weiß"):
132
+ """Erstellt eine Vorschau mit Text und rotem Marker"""
133
  if image is None:
134
  return image
135
 
136
  try:
 
137
  if isinstance(image, np.ndarray):
138
  image = Image.fromarray(image)
139
 
 
140
  preview = image.copy()
141
  draw = ImageDraw.Draw(preview)
142
 
143
+ # Rote Marker
144
  if text and text_x is not None and text_y is not None and (text_x != 100 or text_y != 100):
 
145
  marker_radius = 8
146
  marker_color = (255, 0, 0)
147
  draw.ellipse([
 
151
  text_y + marker_radius
152
  ], fill=marker_color)
153
 
154
+ # Text zeichnen
155
  if text:
 
156
  try:
157
  pixel_size = int(font_size.replace("px", ""))
158
  except:
159
  pixel_size = 80
160
 
 
161
  color_mapping = {
162
  "Weiß": "white",
163
  "Schwarz": "black",
 
166
 
167
  actual_color = color_mapping.get(font_color, "white")
168
 
169
+ # Gleiche Schriftart-Logik wie oben
170
+ font_path = download_font(font_family)
 
 
 
 
171
 
172
+ if font_path:
 
 
 
 
 
173
  try:
174
+ font = ImageFont.truetype(font_path, pixel_size)
175
  except:
176
+ fallback_font = get_available_font()
177
+ if fallback_font:
178
+ font = ImageFont.truetype(fallback_font, pixel_size)
179
+ else:
180
+ font = ImageFont.load_default()
181
+ else:
182
+ fallback_font = get_available_font()
183
+ if fallback_font:
184
+ font = ImageFont.truetype(fallback_font, pixel_size)
185
+ else:
186
  font = ImageFont.load_default()
 
187
 
188
  draw.text((text_x, text_y), text, fill=actual_color, font=font)
189
  print(f"Vorschau: Text mit Größe {pixel_size}px, Farbe {actual_color} gezeichnet")
 
194
  print(f"Fehler bei Text-Vorschau: {e}")
195
  return image
196
 
197
+ # Rest der Funktionen bleibt gleich wie vorher...
198
  def update_text_preview_i2i(original_image, generated_image, text, text_x, text_y, target_selector):
 
199
  if target_selector == "Originalbild":
200
  target_image = original_image
201
+ else:
202
  target_image = generated_image
 
203
  return create_text_preview(target_image, text, text_x, text_y)
204
 
205
  def update_text_preview_t2i(image, text, text_x, text_y, font_size, font_family, font_color):
 
206
  print(f"Update Vorschau - Größe: {font_size}, Schrift: {font_family}, Farbe: {font_color}")
207
  return create_text_preview(image, text, text_x, text_y, font_size, font_family, font_color)
208
 
209
  def capture_click(event: gr.SelectData):
 
210
  if event and hasattr(event, 'index'):
211
  print(f"🎯 CLICK ERFOLGREICH: ({event.index[0]}, {event.index[1]})")
212
  return event.index[0], event.index[1]
 
213
  return 100, 100
214
 
215
  def create_text_integration_section_t2i():
 
 
216
  with gr.Row():
217
  gr.Markdown("### 📝 Text auf Bild integrieren")
218
 
 
224
  scale=3
225
  )
226
 
 
227
  with gr.Row():
228
  with gr.Column():
229
  font_size_t2i = gr.Dropdown(
 
233
  )
234
  with gr.Column():
235
  font_family_t2i = gr.Dropdown(
236
+ choices=["Roboto", "Open Sans", "DejaVu Sans"],
237
  value="Roboto",
238
  label="Schriftart"
239
  )
 
245
  )
246
 
247
  with gr.Row():
 
248
  text_x_t2i = gr.Number(value=None, visible=False)
249
  text_y_t2i = gr.Number(value=None, visible=False)
250
 
 
254
  return text_input_t2i, text_x_t2i, text_y_t2i, font_size_t2i, font_family_t2i, font_color_t2i, text_btn_t2i
255
 
256
  def create_text_integration_section_i2i():
 
 
257
  with gr.Row():
258
  gr.Markdown("### 📝 Text auf Bild integrieren")
259
 
 
266
  )
267
 
268
  with gr.Row():
 
269
  text_x_i2i = gr.Number(value=None, visible=False)
270
  text_y_i2i = gr.Number(value=None, visible=False)
271