šØ AI Text-to-Infographics Generator
Transform your text into stunning, professional infographics with the power of AI
""" Main Gradio application for Text-to-Infographics Generator """ import os import logging import gradio as gr from typing import Dict, List, Tuple, Optional import tempfile # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Import our modules from config import Config from src.text_processor import TextProcessor from src.gemini_client import GeminiClient from src.template_manager import TemplateManager from src.layout_engine import LayoutEngine from src.color_palette import ColorPalette from src.image_generator import ImageGenerator from utils.helpers import sanitize_text, validate_content_length, generate_unique_id from examples.sample_texts import get_sample_text, get_all_categories # Initialize components text_processor = TextProcessor() gemini_client = GeminiClient() template_manager = TemplateManager() layout_engine = LayoutEngine() color_palette = ColorPalette() image_generator = ImageGenerator() def generate_infographic(text: str, template_style: str, custom_color: str, layout_type: str, progress=gr.Progress()) -> Tuple[str, str, str]: """ Main function to generate infographic Args: text: Input text content template_style: Selected template style custom_color: Custom primary color layout_type: Layout arrangement type progress: Gradio progress tracker Returns: Tuple of (image_path, status_message, download_file_path) """ try: # Validate inputs progress(0.1, desc="Validating input...") if not text or len(text.strip()) < 10: return None, "ā Please provide more substantial text content (at least 10 characters)", None # Sanitize and validate content text = sanitize_text(text) content_validation = validate_content_length(text) if not content_validation['valid']: return None, f"ā {content_validation['message']}", None # Step 1: Process text progress(0.2, desc="Analyzing text content...") logger.info("Starting text analysis") text_analysis = text_processor.analyze_text(text) # Step 2: Get AI insights progress(0.3, desc="Getting AI insights...") logger.info("Getting AI insights from Gemini") enhanced_analysis = gemini_client.analyze_content(text_analysis) # Generate title if not present if not enhanced_analysis.get('title'): progress(0.35, desc="Generating title...") enhanced_analysis['title'] = gemini_client.generate_title(text) # Step 3: Apply template styling progress(0.4, desc="Applying template styling...") logger.info(f"Applying {template_style} template") styled_content = template_manager.apply_template_to_content( enhanced_analysis, template_style, custom_color, layout_type ) # Step 4: Create layout progress(0.6, desc="Creating layout...") logger.info("Generating layout") layout_data = layout_engine.create_layout(styled_content) # Optimize layout progress(0.7, desc="Optimizing layout...") layout_data = layout_engine.optimize_layout(layout_data) # Step 5: Generate image progress(0.8, desc="Generating infographic image...") logger.info("Creating final image") export_data = layout_engine.export_layout_data(layout_data) image_path = image_generator.create_infographic(export_data) # Step 6: Create downloadable file progress(0.9, desc="Preparing download...") download_path = _prepare_download_file(image_path, template_style) progress(1.0, desc="Complete!") success_message = f"ā Infographic generated successfully!\nš Template: {template_style}\nš Layout: {layout_type}\nš {len(text.split())} words processed" return image_path, success_message, download_path except Exception as e: logger.error(f"Error generating infographic: {e}") error_message = f"ā Error generating infographic: {str(e)}" return None, error_message, None def _prepare_download_file(image_path: str, template_style: str) -> str: """Prepare downloadable file""" try: if not image_path or not os.path.exists(image_path): return None # Create a copy for download with better filename download_filename = f"infographic_{template_style.lower()}_{generate_unique_id()}.png" download_path = os.path.join(tempfile.gettempdir(), download_filename) # Copy file import shutil shutil.copy2(image_path, download_path) return download_path except Exception as e: logger.error(f"Error preparing download file: {e}") return image_path # Return original if copy fails def load_sample_text(category: str) -> str: """Load sample text by category""" try: return get_sample_text(category) except Exception as e: logger.error(f"Error loading sample text: {e}") return "" def get_template_info(template_name: str) -> str: """Get template information""" try: info = template_manager.get_template_preview_data(template_name) if info: description = info.get('description', 'Professional infographic template') best_for = ', '.join(info.get('best_for', ['General use'])) return f"**{template_name}**: {description}\n**Best for**: {best_for}" return f"**{template_name}**: Professional infographic template" except Exception as e: logger.error(f"Error getting template info: {e}") return f"**{template_name}**: Professional template" def create_interface(): """Create the main Gradio interface""" # Custom CSS for better styling css = """ .gradio-container { max-width: 1400px !important; margin: auto; } .main-header { text-align: center; margin-bottom: 2rem; } .feature-box { padding: 1rem; border-radius: 8px; margin: 0.5rem 0; } .status-box { padding: 1rem; border-radius: 8px; margin-top: 1rem; } """ with gr.Blocks( theme=gr.themes.Soft( primary_hue="blue", secondary_hue="gray", neutral_hue="gray", ), css=css, title="AI Text-to-Infographics Generator" ) as app: # Header gr.HTML("""
Transform your text into stunning, professional infographics with the power of AI
Built with ā¤ļø using Gradio, Google Gemini, and Hugging Face Spaces
Transform your ideas into visual stories ⢠Perfect for presentations, social media, and reports