Spaces:
Paused
Paused
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 导入Gradio库,这是一个用于快速创建机器学习模型演示界面的Python库
|
| 2 |
+
import gradio as gr
|
| 3 |
+
# 导入TextBlob库,这是一个用于处理文本数据的自然语言处理库,可以进行情感分析、词性标注等
|
| 4 |
+
from textblob import TextBlob
|
| 5 |
+
|
| 6 |
+
# 定义情感分析函数,接收文本字符串作为输入,返回包含情感分析结果的字典
|
| 7 |
+
def sentiment_analysis(text: str) -> dict:
|
| 8 |
+
"""
|
| 9 |
+
Analyze the sentiment of the given text.
|
| 10 |
+
Args:
|
| 11 |
+
text (str): The text to analyze
|
| 12 |
+
Returns:
|
| 13 |
+
dict: A dictionary containing polarity, subjectivity, and assessment
|
| 14 |
+
"""
|
| 15 |
+
# 使用输入的文本创建TextBlob对象,该对象可以进行各种自然语言处理操作
|
| 16 |
+
blob = TextBlob(text)
|
| 17 |
+
# 调用sentiment属性获取情感分析结果,返回一个包含polarity和subjectivity的namedtuple
|
| 18 |
+
sentiment = blob.sentiment
|
| 19 |
+
|
| 20 |
+
# 返回一个包含情感分析结果的字典
|
| 21 |
+
return {
|
| 22 |
+
# polarity表示情感极性,范围从-1(最负面)到1(最正面),保留2位小数
|
| 23 |
+
"polarity": round(sentiment.polarity, 2), # -1 (negative) to 1 (positive)
|
| 24 |
+
# subjectivity表示主观性程度,范围从0(完全客观)到1(完全主观),保留2位小数
|
| 25 |
+
"subjectivity": round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective)
|
| 26 |
+
# assessment是基于polarity值的文本情感评估:大于0为积极,小于0为消极,等于0为中性
|
| 27 |
+
"assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
# 使用Gradio的Interface类创建交互式界面
|
| 31 |
+
# Create the Gradio interface
|
| 32 |
+
demo = gr.Interface(
|
| 33 |
+
# fn参数指定要调用的函数,这里是sentiment_analysis函数
|
| 34 |
+
fn=sentiment_analysis,
|
| 35 |
+
# inputs参数定义输入组件,这里使用文本框,并设置占位符提示文字
|
| 36 |
+
inputs=gr.Textbox(placeholder="Enter text to analyze..."),
|
| 37 |
+
# outputs参数定义输出组件,这里使用JSON格式显示结果
|
| 38 |
+
outputs=gr.JSON(),
|
| 39 |
+
# title参数设置界面的标题
|
| 40 |
+
title="Text Sentiment Analysis",
|
| 41 |
+
# description参数设置界面的描述信息
|
| 42 |
+
description="Analyze the sentiment of text using TextBlob"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# 判断是否作为主程序运行(而不是被导入)
|
| 46 |
+
# Launch the interface and MCP server
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
# 启动Gradio界面,mcp_server=True参数表示启用MCP(Model Context Protocol)服务器
|
| 49 |
+
# MCP服务器允许该应用作为一个服务被其他应用调用
|
| 50 |
+
demo.launch(mcp_server=True)
|