hashirlodhi's picture
Update app.py
289ffa3 verified
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()