|
import gradio as gr |
|
from PIL import Image, ImageDraw, ImageFont |
|
import random |
|
import textwrap |
|
|
|
|
|
def generate_image(text_description): |
|
|
|
img = Image.new('RGB', (512, 512), color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) |
|
draw = ImageDraw.Draw(img) |
|
|
|
|
|
try: |
|
font = ImageFont.truetype("arial.ttf", 30) |
|
except: |
|
font = ImageFont.load_default() |
|
|
|
|
|
wrapper = textwrap.TextWrapper(width=20) |
|
wrapped_text = wrapper.fill(text=text_description) |
|
lines = wrapped_text.split('\n') |
|
|
|
|
|
y_text = 20 |
|
for line in lines: |
|
line_width, line_height = draw.textsize(line, font=font) |
|
draw.text((20, y_text), line, font=font, fill=(255, 255, 255)) |
|
y_text += line_height + 5 |
|
|
|
|
|
if "lake" in text_description.lower() or "mountains" in text_description.lower(): |
|
draw.rectangle([200, 300, 300, 400], fill=(0, 191, 255)) |
|
draw.polygon([(250, 250), (300, 200), (350, 250)], fill=(255, 255, 255)) |
|
|
|
return img |
|
|
|
|
|
with gr.Blocks(title="Text-to-Image Generator") as demo: |
|
gr.Markdown("# Text-to-Image Generator") |
|
gr.Markdown("Enter a description below and generate an image!") |
|
|
|
with gr.Row(): |
|
with gr.Column(): |
|
text_input = gr.Textbox(label="Description", placeholder="Type your image description here...", value="A serene lake surrounded by snow-capped mountains under a vibrant sunset sky with shades of orange and purple.") |
|
generate_btn = gr.Button("Generate Image") |
|
with gr.Column(): |
|
output_image = gr.Image(label="Generated Image") |
|
|
|
|
|
generate_btn.click(fn=generate_image, inputs=text_input, outputs=output_image) |
|
|
|
|
|
demo.launch() |