krishnamishra8848's picture
Update app.py
f5b1799 verified
import gradio as gr
from transformers import pipeline
import requests
import os # Import for accessing environment variables
# Load the sentiment analysis model
classifier = pipeline('sentiment-analysis', model='krishnamishra8848/movie_sentiment_analysis')
# Get API key from secrets
RAPIDAPI_KEY = os.environ.get("RAPIDAPI_KEY") # Securely access the secret
# Language detection function
def detect_language(text):
detect_url = "https://google-translator9.p.rapidapi.com/v2/detect"
detect_payload = {"q": text}
headers = {
"x-rapidapi-key": RAPIDAPI_KEY, # Use the secret here
"x-rapidapi-host": "google-translator9.p.rapidapi.com",
"Content-Type": "application/json"
}
response = requests.post(detect_url, json=detect_payload, headers=headers)
if response.status_code == 200:
detections = response.json().get('data', {}).get('detections', [[]])[0]
if detections:
return detections[0].get('language')
return None
# Translation function
def translate_text(text, source_language, target_language="en"):
translate_url = "https://google-translator9.p.rapidapi.com/v2"
translate_payload = {
"q": text,
"source": source_language,
"target": target_language,
"format": "text"
}
headers = {
"x-rapidapi-key": RAPIDAPI_KEY, # Use the secret here
"x-rapidapi-host": "google-translator9.p.rapidapi.com",
"Content-Type": "application/json"
}
response = requests.post(translate_url, json=translate_payload, headers=headers)
if response.status_code == 200:
translations = response.json().get('data', {}).get('translations', [{}])
if translations:
return translations[0].get('translatedText')
return None
# Main function for Gradio
def analyze_sentiment_with_steps(text):
# Step 1: Detecting Language
yield "Detecting Language..."
detected_language = detect_language(text)
if not detected_language:
yield "Error: Could not detect the language."
return
yield f"Language Detected: {detected_language.upper()}"
# Step 2: Translating if necessary
if detected_language != "en":
yield "Translating text to English..."
text = translate_text(text, detected_language)
if not text:
yield "Error: Could not translate the input text."
return
# Step 3: Sending to model
yield "Sending to Model..."
# Step 4: Sentiment analysis
result = classifier(text)
label_mapping = {"LABEL_0": "negative", "LABEL_1": "positive"}
sentiment = label_mapping[result[0]['label']]
confidence = result[0]['score'] * 100 # Convert to percentage
color = "green" if sentiment == "positive" else "red"
yield f"<h1 style='color:{color}'>Prediction: {sentiment.capitalize()}</h1><p>Confidence: {confidence:.2f}%</p>"
# Gradio interface
interface = gr.Interface(
fn=analyze_sentiment_with_steps,
inputs=gr.Textbox(
label="Enter Movie Review",
placeholder="Type your review in any language...",
lines=3
),
outputs="html",
live=True,
title="Multilingual Movie Sentiment Analysis"
)
# Launch Gradio app
interface.launch(share=True)