import json import gradio as gr from textblob import TextBlob from snownlp import SnowNLP def sentiment_analysis(text: str) -> str: ''' Analyse the sentiment of the given text Args: text (str): The text to analyse Returns: str: A JSON string containing polarity, subjectivity, and assessment ''' blob = TextBlob(text) sentiment = blob.sentiment result = { 'polarity': round(sentiment.polarity, 2), # -1 (negative) to 1 (positive) 'subjectivity': round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective) 'assessment': 'positive' if sentiment.polarity > 0 else 'negative' if sentiment.polarity < 0 else 'neutral' } return json.dumps(result) def chinese_sentiment_analysis(text: str) -> str: ''' Analyse the sentiment of the given Chinese text Args: text (str): The text to analyse Returns: str: A JSON string containing polarity, subjectivity, and assessment ''' s = SnowNLP(text) # SnowNLP 的情感分析返回值範圍是 0 到 1,0 表示負面,1 表示正面 polarity = s.sentiments subjectivity = None # SnowNLP 不提供主觀性評估,可設為 None 或其他值 result = { 'polarity': round(polarity, 2), # 0 (negative) to 1 (positive) 'subjectivity': subjectivity, # SnowNLP 不提供主觀性評估 'assessment': 'positive' if polarity > 0.5 else 'negative' if polarity < 0.5 else 'neutral' } return json.dumps(result) # gradio interface demo = gr.TabbedInterface( [ gr.Interface( fn = sentiment_analysis, inputs = gr.Textbox(placeholder = 'Enter text to analyse...'), outputs = gr.Textbox(), title = 'Text Sentiment Analysis', description = 'Analyse the sentiment of text using TextBlob', api_name = 'sentiment_analysis' ), gr.Interface( fn = chinese_sentiment_analysis, inputs = gr.Textbox(placeholder = '要分析的中文...'), outputs = gr.Textbox(), title = 'Chinese Sentiment Analysis', description = 'Analyse the sentiment of Chinese text using SnowNLP', api_name = 'chinese_sentiment_analysis'), ], [ 'sentiment analysis', 'chinese sentiment analysis', ] ) # Launch the interface and MCP server if __name__ == '__main__': demo.launch(mcp_server = True)