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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -61
app.py CHANGED
@@ -3,17 +3,17 @@ import matplotlib.pyplot as plt
3
  from io import BytesIO
4
  from PIL import Image, ImageDraw, ImageFont
5
 
6
- # Function to parse color
7
- def parse_color(color):
8
- """Convert RGBA string to RGB tuple if necessary."""
9
- if isinstance(color, str) and color.startswith('rgba'):
10
- color = color.replace('rgba', '').strip('()').split(',')
11
- return tuple(int(float(c)) for c in color[:3]) # Convert to (R, G, B)
12
- return color # If already valid, return as is
13
-
14
- # Function to render plain text as an image
15
- def render_plain_text_image(text, font_size, width, height, bg_color, text_color):
16
- """Convert plain text to an image with the given parameters."""
17
  bg_color = parse_color(bg_color)
18
  text_color = parse_color(text_color)
19
 
@@ -21,94 +21,85 @@ def render_plain_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 font (default system font)
25
  try:
26
  font = ImageFont.truetype("arial.ttf", font_size)
27
- except:
28
  font = ImageFont.load_default()
29
 
30
  # Get text size
31
  text_width, text_height = draw.textsize(text, font=font)
32
 
33
- # Position text in center
34
- x = (width - text_width) // 2
35
- y = (height - text_height) // 2
36
 
37
- draw.text((x, y), text, fill=text_color, font=font)
 
38
 
39
  return img
40
 
41
- # Function to render math (LaTeX) as an image
42
  def render_math_image(text, font_size, width, height, bg_color, text_color):
43
- """Convert LaTeX-formatted text to an image."""
44
  fig, ax = plt.subplots(figsize=(width / 100, height / 100))
45
  ax.set_axis_off()
46
 
47
- # Ensure LaTeX formatting is correct
48
- if "$" in text:
49
- text = rf"{text}"
 
 
50
 
51
- ax.text(0.5, 0.5, text, fontsize=font_size, ha='center', va='center', color=text_color)
52
 
53
  buf = BytesIO()
54
- plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0.1)
55
  plt.close(fig)
56
 
57
  buf.seek(0)
58
  return Image.open(buf)
59
 
60
- # Main function to handle input
61
- def text_to_image(input_text, font_size, width, height, bg_color, text_color, mode):
62
- """Determine whether to use plain text or LaTeX rendering."""
63
- if mode == "Plain Text":
64
- return render_plain_text_image(input_text, font_size, width, height, bg_color, text_color)
65
- elif mode == "LaTeX Math":
66
- return render_math_image(input_text, font_size, width, height, bg_color, text_color)
67
  else:
68
- return "Invalid mode selected!"
69
 
70
- # Function to handle file upload
71
- def handle_file_upload(file, font_size, width, height, bg_color, text_color, mode):
72
- """Extract text from file and convert to an image."""
73
- if file is not None:
74
- text = file.read().decode("utf-8") # Read and decode text file
75
- return text_to_image(text, font_size, width, height, bg_color, text_color, mode)
76
- return "No file uploaded!"
77
 
78
- # Gradio Interface
79
  with gr.Blocks() as demo:
80
- gr.Markdown("# 🖼️ Text to Image Converter")
81
 
82
  with gr.Row():
83
- input_text = gr.Textbox(label="Enter Text", placeholder="Type or paste text here...")
84
- file_input = gr.File(label="Upload a Text File", type="file")
85
 
86
  with gr.Row():
87
- font_size = gr.Slider(10, 100, value=30, label="Font Size")
88
- width = gr.Slider(200, 1000, value=500, label="Image Width")
89
- height = gr.Slider(200, 1000, value=300, label="Image Height")
90
 
91
  with gr.Row():
92
  bg_color = gr.ColorPicker(label="Background Color", value="#FFFFFF")
93
  text_color = gr.ColorPicker(label="Text Color", value="#000000")
94
 
95
- mode = gr.Radio(["Plain Text", "LaTeX Math"], label="Rendering Mode", value="Plain Text")
96
-
97
- output_image = gr.Image(label="Generated Image")
98
-
99
- convert_button = gr.Button("Convert Text to Image")
100
- file_convert_button = gr.Button("Convert File to Image")
101
-
102
- convert_button.click(
103
- text_to_image,
104
- inputs=[input_text, font_size, width, height, bg_color, text_color, mode],
105
- outputs=output_image
106
- )
107
 
108
- file_convert_button.click(
109
- handle_file_upload,
110
- inputs=[file_input, font_size, width, height, bg_color, text_color, mode],
111
  outputs=output_image
112
  )
113
 
 
114
  demo.launch()
 
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
  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()