ArrcttacsrjksX commited on
Commit
71e45d9
·
verified ·
1 Parent(s): 77f8ac4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -60
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
- # Function to convert text to an image
7
- def render_text_image(text, font_size, width, height, bg_color, text_color):
8
- """Converts plain text to an image."""
9
-
10
- # Convert RGBA float colors to RGB tuples
11
- def parse_color(color):
12
- if isinstance(color, str) and "rgba" in color:
13
- color = color.replace("rgba", "").strip("()").split(",")
14
- return tuple(int(float(c)) for c in color[:3]) # Convert to (R, G, B)
15
- return color
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 a default font
25
  try:
26
- font = ImageFont.truetype("arial.ttf", font_size)
27
- except IOError:
 
28
  font = ImageFont.load_default()
29
 
30
- # Get text size
31
- text_width, text_height = draw.textsize(text, font=font)
32
-
33
- # Center text
34
- text_x = (width - text_width) // 2
35
- text_y = (height - text_height) // 2
36
-
37
- # Draw text on image
38
- draw.text((text_x, text_y), text, font=font, fill=text_color)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  return img
41
 
42
- # Function to render LaTeX equations as an image
43
  def render_math_image(text, font_size, width, height, bg_color, text_color):
44
- """Converts LaTeX math expressions into an image."""
45
- fig, ax = plt.subplots(figsize=(width / 100, height / 100))
46
- ax.set_axis_off()
47
 
48
- # Ensure proper LaTeX formatting
49
- try:
50
- formatted_text = rf"${text}$"
51
- except Exception as e:
52
- return f"Error parsing LaTeX: {e}"
 
 
53
 
54
- ax.text(0.5, 0.5, formatted_text, fontsize=font_size, ha='center', va='center', color=text_color)
55
 
56
  buf = BytesIO()
57
- plt.savefig(buf, format="png", bbox_inches="tight", pad_inches=0.1)
58
  plt.close(fig)
59
 
60
  buf.seek(0)
61
  return Image.open(buf)
62
 
63
- # File handler function
64
- def process_text_or_file(input_text, uploaded_file, font_size, width, height, bg_color, text_color):
65
- """Handles text input or file upload to generate an image."""
66
-
67
- # Read text from uploaded file
68
- if uploaded_file is not None:
69
- text = uploaded_file.read().decode("utf-8")
70
  else:
71
- text = input_text
72
 
73
- # Determine if the text is a LaTeX equation
74
- if "$" in text or "\\" in text:
75
- return render_math_image(text, font_size, width, height, bg_color, text_color)
76
- else:
77
- return render_text_image(text, font_size, width, height, bg_color, text_color)
78
 
79
- # Gradio UI
 
 
 
 
 
 
 
 
 
 
 
 
80
  with gr.Blocks() as demo:
81
- gr.Markdown("## 🖼️ Convert Text or Math to Image")
82
 
83
  with gr.Row():
84
- input_text = gr.Textbox(label="Enter Text or LaTeX", lines=3)
85
- uploaded_file = gr.File(label="Upload a File (TXT, CSV)")
86
 
87
  with gr.Row():
88
- font_size = gr.Slider(10, 100, value=30, step=2, label="Font Size")
89
- width = gr.Slider(100, 1000, value=500, step=50, label="Image Width")
90
- height = gr.Slider(100, 1000, value=200, step=50, label="Image Height")
 
 
 
 
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
- output_image = gr.Image(type="pil", label="Generated Image")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
- gr.Button("Generate Image").click(
99
- fn=process_text_or_file,
100
- inputs=[input_text, uploaded_file, font_size, width, height, bg_color, text_color],
 
 
 
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()