Spaces:
Sleeping
Sleeping
File size: 2,494 Bytes
033b96e 96606a5 033b96e 96606a5 c0b77e8 96606a5 033b96e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
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) |