pipeline 万物皆可 one-liner

知识库
知识库文档
/tech-stacks/huggingface-transformers/examples/pipeline 万物皆可 one-liner.md

文档

HuggingFace pipeline:一行代码搞定 6 大任务

目标

展示 pipeline() 的「瑞士军刀」能力:一个 API 覆盖情感分析、命名实体识别、文本生成、翻译、文生图、语音识别。

完整代码

from transformers import pipeline
from PIL import Image

# ─── 1. 情感分析 ───
sentiment = pipeline("sentiment-analysis")
print(sentiment("This product is amazing!"))
# [{'label': 'POSITIVE', 'score': 0.999...}]

# ─── 2. 命名实体识别 ───
ner = pipeline("ner", grouped_entities=True)
print(ner("Elon Musk founded SpaceX in Hawthorne, California."))
# [{'entity_group': 'PER', 'word': 'Elon Musk', 'score': 0.99}, ...]

# ─── 3. 文本生成 ───
generator = pipeline("text-generation", model="gpt2")
print(generator("The future of AI is", max_length=30, num_return_sequences=1)[0]["generated_text"])

# ─── 4. 翻译(英语 → 中文) ───
translator = pipeline("translation_en_to_zh", model="Helsinki-NLP/opus-mt-en-zh")
print(translator("Hello, how are you today?"))
# [{'translation_text': '你好,你今天好吗?'}]

# ─── 5. 文本摘要 ───
summarizer = pipeline("summarization")
text = """The Apollo program, also known as Project Apollo, was the third United States 
human spaceflight program carried out by NASA, which succeeded in landing the first 
humans on the Moon from 1969 to 1972."""
print(summarizer(text, max_length=30, min_length=10))

# ─── 6. 零样本分类 ───
classifier = pipeline("zero-shot-classification")
print(classifier(
    "I need to renew my passport and apply for a visa",
    candidate_labels=["travel", "cooking", "education", "finance"],
))

运行步骤

pip install transformers torch sentencepiece sacremoses pillow
python pipeline_demo.py

预期输出

6 个任务的推理结果均正确输出。首次运行会自动从 HF Hub 下载模型到 ~/.cache/huggingface/

信息

路径
/tech-stacks/huggingface-transformers/examples/pipeline 万物皆可 one-liner.md
更新时间
2026/5/31