Featured image of post HF使用体验

HF使用体验

pipeline使用 + openrouter体验
 
HF简介
DeepSeek: Hugging Face 堪称 AI 界的「模型超市」——就像 GitHub 托管代码一样,它汇聚了全球开发者训练的机器学习模型(从聊天机器人到图像生成器),并提供开箱即用的工具链。只需几行代码,你就能调用 ChatGPT 同款技术栈,或像逛应用商店一样下载现成模型,把「造火箭」变成「拼乐高」。

Transformers安装

DeepSeek总结

Transformers 和 Hugging Face 的关系

一句话总结
Transformers 是 Hugging Face 生态的核心库,相当于 GitHub 的 Git——它是 HF 技术栈的底层引擎,而 Hugging Face 平台(如 Model Hub)则像 GitHub 网站一样提供模型托管、社区协作等完整生态。

关键关联点

  1. 库(Transformers)⇨ 平台(HF)

    • Transformers :提供代码工具(如 pipeline())来加载和运行模型
    • Hugging Face 平台:提供模型托管(Model Hub)、数据集(Datasets)、推理API(Inference API)等配套服务
  2. 模型共享生态

    • 通过 transformers 库的 from_pretrained() 方法,可直接加载 Hugging Face Hub 上的 30万+开源模型(如 model="meta-llama/Llama-2-7b"
  3. 协同工作流

    1
    2
    3
    
    # 用transformers库调用HF平台上的模型
    from transformers import AutoModel
    model = AutoModel.from_pretrained("bert-base-uncased")  # 自动从HF Hub下载
    

类比
就像 Git(工具) + GitHub(平台)的组合,Transformers 是技术基础,Hugging Face 是扩展生态的「模型社区」。

安装的前置条件

  1. Python版本需要大于等于3.8(之前用3.6的安装失败了,报了这个错)

    创建新的虚拟环境时,报HTTP错误,404

    1
    2
    3
    4
    5
    
    An HTTP error occurred when trying to retrieve this URL.
    HTTP errors are often intermittent, and a simple retry will get you on your way.
    
    CondaError: CondaHTTPError: HTTP 404 NOT FOUND for url <https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/win-64/xxxxxx>
    Elapsed: 00:00.635947
    

    解决方案

    参考文章: https://blog.csdn.net/qq_44833403/article/details/144535945

    • 在C盘\用户<用户名>文件夹下 找到.condarc文件(注意是文件,不是文件夹,因为本人电脑文件排序原因,文件夹整体排前面,看字母序去找一直没找到🤣),整体替换为
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    channels:
     - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
     - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/
     - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
     - http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
    default_channels:
     - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
     - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
     - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
    custom_channels:
       conda-forge: http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
       msys2: http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
       bioconda: http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
       menpo: http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
       pytorch: http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
       pytorch-lts: http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
       simpleitk: http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
     show_channel_urls: true
     offline: false
     ssl_verify: false
    
    • python版本需要和setuptools版本匹配,python 3.9版本可以搭配63.4.1版本的setuptools,执行下面命令即可
    1
    
    conda create -n env python=3.9 setuptools==63.4.1
    
  2. 电脑需要有rust的环境,rustc的版本需要有一定要求,之前版本1.71.0失败了,目前好像是最低要1.74以上,通过以下代码更新

    1
    2
    3
    4
    
    rustup --version # 查看是否安装了rustup,没有需要安装
    rustup self update # 更新rustup
    rustup update stable # 更新rust版本
    rustc --version # 查看更新后的rustc版本
    

安装transformers

通过下面命令即可安装

1
pip install transformers

Transformers使用

环境变量设置

Hugging Face的默认的cache地址为C:\ 用户 \ 用户名 \ .cache \ huggingface,假如需要放置到其他位置,可添加一个环境变量

  • 变量名: HF_HOME
  • 变量值: D:\.cache\huggingface(这里我是放到D盘下,之后模型会自动缓存在这里)

使用pipeline

下面通过img2txt的模型演示一下使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from transformers import pipeline

def img2text(image_path):
    # 加载图像描述模型
    img_to_txt = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")

    # 使用模型生成图片描述
    captions = img_to_txt(image_path)

    # 输出结果
    print(captions)

    return captions[0]['generated_text']

使用openrouter

openrouter简介
OpenRouter 的核心功能是提供 单一 API 接口,让开发者无需分别对接不同厂商的 AI 模型(如 GPT-4、Claude、Llama 等),即可通过一次集成调用多种模型。

这里主要是练习一下使用openrouter,通过调用其api完成一些有趣的任务。目前可以免费调用DeepSeek: DeepSeek V3 0324 (free)。下面将演示调用免费的deepseek模型基于一段图片描述生成一首中文诗歌。

依赖包

首先需要安装下面的依赖包

1
pip install langchain langchain-community langchain-openai

调用模型

获取api key

点击后面链接在openrouter中创建一个key, https://openrouter.ai/deepseek/deepseek-chat-v3-0324:free/api

通过key调用模型

 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
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate


def generate_poem(scenario):
    system_prompt  = """
    你是一个作诗非常好的诗人,接下来你要根据一段英文描述的场景生成一首中文现代诗。
    1.希望你能用优美的语言描绘出这个场景
    2.诗的内容要有意境
    3.字数在100个字以内。"""

    prompt_template = ChatPromptTemplate.from_messages([
        ("system", system_prompt),  # 系统级提示
        ("human", "{scenario}")   # 用户输入
    ])

    # 初始化模型
    chat_llm = ChatOpenAI(
        openai_api_base="https://openrouter.ai/api/v1", # 统一都是调这个api url
        openai_api_key="你创建的key",
        model="deepseek/deepseek-chat-v3-0324:free", # 指定模型名称
        temperature=0.7
    )

    print("正在生成诗歌...")
    # 3. 创建 LLMChain,并运行
    chain = prompt_template | chat_llm # 通过管道输入到llm模型中
    result = chain.invoke({"scenario": scenario}) 

    print(result.content)
    return result

效果展示

用 HuggingFace 模型提取图片描述,再调用 LLM 生成诗歌,就能让图片‘开口吟诗’啦!🤪!

1
2
txt = img2text(image_path="img2poem\image.jpg") # 使用img2poem文件夹下的图片生成诗歌
generate_poem(txt)

待描述的图片

运行结果展示

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Device set to use cpu
[{'generated_text': 'a cartoon character running in the grass'}]
正在生成诗歌...
《草上飞》


绿浪里跃动的光点,
是风追不上的弧线。
大地在脚下柔软,
天空在头顶旋转。

橡皮鞋底沾满春天,
笑声把阳光压弯。
地平线张开双臂,
接住这失控的欢颜。
Licensed under CC BY-NC-SA 4.0
最后更新于 Apr 06, 2025 21:16 CST
总访问量  |  总访客数  
Built with Hugo   主题 StackJimmy 设计