andreggalvaoCW commited on
Commit
914749b
·
unverified ·
0 Parent(s):

initial commit

Browse files
Files changed (2) hide show
  1. app.py +83 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+
4
+ # Initialize the sentiment analysis pipeline globally
5
+ # This will download and cache the model on the first run.
6
+ # The default model is 'distilbert-base-uncased-finetuned-sst-2-english'
7
+ try:
8
+ sentiment_analyzer = pipeline("sentiment-analysis")
9
+ except Exception as e:
10
+ print(f"Error initializing sentiment analysis pipeline: {e}")
11
+ sentiment_analyzer = None
12
+
13
+ def sentiment_analysis(text: str) -> dict:
14
+ """
15
+ Analyze the sentiment of the given text using a Hugging Face transformers model.
16
+
17
+ Args:
18
+ text (str): The text to analyze.
19
+
20
+ Returns:
21
+ dict: A dictionary containing the sentiment assessment.
22
+ """
23
+ if not sentiment_analyzer:
24
+ return {
25
+ "assessment": "error",
26
+ "polarity": 0.0,
27
+ "details": "Sentiment analyzer not available."
28
+ }
29
+
30
+ # Handle empty or whitespace-only input
31
+ if not text or not text.strip():
32
+ return {
33
+ "assessment": "neutral", # Or specific "empty_input"
34
+ "polarity": 0.0,
35
+ "model_score": 0.0,
36
+ "details": "Input text is empty."
37
+ }
38
+
39
+ try:
40
+ # The pipeline returns a list of dictionaries, e.g., [{'label': 'POSITIVE', 'score': 0.99}]
41
+ # We take the first result as we are analyzing the whole text as one segment.
42
+ result = sentiment_analyzer(text)[0]
43
+ label = result['label']
44
+ score = result['score']
45
+
46
+ assessment = "neutral" # Default assessment
47
+ polarity = 0.0
48
+
49
+ if label == "POSITIVE":
50
+ assessment = "positive"
51
+ polarity = score # Score is confidence, directly maps to positive polarity
52
+ elif label == "NEGATIVE":
53
+ assessment = "negative"
54
+ # To align with a -1 to 1 range like TextBlob, make polarity negative for negative sentiment
55
+ polarity = -score
56
+
57
+ # Note: Subjectivity is not directly provided by this specific transformer model.
58
+ # We return polarity, assessment, and the raw model score for more detail.
59
+ return {
60
+ "polarity": round(polarity, 2),
61
+ "assessment": assessment,
62
+ "model_score": round(score, 4)
63
+ }
64
+ except Exception as e:
65
+ print(f"Error during sentiment analysis for text '{text[:50]}...': {e}")
66
+ return {
67
+ "assessment": "error",
68
+ "polarity": 0.0,
69
+ "details": f"Error processing text: {str(e)}"
70
+ }
71
+
72
+ # Create the Gradio interface
73
+ demo = gr.Interface(
74
+ fn=sentiment_analysis,
75
+ inputs=gr.Textbox(placeholder="Enter text to analyze..."),
76
+ outputs=gr.JSON(),
77
+ title="Advanced Text Sentiment Analysis (Transformers)",
78
+ description="Analyze the sentiment of text using a Hugging Face Transformers model. Provides polarity, assessment, and model score."
79
+ )
80
+
81
+ # Launch the interface and MCP server
82
+ if __name__ == "__main__":
83
+ demo.launch(mcp_server=True)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio
2
+ transformers
3
+ torch
4
+ textblob