Spaces:
Sleeping
Sleeping
import gradio as gr | |
import matplotlib.pyplot as plt | |
from io import BytesIO | |
from PIL import Image, ImageDraw, ImageFont | |
# Function to convert text to an image | |
def render_text_image(text, font_size, width, height, bg_color, text_color): | |
"""Converts plain text to an image.""" | |
# Convert RGBA float colors to RGB tuples | |
def parse_color(color): | |
if isinstance(color, str) and "rgba" in color: | |
color = color.replace("rgba", "").strip("()").split(",") | |
return tuple(int(float(c)) for c in color[:3]) # Convert to (R, G, B) | |
return color | |
bg_color = parse_color(bg_color) | |
text_color = parse_color(text_color) | |
# Create blank image | |
img = Image.new("RGB", (width, height), color=bg_color) | |
draw = ImageDraw.Draw(img) | |
# Load a default font | |
try: | |
font = ImageFont.truetype("arial.ttf", font_size) | |
except IOError: | |
font = ImageFont.load_default() | |
# Get text size | |
text_width, text_height = draw.textsize(text, font=font) | |
# Center text | |
text_x = (width - text_width) // 2 | |
text_y = (height - text_height) // 2 | |
# Draw text on image | |
draw.text((text_x, text_y), text, font=font, fill=text_color) | |
return img | |
# Function to render LaTeX equations as an image | |
def render_math_image(text, font_size, width, height, bg_color, text_color): | |
"""Converts LaTeX math expressions into an image.""" | |
fig, ax = plt.subplots(figsize=(width / 100, height / 100)) | |
ax.set_axis_off() | |
# Ensure proper LaTeX formatting | |
try: | |
formatted_text = rf"${text}$" | |
except Exception as e: | |
return f"Error parsing LaTeX: {e}" | |
ax.text(0.5, 0.5, formatted_text, fontsize=font_size, ha='center', va='center', color=text_color) | |
buf = BytesIO() | |
plt.savefig(buf, format="png", bbox_inches="tight", pad_inches=0.1) | |
plt.close(fig) | |
buf.seek(0) | |
return Image.open(buf) | |
# File handler function | |
def process_text_or_file(input_text, uploaded_file, font_size, width, height, bg_color, text_color): | |
"""Handles text input or file upload to generate an image.""" | |
# Read text from uploaded file | |
if uploaded_file is not None: | |
text = uploaded_file.read().decode("utf-8") | |
else: | |
text = input_text | |
# Determine if the text is a LaTeX equation | |
if "$" in text or "\\" in text: | |
return render_math_image(text, font_size, width, height, bg_color, text_color) | |
else: | |
return render_text_image(text, font_size, width, height, bg_color, text_color) | |
# Gradio UI | |
with gr.Blocks() as demo: | |
gr.Markdown("## 🖼️ Convert Text or Math to Image") | |
with gr.Row(): | |
input_text = gr.Textbox(label="Enter Text or LaTeX", lines=3) | |
uploaded_file = gr.File(label="Upload a File (TXT, CSV)") | |
with gr.Row(): | |
font_size = gr.Slider(10, 100, value=30, step=2, label="Font Size") | |
width = gr.Slider(100, 1000, value=500, step=50, label="Image Width") | |
height = gr.Slider(100, 1000, value=200, step=50, label="Image Height") | |
with gr.Row(): | |
bg_color = gr.ColorPicker(label="Background Color", value="#FFFFFF") | |
text_color = gr.ColorPicker(label="Text Color", value="#000000") | |
output_image = gr.Image(type="pil", label="Generated Image") | |
gr.Button("Generate Image").click( | |
fn=process_text_or_file, | |
inputs=[input_text, uploaded_file, font_size, width, height, bg_color, text_color], | |
outputs=output_image | |
) | |
# Run Gradio app | |
demo.launch() | |