Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from textblob import TextBlob | |
| # 此段函数接受文本输入并返回一个字典,包含三项信息:极性(polarity)、主观性(subjectivity)、评价(assessment) | |
| def sentiment_analysis(text: str) -> dict: | |
| #以下字符串非常重要,该字符串协助Gradio生成MCP工具模式 | |
| """ | |
| Perform sentiment analysis on input text using TextBlob library. | |
| The function calculates polarity (sentiment score from -1 to 1) and subjectivity | |
| (how opinionated the text is from 0 to 1), then provides a human-readable assessment. | |
| Args: | |
| text (str): Input text to be analyzed for sentiment. Should be in English for best results. | |
| Returns: | |
| dict: Dictionary containing three keys: | |
| - polarity (float): Sentiment score between -1.0 (negative) and 1.0 (positive) | |
| - subjectivity (float): Score between 0.0 (objective) and 1.0 (subjective) | |
| - assessment (str): Categorical classification ('positive', 'negative', or 'neutral') | |
| """ | |
| # 使用TextBlob分析文本情感 | |
| blob = TextBlob(text) | |
| sentiment = blob.sentiment | |
| # Format and return sentiment analysis results | |
| return { | |
| "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" | |
| } | |
| # gr.Interface 同时创建网页用户界面和 MCP 服务器 | |
| demo = gr.Interface( | |
| fn=sentiment_analysis, # 调用前面定义的sentiment_analysis方法 | |
| inputs=gr.Textbox(placeholder="Enter text to analyze..."), # 输入和输出组件定义工具的模式 | |
| outputs=gr.JSON(), # JSON 输出组件确保正确的序列化 | |
| title="Text Sentiment Analysis", # Interface title | |
| description="Analyze the sentiment of text using TextBlob" # Description below title | |
| ) | |
| # Launch the web interface when script is run directly | |
| if __name__ == "__main__": | |
| # 置 mcp_server=True 启用 MCP 服务器 | |
| demo.launch(mcp_server=True) |