File size: 3,150 Bytes
29ffd49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cee8e13
29ffd49
cee8e13
29ffd49
cee8e13
29ffd49
 
 
 
 
 
 
 
cee8e13
29ffd49
cee8e13
 
29ffd49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a49089b
29ffd49
 
 
cee8e13
29ffd49
cee8e13
 
 
 
 
29ffd49
cee8e13
29ffd49
 
 
cee8e13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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_button.click(
        fn=user,  # Call user function first
        inputs=[text_input, chatbot_output],
        outputs=[chatbot_output],
        queue=False  # Prevent user input from being queued
    ).then(
        fn=bot,
        inputs=[image_input, 0.4, 1024, "END", 32, 1, chatbot_output],
        outputs=[chatbot_output]
    )

demo.launch()