|
import gradio as gr |
|
from transformers import pipeline |
|
import requests |
|
import os |
|
|
|
|
|
classifier = pipeline('sentiment-analysis', model='krishnamishra8848/movie_sentiment_analysis') |
|
|
|
|
|
RAPIDAPI_KEY = os.environ.get("RAPIDAPI_KEY") |
|
|
|
|
|
def detect_language(text): |
|
detect_url = "https://google-translator9.p.rapidapi.com/v2/detect" |
|
detect_payload = {"q": text} |
|
headers = { |
|
"x-rapidapi-key": RAPIDAPI_KEY, |
|
"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 |
|
|
|
|
|
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, |
|
"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 |
|
|
|
|
|
def analyze_sentiment_with_steps(text): |
|
|
|
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()}" |
|
|
|
|
|
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 |
|
|
|
|
|
yield "Sending to Model..." |
|
|
|
|
|
result = classifier(text) |
|
label_mapping = {"LABEL_0": "negative", "LABEL_1": "positive"} |
|
sentiment = label_mapping[result[0]['label']] |
|
confidence = result[0]['score'] * 100 |
|
color = "green" if sentiment == "positive" else "red" |
|
yield f"<h1 style='color:{color}'>Prediction: {sentiment.capitalize()}</h1><p>Confidence: {confidence:.2f}%</p>" |
|
|
|
|
|
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" |
|
) |
|
|
|
|
|
interface.launch(share=True) |
|
|