import gradio as gr from transformers import pipeline # Initialize the sentiment analysis pipeline globally # This will download and cache the model on the first run. # The default model is 'distilbert-base-uncased-finetuned-sst-2-english' try: sentiment_analyzer = pipeline("sentiment-analysis") except Exception as e: print(f"Error initializing sentiment analysis pipeline: {e}") sentiment_analyzer = None def sentiment_analysis(text: str) -> dict: """ Analyze the sentiment of the given text using a Hugging Face transformers model. Args: text (str): The text to analyze. Returns: dict: A dictionary containing the sentiment assessment. """ if not sentiment_analyzer: return { "assessment": "error", "polarity": 0.0, "details": "Sentiment analyzer not available." } # Handle empty or whitespace-only input if not text or not text.strip(): return { "assessment": "neutral", # Or specific "empty_input" "polarity": 0.0, "model_score": 0.0, "details": "Input text is empty." } try: # The pipeline returns a list of dictionaries, e.g., [{'label': 'POSITIVE', 'score': 0.99}] # We take the first result as we are analyzing the whole text as one segment. result = sentiment_analyzer(text)[0] label = result['label'] score = result['score'] assessment = "neutral" # Default assessment polarity = 0.0 if label == "POSITIVE": assessment = "positive" polarity = score # Score is confidence, directly maps to positive polarity elif label == "NEGATIVE": assessment = "negative" # To align with a -1 to 1 range like TextBlob, make polarity negative for negative sentiment polarity = -score # Note: Subjectivity is not directly provided by this specific transformer model. # We return polarity, assessment, and the raw model score for more detail. return { "polarity": round(polarity, 2), "assessment": assessment, "model_score": round(score, 4) } except Exception as e: print(f"Error during sentiment analysis for text '{text[:50]}...': {e}") return { "assessment": "error", "polarity": 0.0, "details": f"Error processing text: {str(e)}" } # Create the Gradio interface demo = gr.Interface( fn=sentiment_analysis, inputs=gr.Textbox(placeholder="Enter text to analyze..."), outputs=gr.JSON(), title="Advanced Text Sentiment Analysis (Transformers)", description="Analyze the sentiment of text using a Hugging Face Transformers model. Provides polarity, assessment, and model score." ) # Launch the interface and MCP server if __name__ == "__main__": demo.launch(mcp_server=True)