import os import time from typing import List, Tuple, Optional import google.generativeai as genai import gradio as gr from PIL import Image print("google-generativeai:", genai.__version__) GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY") # UI Titles and Subtitles TITLE = "

🚀 Gender Bias Detection App 🚀

" SUBTITLE = "

Detect and analyze gender-based discrimination in communication.

" IMAGE_WIDTH = 512 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)) def user(text_prompt: str, chatbot: List[Tuple[str, str]]): return "", chatbot + [[text_prompt, None]] def bot( google_key: str, image_prompt: Optional[Image.Image], temperature: float, max_output_tokens: int, stop_sequences: str, top_k: int, top_p: float, 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.") text_prompt = chatbot[-1][0] genai.configure(api_key=google_key) generation_config = genai.types.GenerationConfig( temperature=temperature, max_output_tokens=max_output_tokens, stop_sequences=preprocess_stop_sequences(stop_sequences), top_k=top_k, top_p=top_p, instructions="Analyze this text for gender-based discrimination, including implicit biases and stereotypes. Provide specific examples and explain why each example demonstrates bias. Also, suggest tips for how to address or mitigate these biases within the text." ) model_name = "gemini-1.5-pro-latest" model = genai.GenerativeModel(model_name) inputs = [text_prompt] if image_prompt is None else [text_prompt, preprocess_image(image_prompt)] response = model.generate_content(inputs, stream=True, generation_config=generation_config) response.resolve() chatbot[-1][1] = "" for chunk in response: for i in range(0, len(chunk.text), 10): chatbot[-1][1] += chunk.text[i:i + 10] time.sleep(0.01) yield chatbot # Gradio Interface with gr.Blocks() as demo: gr.Markdown(TITLE) gr.Markdown(SUBTITLE) with gr.Row(): text_input = gr.Textbox(placeholder="Enter text to analyze for gender-based discrimination") image_input = gr.Image(type="pil", label="Upload Image") submit_button = gr.Button("Analyze") chatbot_output = gr.Chatbot(label="Analysis Output") submit_button.click( fn=bot, inputs=[GOOGLE_API_KEY, image_input, 0.4, 1024, "END", 32, 1, chatbot_output], outputs=[chatbot_output] ) demo.launch()