VirtualOasis commited on
Commit
8f38a6d
·
verified ·
1 Parent(s): a8058b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -91
app.py CHANGED
@@ -1,120 +1,223 @@
1
  import gradio as gr
2
- from PIL import Image, ImageDraw, ImageFont
3
- import textwrap
4
- import io
5
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- def text_to_image(text_content, font_size_option):
8
  """
9
- Convert text content to a formatted image with customizable font size.
 
10
  Args:
11
- text_content (str): The input text to convert to image
12
- font_size_option (str): Font size option (Small, Medium, Large)
 
 
13
  Returns:
14
- PIL.Image: Generated image
15
  """
16
  if not text_content.strip():
17
- text_content = "Please enter some text to convert to image."
18
 
19
- # Font size mapping
20
- font_sizes = {
21
- "Small": 20,
22
- "Medium": 28,
23
- "Large": 36
24
- }
25
- font_size = font_sizes.get(font_size_option, 28)
26
 
27
- # Fixed styling parameters
28
- img_width = 600 # 3:4 ratio width
29
- img_height = 800 # 3:4 ratio height
30
- background_color = "#F8F9FA" # Light theme background
31
- text_color = "#000000" # Black text
32
- padding = 50
33
- line_spacing = font_size // 3 # Dynamic line spacing based on font size
34
 
35
- # Create image with higher quality
36
- img = Image.new('RGB', (img_width, img_height), background_color)
37
- draw = ImageDraw.Draw(img)
38
 
39
- # Try to use a nice font with better quality, fallback to default if not available
40
  font = None
41
- font_paths = [
42
- "/System/Library/Fonts/Helvetica.ttc", # macOS
43
- "/System/Library/Fonts/Arial.ttf", # macOS
44
- "/Windows/Fonts/arial.ttf", # Windows
45
- "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", # Linux
46
- "arial.ttf"
47
- ]
48
-
49
- for font_path in font_paths:
50
- try:
51
- font = ImageFont.truetype(font_path, font_size)
52
- break
53
- except:
54
- continue
55
-
56
- if font is None:
57
- try:
58
- font = ImageFont.load_default()
59
- except:
60
- # Fallback font
61
- font = ImageFont.load_default()
62
-
63
- # Calculate text area with better precision
64
- text_width = img_width - (padding * 2)
65
-
66
- # More accurate text wrapping based on actual character width
67
- # Test character width
68
- test_char_width = draw.textbbox((0, 0), "W", font=font)[2]
69
- chars_per_line = max(1, text_width // test_char_width)
70
-
71
- wrapped_lines = []
72
- paragraphs = text_content.split('\n')
73
-
74
- for paragraph in paragraphs:
75
- if paragraph.strip():
76
- lines = textwrap.wrap(paragraph, width=chars_per_line)
77
- wrapped_lines.extend(lines)
78
- wrapped_lines.append("") # Add space between paragraphs
79
  else:
80
- wrapped_lines.append("")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- # Remove trailing empty lines
83
- while wrapped_lines and wrapped_lines[-1] == "":
84
- wrapped_lines.pop()
 
85
 
86
- # Draw text with better positioning
87
- y_position = padding
88
- for line in wrapped_lines:
89
- if y_position + font_size + line_spacing > img_height - padding:
90
- # Add "..." if text is too long
91
- draw.text((padding, y_position), "...", font=font, fill=text_color)
92
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- # Use textbbox for better text positioning
95
- draw.text((padding, y_position), line, font=font, fill=text_color)
96
- y_position += font_size + line_spacing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
- return img
 
 
 
 
 
 
 
99
 
100
  demo = gr.Interface(
101
- fn=text_to_image,
102
  inputs=[
103
  gr.Textbox(
104
- label="Text Content",
105
- placeholder="Enter your text content here...",
106
  lines=10,
107
- value="Welcome to Text-to-Image Converter!\n\nThis tool converts your text into beautifully formatted images perfect for social media posts.\n\nSimply replace this text with your content, choose your preferred font size, and click generate!"
 
 
 
 
 
 
 
 
108
  ),
109
- gr.Radio(
110
- choices=["Small", "Medium", "Large"],
111
- value="Medium",
112
- label="Font Size"
 
 
 
 
 
 
 
113
  )
114
  ],
115
- outputs=[gr.Image(label="Generated Image", type="pil")],
116
- title="Text to Image Converter",
117
- description="Convert your text content into attractive images with a clean, readable design. Choose your font size and generate high-quality images perfect for social media!"
 
 
 
 
 
 
118
  )
119
 
120
  if __name__ == "__main__":
 
1
  import gradio as gr
 
 
 
2
  import os
3
+ import zipfile
4
+ import tempfile
5
+ from PIL import Image, ImageDraw, ImageFont
6
+
7
+ def draw_horizontal_lines(draw, width, height, spacing=60, color=(230, 230, 230)):
8
+ """Draws horizontal lines on the image."""
9
+ for y in range(0, height, spacing):
10
+ draw.line([(0, y), (width, y)], fill=color, width=2)
11
+
12
+ def draw_dot_grid(draw, width, height, spacing=50, color=(220, 220, 220)):
13
+ """Draws a dot grid on the image."""
14
+ for x in range(0, width, spacing):
15
+ for y in range(0, height, spacing):
16
+ draw.ellipse([(x-2, y-2), (x+2, y+2)], fill=color)
17
+
18
+ def draw_lattice_grid(draw, width, height, spacing=100, color=(235, 235, 235)):
19
+ """Draws a lattice/graph paper grid on the image."""
20
+ # Draw vertical lines
21
+ for x in range(0, width, spacing):
22
+ draw.line([(x, 0), (x, height)], fill=color, width=2)
23
+ # Draw horizontal lines
24
+ for y in range(0, height, spacing):
25
+ draw.line([(0, y), (width, y)], fill=color, width=2)
26
 
27
+ def text_to_images_mcp(text_content, style='lines', font_path=None):
28
  """
29
+ Converts text to images and returns a zip file containing all generated images.
30
+
31
  Args:
32
+ text_content (str): The text to be converted.
33
+ style (str): The background style ('plain', 'lines', 'dots', 'grid').
34
+ font_path (str, optional): The path to a .ttf font file.
35
+
36
  Returns:
37
+ str: Path to the zip file containing all generated images.
38
  """
39
  if not text_content.strip():
40
+ return None
41
 
42
+ # --- Configuration ---
43
+ IMG_WIDTH = 1080
44
+ IMG_HEIGHT = 1080
45
+ BACKGROUND_COLOR = (255, 255, 255)
46
+ TEXT_COLOR = (10, 10, 10)
47
+ STYLE_COLOR = (225, 225, 225)
 
48
 
49
+ PADDING_X = 80
50
+ PADDING_Y = 80
51
+ FONT_SIZE = 48
52
+ LINE_SPACING = 20
 
 
 
53
 
54
+ # Create temporary directory for images
55
+ temp_dir = tempfile.mkdtemp()
 
56
 
57
+ # --- Font Loading ---
58
  font = None
59
+ try:
60
+ if font_path and os.path.exists(font_path):
61
+ font = ImageFont.truetype(font_path, FONT_SIZE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  else:
63
+ font_paths_to_try = [
64
+ "Arial.ttf", "arial.ttf",
65
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
66
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
67
+ ]
68
+ for f_path in font_paths_to_try:
69
+ try:
70
+ font = ImageFont.truetype(f_path, FONT_SIZE)
71
+ break
72
+ except IOError:
73
+ continue
74
+ if not font:
75
+ font = ImageFont.load_default()
76
+ except Exception as e:
77
+ font = ImageFont.load_default()
78
+
79
+ # --- Text Wrapping Logic ---
80
+ drawable_width = IMG_WIDTH - 2 * PADDING_X
81
+ paragraphs = [p.strip() for p in text_content.strip().split('\n') if p.strip()]
82
+
83
+ if not paragraphs:
84
+ return None
85
+
86
+ all_lines_and_breaks = []
87
+ for i, paragraph in enumerate(paragraphs):
88
+ words = paragraph.split()
89
+ current_line = ""
90
+ for word in words:
91
+ if font.getlength(word) > drawable_width:
92
+ temp_word = ""
93
+ for char in word:
94
+ if font.getlength(temp_word + char) > drawable_width:
95
+ all_lines_and_breaks.append(temp_word)
96
+ temp_word = char
97
+ else:
98
+ temp_word += char
99
+ word = temp_word
100
+ if font.getlength(current_line + " " + word) <= drawable_width:
101
+ current_line += " " + word
102
+ else:
103
+ all_lines_and_breaks.append(current_line.strip())
104
+ current_line = word
105
+ all_lines_and_breaks.append(current_line.strip())
106
+ if i < len(paragraphs) - 1:
107
+ all_lines_and_breaks.append(None)
108
+
109
+ # --- Image Generation ---
110
+ img_count = 0
111
+ page_content = []
112
+ y_text = PADDING_Y
113
 
114
+ try:
115
+ line_height = font.getbbox("A")[3] - font.getbbox("A")[1]
116
+ except AttributeError:
117
+ line_height = 12
118
 
119
+ PARAGRAPH_SPACING = line_height
120
+ image_paths = []
121
+
122
+ def create_image_page(content, page_num):
123
+ """Helper function to create and save a single image page."""
124
+ img = Image.new('RGB', (IMG_WIDTH, IMG_HEIGHT), color=BACKGROUND_COLOR)
125
+ draw = ImageDraw.Draw(img)
126
+
127
+ # Draw the selected background style first
128
+ if style == 'lines':
129
+ line_style_spacing = line_height + LINE_SPACING
130
+ draw_horizontal_lines(draw, IMG_WIDTH, IMG_HEIGHT, spacing=line_style_spacing, color=STYLE_COLOR)
131
+ elif style == 'dots':
132
+ draw_dot_grid(draw, IMG_WIDTH, IMG_HEIGHT, color=STYLE_COLOR)
133
+ elif style == 'grid':
134
+ draw_lattice_grid(draw, IMG_WIDTH, IMG_HEIGHT, color=STYLE_COLOR)
135
+
136
+ # Draw the text on top of the background
137
+ current_y = PADDING_Y
138
+ for page_item in content:
139
+ if page_item is not None:
140
+ draw.text((PADDING_X, current_y), page_item, font=font, fill=TEXT_COLOR)
141
+ current_y += line_height + LINE_SPACING
142
+ else:
143
+ current_y += PARAGRAPH_SPACING
144
 
145
+ filename = os.path.join(temp_dir, f"page_{page_num}.png")
146
+ img.save(filename)
147
+ image_paths.append(filename)
148
+ return filename
149
+
150
+ for item in all_lines_and_breaks:
151
+ is_break = item is None
152
+ item_height = PARAGRAPH_SPACING if is_break else line_height
153
+
154
+ if y_text + item_height > IMG_HEIGHT - PADDING_Y:
155
+ img_count += 1
156
+ create_image_page(page_content, img_count)
157
+
158
+ page_content = [item]
159
+ y_text = PADDING_Y + item_height + (0 if is_break else LINE_SPACING)
160
+ else:
161
+ page_content.append(item)
162
+ y_text += item_height + (0 if is_break else LINE_SPACING)
163
+
164
+ if page_content:
165
+ img_count += 1
166
+ create_image_page(page_content, img_count)
167
+
168
+ # Create zip file
169
+ zip_path = os.path.join(tempfile.gettempdir(), f"text_to_images_{len(os.listdir(temp_dir))}_pages.zip")
170
+ with zipfile.ZipFile(zip_path, 'w') as zipf:
171
+ for img_path in image_paths:
172
+ zipf.write(img_path, os.path.basename(img_path))
173
 
174
+ return zip_path
175
+
176
+ # Sample text for demonstration
177
+ sample_text = """In the heart of a bustling city, there lived a clockmaker named Alistair. His shop, a quaint corner of tranquility amidst the urban chaos, was filled with the gentle ticking of countless timepieces. Each clock was a masterpiece, a testament to his dedication and skill. But Alistair held a secret. One of his clocks, an old grandfather clock in the corner, did not just tell time. It told stories.
178
+
179
+ Every midnight, as the city slept, the clock would chime, not with bells, but with whispers of forgotten tales. Stories of ancient kings, lost love, and adventures in lands woven from starlight and dreams. Alistair would sit by the fire, listening, his heart filled with the magic of the past. He was the keeper of time, and in turn, time had made him its confidant.
180
+
181
+ One day, a young girl with eyes as curious as a cat's wandered into his shop. She wasn't interested in the shiny new watches but was drawn to the grandfather clock. "What's its story?" she asked, her voice soft. Alistair smiled, for he knew he had found the next guardian of the stories. The legacy of the whispering clock would live on."""
182
 
183
  demo = gr.Interface(
184
+ fn=text_to_images_mcp,
185
  inputs=[
186
  gr.Textbox(
187
+ value=sample_text,
 
188
  lines=10,
189
+ max_lines=20,
190
+ label="Text Content",
191
+ placeholder="Enter your long-form text here..."
192
+ ),
193
+ gr.Dropdown(
194
+ choices=['plain', 'lines', 'dots', 'grid'],
195
+ value='lines',
196
+ label="Background Style",
197
+ info="Choose the background style for your images"
198
  ),
199
+ gr.Textbox(
200
+ value="",
201
+ label="Custom Font Path (Optional)",
202
+ placeholder="/path/to/your/font.ttf",
203
+ info="Leave empty to use system default font"
204
+ )
205
+ ],
206
+ outputs=[
207
+ gr.File(
208
+ label="Download Images (ZIP)",
209
+ file_count="single"
210
  )
211
  ],
212
+ title="📖 Text to Images Converter",
213
+ description="Transform long-form text into a series of attractive, readable images. Simply paste your text, choose a background style, and download the generated images as a ZIP file.",
214
+ examples=[
215
+ [sample_text, 'lines', ''],
216
+ [sample_text, 'dots', ''],
217
+ [sample_text, 'grid', ''],
218
+ [sample_text, 'plain', '']
219
+ ],
220
+ cache_examples=False
221
  )
222
 
223
  if __name__ == "__main__":