Download gradio_app.py from fexeak/my-space: direct link, hf CLI and curl.
- Browser
- Download file 2.58 kB
-
https://huggingface.co/spaces/fexeak/my-space/resolve/main/gradio_app.py
- Command line
-
hf download hf://spaces/fexeak/my-space/gradio_app.py
-
curl -L -o gradio_app.py https://huggingface.co/spaces/fexeak/my-space/resolve/main/gradio_app.py
2.58 kB
| import gradio as gr | |
| from transformers import pipeline | |
| def load_model(): | |
| try: | |
| print("[INFO] 开始加载模型...") | |
| # 使用预训练的情感分析模型 | |
| model_name = "distilbert-base-uncased-finetuned-sst-2-english" | |
| print(f"[INFO] 加载预训练模型: {model_name}") | |
| pipe = pipeline( | |
| "sentiment-analysis", | |
| model=model_name, | |
| device=-1 # 使用CPU | |
| ) | |
| print("[INFO] Pipeline创建完成") | |
| return pipe | |
| except Exception as e: | |
| print(f"[ERROR] 模型加载失败: {str(e)}") | |
| raise e | |
| def analyze_sentiment(text): | |
| try: | |
| print(f"[INFO] 收到文本分析请求: {text}") | |
| result = pipe(text) | |
| print(f"[INFO] 模型返回结果: {result}") | |
| sentiment = result[0]['label'] | |
| confidence = result[0]['score'] | |
| response = f"情感类别: {sentiment}\n置信度: {confidence:.4f}" | |
| print(f"[INFO] 返回分析结果: {response}") | |
| return response | |
| except Exception as e: | |
| error_msg = f"错误: {str(e)}" | |
| print(f"[ERROR] 分析过程出错: {error_msg}") | |
| return error_msg | |
| print("[INFO] 正在加载模型,请稍候...") | |
| pipe = load_model() | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 电影评论情感分析") | |
| with gr.Row(): | |
| text_input = gr.Textbox( | |
| label="请输入电影评论", | |
| placeholder="例如: I absolutely love this movie!", | |
| lines=3 | |
| ) | |
| with gr.Row(): | |
| analyze_btn = gr.Button("分析情感") | |
| with gr.Row(): | |
| output = gr.Textbox(label="分析结果") | |
| analyze_btn.click( | |
| fn=analyze_sentiment, | |
| inputs=text_input, | |
| outputs=output | |
| ) | |
| gr.Examples( | |
| examples=[ | |
| "I absolutely love this movie!", | |
| "This film is terrible and a waste of time.", | |
| "The acting was good but the story was predictable." | |
| ], | |
| inputs=text_input | |
| ) | |
| if __name__ == "__main__": | |
| try: | |
| print("[INFO] 启动Gradio界面...") | |
| demo.launch( | |
| server_name="0.0.0.0", # 允许外部访问 | |
| server_port=7860, # 指定端口 | |
| share=True, # 创建公共URL | |
| show_error=True, # 显示详细错误信息 | |
| show_api=False, # 不显示API文档 | |
| favicon_path=None # 禁用favicon请求 | |
| ) | |
| except Exception as e: | |
| print(f"[ERROR] Gradio启动失败: {str(e)}") | |
| raise e |