AIImage / app.py
dschandra's picture
Update app.py
78a6634 verified
raw
history blame
2.68 kB
import gradio as gr
from PIL import Image, ImageDraw, ImageFont
import random
import textwrap
# Enhanced function for image generation with better visual representation
def generate_image(text_description):
# Create a blank image with a gradient background to simulate a sunset
img = Image.new('RGB', (512, 512), color=(0, 0, 0)) # Start with black
draw = ImageDraw.Draw(img)
# Create a simple gradient for sunset (orange to purple)
for y in range(512):
r = int(255 * (1 - y / 512) * 0.8) # Fade red/orange
g = int(100 * (1 - y / 512)) # Minimal green
b = int(150 + 105 * (y / 512)) # Increase blue/purple
draw.line([(0, y), (512, y)], fill=(r, g, b))
# Load a default font (fallback to system font if arial.ttf is unavailable)
try:
font = ImageFont.truetype("arial.ttf", 25)
except:
font = ImageFont.load_default()
# Wrap text to fit within the image
wrapper = textwrap.TextWrapper(width=20) # Adjust width for better wrapping
wrapped_text = wrapper.fill(text=text_description)
lines = wrapped_text.split('\n')
# Draw each line of text at the bottom
y_text = 400
for line in lines:
bbox = draw.textbbox((0, 0), line, font=font)
line_width = bbox[2] - bbox[0]
line_height = bbox[3] - bbox[1]
draw.text((20, y_text), line, font=font, fill=(255, 255, 255))
y_text += line_height + 5
# Add graphical elements based on description
if "lake" in text_description.lower():
draw.rectangle([150, 300, 350, 400], fill=(0, 191, 255)) # Blue lake
if "mountains" in text_description.lower():
draw.polygon([(200, 250), (250, 200), (300, 250)], fill=(255, 255, 255)) # White mountain
draw.polygon([(250, 200), (300, 150), (350, 200)], fill=(255, 255, 255)) # Second mountain
return img
# Gradio interface
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")
# Connect the button to the function
generate_btn.click(fn=generate_image, inputs=text_input, outputs=output_image)
# Launch the app
demo.launch()