Spaces:
Build error
Build error
| import gradio as gr | |
| from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification | |
| # Load sentiment model | |
| def load_model(): | |
| model_name = "cardiffnlp/twitter-roberta-base-sentiment" | |
| tokenizer = AutoTokenizer.from_pretrained(model_name) | |
| model = AutoModelForSequenceClassification.from_pretrained(model_name) | |
| sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer) | |
| return sentiment_pipeline | |
| sentiment_pipeline = load_model() | |
| label_map = {"LABEL_0": "negative", "LABEL_1": "neutral", "LABEL_2": "positive"} | |
| # Simple explanation generator | |
| def explain_sentiment(text, sentiment): | |
| text_lower = text.lower() | |
| if sentiment == "positive": | |
| if any(word in text_lower for word in ["love", "great", "happy", "excellent", "good", "amazing"]): | |
| return "Detected positive language such as 'great', 'happy', or 'love'." | |
| else: | |
| return "Overall positive tone based on context." | |
| elif sentiment == "negative": | |
| if any(word in text_lower for word in ["hate", "bad", "terrible", "awful", "worst", "sad"]): | |
| return "Detected negative words like 'hate', 'bad', or 'worst'." | |
| else: | |
| return "Overall negative tone based on context." | |
| else: | |
| return "Text appears to be neutral with no strong emotional cues." | |
| # Gradio function | |
| def analyze_sentiment(text): | |
| if not text.strip(): | |
| return "Please enter some text.", "" | |
| result = sentiment_pipeline(text)[0] | |
| sentiment = label_map[result["label"]] | |
| confidence = result["score"] | |
| explanation = explain_sentiment(text, sentiment) | |
| sentiment_result = f"**Sentiment**: {sentiment.capitalize()} \n**Confidence**: {confidence:.2f}" | |
| return sentiment_result, explanation | |
| # Gradio interface | |
| iface = gr.Interface( | |
| fn=analyze_sentiment, | |
| inputs=gr.Textbox(lines=4, placeholder="Type something here..."), | |
| outputs=[ | |
| gr.Markdown(label="Sentiment Result"), | |
| gr.Textbox(label="Explanation") | |
| ], | |
| title="Fast Sentiment Analyzer", | |
| description="Enter some text. This app will classify the sentiment (Positive, Negative, or Neutral) and offer a basic explanation.", | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() |