Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,18 +2,29 @@ import gradio as gr
|
|
2 |
import matplotlib.pyplot as plt
|
3 |
from io import BytesIO
|
4 |
from PIL import Image, ImageDraw, ImageFont
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
bg_color = parse_color(bg_color)
|
18 |
text_color = parse_color(text_color)
|
19 |
|
@@ -21,85 +32,138 @@ def render_text_image(text, font_size, width, height, bg_color, text_color):
|
|
21 |
img = Image.new("RGB", (width, height), color=bg_color)
|
22 |
draw = ImageDraw.Draw(img)
|
23 |
|
24 |
-
# Load
|
25 |
try:
|
26 |
-
|
27 |
-
|
|
|
28 |
font = ImageFont.load_default()
|
29 |
|
30 |
-
#
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
#
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
return img
|
41 |
|
42 |
-
# Function to render LaTeX
|
43 |
def render_math_image(text, font_size, width, height, bg_color, text_color):
|
44 |
-
"""
|
45 |
-
|
46 |
-
|
47 |
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
|
|
|
|
53 |
|
54 |
-
ax.text(0.5, 0.5,
|
55 |
|
56 |
buf = BytesIO()
|
57 |
-
plt.savefig(buf, format=
|
58 |
plt.close(fig)
|
59 |
|
60 |
buf.seek(0)
|
61 |
return Image.open(buf)
|
62 |
|
63 |
-
#
|
64 |
-
def
|
65 |
-
"""
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
else:
|
71 |
-
|
72 |
|
73 |
-
#
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
|
79 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
with gr.Blocks() as demo:
|
81 |
-
gr.Markdown("
|
82 |
|
83 |
with gr.Row():
|
84 |
-
input_text = gr.Textbox(label="Enter Text or
|
85 |
-
|
86 |
|
87 |
with gr.Row():
|
88 |
-
font_size = gr.Slider(10, 100, value=30,
|
89 |
-
|
90 |
-
|
|
|
|
|
|
|
|
|
91 |
|
92 |
with gr.Row():
|
93 |
bg_color = gr.ColorPicker(label="Background Color", value="#FFFFFF")
|
94 |
text_color = gr.ColorPicker(label="Text Color", value="#000000")
|
95 |
|
96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
-
|
99 |
-
|
100 |
-
inputs=[
|
|
|
|
|
|
|
101 |
outputs=output_image
|
102 |
)
|
103 |
|
104 |
-
# Run Gradio app
|
105 |
demo.launch()
|
|
|
2 |
import matplotlib.pyplot as plt
|
3 |
from io import BytesIO
|
4 |
from PIL import Image, ImageDraw, ImageFont
|
5 |
+
import textwrap
|
6 |
+
import os
|
7 |
+
import matplotlib
|
8 |
+
|
9 |
+
# Function to get available system fonts
|
10 |
+
def get_system_fonts():
|
11 |
+
fonts = []
|
12 |
+
for font in matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf'):
|
13 |
+
font_name = os.path.basename(font)
|
14 |
+
fonts.append(font_name)
|
15 |
+
return sorted(set(fonts))
|
16 |
+
|
17 |
+
# Function to parse color
|
18 |
+
def parse_color(color):
|
19 |
+
"""Convert RGBA string to RGB tuple if necessary."""
|
20 |
+
if isinstance(color, str) and color.startswith('rgba'):
|
21 |
+
color = color.replace('rgba', '').strip('()').split(',')
|
22 |
+
return tuple(int(float(c.strip())) for c in color[:3]) # Convert to (R, G, B)
|
23 |
+
return color # If already valid, return as is
|
24 |
+
|
25 |
+
# Function to render plain text as an image
|
26 |
+
def render_plain_text_image(text, font_size, width, height, bg_color, text_color, font_name, align):
|
27 |
+
"""Convert plain text to an image with the given parameters."""
|
28 |
bg_color = parse_color(bg_color)
|
29 |
text_color = parse_color(text_color)
|
30 |
|
|
|
32 |
img = Image.new("RGB", (width, height), color=bg_color)
|
33 |
draw = ImageDraw.Draw(img)
|
34 |
|
35 |
+
# Load font
|
36 |
try:
|
37 |
+
font_path = matplotlib.font_manager.findfont(font_name)
|
38 |
+
font = ImageFont.truetype(font_path, font_size)
|
39 |
+
except Exception:
|
40 |
font = ImageFont.load_default()
|
41 |
|
42 |
+
# Text wrapping
|
43 |
+
margin = 10
|
44 |
+
max_width = width - 2 * margin
|
45 |
+
lines = []
|
46 |
+
for line in text.split('\n'):
|
47 |
+
lines.extend(textwrap.wrap(line, width=int(max_width / font_size * 1.8)))
|
48 |
+
|
49 |
+
# Calculate total text height
|
50 |
+
line_height = font.getsize('Ay')[1]
|
51 |
+
total_text_height = line_height * len(lines)
|
52 |
+
|
53 |
+
# Starting position
|
54 |
+
y = (height - total_text_height) // 2
|
55 |
+
|
56 |
+
for line in lines:
|
57 |
+
line_width = font.getsize(line)[0]
|
58 |
+
if align == 'Left':
|
59 |
+
x = margin
|
60 |
+
elif align == 'Center':
|
61 |
+
x = (width - line_width) // 2
|
62 |
+
else: # Right alignment
|
63 |
+
x = width - line_width - margin
|
64 |
+
draw.text((x, y), line, fill=text_color, font=font)
|
65 |
+
y += line_height
|
66 |
|
67 |
return img
|
68 |
|
69 |
+
# Function to render math (LaTeX) as an image
|
70 |
def render_math_image(text, font_size, width, height, bg_color, text_color):
|
71 |
+
"""Convert LaTeX-formatted text to an image."""
|
72 |
+
bg_color = parse_color(bg_color)
|
73 |
+
text_color = parse_color(text_color)
|
74 |
|
75 |
+
fig, ax = plt.subplots(figsize=(width / 100, height / 100), facecolor=bg_color)
|
76 |
+
ax.set_facecolor(bg_color)
|
77 |
+
ax.axis('off')
|
78 |
+
|
79 |
+
# Ensure LaTeX formatting is correct
|
80 |
+
if not (text.startswith(r"$") and text.endswith(r"$")):
|
81 |
+
text = rf"${text}$"
|
82 |
|
83 |
+
ax.text(0.5, 0.5, text, fontsize=font_size, ha='center', va='center', color=text_color)
|
84 |
|
85 |
buf = BytesIO()
|
86 |
+
plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
|
87 |
plt.close(fig)
|
88 |
|
89 |
buf.seek(0)
|
90 |
return Image.open(buf)
|
91 |
|
92 |
+
# Main function to handle input
|
93 |
+
def text_to_image(input_text, font_size, width, height, bg_color, text_color, mode, font_name, align, image_format):
|
94 |
+
"""Determine whether to use plain text or LaTeX rendering."""
|
95 |
+
if mode == "Plain Text":
|
96 |
+
img = render_plain_text_image(input_text, font_size, width, height, bg_color, text_color, font_name, align)
|
97 |
+
elif mode == "LaTeX Math":
|
98 |
+
img = render_math_image(input_text, font_size, width, height, bg_color, text_color)
|
99 |
else:
|
100 |
+
return "Invalid mode selected!"
|
101 |
|
102 |
+
# Save image to buffer
|
103 |
+
buf = BytesIO()
|
104 |
+
img.save(buf, format=image_format)
|
105 |
+
buf.seek(0)
|
106 |
+
return buf
|
107 |
|
108 |
+
# Function to handle file upload
|
109 |
+
def handle_file_upload(file, font_size, width, height, bg_color, text_color, mode, font_name, align, image_format):
|
110 |
+
"""Extract text from file and convert to an image."""
|
111 |
+
if file is not None:
|
112 |
+
text = file.read().decode("utf-8") # Read and decode text file
|
113 |
+
return text_to_image(text, font_size, width, height, bg_color, text_color, mode, font_name, align, image_format)
|
114 |
+
return "No file uploaded!"
|
115 |
+
|
116 |
+
# Get list of system fonts
|
117 |
+
font_list = get_system_fonts()
|
118 |
+
default_font = "DejaVuSans.ttf" if "DejaVuSans.ttf" in font_list else font_list[0]
|
119 |
+
|
120 |
+
# Gradio Interface
|
121 |
with gr.Blocks() as demo:
|
122 |
+
gr.Markdown("# 🖼️ Text to Image Converter")
|
123 |
|
124 |
with gr.Row():
|
125 |
+
input_text = gr.Textbox(label="Enter Text", placeholder="Type or paste text here...")
|
126 |
+
file_input = gr.File(label="Upload a Text File", type="file")
|
127 |
|
128 |
with gr.Row():
|
129 |
+
font_size = gr.Slider(10, 100, value=30, label="Font Size")
|
130 |
+
font_name = gr.Dropdown(choices=font_list, value=default_font, label="Font")
|
131 |
+
align = gr.Radio(["Left", "Center", "Right"], label="Text Alignment", value="Center")
|
132 |
+
|
133 |
+
with gr.Row():
|
134 |
+
width = gr.Slider(200, 2000, value=800, label="Image Width")
|
135 |
+
height = gr.Slider(200, 2000, value=600, label="Image Height")
|
136 |
|
137 |
with gr.Row():
|
138 |
bg_color = gr.ColorPicker(label="Background Color", value="#FFFFFF")
|
139 |
text_color = gr.ColorPicker(label="Text Color", value="#000000")
|
140 |
|
141 |
+
with gr.Row():
|
142 |
+
mode = gr.Radio(["Plain Text", "LaTeX Math"], label="Rendering Mode", value="Plain Text")
|
143 |
+
image_format = gr.Radio(["PNG", "JPEG"], label="Image Format", value="PNG")
|
144 |
+
|
145 |
+
output_image = gr.Image(label="Generated Image")
|
146 |
+
|
147 |
+
with gr.Row():
|
148 |
+
convert_button = gr.Button("Convert Text to Image")
|
149 |
+
file_convert_button = gr.Button("Convert File to Image")
|
150 |
+
|
151 |
+
convert_button.click(
|
152 |
+
text_to_image,
|
153 |
+
inputs=[
|
154 |
+
input_text, font_size, width, height, bg_color, text_color,
|
155 |
+
mode, font_name, align, image_format
|
156 |
+
],
|
157 |
+
outputs=output_image
|
158 |
+
)
|
159 |
|
160 |
+
file_convert_button.click(
|
161 |
+
handle_file_upload,
|
162 |
+
inputs=[
|
163 |
+
file_input, font_size, width, height, bg_color, text_color,
|
164 |
+
mode, font_name, align, image_format
|
165 |
+
],
|
166 |
outputs=output_image
|
167 |
)
|
168 |
|
|
|
169 |
demo.launch()
|