import os import time from typing import List, Tuple, Optional import google.generativeai as genai import gradio as gr from PIL import Image # Environment variable for Google API Key GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY") # Constants for image processing IMAGE_WIDTH = 512 # Helper functions def preprocess_stop_sequences(stop_sequences: str) -> Optional[List[str]]: return [seq.strip() for seq in stop_sequences.split(",")] if stop_sequences else None def preprocess_image(image: Image.Image) -> Image.Image: image_height = int(image.height * IMAGE_WIDTH / image.width) return image.resize((IMAGE_WIDTH, image_height)) # Function to trigger model invocation def bot( google_key: str, image_prompt: Optional[Image.Image], chatbot: List[Tuple[str, str]] ): google_key = google_key or GOOGLE_API_KEY if not google_key: raise ValueError("GOOGLE_API_KEY is not set. Please set it up.") # Fixed text prompt for analyzing gender-based discrimination text_prompt = "Analyze this for any instances of gender-based discrimination. Consider both explicit and implicit biases, stereotypes, and unequal treatment. Provide specific examples from the text to support your analysis." genai.configure(api_key=google_key) generation_config = genai.types.GenerationConfig( temperature=0.4, max_output_tokens=1024, stop_sequences=preprocess_stop_sequences("STOP, END"), top_k=32, top_p=1.0, ) model_name = "gemini-1.5-pro-latest" model = genai.GenerativeModel(model_name) inputs = [text_prompt, preprocess_image(image_prompt)] if image_prompt else [text_prompt] response = model.generate_content(inputs, stream=True, generation_config=generation_config) response.resolve() chatbot[-1][1] = "" for chunk in response: chatbot[-1][1] += chunk.text time.sleep(0.01) return chatbot # Gradio Interface Components google_key_component = gr.Textbox(label="GOOGLE API KEY", type="password", placeholder="...", visible=GOOGLE_API_KEY is None) image_prompt_component = gr.Image(type="pil") chatbot_component = gr.Chatbot(label='Gemini', bubble_full_width=False) run_button_component = gr.Button("Check Discrimination") # Layout and Interaction with gr.Blocks() as demo: with gr.Column(): google_key_component.render() image_prompt_component.render() run_button_component.render() chatbot_component.render() # Connect button to the bot function run_button_component.click( fn=bot, inputs=[google_key_component, image_prompt_component, chatbot_component], outputs=[chatbot_component] ) # Launch the app demo.launch()