import gradio as gr from PIL import Image, ImageDraw, ImageFont import textwrap import os import io # --- Helper Function to Create the Poster and PDF --- def create_poster_and_pdf(image: Image.Image, text: str, layout_style: str): """ Generates a visually attractive poster from an image and text, and saves it as both a PNG image and a PDF file. Args: image (PIL.Image.Image): The input image. text (str): The text for the poster. layout_style (str): The chosen layout style ('Centered Title', 'Modern Grid', 'Dramatic Overlay'). Returns: tuple: A tuple containing the generated PIL Image, the file path to the PNG, and the file path to the PDF. Returns (None, None, None) if inputs are invalid. """ if image is None or not text.strip(): # Handle cases where inputs are empty return None, None, None # --- Image & Font Setup --- poster = image.copy() draw = ImageDraw.Draw(poster) img_width, img_height = poster.size # Try to load a stylish font. For a Hugging Face Space, you might need to # include a .ttf file in your repository and reference it here. # This example attempts to find a system font as a fallback. font_path = None try: # Common system paths for a sans-serif font font_paths_to_check = [ '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', # Linux '/System/Library/Fonts/Supplemental/Arial.ttf', # macOS 'C:/Windows/Fonts/Arial.ttf' # Windows ] for path in font_paths_to_check: if os.path.exists(path): font_path = path break # Determine initial font size. This will be adjusted later. font_size = 100 if layout_style == "Dramatic Overlay" else 60 font = ImageFont.truetype(font_path, font_size) if font_path else ImageFont.load_default() except (IOError, OSError): # Fallback to the default Pillow font if system font is not found print("Warning: Could not find a system font. Using default PIL font.") font = ImageFont.load_default() font_size = 15 # Default font is small, so adjust size # --- Text Wrapping and Auto-Sizing --- # We wrap the text to fit within a certain width of the image. margin = int(img_width * 0.1) # 10% margin from the edges max_text_width = img_width - 2 * margin # This loop dynamically adjusts the font size to make the text fit nicely. # It's a simple AI-like logic for responsive design. wrapped_text = "" for size in range(font_size, 10, -2): # Decrease font size from max to 10 try: # Create a font object for the current size current_font = ImageFont.truetype(font_path, size) if font_path else ImageFont.load_default() # Use `textwrap` to split the text into lines that fit the width # The width is calculated by dividing the pixel width by an estimated character width avg_char_width = current_font.getlength('A') if avg_char_width == 0: avg_char_width = 10 # Avoid division by zero wrapped_lines = textwrap.wrap(text, width=int(max_text_width / avg_char_width * 1.5)) wrapped_text = "\n".join(wrapped_lines) # Check if the wrapped text fits vertically text_bbox = draw.multiline_textbbox((0, 0), wrapped_text, font=current_font) text_height = text_bbox[3] - text_bbox[1] if text_height < img_height - 2 * margin: font = current_font # Font size is perfect, let's use it break except Exception as e: # Fallback for font errors print(f"Error during font sizing: {e}") font = ImageFont.load_default() wrapped_text = textwrap.fill(text, width=40) # A fixed fallback width break # --- Apply Layout and Draw Text --- text_bbox = draw.multiline_textbbox((0, 0), wrapped_text, font=font) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] - text_bbox[1] # Default text color text_color = "white" if layout_style == "Centered Title": # Calculate position for centering x = (img_width - text_width) / 2 y = (img_height - text_height) / 2 # Add a semi-transparent black background box for excellent readability draw.rectangle([x - 20, y - 20, x + text_width + 20, y + text_height + 20], fill=(0, 0, 0, 150)) text_color = "white" elif layout_style == "Modern Grid": # Place text in the bottom-left corner x = margin y = img_height - text_height - margin # Add a solid white background box for a clean, modern look draw.rectangle([x - 20, y - 20, x + text_width + 20, y + text_height + 20], fill=(255, 255, 255, 200)) text_color = "black" elif layout_style == "Dramatic Overlay": # Create a full-image semi-transparent black overlay for a dramatic effect overlay = Image.new('RGBA', (img_width, img_height), (0, 0, 0, 128)) # 50% opacity black poster = Image.alpha_composite(poster.convert('RGBA'), overlay) draw = ImageDraw.Draw(poster) # Re-initialize the draw context on the new image # Center the text on the overlaid image x = (img_width - text_width) / 2 y = (img_height - text_height) / 2 text_color = "white" # Draw the wrapped text onto the poster draw.multiline_text((x, y), wrapped_text, font=font, fill=text_color, align="center") # --- Save Outputs --- png_path = "generated_poster.png" pdf_path = "generated_poster.pdf" # 1. Save the final image as a PNG file poster.save(png_path, "PNG") # 2. Save the final image as a PDF file # Pillow can convert an image directly to a PDF. # It requires the image to be in RGB mode for saving to PDF. poster.convert('RGB').save(pdf_path, "PDF", resolution=100.0) return poster, png_path, pdf_path # --- Gradio UI & Event Handler --- def generate_and_update_ui(image, text, layout_style): """ This function acts as the main event handler for the Gradio interface. It calls the poster generation logic and updates the UI components. """ # Call the core function to generate the poster and file paths poster_img, png_path, pdf_path = create_poster_and_pdf(image, text, layout_style) if poster_img is None: # If no poster is generated, clear outputs and hide download buttons return None, gr.DownloadButton(visible=False), gr.File(visible=False) # Return the generated poster image and update the download buttons to be visible # and contain the file paths. return ( poster_img, gr.DownloadButton(value=png_path, visible=True), gr.File(value=pdf_path, visible=True) ) # --- Gradio Interface Layout --- with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# ✨ InstaPoster: AI-Powered Poster Generator") gr.Markdown("Turn your photos and words into stunning, eye-catching posters! Upload your image and text, choose a layout, and download your creation as a PNG or PDF.") with gr.Row(): with gr.Column(scale=1): # Input Components image_input = gr.Image(label="🖼️ Upload Your Image", type="pil") text_input = gr.Textbox(label="✍️ Enter Your Poster Text", lines=3, placeholder="E.g., 'Inspire your mind, ignite your future.'") with gr.Accordion("🎨 Layout & Design Options", open=True): layout_choice = gr.Radio( ["Centered Title", "Modern Grid", "Dramatic Overlay"], label="Choose a Layout Style", value="Centered Title", info="Select a layout to instantly change your poster's design." ) generate_button = gr.Button("🚀 Generate Poster", size="lg") with gr.Column(scale=2): # Output and Download Components gr.Markdown("### 🌟 Your Generated Poster") poster_output = gr.Image(label="Poster Preview", elem_id="poster-output") gr.Markdown("### 📥 Download Your Poster") with gr.Row(): download_image_btn = gr.DownloadButton( label="Download as Image (PNG)", visible=False, # Hidden until a poster is generated elem_id="download-png-btn" ) download_pdf_file = gr.File( label="Download as PDF", visible=False, # Hidden until a poster is generated elem_id="download-pdf-btn" ) # Link the button click to the main handler function generate_button.click( fn=generate_and_update_ui, inputs=[image_input, text_input, layout_choice], outputs=[poster_output, download_image_btn, download_pdf_file] ) # Launch the Gradio app demo.launch(share=True) # `share=True` creates a public link for easy sharing on Hugging Face Spaces