ArrcttacsrjksX commited on
Commit
1414db8
·
verified ·
1 Parent(s): df27c04

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -26
app.py CHANGED
@@ -6,7 +6,6 @@ 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'):
@@ -14,61 +13,56 @@ def get_system_fonts():
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
 
31
- # Create blank image
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
 
@@ -76,7 +70,6 @@ def render_math_image(text, font_size, width, height, bg_color, text_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
 
@@ -89,9 +82,7 @@ def render_math_image(text, font_size, width, height, bg_color, text_color):
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":
@@ -99,28 +90,22 @@ def text_to_image(input_text, font_size, width, height, bg_color, text_color, mo
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 using file path
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
- # 'file' is a list of file paths; use the first file path.
113
  file_path = file[0]
114
  with open(file_path, "r", encoding="utf-8") as f:
115
  text = f.read()
116
  return text_to_image(text, font_size, width, height, bg_color, text_color, mode, font_name, align, image_format)
117
  return "No file uploaded!"
118
 
119
- # Get list of system fonts
120
  font_list = get_system_fonts()
121
  default_font = "DejaVuSans.ttf" if "DejaVuSans.ttf" in font_list else font_list[0]
122
 
123
- # Gradio Interface
124
  with gr.Blocks() as demo:
125
  gr.Markdown("# 🖼️ Text to Image Converter")
126
 
@@ -169,4 +154,4 @@ with gr.Blocks() as demo:
169
  outputs=output_image
170
  )
171
 
172
- demo.launch()
 
6
  import os
7
  import matplotlib
8
 
 
9
  def get_system_fonts():
10
  fonts = []
11
  for font in matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf'):
 
13
  fonts.append(font_name)
14
  return sorted(set(fonts))
15
 
 
16
  def parse_color(color):
 
17
  if isinstance(color, str) and color.startswith('rgba'):
18
  color = color.replace('rgba', '').strip('()').split(',')
19
+ return tuple(int(float(c.strip())) for c in color[:3])
20
+ return color
21
 
 
22
  def render_plain_text_image(text, font_size, width, height, bg_color, text_color, font_name, align):
 
23
  bg_color = parse_color(bg_color)
24
  text_color = parse_color(text_color)
25
 
 
26
  img = Image.new("RGB", (width, height), color=bg_color)
27
  draw = ImageDraw.Draw(img)
28
 
 
29
  try:
30
  font_path = matplotlib.font_manager.findfont(font_name)
31
  font = ImageFont.truetype(font_path, font_size)
32
  except Exception:
33
  font = ImageFont.load_default()
34
 
 
35
  margin = 10
36
  max_width = width - 2 * margin
37
  lines = []
38
  for line in text.split('\n'):
39
  lines.extend(textwrap.wrap(line, width=int(max_width / font_size * 1.8)))
40
 
41
+ # Use getbbox() instead of getsize()
42
+ bbox = font.getbbox('Ay')
43
+ line_height = bbox[3] - bbox[1]
44
  total_text_height = line_height * len(lines)
45
 
 
46
  y = (height - total_text_height) // 2
47
 
48
  for line in lines:
49
+ # Use getbbox() to get line width
50
+ bbox = font.getbbox(line)
51
+ line_width = bbox[2] - bbox[0]
52
+
53
  if align == 'Left':
54
  x = margin
55
  elif align == 'Center':
56
  x = (width - line_width) // 2
57
  else: # Right alignment
58
  x = width - line_width - margin
59
+
60
  draw.text((x, y), line, fill=text_color, font=font)
61
  y += line_height
62
 
63
  return img
64
 
 
65
  def render_math_image(text, font_size, width, height, bg_color, text_color):
 
66
  bg_color = parse_color(bg_color)
67
  text_color = parse_color(text_color)
68
 
 
70
  ax.set_facecolor(bg_color)
71
  ax.axis('off')
72
 
 
73
  if not (text.startswith(r"$") and text.endswith(r"$")):
74
  text = rf"${text}$"
75
 
 
82
  buf.seek(0)
83
  return Image.open(buf)
84
 
 
85
  def text_to_image(input_text, font_size, width, height, bg_color, text_color, mode, font_name, align, image_format):
 
86
  if mode == "Plain Text":
87
  img = render_plain_text_image(input_text, font_size, width, height, bg_color, text_color, font_name, align)
88
  elif mode == "LaTeX Math":
 
90
  else:
91
  return "Invalid mode selected!"
92
 
 
93
  buf = BytesIO()
94
  img.save(buf, format=image_format)
95
  buf.seek(0)
96
  return buf
97
 
 
98
  def handle_file_upload(file, font_size, width, height, bg_color, text_color, mode, font_name, align, image_format):
 
99
  if file is not None:
 
100
  file_path = file[0]
101
  with open(file_path, "r", encoding="utf-8") as f:
102
  text = f.read()
103
  return text_to_image(text, font_size, width, height, bg_color, text_color, mode, font_name, align, image_format)
104
  return "No file uploaded!"
105
 
 
106
  font_list = get_system_fonts()
107
  default_font = "DejaVuSans.ttf" if "DejaVuSans.ttf" in font_list else font_list[0]
108
 
 
109
  with gr.Blocks() as demo:
110
  gr.Markdown("# 🖼️ Text to Image Converter")
111
 
 
154
  outputs=output_image
155
  )
156
 
157
+ demo.launch()