import gradio as gr from google import genai from google.genai import types from PIL import Image from io import BytesIO import base64 import os # Initialize the Google Generative AI client with the API key from environment variables client = genai.Client(api_key=os.environ['GEMINI_API_KEY']) def generate_item(tag): # Generate text using Gemini LLM prompt = f"Generate a short, engaging post about {tag} in the style of a TikTok caption." text_response = client.models.generate_content( model='gemini-2.5-flash-preview-04-17', contents=[prompt] ) text = text_response.text.strip() # Generate an image based on the text or tag image_response = client.models.generate_images( model='imagen-3.0-generate-002', prompt=text, # Using the generated text as the prompt config=types.GenerateImagesConfig( number_of_images=1, aspect_ratio="9:16", person_generation="DONT_ALLOW" ) ) # Check if images were generated if image_response.generated_images and len(image_response.generated_images) > 0: generated_image = image_response.generated_images[0] image = Image.open(BytesIO(generated_image.image.image_bytes)) else: # Fallback to a placeholder image if no images are generated image = Image.new('RGB', (300, 533), color='gray') # Size matches 9:16 aspect ratio # Convert the image to base64 buffered = BytesIO() image.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode() return {'text': text, 'image_base64': img_str} def start_feed(tag): """ Start a new feed with the given tag by generating one initial item. Args: tag (str): The tag to generate content for. Returns: tuple: (current_tag, feed_items, html_content) """ item = generate_item(tag) feed_items = [item] html_content = generate_html(feed_items) return tag, feed_items, html_content def load_more(current_tag, feed_items): """ Append a new item to the existing feed using the current tag. Args: current_tag (str): The tag currently being used for the feed. feed_items (list): The current list of feed items. Returns: tuple: (current_tag, updated_feed_items, updated_html_content) """ new_item = generate_item(current_tag) feed_items.append(new_item) html_content = generate_html(feed_items) return current_tag, feed_items, html_content def generate_html(feed_items): """ Generate an HTML string to display the feed items. Args: feed_items (list): List of dictionaries containing 'text' and 'image_base64'. Returns: str: HTML string representing the feed. """ html_str = '
{item['text']}