File size: 1,546 Bytes
289ffa3
1f14729
289ffa3
1f14729
289ffa3
 
 
 
1f14729
289ffa3
1f14729
289ffa3
 
1f14729
289ffa3
1f14729
289ffa3
1f14729
289ffa3
 
1f14729
289ffa3
 
 
 
 
 
 
 
 
 
 
1f14729
 
 
289ffa3
 
1f14729
289ffa3
 
1f14729
 
 
 
 
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
import os
import gradio as gr
import google.generativeai as genai

# Configure the Gemini API with environment variable
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
if not GOOGLE_API_KEY:
    raise ValueError("GOOGLE_API_KEY environment variable not set. Please configure it in the Hugging Face Space settings.")

genai.configure(api_key=GOOGLE_API_KEY)

# Use Gemini 1.5 Flash model
model = genai.GenerativeModel('gemini-1.5-flash-latest')

def sentiment_analysis(text):
    if not text.strip():
        return "Error: Please enter a non-empty text for analysis."
    
    prompt = f"""
    Analyze the sentiment of the following text and respond in this format:
    
    Sentiment: [Positive / Negative / Neutral]
    Reason: [Brief explanation of why you classified it this way]

    Text: \"{text}\"
    """

    try:
        response = model.generate_content(prompt)
        return response.text.strip()
    except Exception as e:
        return f"Error: {str(e)}\nTip: Ensure your API key is valid at https://aistudio.google.com/"

# Define Gradio interface
iface = gr.Interface(
    fn=sentiment_analysis,
    inputs=gr.Textbox(lines=5, placeholder="Enter text for sentiment analysis...", label="Text Input"),
    outputs=gr.Textbox(label="Sentiment Analysis Result"),
    title="Gemini Sentiment Analyzer",
    description="Enter text to analyze its sentiment using Google's Gemini 1.5 Flash model. Provide a valid GOOGLE_API_KEY in the Hugging Face Space settings."
)

# Launch the interface
if __name__ == "__main__":
    iface.launch()