from transformers import pipeline import gradio as gr import os # 1. 建立情緒分析管線 sent_cls = pipeline( task="sentiment-analysis", model="uer/roberta-base-finetuned-jd-binary-chinese" # 雙分類 ) # 2. 推論函式 def classify(text: str): if not text.strip(): return {"error": "請輸入文字"} res = sent_cls(text)[0] return {"label": res["label"], "score": round(res["score"], 4)} # 3. Gradio 介面 demo = gr.Interface( fn=classify, inputs=gr.Textbox(lines=4, placeholder="輸入評論…"), outputs="json", title="中文情緒分析 Demo", description="RoBERTa 中文二分類情緒分析(positive/negative)" ) if __name__ == "__main__": # localhost:7860 預覽 demo.launch(share=True)