mcp-sentiment / app.py
real-jiakai's picture
Create app.py
4658e66 verified
# 导入Gradio库,这是一个用于快速创建机器学习模型演示界面的Python库
import gradio as gr
# 导入TextBlob库,这是一个用于处理文本数据的自然语言处理库,可以进行情感分析、词性标注等
from textblob import TextBlob
# 定义情感分析函数,接收文本字符串作为输入,返回包含情感分析结果的字典
def sentiment_analysis(text: str) -> dict:
"""
Analyze the sentiment of the given text.
Args:
text (str): The text to analyze
Returns:
dict: A dictionary containing polarity, subjectivity, and assessment
"""
# 使用输入的文本创建TextBlob对象,该对象可以进行各种自然语言处理操作
blob = TextBlob(text)
# 调用sentiment属性获取情感分析结果,返回一个包含polarity和subjectivity的namedtuple
sentiment = blob.sentiment
# 返回一个包含情感分析结果的字典
return {
# polarity表示情感极性,范围从-1(最负面)到1(最正面),保留2位小数
"polarity": round(sentiment.polarity, 2), # -1 (negative) to 1 (positive)
# subjectivity表示主观性程度,范围从0(完全客观)到1(完全主观),保留2位小数
"subjectivity": round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective)
# assessment是基于polarity值的文本情感评估:大于0为积极,小于0为消极,等于0为中性
"assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"
}
# 使用Gradio的Interface类创建交互式界面
# Create the Gradio interface
demo = gr.Interface(
# fn参数指定要调用的函数,这里是sentiment_analysis函数
fn=sentiment_analysis,
# inputs参数定义输入组件,这里使用文本框,并设置占位符提示文字
inputs=gr.Textbox(placeholder="Enter text to analyze..."),
# outputs参数定义输出组件,这里使用JSON格式显示结果
outputs=gr.JSON(),
# title参数设置界面的标题
title="Text Sentiment Analysis",
# description参数设置界面的描述信息
description="Analyze the sentiment of text using TextBlob"
)
# 判断是否作为主程序运行(而不是被导入)
# Launch the interface and MCP server
if __name__ == "__main__":
# 启动Gradio界面,mcp_server=True参数表示启用MCP(Model Context Protocol)服务器
# MCP服务器允许该应用作为一个服务被其他应用调用
demo.launch(mcp_server=True)