Spaces:
Running
Running
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 = "<h1 align='center'>π Gender Bias Detection App π</h1>" | |
SUBTITLE = "<h2 align='center'>Detect and analyze gender-based discrimination in communication.</h2>" | |
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( | |
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]] | |
): | |
if not GOOGLE_API_KEY: | |
raise ValueError("GOOGLE_API_KEY is not set. Please set it up.") | |
text_prompt = chatbot[-1][0] | |
genai.configure(api_key=GOOGLE_API_KEY) # Use the global API 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) | |
# Correctly handle inputs based on image_prompt | |
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_btn.click(fn=respond, inputs=[txt_input, chatbot], outputs=[chatbot, txt_input]) | |
demo.launch() |